diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 3d0ef5bba..1e6a5c867 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1408289866, "producer_workflow_id": 429719786, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", @@ -83,7 +83,9 @@ } }, "max_artifact_bytes": 2147483648, - "automatic_signer_actors": [], + "automatic_signer_actors": [ + "github-actions[bot]" + ], "platforms": { "windows-x86_64": { "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", @@ -95,7 +97,15 @@ "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", diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 000000000..41808334a --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,72 @@ +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.') diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 385aa647a..51f684d12 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main 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. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 2b068623d..dbf33d355 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,8 +1,10 @@ name: CADCraft unsigned nightly -# 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). +# 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. on: + schedule: + - cron: '30 0 * * *' workflow_dispatch: permissions: @@ -22,9 +24,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: main app-name: cadcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 @@ -32,3 +34,4 @@ 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"]' diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3..0a61da4ba 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -10,7 +10,7 @@ permissions: contents: read concurrency: - group: sonarcloud-${{ github.ref }} + group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', 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' }} diff --git a/AGENTS.md b/AGENTS.md index 08329d13d..8ce5bf0b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,6 +72,8 @@ Layout: Checks for the crates you changed: `cargo test -p `, `cargo clippy -p --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). diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index aa67f69f6..68fa7f260 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -25,6 +25,7 @@ Generated-in-code assets are original and have no file to list: | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| +| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. | | `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. | | `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. | | `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. | @@ -85,7 +86,7 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added | | `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | 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/tr.tsv` | @ogzhnklvz (AI-assisted); 870 later rows: @HolyZephyros (AI-assisted) | Original Turkish translations of CADCraft English strings (original catalog by @ogzhnklvz; 870 later rows written from CADCraft's English strings in #3291) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app for the original catalog was reviewed by a native speaker; the 870 rows added in #3291 have not yet been reviewed by a native speaker | | `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending | | `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full | | `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) | diff --git a/Cargo.lock b/Cargo.lock index c02817737..66f0e94f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -378,9 +378,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", @@ -736,6 +736,7 @@ dependencies = [ "cadcraft-ui-egui", "chrono", "clap", + "craft-nightly", "craft-quit", "craft-update", "eframe", @@ -1593,6 +1594,15 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8945bdb09b36245a1d442438ce8876377ef430d0#8945bdb09b36245a1d442438ce8876377ef430d0" +dependencies = [ + "uds_windows", + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -2726,9 +2736,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -6611,9 +6621,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/Cargo.toml b/Cargo.toml index 7294622de..cbf388b4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9 craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" } cadcraft-color = { path = "crates/color" } cadcraft-doc = { path = "crates/doc" } cadcraft-constraints = { path = "crates/constraints" } diff --git a/README.md b/README.md index 82af0d3d7..8f5413303 100644 --- a/README.md +++ b/README.md @@ -94,9 +94,9 @@ untested, 2018 tested only on synthetic files) open through the open-source acadrust library and save as 2000 through 2018. New drawings default to 2018 (AC1032) in both formats. In the app's Save dialog, File ▸ Default Save Format - (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version 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 + (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version Save As and + Export write, for opened drawings too; Save (QSAVE) of an opened file keeps its own version, + subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. Export to SVG and PNG today. - **Fast and native.** Pure Rust and egui, no Electron, no web view. One binary on macOS (universal), Windows, Linux and FreeBSD, plus a WebAssembly build for the browser. @@ -120,7 +120,7 @@ numbers): | Layers & properties | Layers palette and Layer Properties Manager (on/off, freeze, lock, plot, colour, linetype), layer tools (isolate, freeze, off, lock, match, previous), Properties palette with per-object editing, linetypes, lineweights, colour index and true colour | | Annotation | All DIM* commands with full DIMSTYLE variables, overrides and every arrowhead, associative dimensions that follow geometry, MLEADER, TABLE, TrueType fonts (`.ttf`, `.otf`, `.ttc` collections), MTEXT formatting codes (fonts, heights, colours, stacked fractions), our own single-stroke drafting font | | Hatch & blocks | Pick-point hatch boundaries with islands, pattern, solid and gradient fills from our own pattern library, BLOCK/INSERT, attributes and nested blocks | -| Files | DXF read (R12–2018, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version 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, binary from R13) and write (2000–2018, ASCII and binary), including dimension styles, associativity, tables and constraints; DWG read (via the acadrust library; R13 and R14 untested, 2018 tested only on synthetic files) and write (2000–2018). New drawings save as 2018 (AC1032); opened drawings keep their supported version, except DWG defaults to at least 2004. In the app's Save dialog, File ▸ Default Save Format (also Options ▸ Open and Save, `saveVersion`, default 2018) sets the version Save As and Export write, for opened drawings too; Save (QSAVE) of an opened file keeps its own version, subject to supported-version mapping and the DWG minimum. SAVEAS `version` overrides this choice and is remembered for later saves. DXF uses R2000 structure with the chosen `$ACADVER`. PDF plotting, SVG and PNG export. Entities CADCraft doesn't model yet are not kept on save: see [file-format parity](docs/file-format-parity.md) for version selection and fidelity | | 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 | diff --git a/ROADMAP.md b/ROADMAP.md index 980c63153..1b3059897 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet) -> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-25 · **Change:** minor (Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-12-01 · **Change:** minor (Upcoming updated for what merged from 2026-11-25 to 2026-12-01; previously minor: Upcoming updated for what merged from 2026-11-21 to 2026-11-25; previously minor: Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027 CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a @@ -84,8 +84,8 @@ Hours are Opus 5.5 agent wall-clock hours, calibrated on this repo's own build: ## Languages -AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus eighteen catalogs -(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian and Vietnamese). Detail: [localization-parity.md](docs/localization-parity.md). +AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus twenty catalogs +(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian, Vietnamese, Polish and Tamil; Tamil needs an installed Tamil font or a build with the craft-fonts face, and without one the interface stays in English). Detail: [localization-parity.md](docs/localization-parity.md). | Language | Status | UI translated | |---|---|---:| @@ -103,7 +103,7 @@ AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus ei | Korean | partial | 1,235 catalog rows | | Vietnamese | partial | 1,460 catalog rows (2026-11-07); native review pending | -Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)). +Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Since those counts Polish (#218) and Tamil (#3105) landed and the Russian (#3378), Czech (#1579) and Vietnamese (#3500) catalogs were brought up to date; the counts here are not redone. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)). ## Upcoming @@ -112,16 +112,18 @@ already written and waiting in a pull request lands before new work starts, whoe and the beta checklist are in [docs/roadmap.md](docs/roadmap.md). **1. Urgent: security fixes, leaks, crashes and lost work.** -- The open findings of the security audit (#1919–#1935): check each against the input limits that +- The open findings of the security audit (#1922, #1925, #1931, #1932 and #1935 of #1919–#1935; the others are closed): check each against the input limits that landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities overwrite existing ones (#1921) is fixed by #1276. - A saved file that crashes AutoCAD 2021 (#3303); dimension text lost on save (#3299) was fixed on 2026-11-20. -- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content - (#2174), startup on older graphics hardware (#1724, #1631, #3222). +- Crashes and hangs with a reproduction: the web build on a large DXF (#1603; bounded by #3594 and + #3622, still open), a DWG with 3D content (#2174), startup on older graphics hardware (#1724, #1631, + #3222). **2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).** -- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual - switch since #3336). +- It starts on common hardware: the automatic fallback renderer landed (#3685; `CADCRAFT_STENCIL=0` + is the manual switch since #3336); waiting for the reporters to confirm, and older Intel Macs (#1631, + #2146) are not covered. - It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and paper units (#1672, #2836), and a corpus of real files run in CI. - Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632). @@ -131,16 +133,18 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md). - The prompt options that still say "not available yet" (gaps F1). - Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since #3308. -- 602 pull requests are open (2026-11-25; 661 on 2026-11-20). About 230 were mergeable, passed CI and were small; they are +- 586 pull requests are open (2026-12-01; 602 on 2026-11-25). About 230 were mergeable, passed CI and were small; they are reviewed and landed in this order, the longest-waiting authors first within a row. **3. Lower priority: affects fewer people and nothing breaks without it.** -- Dynamic-block authoring, editing an xref in place, exact ellipse and spline geometry, correct - polyline offsets. +- Dynamic-block authoring, the leftovers of editing an xref in place (landed in #3352), exact ellipse + and spline geometry, correct polyline offsets. - Prompt options that need 3D (DVIEW's camera options, -RENAME Material); 3D itself comes after 1.0, but a file with 3D content must open safely (tier 1). - Menu breadth against AutoCAD for Mac as a headline number. +Done from 2026-11-25 to 2026-12-01: REFEDIT, REFSET and REFCLOSE on xrefs, writing the xref's drawing back in the version it was read in (#2355 in #3352; not on the web); an automatic fallback renderer when the graphics can't start (#3685 in #3692; not yet confirmed by the reporters, and older Intel Macs are not covered); TRIM highlights only the part a click removes and EXTEND what it adds, and EXTRIM (#3382, #2808 in #3471; follow-ups #3526 in #3690); SCALE Reference Points and Copy, and grip Scale of text heights (#3288 in #3472); QLEADER at the command line (#2740; its Settings dialog is not available yet); OFFSETGAPTYPE (#1506); FILLET and CHAMFER with two polylines and with middle, closed and arc segments (#1223); prompts and results of COPY, JOIN, PEDIT, RECTANG, STRETCH, PLINE, SPLINE, SPLINEDIT, ARRAY, ARRAYPATH, DIVIDE, INSERT and MINSERT brought closer to AutoCAD's (#2726, #2725, #2906, #2790, #2204, #2209, #2205, #2699, #2703, #2705, #2772, #2778, #2761, #2762, #2774, #2782, #2780, #2784, #2766, #2789); spreadsheet text pasted as a TABLE (#3290 in #3470), with wrapped cell text and Enter to repeat (#3584, #3587 in #3690); GROUPDISPLAYMODE, group copies and draw order across every layout (#2152); New Layout from Area (#2080); drawing locks and WHOHAS, which say when a drawing is open elsewhere (#1018, part of #540); REVCLOUD arcs that other readers recognise as a cloud (#1692); hatches by internal point that keep their arcs (#1474); `\X` dimension text below the line (#1084); JIS and Japanese paper sizes (#1810); a translucent fill in the AREA preview (#1303); selection through a viewport that leaves out block parts on its frozen layers (#3214 in #3692); saves that keep covered cell text, WIPEOUTFRAME, LAYOUT flags, VPORT group 72, attributes on layer 0 and DIMLFAC measurements (#3520, #3611, #3668, #3670, #3613 in #3689; #3540 in #3692), and RENAME that keeps foreign data (#1020); the web build's display list, selection highlight and plot style outlines bounded (#3594, #3622 in #3692; #1603 stays open); hostile-input fixes toward the security audit (#3482, #3491, #3536 for #1923; #3610, #3647 for #1922; #3588 for #1925; #3609 for #1935; #3484, #3539, #3562, #3590 for quadratic-time opens); LISP and script fixes (#3519, #3572, #3576, #3642, #3646, #3651); the move to the shared UI framework, with floating palettes as OS windows and Ctrl+= and Ctrl+- for the interface scale (#3449); the Tamil catalog (#3105 in #3470) and the Russian, Czech and Vietnamese catalogs brought up to date (#3378, #1579, #3500). + Done from 2026-11-21 to 2026-11-25: PDFIMPORT, a PDF page as editable lines, polylines, solid hatches and text (#3375 in #3419); dynamic block references that rotate, flip, array, scale, stretch polar, align and look up, with their grips (#963, #993, #1030, #1098, #1699, #1723, #1752 in #3424; authoring is still open); the proxy graphics of other applications' objects drawn (#2697, #3435, #3437) and dimensions kept as read drawn from their `*D` block (#3439); saves that keep layout plot settings (#3233, #3386, #3390), DXF 2007+ table cell text (#3392), hatch boundary flags (#3389), fit text (#3391) and registered applications (#2918); the Array window for ARRAYRECT and ARRAYPOLAR (#3394); ATTDIA and the Edit Attributes dialog on INSERT (#3411) and constant attribute values drawn (#3462); Edit > Paste from the system clipboard (#3366, #3460, #3461; #3320 open); opening from Finder and quit prompts on macOS (#1347 in #3344, not yet run on a Mac); an already-open drawing selects its tab when opened from the interface (#899 in #3422; the control channel, MCP, scripts and LISP still open a second copy); Tab through every object snap candidate (#1673); the Write Block dialog for WBLOCK (#1778); Generate Boundary (#2804); mitred wide polylines (#3453; the extents leave out the mitre tip, #3443); DIMASSOC 1 (#2977); crossing selection of block references by what they draw (#3445); an option to turn off the update check (#3097). Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345). @@ -172,6 +176,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D | Date | Change | Summary | |---|---|---| +| 2026-12-01 | minor | Upcoming updated for the merges of 2026-11-25 to 2026-12-01 (REFEDIT on xrefs, the automatic fallback renderer, TRIM/EXTEND highlight and EXTRIM, SCALE Reference, QLEADER, OFFSETGAPTYPE, FILLET/CHAMFER with polylines, spreadsheet paste as a TABLE, groups and draw order, New Layout from Area, drawing locks and WHOHAS, what saves keep, web display-list bounds, security-audit fixes, the shared UI framework); languages list now twenty catalogs (Polish, Tamil); pull-request count 602 → 586; percentages and hours not re-scored | | 2026-11-25 | minor | Upcoming updated for the merges of 2026-11-21 to 2026-11-25 (PDF import, dynamic block reference actions, proxy graphics, what saves keep, Array window, ATTDIA, system clipboard paste, macOS opening from Finder, WBLOCK dialog, Generate Boundary); #3299 fixed; pull-request count 661 → 602; percentages and hours not re-scored | | 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored | | 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored | diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index 5b5b9ef0e..cfc1dc8e9 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -66,7 +66,7 @@ fn convert_long_about() -> &'static str { /// cadcraft-cli: headless CADCraft #[derive(Parser)] -#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), arg_required_else_help = true)] +#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), propagate_version = true, arg_required_else_help = true)] pub(crate) struct Cli { #[command(subcommand)] pub(crate) command: Command, diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index fbb4462f6..5993b1e4a 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -61,6 +61,8 @@ fn install_io() { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups, }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); // What a DXF before 2007 leaves out for its proxies' string streams (#3229). diff --git a/apps/cadcraft-cli/src/perf.rs b/apps/cadcraft-cli/src/perf.rs index e52b6107b..97edf3813 100644 --- a/apps/cadcraft-cli/src/perf.rs +++ b/apps/cadcraft-cli/src/perf.rs @@ -66,6 +66,8 @@ fn synthetic(n: usize, side: f64) -> Result Dir { + let p = std::env::temp_dir().join(format!("cc-cli-attribs-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).expect("create scratch dir"); + Dir(p) + } + + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// One `cadcraft-cli run`: a fresh profile, an optional drawing to open, and the steps to run. +struct Run { + args: Vec, +} + +impl Run { + fn new(dir: &Dir, file: Option<&Path>) -> Run { + let mut args: Vec = vec!["run".into(), "--config-dir".into(), dir.path("profile").to_string_lossy().into_owned()]; + match file { + Some(f) => args.push(f.to_string_lossy().into_owned()), + None => args.push("--metric".into()), + } + Run { args } + } + + fn cmd(&mut self, id: &str, params: Value) -> &mut Run { + self.args.push("--cmd".into()); + self.args.push(format!("{id} {params}")); + self + } + + fn lisp(&mut self, code: &str) -> &mut Run { + self.cmd("lisp", json!({ "code": code })) + } + + fn save(&mut self, path: &Path) -> &mut Run { + self.args.push("--save".into()); + self.args.push(path.to_string_lossy().into_owned()); + self + } + + fn output(&self) -> Output { + Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&self.args).output().expect("run cadcraft-cli") + } + + /// Run it: the value each `lisp` step returned, in order (commands' own results are left out). + fn out(&self) -> Vec { + let out = self.output(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{}: {}", self.args.join(" "), err); + let text = String::from_utf8_lossy(&out.stdout); + text.lines() + .map(|l| serde_json::from_str::(l).unwrap_or_else(|e| panic!("not a result: {l}: {e}"))) + .filter(|v| v.get("value").is_some()) + .collect() + } +} + +/// The value a `lisp` step returned, as AutoLISP's `prin1` shows it. +fn value(results: &[Value], i: usize) -> String { + match results.get(i).and_then(|r| r.get("value")) { + Some(Value::String(s)) => s.clone(), + other => panic!("step {i}: no value: {other:?} in {results:?}"), + } +} + +/// `value` without the quotes `prin1` puts round a string. +fn text(results: &[Value], i: usize) -> String { + value(results, i).trim_matches('"').to_string() +} + +/// TAGBLK.dxf: block TAGBLK with a circle and four attribute definitions (TAG1 D1, TAG2 D2 +/// verify, TAG3 P3 preset, TAG4 C4 constant). Opening the file again gives the drawing fresh +/// names. +const FIXTURE: &str = r#"(progn + (entmake '((0 . "BLOCK") (2 . "TAGBLK") (70 . 2) (10 0.0 0.0 0.0))) + (entmake '((0 . "CIRCLE") (10 -5.0 0.0 0.0) (40 . 2.0))) + (entmake '((0 . "ATTDEF") (10 0.0 0.0 0.0) (40 . 2.5) (1 . "D1") (3 . "P1") (2 . "TAG1") (70 . 0))) + (entmake '((0 . "ATTDEF") (10 0.0 5.0 0.0) (40 . 2.5) (1 . "D2") (3 . "P2") (2 . "TAG2") (70 . 4))) + (entmake '((0 . "ATTDEF") (10 0.0 10.0 0.0) (40 . 2.5) (1 . "P3") (3 . "P3") (2 . "TAG3") (70 . 8))) + (entmake '((0 . "ATTDEF") (10 0.0 15.0 0.0) (40 . 2.5) (1 . "C4") (3 . "P4") (2 . "TAG4") (70 . 2))) + (entmake '((0 . "ENDBLK"))))"#; + +/// The first reference: INSERT TAGBLK at (10,10) with TAG1 "A1", TAG2 verified as "B1" and +/// TAG3 preset ("P3"); TAG4 is constant, so it is not asked. +const INSERT: &str = r#"(command "_.-INSERT" "TAGBLK" '(10 10) 1 1 0 "A1" "B1" "")"#; + +fn fixture(dir: &Dir) -> PathBuf { + let file = dir.path("TAGBLK.dxf"); + let mut run = Run::new(dir, None); + let out = run.lisp(FIXTURE).save(&file).out(); + assert_eq!(text(&out, 0), "TAGBLK"); + file +} + +/// The walk from the entity named `i`: its records' tags and values, then the type of the record +/// that ends the run. +const WALK: &str = r#"(progn + (setq e (entnext i) n 0 ts nil ed nil) + (while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e)))))) + (setq ts (append ts (list (cdr (assoc 2 ed)) (cdr (assoc 1 ed)))) n (1+ n) e (entnext e))) + (list n ts (cdr (assoc 0 ed))))"#; + +#[test] +fn the_walk_reaches_each_attrib_and_ends_at_the_seqend() { + let dir = Dir::new("walk"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!( + r#"(progn + {INSERT} + (setq i (entlast)) + (setvar "ATTREQ" 0) + (command "_.-INSERT" "TAGBLK" '(60 10) 1 1 0) + (setvar "ATTREQ" 1) + (setq second (entlast)) + "inserted")"# + )) + // Three attributes, then the SEQEND owned by the reference, then the next main entity. + .lisp(&format!( + r#"(progn {WALK} + (list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (equal (entnext e) second) (cdr (assoc 0 (entget (entnext e))))))"# + )) + // The second reference (no attribute answers, ATTREQ 0) took the definitions' values; its + // own run ends at its SEQEND, with nothing drawn after it. + .lisp(&format!( + r#"(progn (setq i second) {WALK} + (list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (entnext e)))"# + )) + .out(); + assert_eq!(text(&out, 0), "inserted"); + assert_eq!(value(&out, 1), "(3 (\"TAG1\" \"A1\" \"TAG2\" \"B1\" \"TAG3\" \"P3\") \"SEQEND\" T T \"INSERT\")"); + // Its record ends with its own SEQEND, and nothing is drawn after the reference. + assert_eq!(value(&out, 2), "(3 (\"TAG1\" \"D1\" \"TAG2\" \"D2\" \"TAG3\" \"P3\") \"SEQEND\" T nil)"); +} + +#[test] +fn a_value_edit_changes_group_one_only_and_is_one_undo_step() { + let dir = Dir::new("value"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 2 (entget a))) (cdr (assoc 1 (entget a)))))"#)) + .lisp( + r#"(progn + (setq d (entget a) r (entmod (subst (cons 1 "A2") (assoc 1 d) d))) + (list (cdr (assoc 0 r)) (cdr (assoc 1 r)) (cdr (assoc 1 (entget a))) (cdr (assoc 2 (entget a))) + (cdr (assoc 40 (entget a))) (cdr (assoc 8 (entget a))) (equal (cdr (assoc -2 (entget a))) i)))"#, + ) + .cmd("undo", json!({ "count": 1 })) + // The edit is one Undo step: the value is back, and the name given before it holds no + // longer (the drawing it was given in was restored from another state). + .lisp( + r#"(list (entget a) (progn (setq e (entnext (entlast))) + (list (cdr (assoc 2 (entget e))) (cdr (assoc 1 (entget e))))))"#, + ) + .out(); + assert_eq!(value(&out, 0), "(\"TAG1\" \"A1\")"); + assert_eq!(value(&out, 1), "(\"ATTRIB\" \"A2\" \"A2\" \"TAG1\" 2.5 \"0\" T)"); + assert_eq!(value(&out, 2), "(nil (\"TAG1\" \"A1\"))"); + // Redo brings the edit back; the name given before the Undo still names nothing. + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i) d (entget a)) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#)) + .cmd("undo", json!({ "count": 1 })) + .cmd("redo", json!({ "count": 1 })) + .lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(value(&out, 1), "(nil \"A2\")"); +} + +#[test] +fn a_name_stops_holding_after_erase_attsync_and_undo() { + let dir = Dir::new("stale"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run.lisp(&format!(r#"(progn {INSERT} (setq i (entlast)) (cdr (assoc 5 (entget i))))"#)).out(); + let handle = text(&out, 0); + + // Erased: the reference's records are gone with it, and the name names nothing. + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (cdr (assoc 2 (entget a))))"#)) + .cmd("erase", json!({ "handles": [handle] })) + .lisp("(list (entget a) (entnext a))") + // Undone: the reference is back, but a name given before the Undo does not come back with + // it: a walk gives its records new ones. + .cmd("undo", json!({ "count": 1 })) + .lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))") + // ATTSYNC rebuilds the reference's attributes: the name given before names nothing, and + // the rebuilt attribute keeps the value. + .lisp("(progn (setq b (entnext (entlast))) (cdr (assoc 2 (entget b))))") + .cmd("attsync", json!({ "name": "TAGBLK" })) + .lisp("(list (entget b) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(value(&out, 0), "\"TAG1\""); + assert_eq!(value(&out, 1), "(nil nil)"); + assert_eq!(value(&out, 2), "(nil \"A1\")"); + assert_eq!(value(&out, 3), "\"TAG1\""); + assert_eq!(value(&out, 4), "(nil \"A1\")"); + + // A reinsert after an Undo takes the parent handle back: the old name must not name its + // attribute. + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 5 (entget i))) (cdr (assoc 2 (entget a)))))"#)) + .cmd("undo", json!({ "count": 1 })) + .lisp(&format!(r#"(progn {INSERT} (list (cdr (assoc 5 (entget (entlast)))) (entget a)))"#)) + .lisp("(list (cdr (assoc 2 (entget (entnext (entlast))))) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(text(&out, 0), format!("(\"{handle}\" \"TAG1\")")); + // The same handle, and the old name names nothing in the new reference. + assert_eq!(value(&out, 1), format!("(\"{handle}\" nil)")); + assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\")"); +} + +#[test] +fn an_edit_of_anything_but_the_value_is_refused() { + let dir = Dir::new("refused"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!( + r#"(progn {INSERT} (setq i (entlast) a (entnext i) s (entnext (entnext (entnext a))) p0 (cdr (assoc 10 (entget a)))) "named")"# + )) + .lisp( + r#"(progn + (setq d (entget a)) + (list + (entmod (subst (cons 2 "TAGX") (assoc 2 d) d)) + (entmod (subst (cons 40 9.0) (assoc 40 d) d)) + (entmod (subst (cons 0 "SEQEND") (assoc 0 d) d)) + (entmod (entget s)) + (entmod (subst (cons 410 "Layout2") (assoc 410 d) d)) + (entmod (subst (cons 1 "A2") (assoc 1 d) (subst (cons 410 "Layout2") (assoc 410 d) d))) + (entdel a) (entdel s)))"#, + ) + // Nothing changed: the same tag, value, height and place, and the name still holds. + .lisp( + r#"(progn (setq e (entnext (entlast)) d (entget e)) + (list (cdr (assoc 2 d)) (cdr (assoc 1 d)) (cdr (assoc 40 d)) (equal p0 (cdr (assoc 10 d))) (equal (entget a) d)))"#, + ) + .out(); + assert_eq!(text(&out, 0), "named"); + assert_eq!(value(&out, 1), "(nil nil nil nil nil nil nil nil)"); + assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\" 2.5 T T)"); +} + +/// A minimal drawing: `before` (records written as they are), then an INSERT with `attribs` +/// ATTRIBs (each tag T, value V) and its SEQEND, last in the file. A header `$HANDSEED` is +/// written when `handseed` is given (a hostile file can name any next handle). +fn insert_dxf_seed(attribs: usize, before: &str, handseed: Option<&str>) -> String { + let mut s = String::with_capacity(before.len().saturating_add(attribs.saturating_mul(96))); + if let Some(seed) = handseed { + s.push_str("0\nSECTION\n2\nHEADER\n9\n$HANDSEED\n5\n"); + s.push_str(seed); + s.push('\n'); + s.push_str("0\nENDSEC\n"); + } + s.push_str("0\nSECTION\n2\nENTITIES\n"); + s.push_str(before); + s.push_str("0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nTAGBLK\n10\n0\n20\n0\n30\n0\n"); + for _ in 0..attribs { + s.push_str("0\nATTRIB\n5\n21\n8\n0\n10\n0\n20\n0\n30\n0\n40\n1\n1\nV\n2\nT\n70\n0\n"); + } + s.push_str("0\nSEQEND\n5\n22\n0\nENDSEC\n0\nEOF\n"); + s +} + +fn insert_dxf(attribs: usize, before: &str) -> String { + insert_dxf_seed(attribs, before, None) +} + +/// The number of records a walk from `i` reaches, counting each `entnext`. +const COUNT: &str = r#"(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"#; + +#[test] +fn a_walk_is_stable_and_its_names_are_no_handles() { + let dir = Dir::new("stable"); + // A file's line one below the top of the handle range: it keeps its handle, and the + // records' names, which are no handles, never name it. + let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n"; + let file = dir.path("hostile.dxf"); + std::fs::write(&file, insert_dxf(2, before)).expect("write the DXF"); + + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp( + r#"(progn + (setq i (handent "20") line (handent "FFFFFFFFFFFFFFFE") a (entnext i) b (entnext i)) + (list (cdr (assoc 5 (entget line))) (equal (handent "FFFFFFFFFFFFFFFE") line) + (not (equal a line)) (cdr (assoc 0 (entget a))) (equal a b) (equal (entnext a) (entnext b))))"#, + ) + .lisp(&format!(r#"(progn (setq i (handent "20")) {COUNT})"#)) + .out(); + assert_eq!(value(&out, 0), "(\"FFFFFFFFFFFFFFFE\" T T \"ATTRIB\" T T)"); + // Two ATTRIBs and the SEQEND, then the line (it sorts last by its handle), then the end. + assert_eq!(value(&out, 1), "4"); +} + +#[test] +fn a_restored_reference_does_not_revive_an_old_name() { + let dir = Dir::new("restored"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!( + r#"(progn {INSERT} (setq i (entlast) a (entnext i)) + (entdel i) + (setq gone (entget a)) + (entdel i) + (list gone (entget a) (cdr (assoc 1 (entget (entnext i))))))"# + )) + .out(); + assert_eq!(value(&out, 0), "(nil nil \"A1\")", "the reference comes back, the old name does not"); + + // ERASE, then OOPS: the same. The old name never comes back with the reference. + let mut run = Run::new(&dir, Some(&file)); + let handle = text(&run.lisp(&format!(r#"(progn {INSERT} (cdr (assoc 5 (entget (entlast)))))"#)).out(), 0); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq a (entnext (entlast))) "named")"#)) + .cmd("erase", json!({ "handles": [handle] })) + .cmd("oops", json!({})) + .lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(value(&out, 1), "(nil \"A1\")", "OOPS restores the reference, not the old name"); +} + +#[test] +fn a_new_line_is_never_a_record() { + let dir = Dir::new("handseed"); + let file = dir.path("hostile.dxf"); + // A file's $HANDSEED in the reserved band is the file's own handle and is not followed (#913), + // so the line made after the walk gets the drawing's seed. The record's name is no handle: + // the line is the line, and the name still names the attribute. The engine's + // `a_new_object_at_any_handle_is_never_a_record` puts the seed at the top of the range. + std::fs::write(&file, insert_dxf_seed(1, "", Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF"); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(r#"(progn (setq i (handent "20") a (entnext i)) (list (cdr (assoc 0 (entget a))) (cdr (assoc 5 (entget (entlast))))))"#) + .lisp(r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#) + .lisp(r#"(list (cdr (assoc 0 (entget a))) (entdel a))"#) + .out(); + assert_eq!(value(&out, 0), "(\"ATTRIB\" \"20\")"); + assert_eq!(value(&out, 1), "\"100\""); + assert_eq!(value(&out, 2), "(\"ATTRIB\" nil)"); +} + +#[test] +fn lines_at_the_top_of_the_handle_range_walk_as_lines() { + let dir = Dir::new("walkrange"); + let file = dir.path("hostile.dxf"); + let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n\ + 0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0\n20\n0\n30\n0\n11\n6\n21\n6\n31\n0\n"; + std::fs::write(&file, insert_dxf_seed(1, before, Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF"); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(r#"(progn (setq i (handent "20")) (entnext i))"#) + // The line at the top of the range is in the drawing. Without it, the walk from the line + // below would end in nil, and nil equals the nil `handent` gives for a handle not there. + .lisp(r#"(progn (setq top (handent "FFFFFFFFFFFFFFFF")) (list (cdr (assoc 0 (entget top))) (cdr (assoc 5 (entget top)))))"#) + .lisp(r#"(equal (entnext (handent "FFFFFFFFFFFFFFFE")) top)"#) + .lisp("(entnext top)") + .out(); + assert_eq!(value(&out, 1), "(\"LINE\" \"FFFFFFFFFFFFFFFF\")"); + assert_eq!(value(&out, 2), "T"); + assert_eq!(value(&out, 3), "nil"); +} + +#[test] +fn the_session_names_at_most_65536_records() { + let dir = Dir::new("names"); + let file = dir.path("many.dxf"); + // One more attribute than the limit of names: the walk stops at the limit, and nothing in the + // drawing changed. + std::fs::write(&file, insert_dxf(65_537, "")).expect("write the DXF"); + let mut run = Run::new(&dir, Some(&file)); + let out = run.lisp(&format!("(progn (setq i (entlast)) {COUNT})")).lisp(&format!("(progn (setq i (entlast)) {COUNT})")).out(); + assert_eq!(value(&out, 0), "65536"); + // The names given by the first walk hold: the second walk is the same. + assert_eq!(value(&out, 1), "65536"); +} diff --git a/apps/cadcraft-cli/tests/it/lisp_script.rs b/apps/cadcraft-cli/tests/it/lisp_script.rs new file mode 100644 index 000000000..8db041962 --- /dev/null +++ b/apps/cadcraft-cli/tests/it/lisp_script.rs @@ -0,0 +1,43 @@ +//! A LISP routine in a `run` script runs to its end before the script goes on and the drawing is +//! saved, however many slices it takes (#3635). + +use std::process::{Command, Output}; + +fn cli(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap() +} + +/// A fresh scratch directory that is removed on drop, also when an assertion fails. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).expect("create scratch dir"); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The loop takes many slices: the circle drawn after it is in the saved drawing, and the next +/// line runs once the routine has ended. +#[test] +fn a_long_routine_in_a_script_draws_before_the_save() { + let scratch = Scratch::new("lisp-script"); + let saved = scratch.0.join("out.dxf"); + let saved = saved.to_str().unwrap(); + let script = r#"(progn (repeat 1000000 (setq x 1)) (command "circle" "0,0" "5") (princ "done"))\n(princ (+ x 1))"#; + let out = cli(&["run", "--metric", "--script", script, "--save", saved]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{:?}: {err}", out.status); + assert!(err.lines().any(|l| l == "done") && err.lines().any(|l| l == "2"), "{err}"); + let info = cli(&["info", saved]); + let v: serde_json::Value = serde_json::from_slice(&info.stdout).unwrap(); + assert_eq!(v["counts"]["Circle"], 1, "{v}"); +} diff --git a/apps/cadcraft-cli/tests/it/main.rs b/apps/cadcraft-cli/tests/it/main.rs index cbf9cbe93..7b74f031a 100644 --- a/apps/cadcraft-cli/tests/it/main.rs +++ b/apps/cadcraft-cli/tests/it/main.rs @@ -1,7 +1,9 @@ +mod block_resources; mod cli; mod dash_limit_note; mod drafting_spacing; mod help; +mod lisp_script; // DWG output needs craft-dwg's bridge. #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] mod ltype_dwg_note; diff --git a/apps/cadcraft-cli/tests/it/usage.rs b/apps/cadcraft-cli/tests/it/usage.rs index 6cb4ab831..0ba9f8c71 100644 --- a/apps/cadcraft-cli/tests/it/usage.rs +++ b/apps/cadcraft-cli/tests/it/usage.rs @@ -188,12 +188,25 @@ fn subcommand_help_requests() { ), case("help after an extra argument", &["info", "{b}", "extra", "-h"], 0, Line("Print a drawing's summary as JSON"), Empty), case("--help after -- is a file name", &["run", "--", "--help"], 1, Empty, Starts("error: invalid parameters for `open`: --help:")), - case("run --version", &["run", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")), - case("info --version", &["info", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")), ], ); } +/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and +/// return without running it (`mcp` would otherwise wait for a client). +#[test] +fn every_subcommand_prints_the_version() { + for sub in ["info", "convert", "run", "commands", "mcp", "perf", "sample", "roundtrip"] { + for flag in ["--version", "-V"] { + let top = invoke(&[flag]); + let release = top.stdout.strip_prefix("cadcraft-cli ").unwrap_or_else(|| panic!("{:?}", top.stdout)); + let got = invoke(&[sub, flag]); + assert_eq!((got.code, got.stderr.as_str()), (0, ""), "{sub} {flag}"); + assert_eq!(got.stdout, format!("cadcraft-cli-{sub} {release}"), "{sub} {flag}"); + } + } +} + #[test] fn unknown_flags_on_every_subcommand() { run_cases( diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index 14e53285d..9da9817ec 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -136,6 +136,8 @@ mod web { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups, }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); // What a DXF before 2007 leaves out for its proxies' string streams (#3229). diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index cd1d15412..6c019e1c7 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -24,11 +24,16 @@ serde_json = { workspace = true } serde = { workspace = true } log = { workspace = true } clap = { workspace = true } +craft-nightly = { workspace = true } thiserror = { workspace = true } chrono = { workspace = true } # Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`). # Already in Cargo.lock through eframe; same version so nothing is built twice. ron = "0.12" +# Waits for wgpu's answers while the graphics start (src/renderer.rs) and, on macOS, for the +# answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already in +# Cargo.lock through eframe. +pollster = "1" [build-dependencies] winresource = "0.1" @@ -55,9 +60,6 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std", # The same winit eframe uses (the storytold fork, patched in the workspace). # `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs). winit = { version = "0.30", default-features = false, features = ["rwh_06"] } -# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already -# in Cargo.lock through eframe. -pollster = "1" # Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a # kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C # handler behind a safe API, without relaxing the workspace's unsafe-code lint. diff --git a/apps/cadcraft/src/build_flavor.rs b/apps/cadcraft/src/build_flavor.rs index b63ede7c5..e56d8826e 100644 --- a/apps/cadcraft/src/build_flavor.rs +++ b/apps/cadcraft/src/build_flavor.rs @@ -1,23 +1,11 @@ //! 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; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; 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 } @@ -35,7 +23,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { - use super::*; + use super::{BuildFlavor, needs_native_error, version, version_query}; + #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { assert!(needs_native_error(BuildFlavor::NightlyV1, true)); @@ -44,20 +33,6 @@ 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"); diff --git a/apps/cadcraft/src/env.rs b/apps/cadcraft/src/env.rs index 6af615a4a..6539dcf02 100644 --- a/apps/cadcraft/src/env.rs +++ b/apps/cadcraft/src/env.rs @@ -23,7 +23,10 @@ pub(crate) const VARS: &[(&str, &str)] = &[ (CONFIG_DIR, "the settings folder (logs, autosave, workspace, plotters); empty means no settings folder"), (LOCALE, "the interface language, instead of the system's"), (VSYNC, "1 presents with vsync, 0 without it (default: without on Linux and BSD)"), - (STENCIL, "0 opens the window without a stencil buffer, for drivers that show a black window; clipped layout viewports then draw unclipped"), + ( + STENCIL, + "0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)", + ), (WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"), (NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"), (SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"), @@ -46,8 +49,10 @@ pub(crate) struct Env { pub(crate) locale: Option, /// Present with vsync (default: off on Linux and BSD, on elsewhere). pub(crate) vsync: Switch, - /// Off: the window has no stencil buffer (default: on). Some old drivers (Mesa on Intel HD - /// 4000, old Intel drivers on Windows) accept a stencil pass and then present a black window. + /// Off: the window has no stencil buffer; on: it keeps one on every attempt at starting the + /// graphics. Default: it starts with one, and a start that can't draw with it drops it (see + /// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a + /// stencil pass and then present a black window. pub(crate) stencil: Switch, /// Keep the native Wayland backend instead of XWayland. #[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))] diff --git a/apps/cadcraft/src/launch_profile.rs b/apps/cadcraft/src/launch_profile.rs index 09f4e40c1..f6cf43758 100644 --- a/apps/cadcraft/src/launch_profile.rs +++ b/apps/cadcraft/src/launch_profile.rs @@ -1,211 +1,101 @@ -//! 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. +//! 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 ` invocations keep their +//! launcher-supplied root. Stable launches retain their original arguments and directory policy. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -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, -} - -static PROFILE: OnceLock = OnceLock::new(); +use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().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) -> Result { - 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) -> Result { - 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, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::portable::probe) +pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + craft_nightly::prepare_launch(flavor, &crate::profile_root::spec(), args, &StartupOptions::new()) } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; + 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}; + fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() } + fn absolute() -> &'static str { if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + + #[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()); } #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { - for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] { - 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 }); - } - } - - #[test] - 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(); + 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.args, args(&["--", "--profile-root", "drawing with spaces.dxf"])); + assert_eq!(launch.passthrough_args, args(&["drawing with spaces.dxf"])); + assert!(!launch.is_version_query()); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + 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 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(); for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT]), args(&["--profile-root", absolute()]), args(&["--launch-profile", "future-v2", "--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()]), + 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()]), ] { - assert!(parse(argv).is_err()); + assert!(parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).is_err()); } } #[test] - 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]; + fn launcher_and_direct_version_queries_are_recognized() { + let s = spec(); for flag in ["--version", "-V"] { - 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 direct = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(direct.is_version_query(), "direct {flag}"); - #[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()); - } + 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}"); + } - #[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()); + let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } } diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index c090937c7..61e94954a 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -33,6 +33,7 @@ mod nightly_session; mod portable; mod process_identity; mod profile_root; +mod renderer; #[cfg(target_os = "macos")] mod sheet; mod single_instance; @@ -198,6 +199,8 @@ pub fn install_io() { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups, }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); // What a DXF before 2007 leaves out for its proxies' string streams (#3229). @@ -239,9 +242,38 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> { } } +/// `Services::start_pick` for Linux and the BSDs: the blocking dialog runs on a thread of its +/// own, so the window keeps answering the desktop while the dialog is open; `ui` is woken when +/// it answers. If the thread cannot start, `done` is dropped unanswered and the app says the +/// dialog could not be shown. +#[cfg(all(unix, not(target_os = "macos")))] +fn start_pick(ui: egui::Context) -> cadcraft_ui_egui::StartPick { + Box::new(move |pick, done| { + let ui = ui.clone(); + // Here, not on the thread: the interface language is this thread's + // (`i18n::with_language`), and the filter labels are translated. + let filters = filters(&pick); + let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || { + let dialog = file_dialog_with(&pick, &filters); + let picked = if matches!(pick, Pick::Save(_)) { dialog.save_file() } else { dialog.pick_file() }; + done(picked.map(|p| p.to_string_lossy().to_string())); + ui.request_repaint(); + }); + if let Err(e) = spawned { + log::warn!("file dialog: {e}"); + } + }) +} + /// The blocking dialog for `pick` (Windows, Linux, FreeBSD). fn file_dialog(pick: &Pick) -> rfd::FileDialog { - let dialog = filters(pick).iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts)); + file_dialog_with(pick, &filters(pick)) +} + +/// [`file_dialog`] offering `filters`, the file types of `pick` ([`filters`]) as the caller's +/// thread names them. +fn file_dialog_with(pick: &Pick, filters: &[(&'static str, Vec<&'static str>)]) -> rfd::FileDialog { + let dialog = filters.iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts)); match pick { Pick::Save(name) => dialog.set_file_name(name), Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir), @@ -306,7 +338,7 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0]; /// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state /// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of -/// its render pass ([`stencil_bits`]). +/// its render pass (each attempt at starting the graphics sets its own, see [`renderer::apply`]). 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())) @@ -335,17 +367,6 @@ fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui: /// The key eframe saves the main window state under in its storage. const WINDOW_KEY: &str = "window"; -/// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`). -const STENCIL_BITS: u8 = 8; - -/// The stencil bits of the window's render pass: none when `CADCRAFT_STENCIL` is off. Some old -/// drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a stencil pass without an -/// error and then present a black window, so only an explicit opt-out drops it. Without a stencil -/// buffer, clipped layout viewports draw unclipped. -fn stencil_bits(stencil: Switch) -> u8 { - if stencil == Switch::Off { 0 } else { STENCIL_BITS } -} - #[cfg(target_os = "macos")] const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png"); #[cfg(not(target_os = "macos"))] @@ -428,35 +449,30 @@ fn report_launch_profile_error(error: &str) { /// should return success without opening a window. fn prepare_launch() -> Option> { let argv: Vec<_> = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --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)) - { + // 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) { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "{}", nightly_version_line()); return None; } - 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)) { + 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 --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)) { report_launch_profile_error(&error); std::process::exit(2); } - Some(early.args) + Some(launch.passthrough_args) } /// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe. @@ -550,12 +566,6 @@ fn main() -> eframe::Result { cadcraft_engine::fonts::ttf::set_fallback_fonts(list); } let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos")))); - // The window's render pass and the canvas's pipelines must agree on it; a mismatch is a wgpu - // validation error. - let stencil = stencil_bits(vars.stencil); - if stencil == 0 { - log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped"); - } // XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend. let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On; let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11); @@ -568,7 +578,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()), renderer::STENCIL_BITS, frame.as_ref()) }; if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); @@ -605,10 +615,13 @@ fn main() -> eframe::Result { let apple_events = &apple_events; // The exit hook's own handle: the app creator is a `move` closure, so the watch is cloned before it. let exit_watch = std::sync::Arc::clone(&nightly_watch); - let result = eframe::run_native( + // Each attempt at starting the graphics sets its backends, adapter and stencil buffer, and a + // failed one is followed by the next (see renderer.rs). + let result = renderer::run_native( os_window::name_for(os_window::identity()), options, - Box::new(move |cc| { + vars.stencil, + Box::new(move |cc, started| { 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 @@ -623,6 +636,13 @@ fn main() -> eframe::Result { if let Some(window) = cc.winit_window().cloned() { app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone())); } + // On Linux and the BSDs the dialog is the desktop portal's, another process: waiting + // for it in the event handler leaves the window unanswered for as long as it is open, + // and the desktop then offers to force-quit the app. + #[cfg(all(unix, not(target_os = "macos")))] + { + app.services.start_pick = Some(start_pick(cc.egui_ctx.clone())); + } let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref()); if let Some(ui) = restored { app.ui = ui; @@ -676,9 +696,8 @@ fn main() -> eframe::Result { if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync { app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240)); } - if let Some(rs) = &cc.wgpu_render_state { - app.set_wgpu(rs, eframe::egui_wgpu::depth_format_from_bits(0, stencil)); - } + // On the GPU with the window's stencil buffer, or on the CPU when the GPU refuses the canvas. + started.install(&mut app, cc.wgpu_render_state.as_ref()); if let Some(port) = control_port { let rx = control_server::start(port, cc.egui_ctx.clone()); app = app.with_control(rx); @@ -736,10 +755,8 @@ fn main() -> eframe::Result { #[cfg(test)] mod tests { - use super::{ - STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options, - without_tiny_window, - }; + use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window}; + use crate::renderer::STENCIL_BITS; #[test] fn save_dialog_offers_dwg_with_the_drawing_format_first() { @@ -774,18 +791,25 @@ mod tests { } /// `CADCRAFT_STENCIL=0` (also `no`, `false`, any case) opens the window without a stencil - /// buffer; unset, blank, `1` or anything else keeps it. + /// buffer, and `1` keeps it on every attempt; unset, blank or anything else starts with one and + /// lets a failed start drop it. #[test] - fn the_stencil_buffer_is_dropped_only_when_asked() { - let bits = |value: Option<&str>| { + fn the_stencil_buffer_follows_cadcraft_stencil() { + let stencils = |value: Option<&str>| { let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(value).flatten().map(Into::into)); - stencil_bits(vars.stencil) + let attempts = crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil); + attempts.iter().map(|a| a.stencil).collect::>().into_iter().collect::>() }; for off in ["0", "no", "NO", "false", "False", " 0 "] { - assert_eq!(bits(Some(off)), 0, "{off:?}"); + assert_eq!(stencils(Some(off)), [false], "{off:?}"); } - for on in [None, Some(""), Some("1"), Some("yes"), Some("8"), Some("maybe")] { - assert_eq!(bits(on), STENCIL_BITS, "{on:?}"); + for on in ["1", "yes", "On"] { + assert_eq!(stencils(Some(on)), [true], "{on:?}"); + } + for unset in [None, Some(""), Some("8"), Some("maybe")] { + assert_eq!(stencils(unset), [false, true], "{unset:?}"); + let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(unset).flatten().map(Into::into)); + assert!(crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil)[0].stencil, "{unset:?}: the first has one"); } } diff --git a/apps/cadcraft/src/profile_root.rs b/apps/cadcraft/src/profile_root.rs index 45a5acb2e..0859764a5 100644 --- a/apps/cadcraft/src/profile_root.rs +++ b/apps/cadcraft/src/profile_root.rs @@ -1,607 +1,218 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! CADCraft's `craft-nightly` isolation specification: stable paths, environment fence, +//! portable-mode markers, folder-only entries, and platform-specific forbidden roots. use std::ffi::OsString; +use std::path::PathBuf; -use crate::portable::{PORTABLE_DATA_DIR, portable_marker}; -use std::path::{Component, Path, PathBuf}; +use craft_nightly::AppProfileSpec; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, +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)) } -impl Platform { - fn current() -> Result { - 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 spec_with_env(env: impl Fn(&str) -> Option) -> 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), } } -fn absolute(path: PathBuf, label: &str) -> Result { - 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, key: &str) -> Result { - 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, key: &str, fallback: &str) -> Result { - 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 { - 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")?; +fn extra_forbidden_roots(env: &impl Fn(&str) -> Option) -> Vec { + 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")); } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), } } - 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); - } - Ok(resolved) -} - -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::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - 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()); + #[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")); } } - 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, exe: &Path) -> Result, 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::, _>>()?; - // 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::, _>>()?; - 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")?; + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs(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(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(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() + roots.push(PathBuf::from("/Applications/CADCraft.app")); + } + roots } -fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { - 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) +fn non_empty_abs(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -/// 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, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} - -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - 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`], `/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}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } + use craft_nightly::{ProfileError, validate_and_prepare_root}; - impl Fixture { - fn new() -> Self { + 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 { static NEXT: AtomicU64 = AtomicU64::new(0); let root = loop { - let candidate = - std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let candidate = std::env::temp_dir().join(format!( + "cadcraft-profile-spec-{}-{}-{label}", + 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 owned fixture: {error}"), + Err(error) => panic!("cannot create temp dir: {error}"), } }; - 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 { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - 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()) + Self(root) } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory successfully created by this fixture is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.0); } } #[test] - 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); - } - } - 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"); - } + fn spec_preserves_cadcraft_isolation_constants_and_extra_forbidden_roots() { + let mut env = BTreeMap::::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")); - #[cfg(unix)] - #[test] - 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(()) - }, + 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"))); + } + #[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!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias"); - assert!(!probed.get()); + assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Applications/CADCraft.app"))); + assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/Applications/CADCraft.app"))); } - 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); + } + + #[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"); } #[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"); + 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(); - 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); + std::fs::create_dir_all(&private).unwrap(); + std::os::unix::fs::symlink(outside.join("target"), private.join("autosave")).unwrap(); + + let err = validate_and_prepare_root(&private, &spec()).unwrap_err(); + assert!(matches!(err, ProfileError::SymlinkEntry(_)), "unexpected error: {err}"); } } diff --git a/apps/cadcraft/src/renderer.rs b/apps/cadcraft/src/renderer.rs new file mode 100644 index 000000000..fa13ed217 --- /dev/null +++ b/apps/cadcraft/src/renderer.rs @@ -0,0 +1,660 @@ +//! Which renderer draws the window, and what the app does when one can't start. +//! +//! The window draws with wgpu (eframe is built with its `wgpu` renderer only). Where a start fails +//! decides what is tried next: +//! +//! - The adapter, the device or the window's surface can't be made (no adapter for the backends, a +//! device the driver refuses or loses): eframe returns `Error::Wgpu` before the app exists. The +//! stencil buffer plays no part, so another adapter is tried. +//! - The window's surface can't be configured, or egui's pipelines are refused: also before the app +//! exists. The stencil buffer is part of both, so the same adapter is tried without it first. +//! - The driver takes the stencil buffer and then draws nothing, with no error: Mesa's OpenGL on Ivy +//! Bridge refuses `glTexStorage2D(GL_STENCIL_INDEX8)`, the frame buffer is incomplete and every +//! frame comes out black (#1724). egui makes the window's stencil buffer a texture it can also +//! sample, which wgpu's OpenGL backend stores with that call. Before the app is created, [`check`] +//! clears a small target, without and then with a stencil buffer made the same way, and reads it +//! back. +//! - The canvas's own pipelines are refused: the canvas draws on the CPU ([`Started::install`]). +//! +//! Not caught: a driver that crashes the process or hangs, a black window whose offscreen check +//! passes (a fault in presenting to the window), a failure after the app was created (an error +//! then ends the start as before), and a panic inside eframe or egui-wgpu. +//! +//! The attempts, in order ([`attempts`]): the start as it always was (DirectX 12 alone on Windows, +//! see `graphics.rs`; eframe's backends elsewhere); OpenGL alone, where those backends have it +//! beside another; then those backends with a software adapter only (WARP, llvmpipe). Each is tried +//! with a stencil buffer, then without. No attempt creates a backend the first one did not, so no +//! driver code runs that the start did not run before: on Windows, where OpenGL is left out because +//! an AMD driver crashes inside it (#31), the fallback is WARP. A start that works today makes only +//! the first attempt, and the check. +//! +//! `WGPU_BACKEND` limits every attempt to its backends, and `CADCRAFT_STENCIL` fixes the stencil +//! buffer. Nothing is remembered between starts: a failed attempt costs a fraction of a second, and +//! a remembered choice would keep a lesser renderer after a failure that happened once. + +use std::sync::Arc; +use std::time::Duration; + +use cadcraft_ui_egui::CadApp; +use cadcraft_ui_egui::switch::Switch; +use eframe::egui_wgpu::{self, NativeAdapterSelectorMethod, WgpuError, WgpuSetup}; +use eframe::wgpu::{self, Backends, DeviceType}; + +/// Stencil bits of the window's render pass when an attempt has a stencil buffer (see +/// `NativeOptions::stencil_buffer`). +pub(crate) const STENCIL_BITS: u8 = 8; + +/// How long [`check`] waits for its read-back. A slower answer counts as a pass: a busy GPU is no +/// reason to fall back. +const CHECK_TIMEOUT: Duration = Duration::from_secs(10); + +/// The width of [`check`]'s target: one row of RGBA8 pixels is then exactly the row alignment a +/// copy to a buffer needs. +const CHECK_WIDTH: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT / 4; + +/// The colour [`check`] clears to, as it reads back: a new texture starts as zeros. +const CHECK_COLOR: [u8; 4] = [255, 0, 255, 255]; + +type DynError = Box; + +/// Builds the app once an attempt's window draws. +pub(crate) type Creator<'a> = Box, &Started) -> Result, DynError> + 'a>; + +/// The backends by name, for the log and the status bar. +const NAMES: [(Backends, &str); 4] = + [(Backends::DX12, "DirectX 12"), (Backends::METAL, "Metal"), (Backends::VULKAN, "Vulkan"), (Backends::GL, "OpenGL")]; + +/// One way to start the window's graphics. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Attempt { + /// The backends wgpu chooses an adapter from. + pub(crate) backends: Backends, + /// Only a software adapter (WARP, llvmpipe); otherwise wgpu's choice, which prefers a GPU. + pub(crate) software: bool, + /// The window has a stencil buffer, which clips the contents of clipped layout viewports. + pub(crate) stencil: bool, +} + +impl Attempt { + /// The same adapter: an attempt that differs only in its stencil buffer. + fn same_adapter(self, other: Attempt) -> bool { + (self.backends, self.software) == (other.backends, other.software) + } +} + +impl std::fmt::Display for Attempt { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let backends: Vec<&str> = NAMES.iter().filter(|n| self.backends.contains(n.0)).map(|n| n.1).collect(); + f.write_str(&if backends.is_empty() { format!("{:?}", self.backends) } else { backends.join(" or ") })?; + if self.software { + f.write_str(" on a software adapter")?; + } + f.write_str(if self.stencil { "" } else { " without a stencil buffer" }) + } +} + +/// The attempts in order (see the module docs). `first`: the backends the start is configured with; +/// `requested`: they are `WGPU_BACKEND`'s, which every attempt keeps; `stencil`: `CADCRAFT_STENCIL`. +pub(crate) fn attempts(first: Backends, requested: bool, stencil: Switch) -> Vec { + let mut adapters = vec![(first, false)]; + if !requested && first.contains(Backends::GL) && first != Backends::GL { + adapters.push((Backends::GL, false)); + } + adapters.push((first, true)); + let stencils: &[bool] = match stencil { + Switch::On => &[true], + Switch::Off => &[false], + Switch::Default => &[true, false], + }; + adapters.into_iter().flat_map(|(backends, software)| stencils.iter().map(move |&stencil| Attempt { backends, software, stencil })).collect() +} + +/// What a failed attempt says about the attempts after it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Failure { + /// The adapter, the device or the surface couldn't be made, or nothing was drawn: the same + /// adapter without a stencil buffer fails the same way. + Adapter, + /// Something the stencil buffer is part of failed: the same adapter without one may work. + Stencil, +} + +/// The attempt to try after the one at `at` failed with `failure`: the next one after a stencil +/// failure, else the next on another adapter. +pub(crate) fn next(attempts: &[Attempt], at: usize, failure: Failure) -> Option { + let failed = *attempts.get(at)?; + attempts.iter().enumerate().skip(at + 1).find(|(_, a)| failure == Failure::Stencil || !a.same_adapter(failed)).map(|(i, _)| i) +} + +/// What `error` from `eframe::run_native` says about the attempt: `None` when it isn't the graphics +/// (the app's own start, the windowing system). +pub(crate) fn classify(error: &eframe::Error) -> Option { + match error { + eframe::Error::Wgpu(WgpuError::ConfigureSurface(_) | WgpuError::CreateRenderer(_)) => Some(Failure::Stencil), + eframe::Error::Wgpu(_) => Some(Failure::Adapter), + eframe::Error::AppCreation(error) => error.downcast_ref::().map(|c| c.failure), + _ => None, + } +} + +/// The attempt to try after the one at `at` ended with `error`: none once the app was `created`, +/// since a failure after that is no start failure (and the app can't be built twice), and none for +/// an error that isn't the graphics'. +pub(crate) fn retry(attempts: &[Attempt], at: usize, created: bool, error: &eframe::Error) -> Option { + if created { + return None; + } + next(attempts, at, classify(error)?) +} + +/// [`check`] found that the window can't draw. Returned from the app creator, it ends the attempt +/// before the app exists. +#[derive(Debug)] +pub(crate) struct CheckFailed { + failure: Failure, + message: String, +} + +impl std::fmt::Display for CheckFailed { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for CheckFailed {} + +/// Clear a small target and read it back: as it is, then with a stencil buffer of `stencil`, made +/// as egui makes the window's (see the module docs). A target that doesn't come back cleared is a +/// [`Failure::Adapter`] without the stencil buffer and a [`Failure::Stencil`] with it. +pub(crate) fn check(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option) -> Result<(), CheckFailed> { + passes(stencil, |format| clear_and_read(device, queue, format)) +} + +/// [`check`]'s passes, each made by `pass` with or without the stencil buffer: what failed names +/// the [`Failure`], and a device that didn't answer the first pass isn't waited for a second time. +fn passes( + stencil: Option, + mut pass: impl FnMut(Option) -> Result, +) -> Result<(), CheckFailed> { + let failed = |failure: Failure| move |message: String| CheckFailed { failure, message }; + let answered = pass(None).map_err(failed(Failure::Adapter))?; + match stencil { + Some(format) if answered => pass(Some(format)).map(|_| ()).map_err(failed(Failure::Stencil)), + _ => Ok(()), + } +} + +/// One pass of [`check`]: `Err` names what came back instead of [`CHECK_COLOR`]; `Ok(false)`: no +/// answer came, which counts as a pass. +fn clear_and_read(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option) -> Result { + let size = wgpu::Extent3d { width: CHECK_WIDTH, height: 1, depth_or_array_layers: 1 }; + let row = CHECK_WIDTH * 4; + let submitted = pollster::block_on(egui_wgpu::winit::catch_errors(device, || { + let texture = |format, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("startup check"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + let color = texture(wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC); + // The usage egui gives the window's depth and stencil texture. + let depth = stencil.map(|format| texture(format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)); + let color_view = color.create_view(&wgpu::TextureViewDescriptor::default()); + let depth_view = depth.as_ref().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default())); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("startup check"), + size: u64::from(row), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + let [r, g, b, a] = CHECK_COLOR.map(|c| f64::from(c) / 255.0); + drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("startup check"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &color_view, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r, g, b, a }), store: wgpu::StoreOp::Store }, + depth_slice: None, + })], + depth_stencil_attachment: depth_view.as_ref().zip(stencil).map(|(view, format)| wgpu::RenderPassDepthStencilAttachment { + view, + depth_ops: format.has_depth_aspect().then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), + stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }), + }), + ..Default::default() + })); + encoder.copy_texture_to_buffer( + color.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: None }, + }, + size, + ); + queue.submit([encoder.finish()]); + buffer + })); + let buffer = submitted.map_err(|e| format!("the device refused the check: {e}"))?; + let (send, mapped) = std::sync::mpsc::channel(); + buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| { + let _ = send.send(result); + }); + match device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(CHECK_TIMEOUT) }) { + Ok(_) => {} + Err(wgpu::PollError::Timeout) => { + log::warn!("graphics: the start-up check had no answer after {CHECK_TIMEOUT:?}; taken as passed"); + return Ok(false); + } + Err(e) => return Err(format!("waiting for the check failed: {e}")), + } + match mapped.try_recv() { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(format!("the check could not be read back: {e}")), + Err(_) => { + log::warn!("graphics: the start-up check was not read back; taken as passed"); + return Ok(false); + } + } + let pixels = buffer.slice(..).get_mapped_range().map_err(|e| format!("the check could not be read back: {e}"))?; + read_back(&pixels).map(|()| true) +} + +/// Whether the row [`check`] read back is [`CHECK_COLOR`] throughout, within what a driver's +/// rounding could change. +fn read_back(pixels: &[u8]) -> Result<(), String> { + let row = CHECK_WIDTH as usize * CHECK_COLOR.len(); + let cleared = |p: &[u8; CHECK_COLOR.len()]| p.iter().zip(CHECK_COLOR).all(|(&p, c)| p.abs_diff(c) <= 8); + match pixels.as_chunks::<{ CHECK_COLOR.len() }>().0.iter().find(|&p| !cleared(p)) { + Some(p) => Err(format!("a cleared target read back {p:?}, not {CHECK_COLOR:?}")), + None if pixels.len() == row => Ok(()), + None => Err(format!("the check read back {} bytes, not {row}", pixels.len())), + } +} + +/// `options` for `attempt`: its backends, its adapter and its stencil buffer. +pub(crate) fn apply(options: &mut eframe::NativeOptions, attempt: Attempt) { + options.stencil_buffer = if attempt.stencil { STENCIL_BITS } else { 0 }; + if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { + create.instance_descriptor.backends = attempt.backends; + create.native_adapter_selector = attempt.software.then(|| Arc::new(software_adapter) as NativeAdapterSelectorMethod); + } +} + +/// A software adapter of `adapters` that can show `surface`. +fn software_adapter(adapters: &[wgpu::Adapter], surface: Option<&wgpu::Surface<'_>>) -> Result { + adapters + .iter() + .find(|a| a.get_info().device_type == DeviceType::Cpu && surface.is_none_or(|s| a.is_surface_supported(s))) + .cloned() + .ok_or_else(|| "no software adapter can show the window".to_owned()) +} + +/// Run eframe with each attempt in turn until one starts the window, then build the app with +/// `create`. `options` are as configured (their backends are `WGPU_BACKEND`'s or the platform's), +/// `stencil` is `CADCRAFT_STENCIL`. A failed attempt is dropped with its window before any app +/// exists; an error once the app was created ends the start, as before. When every attempt failed, +/// the first one's error is returned: it is the one the start as it always was would have given. +pub(crate) fn run_native(name: &str, options: eframe::NativeOptions, stencil: Switch, create: Creator<'_>) -> eframe::Result { + let requested = Backends::from_env().is_some(); + let configured = match &options.wgpu_options.wgpu_setup { + WgpuSetup::CreateNew(create) => create.instance_descriptor.backends, + WgpuSetup::Existing(_) => Backends::all(), + }; + // Only what this build has, so no attempt asks for a backend that can't be there. + let first = if requested { configured } else { configured & wgpu::Instance::enabled_backend_features() }; + let attempts = attempts(first, requested, stencil); + // Later attempts reuse eframe's event loop, so the hooks a clone drops aren't needed again. + let template = options.clone(); + let mut options = Some(options); + let mut create = Some(create); + let mut first_failure = None; + let mut why = None; + let mut at = 0; + while let Some(&attempt) = attempts.get(at) { + let mut attempt_options = options.take().unwrap_or_else(|| template.clone()); + apply(&mut attempt_options, attempt); + fault::refuse_adapter(&mut attempt_options, at); + log::info!("graphics: starting with {attempt} (attempt {} of {})", at + 1, attempts.len()); + let started = Started { attempt, index: at, why: why.clone() }; + let slot = &mut create; + let result = eframe::run_native( + name, + attempt_options, + Box::new(|cc| { + if let Some(rs) = &cc.wgpu_render_state { + fault::check(started.index, started.stencil_format())?; + let checking = std::time::Instant::now(); + check(&rs.device, &rs.queue, started.stencil_format())?; + log::info!("graphics: the start-up check passed in {:.1?}", checking.elapsed()); + } + let create = slot.take().ok_or("the app was already created")?; + create(cc, &started) + }), + ); + let Err(error) = result else { return Ok(()) }; + let Some(after) = retry(&attempts, at, create.is_none(), &error) else { + if create.is_none() || classify(&error).is_none() { + return Err(error); + } + log::error!("graphics: {attempt} failed: {error}; no other renderer is left to try"); + return Err(first_failure.unwrap_or(error)); + }; + log::warn!("graphics: {attempt} failed: {error}; trying the next renderer"); + // The first failure says why the first choice isn't drawing; the log has the others. + why.get_or_insert_with(|| format!("{attempt} failed: {}", error.to_string().lines().next().unwrap_or_default())); + first_failure.get_or_insert(error); + at = after; + } + Err(first_failure.unwrap_or_else(|| eframe::Error::AppCreation("no renderer to start the window with".into()))) +} + +/// The attempt that started the window, handed to the app creator. +pub(crate) struct Started { + attempt: Attempt, + /// Its position in [`attempts`]. + index: usize, + /// Why the first attempt isn't the one drawing. + why: Option, +} + +impl Started { + /// The format of the window's stencil buffer, which the canvas's pipelines must match. + fn stencil_format(&self) -> Option { + egui_wgpu::depth_format_from_bits(0, if self.attempt.stencil { STENCIL_BITS } else { 0 }) + } + + /// Draw the canvas on the GPU with the window's render state `rs`, or on the CPU when its + /// pipelines are refused. Logs which renderer draws, and says in the status bar why when it is + /// not the first choice (unless the start already put something there). + pub(crate) fn install(&self, app: &mut CadApp, rs: Option<&egui_wgpu::RenderState>) { + let Some(rs) = rs else { return }; + let stencil = self.stencil_format(); + let installed = pollster::block_on(egui_wgpu::winit::catch_errors(&rs.device, || app.set_wgpu(rs, stencil))); + let canvas_failed = match installed { + Err(e) => Some(e.to_string()), + Ok(()) => fault::canvas(self.index), + }; + if canvas_failed.is_some() { + app.canvas.gpu = None; + app.canvas.gpu_device = None; + } + let info = rs.adapter.get_info(); + log::info!( + "graphics: {} draws the window on {} ({:?}, {:?}, driver {}); the canvas draws on the {}", + self.attempt, + info.name.trim(), + info.backend, + info.device_type, + [info.driver.trim(), info.driver_info.trim()].into_iter().filter(|s| !s.is_empty()).collect::>().join(" "), + if canvas_failed.is_some() { "CPU" } else { "GPU" } + ); + if !self.attempt.stencil { + log::warn!("graphics: no stencil buffer: clipped layout viewports draw unclipped"); + } + let note = match (&self.why, &canvas_failed) { + (_, Some(error)) => { + Some(cadcraft_ui_egui::tf!("Graphics: the drawing area draws on the CPU, because the GPU refused it: {error}", error = error)) + } + (Some(why), None) => Some(cadcraft_ui_egui::tf!("Graphics: drawing with {renderer}, because {why}", renderer = self.attempt, why = why)), + (None, None) => None, + }; + if let Some(note) = note { + log::warn!("{note}"); + if app.status.is_none() { + app.set_status(note); + } + } + } +} + +/// A test switch read only by debug builds: `CADCRAFT_GRAPHICS_FAULT=:[,...]` fails +/// the attempt at that position in [`attempts`] (from 0) at `adapter` (its adapter is refused), +/// `draw` or `stencil` ([`check`]'s pass without or with the stencil buffer), or `canvas` (the +/// canvas's pipelines), so each fallback can be run on a machine whose graphics work. +mod fault { + use super::{Arc, CheckFailed, Failure, NativeAdapterSelectorMethod, WgpuSetup, wgpu}; + + #[cfg(debug_assertions)] + fn asked(index: usize, step: &str) -> bool { + listed(std::env::var("CADCRAFT_GRAPHICS_FAULT").ok().as_deref(), index, step) + } + + #[cfg(not(debug_assertions))] + fn asked(_index: usize, _step: &str) -> bool { + false + } + + /// Whether `value` lists `:`. + #[cfg(any(debug_assertions, test))] + pub(super) fn listed(value: Option<&str>, index: usize, step: &str) -> bool { + value.is_some_and(|v| v.split(',').any(|f| f.trim().split_once(':') == Some((index.to_string().as_str(), step)))) + } + + pub(super) fn refuse_adapter(options: &mut eframe::NativeOptions, index: usize) { + if asked(index, "adapter") + && let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup + { + let refuse = |_: &[wgpu::Adapter], _: Option<&wgpu::Surface<'_>>| Err("refused by CADCRAFT_GRAPHICS_FAULT".to_owned()); + create.native_adapter_selector = Some(Arc::new(refuse) as NativeAdapterSelectorMethod); + } + } + + pub(super) fn check(index: usize, stencil: Option) -> Result<(), CheckFailed> { + let fail = |failure, step| CheckFailed { failure, message: format!("the {step} check failed (CADCRAFT_GRAPHICS_FAULT)") }; + if asked(index, "draw") { + return Err(fail(Failure::Adapter, "draw")); + } + if stencil.is_some() && asked(index, "stencil") { + return Err(fail(Failure::Stencil, "stencil")); + } + Ok(()) + } + + pub(super) fn canvas(index: usize) -> Option { + asked(index, "canvas").then(|| "refused by CADCRAFT_GRAPHICS_FAULT".to_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ANY: Backends = Backends::VULKAN.union(Backends::GL); + + /// A short name of `attempt`, to read the order in the asserts. + fn key(attempt: &Attempt) -> String { + let short = [(Backends::DX12, "dx12"), (Backends::METAL, "metal"), (Backends::VULKAN, "vulkan"), (Backends::GL, "gl")]; + let mut key = short.iter().filter(|(b, _)| attempt.backends.contains(*b)).map(|(_, n)| *n).collect::>().join("+"); + if attempt.software { + key.push_str(" software"); + } + if !attempt.stencil { + key.push_str(" no-stencil"); + } + key + } + + fn keys(list: &[Attempt]) -> Vec { + list.iter().map(key).collect() + } + + /// The first attempt is the start as it always was; OpenGL alone comes only where it was one of + /// several, then the same backends on a software adapter, each with and then without a stencil + /// buffer. `WGPU_BACKEND` keeps its backends on every attempt, and `CADCRAFT_STENCIL` its choice. + #[test] + fn the_attempts_begin_with_the_start_as_it_was_and_keep_explicit_choices() { + let linux = attempts(ANY, false, Switch::Default); + assert_eq!(keys(&linux), ["vulkan+gl", "vulkan+gl no-stencil", "gl", "gl no-stencil", "vulkan+gl software", "vulkan+gl software no-stencil"]); + // Windows: DirectX 12 alone (graphics.rs), so the fallback never creates OpenGL there. + let windows = attempts(Backends::DX12, false, Switch::Default); + assert_eq!(keys(&windows), ["dx12", "dx12 no-stencil", "dx12 software", "dx12 software no-stencil"]); + // WGPU_BACKEND=vulkan,gl: no attempt leaves its backends. + assert!(attempts(ANY, true, Switch::Default).iter().all(|a| a.backends == ANY)); + assert_eq!(attempts(Backends::GL, false, Switch::Default).len(), 4, "OpenGL alone is already the first"); + // CADCRAFT_STENCIL: off is never on, on is never dropped. + assert!(attempts(ANY, false, Switch::Off).iter().all(|a| !a.stencil)); + assert!(attempts(ANY, false, Switch::On).iter().all(|a| a.stencil)); + assert_eq!(attempts(ANY, false, Switch::On).len() * 2, linux.len()); + } + + /// A stencil failure tries the same adapter without the stencil buffer; any other failure skips + /// that twin and tries the next adapter; past the last there is nothing. + #[test] + fn a_failure_picks_the_next_attempt_by_what_failed() { + let list = attempts(ANY, false, Switch::Default); + let at = |k: &str| list.iter().position(|a| key(a) == k).unwrap(); + let next_key = |from: &str, failure| next(&list, at(from), failure).map(|i| key(&list[i])); + assert_eq!(next_key("vulkan+gl", Failure::Stencil).as_deref(), Some("vulkan+gl no-stencil")); + assert_eq!(next_key("vulkan+gl", Failure::Adapter).as_deref(), Some("gl")); + assert_eq!(next_key("vulkan+gl no-stencil", Failure::Adapter).as_deref(), Some("gl")); + assert_eq!(next_key("gl no-stencil", Failure::Stencil).as_deref(), Some("vulkan+gl software")); + assert_eq!(next_key("vulkan+gl software", Failure::Adapter), None); + assert_eq!(next_key("vulkan+gl software no-stencil", Failure::Stencil), None); + assert_eq!(next(&list, list.len(), Failure::Stencil), None); + // CADCRAFT_STENCIL=1: a stencil failure has no twin to fall back to, so the next adapter. + let on = attempts(Backends::DX12, false, Switch::On); + assert_eq!(next(&on, 0, Failure::Stencil), Some(1)); + assert!(on[1].software); + } + + /// Errors before the app exists are graphics failures; which kind decides the next attempt. The + /// app's own errors and the windowing system's are not, so they end the start as before. + #[test] + fn start_errors_are_sorted_by_what_failed() { + let no_adapter = eframe::Error::Wgpu(WgpuError::CustomNativeAdapterSelectionError("none".into())); + assert_eq!(classify(&no_adapter), Some(Failure::Adapter)); + assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable)), Some(Failure::Adapter)); + let refused = || wgpu::Error::Validation { source: Box::new(std::fmt::Error), description: "refused".into() }; + assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::ConfigureSurface(refused()))), Some(Failure::Stencil)); + assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::CreateRenderer(refused()))), Some(Failure::Stencil)); + for failure in [Failure::Adapter, Failure::Stencil] { + let failed = eframe::Error::AppCreation(Box::new(CheckFailed { failure, message: "black".into() })); + assert_eq!(classify(&failed), Some(failure)); + } + assert_eq!(classify(&eframe::Error::AppCreation("the app's own start".into())), None); + } + + /// Only a graphics failure before the app exists is retried: once the app was created an error + /// ends the start (the app can't be built twice), as does an error that isn't the graphics'. + #[test] + fn only_a_start_failure_before_the_app_exists_is_retried() { + let list = attempts(Backends::DX12, false, Switch::Default); + let gpu = eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable); + assert_eq!(retry(&list, 0, false, &gpu), Some(2)); + assert_eq!(retry(&list, 0, true, &gpu), None); + let black = eframe::Error::AppCreation(Box::new(CheckFailed { failure: Failure::Stencil, message: "black".into() })); + assert_eq!(retry(&list, 0, false, &black), Some(1)); + assert_eq!(retry(&list, 0, false, &eframe::Error::AppCreation("the app's own start".into())), None); + } + + /// Each attempt takes its backends, its adapter and its stencil buffer. + #[test] + fn an_attempt_sets_its_backends_adapter_and_stencil_buffer() { + let mut options = eframe::NativeOptions::default(); + for attempt in attempts(Backends::VULKAN | Backends::GL, false, Switch::Default) { + apply(&mut options, attempt); + let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") }; + assert_eq!(create.instance_descriptor.backends, attempt.backends); + assert_eq!(create.native_adapter_selector.is_some(), attempt.software, "{attempt}"); + assert_eq!(options.stencil_buffer > 0, attempt.stencil, "{attempt}"); + } + } + + /// The read-back is answered and passes on a working device, with and without a stencil + /// buffer. The device is made as the app makes it: on Windows DirectX 12 alone with FXC + /// (graphics.rs; an AMD driver crashes when OpenGL is created there, #31), and egui's limits for + /// the adapter. + #[test] + fn the_check_passes_on_a_device_that_draws() { + let mut options = eframe::NativeOptions::default(); + crate::graphics::configure(&mut options, if cfg!(windows) { None } else { Some(Backends::all()) }, None); + let WgpuSetup::CreateNew(mut create) = options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") }; + create.instance_descriptor.backends.remove(Backends::BROWSER_WEBGPU); + let setup = WgpuSetup::CreateNew(create); + let instance = pollster::block_on(setup.new_instance()); + let config = egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() }; + let Ok(rs) = pollster::block_on(egui_wgpu::RenderState::create(&config, &instance, None, Default::default())) else { + eprintln!("no graphics adapter here: the device check is left to machines with one"); + return; + }; + let info = rs.adapter.get_info(); + for stencil in [None, Some(wgpu::TextureFormat::Stencil8)] { + // `check` takes no answer as a pass; a working device must answer, or every start on it + // would wait for the timeout. + let started = std::time::Instant::now(); + let read = clear_and_read(&rs.device, &rs.queue, stencil); + let elapsed = started.elapsed(); + assert_eq!(read, Ok(true), "{stencil:?} on {} ({:?}, {:?}) after {elapsed:?}", info.name, info.backend, info.device_type); + } + } + + /// The read-back passes only when every pixel came back cleared: a target the clear never + /// reached still holds the zeros a texture starts as. + #[test] + fn the_check_fails_a_target_the_clear_did_not_reach() { + let row = |pixel: [u8; 4]| pixel.repeat(CHECK_WIDTH as usize); + assert!(read_back(&row(CHECK_COLOR)).is_ok()); + assert!(read_back(&row([250, 6, 251, 255])).is_ok(), "a driver's rounding"); + assert!(read_back(&row([0, 0, 0, 0])).is_err(), "never cleared"); + assert!(read_back(&row([255, 0, 255, 0])).is_err(), "another alpha"); + let mut one_off = row(CHECK_COLOR); + one_off[CHECK_COLOR.len() * 7 + 1] = 200; + assert!(read_back(&one_off).is_err(), "one pixel the clear missed"); + assert!(read_back(&row(CHECK_COLOR)[..8]).is_err(), "a short read"); + assert!(read_back(&[]).is_err()); + } + + /// A target that didn't come back cleared blames the adapter without the stencil buffer and the + /// stencil buffer with it; no answer is a pass, and isn't waited for twice. + #[test] + fn a_failed_pass_names_what_failed() { + let stencil = Some(wgpu::TextureFormat::Stencil8); + let failure = |black_with: Option| { + passes(stencil, |format| if black_with.is_none_or(|with| with == format.is_some()) { Err("black".into()) } else { Ok(true) }) + .map_err(|e| e.failure) + }; + assert_eq!(failure(Some(false)), Err(Failure::Adapter), "black without the stencil buffer"); + assert_eq!(failure(None), Err(Failure::Adapter), "black either way"); + assert_eq!(failure(Some(true)), Err(Failure::Stencil), "black only with it"); + let mut asked = Vec::new(); + let unanswered = passes(stencil, |format| { + asked.push(format); + Ok(false) + }); + assert!(unanswered.is_ok()); + assert_eq!(asked, [None], "no second wait after no answer"); + let mut asked = Vec::new(); + let answered = passes(stencil, |format| { + asked.push(format); + Ok(true) + }); + assert!(answered.is_ok()); + assert_eq!(asked, [None, stencil], "both passes when the first answered"); + } + + /// The test switch names attempts by position and step, and nothing else trips it. + #[test] + fn the_fault_switch_names_one_step_of_one_attempt() { + assert!(fault::listed(Some("0:stencil"), 0, "stencil")); + assert!(fault::listed(Some(" 2:adapter , 0:draw"), 0, "draw")); + assert!(!fault::listed(Some("0:stencil"), 1, "stencil")); + assert!(!fault::listed(Some("10:draw"), 1, "draw")); + assert!(!fault::listed(Some("0:stencils"), 0, "stencil")); + assert!(!fault::listed(None, 0, "draw")); + } + + /// The log and the status bar tell the attempts apart. + #[test] + fn an_attempt_names_what_it_tries() { + let list = attempts(ANY, false, Switch::Default); + let names: std::collections::BTreeSet = list.iter().map(ToString::to_string).collect(); + assert_eq!(names.len(), list.len()); + } +} diff --git a/apps/cadcraft/src/single_instance.rs b/apps/cadcraft/src/single_instance.rs index 9ab46229a..c66bad870 100644 --- a/apps/cadcraft/src/single_instance.rs +++ b/apps/cadcraft/src/single_instance.rs @@ -428,4 +428,62 @@ mod tests { received.sort(); assert_eq!(received, handed); } + + /// A Nightly profile on Windows keeps its single-instance AF_UNIX socket under + /// `\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 `\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 + // `\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)]); + } } diff --git a/craft-i18n.rev b/craft-i18n.rev new file mode 100644 index 000000000..174050625 --- /dev/null +++ b/craft-i18n.rev @@ -0,0 +1 @@ +9fa32aecf2759cd61bb216a958df68da619798f3 diff --git a/crates/constraints/src/lib.rs b/crates/constraints/src/lib.rs index 5b01fc022..4ea28547f 100644 --- a/crates/constraints/src/lib.rs +++ b/crates/constraints/src/lib.rs @@ -206,8 +206,7 @@ pub fn next_id(d: &Drawing) -> u32 { /// Interpret a constraint against the model's current parameters, appending its auxiliary /// unknowns (contact parameters) to the model, settled with the geometry held still. pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result { - let x = model.x0.clone(); - let mut b = Built::new(c, model, &x, target)?; + let mut b = Built::new(c, model, &model.x0, target)?; if b.aux_init.is_empty() { return Ok(b); } @@ -527,22 +526,26 @@ pub fn solve(d: &mut Drawing, opts: &SolveOptions) -> Result Vec<(u32, Option)> { - let mut e = env(d); + residuals_with_model(d, residual_model(d)).collect() +} + +fn residual_model(d: &Drawing) -> Model { let handles: Vec = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect(); - let mut model = Model::build(d, &handles); - d.constraints - .iter() - .take(MAX_CONSTRAINTS) - .map(|c| { - let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) }; - let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| { - let mut out = Vec::new(); - b.eval(&model, &model.x0, &mut out); - lm::max_abs(&out) - }); - (c.id, r) - }) - .collect() + Model::build(d, &handles) +} + +fn residuals_with_model(d: &Drawing, mut model: Model) -> impl Iterator)> + '_ { + let mut e = env(d); + let mut out = Vec::new(); + d.constraints.iter().take(MAX_CONSTRAINTS).map(move |c| { + let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) }; + let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| { + out.clear(); + b.eval(&model, &model.x0, &mut out); + lm::max_abs(&out) + }); + (c.id, r) + }) } /// Put back what each Fix locks where `before` had it, and report whether anything moved. @@ -683,9 +686,9 @@ pub fn moved_anchors(d: &Drawing, before: &Drawing) -> Vec<(u32, Vec2)> { /// True when every interpretable constraint holds at the current geometry. pub fn all_satisfied(d: &Drawing) -> bool { - let handles: Vec = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect(); - let tol = scale_tol(&Model::build(d, &handles).x0) * 10.0; - residuals(d).iter().all(|(_, r)| r.is_none_or(|v| v <= tol)) + let model = residual_model(d); + let tol = scale_tol(&model.x0) * 10.0; + residuals_with_model(d, model).all(|(_, r)| r.is_none_or(|v| v <= tol)) } /// Check that a constraint's references make sense for its type. diff --git a/crates/constraints/src/lm.rs b/crates/constraints/src/lm.rs index f2e3304d0..eff4db4dd 100644 --- a/crates/constraints/src/lm.rs +++ b/crates/constraints/src/lm.rs @@ -222,6 +222,27 @@ pub(crate) fn null_space(m: &[f64], rows: usize, cols: usize) -> (usize, Vec Vec { + let mut matrix = vec![0.0; rows * rows]; + let mut terms = Vec::new(); + let width = inverse_weights.len(); + for (i, row) in jac.chunks_exact(width).enumerate() { + terms.clear(); + terms.extend(row.iter().enumerate().filter(|(_, value)| **value != 0.0).map(|(col, &value)| (col, value, inverse_weights[col]))); + for (k, other) in jac.chunks_exact(width).enumerate().skip(i) { + let sum = if terms.len() == width { + row.iter().zip(other).zip(inverse_weights).fold(0.0, |sum, ((&v, &other_v), &weight)| sum + v * other_v * weight) + } else { + terms.iter().fold(0.0, |sum, &(col, v, weight)| sum + v * other[col] * weight) + }; + matrix[i * rows + k] = sum; + matrix[k * rows + i] = sum; + } + } + matrix +} + /// Run the solver from `x0`. Only `free` parameters change. pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec), x0: &[f64], free: &[usize], weights: &[f64], tol: f64, max_iter: usize) -> Outcome { let mut x = x0.to_vec(); @@ -243,22 +264,7 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec), x0: &[f64], free: &[usize while iter < max_iter { iter += 1; let jac = jacobian(f, &x, free, rows); - // A = J W⁻¹ Jᵀ - let mut a = vec![0.0; rows * rows]; - for i in 0..rows { - for k in i..rows { - let mut s = 0.0; - for (c, w) in winv.iter().enumerate() { - s += jac.get(i * nf + c).copied().unwrap_or(0.0) * jac.get(k * nf + c).copied().unwrap_or(0.0) * w; - } - if let Some(v) = a.get_mut(i * rows + k) { - *v = s; - } - if let Some(v) = a.get_mut(k * rows + i) { - *v = s; - } - } - } + let a = normal_matrix(&jac, &winv, rows); let diag_max = (0..rows).map(|i| a.get(i * rows + i).copied().unwrap_or(0.0)).fold(0.0f64, f64::max).max(1e-12); let mut improved = false; for _ in 0..12 { @@ -310,6 +316,20 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec), x0: &[f64], free: &[usize mod tests { use super::*; + #[test] + fn sparse_and_dense_constraints_keep_their_weighted_cross_terms() { + // Includes an empty row, an unconstrained column in a sparse row, and a tiny derivative. + let rows = [[-0., 0., -0., -0.], [2., 0., -3., 0.], [0., 0., 0., 1e-12], [1., 3., 2., -5.]]; + let weights = [1., 0.25, 0.5, 2.]; + let matrix = normal_matrix(&rows.concat(), &weights, rows.len()); + for (i, row) in rows.iter().enumerate() { + for (k, other) in rows.iter().enumerate() { + let reference = (0..weights.len()).fold(0.0, |sum, c| sum + row[c] * other[c] * weights[c]); + assert_eq!(matrix[i * rows.len() + k].to_bits(), reference.to_bits()); + } + } + } + #[test] fn dense_and_rank() { let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap(); diff --git a/crates/constraints/src/tests.rs b/crates/constraints/src/tests.rs index eadc7a3c2..d398a6bed 100644 --- a/crates/constraints/src/tests.rs +++ b/crates/constraints/src/tests.rs @@ -328,6 +328,8 @@ fn invalid_references_and_purge() { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), ); let bad = |d: &mut Drawing, c: Constraint| assert!(add(d, c, &SolveOptions::default()).is_err()); diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index a88cbef0b..75978e0e2 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -46,15 +46,21 @@ mod layout; mod proxy; mod text; mod wipeout; +mod xdata; + +pub use xdata::{ + MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name, + check_xdata_groups, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of, +}; pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal}; pub use common::{Common, Handle, Lineweight, RawTag, Transparency}; pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid}; pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader}; pub use fill::{Gradient, Hatch, HatchLoop}; -pub use layout::{Image, Table, TableCell, Viewport}; -pub use proxy::{ProxyTables, proxy_entities}; -pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign}; +pub use layout::{Image, Table, TableCell, Viewport, ViewportUcs}; +pub use proxy::{ProxyTables, TableOrder, proxy_entities}; +pub use text::{HAlign, MText, MTextBackground, MTextColumnType, MTextColumns, Text, VAlign}; pub use wipeout::Wipeout; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Unknown { @@ -399,7 +405,9 @@ impl EntityKind { t3(p); } if let DimKind::Linear { rotation } = &mut d.kind { - *rotation = cadcraft_geom::norm_angle(*rotation + rot); + // 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 }); } d.marks.transform(&t3, rot, s, mirror); d.block = None; @@ -617,7 +625,8 @@ impl EntityKind { EntityKind::Polyline3d(p) => p.points.iter().map(|q| q.xy()).collect(), EntityKind::Spline(s) => { if s.fit.is_empty() { - s.control.clone() + // One grip per control vertex: a closed spline's repeats have none (#3566). + s.control.iter().take(s.distinct_controls()).copied().collect() } else { s.fit.clone() } diff --git a/crates/doc/src/entity/block.rs b/crates/doc/src/entity/block.rs index 9d41548ea..652e2fb2e 100644 --- a/crates/doc/src/entity/block.rs +++ b/crates/doc/src/entity/block.rs @@ -154,7 +154,43 @@ impl AttribProps { #[derive(Clone, Copy, Debug)] pub struct TagKey<'a>(pub &'a str); +#[cfg(test)] +std::thread_local! { + static TAG_CROSS_PROBE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn record_tag_cross_probe(left: &str, right: &str) { + TAG_CROSS_PROBE.with(|probe| { + let Some((position, mut counts)) = probe.get() else { return }; + match (left.as_bytes().get(position), right.as_bytes().get(position)) { + (Some(b'A'), Some(b'D')) => counts[0] += 1, + (Some(b'D'), Some(b'A')) => counts[1] += 1, + _ => return, + } + probe.set(Some((position, counts))); + }); +} + impl TagKey<'_> { + /// Count comparisons in both directions between the A and D fixture tag sets. + #[cfg(test)] + pub(crate) fn with_cross_probes(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) { + struct Restore(Option<(usize, [usize; 2])>); + + impl Drop for Restore { + fn drop(&mut self) { + TAG_CROSS_PROBE.with(|probe| probe.set(self.0)); + } + } + + TAG_CROSS_PROBE.with(|probe| { + let _restore = Restore(probe.replace(Some((position, [0; 2])))); + let value = f(); + (value, probe.get().map_or([0; 2], |(_, counts)| counts)) + }) + } + /// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case` /// finds equal. fn folded(&self) -> impl Iterator + '_ { @@ -164,6 +200,8 @@ impl TagKey<'_> { impl PartialEq for TagKey<'_> { fn eq(&self, other: &Self) -> bool { + #[cfg(test)] + record_tag_cross_probe(self.0, other.0); self.0.eq_ignore_ascii_case(other.0) } } @@ -172,6 +210,8 @@ impl Eq for TagKey<'_> {} impl Ord for TagKey<'_> { fn cmp(&self, other: &Self) -> Ordering { + #[cfg(test)] + record_tag_cross_probe(self.0, other.0); self.folded().cmp(other.folded()) } } diff --git a/crates/doc/src/entity/dim.rs b/crates/doc/src/entity/dim.rs index dc4635c7a..81fcbdf30 100644 --- a/crates/doc/src/entity/dim.rs +++ b/crates/doc/src/entity/dim.rs @@ -100,7 +100,9 @@ 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 = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot }); + // 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 }); } if let Some(j) = &mut self.jog_line { t3(j); diff --git a/crates/doc/src/entity/fill.rs b/crates/doc/src/entity/fill.rs index 7a7799a55..fef6bc513 100644 --- a/crates/doc/src/entity/fill.rs +++ b/crates/doc/src/entity/fill.rs @@ -7,8 +7,9 @@ pub struct HatchLoop { pub vertices: Vec, #[serde(default)] pub outer: bool, - /// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and - /// Outermost (16), derives External (1) from `outer`, and sets Polyline (2). + /// Original DXF group 92 bits. Writing keeps only Textbox (8) and Outermost (16), derives + /// External (1) from `outer`, and sets Polyline (2). Derived (4) stays here but is not + /// written: the pixel size (group 47) it needs is not kept (#3664). /// None uses the flags of a locally created loop. #[serde(default, skip_serializing_if = "Option::is_none")] pub boundary_flags: Option, diff --git a/crates/doc/src/entity/layout.rs b/crates/doc/src/entity/layout.rs index 9155add9e..327fb5a61 100644 --- a/crates/doc/src/entity/layout.rs +++ b/crates/doc/src/entity/layout.rs @@ -1,6 +1,6 @@ use cadcraft_geom::Mat3; -use super::common::Handle; +use super::common::{Handle, RawTag}; use super::{Color, Deserialize, Serialize, Vec2, Vec3, standard, yes}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -27,6 +27,19 @@ pub struct Viewport { /// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space. #[serde(default = "yes")] pub on: bool, + /// The viewport's own UCS (DXF groups 110–112, 79, 146, 345, 346), the one it keeps while + /// `ucs_per_viewport` is set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ucs: Option, + /// UCS per viewport (UCSVP, DXF group 71): the viewport keeps its own UCS instead of + /// following the current one. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub ucs_per_viewport: bool, + /// The viewport's groups CADCraft doesn't model (snap, grid, lens and clipping, render mode, + /// plot style sheet, shade plot, visual style, background, lighting…), as read: written back + /// on save and carried by copies, their references pointed at what they named. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub extra: Vec, /// The view twist (DVIEW TWist inside the viewport; DXF group 51): radians counterclockwise, /// the model view seen through the viewport is turned on the sheet by it. 0 is untwisted. #[serde(default, skip_serializing_if = "is_zero_twist")] @@ -62,6 +75,27 @@ impl Viewport { } } +/// A layout viewport's own UCS. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ViewportUcs { + pub origin: Vec3, + pub x_axis: Vec3, + pub y_axis: Vec3, + /// Elevation (DXF group 146). + #[serde(default)] + pub elevation: f64, + /// Orthographic type (DXF group 79): 0 none, 1 top, 2 bottom, 3 front, 4 back, 5 left, 6 right. + #[serde(default)] + pub ortho: u8, + /// The named UCS it is, by UCS table name (DXF group 345). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub named: Option, + /// The UCS an orthographic one is based on, by UCS table name (DXF group 346); none: the WCS. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base: Option, +} + impl Default for Viewport { fn default() -> Self { Viewport { @@ -76,6 +110,9 @@ impl Default for Viewport { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, } } diff --git a/crates/doc/src/entity/proxy.rs b/crates/doc/src/entity/proxy.rs index e0b1eb1cf..bdc46580f 100644 --- a/crates/doc/src/entity/proxy.rs +++ b/crates/doc/src/entity/proxy.rs @@ -35,6 +35,36 @@ pub struct ProxyTables { pub styles: Vec<(String, String)>, } +/// The LAYER and LTYPE names the indices of proxy graphics count in, in table order (the +/// linetypes without ByBlock and ByLayer, as in [`ProxyTables`]). +#[derive(Clone, Copy, Debug, Default)] +pub struct TableOrder<'a> { + pub layers: &'a [String], + pub linetypes: &'a [String], +} + +/// The chunk that sets the layer by its index (ATTRIBUTE_LAYER). +const LAYER_CHUNK: u32 = 16; +/// The chunk that sets the linetype by its index (ATTRIBUTE_LINETYPE). +const LINETYPE_CHUNK: u32 = 18; +/// The linetype indices that stand for ByBlock and ByLayer. +const LINETYPE_BYBLOCK: u32 = 32766; +const LINETYPE_BYLAYER: u32 = 32767; + +/// The names a record's own graphics show for its table indices (`Unknown::names_by_index`). +#[derive(Default)] +struct Learned { + layers: std::collections::HashMap>, + linetypes: std::collections::HashMap, +} + +/// The names that stand for the table indices a record uses while it is decoded again to learn +/// them; an index without one leaves the layer, or gives ByLayer, as one past a table does. +struct Marks { + layers: std::collections::HashMap, + linetypes: std::collections::HashMap, +} + impl Unknown { /// The proxy graphics bytes of an entity: the 310 groups after its size group (92, or 160 in /// newer files), cut to that size. An ACAD_PROXY_ENTITY holds them in its proxy data: the size @@ -92,21 +122,22 @@ impl Unknown { Some((at, size)) } - /// The record's groups with the layer indices of its proxy graphics (ATTRIBUTE_LAYER) turned - /// into the written LAYER table `written`, by name; everything else as read. The name of an - /// index is the one the record's own decoded graphics draw on after it (so a proxy copied from - /// another drawing, or one whose layer was renamed, keeps the layer it shows); an index no - /// drawn entity follows takes the name from the file's table `read` (see - /// [`crate::Drawing::proxy_layers`]). A layer that is gone becomes layer 0 (the proxy's own - /// layer, as in a block); an index past the table, or one of a record without a name, stays - /// past the written one, which keeps the layer before it as AutoCAD does. Only the 310 groups - /// that hold the declared size are read and rewritten. `None` when no index changes, or the - /// graphics aren't readable. - pub fn with_proxy_layers(&self, read: &[String], written: &[String]) -> Option> { - // Only a proxy entity's own graphics: a kept dimension draws from its block instead. - if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") { - return None; - } + /// The record's groups with the table indices of its proxy graphics (ATTRIBUTE_LAYER and + /// ATTRIBUTE_LINETYPE) turned into the written tables `written`, by name; everything else as + /// read. The name of an index is the one the record's own decoded graphics use after it (so a + /// proxy copied from another drawing, or one whose layer was renamed, keeps what it shows); + /// an index no drawn entity follows takes the name from the file's tables `read` (see + /// [`crate::Drawing::proxy_layers`] and [`crate::Drawing::proxy_linetypes`]). + /// + /// A layer that is gone becomes layer 0 (the proxy's own layer, as in a block); a layer index + /// past the table, or one of a record without a name, stays past the written one, which keeps + /// the layer before it as AutoCAD does. A linetype that is gone, or an index that names none, + /// becomes ByLayer (32767, what an index past the table means too); ByBlock (32766) and + /// ByLayer stay. The picture of a kept dimension (#3438) is rewritten too: by the tables alone + /// when the dimension draws its block instead. Only the 310 groups that hold the declared size + /// are read and rewritten. `None` when no index changes, or the graphics aren't readable. + pub fn with_proxy_tables(&self, read: TableOrder<'_>, written: TableOrder<'_>) -> Option> { + use std::collections::HashMap; let (at, size) = self.graphics_size_group()?; let (mut bytes, mut groups) = (Vec::new(), Vec::new()); for i in (at + 1..self.tags.len()).take_while(|&i| self.tags[i].code == 310) { @@ -120,49 +151,72 @@ impl Unknown { groups.push((i, bytes.len() - before)); } let end = size.min(bytes.len()); - // The ATTRIBUTE_LAYER chunks: where each index sits. - let mut refs: Vec<(usize, u32)> = Vec::new(); + // The ATTRIBUTE_LAYER (16) and ATTRIBUTE_LINETYPE (18) chunks: where each index sits. + let mut refs: Vec<(usize, u32, u32)> = Vec::new(); let mut chunk = 8usize; while let (Some(len), Some(kind)) = (u32_at(&bytes[..end], chunk), u32_at(&bytes[..end], chunk + 4)) { let len = len as usize; if len < 8 || chunk.saturating_add(len) > end { break; } - if kind == 16 + if (kind == LAYER_CHUNK || kind == LINETYPE_CHUNK) && let Some(i) = u32_at(&bytes[..chunk + len], chunk + 8) { - refs.push((chunk + 8, i)); + refs.push((chunk + 8, kind, i)); } chunk += len; } if refs.is_empty() { return None; } - let indices: Vec = refs.iter().map(|r| r.1).collect(); - let learned = self.layers_by_index(&bytes[..end], &indices); - if read.is_empty() && learned.is_empty() { - return None; - } + let of = |k: u32| -> Vec { refs.iter().filter(|r| r.1 == k).map(|r| r.2).collect() }; + let learned = self.names_by_index(&bytes[..end], &of(LAYER_CHUNK), &of(LINETYPE_CHUNK), read.layers); // Each written name's first place, found once. - let mut place: std::collections::HashMap = std::collections::HashMap::new(); - for (p, n) in written.iter().enumerate() { - place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX)); - } - let zero = place.get("0").copied(); - let past = u32::try_from(written.len()).unwrap_or(u32::MAX).max(u32::try_from(read.len()).unwrap_or(u32::MAX)); - let mut resolved: std::collections::HashMap = std::collections::HashMap::new(); + let places = |names: &[String]| { + let mut place: HashMap = HashMap::new(); + for (p, n) in names.iter().enumerate() { + place.entry(n.to_ascii_lowercase()).or_insert(u32::try_from(p).unwrap_or(u32::MAX)); + } + place + }; + let (layer_at, linetype_at) = (places(written.layers), places(written.linetypes)); + let zero = layer_at.get("0").copied(); + let len = |names: &[String]| u32::try_from(names.len()).unwrap_or(u32::MAX); + let layers_past = len(written.layers).max(len(read.layers)); + let linetypes_past = len(written.linetypes).max(len(read.linetypes)); + // Without the file's table or names from the graphics, an index can't be placed. + let known_layers = !read.layers.is_empty() || !learned.layers.is_empty(); + let known_linetypes = !read.linetypes.is_empty() || !learned.linetypes.is_empty(); + let layer = |i: u32| { + let name = match learned.layers.get(&i) { + Some(name) => name.as_deref(), + None => read.layers.get(i as usize).map(String::as_str), + }; + match name.filter(|n| !n.is_empty()) { + Some(name) => layer_at.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i), + None if i >= layers_past => i, + None => layers_past, + } + }; + let linetype = |i: u32| { + if i == LINETYPE_BYBLOCK || i == LINETYPE_BYLAYER { + return i; + } + let name = learned.linetypes.get(&i).or_else(|| read.linetypes.get(i as usize)).map(String::as_str); + let by = |n: &str| n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock"); + match name.filter(|n| !n.is_empty() && !by(n)) { + Some(name) => linetype_at.get(&name.to_ascii_lowercase()).copied().unwrap_or(LINETYPE_BYLAYER), + None if i >= linetypes_past => i, + None => LINETYPE_BYLAYER, + } + }; + let mut resolved: HashMap<(u32, u32), u32> = HashMap::new(); let mut changed = false; - for (offset, i) in refs { - let j = *resolved.entry(i).or_insert_with(|| { - let name = match learned.get(&i) { - Some(name) => name.as_deref(), - None => read.get(i as usize).map(String::as_str), - }; - match name.filter(|n| !n.is_empty()) { - Some(name) => place.get(&name.to_ascii_lowercase()).copied().or(zero).unwrap_or(i), - None if i >= past => i, - None => past, - } + for (offset, kind, i) in refs { + let j = *resolved.entry((kind, i)).or_insert_with(|| match kind { + LAYER_CHUNK if known_layers => layer(i), + LINETYPE_CHUNK if known_linetypes => linetype(i), + _ => i, }); if j != i { bytes[offset..offset + 4].copy_from_slice(&j.to_le_bytes()); @@ -181,15 +235,20 @@ impl Unknown { Some(tags) } - /// The layer each ATTRIBUTE_LAYER index of `bytes` (the record's `indices`) stands for in - /// this record's decoded graphics: the bytes decoded again with index `i` named `#i` give the - /// same entities in the same order, so each one's marker meets its real layer. `None` for an - /// index after which the graphics stay on the layer before (one past the table it was read - /// with). An index above 65,535 isn't named here (it resolves through the file's table, like - /// one no entity follows). Empty when the graphics don't match - /// (not decoded from these bytes); an index whose entities disagree is left out. - fn layers_by_index(&self, bytes: &[u8], indices: &[u32]) -> std::collections::HashMap> { - /// What the entities after an index say about it. + /// The layer and linetype each index of `bytes` (the record's ATTRIBUTE_LAYER indices + /// `layers` and ATTRIBUTE_LINETYPE indices `linetypes`) stands for in this record's decoded + /// graphics: the bytes decoded again with each index `i` named `#i` give the same entities in + /// the same order, so each one's marker meets its real name. Only the indices the record uses + /// get a marker, so the work follows the chunks, not the largest index. + /// + /// A layer is `None` for an index after which the graphics stay on the layer before (one past + /// the table it was read with). When the entities after an index stay on the layer before but + /// the file's LAYER table `read` names that layer at the index, it names it. An index whose + /// entities disagree is left out. Empty when the graphics don't match (not decoded from these + /// bytes, such as a kept dimension's reference to its block). + fn names_by_index(&self, bytes: &[u8], layers: &[u32], linetypes: &[u32], read: &[String]) -> Learned { + use std::collections::{HashMap, HashSet}; + /// What the entities after a layer index say about it. enum Seen { /// They are on this layer, and the ones before them weren't. Named(String), @@ -199,27 +258,42 @@ impl Unknown { /// It keeps the layer before (two kept observations on different layers). Keeps, } - const MAX: u32 = 65_535; - let mut out: std::collections::HashMap> = std::collections::HashMap::new(); - if self.graphics.is_empty() { + let mut out = Learned::default(); + if self.graphics.is_empty() || self.graphics.iter().any(|g| matches!(g.kind, EntityKind::Insert(_))) { return out; } - let max = indices.iter().copied().filter(|&i| i <= MAX).max().unwrap_or(0); - let markers = ProxyTables { layers: (0..=max).map(|i| format!("\u{1}{i}")).collect(), ..ProxyTables::default() }; - let marked = proxy_entities(bytes, &markers, Handle(0)); + let mark = |i: &u32| (*i, format!("\u{1}{i}")); + let marks = Marks { + layers: layers.iter().map(mark).collect(), + linetypes: linetypes.iter().filter(|&&i| i != LINETYPE_BYBLOCK && i != LINETYPE_BYLAYER).map(mark).collect(), + }; + let marked = decode(bytes, &ProxyTables::default(), Handle(0), Some(&marks)); if marked.len() != self.graphics.len() { return out; } let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b); - let mut seen: std::collections::HashMap = std::collections::HashMap::new(); - let mut conflict = std::collections::HashSet::new(); + let index = |name: &str| name.strip_prefix('\u{1}').and_then(|i| i.parse::().ok()); + let mut seen: HashMap = HashMap::new(); + let mut conflict = HashSet::new(); + let mut linetype_conflict = HashSet::new(); let mut before: Option<(&str, &str)> = None; for (m, g) in marked.iter().zip(&self.graphics) { + if let Some(i) = index(&m.common.linetype) { + match out.linetypes.get(&i) { + Some(a) if !same(a, &g.common.linetype) => { + linetype_conflict.insert(i); + } + Some(_) => {} + None => { + out.linetypes.insert(i, g.common.linetype.clone()); + } + } + } let (mark, real) = (m.common.layer.as_str(), g.common.layer.as_str()); let changed_here = before.is_none_or(|(prev_mark, _)| prev_mark != mark); let kept = before.is_some_and(|(_, prev_real)| same(prev_real, real)); before = Some((mark, real)); - let Some(i) = mark.strip_prefix('\u{1}').and_then(|i| i.parse::().ok()) else { continue }; + let Some(i) = index(mark) else { continue }; if !changed_here { // The same marker on another real layer: an index in between (one past the table // the marker decoding doesn't see as such) changed it, so this one can't be named. @@ -247,10 +321,19 @@ impl Unknown { } } for (i, s) in seen { - if !conflict.contains(&i) { - out.insert(i, if let Seen::Named(n) = s { Some(n) } else { None }); + if conflict.contains(&i) { + continue; } + let name = match s { + Seen::Named(n) => Some(n), + // Staying on the layer before says nothing when the table names that layer here: + // the index sets it again. + Seen::Kept(n) => read.get(i as usize).filter(|r| !r.is_empty() && same(r, &n)).map(|_| n), + Seen::Keeps => None, + }; + out.layers.insert(i, name); } + out.linetypes.retain(|i, _| !linetype_conflict.contains(i)); out } } @@ -261,16 +344,27 @@ impl crate::Drawing { /// it at once. RENAME calls it, LAYMRG for each merged layer (its graphics move to the /// target, as its objects do) and LAYDEL with layer 0. pub fn rename_proxy_layer(&mut self, old: &str, new: &str) { - for n in &mut self.proxy_layers { - if n.eq_ignore_ascii_case(old) { - *n = new.to_string(); - } - } - let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| g.common.layer.eq_ignore_ascii_case(old))); + rename_in(&mut self.proxy_layers, old, new); + self.rename_in_graphics(old, new, TableName::Layer); + } + + /// Rename linetype `old` to `new` where proxy graphics use it, as + /// [`crate::Drawing::rename_proxy_layer`] does for a layer: RENAME calls it. + pub fn rename_proxy_linetype(&mut self, old: &str, new: &str) { + rename_in(&mut self.proxy_linetypes, old, new); + self.rename_in_graphics(old, new, TableName::Linetype); + } + + /// Rename the graphics' `field` from `old` to `new`. + fn rename_in_graphics(&mut self, old: &str, new: &str, field: TableName) { + let uses = |e: &Entity| matches!(&e.kind, EntityKind::Unknown(u) if u.graphics.iter().any(|g| field.of(&g.common).eq_ignore_ascii_case(old))); let fix = |e: &mut Entity| { if let EntityKind::Unknown(u) = &mut e.kind { - for g in u.graphics.iter_mut().filter(|g| g.common.layer.eq_ignore_ascii_case(old)) { - g.common.layer = new.to_string(); + for g in &mut u.graphics { + let n = field.of_mut(&mut g.common); + if n.eq_ignore_ascii_case(old) { + *n = new.to_string(); + } } } }; @@ -290,6 +384,36 @@ impl crate::Drawing { } } +/// The table name of an entity's properties that proxy graphics set by index. +#[derive(Clone, Copy)] +enum TableName { + Layer, + Linetype, +} + +impl TableName { + fn of(self, c: &Common) -> &str { + match self { + TableName::Layer => &c.layer, + TableName::Linetype => &c.linetype, + } + } + + fn of_mut(self, c: &mut Common) -> &mut String { + match self { + TableName::Layer => &mut c.layer, + TableName::Linetype => &mut c.linetype, + } + } +} + +/// Rename `old` to `new` in the table order `names`. +fn rename_in(names: &mut [String], old: &str, new: &str) { + for n in names.iter_mut().filter(|n| n.eq_ignore_ascii_case(old)) { + *n = new.to_string(); + } +} + /// Append the bytes of hex string `s`. False on a character that isn't a hex digit. fn push_hex(out: &mut Vec, s: &str) -> bool { let digits: Vec = s.trim().bytes().collect(); @@ -304,8 +428,14 @@ fn push_hex(out: &mut Vec, s: &str) -> bool { /// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one /// selects the proxy. pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec { + decode(bytes, tables, handle, None) +} + +/// [`proxy_entities`], with the indices in `marks` named by them instead of `tables`. +fn decode(bytes: &[u8], tables: &ProxyTables, handle: Handle, marks: Option<&Marks>) -> Vec { let mut r = Decoder { tables, + marks, handle, pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() }, fill: false, @@ -327,6 +457,8 @@ pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec struct Decoder<'a> { tables: &'a ProxyTables, + /// Names standing for the indices while a record is decoded again (`Unknown::names_by_index`). + marks: Option<&'a Marks>, handle: Handle, /// Layer, colour, linetype and lineweight for the entities that follow. pen: Common, @@ -427,18 +559,26 @@ impl Decoder<'_> { } // ATTRIBUTE_LAYER: index into the layer table; an index past it, or one of a record // without a name, leaves the layer. - 16 => { - if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)).filter(|n| !n.is_empty()) { + LAYER_CHUNK => { + let name = b.u32().and_then(|i| match self.marks { + Some(m) => m.layers.get(&i), + None => self.tables.layers.get(i as usize), + }); + if let Some(name) = name.filter(|n| !n.is_empty()) { self.pen.layer = name.clone(); } } // ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer; // 32766 is ByBlock, 32767 and anything past the table ByLayer. - 18 => { + LINETYPE_CHUNK => { if let Some(i) = b.u32() { + let name = match self.marks { + Some(m) => m.linetypes.get(&i), + None => self.tables.linetypes.get(i as usize), + }; self.pen.linetype = match i { - 32766 => "ByBlock".into(), - _ => self.tables.linetypes.get(i as usize).filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()), + LINETYPE_BYBLOCK => "ByBlock".into(), + _ => name.filter(|n| !n.is_empty()).cloned().unwrap_or_else(|| "ByLayer".into()), }; } } @@ -596,6 +736,15 @@ impl Decoder<'_> { fn arc_between(&mut self, c: Vec3, r: f64, e1: Vec3, e2: Vec3, a0: f64, a1: f64) { let (at, u, v) = self.axes(c, e1, e2); let on = |a: f64| at + u * (r * a.cos()) + v * (r * a.sin()); + // A sweep too short for an arc or an elliptical arc to hold (it would read as a full + // turn): the chord between its ends. + if (a1 - a0).abs() <= cadcraft_geom::EPS { + let (p, q) = (on(a0), on(a1)); + if p != q && p.is_finite() && q.is_finite() { + self.push(EntityKind::Line(Line { a: p.to3(0.0), b: q.to3(0.0) })); + } + return; + } if round(u * r, v * r).is_some() { return self.arc_3p(on(a0), on((a0 + a1) / 2.0), on(a1)); } @@ -730,6 +879,8 @@ impl Decoder<'_> { style, halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, })); } } @@ -767,6 +918,13 @@ fn round(u: Vec2, v: Vec2) -> Option { /// ellipse's own parameter (counter-clockwise from its major axis). fn ellipse(c: Vec2, u: Vec2, v: Vec2, a0: f64, a1: f64) -> Option { use std::f64::consts::{FRAC_PI_2, TAU}; + // Conjugate radii on one line (a plane seen edge-on, also through an exact quarter turn, + // whose cosine leaves a tiny minor axis), relative to the longer: no ellipse, the caller + // draws the line it covers. + let longer = u.len().max(v.len()); + if u.cross(v).abs() <= 1e-9 * longer * longer { + return None; + } // c + u·cos a + v·sin a = c + p·cos(a − t) + q·sin(a − t): p and q at right angles. let t = 0.5 * (2.0 * u.dot(v)).atan2(u.len2() - v.len2()); let p = u * t.cos() + v * t.sin(); @@ -1299,6 +1457,155 @@ mod tests { assert!(own.proxy_graphics_bytes().is_empty()); } + /// The layer order `names` with no linetypes. + fn layers(names: &[String]) -> TableOrder<'_> { + TableOrder { layers: names, linetypes: &[] } + } + + /// A record with the graphics `g`: in its proxy data for an ACAD_PROXY_ENTITY, else in its + /// `AcDbEntity` part (a kept dimension naming block `*D1`). + fn record(dxf_type: &str, g: &[u8], graphics: Vec) -> Unknown { + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let hex: String = g.iter().map(|b| format!("{b:02X}")).collect(); + let tags = if dxf_type == "ACAD_PROXY_ENTITY" { + vec![tag(100, "AcDbProxyEntity"), tag(92, &g.len().to_string()), tag(310, &hex)] + } else { + vec![tag(100, "AcDbEntity"), tag(8, "0"), tag(92, &g.len().to_string()), tag(310, &hex), tag(100, "AcDbDimension"), tag(2, "*D1")] + }; + Unknown { dxf_type: dxf_type.into(), tags, graphics } + } + + fn unit_circle() -> Vec { + let mut circle = pt(0.0, 0.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + circle + } + + /// Graphics that stay on the layer before after an index don't hide that the table names the + /// index: with layers 1, then 2 and 99, then 2, then 1 and 99 before four circles (A, B, B, + /// A), the second 2 sets B again, and saving keeps all four where they are. + #[test] + fn an_index_staying_on_the_layer_its_table_names_keeps_it() { + let circle = unit_circle(); + let layer = |i: u32| chunk(16, &i.to_le_bytes()); + let g = graphics(&[ + layer(1), + chunk(2, &circle), + layer(2), + layer(99), + chunk(2, &circle), + layer(2), + chunk(2, &circle), + layer(1), + layer(99), + chunk(2, &circle), + ]); + let read: Vec = ["0", "A", "B"].map(String::from).to_vec(); + let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() }; + let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1))); + let on = |es: &[Entity]| es.iter().map(|e| e.common.layer.clone()).collect::>(); + assert_eq!(on(&u.graphics), ["A", "B", "B", "A"]); + assert!(u.with_proxy_tables(layers(&read), layers(&read)).is_none(), "nothing changes for the same table"); + let written: Vec = ["0", "X", "A", "B"].map(String::from).to_vec(); + let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() }; + let w = ProxyTables { layers: written, ..ProxyTables::default() }; + assert_eq!(on(&proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))), ["A", "B", "B", "A"]); + } + + /// Linetype indices follow the written LTYPE table by name, as layer indices do: a linetype + /// that is gone becomes ByLayer, and ByBlock, ByLayer and an index past the table stay. + #[test] + fn linetype_indices_follow_the_written_table() { + let circle = unit_circle(); + let linetype = |i: u32| chunk(18, &i.to_le_bytes()); + let g = graphics(&[ + linetype(2), + chunk(2, &circle), + linetype(32766), + chunk(2, &circle), + linetype(1), + chunk(2, &circle), + linetype(9), + chunk(2, &circle), + ]); + let read: Vec = ["Continuous", "DASHED", "HIDDEN"].map(String::from).to_vec(); + let tables = ProxyTables { linetypes: read.clone(), ..ProxyTables::default() }; + let u = record("ACAD_PROXY_ENTITY", &g, proxy_entities(&g, &tables, Handle(1))); + let drawn = |es: &[Entity]| es.iter().map(|e| e.common.linetype.clone()).collect::>(); + assert_eq!(drawn(&u.graphics), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]); + let saved = |written: &[String]| { + let tags = u.with_proxy_tables(TableOrder { layers: &[], linetypes: &read }, TableOrder { layers: &[], linetypes: written }); + let again = Unknown { tags: tags.unwrap_or_else(|| u.tags.clone()), ..u.clone() }; + drawn(&proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { linetypes: written.to_vec(), ..ProxyTables::default() }, Handle(1))) + }; + let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(saved(&read), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]); + assert_eq!(saved(&names(&["Continuous", "CENTER", "DASHED", "HIDDEN"])), ["HIDDEN", "ByBlock", "DASHED", "ByLayer"]); + assert_eq!(saved(&names(&["Continuous", "HIDDEN"])), ["HIDDEN", "ByBlock", "ByLayer", "ByLayer"]); + } + + /// A kept dimension's picture (#3438) follows the written LAYER table too: by its decoded + /// graphics when it draws them, by the file's table when it draws its block instead. + #[test] + fn a_kept_dimensions_picture_follows_the_written_table() { + let circle = unit_circle(); + let g = graphics(&[chunk(16, &2u32.to_le_bytes()), chunk(2, &circle)]); + let read: Vec = ["0", "UNUSED", "A"].map(String::from).to_vec(); + let written: Vec = ["0", "A", "Defpoints"].map(String::from).to_vec(); + let tables = ProxyTables { layers: read.clone(), ..ProxyTables::default() }; + let w = ProxyTables { layers: written.clone(), ..ProxyTables::default() }; + for graphics in [proxy_entities(&g, &tables, Handle(1)), vec![block_ref()]] { + let u = record("LARGE_RADIAL_DIMENSION", &g, graphics); + let again = Unknown { tags: u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"), ..u.clone() }; + assert_eq!(proxy_entities(&again.proxy_graphics_bytes(), &w, Handle(1))[0].common.layer, "A"); + } + // A reference to the block on another layer isn't taken for the picture (one entity as + // well): the file's table names index 2. + let elsewhere = Entity { common: Common { layer: "Defpoints".into(), ..Common::default() }, ..block_ref() }; + let u = record("LARGE_RADIAL_DIMENSION", &g, vec![elsewhere]); + assert!(u.names_by_index(&g, &[2], &[], &read).layers.is_empty()); + } + + fn block_ref() -> Entity { + Entity { + handle: Handle(1), + common: Common::default(), + kind: EntityKind::Insert(super::super::Insert { block: "*D1".into(), ..super::super::Insert::default() }), + } + } + + /// An exact quarter turn about Y shows a circle edge-on: it draws as the line it covers, not + /// as an ellipse with the minor axis the turn's cosine leaves. An arc too short for its sweep + /// to be held draws as its chord, not as a full turn, round or under an uneven matrix. + #[test] + fn quarter_turns_and_tiny_sweeps_draw_lines() { + let matrix = |m: [f64; 16]| chunk(29, &m.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let (s, c) = std::f64::consts::FRAC_PI_2.sin_cos(); + let turn = matrix([c, 0.0, s, 0.0, 0.0, 1.0, 0.0, 0.0, -s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0]); + let line = |es: &[Entity]| match es { + [e] => match &e.kind { + EntityKind::Line(l) => (l.a.xy(), l.b.xy()), + other => panic!("{other:?}"), + }, + _ => panic!("{es:?}"), + }; + let near = |p: Vec2, x: f64, y: f64| (p - Vec2::new(x, y)).len() < 1e-12; + let (a, b) = line(&proxy_entities(&graphics(&[turn, chunk(2, &unit_circle())]), &tables(), Handle(1))); + assert!(near(a, 0.0, -1.0) && near(b, 0.0, 1.0), "{a:?} {b:?}"); + let sweep = 5e-10f64; + let mut tiny = pt(0.0, 0.0); + tiny.extend(1.0f64.to_le_bytes()); + tiny.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + tiny.extend(pt(1.0, 0.0)); + tiny.extend(sweep.to_le_bytes()); + let stretch = matrix([2.0, 0.0, 0.0, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + for (chunks, x) in [(vec![chunk(4, &tiny)], 1.0), (vec![stretch, chunk(4, &tiny)], 12.0)] { + let (a, b) = line(&proxy_entities(&graphics(&chunks), &tables(), Handle(1))); + assert!(near(a, x, 0.0) && (b - Vec2::new(x, sweep)).len() < 1e-15, "{a:?} {b:?}"); + } + } + /// Saving renames the layer indices by name into the written table, reading only the 310 /// groups the declared size needs: a damaged group after them doesn't stop it. #[test] @@ -1318,7 +1625,7 @@ mod tests { }; assert_eq!(u.graphics[0].common.layer, "B"); let written: Vec = ["0", "B", "C"].map(String::from).to_vec(); - let tags = u.with_proxy_layers(&read, &written).expect("remapped"); + let tags = u.with_proxy_tables(layers(&read), layers(&written)).expect("remapped"); let again = Unknown { tags, ..u.clone() }; assert_eq!( proxy_entities(&again.proxy_graphics_bytes(), &ProxyTables { layers: written, ..ProxyTables::default() }, Handle(1))[0].common.layer, @@ -1328,8 +1635,8 @@ mod tests { } /// An index whose graphics stay on the layer before (99 here, past the table) doesn't make - /// the index before it (3) look contradictory when that one comes again; an index above - /// 65,535 isn't named (it resolves through the file's table), and the others still are. + /// the index before it (3) look contradictory when that one comes again, and a large index + /// is found like any other. #[test] fn indices_are_named_around_kept_layers_and_huge_indices() { let mut circle = pt(0.0, 0.0); @@ -1345,12 +1652,13 @@ mod tests { } let g = graphics(&chunks); let u = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: proxy_entities(&g, &tables, Handle(1)) }; - let mut learned: Vec<(u32, Option)> = u.layers_by_index(&g, indices).into_iter().collect(); + let mut learned: Vec<(u32, Option)> = u.names_by_index(&g, indices, &[], &tables.layers).layers.into_iter().collect(); learned.sort(); learned }; assert_eq!(named(&[0, 3, 99, 3]), [(0, Some("0".into())), (3, Some("B".into())), (99, None)]); - assert_eq!(named(&[2, 70_000]), [(2, Some("C".into()))]); + // Only the indices used get a marker: 70,000 keeps the layer before, as past the table. + assert_eq!(named(&[2, 70_000]), [(2, Some("C".into())), (70_000, None)]); // Layer 4 (past the table, so it keeps layer 0), a circle, then layers 1 and 4 at once (4 // keeps A): both circles follow index 4 in the marker decoding, on different layers. let g = graphics(&[ @@ -1368,9 +1676,9 @@ mod tests { graphics: proxy_entities(&g, &tables, Handle(1)), }; assert_eq!(u.graphics.iter().map(|e| e.common.layer.as_str()).collect::>(), ["0", "A"]); - assert!(!u.layers_by_index(&g, &[4, 1, 4]).contains_key(&4), "index 4 isn't named"); + assert!(!u.names_by_index(&g, &[4, 1, 4], &[], &tables.layers).layers.contains_key(&4), "index 4 isn't named"); // Saved with the same table, nothing changes, so both circles stay where they are. - assert!(u.with_proxy_layers(&tables.layers, &tables.layers).is_none()); + assert!(u.with_proxy_tables(layers(&tables.layers), layers(&tables.layers)).is_none()); } /// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and diff --git a/crates/doc/src/entity/text.rs b/crates/doc/src/entity/text.rs index 75857eb30..bf2ac77d3 100644 --- a/crates/doc/src/entity/text.rs +++ b/crates/doc/src/entity/text.rs @@ -42,6 +42,13 @@ pub struct Text { pub halign: HAlign, #[serde(default)] pub valign: VAlign, + /// Mirrored left to right (AutoCAD's Backwards; DXF 71 bit 2). New text takes it from its + /// style; later style changes don't change it. + #[serde(default)] + pub backwards: bool, + /// Mirrored top to bottom (AutoCAD's Upside down; DXF 71 bit 4). + #[serde(default)] + pub upside_down: bool, } impl Text { @@ -83,6 +90,27 @@ pub struct MText { /// one column. #[serde(default, skip_serializing_if = "Option::is_none")] pub columns: Option, + /// Background mask (DXF 90/63/421/45); `None` when off. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, +} + +/// MTEXT background mask (DXF 90, 63/421, 45). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MTextBackground { + /// DXF group 90 bitmask: bit 1 = fill colour set, bit 2 = use drawing background colour. + pub mask: u8, + /// DXF group 63 (ACI) or 421 (true colour); `None` when using drawing background. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + /// DXF group 45 border offset factor (default 1.5, valid 1.0..=5.0). + #[serde(default = "default_bg_scale")] + pub scale: f64, +} + +fn default_bg_scale() -> f64 { + 1.5 } fn attach_tl() -> u8 { diff --git a/crates/doc/src/entity/xdata.rs b/crates/doc/src/entity/xdata.rs new file mode 100644 index 000000000..9f830801f --- /dev/null +++ b/crates/doc/src/entity/xdata.rs @@ -0,0 +1,293 @@ +//! Extended entity data (xdata): the groups 1000–1071 other applications attach to an entity, +//! kept raw in [`Common::xdata`](super::Common::xdata) as whole applications, each from its +//! `1001` group on. This module reads them per application, replaces or removes one +//! application's data, and checks data that comes from outside (a command's parameters, a LISP +//! list) before it goes onto an entity: input is hostile, so codes, values, brace nesting and +//! sizes are all checked and nothing here panics. + +use super::RawTag; + +/// Most xdata groups one object may carry (AutoCAD allows 16 KB of xdata per object). +pub const MAX_XDATA_GROUPS: usize = 16_384; +/// Longest application name, in bytes. +pub const MAX_XDATA_APP_NAME: usize = 255; +/// Longest string value (groups 1000 and 1003), in bytes: what one DXF group holds. +pub const MAX_XDATA_STRING: usize = 255; +/// Longest binary chunk (group 1004), in bytes. +pub const MAX_XDATA_CHUNK: usize = 127; + +/// Applications whose xdata CADCraft writes itself, from its own model, when a drawing is saved. +/// It is never kept as an entity's raw xdata (the reader models it) and can't be set as such: +/// a copy written beside the generated data would contradict it. +pub const RESERVED_XDATA_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; + +/// Whether `name` (any case) is one of [`RESERVED_XDATA_APPS`]. +pub fn is_reserved_xdata_app(name: &str) -> bool { + let up = name.trim().to_ascii_uppercase(); + RESERVED_XDATA_APPS.contains(&up.as_str()) +} + +/// Whether application `name`'s xdata on an entity of `kind` is written from the model rather +/// than kept raw: the [`RESERVED_XDATA_APPS`] on any entity, and `ACAD` on a dimension, whose +/// `ACAD` run (`DSTYLE`) holds its dimension-style overrides. The reader models those too, so +/// raw groups set under such a name would be dropped on save; they are refused instead. +pub fn is_model_xdata_app(name: &str, kind: &super::EntityKind) -> bool { + is_reserved_xdata_app(name) || (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Dimension(_))) +} + +/// Why an application name or a run of xdata groups was refused. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct XdataError(pub String); + +impl std::fmt::Display for XdataError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for XdataError {} + +fn err(msg: impl Into) -> Result { + Err(XdataError(msg.into())) +} + +/// Check an application name: not empty, at most [`MAX_XDATA_APP_NAME`] bytes, no control +/// characters and none of the characters a symbol table name can't hold. +pub fn check_xdata_app_name(name: &str) -> Result<(), XdataError> { + let name = name.trim(); + if name.is_empty() { + return err("an xdata application name must not be empty"); + } + if name.len() > MAX_XDATA_APP_NAME { + return err(format!("an xdata application name may have at most {MAX_XDATA_APP_NAME} bytes")); + } + if name.chars().any(|c| c.is_control() || "<>/\\\":;?*|,=`".contains(c)) { + return err(format!("`{name}` is not a valid xdata application name (no control characters or <>/\\\":;?*|,=`)")); + } + Ok(()) +} + +/// Whether `code` is an xdata group code an application's data may hold (`1001`, the +/// application name, is not one of them: it starts an application). +pub fn is_xdata_group(code: i32) -> bool { + matches!(code, 1000 | 1002..=1005 | 1010..=1013 | 1020..=1023 | 1030..=1033 | 1040..=1042 | 1070 | 1071) +} + +/// Check the groups of one application (after its `1001`): every code an xdata code with a +/// value of its kind, control strings `{` and `}` balanced, points complete (a `101x` group +/// followed by its `102x` and `103x`), at most [`MAX_XDATA_GROUPS`] groups. +pub fn check_xdata_groups(groups: &[RawTag]) -> Result<(), XdataError> { + if groups.len() > MAX_XDATA_GROUPS { + return err(format!("at most {MAX_XDATA_GROUPS} xdata groups per application")); + } + let mut depth: u32 = 0; + let mut i = 0; + while let Some(t) = groups.get(i) { + let v = t.value.trim(); + match t.code { + 1000 | 1003 => { + if t.value.len() > MAX_XDATA_STRING { + return err(format!("group {}: a string may have at most {MAX_XDATA_STRING} bytes", t.code)); + } + if t.value.chars().any(|c| c == '\n' || c == '\r') { + return err(format!("group {}: a string may not hold a line break", t.code)); + } + } + 1002 => match v { + "{" => depth = depth.saturating_add(1), + "}" => match depth.checked_sub(1) { + Some(d) => depth = d, + None => return err("group 1002: a `}` without its `{`"), + }, + _ => return err("group 1002 must be `{` or `}`"), + }, + 1004 => { + if v.len() > MAX_XDATA_CHUNK * 2 || v.len() % 2 != 0 || !v.bytes().all(|b| b.is_ascii_hexdigit()) { + return err(format!("group 1004 must be hex text of an even length, at most {MAX_XDATA_CHUNK} bytes")); + } + } + 1005 => { + if v.is_empty() || v.len() > 16 || !v.bytes().all(|b| b.is_ascii_hexdigit()) { + return err("group 1005 must be a hex handle"); + } + } + 1010..=1013 => { + let (y, z) = (groups.get(i + 1), groups.get(i + 2)); + let complete = y.is_some_and(|y| y.code == t.code + 10) && z.is_some_and(|z| z.code == t.code + 20); + if !complete { + return err(format!("group {}: a point needs its {} and {} groups", t.code, t.code + 10, t.code + 20)); + } + for p in [Some(t), y, z].into_iter().flatten() { + real(p)?; + } + i += 3; + continue; + } + 1020..=1023 | 1030..=1033 => return err(format!("group {} may only follow its {} group", t.code, t.code - (t.code - 1010) / 10 * 10)), + 1040..=1042 => { + real(t)?; + } + 1070 => { + let ok = v.parse::().is_ok_and(|n| i16::try_from(n).is_ok()); + if !ok { + return err("group 1070 must be a 16-bit integer"); + } + } + 1071 => { + let ok = v.parse::().is_ok_and(|n| i32::try_from(n).is_ok()); + if !ok { + return err("group 1071 must be a 32-bit integer"); + } + } + 1001 => return err("group 1001 (an application name) can't be inside an application's data"), + c => return err(format!("group {c} is not an xdata group code (1000–1071)")), + } + i += 1; + } + if depth != 0 { + return err("group 1002: a `{` without its `}`"); + } + Ok(()) +} + +fn real(t: &RawTag) -> Result { + match t.value.trim().parse::() { + Ok(v) if v.is_finite() => Ok(v), + _ => err(format!("group {} must be a finite number", t.code)), + } +} + +/// The applications of an xdata run, in order: each name as written and its groups after the +/// `1001`. Groups before the first `1001` belong to nobody and are left out. +pub fn xdata_apps(xdata: &[RawTag]) -> Vec<(&str, &[RawTag])> { + let mut out = Vec::new(); + let mut start: Option<(usize, &str)> = None; + for (i, t) in xdata.iter().enumerate() { + if t.code != 1001 { + continue; + } + if let Some((s, name)) = start.take() { + out.push((name, xdata.get(s + 1..i).unwrap_or(&[]))); + } + start = Some((i, t.value.trim())); + } + if let Some((s, name)) = start { + out.push((name, xdata.get(s + 1..).unwrap_or(&[]))); + } + out +} + +/// The groups of application `app` (any case): those of its first run. +pub fn xdata_of<'a>(xdata: &'a [RawTag], app: &str) -> Option<&'a [RawTag]> { + xdata_apps(xdata).into_iter().find(|(name, _)| name.eq_ignore_ascii_case(app.trim())).map(|(_, g)| g) +} + +/// Replace the xdata of application `app` (any case) with `groups`, or remove it (`None`, or no +/// groups). Every run of that application goes; new data is appended after the other +/// applications' data, with its `1001` group. The groups are taken as given: check them with +/// [`check_xdata_groups`] first when they come from outside. +pub fn set_xdata_app(xdata: &mut Vec, app: &str, groups: Option<&[RawTag]>) { + let app = app.trim(); + let mut kept: Vec = Vec::with_capacity(xdata.len()); + let mut skipping = false; + for t in xdata.drain(..) { + if t.code == 1001 { + skipping = t.value.trim().eq_ignore_ascii_case(app); + } + if !skipping { + kept.push(t); + } + } + if let Some(groups) = groups.filter(|g| !g.is_empty()) { + kept.push(RawTag { code: 1001, value: app.to_string() }); + kept.extend(groups.iter().cloned()); + } + *xdata = kept; +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn t(code: i32, value: &str) -> RawTag { + RawTag { code, value: value.into() } + } + + #[test] + fn apps_are_split_at_their_names() { + let x = vec![t(1001, "A"), t(1000, "one"), t(1070, "1"), t(1001, "b"), t(1000, "two")]; + let apps = xdata_apps(&x); + assert_eq!(apps.len(), 2); + assert_eq!(apps[0].0, "A"); + assert_eq!(apps[0].1.len(), 2); + assert_eq!(apps[1], ("b", &x[4..])); + assert_eq!(xdata_of(&x, "B"), Some(&x[4..])); + assert_eq!(xdata_of(&x, "c"), None); + assert!(xdata_apps(&[t(1000, "stray")]).is_empty()); + } + + #[test] + fn set_replaces_removes_and_appends() { + let mut x = vec![t(1001, "A"), t(1000, "one"), t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1000, "dup")]; + set_xdata_app(&mut x, "a", Some(&[t(1070, "7")])); + assert_eq!(x, vec![t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1070, "7")]); + set_xdata_app(&mut x, "B", None); + assert_eq!(x, vec![t(1001, "a"), t(1070, "7")]); + set_xdata_app(&mut x, "C", Some(&[])); + assert_eq!(x.len(), 2); + set_xdata_app(&mut x, "A", None); + assert!(x.is_empty()); + } + + #[test] + fn checks_accept_every_kind_and_refuse_bad_data() { + let good = vec![ + t(1000, "text"), + t(1002, "{"), + t(1003, "Layer"), + t(1004, "DEADBEEF"), + t(1005, "1A2"), + t(1010, "1.5"), + t(1020, "2"), + t(1030, "0"), + t(1040, "2.5"), + t(1041, "1e3"), + t(1042, "-1"), + t(1070, "32767"), + t(1071, "2147483647"), + t(1002, "}"), + ]; + assert_eq!(check_xdata_groups(&good), Ok(())); + for bad in [ + vec![t(1002, "}")], + vec![t(1002, "{")], + vec![t(1002, "x")], + vec![t(1001, "APP")], + vec![t(999, "comment")], + vec![t(8, "layer")], + vec![t(1010, "1"), t(1020, "2")], + vec![t(1020, "2")], + vec![t(1010, "nan"), t(1020, "2"), t(1030, "3")], + vec![t(1040, "inf")], + vec![t(1040, "x")], + vec![t(1070, "40000")], + vec![t(1071, "3000000000")], + vec![t(1004, "ABC")], + vec![t(1004, "XY")], + vec![t(1005, "")], + vec![t(1005, "zz")], + vec![t(1000, &"x".repeat(256))], + vec![t(1000, "a\nb")], + vec![t(1000, "x"); MAX_XDATA_GROUPS + 1], + ] { + assert!(check_xdata_groups(&bad).is_err(), "{:?}", bad.first()); + } + assert_eq!(check_xdata_app_name("PE_URL"), Ok(())); + assert_eq!(check_xdata_app_name("My App-1.0$"), Ok(())); + for bad in ["", " ", "a*b", "a\tb", "x/y", &"n".repeat(256)] { + assert!(check_xdata_app_name(bad).is_err(), "{bad:?}"); + } + assert!(is_reserved_xdata_app("cadcraft") && !is_reserved_xdata_app("ACAD")); + } +} diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index ad4cdbde7..67ca89028 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -242,27 +242,126 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool { m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t } -/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification -/// the same way the renderer places it (the stroke font is about 0.88 of the height per character). +/// How many characters a single-line text value draws, as the fonts read it: a `%%` code is the +/// one character it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (the underline and +/// overline toggles `%%u` and `%%o`), `\U+XXXX` is one character, and invisible formatting +/// characters (joiners, directional marks) take no room. +fn drawn_chars(value: &str) -> usize { + let invisible = |c: char| matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}' | '\u{061C}'); + let chars: Vec = value.chars().collect(); + let (mut i, mut drawn) = (0usize, 0usize); + while let Some(&c) = chars.get(i) { + let escaped = (c == '\\' && matches!(chars.get(i + 1), Some('U' | 'u')) && chars.get(i + 2) == Some(&'+')) + .then(|| chars.get(i + 3..i + 7)) + .flatten() + .filter(|hex| hex.iter().all(char::is_ascii_hexdigit)) + .and_then(|hex| u32::from_str_radix(&hex.iter().collect::(), 16).ok()) + .and_then(char::from_u32); + if let Some(u) = escaped { + drawn += usize::from(!invisible(u)); + i += 7; + } else if c == '%' && chars.get(i + 1) == Some(&'%') { + match chars.get(i + 2).map_or(' ', char::to_ascii_lowercase) { + 'u' | 'o' => i += 3, + 'd' | 'p' | 'c' | '%' => (drawn, i) = (drawn + 1, i + 3), + digit if digit.is_ascii_digit() => { + let digits = chars.iter().skip(i + 2).take(3).take_while(|d| d.is_ascii_digit()).count(); + (drawn, i) = (drawn + 1, i + 2 + digits); + } + // Not a code: the percent sign is drawn, and the next one is read again. + _ => (drawn, i) = (drawn + 1, i + 1), + } + } else { + drawn += usize::from(!invisible(c)); + i += 1; + } + } + drawn +} + +/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` drawn characters, following its +/// justification the same way the renderer places it (the stroke font is about 0.88 of the height +/// per character). Empty when nothing is drawn. fn text_box(t: &crate::Text, len: usize) -> Bounds2 { use crate::{HAlign, VAlign}; - let w = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64; + if len == 0 { + return Bounds2::EMPTY; + } + let natural = t.height * 0.9 * t.width_factor.abs().max(0.01) * len as f64; // Justified text (TL, ML and BL too) hangs from its alignment point (DXF group 11). let origin = t.justify_point(); + // Aligned and Fit text span their two points (groups 10 and 11) whatever rotation is stored: + // the line runs from the first to the second, Fit at its own height with its width stretched, + // Aligned at the height that keeps its proportions. With no second point, or one on the + // first, they are placed like left-justified text, as the renderer places them. + let second = t.align_pt.map(|p| p.xy()).filter(|_| matches!(t.halign, HAlign::Aligned | HAlign::Fit)); + let span = second.map(|p| origin.dist(p)).filter(|d| d.is_finite() && *d > 1e-12); + // The fonts shape with the width factor as it is, not floored like the fallback width above, + // with 1 when it is unusable, and with a height of 1 when the height is. + let usable = t.width_factor.is_finite() && t.width_factor.abs() > 1e-6; + let wf = if usable { t.width_factor.abs() } else { 1.0 }; + let height = if t.height.is_finite() && t.height > 0.0 { t.height } else { 1.0 }; + let shaped = height * 0.9 * wf * len as f64; + // Fit text is stretched by scaling its width factor by span / shaped width and shaping again. + // When the scaled factor is one the fonts cannot use (the stored one is, or the span is a tiny + // part of the text's width), the text is not stretched: it is drawn at a factor of 1. + // The shaped width here is an estimate, and the fonts decide by their own: it is taken to be + // within this factor of the estimate. Where the fonts decide by a cutoff, the box is the larger + // of the two outcomes unless the estimate is clear of the cutoff by this factor. + const MARGIN: f64 = 4.0; + let fits = |d: f64| { + let fitted = wf * d / shaped; + usable && fitted.is_finite() && fitted > 1e-6 * MARGIN + }; + let unstretched = height * 0.9 * len as f64; + // The fonts leave a line of next to no width as it is, neither stretched nor scaled: the same + // cutoff as theirs, with no margin, since a box scaled for text that is left alone is + // enormous. + let no_width = shaped <= 1e-12; + // Aligned text is scaled by span / shaped width, so the narrower the line, the taller it is + // drawn. The least width the stroke font gives a line: its narrowest characters are 1 unit + // wide on a cap height of 6, with 1.6 units between characters. The height from that width + // holds whatever the line is made of, also shrunk into a span shorter than its width. + let narrowest = height * wf * (2.6 * len as f64 - 1.6) / 6.0; + // The most width it gives one (its widest characters are 4 units wide), for the least height + // the line can be drawn at. + let widest = height * wf * (5.6 * len as f64 - 1.6) / 6.0; + // Width, the most and the least height the line is drawn at, and its direction. + let (w, h, low, rotation) = match (span, second) { + (Some(_), Some(p)) if no_width => (shaped, height, height, origin.angle_to(p)), + // Unstretched is the larger outcome: a span this near the cutoff is far shorter than the text. + (Some(d), Some(p)) if t.halign == HAlign::Fit && !fits(d) => (unstretched, height, height, origin.angle_to(p)), + (Some(d), Some(p)) if t.halign == HAlign::Fit => (d, height, height, origin.angle_to(p)), + (Some(d), Some(p)) => (d, height * d / narrowest, height * d / widest, origin.angle_to(p)), + _ => (natural, t.height, t.height, t.rotation), + }; let dx = match t.halign { HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0, HAlign::Center | HAlign::Middle => -w / 2.0, HAlign::Right => -w, }; - let dy = match (t.halign, t.valign) { - (HAlign::Middle, _) => -t.height / 2.0, - (_, VAlign::Baseline) => 0.0, - (_, VAlign::Bottom) => t.height / 3.0, - (_, VAlign::Middle) => -t.height / 2.0, - (_, VAlign::Top) => -t.height, + // The box from its bottom to its top. Bottom justification lifts the line by a third of the + // height it is drawn at: the box starts where the shortest line would and ends where the + // tallest would. + let (y0, y1) = match (t.halign, t.valign) { + (HAlign::Middle, _) | (_, VAlign::Middle) => (-h / 2.0, h / 2.0), + (_, VAlign::Baseline) => (0.0, h), + (_, VAlign::Bottom) => (low / 3.0, h / 3.0 + h), + (_, VAlign::Top) => (-h, 0.0), }; - let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + t.height), Vec2::new(dx, dy + t.height)]; - Bounds2::from_points(local.map(|p| origin + p.rotate(t.rotation))) + let local = [Vec2::new(dx, y0), Vec2::new(dx + w, y0), Vec2::new(dx + w, y1), Vec2::new(dx, y1)]; + // Backwards and upside-down text is mirrored about the point it is placed by. + let (mx, my) = (if t.backwards { -1.0 } else { 1.0 }, if t.upside_down { -1.0 } else { 1.0 }); + Bounds2::from_points(local.map(|p| origin + Vec2::new(p.x * mx, p.y * my).rotate(rotation))) +} + +/// Whether `e` is a point on the layer Defpoints (the name in any case), as the block of a +/// dimension holds the dimension's definition points. The reference app selects a dimension and a +/// block reference by such a point of its block whatever a viewport freezes, the layer Defpoints +/// too, where a line on that layer follows the viewport. So a selection through a viewport counts +/// such a part of a block ([`ViewportBounds`]); the viewport itself does not draw it. +pub fn point_on_defpoints(e: &Entity) -> bool { + matches!(e.kind, EntityKind::Point(_)) && e.common.layer.eq_ignore_ascii_case("Defpoints") } /// Whether an entity inside a block definition shows: its own invisible flag and its layer count, @@ -270,16 +369,27 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 { /// entities a visibility state hides are invisible this way, and they sit far from the block's /// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked. /// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]). -fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool { +/// `frozen`: the layers frozen in the layout viewport measured through ([`ViewportBounds`]); a +/// point on the layer Defpoints counts whatever that viewport freezes ([`point_on_defpoints`]). +fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String]) -> bool { + let frozen: &[String] = if point_on_defpoints(e) { &[] } else { frozen }; // Attribute definitions are not drawn in an insert (its attribs are, see below), except // constant ones, which the insert's bounds add on their own. - !matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts) + !matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts, frozen) } /// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which /// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`. -fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool { - layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) +/// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through, +/// which does not draw them (the names compared as the renderer compares them). +fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool { + layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen_in(frozen, layer)) +} + +/// Whether `layer` is one of the layers in `frozen`, those frozen in a layout viewport (the names +/// compared as the renderer compares them). +fn frozen_in(frozen: &[String], layer: &str) -> bool { + frozen.iter().any(|f| f.eq_ignore_ascii_case(layer)) } /// The layer an insert's attribute draws on, as the renderer takes it: its own, else its @@ -313,13 +423,18 @@ impl Contents<'_> { } } -/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`. +/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`: the parts that +/// count there ([`in_block_visible`], and a constant value by its layer as [`layer_counts`] says), +/// so those on a layer in `frozen` are left out ([`bounds_in`] says what the maps hold and why the +/// depth is part of the key). fn contents<'a, 'm>( d: &'a Drawing, blk: &'a crate::Block, depth: usize, blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>, + in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>, off_counts: bool, + frozen: &[String], ) -> Option<&'m Contents<'a>> { let key = (blk.name.as_str(), depth); if !blocks.contains_key(&key) { @@ -334,11 +449,13 @@ fn contents<'a, 'm>( && attmode != 0 && (!a.invisible || attmode == 2) && be.common.visible - && layer_counts(d, &be.common.layer, off_counts) => + && layer_counts(d, &be.common.layer, off_counts, frozen) => { c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation()))); } - _ if in_block_visible(d, be, off_counts) => c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, off_counts)), + _ if in_block_visible(d, be, off_counts, frozen) => { + c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, in_drawing, off_counts, frozen)); + } _ => {} } } @@ -347,13 +464,27 @@ fn contents<'a, 'm>( blocks.get(&key) } +/// [`Contents`] of the block `blk`, referenced at `depth`, as the drawing shows them: no viewport's +/// frozen layers are left out. For a clipped reference measured through a viewport ([`bounds_in`]). +/// `in_drawing` keeps them, apart from that viewport's own block bounds. +fn drawing_contents<'a, 'm>( + d: &'a Drawing, + blk: &'a crate::Block, + depth: usize, + off_counts: bool, + in_drawing: &'m mut HashMap<(&'a str, usize), Contents<'a>>, +) -> Option<&'m Contents<'a>> { + // With no layer left out, the measure never asks for the drawing's boxes itself. + contents(d, blk, depth, in_drawing, &mut HashMap::new(), off_counts, &[]) +} + /// The box of a constant attribute definition's value, as a block reference draws it: upright /// when the definition matches the layout's orientation, like other text (#2498). fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 { let turn = |r: f64| if upright { 0.0 } else { r }; match a.multiline_text() { Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }), - None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, a.text.value.chars().count()), + None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_chars(&a.text.value)), _ => Bounds2::EMPTY, } } @@ -394,13 +525,13 @@ fn mtext_box(t: &crate::MText) -> Bounds2 { /// The box of what `e` draws (block contents on layers turned off left out). pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 { - bounds_of(d, e, depth, false, &mut HashMap::new()) + bounds_of(d, e, depth, false, &[], &mut HashMap::new(), &mut HashMap::new()) } /// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer /// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not). pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 { - bounds_of(d, e, 0, true, &mut HashMap::new()) + bounds_of(d, e, 0, true, &[], &mut HashMap::new(), &mut HashMap::new()) } /// The bounds of block contents measured so far, kept across the entities of one unchanged @@ -418,35 +549,95 @@ pub struct BlockBoundsCache<'a> { /// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { - bounds_of(d, e, depth, false, &mut cache.drawn) + bounds_of(d, e, depth, false, &[], &mut cache.drawn, &mut HashMap::new()) } /// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { - bounds_of(d, e, 0, true, &mut cache.extents) + bounds_of(d, e, 0, true, &[], &mut cache.extents, &mut HashMap::new()) } -fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>) -> Bounds2 { +/// The boxes of what one layout viewport draws: [`entity_bounds`] with the block contents on the +/// layers frozen in that viewport left out, as the viewport leaves them out when it draws. It +/// keeps the block bounds it has measured, as a [`BlockBoundsCache`] does, so use one only while +/// the drawing it measured is unchanged. The layers belong to it, so the bounds measured through +/// one viewport never answer for another. Two things a selection counts whatever the viewport +/// draws stay in: a clipped reference (XCLIP) is selected by its boundary, so it keeps the box the +/// drawing gives it, and a dimension by its definition points, which its block holds as points on +/// the layer Defpoints, so such a point counts in any block ([`point_on_defpoints`]). +pub struct ViewportBounds<'a> { + /// The layers frozen in the viewport. + frozen: &'a [String], + /// By block name and depth, the box of the block contents the viewport draws. + blocks: HashMap<(&'a str, usize), Contents<'a>>, + /// The same with no layer of the viewport left out: the box the drawing gives the contents, + /// which a clipped reference keeps. + in_drawing: HashMap<(&'a str, usize), Contents<'a>>, +} + +impl<'a> ViewportBounds<'a> { + /// For a viewport that freezes the layers in `frozen` (none: the drawing as it shows anywhere). + pub fn new(frozen: &'a [String]) -> Self { + ViewportBounds { frozen, blocks: HashMap::new(), in_drawing: HashMap::new() } + } + + /// The layers frozen in the viewport. + pub fn frozen(&self) -> &'a [String] { + self.frozen + } + + /// Whether the viewport leaves `part` out for its layer. `part` is an entity of the block + /// that an object the viewport draws is drawn from (a block reference, a dimension, a + /// multileader), and it is left out when its layer is frozen in the viewport, as in the + /// boxes above. A part on layer 0 never is: it takes the layer of the object, which the + /// caller has checked. What the drawing itself hides (a layer frozen for the whole drawing + /// or turned off) is not looked at here. + pub fn leaves_out(&self, part: &Entity) -> bool { + part.common.layer != "0" && frozen_in(self.frozen, &part.common.layer) + } + + /// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the + /// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check. + pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 { + bounds_of(d, e, 0, false, self.frozen, &mut self.blocks, &mut self.in_drawing) + } +} + +/// The box of `e` at `depth` with the block bounds in `blocks` and `in_drawing`: [`bounds_in`], a +/// top-level annotative object measured as it draws. +fn bounds_of<'a>( + d: &'a Drawing, + e: &Entity, + depth: usize, + off_counts: bool, + frozen: &[String], + blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, + in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>, +) -> Bounds2 { // A top-level annotative object measures as it draws at the current annotation scale. if depth == 0 { match d.anno_draw(e) { crate::AnnoDraw::Plain => {} crate::AnnoDraw::Hidden => return Bounds2::EMPTY, - crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts), + crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen), } } - bounds_in(d, e, depth, blocks, off_counts) + bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen) } /// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw /// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an -/// OLE2FRAME as its frame. +/// OLE2FRAME as its frame. Measured through a viewport, the proxy graphics on a layer `frozen` +/// there are left out as a block's parts are ([`in_block_visible`]), and a reference among them +/// takes its boxes from `blocks` and `in_drawing` as any other does ([`bounds_in`]). fn unknown_bounds<'a>( d: &'a Drawing, u: &crate::Unknown, depth: usize, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, + in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>, off_counts: bool, + frozen: &[String], ) -> Bounds2 { if u.graphics.is_empty() { return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points); @@ -456,8 +647,8 @@ fn unknown_bounds<'a>( } u.graphics .iter() - .filter(|g| in_block_visible(d, g, off_counts)) - .fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts))) + .filter(|g| in_block_visible(d, g, off_counts, frozen)) + .fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, in_drawing, off_counts, frozen))) } /// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed, @@ -465,19 +656,29 @@ fn unknown_bounds<'a>( /// expanding the block again, so nested or self-referencing blocks cost at most one pass over each /// definition per depth instead of one per reference (which grows exponentially with the nesting /// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its -/// bounds must not stand in for a shallower reference to the same block (#706). -fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, off_counts: bool) -> Bounds2 { +/// bounds must not stand in for a shallower reference to the same block (#706). The bounds in +/// `blocks` depend on `off_counts` and on `frozen` (see [`layer_counts`]), so one map goes with +/// one value of each. `in_drawing` is the map that goes with the same `off_counts` and no frozen +/// layer: a measure through a viewport takes from it the box the drawing gives the block of a +/// clipped reference ([`drawing_contents`]). A measure with no frozen layer does not use it. +fn bounds_in<'a>( + d: &'a Drawing, + e: &Entity, + depth: usize, + blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, + in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>, + off_counts: bool, + frozen: &[String], +) -> Bounds2 { match &e.kind { EntityKind::Table(t) if t.is_broken() => t.bounds(), EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY, EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY, // Text that matches the layout's orientation is drawn upright (#2498). - EntityKind::Text(t) if e.common.matches_layout_orientation() => { - text_box(&crate::Text { rotation: 0.0, ..t.clone() }, t.value.chars().count()) - } + EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_chars(&t.value)), EntityKind::MText(t) if e.common.matches_layout_orientation() => mtext_box(&crate::MText { rotation: 0.0, ..t.clone() }), - EntityKind::Text(t) => text_box(t, t.value.chars().count()), - EntityKind::AttDef(a) => text_box(&a.text, a.tag.chars().count()), + EntityKind::Text(t) => text_box(t, drawn_chars(&t.value)), + EntityKind::AttDef(a) => text_box(&a.text, drawn_chars(&a.tag)), EntityKind::MText(t) => mtext_box(t), EntityKind::Insert(ins) => { if depth >= MAX_BLOCK_DEPTH { @@ -490,9 +691,18 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< 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); + let c = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen); defs = c.map(|c| &c.defs); - let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins)); + let mut inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins)); + // XCLIP: the reference app selects a clipped reference by its boundary whatever a + // viewport draws inside it, so a clipped reference keeps the box the drawing gives it. + // One that is not inverted and has a part drawn gets the boundary's box below as it is. + if !frozen.is_empty() + && let Some(c) = ins.clip.as_ref().filter(|c| c.active()) + && (c.inverted || inner.is_empty()) + { + inner = drawing_contents(d, blk, depth, off_counts, in_drawing).map_or(Bounds2::EMPTY, |c| c.in_reference(ins)); + } 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,10 +724,10 @@ 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(defs, a), off_counts, frozen) { b = b.union(&match a.multiline_text() { Some(m) => mtext_box(&m), - None => text_box(&a.text, a.text.value.chars().count()), + None => text_box(&a.text, drawn_chars(&a.text.value)), }); } } @@ -551,7 +761,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< // Reuse the shared block-bounds cache (as the Insert branch does) so a dimension // block with branching or self-referencing children costs one pass per definition // per depth, not one per reference (which grows exponentially) (CWE-400). - let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.geometry); + let inner = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen).map_or(Bounds2::EMPTY, |c| c.geometry); // The block draws translated by the insertion point (group 12), so its bounds // move with it (#2634); the cache above keeps the block's own bounds. let off = dm.insertion_point.xy(); @@ -570,7 +780,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } if let Some(ins) = &m.block { let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) }; - b = b.union(&bounds_in(d, &be, depth, blocks, off_counts)); + b = b.union(&bounds_in(d, &be, depth, blocks, in_drawing, off_counts, frozen)); } b } @@ -590,7 +800,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< EntityKind::LwPolyline(p) => lwpolyline_bounds(p), // A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its // frame is, so the frame counts (#2422). - EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts), + EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, in_drawing, off_counts, frozen), kind => { let mut b = Bounds2::EMPTY; for p in kind.prims() { @@ -682,6 +892,8 @@ mod tests { style: "Standard".into(), halign, valign, + backwards: false, + upside_down: false, } } @@ -701,6 +913,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } @@ -720,6 +933,15 @@ mod tests { let b = bounds(EntityKind::MText(mtext("A LONG LINE OF WRAPPING TEXT", 5.0))); assert!((b.max.x - b.min.x - 5.0).abs() < 1e-9, "width {}", b.max.x - b.min.x); } + #[test] + fn mirrored_text_extends_the_other_way() { + let plain = bounds(EntityKind::Text(text(HAlign::Left, VAlign::Baseline))); + assert!(plain.min.x >= -1e-9 && plain.min.y >= -1e-9); + let back = bounds(EntityKind::Text(Text { backwards: true, upside_down: true, ..text(HAlign::Left, VAlign::Baseline) })); + assert!(back.max.x <= 1e-9 && back.max.y <= 1e-9, "{back:?}"); + assert!((back.width() - plain.width()).abs() < 1e-9); + } + #[test] fn right_justified_text_is_left_of_alignment_point() { let b = bounds(EntityKind::Text(text(HAlign::Right, VAlign::Baseline))); @@ -767,6 +989,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let ml = crate::MLeader { leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]], @@ -874,6 +1097,247 @@ mod tests { } } + /// A viewport leaves a part of a block out for its layer when that layer is frozen in the + /// viewport, its name matched whatever its case. A part on layer 0 is never left out, also + /// where the viewport freezes layer 0: it takes the layer of the object drawn from the block. + /// A layer the drawing itself hides (frozen for the whole drawing, or turned off) is not the + /// viewport's to leave out, and a viewport that freezes no layer leaves nothing out. + #[test] + fn a_viewport_leaves_out_the_parts_on_its_frozen_layers() { + let part = |layer: &str| { + let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }); + let mut e = Entity::new(crate::Handle(1), kind); + e.common.layer = layer.into(); + e + }; + let frozen = ["hidden".to_string(), "0".to_string()]; + let (through, plain) = (ViewportBounds::new(&frozen), ViewportBounds::new(&[])); + assert!(through.leaves_out(&part("Hidden")), "a layer frozen in the viewport, its name in another case"); + assert!(!plain.leaves_out(&part("Hidden")), "the same part where no layer is frozen"); + assert!(!through.leaves_out(&part("0")), "layer 0 takes the object's layer"); + assert!(!through.leaves_out(&part("Other")), "a layer the viewport does not freeze"); + } + + /// Through a layout viewport the block contents on a layer frozen in it take no room: a part + /// of a reference, a part two blocks deep, a nested reference that is itself on that layer + /// (with everything in it), an attribute, the parts of the block a dimension or a multileader + /// draws (a reference nested in a dimension's block too), and the parts of an annotative + /// reference. A clipped reference (XCLIP) keeps the box the drawing gives it, whatever is drawn + /// of it. The layer's name is matched whatever its case. With no layer frozen + /// the box is the one [`entity_bounds`] gives, and one [`ViewportBounds`] gives every entity + /// the box a fresh one gives it. + #[test] + fn a_viewport_leaves_out_block_contents_on_the_layers_frozen_in_it() { + let line = |handle: u64, y: f64, layer: &str| { + let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }); + let mut e = Entity::new(crate::Handle(handle), kind); + e.common.layer = layer.into(); + e + }; + let reference = |block: &str| crate::Insert { block: block.into(), ..crate::Insert::default() }; + let ins = |block: &str, layer: &str| { + let mut e = Entity::new(crate::Handle(2), EntityKind::Insert(reference(block))); + e.common.layer = layer.into(); + e + }; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let mut add = |name: &str, parts: Vec| { + let mut b = crate::Block::new(name); + for part in parts { + b.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(b)); + }; + // B: a line on layer 0 along y = 0 and one on "Hidden" along y = 50. N nests B. Z holds a + // reference to B that is itself on "Hidden", and a line along y = 90. H is all on "Hidden". + add("B", vec![line(1, 0.0, "0"), line(3, 50.0, "Hidden")]); + add("N", vec![ins("B", "0")]); + add("Z", vec![ins("B", "Hidden"), line(1, 90.0, "0")]); + add("H", vec![line(1, 50.0, "Hidden")]); + // A reference to B with an attribute on "Hidden" at y = 70. + let mut tagged = ins("B", "0"); + if let EntityKind::Insert(i) = &mut tagged.kind { + i.attribs.push(crate::Attrib { + tag: "T".into(), + text: Text { insert: Vec3::new(0.0, 70.0, 0.0), align_pt: None, ..text(HAlign::Left, VAlign::Baseline) }, + invisible: false, + constant: false, + prompt: String::new(), + props: crate::AttribProps { layer: Some("Hidden".into()), ..Default::default() }, + multiline: None, + modes: Default::default(), + }); + } + // References to H clipped to a boundary around its line, and with that clip inverted: no + // part of either is drawn where "Hidden" is frozen in the viewport. And a reference to B + // with the inverted clip: its line along y = 0 is drawn there. + let clip = |block: &str, inverted: bool| { + let mut e = ins(block, "0"); + if let EntityKind::Insert(i) = &mut e.kind { + let boundary = crate::ClipBoundary::new(vec![Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)]); + i.clip = Some(crate::ClipBoundary { inverted, ..boundary }); + } + e + }; + let (clipped, clipped_inverted, clipped_partly) = (clip("H", false), clip("H", true), clip("B", true)); + // An annotative reference to B: measured as it draws at the annotation scale, here 1:1. + let mut scaled = ins("B", "0"); + scaled.common.anno_scales = vec![crate::AnnoScale::unit()]; + // Dimensions that draw B and N, and a multileader that draws B. + let dimension = |block: &str| { + let kind = EntityKind::Dimension(crate::Dimension { + kind: crate::DimKind::Aligned, + defpt: Vec3::new(5.0, 1.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some(block.into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }); + Entity::new(crate::Handle(3), kind) + }; + let (dim, dim_nested) = (dimension("B"), dimension("N")); + let leader = Entity::new( + crate::Handle(4), + EntityKind::MLeader(crate::MLeader { + leaders: vec![vec![Vec3::ZERO]], + landing: Vec3::new(1.0, 0.0, 0.0), + dogleg: 0.45, + text: None, + style: "Standard".into(), + arrow_size: 1.0, + spline: false, + block: Some(reference("B")), + }), + ); + let frozen = ["HIDDEN".to_string()]; + let mut view = ViewportBounds::new(&frozen); + let ys = |b: Bounds2| (b.min.y, b.max.y); + assert_eq!(ys(entity_bounds(&d, &ins("B", "0"), 0)), (0.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &ins("B", "0"))), (0.0, 0.0), "a part on the frozen layer"); + assert_eq!(ys(view.entity_bounds(&d, &ins("N", "0"))), (0.0, 0.0), "a part two blocks deep"); + assert_eq!(ys(entity_bounds(&d, &ins("Z", "0"), 0)), (0.0, 90.0)); + assert_eq!(ys(view.entity_bounds(&d, &ins("Z", "0"))), (90.0, 90.0), "a nested reference on the frozen layer"); + assert!(!entity_bounds(&d, &ins("H", "0"), 0).is_empty()); + assert!(view.entity_bounds(&d, &ins("H", "0")).is_empty(), "nothing of it is drawn"); + let boundary = (Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)); + let (drawn, seen) = (entity_bounds(&d, &clipped, 0), view.entity_bounds(&d, &clipped)); + assert_eq!((drawn.min, drawn.max), boundary); + assert_eq!((seen.min, seen.max), boundary, "a clipped reference no part of which is drawn keeps its boundary"); + assert_eq!(ys(entity_bounds(&d, &clipped_inverted, 0)), (50.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &clipped_inverted)), (50.0, 50.0), "and one clipped the other way its block's box"); + assert_eq!(ys(entity_bounds(&d, &clipped_partly, 0)), (0.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &clipped_partly)), (0.0, 50.0), "with a part drawn too"); + assert!(entity_bounds(&d, &tagged, 0).max.y >= 70.0); + assert_eq!(ys(view.entity_bounds(&d, &tagged)), (0.0, 0.0), "an attribute on the frozen layer"); + assert_eq!(ys(entity_bounds(&d, &scaled, 0)), (0.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &scaled)), (0.0, 0.0), "an annotative reference"); + assert_eq!(entity_bounds(&d, &dim, 0).max.y, 50.0); + assert!(view.entity_bounds(&d, &dim).max.y < 50.0, "the block a dimension draws"); + assert_eq!(entity_bounds(&d, &dim_nested, 0).max.y, 50.0); + assert!(view.entity_bounds(&d, &dim_nested).max.y < 50.0, "a reference nested in the block a dimension draws"); + assert_eq!(entity_bounds(&d, &leader, 0).max.y, 50.0); + assert!(view.entity_bounds(&d, &leader).max.y < 50.0, "the block a multileader draws"); + let clips = [clipped, clipped_inverted, clipped_partly]; + let all = [ins("B", "0"), ins("N", "0"), ins("Z", "0"), ins("H", "0"), tagged, scaled, dim, dim_nested, leader].into_iter().chain(clips); + let all: Vec = all.collect(); + let mut plain = ViewportBounds::new(&[]); + for e in &all { + let (shared, fresh) = (view.entity_bounds(&d, e), ViewportBounds::new(&frozen).entity_bounds(&d, e)); + assert_eq!((shared.min, shared.max), (fresh.min, fresh.max)); + let (unfrozen, drawn) = (plain.entity_bounds(&d, e), entity_bounds(&d, e, 0)); + assert_eq!((unfrozen.min, unfrozen.max), (drawn.min, drawn.max)); + } + } + + /// With the layer Defpoints frozen in the viewport, a point on that layer that is a part of a + /// block still counts: in the block of a reference, one block deeper, in the block of a + /// dimension, as its definition points are held, and in that of a dimension that is itself a + /// part of a block. Here the point lies far above all the rest. A line on Defpoints, a point + /// on another frozen layer and a line on one are left out. One [`ViewportBounds`] gives each of + /// them the box a fresh one gives it. + #[test] + fn a_viewport_keeps_the_points_on_defpoints_in_a_block() { + let line = |handle: u64, y: f64, layer: &str| { + let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }); + let mut e = Entity::new(crate::Handle(handle), kind); + e.common.layer = layer.into(); + e + }; + let point = |handle: u64, y: f64, layer: &str| { + let mut e = Entity::new(crate::Handle(handle), EntityKind::Point(crate::Point { p: Vec3::new(5.0, y, 0.0), angle: 0.0 })); + e.common.layer = layer.into(); + e + }; + let ins = |block: &str| Entity::new(crate::Handle(9), EntityKind::Insert(crate::Insert { block: block.into(), ..crate::Insert::default() })); + let dimension = |block: &str| { + let kind = EntityKind::Dimension(crate::Dimension { + kind: crate::DimKind::Aligned, + defpt: Vec3::new(5.0, 1.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some(block.into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }); + Entity::new(crate::Handle(8), kind) + }; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + d.ensure_layer("Defpoints"); + let mut add = |name: &str, parts: Vec| { + let mut block = crate::Block::new(name); + for part in parts { + block.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + }; + // P: a line along y = 0 on layer 0, a point on Defpoints at y = 200, a line on Defpoints + // along y = 250 and a line on "Hidden" along y = 300. NP holds a reference to P, DP a + // dimension that draws P. H is P with the point on "Hidden". + add("P", vec![line(1, 0.0, "0"), point(2, 200.0, "Defpoints"), line(3, 250.0, "Defpoints"), line(4, 300.0, "Hidden")]); + add("NP", vec![ins("P")]); + add("DP", vec![dimension("P")]); + add("H", vec![line(1, 0.0, "0"), point(2, 200.0, "Hidden")]); + let ys = |b: Bounds2| (b.min.y, b.max.y); + assert_eq!(ys(entity_bounds(&d, &ins("P"), 0)), (0.0, 300.0)); + let frozen = ["HIDDEN".to_string(), "defpoints".to_string()]; + let mut view = ViewportBounds::new(&frozen); + assert_eq!(ys(view.entity_bounds(&d, &ins("P"))), (0.0, 200.0), "the point on Defpoints in a reference's block, not the lines"); + assert_eq!(ys(view.entity_bounds(&d, &ins("NP"))), (0.0, 200.0), "the same one block deeper"); + assert_eq!(view.entity_bounds(&d, &dimension("P")).max.y, 200.0, "a dimension's definition point"); + assert_eq!(view.entity_bounds(&d, &ins("DP")).max.y, 200.0, "the same for a dimension in a block"); + assert_eq!(ys(view.entity_bounds(&d, &ins("H"))), (0.0, 0.0), "a point on another frozen layer"); + // Where the viewport freezes only the other layer, the line on Defpoints counts too. + let hidden = ["Hidden".to_string()]; + assert_eq!(ys(ViewportBounds::new(&hidden).entity_bounds(&d, &ins("P"))), (0.0, 250.0)); + for e in [ins("P"), ins("NP"), dimension("P"), ins("DP"), ins("H")] { + let (shared, fresh) = (view.entity_bounds(&d, &e), ViewportBounds::new(&frozen).entity_bounds(&d, &e)); + assert_eq!((shared.min, shared.max), (fresh.min, fresh.max)); + } + } + /// A turned array of references reaches its side copies, not only the first and the last; /// a hostile count measures only the copies that are drawn. #[test] diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 07ecbf724..d5095a189 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -42,11 +42,19 @@ pub struct ForeignExtra { pub color_book: Option<(String, String)>, /// Other unmodelled property groups (material 347, shadow mode 284). pub props: Vec, + /// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled + /// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them. + pub tail: Vec, } impl ForeignExtra { pub fn is_empty(&self) -> bool { - self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty() + self.xdict.is_none() + && self.reactors.is_empty() + && self.xdata.is_empty() + && self.color_book.is_none() + && self.props.is_empty() + && self.tail.is_empty() } } @@ -89,11 +97,36 @@ pub struct Foreign { /// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a /// later save must not take it for this one (#2471). pub version: Option, + /// Block references with kept annotation scale contexts, as they were read: what a context + /// is brought up to date from (see [`KeptPlacement`]), by handle. + pub placements: BTreeMap, /// The file's registered applications (APPID names as read, in file order). Saving writes /// them all back, whether or not any xdata still names them. pub appids: Vec, } +/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its +/// attributes as read, in order. Its kept contexts were written for it then; what it did since +/// moves them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct KeptPlacement { + pub insert: crate::geom::Vec3, + pub rotation: f64, + pub scale: crate::geom::Vec3, + pub attribs: Vec, +} + +/// An attribute of a block reference as read: its tag, insertion and alignment points and +/// rotation (radians). Found again by tag and place among the reference's attributes with that +/// tag, since the attributes can be reordered or replaced (ATTSYNC) after the file is read. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct KeptAttrib { + pub tag: String, + pub insert: crate::geom::Vec3, + pub align: crate::geom::Vec3, + pub rotation: f64, +} + impl Foreign { /// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any. /// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name. @@ -110,9 +143,47 @@ impl Foreign { && self.targets.is_empty() && self.class_order.is_empty() && self.data_store.is_empty() + && self.placements.is_empty() && self.appids.is_empty() } + /// Re-key what is kept for the record named `from` under each of `kinds` (e.g. `["LAYER"]`, or + /// `["BLOCK_RECORD", "BLOCK", "ENDBLK"]` for a block) to the name `to`, after a rename: its + /// extras ([`Foreign::records`]) and the roles of its file handles ([`Foreign::targets`]), so + /// saving writes its xdata, extension dictionary and reactors on the renamed record. Names + /// compare trimmed and upper-case, as the reader keys them, so a rename that only changes case + /// changes nothing. + pub fn rename(&mut self, kinds: &[&str], from: &str, to: &str) { + let (from, to) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase()); + if from == to { + return; + } + for kind in kinds { + let old: ForeignKey = ((*kind).to_string(), from.clone()); + let new: ForeignKey = ((*kind).to_string(), to.clone()); + if let Some(extra) = self.records.remove(&old) { + self.records.insert(new.clone(), extra); + } + self.targets.values_mut().filter(|k| **k == old).for_each(|k| *k = new.clone()); + } + } + + /// Whether anything is kept for the record named `from` under one of `kinds`: what + /// [`Foreign::rename`] would re-key. + pub fn names(&self, kinds: &[&str], from: &str) -> bool { + let from = from.trim().to_ascii_uppercase(); + let hit = |k: &ForeignKey| k.1 == from && kinds.contains(&k.0.as_str()); + self.records.keys().any(hit) || self.targets.values().any(hit) + } + + /// [`Foreign::rename`] on a drawing's shared copy, which is cloned only when it keeps + /// something for the renamed record and the name really changes (not only its case). + pub fn rename_shared(this: &mut std::sync::Arc, 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 { @@ -390,3 +461,42 @@ pub fn class_number>(groups: impl IntoIterator + pub fn class_index(number: Option) -> Option { 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"))); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index f0d685175..864969e29 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -31,8 +31,8 @@ pub use cadcraft_geom as geom; pub use constraint::*; pub use entity::*; pub use extents::{ - BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts, - ole_frame_transform, + BlockBoundsCache, MAX_BLOCK_DEPTH, ViewportBounds, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, + ole_frame_accepts, ole_frame_transform, point_on_defpoints, }; pub use format::Format; pub use gdt::*; @@ -41,7 +41,7 @@ pub use names::{Named, NamedList, NamedMap}; pub use plotstyle::*; pub use plotter::*; pub use raster::{Raster, Rasters}; -pub use refedit::{RefEdit, WorkItem}; +pub use refedit::{RefEdit, WorkItem, XrefSource}; pub use store::EntityStore; pub use tables::*; pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES}; @@ -112,7 +112,8 @@ pub struct Drawing { /// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name. pub dim_styles: NamedList, pub mleader_styles: Vec, - pub table_styles: Vec, + /// Table styles in table order; looked up by name with [`NamedList::by_name`]. + pub table_styles: NamedList, /// Multiline styles (MLSTYLE); STANDARD is always there. pub mline_styles: Vec, /// Block definitions by name; [`Drawing::block`] looks them up. @@ -120,6 +121,9 @@ pub struct Drawing { pub model: EntityStore, /// Model layout's page setup, or the default extents-to-fit setup for a new drawing. pub model_page: Option, + /// The Model layout's own flags as the file had them (see [`Layout::flags`]); `None` for a + /// new drawing. + pub model_layout_flags: Option, /// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name. pub layouts: NamedList, /// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`), @@ -173,6 +177,9 @@ pub struct Drawing { /// turns those indices into the written table's (#3094). An empty name stands for a record /// without one. Empty for a drawing not read from a file. pub proxy_layers: Vec, + /// The LTYPE table of that file in the same way, without ByBlock and ByLayer (proxy graphics + /// count the others). + pub proxy_linetypes: Vec, } impl Default for Drawing { @@ -195,7 +202,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()]; + d.table_styles = vec![TableStyle::metric()].into(); d.header.set_str("DIMSTYLE", "ISO-25"); d } @@ -213,11 +220,12 @@ impl Drawing { text_styles: vec![TextStyle::default()].into(), dim_styles: vec![DimStyle::default()].into(), mleader_styles: vec![MLeaderStyle::default()], - table_styles: vec![TableStyle::default()], + table_styles: vec![TableStyle::default()].into(), mline_styles: vec![MLineStyle::default()], blocks: NamedMap::default(), model: EntityStore::new(), model_page: None, + model_layout_flags: None, layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(), active_layout: None, views: Vec::new(), @@ -239,6 +247,7 @@ impl Drawing { portable_fonts: false, rasters: Rasters::default(), proxy_layers: Vec::new(), + proxy_linetypes: Vec::new(), } } diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index db7d4b939..9fe841938 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -250,6 +250,39 @@ pub fn pattern_for(d: &Drawing, name: &str) -> Option { Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p }) } +/// The pattern name of a user-defined hatch, as the DXF Reference writes it (group 2). Its families +/// are not a named pattern's: a hatch stores them at unit scale, turned by its angle and spaced by +/// its scale (groups 52, 41 and 77 of a DXF file), so [`user_defined_lines`] makes them for a file +/// that lists none (AutoCAD's own are written with 78 = 0). +pub const USER_PATTERN: &str = "_USER"; + +/// Whether `name` is a user-defined hatch's pattern name ([`USER_PATTERN`], in any case). +pub fn is_user_pattern(name: &str) -> bool { + name.eq_ignore_ascii_case(USER_PATTERN) +} + +/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing. +pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9; + +/// Whether the scale can be used for hatch pattern lines. +pub fn is_supported_hatch_pattern_scale(scale: f64) -> bool { + scale.is_finite() && scale > MIN_HATCH_PATTERN_SCALE +} + +/// The effective scale of a stored hatch. Use unit scale when its scale is unusable. +pub fn effective_hatch_pattern_scale(scale: f64) -> f64 { + if is_supported_hatch_pattern_scale(scale) { scale } else { 1.0 } +} + +/// The line families of a user-defined hatch at unit scale, as a pattern definition has them: lines +/// along the hatch's angle, its scale apart, and with `double` a second family at right angles to +/// them. The hatch's angle turns the families and its scale spaces them, so a hatch of spacing +/// `s` and lines at `a` stores angle `a`, scale `s` and these families. +pub fn user_defined_lines(double: bool) -> Vec { + let family = || PatternLine { angle: 0.0, origin: (0.0, 0.0), delta: (0.0, 1.0), dashes: Vec::new() }; + if double { vec![family(), PatternLine { angle: 90.0, ..family() }] } else { vec![family()] } +} + /// `p` with every length (origins, offsets, dashes) multiplied by `k`. fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern { for l in &mut p.lines { diff --git a/crates/doc/src/names.rs b/crates/doc/src/names.rs index f97e5cb8c..30c6b0910 100644 --- a/crates/doc/src/names.rs +++ b/crates/doc/src/names.rs @@ -1,6 +1,6 @@ -//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles -//! and layouts), whose names are looked up without case through an index instead of a scan once a -//! table is large and looked up often. +//! 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 @@ -117,11 +117,11 @@ macro_rules! named_by_field { } )*}; } -named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout); +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 and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the -/// first entry of a name without case. +/// 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 { list: Vec, index: Lazy, diff --git a/crates/doc/src/plotter.rs b/crates/doc/src/plotter.rs index abcdb9903..ca8d75610 100644 --- a/crates/doc/src/plotter.rs +++ b/crates/doc/src/plotter.rs @@ -79,15 +79,21 @@ 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. + /// 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. 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]; @@ -243,6 +249,9 @@ 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"); diff --git a/crates/doc/src/refedit.rs b/crates/doc/src/refedit.rs index eb0927365..8130f08e2 100644 --- a/crates/doc/src/refedit.rs +++ b/crates/doc/src/refedit.rs @@ -42,6 +42,36 @@ pub struct RefEdit { /// Block objects taken out of the working set with their edits (block coordinates, the block /// object's handle). pub released: Vec, + /// The nested references picked through to reach the edited block: block references inside + /// block definitions, outermost first. Empty when the picked reference's own block is edited. + pub path: Vec, + /// Set when the edited block comes from an external reference: REFCLOSE Save writes it back + /// into its source drawing. + pub xref: Option, +} + +/// Where an xref edited in place is written back to. +#[derive(Clone, Debug, PartialEq)] +pub struct XrefSource { + /// The xref (its block name in this drawing). + pub xref: String, + /// The source drawing file. + pub file: String, + /// `file` with every symbolic link resolved when the edit began: the file that is written. + /// The save is refused when `file` leads somewhere else by then. + pub real: String, + /// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it + /// is written back in that version (`None`: in the drawing's own). + pub version: Option, + /// Whether the file is a binary DXF (written back as one). + pub binary: bool, + /// The block of the source drawing being edited; `None` for its model space. + pub block: Option, + /// The file's size and modification time when the edit began. + pub stamp: Option<(u64, std::time::SystemTime)>, + /// Edited block objects (their handles in this drawing) and the objects of the source + /// drawing they were loaded from. + pub sources: Vec<(Handle, Handle)>, } impl RefEdit { diff --git a/crates/doc/src/store.rs b/crates/doc/src/store.rs index 1b26a0514..558eb06fb 100644 --- a/crates/doc/src/store.rs +++ b/crates/doc/src/store.rs @@ -6,12 +6,19 @@ use std::collections::HashMap; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use crate::{Entity, Handle}; const CHUNK_MAX: usize = 1024; const SHARDS: usize = 64; +/// A content token no store has had: one count for the process (a `u64` does not run out). +fn next_token() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + #[derive(Clone, Debug, Default)] struct Chunk { id: u32, @@ -24,11 +31,19 @@ pub struct EntityStore { shards: Vec>>, len: usize, next_chunk: u32, + /// This state of the entities ([`EntityStore::content_token`]). Not part of [`PartialEq`]. + token: u64, } impl Default for EntityStore { fn default() -> Self { - EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 } + EntityStore { + chunks: Vec::new(), + shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), + len: 0, + next_chunk: 0, + token: next_token(), + } } } @@ -47,6 +62,17 @@ impl EntityStore { pub fn new() -> Self { Self::default() } + /// A number for this state of the entities: a clone has it too, and every edit gives the + /// store a number no store has had, so two stores with one token hold the same entities in + /// the same order. What is derived from the entities (a block's ATTDEFs by tag) can be kept + /// under it. Not part of [`PartialEq`]: equal stores can have different tokens. + pub fn content_token(&self) -> u64 { + self.token + } + /// The entities are about to change: a new token. + fn edited(&mut self) { + self.token = next_token(); + } pub fn len(&self) -> usize { self.len } @@ -101,6 +127,7 @@ impl EntityStore { self.replace(e); return; } + self.edited(); let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX); if needs_new { let c = self.new_chunk(); @@ -120,6 +147,7 @@ impl EntityStore { self.replace(e); return; } + self.edited(); let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX); if needs_new { let c = self.new_chunk(); @@ -137,6 +165,7 @@ impl EntityStore { pub fn replace(&mut self, e: Entity) -> bool { let Some(id) = self.chunk_id(e.handle) else { return false }; let Some(pos) = self.chunk_pos(id) else { return false }; + self.edited(); let Some(c) = self.chunks.get_mut(pos) else { return false }; let chunk = Arc::make_mut(c); if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) { @@ -149,6 +178,7 @@ impl EntityStore { pub fn remove(&mut self, h: Handle) -> Option> { let id = self.chunk_id(h)?; let pos = self.chunk_pos(id)?; + self.edited(); let c = self.chunks.get_mut(pos)?; let chunk = Arc::make_mut(c); let i = chunk.items.iter().position(|x| x.handle == h)?; @@ -165,6 +195,7 @@ impl EntityStore { pub fn modify(&mut self, h: Handle, f: F) -> bool { let Some(id) = self.chunk_id(h) else { return false }; let Some(pos) = self.chunk_pos(id) else { return false }; + self.edited(); let Some(c) = self.chunks.get_mut(pos) else { return false }; let chunk = Arc::make_mut(c); match chunk.items.iter_mut().find(|x| x.handle == h) { @@ -219,6 +250,7 @@ impl EntityStore { self.push(Arc::unwrap_or_clone(e)); return false; }; + self.edited(); let Some(c) = self.chunks.get_mut(pos) else { // Unreachable in practice too; never lose the object. self.push(Arc::unwrap_or_clone(e)); @@ -297,6 +329,47 @@ mod tests { Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 })) } + /// One token per state of the entities: shared by clones, new after every kind of edit, and + /// different for copies edited apart (#1660's ATTDEF index is kept by it). + #[test] + fn a_content_token_names_one_state_of_the_entities() { + let mut a = EntityStore::new(); + for h in 1..=3 { + a.push(ent(h)); + } + assert_eq!(a.clone().content_token(), a.content_token(), "a clone holds the same entities"); + let (mut b, mut c) = (a.clone(), a.clone()); + assert!(b.modify(Handle(1), |e| e.common.layer = "B".into())); + assert!(c.modify(Handle(1), |e| e.common.layer = "C".into())); + assert_ne!(b.content_token(), c.content_token(), "copies edited apart"); + assert_ne!(b.content_token(), a.content_token()); + let edits: [fn(&mut EntityStore); 8] = [ + |s| s.push(ent(9)), + |s| s.push_front(ent(8)), + |s| { + s.replace(ent(2)); + }, + |s| { + s.remove(Handle(3)); + }, + |s| { + s.bring_to_front(Handle(1)); + }, + |s| { + s.send_to_back(Handle(2)); + }, + |s| { + s.move_next_to(Handle(1), Handle(2), true); + }, + |s| s.sort_by_key(|e| std::cmp::Reverse(e.handle.0)), + ]; + for (i, edit) in edits.iter().enumerate() { + let mut s = a.clone(); + edit(&mut s); + assert_ne!(s.content_token(), a.content_token(), "edit {i}"); + } + } + #[test] fn push_get_remove() { let mut s = EntityStore::new(); diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index f3fd8f6dc..deeaaa079 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -725,9 +725,17 @@ pub struct Block { pub explodable: bool, #[serde(default)] pub units: u8, + /// References to this block scale uniformly (the BLOCK_RECORD's group 281). + #[serde(default)] + pub scale_uniformly: bool, /// The parameters of an associative array when this is an array block. #[serde(default, skip_serializing_if = "Option::is_none")] pub array: Option, + /// An xref's file as its loaded objects were read from it: size and modification time (as the + /// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether + /// the file changed since this drawing loaded it (session state; not saved). + #[serde(skip)] + pub xref_stamp: Option<(u64, std::time::SystemTime)>, } /// The load state of an external reference. @@ -773,7 +781,9 @@ impl Block { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, + xref_stamp: None, } } } @@ -899,6 +909,11 @@ pub struct Layout { /// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109). #[serde(default, skip_serializing_if = "Option::is_none")] pub limits: Option<(Vec2, Vec2)>, + /// The layout's own flags (LAYOUT group 70 after the AcDbLayout marker; DXF Reference: 1 is + /// its PSLTSCALE and 2 its LIMCHECK, each the value while the layout is current) as the file + /// had them; `None` for a layout CADCraft made, saved with the drawing's PSLTSCALE. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub flags: Option, } impl Layout { @@ -912,6 +927,7 @@ impl Layout { ucs: None, ucs_previous: Vec::new(), limits: None, + flags: None, } } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 3f0fe8e26..550059aa2 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -29,7 +29,7 @@ fn new_metric_drawing_has_metric_multileader_and_table_styles() { let i = Drawing::new_imperial(); assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]); - assert_eq!(i.table_styles, vec![TableStyle::default()]); + assert_eq!(*i.table_styles, vec![TableStyle::default()]); assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18)); } @@ -222,6 +222,8 @@ fn visible_attributes_of_a_missing_block_still_count() { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }, invisible, constant: false, @@ -271,6 +273,46 @@ 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(); @@ -443,6 +485,8 @@ fn plain_attrib(tag: &str) -> Attrib { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }, invisible: false, constant: false, @@ -598,6 +642,8 @@ fn attdef_in_block_is_ignored_in_insert_extents() { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }, invisible: false, constant: false, @@ -623,6 +669,8 @@ fn text_kind(value: &str) -> EntityKind { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }) } @@ -638,6 +686,7 @@ fn mtext_kind(contents: &str) -> EntityKind { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }) } @@ -891,6 +940,68 @@ fn constant_values_count_in_extents_as_attmode_shows_them() { assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one"); } +#[test] +fn aligned_and_fit_text_extents_span_their_two_points() { + // Drawn from the first point to the second whatever rotation is stored: Fit at its own height, + // Aligned at the height that keeps its proportions. + let ext = |halign: HAlign, second: Option| { + let mut t = plain_attrib("T").text; + t.value = "AB".into(); + (t.halign, t.align_pt) = (halign, second); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); + extents_pair(&d) + }; + let left = ext(HAlign::Left, None); + // Along x to a far second point: both reach it; only Aligned grows taller. + let far = Some(Vec3::new(20.0, 0.0, 0.0)); + let (fit, aligned) = (ext(HAlign::Fit, far), ext(HAlign::Aligned, far)); + assert!((fit.1.x - 20.0).abs() < 1e-9 && (aligned.1.x - 20.0).abs() < 1e-9, "{fit:?} {aligned:?}"); + assert!(fit.1.x > left.1.x + 10.0, "wider than the same text left-justified"); + assert_eq!(fit.1.y, left.1.y, "Fit keeps its height"); + assert!(aligned.1.y > left.1.y * 5.0, "Aligned scales its height with its width"); + // Straight up: the line turns to run to the second point. + let up = ext(HAlign::Fit, Some(Vec3::new(0.0, 20.0, 0.0))); + assert!((up.1.y - 20.0).abs() < 1e-9 && up.1.x < 1.0 && up.0.x < -0.5, "{up:?}"); + // No second point, or one on the first: placed like left-justified text. + assert_eq!(ext(HAlign::Fit, None), left); + assert_eq!(ext(HAlign::Aligned, Some(Vec3::ZERO)), left); +} + +#[test] +fn aligned_text_extents_keep_the_proportions_of_a_narrow_width_factor() { + // The fonts shape with the width factor as stored, so a text ten times narrower fitted over + // the same span is drawn ten times taller: its extents grow with it. + let top = |width_factor: f64| { + let mut t = plain_attrib("T").text; + t.value = "AB".into(); + (t.halign, t.align_pt, t.width_factor) = (HAlign::Aligned, Some(Vec3::new(20.0, 0.0, 0.0)), width_factor); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); + extents_pair(&d).1.y + }; + assert!(top(0.001) > top(0.01) * 5.0, "{} {}", top(0.001), top(0.01)); +} + +#[test] +fn aligned_and_fit_text_extents_follow_how_unusable_sizes_are_drawn() { + let ext = |halign: HAlign, height: f64, width_factor: f64| { + let mut t = plain_attrib("T").text; + t.value = "AB".into(); + (t.halign, t.align_pt, t.height, t.width_factor) = (halign, Some(Vec3::new(1000.0, 0.0, 0.0)), height, width_factor); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); + extents_pair(&d) + }; + // A height of 0 is drawn as a height of 1: Aligned text still spans its points and has room. + let flat = ext(HAlign::Aligned, 0.0, 1.0); + assert!((flat.1.x - 1000.0).abs() < 1e-9 && flat.1.y > flat.0.y, "{flat:?}"); + assert_eq!(flat, ext(HAlign::Aligned, 1.0, 1.0)); + // Fit text with a width factor of 0 is not stretched to the second point. + assert!(ext(HAlign::Fit, 1.0, 0.0).1.x < 100.0); + assert!((ext(HAlign::Fit, 1.0, 1.0).1.x - 1000.0).abs() < 1e-9); +} + #[test] fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() { // Two definitions of one tag, in different case, on a frozen layer and on layer 0: an @@ -965,9 +1076,13 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() { let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") }; ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect(); d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); - let t = std::time::Instant::now(); - assert!(!d.extents(&Space::Model).is_empty()); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model)); + assert!(!bounds.is_empty()); + // Layer inheritance and the constant-value filter each query the opposite set. + // With no matches, an unindexed scan bypasses the probe (zero) or compares every pair. + for probes in cross_probes { + assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}"); + } } /// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N diff --git a/crates/engine/src/audit.rs b/crates/engine/src/audit.rs index 0c60e025b..a210afc16 100644 --- a/crates/engine/src/audit.rs +++ b/crates/engine/src/audit.rs @@ -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, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Handle, Layer, Linetype, MLeaderStyle, TableStyle, TextStyle}; @@ -425,6 +425,9 @@ fn references(d: &mut Drawing, out: &mut Vec) { 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 = 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); @@ -462,12 +465,12 @@ fn references(d: &mut Drawing, out: &mut Vec) { if let Some(t) = &mut m.text { text_style(&mut t.style); } - if !has_name(&d.mleader_styles, &m.style, |s| &s.name) { + if !mleader_styles.contains(&m.style.to_ascii_lowercase()) { note("multileader style", &m.style); m.style = "Standard".into(); } } - EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => { + EntityKind::Table(t) if d.table_styles.by_name(&t.style).is_none() => { note("table style", &t.style); t.style = "Standard".into(); } diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index f23d3159f..c9109cb69 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -166,6 +166,9 @@ pub struct Autosaver { start: std::time::Instant, #[cfg(not(target_arch = "wasm32"))] last_beat: Option, + /// Who-has-it-open locks of the drawings open from files ([`crate::drawlock`]). + #[cfg(not(target_arch = "wasm32"))] + drawing_locks: crate::drawlock::Locks, /// This app's lock files: one per folder, because SAVEFILEPATH can change while files remain /// in the old folder. Each with the file it holds open for the system lock, or `None` where /// locks don't work and only the file's age counts. @@ -187,6 +190,8 @@ impl Autosaver { #[cfg(not(target_arch = "wasm32"))] last_beat: None, #[cfg(not(target_arch = "wasm32"))] + drawing_locks: crate::drawlock::Locks::default(), + #[cfg(not(target_arch = "wasm32"))] locks: Vec::new(), } } @@ -456,7 +461,8 @@ mod native { impl Autosaver { /// Autosave what is due (writing in the background) and delete files no longer needed. - /// Returns how long until the next autosave is due, so the host can wake up for it. + /// Returns how long until the next autosave or drawing-lock heartbeat is due, so the host + /// can wake up for it. pub fn tick(&mut self, s: &Session) -> Option { let now = self.start.elapsed().as_secs_f64(); self.reap(); @@ -465,7 +471,23 @@ mod native { let jobs = self.plan(s, now, minutes, &dir); self.perform(jobs); self.heartbeat(&dir, now); - self.next_due(now, minutes).map(Duration::from_secs_f64) + self.drawing_locks.sync(s, &self.instance); + // The drawing locks need their heartbeat even with nothing to autosave (SAVETIME 0, + // every drawing saved): left untouched they go stale and another app takes them over. + let due = self.next_due(now, minutes).map(Duration::from_secs_f64); + due.into_iter().chain(self.drawing_locks.next_beat()).min() + } + + /// Keep the drawing locks with `locks` instead of the default ones (e.g. a shorter + /// heartbeat, see [`crate::drawlock::Locks::with_heartbeat`]). + pub fn with_locks(mut self, locks: crate::drawlock::Locks) -> Self { + self.drawing_locks = locks; + self + } + + /// What the drawing locks have to tell the user (someone else has a drawing open). + pub fn take_lock_notes(&mut self) -> Vec { + self.drawing_locks.take_notes() } /// Autosave every drawing with changes not yet autosaved right away, without waiting for @@ -641,6 +663,7 @@ mod native { let _ = h.join(); } self.busy.clear(); + self.drawing_locks.release_all(&self.instance); for path in self.files() { discard(&path); } diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 8edfee34a..0ce4ca393 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -280,6 +280,9 @@ impl DocState { self.view_history.clear(); self.block_edit = Some(be); self.revision += 1; + // The editor's drawing is another drawing with the host's handles: a name given in the + // host must not resolve in it (BCLOSE ends the editor's names the same way, #1660). + self.expire_names(); } /// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name` @@ -346,6 +349,9 @@ impl DocState { self.views = host.views; self.view_history = host.view_history; self.revision += 1; + // The editor's drawing shares the host's handles: a name given in it must never resolve + // to a host record (or the other way round) after the drawing comes back. + self.expire_names(); Ok(()) } } diff --git a/crates/engine/src/cmd/annotate/leader.rs b/crates/engine/src/cmd/annotate/leader.rs index 3928a7663..d7a955484 100644 --- a/crates/engine/src/cmd/annotate/leader.rs +++ b/crates/engine/src/cmd/annotate/leader.rs @@ -151,6 +151,7 @@ impl Interactive for LeaderM { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), EntityKind::MText(m) => Some(m.clone()), _ => None, @@ -247,14 +248,25 @@ struct Sizes { text: f64, above: bool, text_style: String, + /// An annotative style: the annotation scale takes DIMSCALE's place, as for an annotative + /// dimension, so the sizes are unscaled and the text is annotative. + annotative: bool, } fn sizes(s: &Session) -> Sizes { // The current style with the drawing's DIM* overrides (what SETVAR DIMTXT… sets). let st = s.doc().ok().and_then(|d| d.dim_style(&style(s)).map(|st| st.with_overrides(&d.dim_overrides()))).unwrap_or_default(); - let k = if st.scale > 0.0 { st.scale } else { 1.0 }; + let dimscale = s.doc().map_or(1.0, |d| d.header.f64("DIMSCALE", 1.0)); + let k = if st.annotative { 1.0 } else { st.effective_scale(dimscale) }; let text_style = if st.text_style.is_empty() { "Standard".to_string() } else { st.text_style.clone() }; - Sizes { arrow: st.arrow_size * k, gap: st.text_gap.abs() * k, text: st.text_height * k, above: st.text_above != 0, text_style } + Sizes { + arrow: st.arrow_size * k, + gap: st.text_gap.abs() * k, + text: st.text_height * k, + above: st.text_above != 0, + text_style, + annotative: st.annotative, + } } /// LEADER's JSON form: a straight leader with an arrow through `pts`, and `text` (lines split at @@ -313,6 +325,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }))?) } Annotation::Quick { lines, width } => { @@ -330,6 +343,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }))?) } Annotation::Copy(m) => { @@ -348,5 +362,12 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo } Annotation::None => None, }; + if let (true, Some(t)) = (z.annotative, annotation) + && matches!(s.doc()?.entity(t).map(|e| &e.kind), Some(EntityKind::MText(_))) + { + let d = s.doc_mut()?; + let cur = d.current_anno_scale(); + d.modify_entity(t, |e| cadcraft_doc::set_annotative(e, true, &cur))?; + } Ok(std::iter::once(leader).chain(annotation).collect()) } diff --git a/crates/engine/src/cmd/annotate/mleader.rs b/crates/engine/src/cmd/annotate/mleader.rs index 9b4e74128..129762739 100644 --- a/crates/engine/src/cmd/annotate/mleader.rs +++ b/crates/engine/src/cmd/annotate/mleader.rs @@ -31,6 +31,7 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option< line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), style: st.name.clone(), arrow_size: st.arrow_size, diff --git a/crates/engine/src/cmd/annotate/tests.rs b/crates/engine/src/cmd/annotate/tests.rs index ee6f9e814..dbd8b72a7 100644 --- a/crates/engine/src/cmd/annotate/tests.rs +++ b/crates/engine/src/cmd/annotate/tests.rs @@ -480,6 +480,31 @@ fn table_create_edit_merge() { assert!(dl.prims.len() > 10); } +#[test] +fn covered_text_survives_save_and_unmerge() { + let text = "CoveredText".repeat(30); + let table = cadcraft_doc::Table { + col_widths: vec![2.0, 2.0], + row_heights: vec![0.5], + cells: vec![vec![ + cadcraft_doc::TableCell { text: "Title".into(), merged: Some((1, 2)), ..Default::default() }, + cadcraft_doc::TableCell { text: text.clone(), ..Default::default() }, + ]], + ..Default::default() + }; + let mut drawing = cadcraft_doc::Drawing::new_imperial(); + drawing.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Table(table)).unwrap(); + let bytes = cadcraft_io::write(&drawing, "table.dxf").unwrap(); + let drawing = cadcraft_io::read(&bytes, "table.dxf").unwrap(); + let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Table(_))).unwrap().handle; + let mut session = Session::new(); + session.open_drawing(drawing, "table.dxf", None); + session.execute("table.unmerge", &json!({ "handle": handle.hex(), "row": 0, "col": 1 })).unwrap(); + let EntityKind::Table(table) = &session.doc().unwrap().entity(handle).unwrap().kind else { panic!("expected table") }; + assert_eq!(table.cells[0][0].merged, None); + assert_eq!(table.cells[0][1].text, text); +} + #[test] fn table_interactive() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index cc3750567..fa959162d 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -117,8 +117,10 @@ fn run_recover(s: &mut Session, p: &Value) -> Result { let st = s.state_mut()?; let report = crate::audit::fix(Arc::make_mut(&mut st.doc)); if report.issues.is_empty() { - // Nothing to fix: the drawing opens unchanged, like OPEN. - st.doc = st.saved.clone(); + // Nothing to fix: the drawing opens unchanged, like OPEN. `fix` may already + // have copied it, so put the saved one back; no record name exists yet. + let saved = st.saved.clone(); + st.restore_drawing(saved); } if copy && !st.is_dirty() { // An unsaved copy (Drawing Recovery): closing it asks to save it under a name. diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 5b334c05e..181aacd28 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -18,7 +18,7 @@ use super::has_doc; use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Origin, Prompt, Result, Session, Step}; mod attdef; -mod attedit; +pub(crate) mod attedit; mod burst; mod description; mod dyngrip; @@ -457,17 +457,20 @@ fn current_text_style(s: &Session) -> String { s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()) } -/// A text style's name as the table spells it, with the width factor and oblique angle an -/// attribute definition takes from it (the renderer uses the entity's own values). `None` when -/// the drawing has no such style. -fn style_values(s: &Session, name: &str) -> Result> { - Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique))) +/// A text style's name as the table spells it, with the width factor, the oblique angle and the +/// Backwards and Upside down effects an attribute definition takes from it (the renderer uses the +/// entity's own values). +type StyleValues = (String, f64, f64, (bool, bool)); + +/// The [`StyleValues`] of the style named `name`. `None` when the drawing has no such style. +fn style_values(s: &Session, name: &str) -> Result> { + Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique, (t.backwards, t.upside_down)))) } /// The current text style (TEXTSTYLE) with its width factor and oblique angle. -fn current_style_values(s: &Session) -> (String, f64, f64) { +fn current_style_values(s: &Session) -> StyleValues { let name = current_text_style(s); - style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0)) + style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0, (false, false))) } /// A justification code as `-ATTDEF` takes it, typed or in `justify`. Align and Fit run between @@ -482,7 +485,7 @@ fn attdef_justify(code: &str) -> Result<(HAlign, VAlign)> { /// The named text style with its width factor and oblique angle, or the error both the JSON form /// and the typed `Style` option give for a style the drawing doesn't have. -fn resolve_style(s: &Session, name: &str) -> Result<(String, f64, f64)> { +fn resolve_style(s: &Session, name: &str) -> Result { style_values(s, name)?.ok_or_else(|| bad("attdef", format!("no text style \"{name}\""))) } @@ -507,10 +510,10 @@ fn attdef_kind( height: f64, invisible: bool, j: (HAlign, VAlign), - style: (String, f64, f64), + style: StyleValues, ) -> EntityKind { let (halign, valign) = j; - let (style, width_factor, oblique) = style; + let (style, width_factor, oblique, (backwards, upside_down)) = style; let left = halign == HAlign::Left && valign == VAlign::Baseline; EntityKind::AttDef(Attrib { tag: tag.to_ascii_uppercase(), @@ -525,6 +528,8 @@ fn attdef_kind( style, halign, valign, + backwards, + upside_down, }, invisible, constant: false, diff --git a/crates/engine/src/cmd/blocks/attdef.rs b/crates/engine/src/cmd/blocks/attdef.rs index 542afabfc..8ce94e566 100644 --- a/crates/engine/src/cmd/blocks/attdef.rs +++ b/crates/engine/src/cmd/blocks/attdef.rs @@ -103,7 +103,7 @@ impl AttdefM { fn finish(&mut self, s: &mut Session, rotation: f64) -> Result { let (h, v) = self.justify; let left = h == HAlign::Left && v == VAlign::Baseline; - let (style, width_factor, oblique) = super::resolve_style(s, &self.style)?; + let (style, width_factor, oblique, (backwards, upside_down)) = super::resolve_style(s, &self.style)?; s.add_entity(EntityKind::AttDef(Attrib { tag: self.tag.to_uppercase(), text: Text { @@ -117,6 +117,8 @@ impl AttdefM { style, halign: h, valign: v, + backwards, + upside_down, }, invisible: self.flags & INVISIBLE != 0, constant: self.flags & CONSTANT != 0, diff --git a/crates/engine/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index 5cf06b03a..4f35fe731 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -3,7 +3,7 @@ //! time or by replacing a string in all of them. Attribute tags match in any case, as in AutoCAD. use cadcraft_doc::color::Color; -use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign}; +use cadcraft_doc::{Attrib, AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign}; use cadcraft_geom::Vec3; use serde_json::{Map, Value, json}; @@ -20,7 +20,7 @@ pub(super) fn attedit_spec() -> CommandSpec { CommandSpec::new("attedit", "Single...", run) .menu(&["Modify", "Object", "Attribute", "Single..."]) .alias(&["ate", "eattedit"]) - .params("{handle, values: {TAG: value} (tags in any case)} → {changed, unknownTags?}") + .params("{handle, values?: {TAG: value} (tags in any case; every attribute with the tag), at?: {index: value} (one attribute, by its place in the reference, for repeated tags); constant attributes are left alone} → {changed, unknownTags?, constantTags?}") .interactive(|_| Ok(Box::new(AtteditM::default()))) } @@ -35,7 +35,11 @@ pub(super) fn dash_attedit_spec() -> CommandSpec { /// The value `values` gives for `tag`, matching the tag in any case. Numbers and booleans count /// as their text. pub(super) fn value_for(values: &Map, tag: &str) -> Option { - let v = values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?; + text_of(values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?) +} + +/// A value given for an attribute as its text (numbers and booleans count as their text). +fn text_of(v: &Value) -> Option { match v { Value::String(t) => Some(t.clone()), Value::Number(n) => Some(n.to_string()), @@ -63,18 +67,103 @@ pub(super) fn with_unknown_tags(s: &Session, h: Handle, values: &Map Result { let h = targets(s, p)?.first().copied().ok_or_else(|| bad("attedit", "`handle` is required"))?; let vals = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default(); + let Some(EntityKind::Insert(ins)) = s.doc()?.entity(h).map(|e| &e.kind) else { + return Err(bad("attedit", format!("{} is not a block reference", h.hex()))); + }; + if super::super::curves::is_locked(s, h) { + return Err(bad("attedit", "the reference is on a locked layer")); + } + // Values by place (`at`): one attribute each, where a tag repeats (a DXF reference may carry + // two attributes with one tag; `values` changes both). + let mut at: Vec<(usize, String)> = Vec::new(); + if let Some(m) = p.get("at").filter(|v| !v.is_null()) { + let m = m.as_object().ok_or_else(|| bad("attedit", "`at` must be an object of {index: value}"))?; + for (k, v) in m { + let i = k + .trim() + .parse::() + .ok() + .filter(|i| *i < ins.attribs.len()) + .ok_or_else(|| bad("attedit", format!("`at`: {k} is not the index of one of the reference's attributes")))?; + at.push((i, text_of(v).ok_or_else(|| bad("attedit", format!("`at`: the value for {k} must be text")))?)); + } + } + let given = |i: usize, tag: &str| at.iter().find(|(j, _)| *j == i).map(|(_, v)| v.clone()).or_else(|| value_for(&vals, tag)); + // Constant attributes keep their definition's value. + let constant: Vec = + ins.attribs.iter().enumerate().filter(|(i, a)| a.constant && given(*i, &a.tag).is_some()).map(|(_, a)| a.tag.clone()).collect(); + if let Some((_, a)) = ins.attribs.iter().enumerate().find(|(i, a)| given(*i, &a.tag).is_some_and(|v| v.len() > MAX_VALUE)) { + return Err(bad("attedit", format!("the value for {} is longer than {MAX_VALUE} bytes", a.tag))); + } let mut n = 0; s.doc_mut()?.modify_entity(h, |e| { if let EntityKind::Insert(i) = &mut e.kind { - for a in &mut i.attribs { - if let Some(v) = value_for(&vals, &a.tag) { + for (j, a) in i.attribs.iter_mut().enumerate().filter(|(_, a)| !a.constant) { + if let Some(v) = given(j, &a.tag) { set_value(&mut a.text, v); n += 1; } } } })?; - Ok(with_unknown_tags(s, h, &vals, json!({ "changed": n }))) + let mut r = with_unknown_tags(s, h, &vals, json!({ "changed": n })); + if !constant.is_empty() + && let Some(o) = r.as_object_mut() + { + o.insert("constantTags".into(), json!(constant)); + } + Ok(r) +} + +/// One attribute of a block reference, as the Properties palette and the Edit Attributes dialog +/// list it. +#[derive(Clone, Debug, PartialEq)] +pub struct AttributeRow { + pub tag: String, + /// The definition's prompt (the tag when it has none). + pub prompt: String, + pub value: String, + /// Where the attribute's text is inserted: two attributes can share a tag and a value, and a + /// reorder of the block's definitions moves them. + pub at: Vec3, + /// Not constant: the value can be changed. + pub editable: bool, + pub invisible: bool, + /// A multiline attribute: its value may hold line breaks. + pub multiline: bool, + /// The whole stored attribute this row was made from. The fields above are what a list shows; + /// this is what a pending edit is bound to, so a row is stale when any stored property differs + /// (text height, rotation, alignment point, justification, style, its own layer/colour/ + /// linetype/lineweight overrides, its modes, …) and not only when the shown ones do. + pub record: Attrib, +} + +/// The attributes of block reference `h`, in order (empty for other objects). The prompt comes +/// from the attribute, else from its definition in the reference's block. +pub fn attributes(d: &cadcraft_doc::Drawing, h: Handle) -> Vec { + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { return Vec::new() }; + let block = d.block(&ins.block); + let def_prompt = |tag: &str| { + block.and_then(|b| { + b.entities.iter().find_map(|e| match &e.kind { + EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag) && !ad.prompt.is_empty() => Some(ad.prompt.clone()), + _ => None, + }) + }) + }; + ins.attribs + .iter() + .map(|a| AttributeRow { + tag: a.tag.clone(), + prompt: if a.prompt.is_empty() { def_prompt(&a.tag).unwrap_or_else(|| a.tag.clone()) } else { a.prompt.clone() }, + value: a.text.value.clone(), + at: a.text.insert, + editable: !a.constant, + invisible: a.invisible, + multiline: a.multiline.is_some(), + record: a.clone(), + }) + .collect() } /// A block name, tag or value specification: comma-separated wildcard patterns, any case. For @@ -220,7 +309,7 @@ fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut c } /// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its -/// definition's (layer 0 is the reference's layer). +/// definition's (layer 0 from the definition is the reference's layer). fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> { let d = s.doc().ok()?; let e = d.entity(h)?; @@ -230,7 +319,7 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color) .block(&ins.block) .and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag)))); let c = a.props.over(&def.map(|de| de.common.clone()).unwrap_or_else(Common::default)); - let layer = if c.layer == "0" { e.common.layer.clone() } else { c.layer }; + let layer = if a.props.layer.is_none() && c.layer == "0" { e.common.layer.clone() } else { c.layer }; Some((layer, c.color)) } @@ -327,6 +416,14 @@ impl Interactive for AtteditM { fn name(&self) -> &'static str { "ATTEDIT" } + /// A selected block reference is taken at once (Edit Attributes from the shortcut menu). + fn begin(&mut self, s: &mut Session) -> Result { + let pre = s.selection(); + if s.settings.pickfirst && !pre.is_empty() && self.pick(s, &pre).is_ok() { + s.set_selection(Vec::new()); + } + Ok(Step::Continue) + } fn prompt(&self, _s: &Session) -> Prompt { match self.attribs.get(self.values.len()) { Some((_, tag, cur)) if self.block.is_some() => Prompt::new(format!("Enter value for {tag}"), Accept::TEXT).default(cur.clone()), diff --git a/crates/engine/src/cmd/blocks/attribs.rs b/crates/engine/src/cmd/blocks/attribs.rs index b6d6b2d24..df9624335 100644 --- a/crates/engine/src/cmd/blocks/attribs.rs +++ b/crates/engine/src/cmd/blocks/attribs.rs @@ -104,12 +104,17 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec let m = ins.transform(blk.base.xy()); // The reference's attributes by tag, gathered once for all the definitions (#1923). let carried = ins.attribs_by_tag(); + #[cfg(test)] + let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::>(); 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()); + let key = TagKey(&ad.tag); + #[cfg(test)] + let key = tests::MeasuredTag(key); + t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone()); Attrib { tag: ad.tag.clone(), text: t, @@ -204,6 +209,8 @@ pub(super) fn sync(s: &mut Session, name: &str) -> Result<(String, usize)> { let defs = attdefs(&blk); let d = s.doc_mut()?; let n = update_references(d, &blk.name, |ins| ins.attribs = synced(&blk, &defs, ins)); + // The references have new ATTRIBs: names given to the old ones hold no longer (#1660). + s.state_mut()?.expire_names(); Ok((blk.name.clone(), n)) } @@ -359,6 +366,74 @@ impl Interactive for AttsyncM { mod tests { use super::*; + std::thread_local! { + static SYNC_CROSS_PROBES: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// Use the actual tag ordering and count only probes between different fixture sets. + pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>); + + impl MeasuredTag<'_> { + fn record(&self, other: &Self) { + let TagKey(left) = self.0; + let TagKey(right) = other.0; + let sides = (left.as_bytes().first(), right.as_bytes().first()); + if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) { + SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1))); + } + } + } + + impl PartialEq for MeasuredTag<'_> { + fn eq(&self, other: &Self) -> bool { + self.record(other); + self.0 == other.0 + } + } + + impl Eq for MeasuredTag<'_> {} + + impl PartialOrd for MeasuredTag<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + + impl Ord for MeasuredTag<'_> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.record(other); + self.0.cmp(&other.0) + } + } + + #[test] + fn sync_uses_indexed_cross_set_tag_matching() { + const N: usize = 512; + let mut s = Session::new(); + s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap(); + s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap(); + let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap(); + let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap(); + let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap(); + let doc = s.doc().unwrap(); + let blk = doc.block("B").unwrap(); + let base = (*attdefs(blk)[0]).clone(); + let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") }; + let value = ins.attribs[0].clone(); + let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect(); + let defs: Vec<_> = defs.iter().collect(); + ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect(); + + SYNC_CROSS_PROBES.with(|count| count.set(Some(0))); + let result = synced(blk, &defs, &ins); + let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap()); + assert_eq!(result.len(), N); + assert!(result.iter().all(|a| a.text.value == "d")); + // No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N. + assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}"); + } + #[test] fn attdisp_keywords_map_to_attmode() { assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]); diff --git a/crates/engine/src/cmd/blocks/blockreplace.rs b/crates/engine/src/cmd/blocks/blockreplace.rs index f4614cbfb..2b0df7d89 100644 --- a/crates/engine/src/cmd/blocks/blockreplace.rs +++ b/crates/engine/src/cmd/blocks/blockreplace.rs @@ -81,6 +81,8 @@ fn replace(s: &mut Session, old: &str, new: &str, purge: bool) -> Result<(usize, }); let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&old)).cloned(); let purged = purge && !referenced(d, &old) && key.is_some_and(|k| d.blocks.remove(&k).is_some()); + // Replaced references have new ATTRIBs: names given to the old ones hold no longer (#1660). + s.state_mut()?.expire_names(); Ok((n, purged)) } diff --git a/crates/engine/src/cmd/blocks/burst.rs b/crates/engine/src/cmd/blocks/burst.rs index b7bcb4b37..bc7678081 100644 --- a/crates/engine/src/cmd/blocks/burst.rs +++ b/crates/engine/src/cmd/blocks/burst.rs @@ -41,13 +41,13 @@ fn burst_pieces(d: &Drawing, e: &Entity) -> Option> { } /// 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. +/// 0 from the definition is the reference's layer (an attribute set on layer 0 itself stays there) +/// and ByBlock colour the reference's colour, as EXPLODE gives the block's objects. fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common { // An attribute without a definition follows the reference. let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() }); let mut c = props.over(&base); - if c.layer == "0" { + if props.layer.is_none() && c.layer == "0" { c.layer.clone_from(&e.common.layer); } if c.color == Color::ByBlock { diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index 034eade79..5c4f9cb20 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -115,7 +115,13 @@ fn drawn(d: &Drawing, h: Handle) -> Vec { 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 common = under(&a.props.over(def.unwrap_or(&by_block)), r); + let own = a.props.over(def.unwrap_or(&by_block)); + let mut common = under(&own, r); + // An attribute set on layer 0 itself stays there; only layer 0 from its definition is + // the reference's layer. + if a.props.layer.is_some() { + common.layer.clone_from(&own.layer); + } let kind = match a.multiline_text() { Some(m) => EntityKind::MText(m), None => EntityKind::Text(a.text.clone()), @@ -274,6 +280,8 @@ mod tests { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }, invisible: false, constant: false, diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 91dfae9f1..5020defe6 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -30,9 +30,10 @@ pub(super) struct FileRef { } impl FileRef { - /// Whether to ask before redefining: a plain path whose block already exists. + /// Whether to ask before redefining: a plain path whose block already exists. EXPERT 2 or + /// more answers Yes without asking. pub fn ask_redefine(&self, s: &Session) -> bool { - !self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some()) + !self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some() && d.header.i64("EXPERT", 0) < 2) } /// Read the file and (re)define its block. Returns the block's name. diff --git a/crates/engine/src/cmd/blocks/purge.rs b/crates/engine/src/cmd/blocks/purge.rs index 5a86c9b79..9739c34cd 100644 --- a/crates/engine/src/cmd/blocks/purge.rs +++ b/crates/engine/src/cmd/blocks/purge.rs @@ -220,14 +220,19 @@ fn linetypes_inside(e: &cadcraft_doc::Entity) -> Vec { out } -/// The linetypes named by objects, layers, dimension styles and multiline styles. +/// The linetypes named by objects, layers, dimension styles and multiline styles, and the ones +/// proxy graphics draw with (as for layers: saving names them by their index in the table). fn linetypes_in_use(d: &Drawing) -> impl Iterator + '_ { let objects = entities(d).map(|e| e.common.linetype.clone()); + let graphics = entities(d).flat_map(|e| match &e.kind { + EntityKind::Unknown(u) => u.graphics.iter().map(|g| g.common.linetype.clone()).collect(), + _ => Vec::new(), + }); let inside = entities(d).flat_map(|e| linetypes_inside(e)); let layers = d.layers.iter().map(|l| l.linetype.clone()); let dims = d.dim_styles.iter().flat_map(|t| [t.dim_linetype.clone(), t.ext_linetype1.clone(), t.ext_linetype2.clone()]); let mlines = d.mline_styles.iter().flat_map(|t| t.elements.iter().map(|e| e.linetype.clone())); - objects.chain(inside).chain(layers).chain(dims).chain(mlines) + objects.chain(graphics).chain(inside).chain(layers).chain(dims).chain(mlines) } /// Names of the unused objects of a named kind, in table order. This is PURGE's scan; `USAGE` diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index 18d0d436b..a29340a5e 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -1,42 +1,62 @@ -//! REFEDIT, REFSET and REFCLOSE: edit a block reference in place. +//! REFEDIT, REFSET and REFCLOSE: edit a block reference or an xref in place. //! //! REFEDIT hides the picked reference and puts the block's objects (all, or the ones named) into //! the drawing where the reference shows them: the *working set*, ordinary objects that every //! command edits. The rest of the block stands there as faded copies, and everything else in the -//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]). Objects -//! drawn while editing join the working set. REFSET adds objects to or removes them from it. -//! REFCLOSE writes the working set back into the block definition, so every reference to the -//! block shows the change, or discards the edit. +//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]) and drawn +//! faded (XFADECTL). Objects drawn while editing join the working set. REFSET adds objects to or +//! removes them from it. REFCLOSE writes the working set back into the block definition, so every +//! reference to the block shows the change, or discards the edit. +//! +//! A reference nested in another block is picked through its parents (`path`, or "Select nesting +//! level [OK/Next]" at the command line): its own block is edited, the parents' other objects +//! stand faded around it. +//! +//! An xref (or a block that came with one) is edited the same way, and REFCLOSE Save writes the +//! change into its source drawing the way SAVE writes a drawing: when ISAVEBAK is on, the previous +//! file is kept as its `.bak` (with it off, no backup is kept); the new one replaces it +//! atomically, and a symbolic link planted beside it or put at its path during the edit never +//! redirects the write. The save is refused when the file is read-only, open in another program +//! (or another drawing tab), or changed since it was loaded. The xref is then loaded again from +//! the file it wrote. //! //! The state is [`Drawing::refedit`]: it travels with undo, is never written to a file (files -//! are written from [`Drawing::committed`]) and ends with the drawing it belongs to. +//! are written from [`Drawing::committed`]) and ends with the drawing it belongs to. UNDO stops +//! at a REFCLOSE Save that wrote an xref's file ([`undo_barrier`]). //! -//! Not yet: external references (their source drawing would have to be written back), nested -//! references picked at a depth, annotative scale contexts and attribute synchronisation. +//! Not yet: annotative scale contexts, attribute synchronisation and xrefs nested in xrefs (open +//! those with XOPEN). -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use cadcraft_doc::{Drawing, Entity, EntityStore, Handle, RefEdit, Transparency, WorkItem}; +use cadcraft_doc::{Block, Drawing, Entity, EntityKind, EntityStore, Handle, RefEdit, WorkItem, XrefSource, XrefStatus}; use cadcraft_geom::Mat3; use serde_json::{Value, json}; use super::super::curves::handle_value; -use super::super::machines::{SelOutcome, SelectPhase, SelectRun}; +use super::super::machines::{SelOutcome, SelectPhase}; use super::references_block; +use super::xref::load::{self, Sym}; +use crate::cmd::file::Version; use crate::cmd::{CommandSpec, bad, bool_or, has_doc, str_param, targets}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; -/// Transparency of the faded copies of the block's other objects. -const GHOST_FADE: u8 = 70; +/// Most nesting levels offered for one picked reference. +const MAX_LEVELS: usize = 256; pub(super) fn specs() -> Vec { vec![ CommandSpec::new("refedit", "Edit Reference In-Place", run_refedit) .menu(&["Tools", "Xref and Block In-place Editing", "Edit Reference In-Place"]) - .params("{handle? | handles? | name? (a block reference, default the selection), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded}") + .alias(&["-refedit"]) + .params("{handle? | handles? | name? (a block or xref reference, default the selection), path?: [handles of nested block references, outermost first] | nested?: block name (the first nested reference to it), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded, path, xref?: {name, file, version: its $ACADVER, binary}}. Editing an xref writes its file back on REFCLOSE Save, in the version and form it was read in (refused for versions CADCraft does not write, such as R12).") .enabled(has_doc) - .interactive(|_| Ok(Box::new(SelectRun::single("refedit", "REFEDIT", "Select reference")))), + .interactive(|_| Ok(Box::new(RefeditM::default()))), + CommandSpec::new("refedit.levels", "Reference Nesting Levels", run_levels) + .params("{handle (a block or xref reference)} → {levels: [{name, path: [handles], xref}]} (the picked reference first, then the references nested in it)") + .enabled(has_doc) + .noundo(), CommandSpec::new("refset", "Working Set", run_refset) .menu(&["Tools", "Xref and Block In-place Editing", "Add to Working Set"]) .params("{add?: [handles], remove?: [handles]} (or {handles, mode?: \"add\"|\"remove\"}); with neither: lists the working set → {working: [handles], added, removed}") @@ -44,7 +64,7 @@ pub(super) fn specs() -> Vec { .interactive(|_| Ok(Box::new(RefsetM::default()))), CommandSpec::new("refclose", "Save Reference Edits", run_refclose) .menu(&["Tools", "Xref and Block In-place Editing", "Save Reference Edits"]) - .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects}") + .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup? (its previous file, as SAVE names it; null when none was kept), notSaved?: {type: count} (what the file couldn't keep, also echoed)}") .enabled(editing) .interactive(|_| Ok(Box::new(RefcloseM))), ] @@ -59,14 +79,13 @@ fn active(s: &Session, cmd: &str) -> Result { s.doc()?.refedit.clone().ok_or_else(|| bad(cmd, "no block reference is being edited (REFEDIT)")) } -/// A block object as the drawing shows it through the edited reference. -fn to_host(to_world: &Mat3, e: &Entity, h: Handle, ghost: bool) -> Entity { +/// A block object as the drawing shows it through the edited reference. The copy keeps the +/// object's own transparency: the renderer fades what is outside the working set by the current +/// XFADECTL, so changing XFADECTL during the edit shows at once. +fn to_host(to_world: &Mat3, e: &Entity, h: Handle) -> Entity { let mut c = e.clone(); c.handle = h; c.kind.transform(to_world); - if ghost { - c.common.transparency = Transparency::Percent(GHOST_FADE); - } c } @@ -88,6 +107,250 @@ fn hexes(hs: impl IntoIterator) -> Vec { hs.into_iter().map(|h| h.hex()).collect() } +// ---------------- nesting ---------------- + +/// One level of a picked reference: a block, how its objects show in the drawing, and the +/// reference inside it that leads to the next level (none at the last). +struct Level { + block: Arc, + to_world: Mat3, + next: Option, +} + +/// Whether a reference with transform `m` can be edited in place (finite, not flat, scaled the +/// same in X and Y). +fn editable_transform(m: &Mat3, sx: f64, sy: f64) -> bool { + let finite = [m.a, m.b, m.c, m.d, m.e, m.f].iter().all(|v| v.is_finite()); + finite && m.det().abs() >= 1e-12 && (sx.abs() - sy.abs()).abs() <= 1e-9 * sx.abs().max(sy.abs()) +} + +/// Whether reference `i` shows its block more than once (columns and rows, as MINSERT makes): one +/// object, so a pick can't tell which instance is meant, and hiding it hides them all. +fn several(i: &cadcraft_doc::Insert) -> bool { + i.cols > 1 || i.rows > 1 +} + +fn several_refused(name: &str) -> crate::EngineError { + bad( + "refedit", + format!( + "the reference to \"{name}\" has several columns or rows, so it can't be edited in place; edit a single reference to the block, or the block with BEDIT" + ), + ) +} + +fn unequal_scale() -> crate::EngineError { + bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place") +} + +/// The levels from top reference `ins` down `path` (references inside the block definitions). +fn levels(d: &Drawing, ins: &cadcraft_doc::Insert, path: &[Handle]) -> Result> { + let mut block = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?; + if several(ins) { + return Err(several_refused(&ins.block)); + } + let mut m = ins.transform(block.base.xy()); + if !editable_transform(&m, ins.scale.x, ins.scale.y) { + return Err(unequal_scale()); + } + if path.len() >= cadcraft_doc::MAX_BLOCK_DEPTH { + return Err(bad("refedit", "the reference is nested too deeply")); + } + let mut out = Vec::with_capacity(path.len() + 1); + for h in path { + let e = block.entities.get(*h).ok_or_else(|| bad("refedit", format!("object {} is not a reference in block \"{}\"", h.hex(), block.name)))?; + let EntityKind::Insert(child) = &e.kind else { return Err(bad("refedit", format!("object {} is not a block reference", h.hex()))) }; + let cb = d.block(&child.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", child.block)))?; + if several(child) { + return Err(several_refused(&cb.name)); + } + let cm = m.then_before(child.transform(cb.base.xy())); + if !editable_transform(&cm, child.scale.x, child.scale.y) { + return Err(bad("refedit", format!("the nested reference to \"{}\" must be scaled equally in X and Y", cb.name))); + } + out.push(Level { block, to_world: m, next: Some(*h) }); + block = cb; + m = cm; + } + out.push(Level { block, to_world: m, next: None }); + Ok(out) +} + +/// The references nested in block `name` (depth first): (path of handles, block name). `m` is how +/// the block shows in the drawing: a reference is checked with everything above it, as [`levels`] +/// checks it. +fn nested(d: &Drawing, name: &str, m: &Mat3, path: &mut Vec, out: &mut Vec<(Vec, String)>) { + if path.len() + 1 >= cadcraft_doc::MAX_BLOCK_DEPTH || out.len() >= MAX_LEVELS { + return; + } + let Some(b) = d.block(name) else { return }; + for e in b.entities.iter() { + let EntityKind::Insert(i) = &e.kind else { continue }; + // Generated geometry (dimensions, arrays) is not offered, nor a reference `levels` would + // refuse (scaled differently in X and Y, flat, several columns or rows): nothing below it + // can be edited either. + let Some(c) = d.block(&i.block) else { continue }; + let cm = m.then_before(i.transform(c.base.xy())); + let editable = editable_transform(&cm, i.scale.x, i.scale.y); + if i.block.starts_with('*') || c.array.is_some() || out.len() >= MAX_LEVELS || !editable || several(i) { + continue; + } + path.push(e.handle); + out.push((path.clone(), i.block.clone())); + nested(d, &i.block, &cm, path, out); + path.pop(); + } +} + +/// The nesting levels of reference `ih`: the reference itself, then every reference nested in it. +fn level_list(d: &Drawing, ih: Handle) -> Result, String)>> { + let Some(EntityKind::Insert(ins)) = d.entity(ih).map(|e| &e.kind) else { return Err(bad("refedit", "select a block reference")) }; + let m = d.block(&ins.block).map_or(Mat3::IDENTITY, |b| ins.transform(b.base.xy())); + // As [`levels`] checks it: a reference it would refuse offers nothing nested in it either. + if several(ins) { + return Err(several_refused(&ins.block)); + } + if !editable_transform(&m, ins.scale.x, ins.scale.y) { + return Err(unequal_scale()); + } + let mut out = vec![(Vec::new(), ins.block.clone())]; + nested(d, &ins.block, &m, &mut Vec::new(), &mut out); + Ok(out) +} + +fn run_levels(s: &mut Session, p: &Value) -> Result { + let ih = targets(s, p)?.into_iter().next().ok_or_else(|| bad("refedit.levels", "select a block reference"))?; + let d = s.doc()?; + let levels: Vec = level_list(d, ih)? + .into_iter() + .map(|(path, name)| json!({ "name": name, "path": hexes(path), "xref": xref_of(d, &name).is_some() })) + .collect(); + Ok(json!({ "levels": levels })) +} + +// ---------------- xrefs ---------------- + +/// The xref block `name` belongs to: (the xref's name, the block of its source drawing or `None` +/// for its model space). `None` for a block of this drawing. +fn xref_of(d: &Drawing, name: &str) -> Option<(String, Option)> { + let b = d.block(name)?; + if b.xref_path.is_some() { + return Some((b.name.clone(), None)); + } + let (root, rest) = name.split_once('|')?; + let x = d.block(root).filter(|x| x.xref_path.is_some())?; + Some((x.name.clone(), Some(rest.to_string()))) +} + +/// Whether a drawing tab other than the active one has `file` open. +fn open_in_another_tab(s: &Session, file: &std::path::Path) -> bool { + let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + let me = canon(file); + s.docs.iter().enumerate().any(|(i, st)| i != s.active && st.path.as_deref().is_some_and(|p| canon(std::path::Path::new(p)) == me)) +} + +/// The source file of xref `name`, checked for an edit in place: found, not open in another +/// drawing tab, writable, not changed since this drawing loaded it. Also returns the +/// [`load::Stamp`] it had then (this drawing's own baseline, [`Block::xref_stamp`]). +fn xref_file(s: &Session, name: &str) -> Result<(std::path::PathBuf, load::Stamp)> { + if cfg!(target_arch = "wasm32") { + return Err(bad("refedit", "editing xrefs in place is not available on the web; open the xref's drawing instead")); + } + let d = s.doc()?; + let b = d.block(name).ok_or_else(|| bad("refedit", format!("no xref \"{name}\"")))?; + if b.xref_status != XrefStatus::Loaded { + return Err(bad("refedit", format!("xref \"{}\" is not loaded ({}); reload it first", b.name, b.xref_status.label()))); + } + let path = b.xref_path.clone().unwrap_or_default(); + let host = s.state().ok().and_then(|st| st.path.clone()); + let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|_| bad("refedit", format!("{path}: file not found")))?; + // Under the automation roots: the file is read for the edit, and written by REFCLOSE Save, so + // an edit that couldn't be saved doesn't begin. + crate::file_access::check_read(&file).map_err(|e| bad("refedit", e))?; + crate::file_access::check_write(&file).map_err(|e| bad("refedit", format!("{e}; open it with XOPEN instead")))?; + if open_in_another_tab(s, &file) { + return Err(bad("refedit", format!("{} is open in another drawing tab: edit it there, or close it first", file.display()))); + } + writable(&file).map_err(|e| bad("refedit", e))?; + // Unknown (the system can't tell, or the file changed while it was read) counts as changed. + match (b.xref_stamp, load::stamp(&file)) { + (Some(then), Some(now)) if then == now => Ok((file, then)), + _ => Err(bad("refedit", format!("{} changed since xref \"{}\" was loaded; reload it first", file.display(), b.name))), + } +} + +/// Whether `file` may be written: not read-only and not open in another program (AutoCAD's +/// `.dwl` lock file beside it, or a file that can't be opened for writing). +fn writable(file: &std::path::Path) -> std::result::Result<(), String> { + #[cfg(target_arch = "wasm32")] + { + let _ = file; + Err("files are not available on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let meta = std::fs::metadata(file).map_err(|e| format!("{}: {e}", file.display()))?; + if meta.permissions().readonly() { + return Err(format!("{} is read-only", file.display())); + } + let lock = file.with_extension("dwl"); + if lock.is_file() { + return Err(format!("{} is open in another program (lock file {})", file.display(), lock.display())); + } + std::fs::OpenOptions::new().append(true).open(file).map(|_| ()).map_err(|e| format!("{} can't be written: {e}", file.display())) + } +} + +/// The objects of the source drawing a block of xref `x` came from, matched one to one with the +/// block's objects (the order loading keeps). Refused when they no longer match. +fn source_handles(blk: &Block, src: &Drawing, inner: Option<&str>) -> Result> { + let store = match inner { + None => &src.model, + Some(n) => { + let b = src.block(n).ok_or_else(|| bad("refedit", format!("block \"{n}\" is no longer in the xref's drawing; reload the xref")))?; + if b.xref_path.is_some() { + return Err(bad("refedit", format!("\"{n}\" is an xref of the xref's drawing: open it with XOPEN to edit it"))); + } + &b.entities + } + }; + let kind = |e: &Entity| std::mem::discriminant(&e.kind); + if store.len() != blk.entities.len() || store.iter().zip(blk.entities.iter()).any(|(a, b)| kind(a) != kind(b)) { + return Err(bad("refedit", "the xref's drawing no longer matches what was loaded; reload the xref first")); + } + Ok(blk.entities.iter().zip(store.iter()).map(|(a, b)| (a.handle, b.handle)).collect()) +} + +/// The version (`$ACADVER` code) and form (binary DXF or not) of the xref's file `file`, read as +/// `src` from bytes beginning with `head` (one read: the file is not opened again), so it is +/// written back as it was: a DWG's version is its first bytes, a DXF's the `$ACADVER` it was read +/// with. Refused when CADCraft can't write that version (an R12 DXF, AC1009): saving would change +/// it, and the xref is often someone else's file. +fn file_form(file: &std::path::Path, src: &Drawing, head: &[u8]) -> Result<(Option, bool)> { + let dwg = head + .get(..6) + .filter(|t| t.starts_with(b"AC") && t.get(2..).is_some_and(|d| d.iter().all(u8::is_ascii_digit))) + .map(|t| String::from_utf8_lossy(t).into_owned()); + let declared = || src.foreign.version.clone().or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).map(str::to_string)); + let version = dwg.or_else(declared).map(|v| v.trim().to_ascii_uppercase()); + if let Some(code) = &version + && Version::parse(code).is_none_or(|v| v.code() != code) + { + return Err(bad( + "refedit", + format!( + "{} is an {code} file, and CADCraft writes only 2000 to 2018 files, so the edit couldn't be saved in the file's own version; open it with XOPEN instead", + file.display() + ), + )); + } + let binary = craft_dxf::is_binary(head); + if (version.is_some() || binary) && crate::cmd::file::write_as().is_none() { + return Err(bad("refedit", "saving an xref in its own version is not available in this build; open it with XOPEN instead")); + } + Ok((version, binary)) +} + // ---------------- REFEDIT ---------------- fn run_refedit(s: &mut Session, p: &Value) -> Result { @@ -100,34 +363,71 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { .model .iter() .chain(d.layouts.iter().flat_map(|l| l.entities.iter())) - .find(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n))) + .find(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n))) .map(|e| e.handle), - None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, cadcraft_doc::EntityKind::Insert(_)))), + None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))), }; let ih = picked.ok_or_else(|| bad("refedit", "select a block reference"))?; let (ins, space) = match d.entity(ih).map(|e| &e.kind) { - Some(cadcraft_doc::EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?), + Some(EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?), _ => return Err(bad("refedit", "select a block reference")), }; - let blk = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?; - if blk.xref_path.is_some() { + // A dynamic block reference shows an anonymous copy (`*U12`) made for its values. + if let Some(r) = cadcraft_doc::dynblock::reference(d, ih) { return Err(bad( "refedit", format!( - "\"{}\" is an external reference: editing it in place would write its source drawing, which is not available yet. Open it with XOPEN, edit and save it, then reload.", - blk.name + "\"{}\" is a dynamic block: edit it in the Block Editor (BEDIT), or its attributes with Edit Attributes (ATTEDIT); editing dynamic blocks in place is not available yet", + r.definition ), )); } + let path: Vec = match (p.get("path"), str_param(p, "nested")) { + (Some(Value::Array(a)), _) => { + a.iter().map(|v| handle_value(v).ok_or_else(|| bad("refedit", format!("`path`: {v} is not an object handle")))).collect::>()? + } + (Some(Value::Null) | None, Some(n)) => level_list(d, ih)? + .into_iter() + .find(|(path, name)| !path.is_empty() && name.eq_ignore_ascii_case(n)) + .map(|(path, _)| path) + .ok_or_else(|| bad("refedit", format!("no reference to \"{n}\" is nested in this one")))?, + (Some(Value::Null) | None, None) => Vec::new(), + (Some(v), _) => return Err(bad("refedit", format!("`path` must be an array of object handles, got {v}"))), + }; + let levels = levels(d, &ins, &path)?; + let Some(edit) = levels.last() else { return Err(bad("refedit", "select a block reference")) }; + let blk = edit.block.clone(); + let to_world = edit.to_world; if blk.name.starts_with('*') || blk.array.is_some() { return Err(bad("refedit", format!("\"{}\" is generated geometry and can't be edited in place", blk.name))); } - let to_world = ins.transform(blk.base.xy()); - let (sx, sy) = (ins.scale.x.abs(), ins.scale.y.abs()); - let finite = [to_world.a, to_world.b, to_world.c, to_world.d, to_world.e, to_world.f].iter().all(|v| v.is_finite()); - if !finite || to_world.det().abs() < 1e-12 || (sx - sy).abs() > 1e-9 * sx.max(sy) { - return Err(bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place")); - } + // An xref's block: where it is written back. + let xref = match xref_of(d, &blk.name) { + Some((x, inner)) => { + let (file, baseline) = xref_file(s, &x)?; + let (src, read_as, head) = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + // The handles, version, form and stamp all come from this one read, which must be of + // the file this drawing loaded. + if read_as != Some(baseline) { + return Err(bad("refedit", format!("{} changed since xref \"{x}\" was loaded; reload it first", file.display()))); + } + let sources = source_handles(&blk, &src, inner.as_deref())?; + let real = std::fs::canonicalize(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + let (version, binary) = file_form(&file, &src, &head)?; + Some(XrefSource { + xref: x, + file: file.to_string_lossy().into_owned(), + real: real.to_string_lossy().into_owned(), + version, + binary, + block: inner, + stamp: read_as, + sources, + }) + } + None => None, + }; + let d = s.doc()?; let chosen: Option> = match p.get("objects") { None | Some(Value::Null) => None, Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => None, @@ -157,20 +457,37 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { items: Vec::new(), ghosts: Vec::new(), released: Vec::new(), + path: path.clone(), + xref, }; let doc = s.doc_mut()?; for e in blk.entities.iter() { let working = chosen.as_ref().is_none_or(|c| c.contains(&e.handle)); let h = doc.new_handle(); - put(doc, &r, to_host(&to_world, e, h, !working))?; + put(doc, &r, to_host(&to_world, e, h))?; if working { r.items.push(WorkItem { copy: h, source: Some(e.handle) }); } else { r.ghosts.push((h, e.handle)); } } + // The parents' other objects stand faded around a nested block. + for level in levels.iter().filter(|l| l.next.is_some()) { + for e in level.block.entities.iter().filter(|e| Some(e.handle) != level.next && !matches!(e.kind, EntityKind::AttDef(_))) { + let h = doc.new_handle(); + put(doc, &r, to_host(&level.to_world, e, h))?; + r.ghosts.push((h, e.handle)); + } + } doc.modify_entity(ih, |e| e.common.visible = false).map_err(|e| bad("refedit", e.to_string()))?; - let out = json!({ "block": r.block, "insert": ih.hex(), "working": hexes(r.items.iter().map(|i| i.copy)), "faded": r.ghosts.len() }); + let out = json!({ + "block": r.block, + "insert": ih.hex(), + "working": hexes(r.items.iter().map(|i| i.copy)), + "faded": r.ghosts.len(), + "path": hexes(r.path.iter().copied()), + "xref": r.xref.as_ref().map(|x| json!({ "name": x.xref, "file": x.file, "version": x.version, "binary": x.binary })), + }); let sel: Vec = r.items.iter().map(|i| i.copy).collect(); doc.refedit = Some(r); s.set_selection(sel); @@ -220,16 +537,19 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result Some(r.released.remove(i)), None => blk.entities.get(src).map(|e| (**e).clone()), }; if let Some(cur) = cur { let c = doc.new_handle(); - put(doc, &r, to_host(&r.to_world, &cur, c, false))?; + put(doc, &r, to_host(&r.to_world, &cur, c))?; r.items.push(WorkItem { copy: c, source: Some(src) }); added += 1; } @@ -248,7 +568,7 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result Result { // Work on a copy: the drawing changes only when everything went through. let mut nd: Drawing = s.doc()?.clone(); let mut objects = 0; + let mut written = None; if save { objects = commit_block(&mut nd, &r)?; + if let Some(x) = &r.xref { + // Opened in another tab since the edit began: that tab would hold a stale drawing. + if open_in_another_tab(s, std::path::Path::new(&x.file)) { + return Err(bad( + "refclose", + format!("{} is open in another drawing tab: close it there first; the edit stays open (REFCLOSE Discard ends it)", x.file), + )); + } + // The file first: when it can't be written the edit stays open (Discard ends it). + written = Some(write_back(&nd, &r, x)?); + } } nd.end_refedit_discard(&r); + let mut notes = Vec::new(); + if let (Some(x), Some(_)) = (&r.xref, &written) { + let host = s.state().ok().and_then(|st| st.path.clone()); + notes = load::load(&mut nd, &x.xref, host.as_deref(), false); + } *s.doc_mut()? = nd; // The objects the edit managed were its own: OOPS doesn't bring them back after it. s.state_mut()?.erased.forget(|h| r.owns(h)); s.set_selection(Vec::new()); - Ok(json!({ "block": r.block, "saved": save, "objects": objects })) + for o in notes { + s.echo(o.message()); + } + let mut out = json!({ "block": r.block, "saved": save, "objects": objects }); + if let (Some(x), Some(w)) = (&r.xref, written) { + out["file"] = json!(x.file); + // `null` when the file didn't look like a whole drawing and the `.bak` there was kept. + out["backup"] = json!(w.backup); + // What the file couldn't keep, said as SAVE says it (nothing is dropped silently). + let kept = w.backup.as_ref().map(|b| format!(" The previous file, with them, is kept as {b}.")).unwrap_or_default(); + let mut not_saved = w.lost.clone(); + if let Some(msg) = crate::cmd::file::lost_message(&x.file, w.version, &w.lost) { + s.echo(format!("{}: {msg}.{kept}", x.file)); + } + if w.associations > 0 { + s.echo(format!( + "{}: Not saved in the file: the dimension associations of {} dimension(s), which tie them to the objects they measure (an xref edited in place doesn't keep them yet).{kept}", + x.file, w.associations + )); + not_saved.insert("dimension associations".into(), w.associations); + } + if !not_saved.is_empty() { + out["notSaved"] = json!(not_saved); + } + } + Ok(out) +} + +/// What writing an xref back did: the backup it kept, the version it was written at, what the +/// file couldn't keep ([`crate::cmd::file::lost_writing`]), and how many dimensions were written +/// without their associations ([`put_edit`]). +struct Written { + backup: Option, + version: Version, + lost: std::collections::BTreeMap, + associations: usize, } /// Replace the block's objects by the working set (and move the drawing objects added to it @@ -333,6 +705,354 @@ fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result { Ok(n) } +// ---------------- writing an xref back ---------------- + +/// Write the edited block of `nd` (committed) into xref source `x`. +fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { + let file = std::path::Path::new(&x.file); + let real = std::path::Path::new(&x.real); + // Under the automation roots, the file written and its backup, before anything is read or + // written: roots put in force since the edit began hold too. + for target in [real.to_path_buf(), crate::cmd::file::backup_path(real)] { + crate::file_access::check_write(&target).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; + } + writable(file).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; + still_leads_to(file, real).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; + unchanged(file, x, load::stamp(file))?; + let hooks = crate::cmd::file::io().ok_or_else(|| bad("refclose", "file formats are not available in this build"))?; + let (mut src, read_as, _) = load::read_file(file).map_err(|e| bad("refclose", format!("{}: {e}", file.display())))?; + // What is written over is what was just read, and that is the file the edit began with. + unchanged(file, x, read_as)?; + let dropped = put_edit(nd, r, x, &mut src)?; + // The xref is loaded again from the file: one it could no longer load is not written. + let objects = load::object_count(&src); + if objects > load::MAX_XREF_OBJECTS { + return Err(bad( + "refclose", + format!( + "{} would hold {objects} objects, more than an xref loads ({}); it is not written (REFCLOSE Discard ends the edit)", + file.display(), + load::MAX_XREF_OBJECTS + ), + )); + } + // In the version and form the file was read in, not the writer's default (a DWG at 2004 or + // later): a version change can lock out whoever made the file. + let version = x.version.as_deref().and_then(Version::parse); + let bytes = if version.is_none() && !x.binary { + (hooks.write)(&src, &x.file) + } else { + let w = crate::cmd::file::write_as().ok_or_else(|| bad("refclose", "saving an xref in its own version is not available in this build"))?; + w(&src, &x.file, &crate::cmd::file::SaveAs { version, binary: x.binary, portable_fonts: false }) + }; + let bytes = bytes.map_err(|e| bad("refclose", format!("writing {}: {e}", file.display())))?; + let as_version = + version.unwrap_or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver).unwrap_or_default()); + let lost = crate::cmd::file::lost_writing(&src, &x.file, as_version); + // Once more just before the file is replaced: another program may have saved it while the + // new file was made. (Without a lock every writer honours, this narrows the window; it + // can't close it.) + unchanged(file, x, load::stamp(file))?; + let backup = replace_file(file, real, &bytes).map_err(|e| bad("refclose", e))?; + Ok(Written { backup, version: as_version, lost, associations: dropped }) +} + +/// Refuse when `now` (the xref's file as it is, or as just read) is not the file the edit began +/// with; an unknown stamp counts as changed. +fn unchanged(file: &std::path::Path, x: &XrefSource, now: Option) -> Result<()> { + if x.stamp.is_none() || now != x.stamp { + return Err(bad( + "refclose", + format!("{} changed since the edit began; it is not overwritten (REFCLOSE Discard ends the edit)", file.display()), + )); + } + Ok(()) +} + +/// Put the edited block of `nd` (committed) into `src`, the xref's drawing as read: its objects +/// with their source handles and names, and the host symbols they use. Returns how many of the +/// dimensions written lose associations: those of the file's own dimensions (loading the xref +/// dropped them; a dimension erased during the edit isn't written, so it doesn't count) and those +/// of a dimension attached to objects of the host (drawn during the edit), whose handles mean +/// nothing in the xref's file. +fn put_edit(nd: &Drawing, r: &RefEdit, x: &XrefSource, src: &mut Drawing) -> Result { + let file = std::path::Path::new(&x.file); + let blk = nd.block(&r.block).ok_or_else(|| bad("refclose", format!("block \"{}\" is gone", r.block)))?; + let prefix = format!("{}|", x.xref); + let map: HashMap = x.sources.iter().copied().collect(); + let mut store = EntityStore::new(); + let mut wanted: Vec<(Sym, String)> = Vec::new(); + // The file's own dimensions attached to objects, in the part the edit replaces. + let replaced = match &x.block { + None => Some(&src.model), + Some(n) => src.block(n).map(|b| &b.entities), + }; + let associative: HashSet = replaced + .map(|st| st.iter().filter(|e| matches!(&e.kind, EntityKind::Dimension(dm) if !dm.assoc.is_empty())).map(|e| e.handle).collect()) + .unwrap_or_default(); + let mut dropped = 0usize; + for e in blk.entities.iter() { + let mut e = (**e).clone(); + let source = map.get(&e.handle).copied(); + e.handle = source.unwrap_or_else(|| src.new_handle()); + rename_into_source(&mut e, &prefix, &mut wanted); + let host_assoc = match &mut e.kind { + EntityKind::Dimension(dm) if !dm.assoc.is_empty() => { + dm.assoc.clear(); + true + } + _ => false, + }; + if host_assoc || source.is_some_and(|h| associative.contains(&h)) { + dropped = dropped.saturating_add(1); + } + store.push(e); + } + bring_symbols(nd, src, &prefix, wanted, MAX_SYMBOLS)?; + match &x.block { + None => src.model = store, + Some(name) => { + let key = src + .blocks + .keys() + .find(|k| k.eq_ignore_ascii_case(name)) + .cloned() + .ok_or_else(|| bad("refclose", format!("block \"{name}\" is gone from {}", file.display())))?; + if let Some(b) = src.blocks.get_mut(&key) { + Arc::make_mut(b).entities = store; + } + } + } + Ok(dropped) +} + +/// Refuse a save when `file` no longer leads to `real` (the file the edit began with), or `real` +/// is no longer a plain file: a symbolic link put at either since would send the edit to another +/// file. +fn still_leads_to(file: &std::path::Path, real: &std::path::Path) -> std::result::Result<(), String> { + let now = std::fs::canonicalize(file).map_err(|e| format!("{}: {e}", file.display()))?; + let plain = std::fs::symlink_metadata(real).is_ok_and(|m| m.is_file()); + if now != real || !plain { + return Err(format!( + "{} leads to another file than when the edit began (a symbolic link was put there); it is not overwritten", + file.display() + )); + } + Ok(()) +} + +/// Symbol names of a host object as the xref's drawing has them: `xref|name` loses its prefix; +/// the host's own symbols keep their names and are noted in `wanted` (copied into the drawing). +fn rename_into_source(e: &mut Entity, prefix: &str, wanted: &mut Vec<(Sym, String)>) { + let found = std::cell::RefCell::new(Vec::new()); + load::rename_refs(e, &|sym, n| { + if load::has_prefix(n, prefix) { + return n.get(prefix.len()..).map(str::to_string); + } + found.borrow_mut().push((sym, n.to_string())); + None + }); + wanted.extend(found.into_inner()); +} + +/// Most distinct symbols [`bring_symbols`] looks at for one save (hostile drawings: blocks naming +/// blocks naming blocks…). +const MAX_SYMBOLS: usize = 100_000; + +/// Copy the host's symbols that objects written into `src` use and `src` lacks (layers, +/// linetypes, text, dimension, multileader and table styles, and blocks with what they use in +/// turn). Only distinct names count against `cap`; past it the save is refused rather than +/// written with symbols missing. +fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Vec<(Sym, String)>, cap: usize) -> Result<()> { + let mut seen: HashSet<(Sym, String)> = HashSet::new(); + let mut blocks: Vec = Vec::new(); + while let Some((sym, name)) = wanted.pop() { + if name.is_empty() || !seen.insert((sym, name.to_ascii_uppercase())) { + continue; + } + if seen.len() > cap { + return Err(bad("refclose", format!("the edit uses more than {cap} symbols; the xref is not written (REFCLOSE Discard ends the edit)"))); + } + if sym == Sym::Block { + blocks.push(name.clone()); + } + bring_symbol(host, src, prefix, sym, &name, &mut wanted)?; + } + // A block the written objects name that the drawing still lacks (an xref of the host, added + // with REFSET) would leave a reference to nothing in the file: refused, nothing written. Only + // names the edit brings in are checked: a reference the file already had (named `xref|name` + // in the host) is written as it was, even to a block the file doesn't define. + if let Some(name) = blocks.iter().find(|n| src.block(n).is_none()) { + return Err(unwritable_block(name)); + } + Ok(()) +} + +/// The refusal for a block the edit uses that the xref's drawing can't take. +fn unwritable_block(name: &str) -> crate::EngineError { + bad( + "refclose", + format!( + "the edit uses block \"{name}\", which can't be written into the xref's drawing (an xref of this drawing, or a block it doesn't define); remove it from the working set (REFSET) or use REFCLOSE Discard" + ), + ) +} + +/// The blocks dimension style `t` of `host` draws its arrowheads with: the names `host` defines as +/// blocks (a built-in arrowhead name is drawn in code, not a block), as the xref's drawing names +/// them. +fn arrow_blocks(host: &Drawing, t: &cadcraft_doc::DimStyle, prefix: &str) -> Vec<(Sym, String)> { + [&t.arrow_block, &t.arrow_block1, &t.arrow_block2, &t.leader_arrow_block] + .into_iter() + .map(|n| n.trim()) + // A name with the xref's prefix is a block of the xref's own file: nothing to bring, and + // its bare name must not be taken for a block (or an xref) of the host with that name. + .filter(|n| !n.is_empty() && !load::has_prefix(n, prefix) && host.block(n).is_some()) + .map(|n| (Sym::Block, n.to_string())) + .collect() +} + +/// Whether block `h` of the host defines what block `s` of the xref's drawing does: the same base +/// point and the same objects in the same order, each compared whole (attribute definitions +/// included) but for its own handle, with the symbols it uses named as the xref's drawing names +/// them. The names its objects use are put in `uses`. One pass over the two definitions, copying +/// one object at a time; it stops at the first difference. +fn same_definition(h: &Block, s: &Block, prefix: &str, uses: &mut Vec<(Sym, String)>) -> bool { + h.base == s.base + && h.entities.len() == s.entities.len() + && h.entities.iter().zip(s.entities.iter()).all(|(a, b)| { + let mut a = (**a).clone(); + a.handle = b.handle; + rename_into_source(&mut a, prefix, uses); + a == **b + }) +} + +/// Copy host symbol `name` of kind `sym` into `src` when `src` lacks it, queueing what it uses. +/// Refused when `src` defines a block `name` differently from the host: the objects written would +/// show the file's block, not the one they showed in the host. +fn bring_symbol(host: &Drawing, src: &mut Drawing, prefix: &str, sym: Sym, name: &str, wanted: &mut Vec<(Sym, String)>) -> Result<()> { + let name = name.to_string(); + { + match sym { + Sym::Layer => { + if name != "0" + && src.layer(&name).is_none() + && let Some(l) = host.layer(&name) + { + wanted.push((Sym::Linetype, l.linetype.clone())); + src.layers.push(l.clone()); + } + } + Sym::Linetype => { + let builtin = ["ByLayer", "ByBlock", "Continuous"].iter().any(|n| n.eq_ignore_ascii_case(&name)); + if !builtin + && src.linetype(&name).is_none() + && let Some(t) = host.linetype(&name) + { + // The text styles its text elements are drawn in. + wanted.extend(t.pattern.iter().filter_map(|e| e.style.clone()).map(|s| (Sym::Style, s))); + src.linetypes.push(t.clone()); + } + } + Sym::Style => { + if src.text_style(&name).is_none() + && let Some(t) = host.text_style(&name) + { + src.text_styles.push(t.clone()); + } + } + Sym::DimStyle => { + if src.dim_style(&name).is_none() + && let Some(t) = host.dim_style(&name) + { + wanted.push((Sym::Style, t.text_style.clone())); + wanted.extend(arrow_blocks(host, t, prefix)); + src.dim_styles.push(t.clone()); + } + } + Sym::Block => { + let Some(b) = host.block(&name) else { return Ok(()) }; + // An xref of the host can't go into the file, whether or not the file has a block + // of that name: with one, the reference would be written and show the file's block. + if b.xref_path.is_some() { + return Err(unwritable_block(&name)); + } + if let Some(have) = src.block(&name) { + // The same block (its objects may name blocks that differ in turn): kept. + let mut uses = Vec::new(); + if !same_definition(b, have, prefix, &mut uses) { + return Err(bad( + "refclose", + format!( + "the edit uses block \"{name}\" of this drawing, and the xref's drawing defines a different block of that name; remove its references from the working set (REFSET) or use REFCLOSE Discard" + ), + )); + } + wanted.extend(uses); + } else { + let mut nb = (**b).clone(); + let mut store = EntityStore::new(); + for e in b.entities.iter() { + let mut e = (**e).clone(); + e.handle = src.new_handle(); + rename_into_source(&mut e, prefix, wanted); + store.push(e); + } + nb.entities = store; + src.blocks.insert(nb.name.clone(), Arc::new(nb)); + } + } + Sym::MLeaderStyle => { + let have = src.mleader_styles.iter().any(|t| t.name.eq_ignore_ascii_case(&name)); + if !have && let Some(t) = host.mleader_styles.iter().find(|t| t.name.eq_ignore_ascii_case(&name)) { + wanted.push((Sym::Style, t.text_style.clone())); + src.mleader_styles.push(t.clone()); + } + } + Sym::TableStyle => { + let have = src.table_styles.iter().any(|t| t.name.eq_ignore_ascii_case(&name)); + if !have && let Some(t) = host.table_styles.iter().find(|t| t.name.eq_ignore_ascii_case(&name)) { + wanted.extend(t.cell_styles.iter().map(|c| (Sym::Style, c.text_style.clone()))); + src.table_styles.push(t.clone()); + } + } + } + } + Ok(()) +} + +/// Replace the xref's file (`file` as the xref names it, `real` the file it leads to) by `bytes`, +/// the way SAVE replaces a drawing: the old file is kept as its `.bak` (when ISAVEBAK is on) +/// ([`crate::cmd::file::backup_path`]: `site.dwg` as `site.bak`, `site.dxf` as `site.dxf.bak`), +/// and the new one goes into a fresh, exclusively created temporary file that is renamed over +/// `real` ([`crate::atomic_write`]). A symbolic link planted at the temporary or backup path is +/// never written through, and a link at `real` is replaced, not followed. Returns the backup's +/// path (`None` when none was kept). +fn replace_file(file: &std::path::Path, real: &std::path::Path, bytes: &[u8]) -> std::result::Result, String> { + #[cfg(target_arch = "wasm32")] + { + let _ = (file, real, bytes); + Err("files are not available on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + // As SAVE: ISAVEBAK off keeps no backup. + let kept = if crate::autosave::isavebak() { + crate::cmd::file::backup(real) + .map_err(|e| format!("the backup copy of {} could not be written ({e}); it is unchanged", file.display()))? + } else { + false + }; + let permissions = std::fs::symlink_metadata(real).ok().filter(std::fs::Metadata::is_file).map(|m| m.permissions()); + crate::atomic_write::write_atomic_with(real, permissions, |f| std::io::Write::write_all(f, bytes)) + .map_err(|e| format!("{} can't be replaced: {e}; it is unchanged", file.display()))?; + // Named beside the file as the xref names it, unless that name is itself a link. + let shown = if std::fs::symlink_metadata(file).is_ok_and(|m| m.file_type().is_symlink()) { real } else { file }; + Ok(kept.then(|| crate::cmd::file::backup_path(shown).to_string_lossy().into_owned())) + } +} + // ---------------- while editing ---------------- /// After a command ran: objects it created join the working set, and a command that changed @@ -353,7 +1073,7 @@ pub(crate) fn after_command(s: &mut Session, before: &Arc, id: &str) -> .iter() .any(|store| store.iter().any(|e| !owned.contains(&e.handle) && !st.doc.entity(e.handle).is_some_and(|a| Arc::ptr_eq(a, e)))); if touched { - st.doc = before.clone(); + st.restore_drawing(before.clone()); return Some("Only the working set can be edited during REFEDIT (REFSET adds objects, REFCLOSE ends the edit).".into()); } let seed = before.handseed; @@ -369,6 +1089,18 @@ pub(crate) fn after_command(s: &mut Session, before: &Arc, id: &str) -> None } +/// Why UNDO stops before bringing back `snap` while the drawing is `cur`: `snap` holds an edit of +/// an xref in place whose file REFCLOSE Save has written since (`cur` shows the xref loaded again +/// from the file as written, so its stamp is no longer the one the edit began with). Brought back, +/// that edit could never be saved (its file changed since it began) and the drawing would show the +/// xref as it was before the save. A discarded edit leaves the xref's stamp as it was: it comes +/// back with UNDO as any other step. +pub(crate) fn undo_barrier(cur: &Drawing, snap: &Drawing) -> Option { + let x = snap.refedit.as_ref()?.xref.as_ref()?; + let now = cur.block(&x.xref).and_then(|b| b.xref_stamp); + (now != x.stamp).then(|| format!("The reference edit was saved to {}, so it can't be undone; the drawing stays as saved.", x.file)) +} + /// Whether `h` may not be edited because a reference is being edited and it is not in the working set. pub(crate) fn locked(d: &Drawing, h: Handle) -> bool { d.refedit.as_ref().is_some_and(|r| !r.is_working(h)) @@ -376,6 +1108,94 @@ pub(crate) fn locked(d: &Drawing, h: Handle) -> bool { // ---------------- interactive ---------------- +/// REFEDIT at the command line: "Select reference", then "Select nesting level [OK/Next]" when +/// the reference has others nested in it. +#[derive(Default)] +struct RefeditM { + sel: SelectPhase, + picked: Option, + levels: Vec<(Vec, String)>, + at: usize, +} + +impl RefeditM { + fn picked(&mut self, s: &mut Session, hs: &[Handle]) -> Result { + let d = s.doc()?; + let Some(h) = hs.iter().copied().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))) else { + s.echo("Select a block or xref reference."); + self.sel = SelectPhase::single(); + return Ok(Step::Continue); + }; + self.levels = level_list(d, h)?; + self.picked = Some(h); + if self.levels.len() > 1 { + self.echo_level(s); + return Ok(Step::Continue); + } + self.finish(s) + } + fn echo_level(&self, s: &mut Session) { + if let Some((path, name)) = self.levels.get(self.at) { + s.echo(format!("Reference name: {name}{}", if path.is_empty() { String::new() } else { format!(" (nested {} deep)", path.len()) })); + } + } + fn finish(&mut self, s: &mut Session) -> Result { + let Some(h) = self.picked else { return Ok(Step::Cancel) }; + let path = self.levels.get(self.at).map(|(p, _)| hexes(p.iter().copied())).unwrap_or_default(); + let r = run_refedit(s, &json!({ "handle": h.hex(), "path": path }))?; + let n = r["working"].as_array().map_or(0, Vec::len); + s.set_selection(Vec::new()); + s.echo(format!("{n} object(s) in the working set. Use REFCLOSE to save or discard the changes.")); + Ok(Step::Done) + } +} + +impl Interactive for RefeditM { + fn name(&self) -> &'static str { + "REFEDIT" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + self.sel.single = true; + if self.sel.done { + let hs = self.sel.picked.clone(); + return self.picked(s, &hs); + } + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + if self.picked.is_none() { + return Prompt::new("Select reference", Accept::SELECT); + } + Prompt::new("Select nesting level", Accept::TEXT).kw(&["OK", "Next"]).default("Next") + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + if self.picked.is_none() { + return match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.picked(s, &hs), + }; + } + let k = match &i { + Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(), + Input::Enter => "next".into(), + _ => return Ok(Step::Continue), + }; + if k.starts_with('o') { + return self.finish(s); + } + if k.starts_with('n') { + self.at = (self.at + 1) % self.levels.len().max(1); + self.echo_level(s); + } + Ok(Step::Continue) + } +} + #[derive(Default)] enum RStage { #[default] @@ -464,8 +1284,39 @@ impl Interactive for RefcloseM { _ => return Ok(Step::Cancel), }; let r = close(s, save)?; - s.echo(if save { "Reference changes saved." } else { "Reference changes discarded." }); - let _ = r; + s.echo(match (save, r.get("file").and_then(Value::as_str)) { + (true, Some(f)) => match r["backup"].as_str() { + Some(b) => format!("Reference changes saved to {f} (the previous file is kept as {b})."), + None => format!("Reference changes saved to {f}."), + }, + (true, None) => "Reference changes saved.".to_string(), + (false, _) => "Reference changes discarded.".to_string(), + }); Ok(Step::Done) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Review of #2355: the budget counted every queued reference, so a host-only layer queued + /// first was skipped once enough repeated ones followed it, and the file was written without + /// it. Only distinct names count now, and running out refuses the save. + #[test] + fn repeated_symbols_do_not_use_up_the_budget() { + let mut host = Drawing::new_metric(); + host.layers.push(cadcraft_doc::Layer { name: "Added".into(), ..cadcraft_doc::Layer::default() }); + let mut wanted = vec![(Sym::Layer, "Added".to_string())]; + for _ in 0..1000 { + wanted.push((Sym::Layer, "0".into())); + wanted.push((Sym::Linetype, "ByLayer".into())); + } + // Distinct: ByLayer, 0, Added and its linetype. + let mut src = Drawing::new_metric(); + bring_symbols(&host, &mut src, "x|", wanted.clone(), 4).unwrap(); + assert!(src.layer("Added").is_some(), "the layer queued first is copied"); + let mut src = Drawing::new_metric(); + assert!(bring_symbols(&host, &mut src, "x|", wanted, 2).is_err(), "past the budget the save is refused"); + } +} diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index e543b34e7..9d1def4f8 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -134,7 +134,7 @@ struct Ctx { } /// The folder of the host drawing at `host` (a file path). -fn folder(host: Option<&Path>) -> Option { +pub(crate) fn folder(host: Option<&Path>) -> Option { let p = host?.parent()?; Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() }) } @@ -293,8 +293,17 @@ fn case_insensitive(p: &Path) -> Result, ()> { Ok(out.is_file().then_some(out)) } +/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the +/// binary DXF sentinel). +const HEAD_BYTES: usize = 4096; + /// Read a drawing file through the host's io hooks, counting its bytes against the load's total. -fn read(file: &Path, cx: &mut Ctx) -> Result { +/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them +/// even when the path is pointed at another file meanwhile; `None` when the file changed while it +/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded. +/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a +/// binary DXF) describes the same read. +fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option, Vec), String> { let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?; #[cfg(not(target_arch = "wasm32"))] { @@ -303,7 +312,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes); let limit = MAX_XREF_BYTES.min(left); let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?; - let len = f.metadata().map_err(|e| e.to_string())?.len(); + let meta = f.metadata().map_err(|e| e.to_string())?; + let len = meta.len(); + let before = stamp_of(&meta); let too_big = || { if limit < MAX_XREF_BYTES { format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20) @@ -321,7 +332,10 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { return Err(too_big()); } cx.bytes = cx.bytes.saturating_add(n); - (hooks.read)(&bytes, &file.to_string_lossy()) + let after = f.metadata().ok().as_ref().and_then(stamp_of); + let read_as = before.filter(|b| Some(*b) == after); + let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec(); + Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head)) } #[cfg(target_arch = "wasm32")] { @@ -330,6 +344,33 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { } } +/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's +/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the +/// system gives it: counted from 1970, a file dated before then would have none and always look +/// changed. +pub(crate) type Stamp = (u64, std::time::SystemTime); + +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn stamp_of(m: &std::fs::Metadata) -> Option { + Some((m.len(), m.modified().ok()?)) +} + +/// The [`Stamp`] of the file at `file` now. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn stamp(file: &Path) -> Option { + stamp_of(&std::fs::metadata(file).ok()?) +} +#[cfg(target_arch = "wasm32")] +pub(crate) fn stamp(_file: &Path) -> Option { + None +} + +/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the +/// first bytes of the bytes read (see [`read`]). +pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option, Vec), String> { + read(file, &mut Ctx::new(None)) +} + /// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's /// own path. pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec { @@ -393,8 +434,14 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: & let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) }; clear(d, &key); let (status, detail) = match fetch(&path, host, chosen, cx, depth) { - Ok((x, file)) => match import(d, &key, &x, cx) { - Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()), + Ok((x, file, read_as)) => match import(d, &key, &x, cx) { + Ok(()) => { + // This drawing's own baseline: another drawing loading the file later doesn't move it. + if let Some(b) = d.blocks.get_mut(&key) { + Arc::make_mut(b).xref_stamp = read_as; + } + (XrefStatus::Loaded, file.to_string_lossy().into_owned()) + } Err(e) => { // Whatever made it in before the failure goes again. A fetch that failed imported // nothing, so it doesn't pay for a second scan of the block table. @@ -409,7 +456,13 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: & } /// Read the drawing referenced as `path` and load its own attached xrefs into it. -fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> { +fn fetch( + path: &str, + host: Option<&Path>, + chosen: bool, + cx: &mut Ctx, + depth: usize, +) -> Result<(Drawing, PathBuf, Option), (XrefStatus, String)> { let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string()); if depth >= MAX_BLOCK_DEPTH { return Err(unresolved("xrefs are nested too deeply")); @@ -423,7 +476,7 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi return Err(unresolved("too many referenced files")); } cx.files += 1; - let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?; + let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?; cx.chain.push(canon); let nested: Vec = x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect(); @@ -434,15 +487,20 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi } } cx.chain.pop(); - Ok((x, file)) + Ok((x, file, read_as)) +} + +/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model +/// space and every block's. +pub(crate) fn object_count(x: &Drawing) -> usize { + x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len())) } /// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its /// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the /// host's settings, so layer changes survive a reload). fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> { - let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len())); - cx.objects = cx.objects.saturating_add(count); + cx.objects = cx.objects.saturating_add(object_count(x)); if cx.objects > MAX_XREF_OBJECTS { return Err(format!("more than {MAX_XREF_OBJECTS} objects")); } diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index f8e1de60d..367fcacd5 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -79,17 +79,27 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result> { let defs = s.clipboard_source.as_ref().map(|c| c.defs.clone()); let space = s.space(); let d = s.doc_mut()?; - let renames = defs.map(|x| merge(d, &x)).unwrap_or_default(); + let renames = defs.as_ref().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) } @@ -270,8 +280,10 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing { d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into(); d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into(); d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name); - d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name); + d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name).into(); d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect(); + let ent_handles: HashSet = 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 } diff --git a/crates/engine/src/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 84842c5cb..7f7259011 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -37,6 +37,9 @@ pub(crate) fn justify_prompt(two_points: bool) -> Prompt { pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind { let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()); + // New text takes Backwards and Upside down from its style, as AutoCAD's does; later style + // changes don't change them. + let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(&style)).map_or((false, false), |t| (t.backwards, t.upside_down)); let (h, v) = j; let left = h == HAlign::Left && v == VAlign::Baseline; EntityKind::Text(Text { @@ -50,6 +53,8 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio style, halign: h, valign: v, + backwards, + upside_down, }) } @@ -92,6 +97,7 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result { line_spacing: f64_or(p, "lineSpacing", 1.0), line_spacing_exact: bool_or(p, "lineSpacingExact", false), columns: crate::cmd::mtext_opts::json_columns(p, height, width)?, + background: None, }); added(s.add_entity(k)?) } diff --git a/crates/engine/src/cmd/draw2/rect.rs b/crates/engine/src/cmd/draw2/rect.rs index 2017af914..fa0d9fac6 100644 --- a/crates/engine/src/cmd/draw2/rect.rs +++ b/crates/engine/src/cmd/draw2/rect.rs @@ -273,7 +273,7 @@ impl Interactive for RectM2 { let msg = if self.center { "Specify center point for rectangle" } else { "Specify first corner point" }; Prompt::new(msg, Accept::POINT).kw(&["Chamfer", "CEnter", "Elevation", "Fillet", "Thickness", "Width"]) } - Some(p) => Prompt::new("Specify other corner point", Accept::POINT).kw(&["Area", "Dimensions", "Rotation"]).corner(p), + Some(p) => Prompt::new("Specify other corner point", Accept::POINT).kw(&["Area", "Dimensions", "Rotation"]).corner(p).xy(), } } /// Consumes one input: option keywords (`Center` only switches the first point's meaning diff --git a/crates/engine/src/cmd/draw2/revcloud.rs b/crates/engine/src/cmd/draw2/revcloud.rs index 3a75b30c2..2fd283a58 100644 --- a/crates/engine/src/cmd/draw2/revcloud.rs +++ b/crates/engine/src/cmd/draw2/revcloud.rs @@ -26,6 +26,10 @@ 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> { let mut pts: Vec = Vec::new(); @@ -69,7 +73,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 { -0.5 } else { 0.5 }; + let b = if reverse { -CLOUD_BULGE } else { CLOUD_BULGE }; Some(out.into_iter().map(|p| PolyVertex::with_bulge(p, b)).collect()) } diff --git a/crates/engine/src/cmd/draworder.rs b/crates/engine/src/cmd/draworder.rs index 8020dc520..d75f4fa12 100644 --- a/crates/engine/src/cmd/draworder.rs +++ b/crates/engine/src/cmd/draworder.rs @@ -63,19 +63,11 @@ enum Order { Under, } -/// 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 { - let space = s.space(); - let d = s.doc_mut()?; - let Some(st) = d.space_mut(&space) else { return Ok(0) }; +fn reorder_store(st: &mut cadcraft_doc::EntityStore, hs: &[Handle], order: Order) -> usize { let index: HashMap = 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 = 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 { @@ -87,6 +79,29 @@ fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Res 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 { + 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 = 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 = 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 { @@ -181,15 +196,23 @@ impl Annot { } } -/// Every object of the current space that `keep` accepts, in draw order. -fn of_kind(s: &Session, keep: impl Fn(&EntityKind) -> bool) -> Result> { - 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()) +/// 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 { + let d = s.doc_mut()?; + let mut total = 0; + // Model space + let hs: Vec = 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 = layout.entities.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect(); + total += reorder_store(&mut layout.entities, &hs, order); + } + Ok(total) } fn annotations_to_front(s: &mut Session, which: Annot) -> Result { - let hs = of_kind(s, |k| which.matches(k))?; - let n = reorder(s, &hs, Order::Front, &[])?; + let n = reorder_all_spaces(s, Order::Front, |k| which.matches(k))?; Ok(json!({ "moved": n, "message": format!("{n} object(s) brought to front.") })) } @@ -208,8 +231,7 @@ fn run_texttofront(s: &mut Session, p: &Value) -> Result { } fn run_hatchtoback(s: &mut Session, _p: &Value) -> Result { - let hs = of_kind(s, |k| matches!(k, EntityKind::Hatch(_)))?; - let n = reorder(s, &hs, Order::Back, &[])?; + let n = reorder_all_spaces(s, Order::Back, |k| matches!(k, EntityKind::Hatch(_)))?; Ok(json!({ "moved": n, "message": format!("{n} hatch object(s) sent to back.") })) } diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index f7a2fbc65..2793631ca 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { 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), version?: 2000|2004|2007|2010|2013|2018 (DXF and DWG; default: the drawing's own), binary?: false (DXF only)} → {format, bytes, version? (DXF and DWG), path? | data, warnings?: what an image draws short of the drawing}") .noundo(), CommandSpec::new("preview", "Plot Preview", run_preview) .menu(&["File", "Plot Preview"]) @@ -57,7 +57,7 @@ pub fn specs() -> Vec { CommandSpec::new("pdfbook", "Sheet Books to PDF...", run_pdfbook) .menu(&["File", "Sheet Books to PDF..."]) .alias(&["printpdf", "pdfb"]) - .params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (ISO A-series, either orientation) they match") + .params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (any standard size — ISO, JIS, ANSI — either orientation) they match") .noundo(), CommandSpec::new("attach", "Attach", |s, p| match str_param(p, "path").map(extension) { Some(e) if super::image::is_image_ext(&e) => super::image::run_imageattach(s, p), @@ -123,7 +123,23 @@ fn run_export(s: &mut Session, p: &Value) -> Result { 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))?; + // DXF and DWG take SAVEAS's version and binary options; the drawing keeps its own version and + // name (an export is not a save). + let opts = super::file::save_options("export", p)?; + let drawing_format = matches!(format.as_str(), "dxf" | "dwg"); + if opts.version.is_some() && !drawing_format { + return Err(bad("export", "`version` applies to DXF and DWG files only")); + } + if opts.binary && format != "dxf" { + return Err(bad("export", "`binary` applies to DXF files only")); + } + let (bytes, notes) = if opts.version.is_some() || opts.binary { + let w = + super::file::write_as().ok_or_else(|| bad("export", "exporting at a chosen version or as binary DXF is not available in this build"))?; + (w(s.doc()?, &file, &opts).map_err(|e| bad("export", e))?, Vec::new()) + } else { + super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))? + }; let folder = path.and_then(super::file::new_folder); let mut r = match path { Some(path) => { @@ -132,8 +148,11 @@ fn run_export(s: &mut Session, p: &Value) -> Result { } None => json!({ "data": base64_encode(&bytes), "format": format, "bytes": bytes.len() }), }; + if let (Some(v), Some(o)) = (opts.version, r.as_object_mut()) { + o.insert("version".into(), json!(v.year())); + } super::file::report_new_folder(s, &mut r, folder); - super::file::report_loss(s, &mut r, &file); + super::file::report_loss(s, &mut r, &file, opts.version); super::file::report_notes(s, &mut r, notes); Ok(r) } @@ -573,7 +592,8 @@ struct Frame { landscape: bool, } -/// The ISO/ANSI paper a frame of `w` x `h` mm fits (either orientation), and whether it is landscape. +/// The standard paper (ISO, JIS or ANSI) a frame of `w` x `h` mm fits (either orientation), and whether +/// it is landscape. fn paper_for(w: f64, h: f64) -> Option<(&'static str, bool)> { cadcraft_render::PAPER_SIZES.iter().find_map(|p| { let (pw, ph) = (p.width_mm, p.height_mm); @@ -878,6 +898,17 @@ mod tests { let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "A4", "landscape": true, "width": 600 })).unwrap(); assert_eq!((r["layout"].as_str(), r["width"].as_u64(), r["height"].as_u64()), (Some("Layout1"), Some(600), Some(424))); assert_eq!(r["paper"], "ISO A4 (210.00 x 297.00 MM)"); + // The bare B5 is the ISO size it always was; the JIS sheet needs its explicit name, and the + // Japanese postcards resolve by their names and their Japanese spelling. + let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5", "landscape": false, "width": 400 })).unwrap(); + assert_eq!(r["paper"], "ISO B5 (176.00 x 250.00 MM)"); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(568))); + let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5 (JIS)", "landscape": false, "width": 400 })).unwrap(); + assert_eq!(r["paper"], "JIS B5 (182.00 x 257.00 MM)"); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(565))); + let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "はがき", "landscape": false, "width": 200 })).unwrap(); + assert_eq!(r["paper"], "Japanese Postcard (100.00 x 148.00 MM)"); + assert_eq!(r["height"], 296); assert!(s.execute("preview", &json!({ "layout": "Nope" })).is_err()); assert!(s.execute("preview", &json!({ "paper": "Nope" })).is_err()); for p in [json!({ "scale": -1, "fit": false }), json!({ "scale": 1e-300, "fit": false }), json!({ "width": -5 }), json!({ "width": 1e30 })] { diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9a21f03fb..212216b97 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -108,6 +108,47 @@ pub fn entity_codec() -> Option<&'static EntityCodec> { CODEC.get() } +/// One record written after an entity's own, at `index` (an INSERT's ATTRIB, then its SEQEND): +/// its type name and the groups of its record, without its `0` group. AutoLISP's `entnext` and +/// `entget` reach an INSERT's attributes through it, one record at a time (the attributes have no +/// handle of their own in the drawing). Installed by the app with the DXF writer, a lower layer; +/// optional, so a host without one simply has no such records ([`EntityCodec`] is unchanged). +pub type EntitySubRecord = fn(&Drawing, &cadcraft_doc::Entity, usize) -> Option<(String, Vec)>; + +static SUB_RECORD: OnceLock = OnceLock::new(); + +// This thread hid the optional provider ([`without_entity_sub_record`], tests only). +#[cfg(test)] +thread_local! { + static SUB_RECORD_HIDDEN: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub fn set_entity_sub_record(f: EntitySubRecord) { + let _ = SUB_RECORD.set(f); +} +pub fn entity_sub_record() -> Option { + #[cfg(test)] + if SUB_RECORD_HIDDEN.with(std::cell::Cell::get) { + return None; + } + SUB_RECORD.get().copied() +} + +/// Run `f` as a host that did not install [`EntitySubRecord`]: `entnext` must walk the drawing's +/// entities as it did before the provider existed. Tests only. +#[cfg(test)] +pub(crate) fn without_entity_sub_record(f: impl FnOnce() -> R) -> R { + struct Unhide; + impl Drop for Unhide { + fn drop(&mut self) { + SUB_RECORD_HIDDEN.with(|h| h.set(false)); + } + } + SUB_RECORD_HIDDEN.with(|h| h.set(true)); + let _unhide = Unhide; + f() +} + /// The drawing's non-graphic records as written (tables, BLOCK records, objects): each one's /// type, groups after the type and role (see [`cadcraft_doc::foreign::ForeignKey`]). AutoLISP's /// `namedobjdict`, `tblobjname` and `handent` of non-graphic objects read them (installed by the @@ -258,7 +299,7 @@ fn version_list() -> String { /// The `version` and `binary` parameters of a save: a version is a year (2018 or "2018"), "R2018" /// or an `$ACADVER` code ("AC1032"). -fn save_options(cmd: &str, p: &Value) -> Result { +pub(super) fn save_options(cmd: &str, p: &Value) -> Result { let version = match p.get("version") { None | Some(Value::Null) => None, Some(v) => { @@ -326,6 +367,10 @@ pub fn specs() -> Vec { .params("{path} | {data: base64, name} → {index, entities?, warnings: what reading left out}") .enabled(always) .noundo(), + CommandSpec::new("whohas", "Who Has", run_whohas) + .params("{path?: a drawing file (default: the current drawing's)} → {path, holder: {user, host, instance, opened} | null}") + .enabled(always) + .noundo(), CommandSpec::new("close", "Close", run_close).menu(&["File", "Close"]).key("Cmd+W").params("{index?}").noundo(), CommandSpec::new("closeall", "Close All", run_closeall).menu(&["File", "Close All"]).enabled(always).noundo(), CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?}").noundo(), @@ -552,6 +597,36 @@ fn run_open(s: &mut Session, p: &Value) -> Result { Ok(opened(s, i, false)) } +/// WHOHAS: who has a drawing open, from its lock file ([`crate::drawlock`]): the current +/// drawing's, or the file `path`. +fn run_whohas(s: &mut Session, p: &Value) -> Result { + // Left out (or null): the current drawing's file; anything but text is an error, not the + // current drawing asked about by mistake. + let path = match p.get("path") { + None | Some(Value::Null) => s.state()?.path.clone().ok_or_else(|| bad("whohas", "the drawing has no file yet; pass `path`"))?, + Some(Value::String(path)) => path.clone(), + Some(_) => return Err(bad("whohas", "`path` must be a file path")), + }; + // The web has no lock files to look at: an error, not "nobody has it open". + #[cfg(target_arch = "wasm32")] + { + let _ = path; + Err(bad("whohas", "drawing locks are not available on the web")) + } + #[cfg(not(target_arch = "wasm32"))] + { + // Under the automation roots, the lock beside a file outside them is not looked at. + crate::file_access::check_read(&path).map_err(|e| bad("whohas", e))?; + let holder = crate::drawlock::holder(std::path::Path::new(&path)); + let msg = match &holder { + Some(h) => format!("{} is open by {}.", file_name(&path), h.describe()), + None => format!("Nobody has {} open (no current lock).", file_name(&path)), + }; + s.echo(msg); + Ok(json!({ "path": path, "holder": holder })) + } +} + /// `close [index]`: cancel the running command, remove the drawing (default: active), keep the active index valid, and bump the document epoch; an unknown index is an error. fn run_close(s: &mut Session, p: &Value) -> Result { let i = p.get("index").and_then(Value::as_u64).map(|i| i as usize).unwrap_or(s.active); @@ -819,12 +894,13 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io:: /// ([`crate::atomic_write::write_atomic_with`]). Nothing /// to keep when there is no file yet. A file that doesn't look like a drawing /// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone. +/// Returns whether the backup was written. Also used for an xref REFEDIT writes back. #[cfg(not(target_arch = "wasm32"))] -fn backup(path: &std::path::Path) -> std::io::Result<()> { +pub(crate) fn backup(path: &std::path::Path) -> std::io::Result { let mut src = match std::fs::File::open(path) { Ok(f) if f.metadata()?.is_file() => f, - Ok(_) => return Ok(()), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Ok(_) => return Ok(false), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), Err(e) => return Err(e), }; let (head, tail, len) = ends(&mut src)?; @@ -833,7 +909,7 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> { // the roots (or to another computer) isn't looked at. if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) { log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display()); - return Ok(()); + return Ok(false); } // The backup is no more readable than the drawing, nor than the .bak it replaces (a private // 0600 drawing or .bak stays private). The mode is set as the new file is created, so a @@ -859,7 +935,8 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> { } std::io::Write::write_all(out, &head)?; std::io::copy(&mut src, out).map(|_| ()) - }) + })?; + Ok(true) } /// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps @@ -1090,10 +1167,10 @@ pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::co } /// Report what the file `path`, just written from the active document (what EXPORT writes: the -/// block while the Block Editor is open) at its own version, left out. -pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) { +/// block while the Block Editor is open) at version `asked` (else its own), left out. +pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str, asked: Option) { let Ok(d) = s.doc() else { return }; - let version = own_version(d, path); + let version = asked.unwrap_or_else(|| 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); diff --git a/crates/engine/src/cmd/gripcmds.rs b/crates/engine/src/cmd/gripcmds.rs index a7ba2cdd6..51817c61c 100644 --- a/crates/engine/src/cmd/gripcmds.rs +++ b/crates/engine/src/cmd/gripcmds.rs @@ -1,7 +1,7 @@ //! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`). use cadcraft_doc::{Entity, EntityKind, Handle}; -use cadcraft_geom::{Mat3, Vec2}; +use cadcraft_geom::{Mat3, Vec2, Vec3}; use serde_json::{Value, json}; use super::curves; @@ -78,6 +78,70 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result { Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::>() })) } +/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the +/// entity stores a 3D position for that grip. +pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option { + let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) { + (cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z, + _ => t.align_pt.unwrap_or(t.insert).z, + }; + let z = match kind { + EntityKind::Line(l) => match index { + 0 => Some(l.a.z), + 1 => Some((l.a.z + l.b.z) * 0.5), + 2 => Some(l.b.z), + _ => None, + }, + EntityKind::Point(p) => (index == 0).then_some(p.p.z), + EntityKind::Circle(c) => (index < 5).then_some(c.center.z), + EntityKind::Arc(a) => (index < 4).then_some(a.center.z), + EntityKind::Ellipse(e) => (index < 5).then_some(e.center.z), + EntityKind::LwPolyline(p) => (index < kind.grips().len()).then_some(p.elevation), + EntityKind::Polyline3d(p) => p.points.get(index).map(|q| q.z), + EntityKind::Helix(h) => match index { + 0 => Some(h.center.z), + 1 => Some(h.start_point().z), + 2 => Some(h.end_point().z), + _ => None, + }, + EntityKind::Ray(r) | EntityKind::XLine(r) => match index { + 0 => Some(r.base.z), + 1 => Some(r.base.z + r.dir.z), + _ => None, + }, + EntityKind::Text(t) => (index == 0).then(|| text_z(t)), + EntityKind::MText(t) => (index == 0).then_some(t.insert.z), + EntityKind::AttDef(a) => (index == 0).then(|| text_z(&a.text)), + EntityKind::Insert(i) => { + if index == 0 { + Some(i.insert.z) + } else { + i.grip_attribs().nth(index - 1).map(|(_, a)| text_z(&a.text)) + } + } + EntityKind::Dimension(d) => match index { + 0 => Some(d.p13.z), + 1 => Some(d.p14.z), + 2 => Some(d.defpt.z), + 3 => Some(d.text_mid.z), + _ => None, + }, + EntityKind::MLine(m) => m.vertices.get(index).map(|v| v.p.z), + EntityKind::Leader(l) => l.vertices.get(index).map(|v| v.z), + EntityKind::MLeader(m) => m.leaders.iter().flatten().map(|v| v.z).chain(std::iter::once(m.landing.z)).nth(index), + EntityKind::Hatch(h) => (index == 0).then_some(h.elevation), + EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.get(index).map(|c| c.z), + EntityKind::Face3d(f) => f.corners.get(index).map(|c| c.z), + EntityKind::PolyfaceMesh(m) => m.vertices.get(index).map(|v| v.z), + EntityKind::Viewport(v) => (index < 4).then_some(v.center.z), + EntityKind::Image(i) => (index == 0).then_some(i.insert.z), + EntityKind::Table(t) => (index < kind.grips().len()).then_some(t.insert.z), + EntityKind::Tolerance(t) => (index == 0).then_some(t.insert.z), + EntityKind::Spline(_) | EntityKind::Region(_) | EntityKind::Wipeout(_) | EntityKind::Unknown(_) => None, + }; + z.filter(|v| v.is_finite()) +} + /// Base point: `base`, or grip `index` of `baseHandle` (default: the first target). fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result { if let Some(b) = point_param(p, "base") { @@ -91,6 +155,27 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip")) } +/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's +/// full 3D position so the grip stays stationary in all three coordinates. +fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result { + if let Some(b) = point_param(p, "base") { + return match p.get("base").and_then(|v| v.get(2)) { + Some(z) => z.as_f64().filter(|v| v.is_finite()).map(|z| Vec3::new(b.x, b.y, z)).ok_or_else(|| bad(cmd, "`base` Z must be a number")), + None => Ok(super::modify::at_elevation(s, b)), + }; + } + let h = curves::handle_param(p, "baseHandle") + .or_else(|| hs.first().copied()) + .ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?; + let i = index_param(cmd, p)?; + let e = curves::entity(s, h)?; + let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?; + Ok(match grip_z(&e.kind, i) { + Some(z) => Vec3::new(g.x, g.y, z), + None => super::modify::at_elevation(s, g), + }) +} + fn apply(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result { let r = super::modify::transform_entities(s, hs, m, copy)?; Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) @@ -252,15 +337,18 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result { fn run_grip_scale(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; - let base = base_point(s, "grip.scale", p, &hs)?; - let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) { - Some(f) if f > 0.0 => Mat3::scale_about(base, f), + // Why: Selected grip is the SCALE base point and must remain stationary in all three coordinates. + let base = base_point_3d(s, "grip.scale", p, &hs)?; + let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) { + Some(f) if f > 1e-12 => f, Some(_) => return Err(bad("grip.scale", "factor must be positive")), None => { - mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))? + let f = base.xy().dist(point_req("grip.scale", p, "to")?); + if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) } } }; - apply(s, &hs, &m, bool_or(p, "copy", false)) + let r = super::modify::scale_entities(s, &hs, base, f, bool_or(p, "copy", false))?; + Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } fn run_grip_mirror(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/griphot.rs b/crates/engine/src/cmd/griphot.rs index 9234d981c..852ba1e5a 100644 --- a/crates/engine/src/cmd/griphot.rs +++ b/crates/engine/src/cmd/griphot.rs @@ -9,12 +9,12 @@ use std::sync::Arc; use cadcraft_doc::{Drawing, EntityKind, Handle}; -use cadcraft_geom::{Mat3, Vec2}; +use cadcraft_geom::{Mat3, Vec2, Vec3}; use super::gripcmds::stretch_grips; use super::helpers::line; use super::machines::number; -use super::modify::transform_entities; +use super::modify::{at_elevation, scale_entities, transform_entities}; use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step}; @@ -47,6 +47,7 @@ pub(crate) struct GripEdit { /// selection that the view being edited shows. targets: Vec, base: Vec2, + base_z: Option, mode: GripMode, copy: bool, ask: Ask, @@ -84,6 +85,7 @@ impl GripEdit { picking: false, targets: Vec::new(), base: Vec2::ZERO, + base_z: None, mode: GripMode::Stretch, copy: false, ask: Ask::Mode, @@ -109,6 +111,7 @@ impl GripEdit { } if self.hot.is_empty() { self.base = p; + self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i)); self.targets.push(h); self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x))); } else if !self.targets.contains(&h) { @@ -220,14 +223,7 @@ impl GripEdit { } } - /// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes). - fn edit(&mut self, s: &mut Session, to: Vec2, m: Option) -> Result { - let before = s.state()?.doc.clone(); - let changed = match (self.mode, m) { - (GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(), - (_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(), - (_, None) => return Err(other("Invalid point.")), - }; + fn finish_edit(&mut self, before: Arc, changed: bool) -> Result { if !changed { return Err(other("The objects can't be edited that way (locked, or the result would be degenerate).")); } @@ -240,6 +236,33 @@ impl GripEdit { } } + /// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes). + fn edit(&mut self, s: &mut Session, to: Vec2, m: Option) -> Result { + let before = s.state()?.doc.clone(); + let changed = match (self.mode, m) { + (GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(), + (_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(), + (_, None) => return Err(other("Invalid point.")), + }; + self.finish_edit(before, changed) + } + + /// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness. + fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result { + if !f.is_finite() || f <= 1e-12 { + return Err(other("Invalid point.")); + } + let before = s.state()?.doc.clone(); + // Why: Selected grip is the SCALE base point and must remain stationary in all three + // coordinates; fall back to ELEVATION only when the base has no stored 3D Z. + let base = match self.base_z.filter(|z| z.is_finite()) { + Some(z) => Vec3::new(self.base.x, self.base.y, z), + None => at_elevation(s, self.base), + }; + let changed = !scale_entities(s, &self.targets, base, f, self.copy)?.is_empty(); + self.finish_edit(before, changed) + } + fn mode_input(&mut self, s: &mut Session, i: Input) -> Result { match i { Input::Keyword(k) => match k.as_str() { @@ -253,9 +276,10 @@ impl GripEdit { } "Undo" => match self.undo.pop() { Some(doc) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an earlier + // one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; Ok(Step::Continue) } @@ -285,13 +309,13 @@ impl GripEdit { s.echo(self.label()); Ok(Step::Continue) } - Input::Point(p) => { - let m = self.matrix(p); - self.edit(s, p, m) - } - Input::Deferred(d) => { - let m = self.matrix(d.at); - self.edit(s, d.at, m) + Input::Point(p) | Input::Deferred(crate::snap::Deferred { at: p, .. }) => { + if self.mode == GripMode::Scale { + self.edit_scale(s, self.base.dist(p)) + } else { + let m = self.matrix(p); + self.edit(s, p, m) + } } Input::Text(t) => match self.mode { GripMode::Rotate => { @@ -300,7 +324,7 @@ impl GripEdit { } GripMode::Scale => { let f = positive(number(&t))?; - self.edit(s, self.base, Some(Mat3::scale_about(self.base, f))) + self.edit_scale(s, f) } _ => Err(other("Requires a point or an option keyword.")), }, @@ -327,14 +351,21 @@ impl GripEdit { (Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?), (Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }), (Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?), - (Ask::RefNew(_), Input::Point(p)) => { - let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?; - return self.edit(s, p, Some(m)); + (Ask::RefNew(r), Input::Point(p)) => { + if rotate { + let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?; + return self.edit(s, p, Some(m)); + } + let f = positive(Some(self.base.dist(p) / r))?; + return self.edit_scale(s, f); } (Ask::RefNew(r), Input::Text(t)) => { let v = value(&t)?; - let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) }; - return self.edit(s, self.base, Some(m)); + if rotate { + return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r))); + } + let f = positive(Some(v / r))?; + return self.edit_scale(s, f); } (_, Input::Enter) => self.ask = Ask::Mode, _ => {} @@ -429,6 +460,7 @@ impl Interactive for GripEdit { Ask::Base => match i { Input::Point(p) => { self.base = p; + self.base_z = None; self.ask = Ask::Mode; Ok(Step::Continue) } diff --git a/crates/engine/src/cmd/groups.rs b/crates/engine/src/cmd/groups.rs index 85b859f90..8fff1bceb 100644 --- a/crates/engine/src/cmd/groups.rs +++ b/crates/engine/src/cmd/groups.rs @@ -71,6 +71,35 @@ 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 = copies.iter().copied().collect(); + let mut new_groups = Vec::new(); + for g in src_groups { + let active_members: Vec = 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 = 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 { let mut seen = std::collections::HashSet::new(); diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 38e659165..43c377d82 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -7,6 +7,7 @@ pub(super) use patfile::run_patterns; pub use patfile::{PatternChoice, pattern_choices}; use cadcraft_color::Color; +use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale}; use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds}; use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon}; use serde_json::{Value, json}; @@ -17,6 +18,7 @@ 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; @@ -25,10 +27,24 @@ use super::has_doc; pub(crate) use assoc::update as refill_associative; pub use pick::{HatchPicks, PickMode}; +/// HATCH's parameters, for its JSON form and its catalog entry (the same for -HATCH). +const HATCH_PARAMS: &str = "{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close"; + pub fn specs() -> Vec { vec![ - CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))), - CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))), + // An AutoLISP routine's `(command …)` call answers HATCH's published command-line questions + // (pattern, how it is drawn, then the boundary). A person, and a script's own HATCH line, + // get the interface's dialog, or the prompts of AutoCAD's -HATCH when it is off: a script + // keeps picking the boundary first as it always has. + CommandSpec::new("hatch", "Hatch...", run_hatch) + .menu(&["Draw", "Hatch..."]) + .alias(&["h", "bh"]) + .params(HATCH_PARAMS) + .interactive(|s| Ok(Box::new(HatchM::new(s, false, s.lisp_program_input())))), + // -HATCH: the command-line form, a script's too. Its own id, so a dashed start takes its + // prompts and never the HATCH sequence above. + CommandSpec::new("-hatch", "Hatch", run_hatch).params(HATCH_PARAMS).interactive(|s| Ok(Box::new(HatchM::new(s, false, false)))), + CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true, false)))), CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))), CommandSpec::new("region", "Region", run_region) .menu(&["Draw", "Region"]) @@ -54,13 +70,15 @@ 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. -fn outlines(d: &Drawing, space: &Space, near: Option) -> (Vec>, Vec) { - let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) }; +/// 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) -> (Vec>, Vec, Vec>, f64) { 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; @@ -73,9 +91,10 @@ fn outlines(d: &Drawing, space: &Space, near: Option) -> (Vec } 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) + (out, owners, pieces, tol) } /// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous @@ -193,7 +212,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 = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite())); + let b = loops_bounds(loops); if b.is_empty() { return current; } @@ -208,6 +227,25 @@ 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 { match t.trim().to_ascii_lowercase().as_str() { @@ -224,15 +262,17 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { let space = s.space(); let ext = d.extents(&space); let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9); - let (polys, owners) = outlines(d, &space, None); + let (polys, owners, pieces, ftol) = 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, outline_tol(ext), tol); + let polys = cadcraft_geom::region::snap_ends(&polys, ftol, 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); - let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, 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 }]; // 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() { @@ -261,7 +301,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { if open_curves { let sources = handles_of(&owners, &island.sources); loops.push(HatchLoop { - vertices: island.outline.into_iter().map(PolyVertex::new).collect(), + vertices: arcs::with_arcs(&island.outline, &island.edges, &pieces, ftol), outer: false, boundary_flags: None, sources, @@ -274,7 +314,9 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result> { let d = s.doc()?; let mut loops = Vec::new(); - for h in hs { + let mut seen = std::collections::HashSet::new(); + // An object selected twice is one boundary. + for h in hs.iter().filter(|h| seen.insert(**h)) { 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] }); } @@ -300,7 +342,12 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> { struct HatchSettings { pattern: String, scale: f64, + /// HPSPACE for user-defined patterns. The entity stores it as its scale. + user_spacing: f64, angle: f64, + /// A user-defined pattern is doubled ("Double hatch area?", DXF group 77): a second family of + /// lines at right angles to the first. + double: bool, gradient: Option, associative: bool, /// HPSEPARATE: one hatch per picked point or selected object. @@ -325,10 +372,13 @@ impl HatchSettings { angle: f64_or(p, "angle", 0.0).to_radians(), centered: bool_or(p, "centered", true), }); + let scale = f64_or(p, "scale", hdr.1).max(1e-9); HatchSettings { pattern, - scale: f64_or(p, "scale", hdr.1).max(1e-9), + scale, + user_spacing: scale, angle: p.get("angle").and_then(Value::as_f64).map(f64::to_radians).unwrap_or(hdr.2), + double: false, gradient: g, associative: bool_or(p, "associative", s.doc().map_or(true, |d| d.header.i64("HPASSOC", 1) != 0)), separate: bool_or(p, "separate", s.doc().is_ok_and(|d| d.header.i64("HPSEPARATE", 0) != 0)), @@ -352,19 +402,22 @@ impl HatchSettings { loops.iter_mut().for_each(|l| l.sources.clear()); } let solid = self.gradient.is_some() || self.pattern == "SOLID"; + let user_defined = cadcraft_doc::library::is_user_pattern(&self.pattern); EntityKind::Hatch(Hatch { pattern: if self.gradient.is_some() { "SOLID".into() } else { self.pattern.clone() }, solid, origin: self.origin_mode.origin(&loops, self.origin), loops, - scale: self.scale, + scale: if user_defined { self.user_spacing } else { self.scale }, angle: self.angle, associative: self.associative, style: self.style, elevation: 0.0, gradient: self.gradient.clone(), background: None, - pattern_lines: patfile::lines_for(&self.pattern), + // A user-defined hatch's families come from its angle, spacing and double flag, not + // from a pattern definition; any other hatch takes the loaded pattern's, if any. + pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) }, }) } } @@ -429,17 +482,18 @@ fn same_loop(a: &HatchLoop, b: &HatchLoop) -> bool { }) } -/// Deduplicate boundary loops that describe the same boundary. +/// 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. fn dedup_loops(loops: &mut Vec) { let mut unique: Vec = Vec::with_capacity(loops.len()); for l in loops.drain(..) { - if let Some(existing) = unique.iter_mut().find(|u| same_loop(u, &l)) { + if let Some(existing) = unique.iter_mut().find(|u| u.outer == l.outer && 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); } @@ -520,8 +574,9 @@ fn run_boundary(s: &mut Session, p: &Value) -> Result { for q in pts { out.extend(boundary_at(s, q)?.into_iter().map(|h| h.hex())); if out.len() > MAX_BOUNDARY_OUTPUT { - // The refused call leaves no partial result behind. - s.state_mut()?.doc = before; + // The refused call leaves no partial result behind. Handles it gave out can + // be given again, so names of INSERT records end. + s.state_mut()?.restore_drawing(before); return Err(bad("boundary", format!("more than {MAX_BOUNDARY_OUTPUT} boundary polylines in one call; split the work"))); } } @@ -554,6 +609,12 @@ fn pattern_exists(name: &str) -> bool { cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some() } +/// Whether `t` answers the pattern prompt with the user-defined form (U, User, User defined), as +/// AutoCAD's HATCH takes it from an AutoLISP routine. +fn user_pattern_keyword(t: &str) -> bool { + matches!(t.trim().to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "u" | "user" | "userdefined") +} + /// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded /// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ). pub(crate) fn pattern_named(name: &str) -> Option { @@ -571,11 +632,22 @@ enum HatchAsk { Pattern, Scale, Angle, + /// The user-defined pattern's line angle: the same answer as [`HatchAsk::Angle`], asked as + /// AutoCAD's user-defined hatch asks it. + UserAngle, + /// The user-defined pattern's spacing between its lines (stored as the hatch's scale). + Spacing, + /// "Double hatch area?": a second family of lines at right angles. + Double, Origin, } struct HatchM { gradient: bool, + /// An AutoLISP routine's `(command …)` call started HATCH ([`Session::lisp_program_input`]): the + /// published command-line sequence (the pattern or the user-defined form, then its values, then the + /// objects) rather than a boundary picked first, as a person and a script's own HATCH line do. + legacy: bool, settings: HatchSettings, /// Loops by pick (one hatch each when separate). loops: Vec>, @@ -588,9 +660,10 @@ struct HatchM { } impl HatchM { - fn new(s: &Session, gradient: bool) -> Self { + fn new(s: &Session, gradient: bool, legacy: bool) -> Self { HatchM { gradient, + legacy: legacy && !gradient, settings: HatchSettings::from(s, &Value::Null, gradient), loops: Vec::new(), asking: None, @@ -620,14 +693,29 @@ impl HatchM { fn answer(&mut self, s: &mut Session, a: HatchAsk, t: &str) -> Result { match a { HatchAsk::Pattern => { - let up = match patfile::typed_file(s, t.trim()) { + let t = t.trim(); + // "?": the patterns there are, as AutoCAD lists them; the pattern is asked again. + if t == "?" { + s.echo(format!("Available patterns: {}", patfile::names().join(", "))); + return Ok(false); + } + // The user-defined form asks for its lines next, not a named pattern's scale and angle. + if self.legacy && user_pattern_keyword(t) { + self.settings.pattern = cadcraft_doc::library::USER_PATTERN.to_string(); + self.settings.user_spacing = s.last_used.hatch_spacing; + self.settings.double = s.last_used.hatch_double; + return Ok(true); + } + let up = match patfile::typed_file(s, t) { // Nothing loaded from it: the pattern is asked again. Some(n) if n.is_empty() => return Ok(false), Some(n) => n, - None => t.trim().to_ascii_uppercase(), + None => t.to_ascii_uppercase(), }; if pattern_exists(&up) { self.settings.pattern = up.clone(); + // A named pattern, SOLID included, is not the user-defined one. + self.settings.double = false; s.doc_mut()?.header.set_str("HPNAME", &up); } else { s.echo(format!("Unknown pattern {up}. Available: {}", patfile::names().join(", "))); @@ -635,16 +723,35 @@ impl HatchM { } } HatchAsk::Scale => { - let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else { return Ok(false) }; - self.settings.scale = v; + let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else { + s.echo("Value must be positive and nonzero."); + return Ok(false); + }; s.doc_mut()?.header.set_f64("HPSCALE", v); + self.settings.scale = v; } - HatchAsk::Angle => { + HatchAsk::Spacing => { + let Some(spacing) = super::machines::number(t).filter(|v| is_supported_hatch_pattern_scale(*v)) else { + s.echo(format!("Hatch spacing must be greater than {MIN_HATCH_PATTERN_SCALE:e} drawing units.")); + return Ok(false); + }; + self.settings.user_spacing = spacing; + s.last_used.hatch_spacing = spacing; + } + HatchAsk::Angle | HatchAsk::UserAngle => { // Turns the pattern from the X axis (not from ANGBASE), clockwise when ANGDIR is 1. let Some(a) = s.angle_settings().rotation(t).filter(|a| a.is_finite()) else { return Ok(false) }; self.settings.angle = a; s.doc_mut()?.header.set_f64("HPANG", a); } + HatchAsk::Double => { + self.settings.double = match t.trim().to_ascii_lowercase().as_str() { + "y" | "yes" => true, + "n" | "no" => false, + _ => return Ok(false), + }; + s.last_used.hatch_double = self.settings.double; + } HatchAsk::Origin => { let mode = match t { "Bottom left" => OriginMode::BottomLeft, @@ -660,15 +767,27 @@ impl HatchM { Ok(true) } + /// The angle prompt `msg` with the current angle as its default, offered as it would be typed. + fn angle_prompt(&self, s: &Session, msg: &str) -> Prompt { + let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0)); + // Offered as it would be typed: clockwise is positive when ANGDIR is 1. + let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle }; + Prompt::new(msg, Accept::NUMBER).default(crate::units::format_angle(a, au, ap)) + } + /// The sub-prompt that follows `a` (`taken`: its answer was taken). The Pattern option goes /// on, as AutoCAD 2024's -HATCH Properties does, from the pattern name to its scale and then /// its angle (a solid fill has neither), and asks again for a pattern or a value it refused. + /// The user-defined form goes instead to its lines' angle, their spacing and the double answer. fn after(&self, a: HatchAsk, taken: bool) -> Option { if !self.properties { return None; } match a { _ if !taken => Some(a), + HatchAsk::Pattern if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) => Some(HatchAsk::UserAngle), + HatchAsk::UserAngle => Some(HatchAsk::Spacing), + HatchAsk::Spacing => Some(HatchAsk::Double), HatchAsk::Pattern if self.settings.pattern != "SOLID" => Some(HatchAsk::Scale), HatchAsk::Scale => Some(HatchAsk::Angle), _ => None, @@ -687,6 +806,13 @@ impl Interactive for HatchM { self.settings.scale, self.settings.angle.to_degrees() )); + if self.legacy { + // A routine answers the published questions first: the pattern, how it is drawn, then the + // boundary objects. A person picks the boundary first, and so does a script's own line. + self.asking = Some(HatchAsk::Pattern); + self.properties = true; + self.selecting = true; + } Ok(Step::Continue) } fn prompt(&self, s: &Session) -> Prompt { @@ -696,17 +822,26 @@ impl Interactive for HatchM { let p = Prompt::new("Enter a pattern name", Accept::TEXT) .default(self.settings.pattern.clone()) .picker(Picker::HatchPattern(self.settings.pattern.clone())); - return if self.gradient { p } else { p.kw(&["Solid"]) }; + return if self.gradient { + p + } else if self.legacy { + // The published command-line answers: a pattern, a solid fill, the user-defined + // form, or the pattern list. + p.kw(&["?", "Solid", "User defined"]) + } else { + p.kw(&["Solid"]) + }; } Some(HatchAsk::Scale) => { return Prompt::new("Specify a scale for the hatch pattern", Accept::NUMBER).default(format!("{:.4}", self.settings.scale)); } - Some(HatchAsk::Angle) => { - let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0)); - // Offered as it would be typed: clockwise is positive when ANGDIR is 1. - let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle }; - let d = crate::units::format_angle(a, au, ap); - return Prompt::new("Specify an angle for the hatch pattern", Accept::NUMBER).default(d); + Some(HatchAsk::Angle) => return self.angle_prompt(s, "Specify an angle for the hatch pattern"), + Some(HatchAsk::UserAngle) => return self.angle_prompt(s, "Specify an angle for the hatch lines"), + Some(HatchAsk::Spacing) => { + return Prompt::new("Specify a spacing between the lines", Accept::NUMBER).default(self.settings.user_spacing.to_string()); + } + Some(HatchAsk::Double) => { + return Prompt::new("Double hatch area?", Accept::TEXT).kw(&["Yes", "No"]).default(if self.settings.double { "Y" } else { "N" }); } Some(HatchAsk::Origin) => return Prompt::new("Specify the pattern origin", Accept::POINT).kw(&ORIGIN_KW).default("Use current"), None => {} @@ -786,7 +921,10 @@ impl Interactive for HatchM { self.asking = Some(HatchAsk::Pattern); self.properties = !self.gradient; } - "sCale" => self.asking = Some(HatchAsk::Scale), + "sCale" => { + let ask = if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) { HatchAsk::Spacing } else { HatchAsk::Scale }; + self.asking = Some(ask); + } "Angle" => self.asking = Some(HatchAsk::Angle), "Origin" => self.asking = Some(HatchAsk::Origin), "sEparate" => { @@ -854,6 +992,16 @@ mod tests { d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some((e.handle.hex(), h.clone())) } else { None }).unwrap() } + /// How many hatches the drawing has. + fn hatch_count(s: &Session) -> usize { + s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Hatch(_))).count() + } + + /// The closed 4000 × 2000 polyline the older LISP routines draw before they hatch it. + fn lisp_rectangle(s: &mut Session) { + s.cmdline("(command \"_.pline\" '(0 0) '(4000 0) '(4000 2000) '(0 2000) \"_c\")").unwrap(); + } + #[test] fn hatchedit_pattern_replaces_gradient() { let mut s = Session::new(); @@ -963,6 +1111,277 @@ mod tests { s.cancel(); } + /// HATCH started by a LISP routine takes the published command-line answers in order: the + /// pattern name, its scale and angle, then the boundary objects (issue #3498). + #[test] + fn lisp_hatch_takes_pattern_scale_and_angle_then_the_objects() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(hatch_count(&s), 1); + let h = only_hatch(&s).1; + assert_eq!((h.pattern.as_str(), h.loops.len()), ("DOTS", 1)); + assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale); + assert!(h.angle.abs() < 1e-12, "{}", h.angle); + } + + /// The user-defined answer (U) asks for the lines' angle, their spacing and whether to double + /// them, as AutoCAD's HATCH does, and makes one hatch of the selection. + #[test] + fn lisp_user_defined_hatch_takes_angle_spacing_and_double() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_n\" \"_l\" \"\")").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(hatch_count(&s), 1); + let h = only_hatch(&s).1; + assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN); + assert!(!h.solid); + assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle); + assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale); + assert_eq!(h.pattern_lines.len(), 1, "not doubled"); + let absolute = h.pattern_lines[0].angle + h.angle.to_degrees(); + assert!((absolute - 45.0).abs() < 1e-9, "lines at {absolute} degrees"); + } + + /// A doubled user-defined hatch has a second family of lines at right angles to the first. + #[test] + fn a_doubled_user_defined_hatch_has_a_second_family_at_right_angles() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap(); + let h = only_hatch(&s).1; + assert_eq!(h.pattern_lines.len(), 2, "double hatch area: two families"); + let absolute = |i: usize| h.pattern_lines[i].angle + h.angle.to_degrees(); + assert!((absolute(1) - absolute(0) - 90.0).abs() < 1e-9, "{} and {}", absolute(0), absolute(1)); + } + + /// Enter at each question takes its default: the current pattern, scale and angle (the + /// user-defined form's angle, spacing and double flag too). + #[test] + fn lisp_hatch_enter_takes_the_current_values() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"\" \"\" \"\" \"_l\" \"\")").unwrap(); + let h = only_hatch(&s).1; + assert_eq!((h.pattern.as_str(), h.scale, h.angle), ("ANSI31", 1.0, 0.0)); + + // The user-defined questions too: ANSI31 is replaced, the current angle and spacing kept, + // and "Double hatch area?" defaults to No. + s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\" \"\" \"_l\" \"\")").unwrap(); + let h = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }) + .find(|h| h.pattern == cadcraft_doc::library::USER_PATTERN) + .unwrap(); + assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN); + assert!((h.scale - 1.0).abs() < 1e-12 && h.angle.abs() < 1e-12, "{} {}", h.scale, h.angle); + assert_eq!(h.pattern_lines.len(), 1, "not doubled"); + } + + #[test] + fn lisp_user_hatch_reads_spacing_and_double_across_drawings() { + let mut s = Session::new(); + s.cmdline("(setvar \"HPSPACE\" 12.5)").unwrap(); + s.cmdline("(setvar \"HPDOUBLE\" 1.0)").unwrap(); + s.new_drawing(false); + lisp_rectangle(&mut s); + + s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\")").unwrap(); + assert!(s.prompt_text().ends_with(":"), "{}", s.prompt_text()); + for answer in ["", "_l", ""] { + s.cmdline(answer).unwrap(); + } + let h = only_hatch(&s).1; + assert_eq!((h.scale, h.pattern_lines.len()), (12.5, 2)); + } + + #[test] + fn lisp_user_hatch_answers_leave_named_scale_unchanged() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(setvar \"HPSCALE\" 2.0)").unwrap(); + s.cmdline("(command \"_.hatch\" \"_u\" 45 10 \"_y\" \"_l\" \"\")").unwrap(); + + assert_eq!(crate::sysvars::get(&s, "HPSCALE"), Some(json!(2.0))); + assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(10.0))); + assert_eq!(crate::sysvars::get(&s, "HPDOUBLE"), Some(json!(1))); + } + + /// Solid asks neither a scale nor an angle, as it never has. + #[test] + fn lisp_hatch_solid_takes_no_scale_or_angle() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"_s\" \"_l\" \"\")").unwrap(); + let h = only_hatch(&s).1; + assert!(h.solid); + assert_eq!(h.pattern, "SOLID"); + } + + /// "?" lists the patterns and asks again, as AutoCAD does. + #[test] + fn lisp_hatch_question_mark_lists_patterns_and_asks_again() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"?\")").unwrap(); + assert!(s.log.iter().any(|l| l.contains("Available patterns") && l.contains("ANSI31")), "{:?}", s.log); + assert!(s.prompt_text().contains("Enter a pattern name"), "{}", s.prompt_text()); + for answer in ["ansi31", "", "", "_l", ""] { + s.cmdline(answer).unwrap(); + } + assert_eq!(only_hatch(&s).1.pattern, "ANSI31"); + } + + /// A zero, a negative number, NaN or text answers a scale or spacing question again, changing + /// nothing; the answers after it are read as the values they are, and nothing panics. + #[test] + fn a_refused_hatch_scale_or_spacing_changes_nothing() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"ansi31\" \"0\" \"-5\" \"nan\" \"x\" 2 30 \"_l\" \"\")").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let h = only_hatch(&s).1; + assert_eq!(h.pattern, "ANSI31"); + assert!((h.scale - 2.0).abs() < 1e-9, "{}", h.scale); + assert!((h.angle - 30f64.to_radians()).abs() < 1e-12, "{}", h.angle); + assert!(s.log.iter().any(|l| l.contains("Value must be positive and nonzero.")), "{:?}", s.log); + + // A spacing refused and then cancelled leaves no hatch behind. + let before = hatch_count(&s); + s.cmdline("(command \"_.hatch\" \"_u\" 45 \"0\")").unwrap(); + assert!(s.running.is_some(), "still asking for the spacing"); + assert!(s.prompt_text().contains("spacing"), "{}", s.prompt_text()); + s.cancel(); + assert_eq!(hatch_count(&s), before); + } + + #[test] + fn user_hatch_spacing_at_the_limit_is_refused_and_just_above_it_draws_and_saves() { + let limit = MIN_HATCH_PATTERN_SCALE; + let spacing = limit.next_up(); + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.execute("setvar", &json!({ "name": "HPSPACE", "value": spacing })).unwrap(); + for value in [limit / 2.0, limit] { + let result = s.execute("setvar", &json!({ "name": "HPSPACE", "value": value })); + assert!(result.unwrap_err().to_string().contains("greater than")); + } + + s.cmdline("(command \"_.hatch\" \"_u\" 0)").unwrap(); + for value in [limit / 2.0, limit] { + s.cmdline(&value.to_string()).unwrap(); + assert!(s.prompt_text().contains("Specify a spacing"), "{}", s.prompt_text()); + } + assert!(s.log.iter().any(|line| line.contains("Hatch spacing must be greater than")), "{:?}", s.log); + let default = s.current_prompt().unwrap().default.unwrap().parse::().unwrap(); + assert_eq!(default, spacing); + assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(spacing))); + for answer in ["", "_n", "_l", ""] { + s.cmdline(answer).unwrap(); + } + + // Draw a strip with room for a few lines so the sweep stays within its line budget. + let opts = cadcraft_render::Options { view: Some(Bounds2::from_points([Vec2::ZERO, Vec2::new(1.0, spacing * 5.0)])), ..Default::default() }; + let original = s.doc().unwrap(); + let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(original).as_bytes()).unwrap(); + for drawing in [original, &reopened] { + let hatch = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap(); + let display = cadcraft_render::build(drawing, &Space::Model, &opts); + let lines: Vec<_> = display + .prims + .iter() + .filter(|p| p.handle == hatch.handle && p.kind == cadcraft_render::Kind::Polyline) + .map(|p| display.points(p)[0].y) + .collect(); + assert!(lines.len() >= 2, "expected multiple hatch lines, got {lines:?}"); + for pair in lines.windows(2) { + let measured = (pair[1] - pair[0]).abs(); + assert!((measured / spacing - 1.0).abs() < 1e-12, "drawn spacing {measured}, requested {spacing}"); + } + } + } + + /// A script's own HATCH line is not a routine's call: it keeps the interface's prompts and picks + /// the boundary first, as it did before a routine's answers were published. + #[test] + fn a_script_hatch_keeps_the_interface_prompts() { + let mut s = Session::new(); + s.script("pline 0,0 4000,0 4000,2000 0,2000 c\nhatch\n").unwrap(); + // The boundary question comes first: no pattern, scale or angle is asked. + assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text()); + s.cmdline("2000,1000").unwrap(); + s.cmdline("").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let h = only_hatch(&s).1; + assert_eq!((h.pattern.as_str(), h.scale), ("ANSI31", 1.0)); + } + + /// A routine's `(command …)` inside a script is still a routine's call: it takes the published + /// order, though the script's own HATCH line above does not. + #[test] + fn a_lisp_hatch_call_from_a_script_takes_the_published_order() { + let mut s = Session::new(); + s.script("pline 0,0 4000,0 4000,2000 0,2000 c\n(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let h = only_hatch(&s).1; + assert_eq!(h.pattern, "DOTS"); + assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale); + } + + /// A script that a routine starts with `(command "_.script" …)` runs its lines as a script: its + /// HATCH line takes the interface's options (A for the angle), not the routine's order. + #[test] + fn a_script_a_routine_starts_keeps_the_interface_prompts() { + let dir = std::env::temp_dir().join(format!("cadcraft-hatch-script-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("angle.scr"); + std::fs::write(&file, "hatch A 45\n\n").unwrap(); + let mut s = Session::new(); + let path = file.to_string_lossy().replace('\\', "/"); + s.cmdline(&format!("(command \"_.script\" \"{path}\")")).unwrap(); + let a = s.doc().unwrap().header.f64("HPANG", 0.0); + let _ = std::fs::remove_dir_all(&dir); + assert!((a - std::f64::consts::FRAC_PI_4).abs() < 1e-9, "HPANG {a}; {}", s.prompt_text()); + assert!(!s.lisp_program_input(), "the routine's flag is restored after the script"); + } + + /// -HATCH keeps its own questions, a routine's included: it picks the boundary first, and the + /// Properties option takes the pattern, scale and angle as before. + #[test] + fn dash_hatch_keeps_its_pick_boundary_prompts() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + s.cmdline("(command \"_.-hatch\")").unwrap(); + assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text()); + s.cancel(); + // Typed by a person (the interface's dialog off) it is the same command line. + s.start("hatch").unwrap(); + assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text()); + s.cancel(); + } + + /// A user-defined hatch is saved as one (pattern `_USER`, pattern type 0, its double flag) and + /// read back with its angle, spacing and families. + #[test] + fn a_user_defined_hatch_survives_a_dxf_save_and_read() { + let mut s = Session::new(); + lisp_rectangle(&mut s); + s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap(); + let text = cadcraft_io::write_dxf(s.doc().unwrap()); + let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let h = d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN); + assert!(!h.solid); + assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale); + assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle); + assert_eq!(h.pattern_lines.len(), 2, "the doubled families are made again"); + } + #[test] fn unknown_pattern_error_and_catalog_name_the_pat_file_route() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/hatch/arcs.rs b/crates/engine/src/cmd/hatch/arcs.rs new file mode 100644 index 000000000..8b528e81c --- /dev/null +++ b/crates/engine/src/cmd/hatch/arcs.rs @@ -0,0 +1,147 @@ +//! 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> { + 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], pieces: &[Option], tol: f64) -> Vec { + let n = pts.len(); + let plain = || pts.iter().map(|p| PolyVertex::new(*p)).collect::>(); + 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> = (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 = 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 } +} diff --git a/crates/engine/src/cmd/hatch/assoc.rs b/crates/engine/src/cmd/hatch/assoc.rs index c0293aa87..00f57b0ac 100644 --- a/crates/engine/src/cmd/hatch/assoc.rs +++ b/crates/engine/src/cmd/hatch/assoc.rs @@ -87,8 +87,14 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill { return Refill::Open; } let tol = super::outline_tol(nb); + let mut polys: Vec> = 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> = 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 { @@ -97,13 +103,14 @@ 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_gap(&polys, map_point(q, &ob, &nb), snap, gap)) - .or_else(|| region::outline(&polys, snap, gap)) + .and_then(|q| region::enclosing_loop_edges_gap(&polys, map_point(q, &ob, &nb), snap, gap)) + .or_else(|| region::outline_edges(&polys, snap, gap)) } else { - region::outline(&polys, snap, gap) + region::outline_edges(&polys, snap, gap) }; match found { - Some(pts) => Refill::Loop(pts.into_iter().map(PolyVertex::new).collect()), + // Traced again from flattened curves: circular runs become arcs again (#1167). + Some((pts, edges)) => Refill::Loop(super::arcs::with_arcs(&pts, &edges, &pieces, tol)), None => Refill::Open, } } diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index 0590dbe7a..853d513e5 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -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}; +use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles, same_loop}; 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,7 +420,21 @@ 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(); - h.loops.extend_from_slice(added); + // 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()), + } + } dedup_loops(&mut h.loops); if h.loops.is_empty() { return Err(bad("hatchedit", "a hatch needs at least one boundary loop")); diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index 78144b09d..964dd1331 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { CommandSpec::new("status", "Status", run_status).menu(&["Tools", "Inquiry", "Status"]).noundo(), CommandSpec::new("drawing.inspect", "Inspect Drawing", run_inspect).params("{entities?: bool, limit?: n}").noundo(), CommandSpec::new("entities", "Query Entities", run_entities) - .params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), limit?, offset?} → {count (all matches), returned, offset, entities}") + .params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), xdata?: true | \"APP\" | [\"APP\", …] (add each entity's extended data {\"APP\": [[code, value], …]}; a name also keeps only entities carrying that application's data), limit?, offset?} → {count (all matches), returned, offset, entities}") .noundo(), CommandSpec::new("shapes", "Analyze Shapes", shapes::run).params(shapes::PARAMS).noundo(), CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(), @@ -532,12 +532,17 @@ 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. - let geoms: Vec = hh.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect(); - let polys: Vec> = geoms.iter().map(|g| g.tessellate(1e-3)).collect(); + // 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 = + kept.iter().filter_map(|(i, _)| hh.loops.get(*i)).map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect(); + let polys: Vec> = kept.into_iter().map(|(_, p)| p).collect(); let mut total = (0.0, 0.0); for (i, g) in geoms.iter().enumerate() { - let probe = polys.get(i).and_then(|p| p.first().copied()); + // 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 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(); @@ -653,6 +658,7 @@ fn run_entities(s: &mut Session, p: &Value) -> Result { .transpose()?; let crossing = given("crossing").map_or(Ok(true), |v| v.as_bool().ok_or_else(|| bad(CMD, "`crossing` must be true or false")))?; let selected = given("selected").map_or(Ok(false), |v| v.as_bool().ok_or_else(|| bad(CMD, "`selected` must be true or false")))?; + let xdata = super::props::xdata::XdataSelect::parse(given("xdata")).map_err(|m| bad(CMD, m))?; let limit = count("limit", 500)?; let offset = count("offset", 0)?; let st = s.state()?; @@ -666,8 +672,20 @@ fn run_entities(s: &mut Session, p: &Value) -> Result { .filter(|e| ty.as_ref().is_none_or(|t| e.kind.type_name().to_ascii_lowercase() == *t || e.kind.dxf_name().to_ascii_lowercase() == *t)) .filter(|e| layer.as_ref().is_none_or(|l| e.common.layer.to_ascii_lowercase() == *l)) .filter(|e| window.as_ref().is_none_or(|w| crate::select::in_window(d, e, None, w, crossing, tol))) + .filter(|e| !xdata.filters() || xdata.matches(&e.common.xdata)) + .collect(); + let page: Vec = matches + .iter() + .skip(offset) + .take(limit) + .map(|e| { + let mut v = entity_summary(e); + if let (Some(x), Some(o)) = (xdata.json(&e.common.xdata), v.as_object_mut()) { + o.insert("xdata".into(), x); + } + v + }) .collect(); - let page: Vec = matches.iter().skip(offset).take(limit).map(|e| entity_summary(e)).collect(); // `count` is every match; `returned` is this page of them (`offset`, `limit`). Ok(json!({ "count": matches.len(), "returned": page.len(), "offset": offset, "entities": page })) } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9bb40610b..85170d776 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -251,6 +251,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { *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 { @@ -835,6 +836,36 @@ mod tests { assert_eq!(graphics_layer(&s), "0"); } + /// The same for linetypes: PURGE keeps one only proxy graphics draw with, and RENAME takes + /// the graphics and the file's LTYPE order with it. + #[test] + fn linetypes_proxy_graphics_draw_with_are_in_use_and_renamed() { + let mut s = proxy_on_b(); + for name in ["DASHED", "HIDDEN"] { + s.execute("linetype", &json!({ "load": name })).unwrap(); + } + let d = s.doc_mut().unwrap(); + d.proxy_linetypes = vec!["Continuous".into(), "DASHED".into(), "HIDDEN".into()]; + let h = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).unwrap().handle; + d.modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Unknown(u) = &mut e.kind { + u.graphics[0].common.linetype = "DASHED".into(); + } + }) + .unwrap(); + s.execute("purge", &json!({})).unwrap(); + let d = s.doc().unwrap(); + assert!(d.linetype("DASHED").is_some() && d.linetype("HIDDEN").is_none()); + s.execute("rename", &json!({ "table": "linetype", "from": "DASHED", "to": "DASH2" })).unwrap(); + let d = s.doc().unwrap(); + let linetype = d.model.iter().find_map(|e| match &e.kind { + cadcraft_doc::EntityKind::Unknown(u) => Some(u.graphics[0].common.linetype.clone()), + _ => None, + }); + assert_eq!(linetype.as_deref(), Some("DASH2")); + assert_eq!(d.proxy_linetypes, ["Continuous", "DASH2", "HIDDEN"]); + } + #[test] fn rename_repoints_paper_space_and_block_entities() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 7e42eb269..a97cf29d1 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -26,8 +26,12 @@ pub fn specs() -> Vec { .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)} → {name, viewport}") + .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)") .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?}"), @@ -78,7 +82,7 @@ pub fn specs() -> Vec { CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup) .menu(&["File", "Page Setup Manager..."]) .params( - "{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}", + "{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}", ), CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot")) .menu(&["File", "Print..."]) @@ -225,7 +229,133 @@ 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, + /// The first corner of the model area. + first: Option, + /// The tab the command started in, put back when it is cancelled. + from: Option, +} + +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 { + 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 { + 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> { + 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 { + // 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)?, @@ -236,16 +366,30 @@ fn run_new(s: &mut Session, p: &Value) -> Result { 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. + // AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents, + // or to the `window` when it has one. 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 { let name = str_param(p, "name").ok_or_else(|| bad("layout.delete", "`name` is required"))?; let name = layout_name("layout.delete", s.doc()?, name)?; @@ -322,6 +466,7 @@ fn run_copy(s: &mut Session, p: &Value) -> Result { ucs: src.ucs, ucs_previous: Vec::new(), limits: src.limits, + flags: src.flags, }); Ok(json!({ "name": to })) } @@ -437,6 +582,11 @@ 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(); @@ -683,8 +833,21 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result { // 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(|| { @@ -723,9 +886,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result { (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") { diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 11c5201aa..3fa5cf8cc 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -88,6 +88,7 @@ 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(); @@ -95,6 +96,141 @@ 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(); @@ -466,3 +602,119 @@ fn plot_path_extension_picks_the_format_like_export() { assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree"); std::fs::remove_dir_all(&dir).ok(); } + +#[test] +fn layout_set_frames_extents_away_from_origin() { + let mut s = Session::new(); + s.doc_mut().unwrap().layouts.push(cadcraft_doc::Layout::new("COVER", 2)); + let paper = Space::Paper("COVER".into()); + s.doc_mut() + .unwrap() + .add( + &paper, + cadcraft_doc::Common::default(), + cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { + a: cadcraft_geom::Vec3::new(12049.0, 4307.0, 0.0), + b: cadcraft_geom::Vec3::new(12449.0, 4594.0, 0.0), + }), + ) + .unwrap(); + s.execute("layout.set", &json!({"name": "COVER"})).unwrap(); + let v = s.state().unwrap().view(); + assert!((v.center.x - 12249.0).abs() < 1e-6, "center.x={}", v.center.x); + assert!((v.center.y - 4450.5).abs() < 1e-6, "center.y={}", v.center.y); + assert!(v.height >= 287.0, "height={}", v.height); +} + +#[test] +fn layout_set_ignores_off_layer_entities_far_from_visible_content() { + let mut s = Session::new(); + let paper = Space::Paper("COVER".into()); + { + let doc = s.doc_mut().unwrap(); + doc.layouts.push(cadcraft_doc::Layout::new("COVER", 2)); + let mut off_layer = cadcraft_doc::Layer::new("HIDDEN_REF"); + off_layer.on = false; + doc.layers.push(off_layer); + doc.add( + &paper, + cadcraft_doc::Common::default(), + cadcraft_doc::EntityKind::Polyline3d(cadcraft_doc::Polyline3d { + points: vec![ + cadcraft_geom::Vec3::new(12000.0, 4000.0, 0.0), + cadcraft_geom::Vec3::new(12400.0, 4000.0, 0.0), + cadcraft_geom::Vec3::new(12400.0, 4300.0, 0.0), + cadcraft_geom::Vec3::new(12000.0, 4300.0, 0.0), + ], + closed: true, + }), + ) + .unwrap(); + doc.add( + &paper, + cadcraft_doc::Common { layer: "HIDDEN_REF".into(), ..Default::default() }, + cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { + a: cadcraft_geom::Vec3::new(1_000_000.0, 1_000_000.0, 0.0), + b: cadcraft_geom::Vec3::new(1_000_100.0, 1_000_100.0, 0.0), + }), + ) + .unwrap(); + } + s.execute("layout.set", &json!({"name": "COVER"})).unwrap(); + let v = s.state().unwrap().view(); + assert!((v.center.x - 12200.0).abs() < 1e-6, "center.x={}", v.center.x); + assert!((v.center.y - 4150.0).abs() < 1e-6, "center.y={}", v.center.y); + assert!(v.height >= 300.0 && v.height < 2000.0, "height={}", v.height); + + // Explicit ZOOM Extents continues to include entities on turned-off layers. + s.execute("zoom", &json!({"mode": "extents"})).unwrap(); + let after_zoom = s.state().unwrap().view(); + assert!(after_zoom.center.x > 100_000.0, "zoom extents center.x={}", after_zoom.center.x); + assert!(after_zoom.height > v.height * 100.0, "zoom extents height={}", after_zoom.height); +} + +#[test] +fn layout_set_falls_back_to_sheet_when_all_layers_hidden() { + let mut s = Session::new(); + let paper = Space::Paper("ALL_OFF".into()); + { + let doc = s.doc_mut().unwrap(); + doc.layouts.push(cadcraft_doc::Layout::new("ALL_OFF", 2)); + let mut off_layer = cadcraft_doc::Layer::new("OFF_LAYER"); + off_layer.on = false; + doc.layers.push(off_layer); + let mut frozen_layer = cadcraft_doc::Layer::new("FROZEN_LAYER"); + frozen_layer.frozen = true; + doc.layers.push(frozen_layer); + doc.add( + &paper, + cadcraft_doc::Common { layer: "OFF_LAYER".into(), ..Default::default() }, + cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { + a: cadcraft_geom::Vec3::new(12000.0, 4000.0, 0.0), + b: cadcraft_geom::Vec3::new(12400.0, 4300.0, 0.0), + }), + ) + .unwrap(); + doc.add( + &paper, + cadcraft_doc::Common { layer: "FROZEN_LAYER".into(), ..Default::default() }, + cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { + a: cadcraft_geom::Vec3::new(15000.0, 5000.0, 0.0), + b: cadcraft_geom::Vec3::new(15400.0, 5300.0, 0.0), + }), + ) + .unwrap(); + } + let (expected_center, expected_height) = { + let doc = s.doc().unwrap(); + let page = doc.layout("ALL_OFF").map(|l| l.page.clone()).unwrap_or_default(); + let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; + let unit = if doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; + (cadcraft_geom::Vec2::new(w * unit / 2.0, h * unit / 2.0), h * unit * 1.15) + }; + s.execute("layout.set", &json!({"name": "ALL_OFF"})).unwrap(); + let v = s.state().unwrap().view(); + assert!((v.center.x - expected_center.x).abs() < 1e-6, "center.x={}", v.center.x); + assert!((v.center.y - expected_center.y).abs() < 1e-6, "center.y={}", v.center.y); + assert!((v.height - expected_height).abs() < 1e-6, "height={}", v.height); +} diff --git a/crates/engine/src/cmd/lisp.rs b/crates/engine/src/cmd/lisp.rs index b9d307a3f..b8f884de5 100644 --- a/crates/engine/src/cmd/lisp.rs +++ b/crates/engine/src/cmd/lisp.rs @@ -50,8 +50,8 @@ fn source(p: &Value) -> Result<(String, String)> { } /// The result of a blocking LISP run as JSON, with the lines it printed. -fn report(s: &Session, from_log: usize, r: Option>) -> Value { - let output: Vec = s.log.get(from_log..).map(|l| l.to_vec()).unwrap_or_default(); +fn report(s: &Session, from_log: u64, r: Option>) -> Value { + let output: Vec = s.log_since(from_log).to_vec(); match r { Some(Ok(v)) => json!({ "value": to_text(&v, true), "output": output }), Some(Err(e)) => json!({ "error": e, "output": output }), @@ -62,7 +62,7 @@ fn report(s: &Session, from_log: usize, r: Option Result { let (name, text) = source(p)?; let before = s.lisp_commands(); - let from = s.log.len(); + let from = s.log_mark(); let r = s.lisp_load(&name, &text, true)?; let mut out = report(s, from, r); // The commands the file defined, so a caller can run them next (a failed file may still @@ -82,7 +82,7 @@ fn input_value(v: &Value) -> Lv { fn run_lisp(s: &mut Session, p: &Value) -> Result { let code = str_param(p, "code").ok_or_else(|| bad("lisp", "`code` is required"))?; let inputs = p.get("inputs").and_then(Value::as_array).map(|a| a.iter().map(input_value).collect()).unwrap_or_default(); - let from = s.log.len(); + let from = s.log_mark(); let r = s.lisp_eval(code, false, true, inputs).map_err(|e| match e { EngineError::Other(m) => bad("lisp", m), e => e, diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 0d331a9bb..505289ec0 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -36,7 +36,7 @@ use oops::run_oops; pub(crate) use oops::{Erased, erase_kept}; use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; -pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities}; +pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, transform_entities}; use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; pub(crate) use trim::{ CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed, diff --git a/crates/engine/src/cmd/modify/explode.rs b/crates/engine/src/cmd/modify/explode.rs index 21051fffc..9e331af44 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -105,6 +105,8 @@ fn explode_mtext(e: &Entity, m: &cadcraft_doc::MText) -> Vec { style: m.style.clone(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), } }) @@ -177,6 +179,7 @@ fn explode_dimension(d: &cadcraft_doc::Drawing, e: &Entity, dm: &cadcraft_doc::D line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), }); } @@ -264,7 +267,7 @@ pub(crate) fn explode_with( // pieces are copies of the block's objects and keep theirs. let own_pieces = !matches!(e.kind, EntityKind::Insert(_)); let d = s.doc_mut()?; - d.remove_entity(*h); + let Some(removed) = d.remove_entity(*h) else { continue }; for mut p in parts { if own_pieces { p.common.xdata.clear(); @@ -275,6 +278,9 @@ pub(crate) fn explode_with( st.push(p); } } + if !own_pieces && let Some(names) = s.record_names() { + names.erased(&removed); + } } s.set_selection(Vec::new()); Ok(out) diff --git a/crates/engine/src/cmd/modify/extrim.rs b/crates/engine/src/cmd/modify/extrim.rs index 8a200582b..ecc0fc5a8 100644 --- a/crates/engine/src/cmd/modify/extrim.rs +++ b/crates/engine/src/cmd/modify/extrim.rs @@ -11,6 +11,7 @@ use cadcraft_geom::{Bounds2, Line, Vec2, line_line, point_in_polygon}; use serde_json::{Value, json}; use super::offset::offset_points; +use super::trim::ON_CUT; use super::{Edges, trim}; use crate::cmd::helpers::lwpoly; use crate::cmd::{CommandSpec, bad, point_param, targets}; @@ -22,7 +23,7 @@ const MAX_FENCE: usize = 10_000; const MAX_OBJECTS: usize = 10_000; /// Most stretches one call removes (an object can lose several). const MAX_STRETCHES: usize = 10_000; -/// Most objects the preview draws (beyond that it shows nothing, to keep the cursor smooth). +/// Most parts the preview draws (beyond that it shows nothing, to keep the cursor smooth). const MAX_PREVIEW: usize = 2000; /// The traced line's distance from the edge, as a fraction of the edge's size. const TRACE_GAP: f64 = 1e-5; @@ -30,7 +31,7 @@ const TRACE_GAP: f64 = 1e-5; pub(super) fn spec() -> CommandSpec { CommandSpec::new("extrim", "Extended Trim", run_extrim) .menu(&["Tools", "Additional Tools", "Extended Trim"]) - .params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut}") + .params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut, partly (of uncut, those cut in part)}") .interactive(|s| Ok(Box::new(ExtrimM::new(s)))) } @@ -146,6 +147,11 @@ struct Edge { impl Edge { /// The cutting edge `h`: a line, arc, circle, ellipse, polyline or spline of the current space. + /// Whether the edge is still an object of the space being edited (MSPACE and PSPACE change + /// it while EXTRIM runs): only there can TRIM cut with it. + fn in_space(&self, s: &Session) -> bool { + s.doc().is_ok_and(|d| d.space_of(self.handle).as_ref() == Some(&s.space())) + } fn new(s: &Session, h: Handle) -> Result { let d = s.doc()?; let e = d.entity(h).ok_or_else(|| bad("extrim", format!("no object {}", h.hex())))?; @@ -394,14 +400,16 @@ fn stretches_of(pts: &[Vec2], closed: bool, edge: &Grid, trace: &Grid) -> Option } /// The trim of everything crossing `edge` on `side`, worked out without changing anything. -fn plan(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Result { +/// `frozen`: the layers the active layout viewport freezes, whose objects it doesn't draw and +/// so leaves alone, as a selection through it does. +fn plan(d: &Drawing, space: &cadcraft_doc::Space, frozen: &[String], edge: &Edge, side: Side) -> Result { let trace = edge.trace(side); let trace_grid = Grid::new(&trace); let edge_grid = Grid::new(&edge.pts); let tol = edge.gap / 20.0; let mut p = Plan::default(); let mut stretches_total = 0; - for h in crate::select::select_fence(d, space, &trace) { + for h in crate::select::select_fence_in(d, space, frozen, &trace) { if h == edge.handle { continue; } @@ -462,6 +470,23 @@ fn midpoint(pts: &[Vec2]) -> Option { pts.last().copied() } +/// Whether `e` has no length at all: every point of its outline the same f64 point. +fn degenerate(d: &Drawing, e: &Entity, tol: f64) -> bool { + length(d, e, tol) <= 0.0 +} + +/// Whether TRIM would pass over a cut at `st`'s end (within ON_CUT of its pick) and run on to the +/// next one, taking more than `st`: such a stretch is left, by the trim and by its preview. The +/// ends and the pick lie on the outline traced within `tol` (and the pick is then brought onto +/// the object), so a true cut can be up to 3 `tol` nearer than the end found: that is the margin. +/// TRIM measures along the object, and so does this: the pick is the middle of the stretch's +/// longest part, half of that part from the nearer of its ends along the outline (straight across, +/// a folded polyline can bring an end next to the pick however far away it is along it). +fn too_short(st: &Stretch, tol: f64) -> bool { + let longest = st.parts.iter().map(|p| arc_length(p)).fold(0.0, f64::max); + longest / 2.0 <= ON_CUT + 3.0 * tol +} + /// The length of an object's drawn outline. fn length(d: &Drawing, e: &Entity, tol: f64) -> f64 { crate::select::hit_polylines(d, e, tol).iter().flat_map(|pl| pl.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?)))).sum() @@ -488,11 +513,15 @@ pub(super) fn run_extrim(s: &mut Session, p: &Value) -> Result { /// Trim every object crossing `edge` on `side`: one undo step, everything checked first. fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result { + if !edge.in_space(s) { + return Err(bad("extrim", "the cutting edge is not in the space being edited; pick it again there")); + } let space = s.space(); - let plan = plan(s.doc()?, &space, edge, side)?; + let plan = plan(s.doc()?, &space, s.viewport_frozen(), edge, side)?; let edges = Edges { only: Some(std::slice::from_ref(&edge.handle)), implied: false }; let tol = edge.gap / 20.0; let mut trimmed = 0; + let mut partly = 0; let mut created = Vec::new(); // Objects some planned cut failed on, reported rather than counted as done. let mut uncut = plan.uncut; @@ -501,7 +530,16 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result { let mut cut = false; // The object as it is before any cut: its lines and arcs, exactly. let exact = s.doc()?.entity(h).and_then(|e| exact_outline(&e.kind)); - for x in stretches.into_iter().map(|st| st.pick) { + for st in stretches { + // TRIM passes over a cut within ON_CUT of the pick and runs on to the next one, which + // would take more than this stretch: a stretch that short is left, and said so. + if too_short(&st, tol) { + if !uncut.contains(&h) { + uncut.push(h); + } + continue; + } + let x = st.pick; // The pick lies on the flattened outline, which strays from a large-radius arc by up to // a millionth of its radius (far more than `tol` next to a short edge): bring it onto // the object itself, and measure the pieces exactly too. @@ -540,9 +578,10 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result { cut = true; live.retain(|l| *l != t); for n in pieces { - // Never leave a piece of no length behind. + // Never leave a piece of no length behind; a short one that has length stays, as + // TRIM leaves it. let d = s.doc()?; - if d.entity(n).is_some_and(|e| length(d, e, tol) <= tol) { + if d.entity(n).is_some_and(|e| degenerate(d, e, tol)) { s.doc_mut()?.remove_entity(n); } else { live.push(n); @@ -550,7 +589,12 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result { } } if cut { - trimmed += 1; + // A partly cut object is counted once, with those not cut everywhere. + if uncut.contains(&h) { + partly += 1; + } else { + trimmed += 1; + } created.extend(live.into_iter().filter(|l| *l != h)); } } @@ -562,12 +606,13 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result { message.push_str(&format!(" {} that can't be trimmed (blocks, hatches, text…) left as they are.", plan.other)); } if !uncut.is_empty() { - message.push_str(&format!(" {} could not be cut everywhere the edge crosses them.", uncut.len())); + message.push_str(&format!(" {} could not be cut everywhere the edge crosses them", uncut.len())); + message.push_str(&if partly > 0 { format!(" ({partly} of them cut in part).") } else { ".".to_string() }); } Ok(json!({ "trimmed": trimmed, "handles": created.iter().map(|h| h.hex()).collect::>(), - "skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len() }, + "skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len(), "partly": partly }, "message": message, })) } @@ -595,15 +640,19 @@ fn on_outline(segs: &[cadcraft_geom::Segment], p: Vec2) -> Vec2 { } /// The parts the trim would remove, drawn red. -fn preview(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Vec { - let Ok(plan) = plan(d, space, edge, side) else { return Vec::new() }; - if plan.work.len() > MAX_PREVIEW { +fn preview(d: &Drawing, space: &cadcraft_doc::Space, frozen: &[String], edge: &Edge, side: Side) -> Vec { + let Ok(plan) = plan(d, space, frozen, edge, side) else { return Vec::new() }; + let tol = edge.gap / 20.0; + // What costs is what is drawn: an object can lose many stretches, each of several parts. + let parts: usize = + plan.work.iter().flat_map(|(_, st)| st).filter(|st| !too_short(st, tol)).map(|st| st.parts.iter().filter(|p| p.len() >= 2).count()).sum(); + if parts > MAX_PREVIEW { return Vec::new(); } let mut out = Vec::new(); for (h, stretches) in plan.work { let Some(e) = d.entity(h) else { continue }; - for part in stretches.into_iter().flat_map(|st| st.parts).filter(|p| p.len() >= 2) { + for part in stretches.into_iter().filter(|st| !too_short(st, tol)).flat_map(|st| st.parts).filter(|p| p.len() >= 2) { let mut ent = Entity::new(Handle(0), lwpoly(part.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false)); ent.common.color = Color::Index(1); ent.common.layer = e.common.layer.clone(); @@ -615,10 +664,15 @@ fn preview(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> /// EXTRIM at the prompts: the cutting edge (or the one object selected beforehand), then the side, /// with the parts that will go shown red as the cursor moves. +/// What a cached EXTRIM preview was worked out for: the space being edited and the frozen layers. +type PreviewFor = (cadcraft_doc::Space, Vec); + pub(super) struct ExtrimM { edge: Option, - /// The preview for each side (left, right), worked out once. - previews: RefCell<[Option>; 2]>, + /// The preview for each side (left, right), worked out once for the space being edited and the + /// layers the active viewport freezes then: a VPLAYER or MSPACE run meanwhile changes what the + /// trim works on. + previews: RefCell<[Option<(PreviewFor, Vec)>; 2]>, } impl ExtrimM { @@ -693,16 +747,22 @@ impl Interactive for ExtrimM { } fn preview_objects(&self, s: &Session, cursor: Vec2) -> Vec { let Some(edge) = &self.edge else { return Vec::new() }; + // An edge left in another space cuts nothing here, so nothing is shown going. + if !edge.in_space(s) { + return Vec::new(); + } let Some(side) = edge.side(cursor) else { return Vec::new() }; let slot = usize::from(side == Side::Right); - let cached = self.previews.borrow().get(slot).cloned().flatten(); + let (space, frozen) = (s.space(), s.viewport_frozen()); + let cached = + self.previews.borrow().get(slot).cloned().flatten().filter(|((sp, f), _)| *sp == space && f.as_slice() == frozen).map(|(_, v)| v); let mut v = match cached { Some(v) => v, None => { let Ok(d) = s.doc() else { return Vec::new() }; - let v = preview(d, &s.space(), edge, side); + let v = preview(d, &space, frozen, edge, side); if let Some(c) = self.previews.borrow_mut().get_mut(slot) { - *c = Some(v.clone()); + *c = Some(((space.clone(), frozen.to_vec()), v.clone())); } v } diff --git a/crates/engine/src/cmd/modify/fillet.rs b/crates/engine/src/cmd/modify/fillet.rs index b0cb32174..ee5fabe77 100644 --- a/crates/engine/src/cmd/modify/fillet.rs +++ b/crates/engine/src/cmd/modify/fillet.rs @@ -328,9 +328,10 @@ impl Interactive for FilletM { Input::Keyword(k) if k == "Undo" => { match self.undo.pop() { Some(doc) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an earlier + // one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; } None => s.echo("Nothing to undo."), diff --git a/crates/engine/src/cmd/modify/offset.rs b/crates/engine/src/cmd/modify/offset.rs index e23bb03f2..492fb0618 100644 --- a/crates/engine/src/cmd/modify/offset.rs +++ b/crates/engine/src/cmd/modify/offset.rs @@ -19,7 +19,8 @@ fn offsettable(k: &EntityKind) -> bool { } /// Offset an entity by `dist` towards `side`. Returns the new geometry. -pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2) -> Option { +/// `gap` is OFFSETGAPTYPE, used by polylines only. +pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2, gap: i64) -> Option { match k { EntityKind::Line(l) => { let ln = Line::new(l.a.xy(), l.b.xy()); @@ -64,7 +65,7 @@ pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2) -> Option 0.0; let d = if left { dist } else { -dist }; - offset_polyline(&pl, d).map(|vs| { + offset_polyline(&pl, d, gap).map(|vs| { let mut k = lwpoly(vs, p.closed); if let EntityKind::LwPolyline(n) = &mut k { n.const_width = p.const_width; @@ -135,35 +136,50 @@ pub(super) fn offset_points(pts: &[Vec2], d: f64, closed: bool) -> Vec { out } -/// Offset a polyline: offset each segment, then join neighbours at their intersections. -pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option> { - let segs: Vec = pl.segments().iter().filter_map(|s| s.offset(d)).collect(); - if segs.is_empty() { +/// Offset a polyline: offset each segment, then join neighbours at their intersections. `gap` +/// (OFFSETGAPTYPE) fills the gap at the outside of a corner between two lines: 0 extends both +/// copies to meet, 1 inserts an arc of radius `d` centred on the corner, 2 inserts a chamfer line. +pub(crate) fn offset_polyline(pl: &Polyline, d: f64, gap: i64) -> Option> { + let pairs: Vec<(Segment, Segment)> = pl.segments().iter().filter_map(|s| s.offset(d).map(|o| (*s, o))).collect(); + if pairs.is_empty() { return None; } + let segs: Vec = pairs.iter().map(|(_, o)| *o).collect(); let n = segs.len(); - // Where each offset segment starts after joining it to the previous one. - let mut starts: Vec = Vec::with_capacity(n); + // At each joint: where the previous copy ends, an optional fill vertex (its start and bulge), + // and where this copy starts. + let mut joints: Vec<(Vec2, Option, Vec2)> = Vec::with_capacity(n); for i in 0..n { let s = segs.get(i)?; - starts.push(if i == 0 && !pl.closed { - s.start() + joints.push(if i == 0 && !pl.closed { + (s.start(), None, s.start()) } else { let prev = segs.get((i + n - 1) % n)?; - join_point(prev, s).unwrap_or(s.start()) + let corner = pairs.get(i)?.0.start(); + // Only two segments that meet in the source have a corner to fill (a collapsed arc + // between them leaves none). + let adjacent = pairs.get((i + n - 1) % n)?.0.end().near(corner, 1e-9); + match gap_fill(prev, s, corner, d.abs(), if adjacent { gap } else { 0 }) { + Some((a, fill, b)) => (a, Some(fill), b), + None => { + let j = join_point(prev, s).unwrap_or(s.start()); + (j, None, j) + } + } }); } let mut verts: Vec = Vec::new(); for i in 0..n { let s = segs.get(i)?; - let start = *starts.get(i)?; - let end = if i + 1 < n { - *starts.get(i + 1)? + let start = joints.get(i)?.2; + let next = if i + 1 < n { + joints.get(i + 1) } else if pl.closed { - *starts.first()? + joints.first() } else { - s.end() + None }; + let end = next.map_or(s.end(), |j| j.0); let bulge = match s { Segment::Line(_) => 0.0, Segment::Arc { arc, ccw } => { @@ -179,6 +195,9 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option> } }; verts.push(PolyVertex { p: start, bulge, start_width: 0.0, end_width: 0.0 }); + if let Some(fill) = next.and_then(|j| j.1) { + verts.push(fill); + } } if !pl.closed { verts.push(PolyVertex::new(segs.last()?.end())); @@ -186,6 +205,40 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option> Some(verts) } +/// The OFFSETGAPTYPE fill between the offset copies `a` and `b` of two lines meeting at `corner`, +/// when the copies leave a gap (the outside of the turn): where `a` ends, the fill vertex, and +/// where `b` starts. `None` keeps the extended join. +fn gap_fill(a: &Segment, b: &Segment, corner: Vec2, d: f64, gap: i64) -> Option<(Vec2, PolyVertex, Vec2)> { + let (Segment::Line(la), Segment::Line(lb)) = (a, b) else { return None }; + if gap == 0 || la.a.near(la.b, 1e-12) || lb.a.near(lb.b, 1e-12) || a.end().near(b.start(), 1e-9) { + return None; + } + let (ta, tb) = (la.dir(), lb.dir()); + let j = join_point(a, b)?; + if (j - la.b).dot(ta) <= 1e-9 { + return None; + } + let (ra, rb) = (la.b - corner, lb.a - corner); + match gap { + 1 => { + let sweep = ra.cross(rb).atan2(ra.dot(rb)); + Some((la.b, PolyVertex::with_bulge(la.b, cadcraft_geom::arc_to_bulge(sweep)), lb.a)) + } + 2 => { + // The chamfer is the line at distance `d` from the corner, square to the bisector. + let m = (ra + rb).normalized(); + let (ka, kb) = (ta.dot(m), tb.dot(m)); + if ka.abs() < 1e-9 || kb.abs() < 1e-9 { + return None; + } + let pa = la.b + ta * ((d - ra.dot(m)) / ka); + let pb = lb.a + tb * ((d - rb.dot(m)) / kb); + Some((pa, PolyVertex::new(pa), pb)) + } + _ => None, + } +} + fn join_point(a: &Segment, b: &Segment) -> Option { if a.end().near(b.start(), 1e-9) { return Some(b.start()); @@ -202,7 +255,8 @@ pub(super) fn run_offset(s: &mut Session, p: &Value) -> Result { } let side = point_req("offset", p, "side")?; let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| bad("offset", "no such object"))?; - let k = offset_kind(&e.kind, dist.abs(), side).ok_or_else(|| bad("offset", "cannot offset that object"))?; + let gap = s.doc()?.header.i64("OFFSETGAPTYPE", 0); + let k = offset_kind(&e.kind, dist.abs(), side, gap).ok_or_else(|| bad("offset", "cannot offset that object"))?; let current_layer = match str_param(p, "layer").map(str::to_ascii_lowercase).as_deref() { None | Some("source") => false, Some("current") => true, @@ -321,9 +375,10 @@ impl Interactive for OffsetM { } let (erase, current) = offset_options(s); s.echo(format!( - "Current settings: Erase source={} Layer={} OFFSETGAPTYPE=0", + "Current settings: Erase source={} Layer={} OFFSETGAPTYPE={}", if erase { "Yes" } else { "No" }, - if current { "Current" } else { "Source" } + if current { "Current" } else { "Source" }, + s.doc().map(|d| d.header.i64("OFFSETGAPTYPE", 0)).unwrap_or(0) )); Ok(Step::Continue) } @@ -436,9 +491,10 @@ impl Interactive for OffsetM { (_, Input::Keyword(k)) if k == "Undo" => { match self.undo.pop() { Some((doc, picked)) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an earlier + // one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; self.picked = if self.multiple { picked } else { None }; if self.picked.is_none() { @@ -491,7 +547,7 @@ impl Interactive for OffsetM { .fold(f64::INFINITY, f64::min) } }; - match offset_kind(&e.kind, dist, p) { + match offset_kind(&e.kind, dist, p, s.doc()?.header.i64("OFFSETGAPTYPE", 0)) { Some(k) => { let before = s.state()?.doc.clone(); let (erase, current) = offset_options(s); @@ -521,6 +577,6 @@ impl Interactive for OffsetM { Some(x) => x, None => crate::select::entity_distance(d, e, c, 1e-3), }; - offset_kind(&e.kind, dist, c).into_iter().collect() + offset_kind(&e.kind, dist, c, d.header.i64("OFFSETGAPTYPE", 0)).into_iter().collect() } } diff --git a/crates/engine/src/cmd/modify/oops.rs b/crates/engine/src/cmd/modify/oops.rs index 6308cc615..0926b099e 100644 --- a/crates/engine/src/cmd/modify/oops.rs +++ b/crates/engine/src/cmd/modify/oops.rs @@ -55,6 +55,13 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result { // (`refedit::after_command`), so what OOPS had stays. let refused = taken.iter().any(|t| crate::cmd::blocks::refedit::locked(d, t.entity.handle)); if n > 0 && !refused { + // The names of the erased references' records went with them: OOPS bringing them back + // brings none back. Other references' names keep holding (#1660). + if let Some(names) = s.record_names() { + for t in &taken { + names.erased(&t.entity); + } + } s.state_mut()?.erased = Erased(taken); } Ok(n) diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 98e3b7742..98fdf15a6 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -39,12 +39,11 @@ pub(super) struct SelectThen { objs: Vec, pts: Vec, reference: bool, - /// ROTATE Reference: the reference angle (radians), once known. Its first point, and the - /// first of the two new-angle points, are kept in `ref_from`. + /// ROTATE Reference: the reference angle (radians), once known. ref_angle: Option, - /// ROTATE Reference: the new angle is given by two points (the `Points` option). + /// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option). ref_points: bool, - /// SCALE Reference: first point of a reference length given by two points. + /// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points. ref_from: Option, /// SCALE Reference: the reference length, once known. ref_len: Option, @@ -107,6 +106,74 @@ impl SelectThen { } } + /// The preview with the cursor at `c` and the base point at `base`. + fn preview_from(&self, s: &Session, base: Vec2, c: Vec2) -> Vec { + let (m, rubber_from) = match self.op { + Op::Move | Op::Copy => (Mat3::translate(c - base), base), + Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base), + Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base), + Op::Scale => match self.scale_reference_factor(base, c) { + Some((f, from)) => (Mat3::scale_about(base, f), from), + None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(), + }, + Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base), + _ => return Vec::new(), + }; + let Ok(d) = s.doc() else { return Vec::new() }; + let mut out: Vec = self + .objs + .iter() + .take(500) + .filter_map(|h| d.entity(*h)) + .map(|e| { + let mut k = e.kind.clone(); + if self.op == Op::Mirror { + mirror_kind(&mut k, &m); + } else { + k.transform(&m); + } + k + }) + .collect(); + out.push(line(rubber_from, c)); + out + } + /// The drag with the cursor at `c` and the base point at `base`. + fn drag_from(&self, s: &Session, base: Vec2, c: Vec2) -> Option { + let (matrix, rubber_from) = match self.op { + Op::Move | Op::Copy => (Mat3::translate(c - base), base), + Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base), + Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base), + Op::Scale => { + let (f, from) = self.scale_reference_factor(base, c)?; + (Mat3::scale_about(base, f), from) + } + Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base), + _ => return None, + }; + let mut extra = vec![line(rubber_from, c)]; + if self.op != Op::Mirror { + return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false }); + } + // Readable text and unchanged hatch directions cannot be drawn by reflecting their + // already-rendered primitives: preview those objects individually, the rest on the GPU. + let d = s.doc().ok()?; + let mut handles = Vec::with_capacity(self.objs.len()); + let mut individual = 0; + for h in &self.objs { + let Some(e) = d.entity(*h) else { continue }; + if !needs_mirror_preview(&e.kind) { + handles.push(*h); + } else if individual < MAX_MIRROR_OBJECT_PREVIEW { + individual += 1; + let mut k = e.kind.clone(); + mirror_kind(&mut k, &matrix); + extra.push(k); + } + } + Some(crate::prompt::Drag { handles, matrix, extra, clipboard: false }) + } + /// COPY's prompt once the base point is known, as AutoCAD 2024 asks it. fn copy_prompt(&self, base: Option) -> Prompt { match self.copy_array { @@ -265,30 +332,47 @@ impl SelectThen { } } - /// SCALE Reference: reference length (typed, or two points), then new length (typed, or a - /// point measured from the base point). The scale factor is new length / reference length. + /// SCALE Reference: reference length (typed, or two points), then new length (typed, a point + /// measured from the base point, or two points after `Points`). The scale factor is new length / + /// reference length. fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result { let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) }; - match (self.ref_len, self.ref_from, i) { - (None, None, Input::Point(p)) => { + if matches!(&i, Input::Keyword(k) if k == "Copy") { + self.copy_mode = true; + s.echo("Scaling a copy of the selected objects."); + return Ok(Step::Continue); + } + let Some(r) = self.ref_len else { + match (self.ref_from, i) { + (None, Input::Point(p)) => self.ref_from = Some(p), + (None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?), + (None, Input::Enter) => self.ref_len = Some(1.0), + (Some(a), Input::Point(p)) => { + self.ref_len = Some(require_length(Some(a.dist(p)))?); + self.ref_from = None; + } + (_, Input::Enter) => return Ok(Step::Done), + _ => {} + } + return Ok(Step::Continue); + }; + match (self.ref_points, self.ref_from, i) { + (false, _, Input::Keyword(k)) if k == "Points" => { + self.ref_points = true; + self.ref_from = None; + Ok(Step::Continue) + } + (false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r), + (false, _, Input::Text(t)) => { + let n = require_length(number(&t))?; + self.scale_by(s, base, n / r) + } + (true, None, Input::Point(p)) => { self.ref_from = Some(p); Ok(Step::Continue) } - (None, None, Input::Text(t)) => { - self.ref_len = Some(require_length(number(&t))?); - Ok(Step::Continue) - } - (None, None, Input::Enter) => { - self.ref_len = Some(1.0); - Ok(Step::Continue) - } - (None, Some(a), Input::Point(p)) => { - self.ref_len = Some(require_length(Some(a.dist(p)))?); - Ok(Step::Continue) - } - (Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r), - (Some(r), _, Input::Text(t)) => { - let n = require_length(number(&t))?; + (true, Some(a), Input::Point(p)) => { + let n = require_length(Some(a.dist(p)))?; self.scale_by(s, base, n / r) } (_, _, Input::Enter) => Ok(Step::Done), @@ -296,6 +380,26 @@ impl SelectThen { } } + /// The prompt while SCALE Reference collects its lengths. + fn scale_reference_prompt(&self) -> Prompt { + let base = self.pts.first().copied(); + match (self.ref_len, self.ref_points, self.ref_from) { + (None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"), + (None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p), + (Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base).distance(), + (Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT), + } + } + + /// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`. + fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> { + match (self.ref_len, self.ref_points, self.ref_from) { + (Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)), + (Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)), + _ => None, + } + } + /// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a /// point measured from the base point, or two points after `Points`). The objects turn by the /// new angle minus the reference angle. @@ -457,11 +561,7 @@ impl Interactive for SelectThen { let k = self.pts.len(); let base = self.pts.first().copied(); if self.op == Op::Scale && self.reference { - return match (self.ref_len, self.ref_from) { - (Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base), - (None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p), - (None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"), - }; + return self.scale_reference_prompt(); } if self.op == Op::Rotate && self.reference { return self.rotate_reference_prompt(); @@ -571,7 +671,7 @@ impl Interactive for SelectThen { } (Op::Scale, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => { let f = match inp { - Input::Point(p) => self.pts[0].dist(p), + Input::Point(p) => require_length(Some(self.pts[0].dist(p)))?, Input::Text(t) => { number(&t).filter(|f| f.is_finite() && *f > 0.0).ok_or_else(|| EngineError::Other("Requires a positive number.".into()))? } @@ -605,36 +705,7 @@ impl Interactive for SelectThen { return Vec::new(); } let Some(base) = self.pts.first().copied() else { return Vec::new() }; - let m = match self.op { - Op::Move | Op::Copy => Mat3::translate(c - base), - Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)), - Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)), - Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) { - Some(f) => Mat3::scale_about(base, f), - None if self.ref_len.is_some() => return Vec::new(), - None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(), - }, - Op::Mirror if !self.ask_erase => Mat3::mirror(base, c), - _ => return Vec::new(), - }; - let Ok(d) = s.doc() else { return Vec::new() }; - let mut out: Vec = self - .objs - .iter() - .take(500) - .filter_map(|h| d.entity(*h)) - .map(|e| { - let mut k = e.kind.clone(); - if self.op == Op::Mirror { - mirror_kind(&mut k, &m); - } else { - k.transform(&m); - } - k - }) - .collect(); - out.push(line(base, c)); - out + self.preview_from(s, base, c) } /// Separate shared GPU transforms from objects that need an individual MIRROR preview. fn drag(&self, s: &Session, c: Vec2) -> Option { @@ -642,35 +713,7 @@ impl Interactive for SelectThen { return None; } let base = self.pts.first().copied()?; - let matrix = match self.op { - Op::Move | Op::Copy => Mat3::translate(c - base), - Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)), - Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)), - Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?), - Op::Mirror if !self.ask_erase => Mat3::mirror(base, c), - _ => return None, - }; - let mut extra = vec![line(base, c)]; - if self.op != Op::Mirror { - return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false }); - } - // Readable text and unchanged hatch directions cannot be drawn by reflecting their - // already-rendered primitives: preview those objects individually, the rest on the GPU. - let d = s.doc().ok()?; - let mut handles = Vec::with_capacity(self.objs.len()); - let mut individual = 0; - for h in &self.objs { - let Some(e) = d.entity(*h) else { continue }; - if !needs_mirror_preview(&e.kind) { - handles.push(*h); - } else if individual < MAX_MIRROR_OBJECT_PREVIEW { - individual += 1; - let mut k = e.kind.clone(); - mirror_kind(&mut k, &matrix); - extra.push(k); - } - } - Some(crate::prompt::Drag { handles, matrix, extra, clipboard: false }) + self.drag_from(s, base, c) } } @@ -681,15 +724,55 @@ pub(super) struct DisplaceM { displacement: bool, /// COPY's mOde option: asking Single or Multiple. ask_mode: bool, + /// A perpendicular or tangent picked at the base point prompt, waiting for the second point + /// it is measured from (#3481), as LINE's first point does. + deferred_base: Option, + /// The last second point gave the deferred base no perpendicular foot or tangent point: the + /// prompt says so and asks for another. + no_base_from_second: 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, ask_mode: false, deferred_base: None, no_base_from_second: false } } /// At "Specify base point": objects selected, no point yet. fn at_base(&self) -> bool { - self.inner.sel.done && self.inner.pts.is_empty() && !self.displacement + self.inner.sel.done && self.inner.pts.is_empty() && !self.displacement && self.deferred_base.is_none() + } + /// The base a deferred perpendicular or tangent `d` resolves to from the second point `p`: + /// the foot of the perpendicular from `p`, or the tangent point seen from it. + fn resolve_base(d: crate::snap::Deferred, p: Vec2) -> Option { + crate::snap::resolve_deferred(crate::snap::LineEnd::Deferred(d), crate::snap::LineEnd::Point(p)).map(|(base, _)| base) + } + /// The second point after a deferred base: the base is resolved from it, then the point + /// moves or copies the objects as if the base had been picked (COPY keeps the base). + /// Anything but a point, or a point the base cannot be resolved from, asks again; the prompt + /// then says why ([`Self::second_point_prompt`]), so the text reaches the user translated. + fn second_point_after_deferred(&mut self, s: &mut Session, d: crate::snap::Deferred, i: Input) -> Result { + let Input::Point(p) = i else { return Ok(Step::Continue) }; + let Some(base) = Self::resolve_base(d, p) else { + self.no_base_from_second = true; + return Ok(Step::Continue); + }; + self.no_base_from_second = false; + self.deferred_base = None; + self.inner.pts.push(base); + self.inner.input(s, Input::Point(p)) + } + /// The second point prompt after the deferred base `d`. Each message is a whole English + /// sentence, the key the interface translates the prompt by. + fn second_point_prompt(&self, d: crate::snap::Deferred) -> Prompt { + let message = match (self.no_base_from_second, d.mode == crate::snap::mode::TAN) { + (false, _) => "Specify second point", + (true, true) => "No tangent from that point. Specify another second point", + (true, false) => "No perpendicular from that point. Specify another second point", + }; + Prompt::new(message, Accept::POINT) + } + /// The deferred base resolved from the cursor `c`, for the preview. + fn preview_base(&self, c: Vec2) -> Option { + Self::resolve_base(self.deferred_base?, c) } } @@ -717,7 +800,10 @@ impl Interactive for DisplaceM { 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(kw).default("Displacement").deferred(); + } + if let Some(d) = self.deferred_base { + return self.second_point_prompt(d); } self.inner.prompt(s) } @@ -745,6 +831,15 @@ impl Interactive for DisplaceM { self.ask_mode = false; return Ok(Step::Continue); } + if let Some(d) = self.deferred_base { + return self.second_point_after_deferred(s, d, i); + } + if self.at_base() + && let Input::Deferred(d) = i + { + self.deferred_base = Some(d); + 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); @@ -768,12 +863,18 @@ impl Interactive for DisplaceM { if self.displacement { return Vec::new(); } + if self.deferred_base.is_some() { + return self.preview_base(c).map(|base| self.inner.preview_from(s, base, c)).unwrap_or_default(); + } self.inner.preview(s, c) } fn drag(&self, s: &Session, c: Vec2) -> Option { if self.displacement { return None; } + if self.deferred_base.is_some() { + return self.inner.drag_from(s, self.preview_base(c)?, c); + } self.inner.drag(s, c) } } diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 6225517da..814df6a26 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -84,6 +84,7 @@ 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> { 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 { @@ -94,6 +95,7 @@ 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); @@ -104,6 +106,9 @@ 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) } diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 7a8f7cbf3..88f371c6f 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -49,9 +49,9 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove // its first piece under the object's handle and the others under new ones, so only the first // stays one of the picked edges, as in a run of trims on the drawing itself. let is_edge = |h: &Handle| edges.only.is_none_or(|es| es.contains(h)); - for e in store.iter() { + let mut visit = |e: &Entity| { if !d.is_visible(e) { - continue; + return; } match overlay.get(&e.handle) { Some(pieces) => { @@ -64,6 +64,22 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove None if e.handle != exclude && is_edge(&e.handle) => add(&e.kind), None => {} } + }; + match edges.only { + // Only the given edges: look them up rather than scan the whole space for them. A piece + // of one is keyed by its handle in the overlay, and the other pieces are never edges. + Some(es) => { + let mut seen = std::collections::HashSet::new(); + for e in es.iter().filter(|h| seen.insert(**h) && store.contains(**h)).filter_map(|h| d.entity(*h)) { + visit(e); + } + } + // Every object is an edge (Quick mode, run on every preview): walk the space as it is. + None => { + for e in store.iter() { + visit(e); + } + } } Ok(out) } @@ -392,7 +408,7 @@ const MAX_SELF_CROSSINGS: usize = 1 << 16; /// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within /// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further, /// to 1e-6; on a line, further still, to 5e-4 on one 10 long). -const ON_CUT: f64 = 5e-7; +pub(crate) const ON_CUT: f64 = 5e-7; /// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick, /// so Quick mode leaves it in place rather than erasing it as one no edge crosses. diff --git a/crates/engine/src/cmd/modify2/fillet_pline.rs b/crates/engine/src/cmd/modify2/fillet_pline.rs index 6ccbf8483..89ce5f3cf 100644 --- a/crates/engine/src/cmd/modify2/fillet_pline.rs +++ b/crates/engine/src/cmd/modify2/fillet_pline.rs @@ -1,9 +1,11 @@ //! FILLET and CHAMFER with polyline segments (#466): two straight segments of one polyline -//! (adjacent, or with one segment between them, which the corner replaces), or a straight end -//! segment of an open polyline with a line, which joins the polyline. +//! (adjacent, or with one segment between them, which the corner replaces), or a segment of a +//! polyline with a line or with another polyline's segment, which joins the polyline. A closed +//! polyline opens at its first vertex, as in AutoCAD; an arc segment joins at radius 0 where the +//! other object crosses it. use cadcraft_doc::{EntityKind, Handle, LwPolyline}; -use cadcraft_geom::{Line, PolyVertex, Polyline, Segment, Vec2, arc_to_bulge, bulge_to_arc, line_line_infinite}; +use cadcraft_geom::{Circle, Line, PolyVertex, Polyline, Segment, Vec2, arc_to_bulge, bulge_to_arc, line_circle, line_line_infinite}; use super::{curves, other, push_entity, set_kind}; use crate::cmd::helpers::{arc, line}; @@ -138,61 +140,205 @@ fn same_polyline( Ok(Some(h)) } -/// An open polyline's straight end segment with a line: the corner is cut and the line joins -/// the polyline. +/// One side of a corner between two objects: the vertices kept, ordered so the corner comes +/// after the last, which is the kept end of the picked straight segment. +struct Run { + vs: Vec, + /// Whether the polyline was turned round to put the corner at its end. + reversed: bool, +} + +impl Run { + fn inner(&self) -> Vec2 { + self.vs.last().map(|v| v.p).unwrap_or_default() + } +} + +/// The run of a line kept on the picked side of the corner `x`. +fn line_run(ln: Line, pick: Vec2, x: Vec2) -> Run { + let keep = if (ln.a - x).dot(pick - x) >= (ln.b - x).dot(pick - x) { ln.a } else { ln.b }; + Run { vs: vec![PolyVertex::new(keep)], reversed: false } +} + +/// A closed polyline as an open one that starts and ends at its first vertex (the closing +/// segment becomes the last): joined to another object, AutoCAD opens it there. An open one as +/// it is. +fn opened(pl: &LwPolyline) -> LwPolyline { + let mut o = pl.clone(); + if pl.closed + && let Some(first) = pl.vertices.first() + { + o.vertices.push(PolyVertex { bulge: 0.0, ..*first }); + o.closed = false; + } + o +} + +/// The picked segment of an open polyline. +fn picked_seg(pl: &LwPolyline, pick: Vec2) -> Result<(usize, Segment)> { + let segs = Polyline { vertices: pl.vertices.clone(), closed: false }.segments(); + let k = picked_segment(&segs, pick).ok_or_else(|| other("Select a polyline segment."))?; + segs.get(k).map(|sg| (k, *sg)).ok_or_else(|| other("Select a polyline segment.")) +} + +/// The picked straight segment of an open polyline, as a line. +fn picked_line(pl: &LwPolyline, pick: Vec2) -> Result<(usize, Line)> { + match picked_seg(pl, pick)? { + (k, Segment::Line(l)) => Ok((k, l)), + _ => Err(other("Fillet and chamfer work on straight polyline segments.")), + } +} + +/// The run of a polyline kept on the picked side of the corner `x` on its segment `k`: what lies +/// beyond the corner on the other side goes, as in AutoCAD (an object crossing a segment keeps +/// the picked part of it and drops the rest of the polyline past the crossing). +fn pline_run(pl: &LwPolyline, k: usize, seg: Line, pick: Vec2, x: Vec2) -> Run { + let toward_start = (seg.a - x).dot(pick - x) >= (seg.b - x).dot(pick - x); + if toward_start { + Run { vs: pl.vertices.get(..=k).map(<[PolyVertex]>::to_vec).unwrap_or_default(), reversed: false } + } else { + let tail = pl.vertices.get(k + 1..).unwrap_or_default(); + Run { vs: curves::reverse_vertices(tail, false), reversed: true } + } +} + +/// A straight segment of an open polyline with a line or another open polyline's: the corner +/// is cut and the other object joins the polyline (`hp`), which keeps its handle and direction. #[allow(clippy::too_many_arguments)] -fn polyline_and_line( +fn polyline_and_other( s: &mut Session, (hp, pl, pp): (Handle, &LwPolyline, Vec2), - (hl, ln, lp): (Handle, Line, Vec2), + (ho, ko, po): (Handle, &EntityKind, Vec2), polyline_first: bool, r: f64, chamfer: Option, trim: bool, ) -> Result> { - let segs = Polyline { vertices: pl.vertices.clone(), closed: pl.closed }.segments(); - let k = picked_segment(&segs, pp).ok_or_else(|| other("Select a polyline segment."))?; - let last = segs.len().checked_sub(1).ok_or_else(|| other("Select a polyline segment."))?; - if pl.closed || (k != 0 && k != last) { - return Err(other("A line fillets or chamfers with an end segment of an open polyline.")); - } - let at_end = match segs.get(k) { - // A single segment: the end nearer the corner is cut. - Some(sg) if k == 0 && k == last => { - line_line_infinite(sg.start(), sg.end(), ln.a, ln.b).is_none_or(|(x, _, _)| x.dist(sg.end()) <= x.dist(sg.start())) + let pl = &opened(pl); + let other_opened = match ko { + EntityKind::LwPolyline(op) => Some(opened(op)), + _ => None, + }; + let other_seg = match (ko, &other_opened) { + (EntityKind::Line(l), _) => (None, Line::new(l.a.xy(), l.b.xy())), + (EntityKind::LwPolyline(_), Some(op)) => { + let (ok, os) = picked_line(op, po)?; + (Some((op, ok)), os) } - _ => k == last, + _ => return Err(other("A polyline fillets or chamfers with a line, or with another segment of itself.")), }; - // Work at the polyline's end; turn it round if the first segment was picked. - let mut vs = if at_end { pl.vertices.clone() } else { curves::reverse_vertices(&pl.vertices, false) }; - let n = vs.len(); - let (Some(inner), Some(end)) = (vs.get(n.wrapping_sub(2)).copied(), vs.get(n.wrapping_sub(1)).copied()) else { - return Err(other("Select a polyline segment.")); + let (other_pl, oseg) = other_seg; + let (k, seg) = match picked_seg(pl, pp)? { + (k, Segment::Line(l)) => (k, l), + (k, Segment::Arc { .. }) => { + if r > 1e-12 || chamfer.is_some() { + return Err(other("A polyline's arc segment fillets with radius 0 only.")); + } + if !trim { + return Ok(None); + } + return arc_segment_and_other(s, (hp, pl, k, pp), (ho, other_pl, oseg, po)); + } + }; + let x = line_line_infinite(seg.a, seg.b, oseg.a, oseg.b).map(|r| r.0).ok_or_else(|| other("Lines are parallel."))?; + let mine = pline_run(pl, k, seg, pp, x); + let theirs = match other_pl { + Some((op, ok)) => pline_run(op, ok, oseg, po, x), + None => line_run(oseg, po, x), }; - if inner.bulge.abs() > 1e-12 { - return Err(other("Fillet and chamfer work on straight polyline segments.")); - } - let x = line_line_infinite(inner.p, end.p, ln.a, ln.b).map(|r| r.0).ok_or_else(|| other("Lines are parallel."))?; - let keep_line = if (ln.a - x).dot(lp - x) >= (ln.b - x).dot(lp - x) { ln.a } else { ln.b }; let side = |keep: Vec2| ((keep - x).normalized(), keep.dist(x)); let c = if polyline_first { - corner(x, side(inner.p), side(keep_line), r, chamfer)? + corner(x, side(mine.inner()), side(theirs.inner()), r, chamfer)? } else { - let c = corner(x, side(keep_line), side(inner.p), r, chamfer)?; + let c = corner(x, side(theirs.inner()), side(mine.inner()), r, chamfer)?; Corner { t1: c.t2, t2: c.t1, bulge: -c.bulge } }; if !trim { return add_loose(s, hp, &c); } - vs.truncate(n - 1); - push_point(&mut vs, PolyVertex { p: c.t1, bulge: c.bulge, ..end }); - push_point(&mut vs, PolyVertex { p: c.t2, bulge: 0.0, ..end }); - push_point(&mut vs, PolyVertex { p: keep_line, bulge: 0.0, ..end }); - if !at_end { + let tmpl = pl.vertices.get(k + 1).copied().unwrap_or_default(); + let mut vs = mine.vs; + if let Some(l) = vs.last_mut() { + l.bulge = 0.0; + } + push_point(&mut vs, PolyVertex { p: c.t1, bulge: c.bulge, ..tmpl }); + push_point(&mut vs, PolyVertex { p: c.t2, bulge: 0.0, ..tmpl }); + // The other object's run, from its kept end at the corner out to its far end. + let back = curves::reverse_vertices(&theirs.vs, false); + for v in back { + push_point(&mut vs, if other_pl.is_some() { v } else { PolyVertex { p: v.p, bulge: 0.0, ..tmpl } }); + } + if mine.reversed { vs = curves::reverse_vertices(&vs, false); } set_kind(s, hp, EntityKind::LwPolyline(LwPolyline { vertices: vs, ..pl.clone() }))?; - s.doc_mut()?.remove_entity(hl); + s.doc_mut()?.remove_entity(ho); + Ok(Some(hp)) +} + +/// A polyline's arc segment `k` with a line, or another polyline's straight segment, that +/// crosses it (FILLET with radius 0): the arc is cut where they cross, nearest the picks, and +/// keeps its picked side; the other object's picked side joins the polyline there. Neither is +/// extended: a line that misses the arc is refused, as in AutoCAD. +fn arc_segment_and_other( + s: &mut Session, + (hp, pl, k, pp): (Handle, &LwPolyline, usize, Vec2), + (ho, other_pl, oseg, po): (Handle, Option<(&LwPolyline, usize)>, Line, Vec2), +) -> Result> { + let vs = &pl.vertices; + let (Some(start), Some(end)) = (vs.get(k).copied(), vs.get(k + 1).copied()) else { return Err(other("Select a polyline segment.")) }; + let (ar, ccw) = bulge_to_arc(start.p, end.p, start.bulge).ok_or_else(|| other("Select a polyline segment."))?; + let total = (4.0 * start.bulge.atan()).abs(); + let a0 = ar.center.angle_to(start.p); + // How far along the arc, from its start in its own direction, a point lies (radians). + let along = |q: Vec2| { + let d = ar.center.angle_to(q) - a0; + let d = if ccw { d } else { -d }; + d.rem_euclid(std::f64::consts::TAU) + }; + let eps = 1e-9 * (1.0 + total); + let x = line_circle(&oseg, &Circle::new(ar.center, ar.radius)) + .into_iter() + .map(|h| h.0) + .filter(|q| q.is_finite() && along(*q) > eps && along(*q) < total - eps) + .min_by(|a, b| (a.dist(pp) + a.dist(po)).total_cmp(&(b.dist(pp) + b.dist(po)))) + .ok_or_else(|| other("The line does not cross the polyline's arc segment."))?; + let tx = along(x); + let sub = |sweep: f64| arc_to_bulge(start.bulge.signum() * sweep); + let theirs = match other_pl { + Some((op, ok)) => pline_run(op, ok, oseg, po, x), + None => line_run(oseg, po, x), + }; + let tmpl = end; + let plain = |v: PolyVertex| if other_pl.is_some() { v } else { PolyVertex { p: v.p, bulge: 0.0, ..tmpl } }; + let mut out: Vec = Vec::new(); + // Where the pick lies along the arc: one a little outside its sweep (within the pick box) + // counts at the nearer end, not always at the far one. + let picked = { + let a = along(pp); + if a > total && std::f64::consts::TAU - a < a - total { 0.0 } else { a.min(total) } + }; + if picked <= tx { + // Keep the start of the arc: the polyline up to the crossing, then the other object. + out.extend(vs.get(..k).unwrap_or_default().iter().copied()); + out.push(PolyVertex { bulge: sub(tx), ..start }); + push_point(&mut out, PolyVertex { p: x, bulge: 0.0, ..tmpl }); + for v in curves::reverse_vertices(&theirs.vs, false) { + push_point(&mut out, plain(v)); + } + } else { + // Keep the end of the arc: the other object, then the polyline from the crossing on. + for v in &theirs.vs { + push_point(&mut out, plain(*v)); + } + if let Some(l) = out.last_mut() { + l.bulge = 0.0; + } + push_point(&mut out, PolyVertex { p: x, bulge: sub(total - tx), ..tmpl }); + out.extend(vs.get(k + 1..).unwrap_or_default().iter().copied()); + } + set_kind(s, hp, EntityKind::LwPolyline(LwPolyline { vertices: out, ..pl.clone() }))?; + s.doc_mut()?.remove_entity(ho); Ok(Some(hp)) } @@ -217,20 +363,13 @@ pub(crate) fn fillet_pline( if curves::is_locked(s, h1) || curves::is_locked(s, h2) { return Err(other("The object is on a locked layer.")); } - let as_line = |k: &EntityKind| match k { - EntityKind::Line(l) => Some(Line::new(l.a.xy(), l.b.xy())), - _ => None, - }; let made = match (&e1.kind, &e2.kind) { (EntityKind::LwPolyline(pl), _) if h1 == h2 => same_polyline(s, h1, pl, (p1, p2), r, chamfer, trim)?, - (EntityKind::LwPolyline(pl), k) if as_line(k).is_some() => { - let ln = as_line(k).ok_or_else(|| other("Select a line."))?; - polyline_and_line(s, (h1, pl, p1), (h2, ln, p2), true, r, chamfer, trim)? - } - (k, EntityKind::LwPolyline(pl)) if as_line(k).is_some() => { - let ln = as_line(k).ok_or_else(|| other("Select a line."))?; - polyline_and_line(s, (h2, pl, p2), (h1, ln, p1), false, r, chamfer, trim)? + // The first polyline picked keeps the result. + (EntityKind::LwPolyline(pl), k) if matches!(k, EntityKind::Line(_) | EntityKind::LwPolyline(_)) => { + polyline_and_other(s, (h1, pl, p1), (h2, k, p2), true, r, chamfer, trim)? } + (k @ EntityKind::Line(_), EntityKind::LwPolyline(pl)) => polyline_and_other(s, (h2, pl, p2), (h1, k, p1), false, r, chamfer, trim)?, (EntityKind::LwPolyline(_), _) | (_, EntityKind::LwPolyline(_)) => { return Err(other("A polyline fillets or chamfers with a line, or with another segment of itself.")); } diff --git a/crates/engine/src/cmd/modify2/mocoro.rs b/crates/engine/src/cmd/modify2/mocoro.rs index 6954919bf..a5e44c458 100644 --- a/crates/engine/src/cmd/modify2/mocoro.rs +++ b/crates/engine/src/cmd/modify2/mocoro.rs @@ -178,9 +178,10 @@ impl MocoroM { fn undo(&mut self, s: &mut Session) -> Result { match self.history.pop() { Some((doc, base)) => { - // Settings changed meanwhile (a transparent command) stay. + // Settings changed meanwhile (a transparent command) stay. The drawing put + // back is an earlier one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); if s.doc()?.header != header { s.doc_mut()?.header = header; } diff --git a/crates/engine/src/cmd/modify2/pedit_multi.rs b/crates/engine/src/cmd/modify2/pedit_multi.rs index 7ba2f94d3..773209e86 100644 --- a/crates/engine/src/cmd/modify2/pedit_multi.rs +++ b/crates/engine/src/cmd/modify2/pedit_multi.rs @@ -126,7 +126,8 @@ impl PeditM { "reverse" | "r" => self.apply_all(s, "reverse", &json!({}))?, "undo" | "u" => match self.mundo.pop() { Some((d, multi, morig)) => { - *s.doc_mut()? = d; + // The saved drawing includes its handle seed. + s.state_mut()?.restore_drawing(std::sync::Arc::new(d)); self.multi = multi; self.morig = morig; s.set_selection(self.multi.clone()); diff --git a/crates/engine/src/cmd/modify2/splinedit.rs b/crates/engine/src/cmd/modify2/splinedit.rs index 8a5a1c745..aa9a8e5df 100644 --- a/crates/engine/src/cmd/modify2/splinedit.rs +++ b/crates/engine/src/cmd/modify2/splinedit.rs @@ -240,34 +240,8 @@ fn tolerance(sp: &Spline, tol: f64) -> Result { // ---------------- 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. -fn distinct(sp: &Spline) -> usize { - let n = sp.control.len(); - if sp.wraps() { - 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 - } else { - n - } -} - -/// Indices holding distinct control point `j` (with its repeats). -fn copies(sp: &Spline, j: usize) -> Vec { - let (n, u) = (sp.control.len(), distinct(sp)); - if j >= u { - return Vec::new(); - } - let mut out = vec![j]; - if u < n { - out.extend((j + u..n).step_by(u.max(1))); - } - out -} - fn move_control(sp: &Spline, j: usize, to: Vec2) -> Result { - let ix = copies(sp, j); + let ix = sp.control_copies(j); if ix.is_empty() { return Err(bad("splinedit", "control point index out of range")); } @@ -284,7 +258,7 @@ fn set_weight(sp: &Spline, j: usize, w: f64) -> Result { if !(w.is_finite() && w > 0.0) { return Err(other("Requires a positive weight.")); } - let ix = copies(sp, j); + let ix = sp.control_copies(j); if ix.is_empty() { return Err(bad("splinedit", "control point index out of range")); } @@ -307,7 +281,7 @@ fn set_weight(sp: &Spline, j: usize, w: f64) -> Result { /// shape as far as it can. fn delete_control(sp: &Spline, j: usize) -> Result { let p = sp.degree; - let (n, u) = (sp.control.len(), distinct(sp)); + let (n, u) = (sp.control.len(), sp.distinct_controls()); if j >= u { return Err(bad("splinedit", "control point index out of range")); } @@ -478,7 +452,7 @@ impl SplineditM { if fit { sp.fit.clone() } else { - let u = distinct(&sp); + let u = sp.distinct_controls(); sp.control.into_iter().take(u).collect() } } @@ -820,7 +794,7 @@ impl Interactive for SplineditM { Sub::VertexOrder => self.input_order(s, &sp, &i)?, Sub::VertexDelete => match point { Some(p) => { - let u = distinct(&sp); + let u = sp.distinct_controls(); let j = nearest(sp.control.get(..u).unwrap_or_default(), p).ok_or_else(|| other("The spline has no control points."))?; self.apply(s, json!({ "option": "vertexdelete", "index": j }))?; } diff --git a/crates/engine/src/cmd/modify2/tests.rs b/crates/engine/src/cmd/modify2/tests.rs index fccbc61ee..3eaa9b36f 100644 --- a/crates/engine/src/cmd/modify2/tests.rs +++ b/crates/engine/src/cmd/modify2/tests.rs @@ -411,6 +411,9 @@ fn chspace_json_and_command_line() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Default::default(), EntityKind::Viewport(vp)).unwrap(); @@ -823,6 +826,135 @@ fn offset_polyline_arc_bulge_follows_joined_endpoints() { assert!((arc.radius - 4.0).abs() < 1e-6, "radius {}", arc.radius); } +/// Offset the polyline `pl` by 1 towards `side` with OFFSETGAPTYPE = `gap`. +fn offset_with_gap(pts: Value, closed: bool, side: [f64; 2], gap: i64) -> cadcraft_doc::LwPolyline { + let mut s = Session::new(); + s.execute("setvar", &json!({"name": "OFFSETGAPTYPE", "value": gap})).unwrap(); + let pl = pline(&mut s, pts, closed); + s.execute("offset", &json!({"handle": pl, "distance": 1, "side": side})).unwrap(); + poly(&last(&s)) +} + +fn area(p: &cadcraft_doc::LwPolyline) -> f64 { + Polyline { vertices: p.vertices.clone(), closed: p.closed }.area() +} + +fn square() -> Value { + json!([[0, 0], [10, 0], [10, 10], [0, 10]]) +} + +#[test] +fn offset_gap_type_extends_fillets_or_chamfers_outside_corners() { + let p = offset_with_gap(square(), true, [12.0, 5.0], 0); + assert_eq!(p.vertices.len(), 4); + assert!(p.vertices.iter().all(|v| v.bulge == 0.0)); + assert!((area(&p) - 144.0).abs() < 1e-9, "area {}", area(&p)); + + let p = offset_with_gap(square(), true, [12.0, 5.0], 1); + assert_eq!(p.vertices.len(), 8); + let q = (std::f64::consts::PI / 8.0).tan(); + assert_eq!(p.vertices.iter().filter(|v| (v.bulge - q).abs() < 1e-9).count(), 4, "{:?}", p.vertices); + assert_eq!(p.vertices.iter().filter(|v| v.bulge == 0.0).count(), 4); + assert!((area(&p) - (140.0 + std::f64::consts::PI)).abs() < 1e-9, "area {}", area(&p)); + for v in p.vertices.iter().filter(|v| v.bulge != 0.0) { + let (arc, ccw) = cadcraft_geom::bulge_to_arc(v.p, p.vertices[(p.vertices.iter().position(|w| w == v).unwrap() + 1) % 8].p, v.bulge).unwrap(); + assert!(ccw && (arc.radius - 1.0).abs() < 1e-9, "{arc:?}"); + assert!([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].iter().any(|&(x, y)| near(arc.center, x, y)), "{arc:?}"); + } + + let p = offset_with_gap(square(), true, [12.0, 5.0], 2); + assert_eq!(p.vertices.len(), 8); + assert!(p.vertices.iter().all(|v| v.bulge == 0.0)); + let k = std::f64::consts::SQRT_2 - 1.0; + assert!(p.vertices.iter().any(|v| near(v.p, 10.0 + k, -1.0)) && p.vertices.iter().any(|v| near(v.p, 11.0, -k)), "{:?}", p.vertices); + // Every chamfer lies at distance 1 from its corner. + let corners = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)]; + for i in 0..8 { + let (a, b) = (p.vertices[i].p, p.vertices[(i + 1) % 8].p); + if a.dist(b) < 2.0 { + let c = corners.iter().min_by(|x, y| x.dist(a).total_cmp(&y.dist(a))).unwrap(); + assert!((cadcraft_geom::Line::new(a, b).dist(*c) - 1.0).abs() < 1e-9, "chamfer {a:?}-{b:?}"); + } + } + assert!((area(&p) - (144.0 - 2.0 * (1.0 - k) * (1.0 - k))).abs() < 1e-9, "area {}", area(&p)); +} + +#[test] +fn offset_gap_type_handles_open_outside_corners_in_both_orientations() { + let k = std::f64::consts::SQRT_2 - 1.0; + // A left turn offset to the right and a right turn offset to the left: the corner at (10, 0) + // is outside in both, with the copies at y = -1 / x = 11 and y = 1 / x = 11. + for (pts, side, sy) in [(json!([[0, 0], [10, 0], [10, 10]]), [5.0, -2.0], -1.0), (json!([[0, 0], [10, 0], [10, -10]]), [5.0, 2.0], 1.0)] { + let p = offset_with_gap(pts.clone(), false, side, 1); + assert_eq!(p.vertices.len(), 4, "{:?}", p.vertices); + assert!(near(p.vertices[1].p, 10.0, sy) && near(p.vertices[2].p, 11.0, 0.0), "{:?}", p.vertices); + let (arc, ccw) = cadcraft_geom::bulge_to_arc(p.vertices[1].p, p.vertices[2].p, p.vertices[1].bulge).unwrap(); + assert_eq!(ccw, sy < 0.0, "{arc:?}"); + assert!(near(arc.center, 10.0, 0.0) && (arc.radius - 1.0).abs() < 1e-9, "{arc:?}"); + + let p = offset_with_gap(pts, false, side, 2); + assert_eq!(p.vertices.len(), 4, "{:?}", p.vertices); + assert!(p.vertices.iter().all(|v| v.bulge == 0.0)); + let (a, b) = (p.vertices[1].p, p.vertices[2].p); + assert!(near(a, 10.0 + k, sy) && near(b, 11.0, sy * k), "{:?}", p.vertices); + assert!((cadcraft_geom::Line::new(a, b).dist(Vec2::new(10.0, 0.0)) - 1.0).abs() < 1e-9, "chamfer {a:?}-{b:?}"); + } +} + +#[test] +fn offset_gap_type_leaves_inside_corners_and_arc_joints_alone() { + let inward: Vec<_> = (0..3).map(|g| offset_with_gap(square(), true, [5.0, 2.0], g).vertices).collect(); + assert_eq!(inward[0].len(), 4); + assert!(inward.iter().all(|v| *v == inward[0])); + // An L's inside corner. + let l = json!([[0, 0], [10, 0], [10, 10]]); + let inside: Vec<_> = (0..3).map(|g| offset_with_gap(l.clone(), false, [8.0, 2.0], g).vertices).collect(); + assert!(near(inside[0][1].p, 9.0, 1.0), "{:?}", inside[0]); + assert!(inside.iter().all(|v| *v == inside[0])); + // A line into an arc keeps its join. + let la = json!([[0, -5], {"p": [10, 0], "bulge": 1}, [10, 10]]); + let arcs: Vec<_> = (0..3).map(|g| offset_with_gap(la.clone(), false, [12.0, 5.0], g).vertices).collect(); + assert!(arcs.iter().all(|v| *v == arcs[0])); + let outward: Vec<_> = (0..3).map(|g| offset_with_gap(la.clone(), false, [9.0, 5.0], g).vertices).collect(); + assert!(outward.iter().all(|v| *v == outward[0])); +} + +#[test] +fn offset_gap_type_leaves_lines_around_a_collapsed_arc_joined() { + // Offset 1 towards the centre of the radius-0.5 arc collapses it; the lines either side of + // it never met, so no gap type fills a corner between them. + let pts = json!([[-2, 0], {"p": [0, 0], "bulge": 1}, [0, -1], [1, -4]]); + let joined: Vec<_> = (0..3).map(|g| offset_with_gap(pts.clone(), false, [-0.3, -0.5], g).vertices).collect(); + assert!(joined[0].iter().all(|v| v.bulge == 0.0), "arc collapsed: {:?}", joined[0]); + assert!(joined.iter().all(|v| *v == joined[0]), "{joined:?}"); +} + +#[test] +fn offset_echoes_the_gap_type() { + let mut s = Session::new(); + s.execute("setvar", &json!({"name": "OFFSETGAPTYPE", "value": 1})).unwrap(); + s.cmdline("offset").unwrap(); + assert!(s.log.iter().any(|l| l.contains("OFFSETGAPTYPE=1")), "{:?}", s.log); +} + +#[test] +fn interactive_offset_previews_and_makes_the_gap_type_fill() { + for (gap, bulged) in [(1, 4), (2, 0)] { + let mut s = Session::new(); + s.execute("setvar", &json!({"name": "OFFSETGAPTYPE", "value": gap})).unwrap(); + pline(&mut s, square(), true); + s.cmdline("offset 1").unwrap(); + s.input(crate::Input::Point(Vec2::new(10.0, 5.0))).unwrap(); + let shown: Vec<_> = s.preview(Vec2::new(12.0, 5.0)).into_iter().map(|e| poly(&e.kind)).collect(); + assert_eq!(shown.len(), 1, "gap {gap}"); + s.input(crate::Input::Point(Vec2::new(12.0, 5.0))).unwrap(); + let made = poly(&last(&s)); + assert_eq!(made.vertices.len(), 8, "gap {gap}: {:?}", made.vertices); + assert_eq!(made.vertices.iter().filter(|v| v.bulge != 0.0).count(), bulged, "gap {gap}: {:?}", made.vertices); + assert_eq!(shown.first().map(|p| &p.vertices), Some(&made.vertices), "gap {gap}: preview matches the copy"); + } +} + #[test] fn offset_elliptical_arc_follows_picked_side() { let max_x = |side: Value| { diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index 9f3226c31..328e27221 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -48,6 +48,7 @@ pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } @@ -95,6 +96,7 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None }) } diff --git a/crates/engine/src/cmd/mtext_opts.rs b/crates/engine/src/cmd/mtext_opts.rs index c234271bf..301b2ea80 100644 --- a/crates/engine/src/cmd/mtext_opts.rs +++ b/crates/engine/src/cmd/mtext_opts.rs @@ -89,6 +89,7 @@ impl MTextOpts { line_spacing: self.spacing, line_spacing_exact: self.exact, columns: self.columns.clone().filter(|_| width > 0.0), + background: None, } } } diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 9208c2a0f..e687669a7 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -215,11 +215,25 @@ 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; - page.margins_mm = p.margins; + // 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 }; } fn unknown_device(cmd: &str, name: &str) -> EngineError { @@ -354,9 +368,16 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { o.remove("paper"); o.insert("width".into(), json!(pp.width)); o.insert("height".into(), json!(pp.height)); - o.insert("margins".into(), json!(pp.margins)); + // 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] })); if p.get("landscape").is_none() && layout.is_none() { - o.insert("landscape".into(), json!(dev.orientation == Orientation::Landscape)); + o.insert("landscape".into(), json!(landscape)); } } Ok(out) @@ -527,13 +548,22 @@ 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 => existing.as_ref().map(|e| e.margins).unwrap_or([0.0; 4]), + 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]), + }, Some(m) => { let a: Vec = 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.min(h) && b + t < w.max(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 && b + t < h => [l, b, r, t], _ => return Err(bad(cmd, "`paper.margins` must be [left, bottom, right, top] in mm, leaving a printable area")), } } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index fe7546528..cd14477c3 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -7,6 +7,7 @@ mod dash_units; mod matchprop; mod rename; mod set; +pub(crate) mod xdata; pub use matchprop::MatchProps; use set::run_set; @@ -24,10 +25,11 @@ pub fn specs() -> Vec { CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), CommandSpec::new("properties.set", "Set Properties", run_set).params( "{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, annotative?, \ - , text: style?, justify?, oblique?, positionX/Y/Z?, alignmentX/Y?, \ + , text: style?, justify?, oblique?, backwards?, upsideDown?, positionX/Y/Z?, alignmentX/Y?, \ mtext: style?, justify?, lineSpacing?, lineSpacingDistance?, lineSpacingStyle?: atLeast | exactly, positionX/Y/Z?, \ dimension: dimStyle?, textOverride?, textRotation?, textPositionX/Y?, prefix?, suffix?, altPrefix?, altSuffix?, dimScale?, precision?, \ - , clearOverrides?, clear?: [variable]} \ + , clearOverrides?, clear?: [variable], \ + xdata?: {\"APP\": [[code, value], …] | null} (replaces or removes that application's extended data; codes 1000–1071, points as [1010, [x, y, z]])} \ → {changed, locked, message?, ignored: keys no selected object took} (the keys are those of `properties.describe` rows): objects on locked layers \ (and, during REFEDIT, outside the working set) are left out, and `message` says how many", ), @@ -125,6 +127,9 @@ pub(super) fn entity_props(d: &cadcraft_doc::Drawing, e: &cadcraft_doc::Entity) o.insert("annotative".into(), json!(cadcraft_doc::is_annotative(e))); o.insert("annotativeScales".into(), json!(e.common.anno_scales.iter().map(|s| s.name.clone()).collect::>())); } + if let (Some(x), Some(o)) = (xdata::xdata_json(&e.common.xdata), v.as_object_mut()) { + o.insert("xdata".into(), x); + } let geo = serde_json::to_value(&e.kind).unwrap_or(Value::Null); if let (Some(o), Some(g)) = (v.as_object_mut(), geo.as_object()) { o.insert("geometry".into(), Value::Object(g.clone())); @@ -556,6 +561,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result { } let st = d.text_styles.by_name_mut(&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) { @@ -794,6 +800,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result { } let st = d.dim_styles.by_name_mut(&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,6 +1024,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result { } let st = d.linetypes.by_name_mut(&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) { @@ -1044,6 +1052,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result { } } } + d.rename_proxy_linetype(&from, &to); } _ => return Err(bad("rename", "unsupported table")), } diff --git a/crates/engine/src/cmd/props/rename.rs b/crates/engine/src/cmd/props/rename.rs index b295064e9..8ebb8da0b 100644 --- a/crates/engine/src/cmd/props/rename.rs +++ b/crates/engine/src/cmd/props/rename.rs @@ -2,6 +2,7 @@ use std::sync::Arc; +use cadcraft_doc::foreign::Foreign; use cadcraft_doc::{Drawing, EntityKind, EntityStore, Handle}; use serde_json::json; @@ -54,6 +55,7 @@ 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)), @@ -102,6 +104,13 @@ 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", diff --git a/crates/engine/src/cmd/props/set.rs b/crates/engine/src/cmd/props/set.rs index c67a4a834..fa5401896 100644 --- a/crates/engine/src/cmd/props/set.rs +++ b/crates/engine/src/cmd/props/set.rs @@ -48,6 +48,7 @@ const SET_KEYS: &[&str] = &[ "suffix", "altPrefix", "altSuffix", + "xdata", // An insert's or hatch's scale; a dimension's overall scale is `dimScale` (or DIMSCALE). "scale", ]; @@ -324,6 +325,32 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { .map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))) .transpose()?; let dim_vars = DimVars::new(d, p)?; + // xdata is checked before anything changes (`ensure_layer` below adds a layer the drawing + // keeps even when the command then fails): no object may end up with more xdata than a + // file holds for one. + let xd = p.get("xdata").filter(|v| !v.is_null()).map(super::xdata::xdata_from_json).transpose().map_err(|m| bad("properties.set", m))?; + if let Some(changes) = &xd { + for h in &hs { + let Some(e) = d.entity(*h) else { continue }; + // A dimension's `ACAD` run is written from its overrides (textHeight, arrowSize…) and + // read back into them: raw groups under that name would be lost on save. + if let Some((app, _)) = changes.iter().find(|(app, _)| cadcraft_doc::is_model_xdata_app(app, &e.kind)) { + return Err(bad( + "properties.set", + format!( + "{}: xdata application {app} of a {} is written from its own properties and can't be set as raw data", + h.hex(), + e.kind.dxf_name() + ), + )); + } + let mut after = e.common.xdata.clone(); + super::xdata::apply(&mut after, changes); + if after.len() > cadcraft_doc::MAX_XDATA_GROUPS { + return Err(bad("properties.set", format!("{}: xdata would exceed {} groups", h.hex(), cadcraft_doc::MAX_XDATA_GROUPS))); + } + } + } // A pattern must be one each hatch can take, as HATCHEDIT refuses others. if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty()) && hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v))) @@ -373,6 +400,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { EntityKind::Hatch(ha) => hatch(ha, &c, &mut used), _ => {} } + if let Some(changes) = &xd { + super::xdata::apply(&mut e.common.xdata, changes); + used.insert("xdata"); + } })?; } let ignored: Vec<&str> = p @@ -548,6 +579,14 @@ fn text(t: &mut Text, c: &Call<'_>, h: Handle, used: &mut Used<'_>) { t.oblique = x.to_radians(); used.insert("oblique"); } + if let Some(b) = p.get("backwards").and_then(Value::as_bool) { + t.backwards = b; + used.insert("backwards"); + } + if let Some(b) = p.get("upsideDown").and_then(Value::as_bool) { + t.upside_down = b; + used.insert("upsideDown"); + } if let Some((ha, va)) = str_param(p, "justify").and_then(crate::cmd::draw::justify) { set_justify(t, ha, va, c.prep.ends.get(&h).copied()); used.insert("justify"); diff --git a/crates/engine/src/cmd/props/xdata.rs b/crates/engine/src/cmd/props/xdata.rs new file mode 100644 index 000000000..48c5b0827 --- /dev/null +++ b/crates/engine/src/cmd/props/xdata.rs @@ -0,0 +1,293 @@ +//! Xdata as JSON, for `entities`, `properties` and `properties.set`: an object by application, +//! `{"APP": [[code, value], …]}`, with each group's value typed by its code: strings for 1000, +//! 1002 (`{` / `}`), 1003 (a layer name), 1004 (hex) and 1005 (a handle), a point `[x, y, z]` +//! for 1010–1013 (its 1020 and 1030 groups folded in), numbers for 1040–1042, integers for +//! 1070 and 1071. Setting takes the same form; `null` for an application removes its data. + +use cadcraft_doc::{MAX_XDATA_GROUPS, RawTag, check_xdata_app_name, check_xdata_groups, is_reserved_xdata_app, set_xdata_app, xdata_apps}; +use serde_json::{Map, Value, json}; + +/// Most applications one `properties.set` call may set. +const MAX_APPS_PER_CALL: usize = 256; + +/// Which applications' xdata a query returns. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) enum XdataSelect { + /// None (the default). + #[default] + None, + /// Every application's. + All, + /// These applications' (any case); an entity without any of them doesn't match the query. + Apps(Vec), +} + +impl XdataSelect { + /// The `xdata` parameter of a query: `true`, `false`, an application name or a list of names. + pub(crate) fn parse(v: Option<&Value>) -> Result { + const MSG: &str = "`xdata` must be true, false, an application name or a list of names"; + match v { + None | Some(Value::Null) => Ok(Self::None), + Some(Value::Bool(b)) => Ok(if *b { Self::All } else { Self::None }), + Some(Value::String(s)) => Ok(Self::Apps(vec![s.clone()])), + Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_APPS_PER_CALL => { + a.iter().map(|x| x.as_str().map(str::to_string).ok_or_else(|| MSG.to_string())).collect::, _>>().map(Self::Apps) + } + Some(_) => Err(MSG.into()), + } + } + + /// Whether the selection narrows a query to entities carrying the named applications' data. + pub(crate) fn filters(&self) -> bool { + matches!(self, Self::Apps(_)) + } + + /// Whether an entity with this xdata passes the filter. + pub(crate) fn matches(&self, xdata: &[RawTag]) -> bool { + match self { + Self::None | Self::All => true, + Self::Apps(apps) => xdata_apps(xdata).iter().any(|(name, _)| apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))), + } + } + + /// The selected applications' data of an entity as JSON; `None` when there is none to show. + pub(crate) fn json(&self, xdata: &[RawTag]) -> Option { + let apps = match self { + Self::None => return None, + Self::All => None, + Self::Apps(apps) => Some(apps), + }; + let mut out = Map::new(); + for (name, groups) in xdata_apps(xdata) { + if apps.is_some_and(|apps| !apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))) { + continue; + } + // A second run of the same application (not something AutoCAD writes; `ACME` and + // `acme` are one application, as `set_xdata_app` treats them) joins the first. + let key = out.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned(); + match key.and_then(|k| out.get_mut(&k)) { + Some(Value::Array(v)) => v.extend(groups_json(groups)), + _ => { + out.insert(name.to_string(), Value::Array(groups_json(groups))); + } + } + } + (!out.is_empty()).then_some(Value::Object(out)) + } +} + +/// Every application's data of an entity as JSON; `None` when it has none. +pub(crate) fn xdata_json(xdata: &[RawTag]) -> Option { + XdataSelect::All.json(xdata) +} + +fn number(t: &RawTag) -> Value { + t.value.trim().parse::().ok().filter(|v| v.is_finite()).map_or_else(|| json!(t.value), |v| json!(v)) +} + +fn integer(t: &RawTag) -> Value { + t.value.trim().parse::().map_or_else(|_| json!(t.value), |v| json!(v)) +} + +/// One application's groups as `[code, value]` pairs, points folded. +fn groups_json(groups: &[RawTag]) -> Vec { + let mut out = Vec::with_capacity(groups.len()); + let mut i = 0; + while let Some(t) = groups.get(i) { + let v = match t.code { + 1010..=1013 => { + let y = groups.get(i + 1).filter(|y| y.code == t.code + 10); + let z = groups.get(i + 2).filter(|z| z.code == t.code + 20); + if let (Some(y), Some(z)) = (y, z) { + i += 3; + out.push(json!([t.code, [number(t), number(y), number(z)]])); + continue; + } + number(t) + } + 1020..=1033 | 1040..=1042 => number(t), + 1070 | 1071 => integer(t), + _ => json!(t.value), + }; + out.push(json!([t.code, v])); + i += 1; + } + out +} + +/// What `properties.set`'s `xdata` parameter asks for: per application, its new groups (with +/// their `1001` left out) or `None` to remove it. Everything is checked here: names, codes, value +/// types and ranges, braces, sizes; reserved applications are refused. +pub(crate) fn xdata_from_json(v: &Value) -> Result>)>, String> { + let Some(obj) = v.as_object() else { return Err("`xdata` must be an object {\"APP\": [[code, value], …] | null}".into()) }; + if obj.len() > MAX_APPS_PER_CALL { + return Err(format!("`xdata` may name at most {MAX_APPS_PER_CALL} applications")); + } + let mut out = Vec::with_capacity(obj.len()); + for (app, groups) in obj { + check_xdata_app_name(app).map_err(|e| e.to_string())?; + if is_reserved_xdata_app(app) { + return Err(format!("xdata application `{app}` is reserved: CADCraft writes its data itself")); + } + let groups = match groups { + Value::Null => None, + Value::Array(a) => Some(groups_from_json(app, a)?), + _ => return Err(format!("xdata of `{app}` must be a list of [code, value] pairs, or null to remove it")), + }; + out.push((app.trim().to_string(), groups)); + } + Ok(out) +} + +/// `[[code, value], …]` of one application as groups, each value checked for its code. +fn groups_from_json(app: &str, pairs: &[Value]) -> Result, String> { + if pairs.len() > MAX_XDATA_GROUPS { + return Err(format!("xdata of `{app}`: at most {MAX_XDATA_GROUPS} groups")); + } + let mut out = Vec::with_capacity(pairs.len()); + for (n, pair) in pairs.iter().enumerate() { + let at = || format!("xdata of `{app}`, group {}", n + 1); + let (code, value) = match pair.as_array().map(Vec::as_slice) { + Some([c, v]) => (c.as_i64().and_then(|c| i32::try_from(c).ok()).ok_or_else(|| format!("{}: the code must be an integer", at()))?, v), + _ => return Err(format!("{}: each group is a [code, value] pair", at())), + }; + let real = |x: &Value| x.as_f64().filter(|x| x.is_finite()).map(craft_dxf::format_real); + match code { + 1000 | 1003 => { + let s = value.as_str().ok_or_else(|| format!("{}: group {code} takes a string", at()))?; + out.push(RawTag { code, value: s.to_string() }); + } + 1002 => match value.as_str() { + Some(b @ ("{" | "}")) => out.push(RawTag { code, value: b.to_string() }), + _ => return Err(format!("{}: group 1002 takes \"{{\" or \"}}\"", at())), + }, + 1004 => { + let s = value.as_str().ok_or_else(|| format!("{}: group 1004 takes hex text", at()))?; + out.push(RawTag { code, value: s.trim().to_ascii_uppercase() }); + } + 1005 => { + let s = value.as_str().ok_or_else(|| format!("{}: group 1005 takes a hex handle", at()))?; + out.push(RawTag { code, value: s.trim().to_ascii_uppercase() }); + } + 1010..=1013 => { + let p = value.as_array().filter(|a| a.len() == 2 || a.len() == 3).and_then(|a| a.iter().map(real).collect::>>()); + let Some(p) = p else { return Err(format!("{}: group {code} takes a point [x, y, z] of finite numbers", at())) }; + out.push(RawTag { code, value: p.first().cloned().unwrap_or_default() }); + out.push(RawTag { code: code + 10, value: p.get(1).cloned().unwrap_or_default() }); + out.push(RawTag { code: code + 20, value: p.get(2).cloned().unwrap_or_else(|| "0.0".into()) }); + } + 1020..=1023 | 1030..=1033 => return Err(format!("{}: give the point as [{}, [x, y, z]]", at(), 1010 + (code % 10))), + 1040..=1042 => { + let x = real(value).ok_or_else(|| format!("{}: group {code} takes a finite number", at()))?; + out.push(RawTag { code, value: x }); + } + 1070 | 1071 => { + let i = value.as_i64().ok_or_else(|| format!("{}: group {code} takes an integer", at()))?; + out.push(RawTag { code, value: i.to_string() }); + } + _ => return Err(format!("{}: {code} is not an xdata group code (1000–1071)", at())), + } + } + check_xdata_groups(&out).map_err(|e| format!("xdata of `{app}`: {e}"))?; + Ok(out) +} + +/// Apply a parsed `xdata` parameter to an entity's xdata. +pub(crate) fn apply(xdata: &mut Vec, changes: &[(String, Option>)]) { + for (app, groups) in changes { + set_xdata_app(xdata, app, groups.as_deref()); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn t(code: i32, value: &str) -> RawTag { + RawTag { code, value: value.into() } + } + + #[test] + fn json_round_trip_types_every_kind() { + let x = vec![ + t(1001, "ACME"), + t(1000, "D-07"), + t(1002, "{"), + t(1003, "Walls"), + t(1004, "0AFF"), + t(1005, "2A"), + t(1010, "1.5"), + t(1020, "2.0"), + t(1030, "0.0"), + t(1040, "2.5"), + t(1070, "3"), + t(1071, "70000"), + t(1002, "}"), + t(1001, "PE_URL"), + t(1000, "https://example.com"), + ]; + let j = xdata_json(&x).unwrap(); + assert_eq!( + j["ACME"], + json!([ + [1000, "D-07"], + [1002, "{"], + [1003, "Walls"], + [1004, "0AFF"], + [1005, "2A"], + [1010, [1.5, 2.0, 0.0]], + [1040, 2.5], + [1070, 3], + [1071, 70000], + [1002, "}"] + ]) + ); + assert_eq!(j["PE_URL"], json!([[1000, "https://example.com"]])); + let back = xdata_from_json(&j).unwrap(); + let mut y = Vec::new(); + apply(&mut y, &back); + assert_eq!(y, x); + assert_eq!(xdata_json(&[]), None); + assert_eq!(XdataSelect::Apps(vec!["pe_url".into()]).json(&x).unwrap().as_object().unwrap().len(), 1); + assert!(XdataSelect::Apps(vec!["nope".into()]).json(&x).is_none()); + assert!(!XdataSelect::Apps(vec!["nope".into()]).matches(&x) && XdataSelect::Apps(vec!["acme".into()]).matches(&x)); + } + + #[test] + fn bad_input_is_refused() { + for bad in [ + json!([]), + json!({"": [[1000, "x"]]}), + json!({"CADCRAFT": [[1000, "x"]]}), + json!({"A": [[1000, 5]]}), + json!({"A": [[1001, "B"]]}), + json!({"A": [[8, "layer"]]}), + json!({"A": [[1002, "("]]}), + json!({"A": [[1002, "{"]]}), + json!({"A": [[1010, [1, 2, 3, 4]]]}), + json!({"A": [[1010, [1, "x"]]]}), + json!({"A": [[1010, 1]]}), + json!({"A": [[1020, 1]]}), + json!({"A": [[1040, "1"]]}), + json!({"A": [[1070, 1.5]]}), + json!({"A": [[1070, 70000]]}), + json!({"A": [[1071, 1e12]]}), + json!({"A": [[1004, "ABC"]]}), + json!({"A": [[1005, "xyz"]]}), + json!({"A": [1000, "x"]}), + json!({"A": "x"}), + json!({"A": [[1000, "x".repeat(300)]]}), + ] { + assert!(xdata_from_json(&bad).is_err(), "{bad}"); + } + assert_eq!(xdata_from_json(&json!({"A": null})).unwrap(), vec![("A".to_string(), None)]); + assert_eq!(xdata_from_json(&json!({"A": []})).unwrap(), vec![("A".to_string(), Some(Vec::new()))]); + assert!(XdataSelect::parse(Some(&json!(1))).is_err()); + assert!(XdataSelect::parse(Some(&json!([]))).is_err()); + assert!(XdataSelect::parse(Some(&json!([1]))).is_err()); + assert_eq!(XdataSelect::parse(Some(&json!(true))).unwrap(), XdataSelect::All); + assert_eq!(XdataSelect::parse(Some(&json!("A"))).unwrap(), XdataSelect::Apps(vec!["A".into()])); + assert_eq!(XdataSelect::parse(None).unwrap(), XdataSelect::None); + } +} diff --git a/crates/engine/src/cmd/table/cells.rs b/crates/engine/src/cmd/table/cells.rs index f7c695036..041fe5f0c 100644 --- a/crates/engine/src/cmd/table/cells.rs +++ b/crates/engine/src/cmd/table/cells.rs @@ -258,7 +258,7 @@ fn run_cellstyle_use(s: &mut Session, p: &Value) -> Result { 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 = s.doc()?.table_styles.clone(); + let styles: Vec = s.doc()?.table_styles.to_vec(); 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) { diff --git a/crates/engine/src/cmd/table/paste.rs b/crates/engine/src/cmd/table/paste.rs index 746d2c0ca..7ca6c8846 100644 --- a/crates/engine/src/cmd/table/paste.rs +++ b/crates/engine/src/cmd/table/paste.rs @@ -1,6 +1,6 @@ //! Paste tabular clipboard data (TSV from Excel or other spreadsheets) as a native `ACAD_TABLE`. -use cadcraft_doc::{EntityKind, Table, TableCell, TableStyle}; +use cadcraft_doc::{CellStyle, EntityKind, Table, TableCell, TableStyle}; use cadcraft_geom::Vec2; use serde_json::{Value, json}; @@ -85,33 +85,54 @@ pub fn is_tsv_table(text: &str) -> bool { } /// Build an `ACAD_TABLE` entity from parsed cell strings, sizing columns and rows cleanly. -fn build_table(st: &TableStyle, at: Vec2, data: &[Vec], text_height: Option) -> Table { +fn build_table(doc: &cadcraft_doc::Drawing, st: &TableStyle, at: Vec2, data: &[Vec], text_height: Option) -> Table { let cols = data.first().map_or(1, Vec::len).max(1); let th = text_height.unwrap_or_else(|| if st.text_height.is_finite() && st.text_height > 0.0 { st.text_height } else { 2.5 }); - let margin = if st.text_height.is_finite() && st.text_height > 0.0 { st.margin * (th / st.text_height) } else { th * 0.5 }; + // Why: `cadcraft_render::table::layout` scales the resolved `Data` cell style's text height + // and horizontal/vertical margins by `th / st.text_height`, so sizing widths, wrap width, and + // row heights with the same scaled `Data` metrics keeps wrapped text inside custom-styled cells. + let scale = if st.text_height.is_finite() && st.text_height > 0.0 { th / st.text_height } else { 1.0 }; + let data_cs = st.cell_style(CellStyle::DATA); + let cell_th = Some(data_cs.text_height * scale).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(th); + let margin_h = Some(data_cs.margin_h * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5); + let margin_v = Some(data_cs.margin_v * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5); let mut col_chars = vec![1usize; cols]; - let mut row_heights = Vec::with_capacity(data.len()); let mut cells = Vec::with_capacity(data.len()); for row in data { - let mut max_lines = 1usize; let mut table_row = Vec::with_capacity(cols); for (c, raw) in row.iter().enumerate() { - let line_count = raw.split('\n').count().clamp(1, 50); - max_lines = max_lines.max(line_count); let max_chars = raw.split('\n').map(|line| line.chars().count()).max().unwrap_or(0).clamp(1, 60); if let Some(slot) = col_chars.get_mut(c) { *slot = (*slot).max(max_chars); } table_row.push(TableCell { text: cadcraft_doc::mtext_literal(raw), ..TableCell::default() }); } - row_heights.push(th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin); cells.push(table_row); } - let min_col_w = (th * 4.0 + 2.0 * margin).max(th * 5.0); - let col_widths: Vec = col_chars.into_iter().map(|chars| (0.75 * th * chars as f64 + 2.0 * margin + 0.5 * th).max(min_col_w)).collect(); + let min_col_w = (cell_th * 4.0 + 2.0 * margin_h).max(cell_th * 5.0); + let col_widths: Vec = + col_chars.into_iter().map(|chars| (0.95 * cell_th * chars as f64 + 2.0 * margin_h + 0.5 * cell_th).max(min_col_w)).collect(); + + let mut row_heights = Vec::with_capacity(cells.len()); + for row in &cells { + let mut max_lines = 1usize; + for (c, cell) in row.iter().enumerate() { + if cell.text.is_empty() { + continue; + } + // Why: share the renderer's resolved MTEXT sizing inputs (named font, width_factor, + // oblique) so pasted row heights match how `cadcraft_render::table::draw` wraps cells. + let inner_w = col_widths.get(c).copied().unwrap_or(0.0) - 2.0 * margin_h; + let wrap_w = if inner_w.is_finite() && inner_w > 0.0 { inner_w } else { 0.0 }; + let mp = cadcraft_render::table_text_mtext_params(doc, &data_cs.text_style, Vec2::ZERO, cell_th, data_cs.align.clamp(1, 9), wrap_w); + let line_count = cadcraft_fonts::layout_mtext_with(&cell.text, &mp).lines.len().max(1); + max_lines = max_lines.max(line_count); + } + row_heights.push(cell_th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin_v); + } Table { insert: v3(at), col_widths, row_heights, cells, style: st.name.clone(), text_height: th, title: false, header: false, ..Table::default() } } @@ -142,7 +163,7 @@ pub(super) fn run_pastetable(s: &mut Session, p: &Value) -> Result { let rows = data.len(); let cols = data.first().map_or(0, Vec::len); let st = style_of(s); - let table = build_table(&st, at, &data, th); + let table = build_table(s.doc()?, &st, at, &data, th); let h = s.add_entity(EntityKind::Table(table))?; s.set_selection(vec![h]); Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols })) @@ -207,7 +228,16 @@ impl Session { let rows = data.len(); let cols = data.first().map_or(0, Vec::len); let st = style_of(self); - let table = build_table(&st, Vec2::ZERO, &data, text_height); + let fallback; + let doc = match self.doc() { + Ok(d) => d, + Err(_) => { + fallback = cadcraft_doc::Drawing::default(); + &fallback + } + }; + let table = build_table(doc, &st, Vec2::ZERO, &data, text_height); + self.last_paste_table = Some((tsv.to_string(), text_height)); let enabled = crate::find_command("pastetable").map_or((|_| Ok(())) as fn(&Session) -> std::result::Result<(), String>, |c| c.enabled); self.launch_interactive("pastetable", enabled, Box::new(PasteTableM { table, rows, cols })) } @@ -301,4 +331,148 @@ mod tests { assert_eq!(s.commands_started, before_started + 1); assert_eq!(s.last_command.as_deref(), Some("pastetable")); } + + #[test] + fn long_wrapped_cells_cap_col_width_and_grow_row_height() { + let mut s = Session::new(); + let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega"; + assert!(long_cell.chars().count() > 60); + let tsv = format!("Short\t{long_cell}\n\"First line\n{long_cell}\"\t\nA\tB",); + let res = s.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0], "text_height": 2.0 })).unwrap(); + let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap(); + let e = s.doc().unwrap().entity(h).unwrap(); + let EntityKind::Table(t) = &e.kind else { panic!("expected table") }; + + // Column 1 width is capped at 60 characters rather than growing unboundedly. + let st = style_of(&s); + let expected_cap_w = 0.95 * 2.0 * 60.0 + 2.0 * (st.margin * (2.0 / st.text_height)) + 0.5 * 2.0; + assert!((t.col_widths[1] - expected_cap_w).abs() < 1e-9); + // Row 0 wraps into multiple lines and is taller than single-line Row 2. + assert!(t.row_heights[0] > t.row_heights[2]); + // Row 1 combines a hard newline and a long wrapped line, making it taller than Row 0. + assert!(t.row_heights[1] > t.row_heights[0]); + } + + #[test] + fn custom_data_cell_style_sizes_wrapped_rows_and_columns() { + let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega"; + let tsv = format!("Short\t{long_cell}\nA\tB"); + + let mut base = Session::new(); + let r_base = base.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap(); + let h_base = cadcraft_doc::Handle::parse_hex(r_base["handle"].as_str().unwrap()).unwrap(); + let EntityKind::Table(t_base) = &base.doc().unwrap().entity(h_base).unwrap().kind else { panic!("expected table") }; + + let mut custom = Session::new(); + { + let doc = custom.doc_mut().unwrap(); + doc.text_styles.push(cadcraft_doc::TextStyle { name: "WideNotes".into(), width_factor: 1.8, ..cadcraft_doc::TextStyle::default() }); + doc.table_styles.iter_mut().find(|ts| ts.name.eq_ignore_ascii_case("Standard")).unwrap().set_cell_style(CellStyle { + name: CellStyle::DATA.into(), + text_style: "WideNotes".into(), + text_height: 5.0, + margin_h: 4.0, + margin_v: 3.0, + ..CellStyle::default() + }); + } + let r_custom = custom.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap(); + let h_custom = cadcraft_doc::Handle::parse_hex(r_custom["handle"].as_str().unwrap()).unwrap(); + let doc = custom.doc().unwrap(); + let EntityKind::Table(t_custom) = &doc.entity(h_custom).unwrap().kind else { panic!("expected table") }; + + assert!(t_custom.col_widths[1] > t_base.col_widths[1]); + assert!(t_custom.row_heights[0] > t_base.row_heights[0]); + assert!(t_custom.row_heights[0] > t_custom.row_heights[1]); + + let g = cadcraft_render::table_geometry(doc, t_custom); + let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap(); + assert_eq!(tx.style, "WideNotes"); + let laid = cadcraft_render::layout_table_text(doc, tx); + let default_laid = cadcraft_fonts::layout_mtext_with( + &tx.text, + &cadcraft_fonts::MTextParams { attach: tx.attach, width: tx.wrap_width, ..cadcraft_fonts::MTextParams::new(tx.at, tx.height) }, + ); + assert!(laid.lines.len() > default_laid.lines.len(), "wider text style must wrap into more lines"); + assert!(t_custom.row_heights[0] >= laid.lines.len() as f64 * tx.height * 5.0 / 3.0 + 2.0 * 3.0 - 1e-6); + assert!(!laid.strokes.is_empty()); + for s in &laid.strokes { + for p in s { + assert!( + p.y <= t_custom.insert.y + 1e-6 && p.y >= t_custom.insert.y - t_custom.row_heights[0] - 1e-6, + "rendered stroke spilled outside row 0 [{}..={}]: y={}", + t_custom.insert.y - t_custom.row_heights[0], + t_custom.insert.y, + p.y + ); + } + } + } + + #[test] + fn cell_wrapping_past_fifty_lines_is_not_clamped() { + let mut s = Session::new(); + let long_cell = vec!["word"; 800].join(" "); + let res = s.execute("pastetable", &json!({ "tsv": format!("A\t{long_cell}\n1\t2"), "at": [0, 0], "text_height": 2.0 })).unwrap(); + let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap(); + let doc = s.doc().unwrap(); + let EntityKind::Table(t) = &doc.entity(h).unwrap().kind else { panic!("expected table") }; + + let g = cadcraft_render::table_geometry(doc, t); + let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap(); + let laid = cadcraft_render::layout_table_text(doc, tx); + assert!(laid.lines.len() > 50, "expected >50 wrapped lines, got {}", laid.lines.len()); + let st = style_of(&s); + let margin_v = st.margin * (2.0 / st.text_height); + let fifty_line_h = 2.0 * (50.0 * 5.0 / 3.0) + 2.0 * margin_v; + assert!(t.row_heights[0] > fifty_line_h); + assert!((t.row_heights[0] - (2.0 * (laid.lines.len() as f64 * 5.0 / 3.0) + 2.0 * margin_v)).abs() < 1e-9); + } + + #[test] + fn enter_repeats_pastetable_with_last_payload() { + let mut s = Session::new(); + s.start_paste_table("A\tB\n1\t2\n", Some(3.0)).unwrap(); + s.input(Input::Point(Vec2::ZERO)).unwrap(); + assert!(s.running.is_none()); + + s.input(Input::Enter).unwrap(); + assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("pastetable")); + s.input(Input::Point(Vec2::new(50.0, 0.0))).unwrap(); + assert!(s.running.is_none()); + + let tables: Vec<_> = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Table(t) => Some(t), + _ => None, + }) + .collect(); + assert_eq!(tables.len(), 2); + assert_eq!(tables[0].cells, tables[1].cells); + assert_eq!(tables[0].text_height, 3.0); + assert_eq!(tables[1].text_height, 3.0); + assert_eq!(tables[0].insert.xy(), Vec2::ZERO); + assert_eq!(tables[1].insert.xy(), Vec2::new(50.0, 0.0)); + } + + #[test] + fn execute_pastetable_without_tsv_still_errors_and_other_command_overrides_repeat() { + let mut s = Session::new(); + let err = s.execute("pastetable", &Value::Null).unwrap_err().to_string(); + assert!(err.contains("`tsv` string is required"), "{err}"); + + s.start_paste_table("A\tB\n1\t2\n", None).unwrap(); + s.input(Input::Point(Vec2::ZERO)).unwrap(); + + for t in ["line", "0,0", "10,0", ""] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_none()); + s.input(Input::Enter).unwrap(); + assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("line")); + } } diff --git a/crates/engine/src/cmd/tolerance.rs b/crates/engine/src/cmd/tolerance.rs index b4edfe0f9..ffa473bf8 100644 --- a/crates/engine/src/cmd/tolerance.rs +++ b/crates/engine/src/cmd/tolerance.rs @@ -307,6 +307,8 @@ pub(crate) fn explode(d: &Drawing, e: &Entity, t: &Tolerance) -> Vec { style: st.text_style.clone(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }))); } v diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index c53e00a6c..30da34b67 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -397,7 +397,8 @@ impl TrimM { let e = d.entity(h)?; // Half a pixel: finer than the eye can tell apart, coarse enough to stay quick. let tol = (s.pixel_size() / 2.0).max(1e-9); - let part = if self.extend { + let extending = self.extend ^ s.shift_down; + let part = if extending { let grown = Entity { kind: extended(s, h, cursor, cut).ok()?, ..(**e).clone() }; uncovered(d, &grown, std::slice::from_ref(&e.kind), tol) } else { @@ -414,7 +415,8 @@ impl TrimM { Edges { only: self.edges.as_deref(), implied: !quick && implied } } fn select_edges(&mut self, s: &mut Session) { - s.echo(if self.extend { "Select boundary edges ..." } else { "Select cutting edges ..." }); + let extending = self.extend ^ s.shift_down; + s.echo(if extending { "Select boundary edges ..." } else { "Select cutting edges ..." }); s.set_selection(Vec::new()); self.stage = Stage::Edges(Vec::new()); } @@ -503,16 +505,27 @@ impl Interactive for TrimM { fn prompt(&self, s: &Session) -> Prompt { match &self.stage { Stage::Pick => { - let (msg, first) = if self.extend { - ("Select object to extend or shift-select to trim", "Boundary edges") + let extending = self.extend ^ s.shift_down; + let (msg, first) = if extending { + let msg = if s.shift_down { + "Select object to extend or release Shift to trim" + } else { + "Select object to extend or shift-select to trim" + }; + (msg, "Boundary edges") } else { - ("Select object to trim or shift-select to extend", "cuTting edges") + let msg = if s.shift_down { + "Select object to trim or release Shift to extend" + } else { + "Select object to trim or shift-select to extend" + }; + (msg, "cuTting edges") }; let mut kw = vec![first, "Fence", "Crossing", "mOde", "Project"]; if !quick_mode(s) { kw.push("Edge"); } - if !self.extend { + if !extending { kw.push("eRase"); } kw.push("Undo"); @@ -528,7 +541,8 @@ impl Interactive for TrimM { Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT), Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT), Stage::Mode => { - let msg = if self.extend { "Enter an extend mode option" } else { "Enter a trim mode option" }; + let extending = self.extend ^ s.shift_down; + let msg = if extending { "Enter an extend mode option" } else { "Enter a trim mode option" }; Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" }) } Stage::Project => { @@ -551,7 +565,7 @@ impl Interactive for TrimM { self.cut.take(); let quick = quick_mode(s); let implied = edge_mode(s); - let extending = self.extend; + let extending = self.extend ^ s.shift_down; match self.stage.clone() { Stage::Mode | Stage::Project | Stage::Edge => self.option(s, i), Stage::Edges(mut picked) => { @@ -682,9 +696,10 @@ impl Interactive for TrimM { } "Undo" => match self.undo.pop() { Some(doc) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an + // earlier one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; } None => s.echo("Nothing to undo."), @@ -719,7 +734,8 @@ impl Interactive for TrimM { return None; } let px = (s.pixel_size() / 2.0).max(1e-9); - Some(picks_preview(s, &work, self.extend, self.edges(quick, implied), quick, tol, px)) + let extending = self.extend ^ s.shift_down; + Some(picks_preview(s, &work, extending, self.edges(quick, implied), quick, tol, px)) } fn preview(&self, _s: &Session, c: Vec2) -> Vec { match &self.stage { @@ -791,7 +807,9 @@ fn uncovered(d: &Drawing, e: &Entity, others: &[EntityKind], tol: f64) -> Vec = ends.iter().filter(|p| ab.closest(**p).dist(**p) <= near).map(|p| ab.param_of(*p).clamp(0.0, 1.0)).collect(); ts.extend([0.0, 1.0]); ts.sort_by(f64::total_cmp); - ts.dedup_by(|x, y| (*x - *y).abs() * len <= 1e-9 * (1.0 + a.len())); + // Only cuts that are one point as far as f64 can tell: a tolerance in drawing units + // that grew with the distance from the origin merged real cuts far from it. + ts.dedup_by(|x, y| (*x - *y).abs() * len <= 64.0 * f64::EPSILON * (1.0 + a.len())); for t in ts.windows(2) { let (Some(&t0), Some(&t1)) = (t.first(), t.get(1)) else { continue }; let (p, q) = (ab.at(t0), ab.at(t1)); diff --git a/crates/engine/src/cmd/txt2mtxt.rs b/crates/engine/src/cmd/txt2mtxt.rs index fb024f08e..dcacf34ca 100644 --- a/crates/engine/src/cmd/txt2mtxt.rs +++ b/crates/engine/src/cmd/txt2mtxt.rs @@ -107,6 +107,7 @@ fn convert(s: &mut Session, hs: &[Handle], o: &Txt2MtxtOptions) -> Result<(Vec = items.iter().skip(1).map(|(h, ..)| *h).collect(); @@ -196,6 +197,7 @@ fn single(t: &Text) -> MText { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index bfe9ba3cd..fe6767c1e 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -1,7 +1,7 @@ //! View menu: ZOOM (with Realtime and Dynamic), PAN, REGEN, REDRAW, named views (VIEW), the view //! twist (DVIEW TWist), layout switching. -use cadcraft_doc::{Space, entity_bounds}; +use cadcraft_doc::{BlockBoundsCache, Drawing, Space, entity_bounds, entity_bounds_cached}; use cadcraft_geom::{Bounds2, Vec2}; use serde_json::{Value, json}; @@ -302,7 +302,7 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result { None => 0.0, }; if !s.state_mut()?.set_view(View { center: c, height: h, twist }) { - s.state_mut()?.doc = before.0; + s.state_mut()?.restore_drawing(before.0); return Err(bad("view.set", "the view is too large to show. Nothing was changed")); } if let Some(dview::Target::Viewport(h)) = target { @@ -311,6 +311,21 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result { ok() } +/// Bounds of the currently visible entities in `space`, excluding entities and block contents +/// on layers that are turned off or frozen. +fn visible_extents(doc: &Drawing, space: &Space) -> Bounds2 { + let mut b = Bounds2::EMPTY; + let mut cache = BlockBoundsCache::default(); + if let Some(store) = doc.space(space) { + for e in store.iter() { + if doc.is_visible(e) { + b = b.union(&entity_bounds_cached(doc, e, 0, &mut cache)); + } + } + } + b +} + fn run_layout_set(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").unwrap_or("Model"); let space = if name.eq_ignore_ascii_case("model") { @@ -320,6 +335,7 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result { Space::Paper(l.name.clone()) }; s.pending_window = None; + let (vw, vh) = s.viewport_px; let st = s.state_mut()?; st.space = space.clone(); st.mspace = None; @@ -327,11 +343,22 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result { if let Space::Paper(n) = &space && !st.views.iter().any(|(sp, _)| sp == &space) { - // Default paper view: the sheet. - let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default(); - let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; - let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; - st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 }); + // Why: fit only visible content on the automatic initial switch so far-away geometry on + // turned-off layers does not push the visible title block out of sight; explicit + // ZOOM Extents continues to use `Drawing::extents` (which includes turned-off layers). + let ext = visible_extents(&st.doc, &space); + if !ext.is_empty() && ext.width().is_finite() && ext.height().is_finite() { + let aspect = st.zoom_aspect(vw / vh.max(1.0)); + let (center, bw, bh) = View::twisted_box(ext, 0.0); + let height = bh.max(bw / aspect.max(1e-6)).max(1e-6) * 1.15; + st.set_view_quiet(View { center, height, twist: 0.0 }); + } else { + // Default paper view: the sheet. + let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default(); + let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; + let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; + st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 }); + } } s.touch(); ok() diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs index 3133fd6fa..58ddd8a7d 100644 --- a/crates/engine/src/cmd/view/dview.rs +++ b/crates/engine/src/cmd/view/dview.rs @@ -237,7 +237,7 @@ impl DviewM { set_twist(s, t, twist)?; } if !s.state_mut()?.set_view(View { twist, ..v }) { - s.state_mut()?.doc = before; + s.state_mut()?.restore_drawing(before); return Err(EngineError::Other("The view is too large to show.".into())); } Ok(()) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 5c67ad89b..df68f6b77 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -28,6 +28,13 @@ pub struct DocState { pub title: String, pub saved: Arc, pub revision: u64, + /// How many times the names AutoLISP gave this drawing's INSERTs' ATTRIBs and SEQENDs ended all + /// at once (#1660): another state of the drawing was shown (Undo, Redo, opening or closing the + /// Block Editor, a change taken back, or a command putting an earlier drawing back through + /// [`DocState::restore_drawing`]), or attribute sets were rebuilt in place (ATTSYNC, + /// -BLOCKREPLACE). A name given before names nothing after one of these, never another + /// record. + pub(crate) names_epoch: u64, pub space: Space, /// Tiled model viewports (VPORTS). pub tiles: ModelTiles, @@ -71,6 +78,7 @@ impl DocState { path, title: title.into(), revision: 1, + names_epoch: 0, space: Space::Model, tiles: ModelTiles::default(), mspace: None, @@ -97,8 +105,26 @@ impl DocState { self.follow_layout(&cur.doc); self.reconcile_untiled_twist(); self.revision += 1; + self.expire_names(); cur } + /// Names given to records without handles (an INSERT's ATTRIBs and SEQEND) stop holding: the + /// records of the drawing they were given for may be gone or replaced. They are never given + /// to another record, so a routine's stale name names nothing (`nil`) rather than something + /// else. + pub(crate) fn expire_names(&mut self) { + self.names_epoch = self.names_epoch.wrapping_add(1); + } + /// Show `doc` again. It is a drawing this document already showed, so its handle seed can + /// give the next object a handle a removed one had. Names of INSERT records end, as they do + /// for Undo. The same drawing already on show is left as it is: nothing was given out again. + pub(crate) fn restore_drawing(&mut self, doc: Arc) { + if Arc::ptr_eq(&self.doc, &doc) { + return; + } + self.doc = doc; + self.expire_names(); + } /// After undo/redo replaced the drawing (`before` is the one shown until then): if the current /// layout no longer exists, follow it to its other name when it was renamed (same tab order, /// a name `before` did not have), else go to the Model tab. diff --git a/crates/engine/src/drawlock.rs b/crates/engine/src/drawlock.rs new file mode 100644 index 000000000..157301794 --- /dev/null +++ b/crates/engine/src/drawlock.rs @@ -0,0 +1,340 @@ +//! Drawing locks: who has a drawing open (WHOHAS), for drawings shared on a network folder (#540). +//! +//! While a drawing opened from a file is open, the app keeps a small lock file beside it, +//! `..cadcraft-lock`, holding who opened it (user, computer, app instance, when). +//! The file's modification time is its heartbeat: the app touches it every [`HEARTBEAT_SECS`], +//! and a lock not touched for [`STALE_SECS`] belongs to an app that is no longer running (a crash +//! leaves it behind, and it is then ignored and taken over). +//! +//! A lock only informs: opening a drawing someone else has open says so on the command line and +//! in the status bar, and the drawing opens anyway (their lock stays theirs). Only lock files of +//! this app instance are ever deleted. The format is CADCraft's own (JSON), not AutoCAD's `.dwl`. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// How often a held lock is touched, in seconds. +pub const HEARTBEAT_SECS: u64 = 60; +/// A lock not touched for this long is stale, in seconds. +pub const STALE_SECS: u64 = 5 * 60; +/// Largest lock file read (bytes): anything bigger isn't ours. +#[cfg(not(target_arch = "wasm32"))] +const MAX_LOCK_BYTES: u64 = 4096; + +/// Who holds a lock. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Holder { + pub user: String, + pub host: String, + /// The app instance (see [`crate::autosave::Autosaver::instance`]). + pub instance: String, + /// When the drawing was opened, in seconds since 1970. + pub opened: u64, +} + +/// The lock file of the drawing at `drawing`. +pub fn lock_path(drawing: &Path) -> PathBuf { + let name = drawing.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + drawing.with_file_name(format!(".{name}.cadcraft-lock")) +} + +/// Whether drawings at `path` get a lock: drawing files only (not exports). +#[cfg(not(target_arch = "wasm32"))] +fn lockable(path: &str) -> bool { + let ext = Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + matches!(ext.as_str(), "dwg" | "dxf" | "dwt") +} + +/// `secs` since 1970 as `YYYY-MM-DD HH:MM` (UTC). +pub fn utc(secs: u64) -> String { + let days = (secs / 86_400) as i64; + let (h, m) = ((secs % 86_400) / 3600, (secs % 3600) / 60); + // Civil date from days since 1970 (Howard Hinnant's algorithm). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let mo = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(mo <= 2); + format!("{y:04}-{mo:02}-{d:02} {h:02}:{m:02} UTC") +} + +impl Holder { + /// "user on host since …". + pub fn describe(&self) -> String { + let who = if self.user.is_empty() { "someone" } else { self.user.as_str() }; + let host = if self.host.is_empty() { String::new() } else { format!(" on {}", self.host) }; + format!("{who}{host}, since {}", utc(self.opened)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub use native::*; + +#[cfg(not(target_arch = "wasm32"))] +mod native { + use std::collections::{HashMap, HashSet}; + use std::time::{Duration, Instant, SystemTime}; + + use super::{HEARTBEAT_SECS, Holder, MAX_LOCK_BYTES, Path, PathBuf, STALE_SECS, lock_path, lockable}; + use crate::Session; + + /// This user's name, from the environment. + fn user() -> String { + ["USER", "USERNAME", "LOGNAME"].iter().find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty())).unwrap_or_default() + } + + /// This computer's name (looked up once). + fn host() -> String { + static HOST: std::sync::OnceLock = std::sync::OnceLock::new(); + HOST.get_or_init(|| { + if let Some(h) = ["COMPUTERNAME", "HOSTNAME"].iter().find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty())) { + return h; + } + std::process::Command::new("hostname") + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + .ok() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().chars().take(255).collect()) + .unwrap_or_default() + }) + .clone() + } + + fn now_secs() -> u64 { + SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) + } + + /// The holder of the lock on `drawing` while its lock is fresh (touched within + /// [`STALE_SECS`]); `None` when there is no lock, it is stale or it isn't one of ours. + pub fn holder(drawing: &Path) -> Option { + let lock = lock_path(drawing); + let meta = std::fs::metadata(&lock).ok()?; + if !meta.is_file() || meta.len() > MAX_LOCK_BYTES { + return None; + } + // A time in the future (clock changes, another computer's clock) counts as fresh. + let age = meta.modified().ok().map(|m| SystemTime::now().duration_since(m).unwrap_or_default())?; + if age >= Duration::from_secs(STALE_SECS) { + return None; + } + serde_json::from_slice(&std::fs::read(&lock).ok()?).ok() + } + + /// This instance's lock contents for `drawing`, staged next to its lock file. + fn stage(drawing: &Path, h: &Holder) -> std::io::Result { + let lock = lock_path(drawing); + let tmp = lock.with_file_name(format!( + "{}.{}.tmp", + lock.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(), + std::process::id() + )); + std::fs::write(&tmp, serde_json::to_vec(h).unwrap_or_default())?; + Ok(tmp) + } + + /// Write this instance's lock on `drawing` (staged, then renamed over any stale one). + fn write(drawing: &Path, h: &Holder) -> std::io::Result<()> { + let tmp = stage(drawing, h)?; + std::fs::rename(&tmp, lock_path(drawing)).inspect_err(|_| { + let _ = std::fs::remove_file(&tmp); + }) + } + + /// Take the lock on `drawing` when there is none or it is stale: whether it is now this + /// instance's. With no lock file it is created atomically (two apps opening the drawing at + /// once can't both get it); a stale one is replaced and read back, so of two apps taking it + /// over at once only the last one keeps it. + fn claim(drawing: &Path, h: &Holder) -> std::io::Result { + let lock = lock_path(drawing); + if lock.exists() { + // Taken meanwhile by another app (its lock is fresh again): leave it. + if holder(drawing).is_some_and(|o| o.instance != h.instance) { + return Ok(false); + } + write(drawing, h)?; + } else { + let tmp = stage(drawing, h)?; + // A hard link appears with the whole lock written, or fails when the lock exists. + let linked = std::fs::hard_link(&tmp, &lock); + let _ = std::fs::remove_file(&tmp); + match linked { + Ok(()) => return Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false), + // No hard links on this file system: create it only if it isn't there. + Err(_) => { + use std::io::Write; + match std::fs::OpenOptions::new().write(true).create_new(true).open(&lock) { + Ok(mut f) => f.write_all(&serde_json::to_vec(h).unwrap_or_default())?, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false), + Err(e) => return Err(e), + } + } + } + } + let back = std::fs::read(&lock).ok().and_then(|b| serde_json::from_slice::(&b).ok()); + Ok(back.is_some_and(|b| b.instance == h.instance)) + } + + /// Touch a held lock (its modification time is the heartbeat). + fn touch(drawing: &Path) -> std::io::Result<()> { + std::fs::OpenOptions::new().write(true).open(lock_path(drawing))?.set_modified(SystemTime::now()) + } + + /// Delete the lock on `drawing` if it is still `instance`'s. + fn release(drawing: &Path, instance: &str) { + let lock = lock_path(drawing); + let ours = std::fs::read(&lock).ok().and_then(|b| serde_json::from_slice::(&b).ok()).is_some_and(|h| h.instance == instance); + if ours { + let _ = std::fs::remove_file(lock); + } + } + + /// The note that `h` also has the drawing at `path` (named `p`) open. + fn also_open(path: &Path, p: &str, h: &Holder) -> String { + let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| p.to_string()); + format!("{name} is also open by {}. Saving it here can overwrite their changes (or theirs yours).", h.describe()) + } + + /// This instance's lock contents. + fn me(instance: &str) -> Holder { + Holder { user: user(), host: host(), instance: instance.to_string(), opened: now_secs() } + } + + /// The drawing locks of one running app. + pub struct Locks { + /// How often held locks are touched and others' locks looked at again. + beat: Duration, + /// Drawings this app holds the lock of, with when it was last touched. + held: HashMap, + /// Drawings open here that someone else holds, with when that was last checked. + others: HashMap, + /// What to tell the user (someone else has a drawing open), taken by [`Locks::take_notes`]. + notes: Vec, + } + + impl Default for Locks { + fn default() -> Self { + Locks::with_heartbeat(Duration::from_secs(HEARTBEAT_SECS)) + } + } + + impl Locks { + /// Locks touched (and others' looked at again) every `beat` instead of [`HEARTBEAT_SECS`]. + pub fn with_heartbeat(beat: Duration) -> Self { + Locks { beat, held: HashMap::new(), others: HashMap::new(), notes: Vec::new() } + } + + /// Bring the locks in line with the drawings open in `s`: take the lock of a drawing just + /// opened from a file (or note who else has it open), touch held locks every + /// [`HEARTBEAT_SECS`], take over a lock its holder let go stale, and release the locks of + /// drawings no longer open here (closed, or saved under another name). + pub fn sync(&mut self, s: &Session, instance: &str) { + let open: HashSet = s.docs.iter().filter_map(|d| d.path.clone()).filter(|p| lockable(p)).collect(); + let gone: Vec = self.held.keys().filter(|p| !open.contains(*p)).cloned().collect(); + for p in gone { + release(Path::new(&p), instance); + self.held.remove(&p); + } + self.others.retain(|p, _| open.contains(p)); + let beat = self.beat; + for p in open { + let path = Path::new(&p); + if let Some(at) = self.held.get(&p) { + if at.elapsed() < beat { + continue; + } + // Still ours? Another app may have taken it over (this one was asleep past + // STALE_SECS): then it is theirs, and noted below. + if holder(path).is_none_or(|h| h.instance == instance) { + // A lock removed meanwhile (by hand, a sync tool) is written again. + if touch(path).is_err() { + let _ = write(path, &me(instance)); + } + self.held.insert(p, Instant::now()); + continue; + } + self.held.remove(&p); + } + if let Some(at) = self.others.get(&p) + && at.elapsed() < beat + { + continue; + } + match holder(path) { + Some(h) if h.instance != instance => { + if !self.others.contains_key(&p) { + self.notes.push(also_open(path, &p, &h)); + } + self.others.insert(p, Instant::now()); + } + _ => match claim(path, &me(instance)) { + // Another app took it first: tell the user as for a lock found. + Ok(false) => { + if let Some(h) = holder(path).filter(|h| h.instance != instance) { + self.notes.push(also_open(path, &p, &h)); + } + self.others.insert(p, Instant::now()); + } + // No lock, a stale one or our own: now ours (a folder we can't write + // to just gets no lock). + _ => { + self.others.remove(&p); + self.held.insert(p, Instant::now()); + } + }, + } + } + } + + /// How long until [`Locks::sync`] next has a lock to touch or look at again (the + /// shortest wait over held locks and others'), so an idle host still wakes up for it; + /// `None` when no drawing open here has a lock. + pub fn next_beat(&self) -> Option { + self.held.values().chain(self.others.values()).map(|at| self.beat.saturating_sub(at.elapsed())).min() + } + + /// The notes [`Locks::sync`] made since the last call. + pub fn take_notes(&mut self) -> Vec { + std::mem::take(&mut self.notes) + } + + /// The app is closing: release every lock it holds. + pub fn release_all(&mut self, instance: &str) { + for (p, _) in self.held.drain() { + release(Path::new(&p), instance); + } + self.others.clear(); + } + } + + #[cfg(test)] + mod tests { + use super::*; + + /// Of two apps claiming a drawing that has no lock, only the first gets it: the second + /// finds it taken and leaves it. A stale lock is taken over. + #[test] + fn only_one_app_claims_a_free_lock() { + let dir = std::env::temp_dir().join(format!("cadcraft-claim-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Plan.dxf"); + std::fs::write(&file, b"").unwrap(); + assert!(claim(&file, &me("1-a")).unwrap()); + assert!(!claim(&file, &me("2-b")).unwrap(), "a fresh lock stays the first app's"); + assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string())); + assert!(claim(&file, &me("1-a")).unwrap(), "its own lock is still its own"); + let stale = SystemTime::now() - Duration::from_secs(STALE_SECS + 60); + std::fs::OpenOptions::new().write(true).open(lock_path(&file)).unwrap().set_modified(stale).unwrap(); + assert!(claim(&file, &me("2-b")).unwrap(), "a stale lock is taken over"); + assert_eq!(holder(&file).map(|h| h.instance), Some("2-b".to_string())); + let _ = std::fs::remove_dir_all(&dir); + } + } +} diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 107c77d23..9afc6d02f 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -7,6 +7,7 @@ /// Commands that read or write files, each path held to the roots where the file is touched. pub const FILES: &[&str] = &[ + "-hatch", "-linetype", "-plottermanager", "-wblock", @@ -49,6 +50,8 @@ pub const FILES: &[&str] = &[ "publish", "qsave", "recover", + "refclose", + "refedit", "reinit", "saveas", "script", @@ -57,6 +60,7 @@ pub const FILES: &[&str] = &[ "stylesmanager", "tableexport", "wblock", + "whohas", "xattach", "xbind", "xopen", @@ -264,9 +268,8 @@ pub const NO_FILES: &[&str] = &[ "attdisp.normal", "attdisp.on", "attdisp.off", - "refedit", + "refedit.levels", "refset", - "refclose", "bedit", "bsave", "bsaveas", @@ -359,6 +362,7 @@ pub const NO_FILES: &[&str] = &[ "laymrg", "laydel", "layout.new", + "layout.newarea", "layout.delete", "layout.rename", "layout.copy", @@ -519,9 +523,9 @@ mod tests { use std::collections::BTreeSet; /// Words in a command's parameter doc that usually name a file. In these commands they don't: - /// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a - /// direction. - const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"]; + /// `array` and `arraypath` follow a path of objects, `refedit.levels` reports paths of nested + /// references, and `blocks.reference.grips` reports a direction. + const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"]; /// The words of a command's documentation, lower case. fn words(doc: &str) -> BTreeSet { diff --git a/crates/engine/src/finite.rs b/crates/engine/src/finite.rs index cc81b5e50..a46009dc3 100644 --- a/crates/engine/src/finite.rs +++ b/crates/engine/src/finite.rs @@ -26,7 +26,7 @@ impl Session { }; let Some(st) = st.filter(|st| !Arc::ptr_eq(before, &st.doc)) else { return Ok(()) }; let Some(h) = first_non_finite(before, &st.doc) else { return Ok(()) }; - st.doc = before.clone(); + st.restore_drawing(before.clone()); st.selection = selection.to_vec(); Err(EngineError::BadParams { cmd: cmd.into(), diff --git a/crates/engine/src/grips.rs b/crates/engine/src/grips.rs index 77e1fc8bd..05ba39304 100644 --- a/crates/engine/src/grips.rs +++ b/crates/engine/src/grips.rs @@ -136,7 +136,14 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option set_xy(p.points.get_mut(index)?, to), EntityKind::Spline(sp) => { if sp.fit.is_empty() { - *sp.control.get_mut(index)? = to; + // A closed spline's repeats of the control vertex move with it (#3566). + let copies = sp.control_copies(index); + if copies.is_empty() { + return None; + } + for i in copies { + *sp.control.get_mut(i)? = to; + } } else { let mut fit = sp.fit.clone(); *fit.get_mut(index)? = to; diff --git a/crates/engine/src/grips/tests.rs b/crates/engine/src/grips/tests.rs index 2fc4502b6..39c1d39a9 100644 --- a/crates/engine/src/grips/tests.rs +++ b/crates/engine/src/grips/tests.rs @@ -249,3 +249,32 @@ fn grips_on_locked_layers_and_hostile_values() { } } } + +/// #3566: a closed spline keeps some control vertices twice: SPLINE CV's Close repeats the first +/// at the end, and control vertices that wrap round repeat the first `degree`. Each control +/// vertex has one grip, and dragging it moves its copies, so the spline stays closed. +#[test] +fn a_closed_spline_has_one_grip_per_control_vertex_and_stays_closed() { + let mut s = Session::new(); + let square = [v(0.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)]; + let clamped = h(&s.execute("spline.cv", &json!({"control": [[0, 0], [10, 0], [10, 10], [0, 10]], "closed": true})).unwrap()); + let wraps = cadcraft_geom::Spline { + degree: 3, + knots: (0..11).map(f64::from).collect(), + control: square.iter().chain(&square[..3]).copied().collect(), + closed: true, + ..Default::default() + }; + assert!(wraps.wraps()); + let wrapped = s.add_entity(EntityKind::Spline(wraps)).unwrap(); + for sp in [clamped, wrapped] { + let g = s.grips_of(sp).unwrap(); + let coincide = g.iter().enumerate().any(|(i, a)| g.iter().skip(i + 1).any(|b| a.near(*b, 1e-9))); + assert!(!coincide, "no grip lies on another: {g:?}"); + s.grip_edit(sp, 0, v(-3.0, -3.0), GripMode::Stretch).unwrap(); + let EntityKind::Spline(x) = kind(&s, sp) else { panic!() }; + assert!(!x.control.iter().any(|c| near(*c, 0.0, 0.0)), "every copy moved: {:?}", x.control); + let (lo, hi) = x.domain(); + assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed: {:?} {:?}", x.eval(lo), x.eval(hi)); + } +} diff --git a/crates/engine/src/last_used.rs b/crates/engine/src/last_used.rs index e884caf1b..34dcc6619 100644 --- a/crates/engine/src/last_used.rs +++ b/crates/engine/src/last_used.rs @@ -3,12 +3,15 @@ use super::cmd; /// Options and values the interactive commands remember for the rest of the session, offered as /// the `` the next time they ask (as AutoCAD does). Values AutoCAD keeps in a drawing /// system variable (HPNAME, OFFSETDIST, FILLETRAD, CHAMFERA, POLYSIDES…) live in the drawing -/// header instead. JSON calls never read these: their explicit parameters and documented defaults -/// stay authoritative. +/// header instead. Drawing commands called with JSON use their own parameter defaults. #[derive(Clone, Debug, PartialEq)] pub struct LastUsed { /// HATCH/GRADIENT starts at "Select objects" instead of "Pick internal point". pub hatch_select: bool, + /// HPSPACE: line spacing for user-defined hatches. + pub hatch_spacing: f64, + /// HPDOUBLE: whether user-defined hatches have a second family of lines. + pub hatch_double: bool, /// POLYGON: circumscribed about the circle (the `C` option) instead of inscribed. pub polygon_circumscribed: bool, /// ROTATE angle (radians). @@ -35,6 +38,8 @@ impl Default for LastUsed { fn default() -> Self { LastUsed { hatch_select: false, + hatch_spacing: 1.0, + hatch_double: false, polygon_circumscribed: false, rotate_angle: 0.0, scale_factor: 1.0, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bc348d070..5dfb9e7c2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -19,6 +19,7 @@ pub mod blockedit; pub mod capped_read; pub mod cmd; pub mod doc_path; +pub mod drawlock; pub mod file_access; mod finite; pub mod grip_dims; @@ -55,6 +56,7 @@ pub use cadcraft_fonts as fonts; pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::blocks::WblockPicks; +pub use cmd::blocks::attedit::{AttributeRow, attributes}; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor}; @@ -125,8 +127,15 @@ pub struct Session { /// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it; /// it resumes when that command ends. One level, as in AutoCAD. pub suspended: Option, + /// The command history. It is trimmed from the front when it grows long, so to find the lines + /// echoed since some moment keep a [`Session::log_mark`], not an index into it. pub log: Vec, + /// Lines [`Session::echo`] has added to `log`, trimmed and cleared ones included. + echoed: u64, pub last_command: Option, + /// Last TSV payload and optional text height passed to [`Session::start_paste_table`], so + /// pressing Enter to repeat `pastetable` restarts interactive placement. + pub(crate) last_paste_table: Option<(String, Option)>, /// LASTPOINT. pub last_point: Vec2, /// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract @@ -154,6 +163,9 @@ pub struct Session { /// change behavior on Ctrl — currently only ARC's "hold Ctrl to switch direction" — read /// this instead of receiving modifiers through `Input`, which stays free of UI state. pub ctrl_down: bool, + /// Whether Shift is held right now (from the UI, overwritten every frame). TRIM/EXTEND read + /// this to temporarily toggle the active mode, as in AutoCAD. + pub shift_down: bool, /// Origin of the point currently being fed by `input_snapped`; never reused by typed points. picked_viewport: Option, /// The last drawing comparison (COMPARE), drawn over the drawing it was made for. @@ -225,7 +237,9 @@ impl Session { program_input: false, suspended: None, log: Vec::new(), + echoed: 0, last_command: None, + last_paste_table: None, last_point: Vec2::ZERO, area: 0.0, perimeter: 0.0, @@ -236,6 +250,7 @@ impl Session { cursor: Vec2::ZERO, cursor_deferred: None, ctrl_down: false, + shift_down: false, picked_viewport: None, compare: None, tracking: snap::tracking::Tracker::default(), @@ -321,11 +336,25 @@ impl Session { let m = msg.into(); log::debug!("{m}"); self.log.push(m); + self.echoed = self.echoed.saturating_add(1); if self.log.len() > 5000 { self.log.drain(..1000); } } + /// A mark in the command history: the number of lines echoed so far. Unlike an index into + /// `log`, it stays valid when the history is trimmed from the front or cleared. + pub fn log_mark(&self) -> u64 { + self.echoed + } + + /// The lines echoed since `mark` ([`Session::log_mark`]) that the history still holds: all of + /// them, or the last ones when the history was trimmed past the first. + pub fn log_since(&self, mark: u64) -> &[String] { + let new = usize::try_from(self.echoed.saturating_sub(mark)).unwrap_or(usize::MAX); + self.log.get(self.log.len().saturating_sub(new)..).unwrap_or_default() + } + /// Common properties for new objects (CLAYER, CECOLOR, CELTYPE, CELWEIGHT, CELTSCALE). pub fn current_common(&self) -> Common { let Ok(d) = self.doc() else { return Common::default() }; @@ -379,6 +408,11 @@ 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 = self diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index f8e492ee3..c42450ef3 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -75,6 +75,10 @@ pub struct Env { /// The command history's length after LISP last printed a line: when something else wrote since /// (a prompt, a command's echo), a leading newline only ends that line. pub printed_at: Option, + /// Application names `regapp` registered (upper case). A drawing's APPID table is written + /// from the xdata its objects carry, so this only makes `regapp` answer like AutoCAD's and + /// shows the names in the APPID table `tblsearch` lists. + pub regapps: std::collections::BTreeSet, } impl Default for Env { @@ -93,6 +97,7 @@ impl Default for Env { pending_block: None, objects: objects::Names::default(), printed_at: None, + regapps: std::collections::BTreeSet::new(), }; builtins::install(&mut e); e @@ -121,6 +126,11 @@ impl Env { #[derive(Default)] pub struct LispState { envs: HashMap, + /// The names given to records without a handle of their own (an INSERT's ATTRIBs and SEQEND, + /// #1660), by drawing. They are the session's, not a snapshot's, so the drawing's undo states + /// and the Block Editor's drawing share them; each use checks what a name stands for against + /// the drawing. + pub(crate) records: HashMap, run: Option>, /// A routine runs, from its start to its end (also while its machine is out of `run`). active: bool, @@ -170,12 +180,14 @@ pub(crate) struct Limits { pub string_bytes: u64, /// Maximum interpreter steps per synchronous callback. pub callback_steps: u64, + /// Steps a routine run on without frames ([`Session::lisp_run_until_input`]) may take in all. + pub frameless_steps: u64, } impl Default for Limits { - /// Provide finite cons-cell, string-byte, and synchronous-callback limits for a LISP run. + /// Provide finite cons-cell, string-byte, synchronous-callback and step limits for a LISP run. fn default() -> Self { - Limits { cells: value::MAX_CELLS, string_bytes: value::STRING_BUDGET, callback_steps: 500_000_000 } + Limits { cells: value::MAX_CELLS, string_bytes: value::STRING_BUDGET, callback_steps: 500_000_000, frameless_steps: BLOCKING_CAP } } } @@ -204,7 +216,7 @@ struct Run { /// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with /// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`]. answer: bool, - /// Steps taken, for the cap on blocking runs. + /// Steps taken, for the caps on blocking runs and on routines run on without frames. steps: u64, /// The `*error*` handler is the one running. handler: bool, @@ -244,6 +256,13 @@ impl Session { pub(crate) fn lisp_forget_closed(&mut self) { let docs = &self.docs; self.lisp.envs.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid)); + self.lisp.records.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid)); + } + + /// The active drawing's names of an INSERT's records (#1660), made on first use. + pub(crate) fn record_names(&mut self) -> Option<&mut drawing::RecordNames> { + let uid = self.state().ok()?.uid; + Some(self.lisp.records.entry(uid).or_default()) } /// A routine is running (possibly waiting for input). @@ -363,6 +382,28 @@ impl Session { self.lisp.run.as_ref().is_some_and(|r| matches!(r.waiting, Some(Need::Yield))) } + /// Carry on a routine that gave the interface a frame ([`Session::lisp_busy`]) until it ends or + /// waits for input, where nothing else would: a script calls this before each input it gives, + /// which belongs to what the routine waits for or comes after it, and once it ends; a host + /// with no window calls it after each line it types. No one can stop the routine by hand + /// meanwhile, so past `limits.frameless_steps` steps, as many as a programmatic call may take, + /// it stops with the error such a call gets. + pub fn lisp_run_until_input(&mut self) { + while self.lisp_busy() { + let cap = self.lisp.limits.frameless_steps; + if self.lisp.run.as_ref().is_some_and(|r| r.steps > cap) { + // `*error*` gets the message and runs on the same count: an endless one stops at + // the next pass. + self.lisp_error(LispError::quit(format!("routine stopped after {cap} steps"))); + continue; + } + if let Some(r) = self.lisp.run.as_mut() { + r.waiting = None; + } + self.lisp_drive(); + } + } + /// Run the machine until it finishes or waits. fn lisp_drive(&mut self) { loop { @@ -403,7 +444,7 @@ impl Session { if let Some((doc, sel)) = self.lisp.steps.base.as_ref().or(run.before.as_ref()) && let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid) { - st.doc = doc.clone(); + st.restore_drawing(doc.clone()); st.selection = sel.clone(); } run.handler = true; @@ -720,6 +761,15 @@ impl Session { Some(label) } + /// Why U may not take back the running routine's last step: it would undo a REFCLOSE Save + /// that already wrote an xref's file ([`crate::cmd::blocks::refedit::undo_barrier`]). + pub(crate) fn lisp_undo_barrier(&self) -> Option { + let uid = self.routine_steps()?; + let st = self.docs.iter().find(|d| d.uid == uid)?; + let snap = self.lisp.steps.undo.back()?; + crate::cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc) + } + /// U or REDO inside the running routine went on to the drawing's steps before it: the /// routine's own undo step starts from the drawing as that left it, and REDO brings back that /// step before what U took back of the routine's. diff --git a/crates/engine/src/lisp/builtins.rs b/crates/engine/src/lisp/builtins.rs index 01f103bfc..3f080e2fe 100644 --- a/crates/engine/src/lisp/builtins.rs +++ b/crates/engine/src/lisp/builtins.rs @@ -252,6 +252,7 @@ static BUILTINS: &[Builtin] = &[ ctx!("ENTNEXT", drawing::entnext), ctx!("ENTUPD", drawing::entupd), ctx!("HANDENT", drawing::handent), + ctx!("REGAPP", drawing::regapp), ctx!("SSGET", drawing::ssget), ctx!("SSADD", drawing::ssadd), ctx!("SSDEL", drawing::ssdel), diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 69ee83466..ff56ca9de 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -6,19 +6,22 @@ //! //! Entity lists use the DXF groups the file reader and writer use (through //! [`crate::cmd::file::entity_codec`]), so what `entget` shows is what a DXF file holds, except -//! for angles, which are radians in a list and degrees in a file. +//! for angles, which are radians in a list and degrees in a file. Extended data (xdata) is the +//! `-3` group, as in AutoCAD: `(entget ename '("APP" …))` adds `(-3 ("APP" (1000 . "…") …))` for +//! the applications named (wildcards allowed), `entmake` and `entmod` take it, and `regapp` +//! registers an application name. use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use cadcraft_doc::{Entity, Handle, Space}; +use cadcraft_doc::{Entity, Handle, RawTag, Space}; use cadcraft_geom::Vec2; use craft_dxf::Tag; use super::builtins::args_err; use super::eval::{Ctx, Flow, Need}; -use super::value::{PickSet, Value, to_text}; +use super::value::{PickSet, RecordName, Value, equal, to_text}; use super::{BlockSlots, LispError}; use crate::{Input, Session}; @@ -116,6 +119,8 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec) -> Result { } } Value::Ename(h) => named(ctx.s, *h, None), + // An INSERT's record (#1660) is no object of the drawing: it picks nothing. + Value::Record(_) => feed(ctx.s, Input::Pick(Vec::new())), Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))), Value::Cons(_) => { if let Some(p) = arg.as_point() { @@ -323,8 +328,8 @@ pub(super) fn groups_to_list(tags: &[Tag]) -> Vec { const MAX_GROUP_TEXT: usize = 32 << 20; /// An association list back to DXF groups (points split into x, y, z groups). The type -/// (`0`), the entity name (`-1`), the handle (`5`), the owner (`330`) and the layout (`410`) are -/// left out: they aren't the entity's to set. +/// (`0`), the entity name (`-1`), the owner of a record (`-2`) and of the entity (`330`), the +/// handle (`5`) and the layout (`410`) are left out: they aren't the entity's to set. fn list_to_groups(list: &Value) -> Result<(String, Vec), LispError> { let mut kind = None; let mut tags = Vec::new(); @@ -340,7 +345,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec), LispError> { other => return Err(LispError::bad_arg("stringp", other)), }) } - -1 | 5 | 330 | 360 | 410 | 102 => {} + -1 | -2 | -3 | 5 | 330 | 360 | 410 | 102 => {} _ if point_group(code) && matches!(v, Value::Cons(_)) => { let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?; tags.push(Tag::f(code, p[0])); @@ -371,9 +376,317 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option { d.space_of(h) } +// ---------------- an INSERT's ATTRIBs and SEQEND ---------------- + +/// The most names one drawing's LISP holds for an INSERT's records at once: a routine can't fill +/// memory by walking. At the limit `entnext` gives no *new* name (`nil`) until names end (an +/// erased reference, Undo, ATTSYNC) and make room; the names already given still hold. +const MAX_RECORD_NAMES: usize = 65_536; + +/// What a name given to an INSERT's ATTRIB or SEQEND stands for, while it holds. +struct Record { + owner: Handle, + /// The record's place after the INSERT's own: an ATTRIB's index, or `attribs.len()` for the + /// SEQEND. + slot: usize, + /// The ATTRIB's tag, which can be empty. A SEQEND has no tag. + tag: Option, +} + +impl Record { + /// Whether the reference still has the same kind of record in this slot, with the same tag. + fn holds(&self, attribs: &[cadcraft_doc::Attrib]) -> bool { + match (attribs.get(self.slot), self.tag.as_deref()) { + (Some(a), Some(tag)) => a.tag.eq_ignore_ascii_case(tag), + (None, None) => self.slot == attribs.len(), + _ => false, + } + } +} + +/// The names a drawing's LISP gave to INSERTs' ATTRIBs and SEQENDs (#1660). These records have no +/// handle of their own in the drawing, and their names are not handles ([`RecordName`]): nothing +/// a drawing, a copy of it or another session gives out can ever be one. A name holds while its +/// reference keeps the record in that place with that tag, in the drawing's name epoch it was +/// given in (`DocState::expire_names`); otherwise it names nothing (`nil`), never another record. +#[derive(Default)] +pub(crate) struct RecordNames { + /// Names by INSERT and then by slot. Removing an INSERT ends all its names, even after a + /// change to the length of its attribute run. + by_owner: HashMap>, + /// What each name that still holds stands for, by its number. + by_name: HashMap, + /// The drawing's name epoch the names were given in. + epoch: u64, +} + +impl RecordNames { + /// Forget every name once the drawing's name epoch moved on: the records they named may be + /// gone or rebuilt. + fn expire(&mut self, epoch: u64) { + if self.epoch != epoch { + self.by_owner.clear(); + self.by_name.clear(); + self.epoch = epoch; + } + } + + /// Drop the name numbered `id`: it names nothing from now on. + fn retire(&mut self, id: u64) { + if let Some(r) = self.by_name.remove(&id) + && let Some(slots) = self.by_owner.get_mut(&r.owner) + && slots.get(&r.slot).is_some_and(|n| n.id == id) + { + slots.remove(&r.slot); + if slots.is_empty() { + self.by_owner.remove(&r.owner); + } + } + } + + /// End the names of the removed reference. Restoring it does not revive any of its names. + pub(crate) fn erased(&mut self, e: &Entity) { + if let Some(slots) = self.by_owner.remove(&e.handle) { + for n in slots.into_values() { + self.by_name.remove(&n.id); + } + } + } + + /// How many names hold now (tests). + #[cfg(test)] + pub(crate) fn count(&self) -> usize { + self.by_name.len() + } + + /// The INSERT and place `name` stands for in `d` now. A name that no longer holds is dropped: + /// it names nothing from then on, also if its record comes back. + fn lookup(&mut self, epoch: u64, d: &cadcraft_doc::Drawing, name: RecordName) -> Option<(Handle, usize)> { + self.expire(epoch); + let r = self.by_name.get(&name.id)?; + let at = insert_attribs(d, r.owner).filter(|attribs| r.holds(attribs)).map(|_| (r.owner, r.slot)); + if at.is_none() { + self.retire(name.id); + } + at + } + + /// The name of record `slot` after INSERT `owner`'s own (its attributes, then its SEQEND), + /// given now if it has none that holds: the same one while the record holds, so a repeated + /// walk is stable. None past the SEQEND, at the limit of names, or when the numbers run out. + fn name(&mut self, epoch: u64, attribs: &[cadcraft_doc::Attrib], owner: Handle, slot: usize) -> Option { + self.expire(epoch); + if let Some(n) = self.by_owner.get(&owner).and_then(|slots| slots.get(&slot)).copied() { + if self.by_name.get(&n.id).is_some_and(|r| r.holds(attribs)) { + return Some(n); + } + self.retire(n.id); + } + let tag = match attribs.get(slot) { + Some(a) => Some(a.tag.clone()), + None if slot == attribs.len() => None, + None => return None, + }; + if self.by_name.len() >= MAX_RECORD_NAMES { + return None; + } + let name = RecordName::fresh(owner)?; + self.by_owner.entry(owner).or_default().insert(slot, name); + self.by_name.insert(name.id, Record { owner, slot, tag }); + Some(name) + } +} + +/// The attributes of the block reference `h` in `d` (none for anything else, and for a reference +/// with no attributes: an empty run of records is not written). +fn insert_attribs(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&[cadcraft_doc::Attrib]> { + match d.entity(h).map(|e| &e.kind) { + Some(cadcraft_doc::EntityKind::Insert(i)) if !i.attribs.is_empty() => Some(&i.attribs), + _ => None, + } +} + +/// The drawing and its name epoch, without holding a borrow of the session. +fn doc_and_epoch(ctx: &Ctx<'_>) -> Option<(Arc, u64)> { + let st = ctx.s.state().ok()?; + Some((st.doc.clone(), st.names_epoch)) +} + +/// The INSERT and record the name `name` stands for now (none when it no longer holds). +fn record_of(ctx: &mut Ctx<'_>, name: RecordName) -> Option<(Handle, usize)> { + let (d, epoch) = doc_and_epoch(ctx)?; + ctx.s.record_names()?.lookup(epoch, &d, name) +} + +/// The name of record `slot` after INSERT `owner`'s own (#1660): an ATTRIB, or its SEQEND (one +/// past the last attribute). None when it has no such record, when the host has no record +/// mapping, or when no name is left to give. +fn name_record(ctx: &mut Ctx<'_>, owner: Handle, slot: usize) -> Option { + crate::cmd::file::entity_sub_record()?; + let (d, epoch) = doc_and_epoch(ctx)?; + let attribs = insert_attribs(&d, owner)?; + ctx.s.record_names()?.name(epoch, attribs, owner, slot) +} + +/// An entity list: `head` (its name, type and, for an INSERT's record, its owner), then the +/// groups of its record with the layout name after the AcDbEntity marker, as AutoCAD lists it. +/// The layout is the one object `at` is in; without a layout of its own (an entity of a block +/// definition) it has none. +fn entity_list(d: &cadcraft_doc::Drawing, mut items: Vec, at: Handle, tags: &[Tag], in_block: bool) -> Value { + let layout = match space_of(d, at) { + Some(Space::Paper(name)) => name, + _ => "Model".into(), + }; + let mut placed_layout = in_block; + for v in groups_to_list(tags) { + // The layout name follows the AcDbEntity marker, as AutoCAD lists it. + let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity"); + items.push(v); + if after_marker { + items.push(Value::cons(Value::Int(410), Value::str(&layout))); + placed_layout = true; + } + } + Value::list(items) +} + +/// The list of record `slot` of the reference `owner` named `name`: the DXF writer's record, +/// its name (`-1`), type (`0`) and reference (`-2`). None when the host has no record mapping. +fn record_list(d: &cadcraft_doc::Drawing, name: RecordName, owner: Handle, slot: usize) -> Option<(Value, Vec)> { + let e = d.entity(owner)?; + let (kind, mut tags) = (crate::cmd::file::entity_sub_record()?)(d, e, slot)?; + convert_angles(&kind, &mut tags, f64::to_radians); + let head = vec![ + Value::cons(Value::Int(-1), Value::Record(name)), + Value::cons(Value::Int(0), Value::str(&kind)), + Value::cons(Value::Int(-2), Value::Ename(owner)), + ]; + Some((entity_list(d, head, owner, &tags, false), tags)) +} + +/// `entget` of an INSERT's ATTRIB or SEQEND (#1660), while `name` names one. +fn record_entget(ctx: &mut Ctx<'_>, name: RecordName) -> Option { + let (owner, slot) = record_of(ctx, name)?; + let d = ctx.s.doc().ok()?; + record_list(d, name, owner, slot).map(|(list, _)| list) +} + +/// What an ATTRIB's submitted list asks to change: `Some(None)` when it asks for nothing, and +/// `Some(Some(value))` for its value (group 1). `None` when it asks for any other edit: a group +/// added, dropped, moved or changed other than the attribute's own value. +fn value_edit(now: &[Tag], asked: &[Tag]) -> Option> { + if now.len() != asked.len() { + return None; + } + let mut value = None; + let mut seen = false; + for (n, a) in now.iter().zip(asked) { + if n.code != a.code { + return None; + } + if n.code == 1 { + // A multiline attribute's embedded text has a group 1 of its own, after its marker + // (101): only the attribute's value, before it, may differ. + match (&n.value, &a.value) { + (craft_dxf::Value::Str(old), craft_dxf::Value::Str(new)) if !seen => { + seen = true; + if old != new { + value = Some(new.clone()); + } + } + _ if n == a => {} + _ => return None, + } + } else if n != a { + return None; + } + } + Some(value) +} + +/// The submitted list has the items `entget` would return, in order, except at group 1 (the +/// value): `value_edit` checks which group 1 may differ. Every other group, including the ones +/// an entity cannot set (`-2`, `5`, `330`, `360`, `410`, `102`), must be the same. +fn only_value_diff(expected: &Value, asked: &Value) -> bool { + let (mut expected, mut asked) = (expected.iter(), asked.iter()); + loop { + match (expected.next(), asked.next()) { + (None, None) => return true, + (Some(x), Some(y)) => { + let code = x.car().as_number(); + if code != y.car().as_number() { + return false; + } + if code != Some(1.0) && !equal(&x, &y, 0.0) { + return false; + } + } + _ => return false, + } + } +} + +/// `entmod` of the INSERT's record `name` stands for (#1660): only an ATTRIB's value may change, +/// the group 1 value; its tag, place, flags and properties are the reference's. A SEQEND holds +/// nothing to change, and a name that no longer holds names nothing: both give `nil`, the drawing +/// as it is. +fn entmod_attrib(ctx: &mut Ctx<'_>, list: &Value, name: RecordName) -> Value { + let Some((owner, slot)) = record_of(ctx, name) else { return Value::Nil }; + // An outer list with an atom tail is not the list `entget` returned: iterating it would drop + // the tail and accept the malformed list. The group pairs inside are dotted, as DXF has them. + if !list.is_list() { + return Value::Nil; + } + let Ok((kind, asked)) = list_to_groups(list) else { return Value::Nil }; + if !kind.eq_ignore_ascii_case("ATTRIB") { + return Value::Nil; + } + let Ok(d) = ctx.s.doc() else { return Value::Nil }; + if crate::cmd::blocks::refedit::locked(d, owner) { + return Value::Nil; + } + let Some((expected, now)) = record_list(d, name, owner, slot) else { return Value::Nil }; + // The type, layout, owner, handle and any other group are not the attribute's to change: a + // list that differs from `entget` anywhere but its group 1 value is refused (a SEQEND's + // list too), the drawing untouched. + if !only_value_diff(&expected, list) { + return Value::Nil; + } + match value_edit(&now, &asked) { + None => Value::Nil, + Some(None) => list.clone(), + Some(Some(value)) => { + let ok = ctx.s.doc_mut().is_ok_and(|d| { + d.modify_entity(owner, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind + && let Some(a) = i.attribs.get_mut(slot) + { + a.text.value = value.clone(); + } + }) + .is_ok() + }); + if ok { + ctx.s.touch(); + } + if ok { list.clone() } else { Value::Nil } + } + } +} + pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 2)?; + // An INSERT's ATTRIB or SEQEND (#1660) is not an entity of the drawing: its name reaches it. + if let Value::Record(r) = &a[0] { + return Ok(Flow::Value(record_entget(ctx, *r).unwrap_or_default())); + } let h = ename(&a[0])?; + // The applications whose xdata to list: names or wildcard patterns ("*": every application). + let apps: Option> = match a.get(1) { + None | Some(Value::Nil) => None, + Some(v) if v.is_list() => Some(v.iter().map(|x| string(&x)).collect::>()?), + Some(other) => return Err(LispError::bad_arg("listp", other)), + }; let drawn = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()); let from_block = if drawn { None } else { block_entity(ctx, h) }; let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; @@ -385,28 +698,161 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { (None, None) => return Ok(Flow::Value(super::objects::entget(ctx, h))), }; let (kind, mut tags) = (codec()?.groups)(d, e); + let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil()); convert_angles(&kind, &mut tags, f64::to_radians); - let layout = match space_of(d, h) { - Some(Space::Paper(name)) => name, - _ => "Model".into(), - }; - let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))]; - let mut placed_layout = in_block; - for v in groups_to_list(&tags) { - // The layout name follows the AcDbEntity marker, as AutoCAD lists it. - let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity"); - items.push(v); - if after_marker { - items.push(Value::cons(Value::Int(410), Value::str(&layout))); - placed_layout = true; - } + let head = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))]; + let mut items = entity_list(d, head, h, &tags, in_block).to_vec(); + if let Some(x) = xdata { + items.push(Value::cons(Value::Int(-3), x)); } Ok(Flow::Value(Value::list(items))) } -/// The entity a list describes, as the reader makes it; a missing layer (8) is the current one. -fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc::Common, cadcraft_doc::EntityKind), LispError> { +/// A group kept raw, typed by its code (so a 1070 lists as an integer, a 1040 as a real, and a +/// 1071 as a real per AutoLISP's `entget`, though the file holds a 32-bit integer). +fn typed_tag(r: &RawTag) -> Tag { + use craft_dxf::{Kind, Value as V, kind_of}; + let v = r.value.trim(); + let value = if r.code == 1071 { + v.parse::().ok().map(|n| V::Real(n as f64)) + } else { + match kind_of(r.code) { + Kind::Real => v.parse::().ok().filter(|x| x.is_finite()).map(V::Real), + Kind::Int16 | Kind::Int32 | Kind::Int64 => v.parse::().ok().map(V::Int), + Kind::Bool => v.parse::().ok().map(|x| V::Bool(x != 0)), + Kind::Hex => Some(V::Hex(v.to_string())), + Kind::Str => None, + } + }; + Tag::new(r.code, value.unwrap_or_else(|| V::Str(r.value.clone()))) +} + +/// The `-3` group's value: `(("APP" (1000 . "…") (1070 . 3) (1010 x y z) …) …)` for the +/// applications of `xdata` matching one of `patterns` (any case; `wcmatch` wildcards). +fn xdata_to_list(xdata: &[RawTag], patterns: &[String]) -> Value { + let patterns: Vec = patterns.iter().map(|p| p.trim().to_ascii_uppercase()).collect(); + // A file may hold several runs of one application, `ACME` and `acme` among them; they are + // one application to `set_xdata_app`, so they are one list here (first spelling, all the + // groups), or `(entmod (entget e '("*")))` would keep only the last run. + let mut apps: Vec<(&str, Vec)> = Vec::new(); + for (name, groups) in cadcraft_doc::xdata_apps(xdata) { + let up = name.to_ascii_uppercase(); + if !patterns.iter().any(|p| super::builtins::wild_match(&up, p)) { + continue; + } + match apps.iter_mut().find(|(app, _)| app.eq_ignore_ascii_case(name)) { + Some((_, all)) => all.extend_from_slice(groups), + None => apps.push((name, groups.to_vec())), + } + } + let lists: Vec = apps + .into_iter() + .map(|(name, groups)| { + let tags: Vec = groups.iter().map(typed_tag).collect(); + Value::list_with_tail(vec![Value::str(name)], Value::list(groups_to_list(&tags))) + }) + .collect(); + Value::list(lists) +} + +/// The applications of a list's `-3` group, each with its groups (checked as xdata): `None` +/// when the list has no `-3`. An application with no groups removes its data in `entmod`. +fn xdata_from_list(list: &Value) -> Result)>>, LispError> { + let Some(x) = list.iter().find(|v| v.car().as_number() == Some(-3.0)).map(|v| v.cdr()) else { return Ok(None) }; + // `(-3 . 7)` is not a list of applications: refused, not read as "no applications". + if !x.is_list() { + return Err(LispError::bad_arg("listp", &x)); + } + let bad = |what: &str| LispError::new(format!("bad DXF group: {what}")); + let mut out = Vec::new(); + for app in x.iter() { + let name = match app.car() { + Value::Str(s) => s.to_string(), + other => return Err(LispError::bad_arg("stringp", &other)), + }; + cadcraft_doc::check_xdata_app_name(&name).map_err(|e| bad(&e.to_string()))?; + if cadcraft_doc::is_reserved_xdata_app(&name) { + return Err(bad(&format!("xdata application {name} is reserved"))); + } + // The application's groups must be a proper list too: `("ACME" . 7)` would otherwise + // read as "no groups" and remove the data in `entmod`, and a dotted tail after real + // groups would be dropped. + let tail = app.cdr(); + if !tail.is_list() { + return Err(LispError::bad_arg("listp", &tail)); + } + let mut groups: Vec = Vec::new(); + for g in tail.iter() { + if groups.len() >= cadcraft_doc::MAX_XDATA_GROUPS { + return Err(bad("too many xdata groups")); + } + let Value::Cons(c) = &g else { return Err(LispError::bad_arg("consp", &g)) }; + let Value::Int(code) = c.car else { return Err(LispError::bad_arg("fixnump", &c.car)) }; + match &c.cdr { + Value::Cons(_) if (1010..=1013).contains(&code) => { + let p = c.cdr.as_point().ok_or_else(|| LispError::bad_arg("3D point", &c.cdr))?; + if p.iter().any(|v| !v.is_finite()) { + return Err(bad("xdata point must be finite")); + } + groups.push(RawTag { code, value: craft_dxf::format_real(p[0]) }); + groups.push(RawTag { code: code + 10, value: craft_dxf::format_real(p[1]) }); + groups.push(RawTag { code: code + 20, value: craft_dxf::format_real(p[2]) }); + } + Value::Int(i) => groups.push(RawTag { code, value: i.to_string() }), + Value::Real(r) if code == 1071 => { + if r.is_finite() && r.fract() == 0.0 && *r >= f64::from(i32::MIN) && *r <= f64::from(i32::MAX) { + groups.push(RawTag { code, value: (*r as i32).to_string() }); + } else { + return Err(bad("group 1071 must be a 32-bit integer")); + } + } + Value::Real(r) => groups.push(RawTag { code, value: craft_dxf::format_real(*r) }), + Value::Str(s) => groups.push(RawTag { code, value: s.to_string() }), + Value::Ename(h) => groups.push(RawTag { code, value: h.hex() }), + other => return Err(LispError::bad_arg("DXF group value", other)), + } + } + cadcraft_doc::check_xdata_groups(&groups).map_err(|e| bad(&e.to_string()))?; + out.push((name, groups)); + } + Ok(Some(out)) +} + +/// `(regapp "name")`: register an application for xdata. The name when it is new, nil when it +/// is already registered (by `regapp` or by xdata an object carries) or invalid. Saving writes +/// an APPID record for every application with xdata, so nothing else is needed. +pub fn regapp(ctx: &mut Ctx<'_>, a: Vec) -> Result { + arity(&a, 1, 1)?; + let name = string(&a[0])?; + if cadcraft_doc::check_xdata_app_name(&name).is_err() { + return Ok(Flow::Value(Value::Nil)); + } + let up = name.trim().to_ascii_uppercase(); + let known = ctx.env.regapps.contains(&up) || ctx.s.doc().is_ok_and(|d| xdata_app_names(d).contains(&up)); + if known { + return Ok(Flow::Value(Value::Nil)); + } + ctx.env.regapps.insert(up); + Ok(Flow::Value(Value::str(name.trim()))) +} + +/// The upper-case names of every application registered in the drawing or carrying xdata on an object. +fn xdata_app_names(d: &cadcraft_doc::Drawing) -> std::collections::BTreeSet { + std::iter::once(&d.model) + .chain(d.layouts.iter().map(|l| &l.entities)) + .chain(d.blocks.values().map(|b| &b.entities)) + .flat_map(|s| s.iter()) + .flat_map(|e| cadcraft_doc::xdata_apps(&e.common.xdata).into_iter().map(|(n, _)| n.to_ascii_uppercase()).collect::>()) + .chain(d.foreign.appids.iter().map(|n| n.to_ascii_uppercase())) + .collect() +} + +/// The entity a list describes, as the reader makes it, with the applications of its `-3` +/// group (their xdata is on the entity); a missing layer (8) is the current one. +type ListedEntity = (String, cadcraft_doc::Common, cadcraft_doc::EntityKind, Option)>>); +fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result { let (kind, mut tags) = list_to_groups(list)?; + let xdata = xdata_from_list(list)?; convert_angles(&kind, &mut tags, f64::to_degrees); if !tags.iter().any(|t| t.code == 8) { let layer = crate::sysvars::get(ctx.s, "CLAYER").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "0".into()); @@ -415,7 +861,23 @@ fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc match (codec()?.entity)(&kind, &tags) { // A type the reader only carries through (an unknown or invalid name) isn't made. Some((_, cadcraft_doc::EntityKind::Unknown(_))) | None => Err(LispError::new(format!("bad DXF group: {kind} can't be made from this list"))), - Some((common, k)) => Ok((kind, common, k)), + Some((mut common, k)) => { + if let Some(apps) = &xdata { + for (app, groups) in apps { + // `ACAD` on a dimension holds its overrides (DSTYLE), written from the model. + if cadcraft_doc::is_model_xdata_app(app, &k) { + return Err(LispError::new(format!("bad DXF group: xdata application {app} of a {kind} is written from its own properties"))); + } + cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups)); + } + // Each application's groups are checked one by one above; together they must + // still fit what a file holds for one object. + if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS { + return Err(LispError::new("bad DXF group: too many xdata groups")); + } + } + Ok((kind, common, k, xdata)) + } } } @@ -428,7 +890,7 @@ pub fn entmake(ctx: &mut Ctx<'_>, a: Vec) -> Result { Ok((k, _)) if k == "ENDBLK" => return Ok(Flow::Value(end_block(ctx))), _ => {} } - let (_, common, kind) = match entity_from_list(ctx, list) { + let (_, common, kind, _) = match entity_from_list(ctx, list) { Ok(x) => x, Err(_) => return Ok(Flow::Value(Value::Nil)), }; @@ -527,11 +989,16 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value { pub fn entmod(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; let list = &a[0]; - let Some(Value::Ename(h)) = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()) else { + let name = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()); + // An INSERT's record takes a value edit only (#1660); any other edit of one is refused. + if let Some(Value::Record(r)) = name { + return Ok(Flow::Value(entmod_attrib(ctx, list, r))); + } + let Some(Value::Ename(h)) = name else { return Err(LispError::bad_arg("lentityp", &Value::Nil)); }; let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) }; - let (kind_name, common, mut kind) = match entity_from_list(ctx, list) { + let (kind_name, mut common, mut kind, xdata) = match entity_from_list(ctx, list) { Ok(x) => x, Err(_) => return Ok(Flow::Value(Value::Nil)), }; @@ -539,6 +1006,17 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec) -> Result { if !kind_name.eq_ignore_ascii_case(old.kind.dxf_name()) { return Ok(Flow::Value(Value::Nil)); } + // Xdata stays unless the list has a -3 group, which replaces the data of the applications it + // names (one with no groups removes it) and leaves the others alone, as in AutoCAD. + common.xdata = old.common.xdata.clone(); + if let Some(apps) = &xdata { + for (app, groups) in apps { + cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups)); + } + if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS { + return Ok(Flow::Value(Value::Nil)); + } + } // A block reference's attributes are entities of their own in AutoCAD, which entmod of the // INSERT leaves alone; its list doesn't hold them, so they are kept from the reference. if let (cadcraft_doc::EntityKind::Insert(new), cadcraft_doc::EntityKind::Insert(was)) = (&mut kind, &old.kind) @@ -560,9 +1038,15 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec) -> Result { Ok(Flow::Value(if ok { list.clone() } else { Value::Nil })) } -/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). +/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). For an INSERT's record +/// (#1660) its reference: the record's name while it holds. pub fn entupd(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; + if let Value::Record(r) = &a[0] { + let holds = record_of(ctx, *r).is_some(); + ctx.s.touch(); + return Ok(Flow::Value(if holds { a[0].clone() } else { Value::Nil })); + } let h = ename(&a[0])?; ctx.s.touch(); Ok(Flow::Value(if ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()) { Value::Ename(h) } else { Value::Nil })) @@ -571,10 +1055,18 @@ pub fn entupd(ctx: &mut Ctx<'_>, a: Vec) -> Result { /// `(entdel ename)`: delete an entity, or bring back one this routine's drawing deleted. pub fn entdel(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; + // An INSERT's ATTRIB or SEQEND is the reference's: it is not deleted on its own (#1660). + if matches!(a[0], Value::Record(_)) { + return Ok(Flow::Value(Value::Nil)); + } let h = ename(&a[0])?; let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) }; if let Some(space) = d.space_of(h) { if let Some(e) = d.remove_entity(h) { + // The names of its records went with it: `entdel` bringing it back brings none back. + if let Some(names) = ctx.s.record_names() { + names.erased(&e); + } ctx.env.deleted.insert(h, (space, e)); ctx.s.touch(); return Ok(Flow::Value(Value::Ename(h))); @@ -670,24 +1162,41 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn entnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 0, 1)?; - // From an entity of a block definition: the next one in that block, nil after the last (#1700). - if let Some(v) = a.first().filter(|v| !v.is_nil()) { - let h = ename(v)?; - if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none()) - && let Some((_, next)) = block_slots(ctx).get(&h) - { - return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())); + let after = match a.first() { + None | Some(Value::Nil) => None, + // From a record of an INSERT (#1660): the next record of its run, and after its SEQEND the + // next main entity after the INSERT. A name that no longer holds names nothing. + Some(Value::Record(r)) => { + let Some((owner, slot)) = record_of(ctx, *r) else { return Ok(Flow::Value(Value::Nil)) }; + let attribs = ctx.s.doc().ok().and_then(|d| insert_attribs(d, owner)).map_or(0, <[cadcraft_doc::Attrib]>::len); + if slot < attribs { + return Ok(Flow::Value(name_record(ctx, owner, slot.saturating_add(1)).map(Value::Record).unwrap_or_default())); + } + Some(owner) } - } - let order = handles_in_order(ctx); - let next = match a.first() { - None | Some(Value::Nil) => order.first().copied(), Some(v) => { let h = ename(v)?; - let i = order.partition_point(|x| *x <= h); - order.get(i).copied() + // From an entity of a block definition: the next one in that block, nil after the last (#1700). + if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none()) + && let Some((_, next)) = block_slots(ctx).get(&h) + { + return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())); + } + // An INSERT with attributes is followed by its ATTRIBs and its SEQEND (#1660): its + // first ATTRIB, or nil when no name is left to give (the walk stops rather than skip + // records it can't name). A host without the optional record mapping has no such + // records: the walk goes on to the next entity, as it always did. + if crate::cmd::file::entity_sub_record().is_some() && ctx.s.doc().is_ok_and(|d| insert_attribs(d, h).is_some()) { + return Ok(Flow::Value(name_record(ctx, h, 0).map(Value::Record).unwrap_or_default())); + } + Some(h) } }; + let order = handles_in_order(ctx); + let next = match after { + Some(h) => order.get(order.partition_point(|x| *x <= h)).copied(), + None => order.first().copied(), + }; Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())) } @@ -969,6 +1478,13 @@ fn compare(h: f64, w: f64, op: &str) -> bool { pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 0, 2)?; + // A selection set holds objects of the drawing; an INSERT's record (#1660) is not one. + if matches!(a.first(), Some(Value::Record(_))) { + if let Some(ss) = a.get(1) { + pickset(ss)?; + } + return Ok(Flow::Value(Value::Nil)); + } match (a.first(), a.get(1)) { (None, _) => Ok(Flow::Value(new_pickset(ctx, Vec::new()))), (Some(e), None) => { @@ -990,6 +1506,11 @@ pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn ssdel(_ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 2, 2)?; + // Never in a selection set (#1660). + if matches!(a[0], Value::Record(_)) { + pickset(&a[1])?; + return Ok(Flow::Value(Value::Nil)); + } let h = ename(&a[0])?; let p = pickset(&a[1])?; let removed = p.items.lock().map(|mut v| { @@ -1017,6 +1538,11 @@ pub fn ssname(_ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn ssmemb(_ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 2, 2)?; + // Never in a selection set (#1660). + if matches!(a[0], Value::Record(_)) { + pickset(&a[1])?; + return Ok(Flow::Value(Value::Nil)); + } let h = ename(&a[0])?; Ok(Flow::Value(if items(&pickset(&a[1])?).contains(&h) { Value::Ename(h) } else { Value::Nil })) } @@ -1116,11 +1642,27 @@ fn table_records(d: &cadcraft_doc::Drawing, table: &str) -> Vec { .iter() .map(|s| Value::list(vec![pair(0, Value::str("DIMSTYLE")), pair(2, Value::str(&s.name)), pair(70, Value::Int(0))])) .collect(), - "APPID" => vec![Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str("ACAD")), pair(70, Value::Int(0))])], + "APPID" => std::iter::once("ACAD".to_string()) + .chain(xdata_app_names(d).into_iter().filter(|n| n != "ACAD")) + .map(|n| Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(&n)), pair(70, Value::Int(0))])) + .collect(), _ => Vec::new(), } } +/// [`table_records`] plus, for APPID, the applications `regapp` registered in this session. +fn table_records_with(ctx: &Ctx<'_>, d: &cadcraft_doc::Drawing, table: &str) -> Vec { + let mut records = table_records(d, table); + if table == "APPID" { + let have: Vec = records.iter().map(record_name).map(|n| n.to_ascii_uppercase()).collect(); + for app in ctx.env.regapps.iter().filter(|a| !have.contains(a)) { + let pair = |c: i32, v: Value| Value::cons(Value::Int(c), v); + records.push(Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(app)), pair(70, Value::Int(0))])); + } + } + records +} + fn record_name(r: &Value) -> String { r.iter().find(|p| p.car().as_number() == Some(2.0)).map(|p| to_text(&p.cdr(), false)).unwrap_or_default() } @@ -1130,7 +1672,7 @@ pub fn tblsearch(ctx: &mut Ctx<'_>, a: Vec) -> Result { let table = string(&a[0])?.to_ascii_uppercase(); let name = string(&a[1])?; let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; - let records = table_records(d, &table); + let records = table_records_with(ctx, d, &table); let found = records.iter().position(|r| record_name(r).eq_ignore_ascii_case(&name)); if let Some(i) = found && a.get(2).is_some_and(|v| !v.is_nil()) @@ -1145,7 +1687,7 @@ pub fn tblnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { let table = string(&a[0])?.to_ascii_uppercase(); let rewind = a.get(1).is_some_and(|v| !v.is_nil()); let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; - let records = table_records(d, &table); + let records = table_records_with(ctx, d, &table); let i = if rewind { 0 } else { ctx.env.tblnext.get(&table).copied().unwrap_or(0) }; ctx.env.tblnext.insert(table, i + 1); Ok(Flow::Value(records.get(i).cloned().unwrap_or_default())) diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 11ed7e3bb..26eac62b6 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -1,11 +1,16 @@ #![allow(clippy::unwrap_used)] +use cadcraft_doc::Handle; +use serde_json::json; + use super::value::{Value, to_text}; use crate::Session; -use crate::cmd::file::{EntityCodec, set_entity_codec, set_object_records}; +use crate::cmd::file::{EntityCodec, set_entity_codec, set_entity_sub_record, set_object_records}; pub(super) fn session() -> Session { set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. set_object_records(cadcraft_io::object_records); Session::new() @@ -666,6 +671,154 @@ fn handseed_follows_new_objects() { assert_eq!(ok(&mut s, "(cdr (assoc 5 (entget (entlast))))"), format!("\"{:X}\"", held + 1)); } +#[test] +fn entity_lists_carry_xdata_in_group_minus_3() { + let mut s = session(); + // entmake with a -3 group puts the xdata on the new entity; entget shows it only when asked. + let made = ok( + &mut s, + "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000)) (\"PE_URL\" (1000 . \"https://example.com\")))))", + ); + assert!(made.contains("LINE")); + assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast)))"), "nil"); + assert_eq!( + ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"), + "((\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000.0)))" + ); + // Group 1070 is INT, whereas group 1071 is REAL in AutoLISP's entget while remaining a 32-bit + // integer in the drawing/API and when written back with entmod. + assert_eq!( + ok( + &mut s, + "(setq g (cdr (car (cdr (assoc -3 (entget (entlast) '(\"ACME\"))))))) (list (type (cdr (assoc 1070 g))) (type (cdr (assoc 1071 g))))" + ), + "(INT REAL)" + ); + assert!(ok(&mut s, "(entmod (entget (entlast) '(\"ACME\")))").contains("LINE")); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2"); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"PE_*\" \"nope\")))))"), "1"); + assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"nope\")))"), "nil"); + // The xdata is what the drawing holds (the API sees 1070 and 1071 as integers too). + let x = s.execute("entities", &serde_json::json!({"xdata": "ACME"})).unwrap(); + assert_eq!(x["entities"][0]["xdata"]["ACME"][1], serde_json::json!([1070, 3])); + assert_eq!(x["entities"][0]["xdata"]["ACME"][5], serde_json::json!([1071, 100000])); + // entmod without -3 keeps the xdata; with -3 it replaces the named applications' data and + // removes one listed without groups; the others stay. + ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"WALLS\") (assoc 8 d) d))"); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2"); + ok(&mut s, "(entmod (append (entget (entlast)) (list (list -3 (list \"ACME\" (cons 1070 9))))))"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACME\"))))"), "((\"ACME\" (1070 . 9)))"); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2"); + ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"PE_URL\")))))"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))"); + // Bad xdata is refused as a bad list (nil), and nothing changes. + for bad in [ + "(-3 (\"ACME\" (1002 . \"{\")))", + "(-3 (\"ACME\" (8 . \"0\")))", + "(-3 (\"ACME\" (1070 . 70000)))", + "(-3 (\"ACME\" (1071 . 1.5)))", + "(-3 (\"ACME\" (1071 . 2147483648.0)))", + "(-3 (\"ACME\" (1071 . -2147483649.0)))", + "(-3 (\"ACME\" (1010 1.0)))", + "(-3 (\"CADCRAFT\" (1000 . \"x\")))", + "(-3 (\"\" (1000 . \"x\")))", + "(-3 (7 (1000 . \"x\")))", + "(-3 (\"ACME\" 5))", + ] { + assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({bad})))")), "nil", "{bad}"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}"); + } + assert!(eval(&mut s, "(entget (entlast) \"ACME\")").is_err(), "the second argument is a list"); + // regapp: the name when new, nil once registered (by regapp or by xdata an object carries); + // the APPID table lists both. + assert_eq!(ok(&mut s, "(regapp \"ACME\")"), "nil"); + assert_eq!(ok(&mut s, "(regapp \"MYAPP\")"), "\"MYAPP\""); + assert_eq!(ok(&mut s, "(regapp \"myapp\")"), "nil"); + assert_eq!(ok(&mut s, "(regapp \"bad*name\")"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"acme\")))"), "\"ACME\""); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"MYAPP\")))"), "\"MYAPP\""); + assert_eq!(ok(&mut s, "(tblsearch \"APPID\" \"PE_URL\")"), "nil"); +} + +#[test] +fn group_1071_boundary_reals_round_trip_as_32bit_integers() { + let mut s = session(); + let made = + ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"LIMITS\" (1071 . 2147483647.0) (1071 . -2147483648.0) (1071 . -0.0)))))"); + assert!(made.contains("LINE")); + assert_eq!(ok(&mut s, "(type (cdr (assoc 1071 (cdr (car (cdr (assoc -3 (entget (entlast) '(\"LIMITS\")))))))))"), "REAL"); + assert!(ok(&mut s, "(entmod (entget (entlast) '(\"LIMITS\")))").contains("LINE")); + let lim = s.execute("entities", &serde_json::json!({"xdata": "LIMITS"})).unwrap(); + assert_eq!(lim["entities"][0]["xdata"]["LIMITS"], serde_json::json!([[1071, 2147483647], [1071, -2147483648], [1071, 0]])); +} + +#[test] +fn entmake_refuses_xdata_over_the_object_limit_across_applications() { + // Each application's groups fit the per-application cap; together they exceed what an object + // may hold, so the list is refused (nil) and nothing is made. + let mut s = session(); + ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0)))"); + let last = ok(&mut s, "(entlast)"); + let groups = "(1000 . \"x\") ".repeat(cadcraft_doc::MAX_XDATA_GROUPS / 2 + 8); + let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}) (\"A2\" {groups}))))"); + assert_eq!(ok(&mut s, &code), "nil"); + assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made"); + // Half of that on one application is within the limit and is made. + let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}))))"); + assert!(ok(&mut s, &code).contains("LINE")); + assert_ne!(ok(&mut s, "(entlast)"), last); +} + +#[test] +fn a_dotted_minus_3_group_is_refused() { + // `(-3 . 7)` names no applications; it is a bad list (nil), not an empty one. + let mut s = session(); + ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1070 . 9)))))"); + let last = ok(&mut s, "(entlast)"); + assert_eq!(ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 . 7)))"), "nil"); + assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made"); + assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 . 7))))"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))"); + // The same one level down: an application whose groups are not a proper list is refused, + // not read as "no groups" (which would remove its data), and a dotted tail after real + // groups is not dropped. + for bad in ["(\"ACME\" . 7)", "(\"ACME\" (1070 . 1) . 5)", "(\"NEW\" . \"x\")"] { + assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '((-3 {bad}))))")), "nil", "{bad}"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}"); + assert_eq!(ok(&mut s, &format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 {bad})))")), "nil", "{bad}"); + assert_eq!(ok(&mut s, "(entlast)"), last, "{bad}"); + } +} + +#[test] +fn runs_of_one_application_in_any_case_are_one_list() { + // A file with `ACME` and `acme` runs on one entity: entget shows one application with every + // group, and writing that list back with entmod keeps them all. + let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\ + 1001\nACME\n1070\n1\n1001\nacme\n1070\n2\n1001\nOTHER\n1000\nx\n0\nENDSEC\n0\nEOF\n"; + let mut s = session(); + s.open_drawing(cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(), "runs", None); + let want = "((\"ACME\" (1070 . 1) (1070 . 2)) (\"OTHER\" (1000 . \"x\")))"; + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"), "((\"ACME\" (1070 . 1) (1070 . 2)))"); + assert!(ok(&mut s, "(entmod (entget (entlast) '(\"*\")))").contains("LINE")); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want); +} + +#[test] +fn acad_xdata_of_a_dimension_is_refused_but_kept_on_other_entities() { + // A dimension's ACAD run is its DSTYLE overrides, written from the model: raw ACAD groups + // on it are refused (nil, nothing changes). On a line, ACAD is foreign data and stays. + let mut s = session(); + s.script("dimlinear 0,0 10,0 5,-3\n").unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entlast))))"), "\"DIMENSION\""); + assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"ACAD\" (1070 . 1))))))"), "nil"); + assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"*\")))"), "nil"); + let made = ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACAD\" (1000 . \"MINE\") (1070 . 42)))))"); + assert!(made.contains("LINE")); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), "((\"ACAD\" (1000 . \"MINE\") (1070 . 42)))"); +} + #[test] fn entity_lists_hold_angles_in_radians() { let mut s = session(); @@ -908,6 +1061,48 @@ fn appload_and_load() { assert!(r["error"].as_str().is_some_and(|e| e.contains("bad argument type"))); } +/// Echo lines until the next one trims the command history from the front. +fn fill_history(s: &mut Session) { + // Grow it to its first trim, then back up to the length it had just before it. + let mut top = 0; + loop { + let len = s.log.len(); + s.echo("filler"); + if s.log.len() < len { + break; + } + top = s.log.len(); + } + while s.log.len() < top { + s.echo("filler"); + } +} + +/// #3643: the `lisp` and `appload` JSON commands report the lines their run printed, also when +/// the command history is trimmed from the front while it runs. +#[test] +fn a_lisp_calls_output_survives_the_history_trim() { + let mut s = session(); + // The `y` lines a reply reports; it reports nothing from before the call. + let ys = |r: &serde_json::Value| { + let out = r["output"].as_array().cloned().unwrap_or_default(); + assert!(!out.contains(&serde_json::json!("filler")), "{r}"); + out.iter().filter(|l| *l == "y").count() + }; + let lines = |n: usize| format!("(repeat {n} (princ \"y\") (terpri))"); + fill_history(&mut s); + let r = s.execute("lisp", &serde_json::json!({"code": lines(20)})).unwrap(); + assert_eq!(ys(&r), 20, "{r}"); + fill_history(&mut s); + let r = s.execute("appload", &serde_json::json!({"name": "ys.lsp", "text": lines(20)})).unwrap(); + assert_eq!(ys(&r), 20, "{r}"); + // A run that prints more than the history holds reports every line still held: all its own. + fill_history(&mut s); + let held = s.log.len(); + let r = s.execute("lisp", &serde_json::json!({"code": lines(held + 100)})).unwrap(); + assert_eq!(ys(&r), s.log.len(), "{r}"); +} + /// `command` gives an entity name, alone or as `entsel` returns it (name and point), to a prompt /// picking one object: the point picks that object, and a bare name stands at its DXF group 10 /// point. Each call and its numbers are AutoCAD 2024's (accoreconsole, read back with `entget`); @@ -1631,6 +1826,54 @@ fn an_expression_at_a_prompt_has_a_short_allowance() { assert_eq!(circles(&s), 0); } +/// #3635: a script's next input goes to a routine an earlier input started only once that routine +/// has run on to its end or to the input it waits for: where there is no window, nothing else +/// carries on a routine that gave the interface a frame. Each loop here takes more than a slice. +#[test] +fn a_script_runs_a_long_routine_on_before_its_next_input() { + let mut s = session(); + let circles = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Circle(_))).count(); + let n = super::SLICE; + // CIRCLE's radius (a `pause`) and the `getint` answer come on the next lines, after a loop + // each; the last line's routine runs on before the script returns. + let script = format!( + "(progn (repeat {n} (setq x 1)) (command \"circle\" \"0,0\" pause) (setq k (getint \"Count: \")) (repeat {n} (setq x 2)))\n\ + 5\n\ + 42\n\ + (setq after (list x k))\n\ + (progn (repeat {n} (setq x 3)) (setq last x))\n" + ); + s.script(&script).unwrap(); + assert!(!s.lisp_running(), "{:?}", s.log); + assert_eq!(circles(&s), 1, "{:?}", s.log); + assert_eq!(ok(&mut s, "after"), "(2 42)"); + assert_eq!(ok(&mut s, "last"), "3"); +} + +/// #3635: a routine a script runs on gets no frames, so nothing can stop it by hand: an endless +/// one is stopped with an error once it has taken the steps it may, an endless `*error*` handler +/// in turn, and the script goes on. +#[test] +fn a_script_stops_an_endless_routine() { + let mut s = session(); + let slice = super::SLICE; + // How far an endless count gets with a cap of `cap` steps; the line after it still runs. + let count = |s: &mut Session, cap: u64| { + s.lisp.limits.frameless_steps = cap; + s.script("(setq i 0)\n(while T (setq i (1+ i)))\n(setq after i)\n").unwrap(); + assert!(!s.lisp_running(), "{:?}", s.log); + ok(s, "after").parse::().unwrap() + }; + // Stopped after its first slice, and after five: about five times as far, not unbounded. + let first = count(&mut s, 0); + let five = count(&mut s, 4 * slice); + assert!(first > 0 && five > 3 * first && five < 7 * first, "{first} {five}"); + assert!(s.log.iter().any(|l| l.starts_with("; error: routine stopped after")), "{:?}", s.log); + s.script("(defun *error* (msg) (setq caught msg) (while T))\n(while T)\n").unwrap(); + assert!(!s.lisp_running(), "the routine and its handler were stopped: {:?}", s.log); + assert!(ok(&mut s, "caught").contains("routine stopped after")); +} + /// #1933: a whole number past 32 bits is a real, as the reader and `fix` make one, not a wrapped /// or clamped integer: `atoi` gives the number its digits read as, `gcd` the true divisor. #[test] @@ -1728,3 +1971,704 @@ fn append_checks_the_cell_cap_before_building_its_result() { assert!(super::value::live_cells() < before + 50_000, "no oversized result was built"); assert_eq!(ok(&mut s, "(setq l nil m nil) (length (append '(1) '(2 3)))"), "3"); } + +// ---------------- an INSERT's ATTRIBs and SEQEND (#1660) ---------------- + +/// A session with block K: a circle and attributes (tag, DXF flags, default value). `entmake` +/// goes through the DXF codec, as in the app. +fn with_attributes(defs: &[(&str, i32, &str)]) -> Session { + let mut s = session(); + let mut code = + String::from("(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0)))"); + for (i, (tag, flags, default)) in defs.iter().enumerate() { + let y = 5.0 + 3.0 * i as f64; + code += &format!( + " (entmake '((0 . \"ATTDEF\") (10 0.0 {y:.1} 0.0) (40 . 2.5) (1 . \"{default}\") (3 . \"P{tag}\") (2 . \"{tag}\") (70 . {flags})))" + ); + } + code += " (entmake '((0 . \"ENDBLK\")))"; + s.cmdline(&format!("(progn {code})")).unwrap(); + s.log.clear(); + s +} + +/// `s` with one reference of K at (10,10), its values `attribs`, and the reference's handle; the +/// LISP global `i` names it. +fn inserted(s: &mut Session, attribs: serde_json::Value) -> Handle { + s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": attribs })).unwrap(); + let h = *s.doc().unwrap().model.handles().last().unwrap(); + ok(s, &format!("(setq i (handent \"{}\")) i", h.hex())); + h +} + +/// Every reference's attributes (tag, value) from the model, in order. +fn attribute_values(s: &Session) -> Vec<(String, String)> { + let d = s.doc().unwrap(); + d.model + .iter() + .filter_map(|e| match &e.kind { + cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect::>()), + _ => None, + }) + .flatten() + .collect() +} + +/// The records from `i` in order: (type, tag, value) and the SEQEND's owner. +const WALK: &str = r#"(progn + (setq e (entnext i) out nil) + (while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e)))))) + (setq out (append out (list (list (cdr (assoc 0 ed)) (cdr (assoc 2 ed)) (cdr (assoc 1 ed)) + (if (equal (cdr (assoc -2 ed)) i) T nil)))) + e (entnext e))) + (list out (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i)))"#; + +#[test] +fn entnext_walks_an_inserts_attribs_then_the_seqend_then_the_next_entity() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2"), ("T3", 0, "D3")]); + inserted(&mut s, json!({ "T1": "A1", "T3": "A3" })); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget i)))"), "\"INSERT\""); + assert_eq!(ok(&mut s, "(cdr (assoc 66 (entget i)))"), "1"); + assert_eq!(ok(&mut s, WALK), "(((\"ATTRIB\" \"T1\" \"A1\" T) (\"ATTRIB\" \"T2\" \"P2\" T) (\"ATTRIB\" \"T3\" \"A3\" T)) \"SEQEND\" T)"); + // After the SEQEND the main order goes on: a line made later is next, then nil. + s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext (entnext (entnext (entnext (entnext i))))))))"), "\"LINE\""); + assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil"); + // A reference of a block without attributes is followed by the next main entity, no SEQEND. + let mut s = with_attributes(&[("T1", 0, "D1")]); + s.cmdline("(progn (entmake '((0 . \"BLOCK\") (2 . \"E\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entmake '((0 . \"ENDBLK\"))))").unwrap(); + s.execute("insert", &json!({ "name": "E", "at": [0, 0] })).unwrap(); + let plain = *s.doc().unwrap().model.handles().last().unwrap(); + s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap(); + assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (entnext (handent \"{}\")))))", plain.hex())), "\"LINE\""); + // The owner is group -2 in a record's list and not 330, and the reference's own list has + // neither (as `entity_groups` keeps it). + inserted(&mut s, json!({ "T1": "A1" })); + assert_eq!(ok(&mut s, "(assoc 330 (entget (entnext i)))"), "nil"); + assert!(attribute_values(&s).iter().any(|(t, v)| t == "T1" && v == "A1")); +} + +#[test] +fn entmod_of_an_attrib_changes_only_its_value() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a) seq (entnext (entnext a)))"); + // The value (group 1) is the one edit an ATTRIB's list takes. + let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))"); + assert!(r.contains("(1 . \"A2\")"), "{r}"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\""); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\""); + assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]); + // A list asking for anything else, and any edit of the SEQEND, is refused and changes nothing. + for code in [ + "(entmod (subst (cons 2 \"X\") (assoc 2 d) d))", + "(entmod (subst (cons 40 9.0) (assoc 40 d) d))", + "(entmod (subst (cons 8 \"L\") (assoc 8 d) d))", + "(entmod (subst (cons 0 \"SEQEND\") (assoc 0 d) d))", + "(entmod (entget seq))", + // Groups `list_to_groups` does not keep are still the reference's: an edit (or an added + // group) is refused, also when the same list changes group 1. + "(entmod (subst (cons 410 \"Layout2\") (assoc 410 d) d))", + "(entmod (subst (cons -2 a) (assoc -2 d) d))", + "(entmod (append d (list (cons 5 \"FF\"))))", + "(entmod (append d (list (cons 330 a))))", + "(entmod (append d (list (cons 360 \"FF\"))))", + "(entmod (append d (list (cons 102 \"{X\"))))", + "(entmod (subst (cons 1 \"A2\") (assoc 1 d) (subst (cons 410 \"Layout2\") (assoc 410 d) d)))", + // The same items, but the outer list ends in an atom: iterating it would drop the tail + // and accept a list `entget` never returned. + "(progn (setq r \"X\" p (reverse d)) (while p (setq r (cons (car p) r) p (cdr p))) (entmod r))", + ] { + assert_eq!(ok(&mut s, code), "nil", "{code}"); + } + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "no refused edit changed the value"); + // `entdel` of a record, and `entdel` of the SEQEND, do nothing either. + assert_eq!(ok(&mut s, "(progn (entdel a) (entdel seq))"), "nil"); + assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "the name still holds: nothing changed"); + // The edit is one undo step: the value goes back with it. + s.undo().unwrap(); + assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]); +} + +#[test] +fn a_subentity_name_expires_when_its_record_is_rebuilt() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // Erased: the records go with the reference. + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(list (entget a) (entnext a))"), "(nil nil)"); + // Undone: the reference is back, the name given before the Undo is not. + s.undo().unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", h.hex())), "\"A1\""); + // ATTSYNC rebuilds the attributes in place: the old name names nothing, the values stay. + ok(&mut s, "(setq b (entnext i))"); + s.execute("attsync", &json!({ "name": "K" })).unwrap(); + assert_eq!(ok(&mut s, "(entget b)"), "nil"); + assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); + // A name never resolves to another attribute: when the record at its place has another tag + // now, it names nothing (the change makes no new epoch), and a new walk reaches the new tag. + ok(&mut s, "(setq c (entnext i))"); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget c)))"), "\"T1\""); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind + && let Some(a) = i.attribs.first_mut() + { + a.tag = "T9".into(); + } + }) + .unwrap(); + assert_eq!(ok(&mut s, "(entget c)"), "nil", "the record at that place has another tag now"); + assert_eq!(ok(&mut s, "(list (cdr (assoc 0 (entget (entnext i)))) (cdr (assoc 2 (entget (entnext i)))))"), "(\"ATTRIB\" \"T9\")"); +} + +#[test] +fn an_empty_attrib_and_a_seqend_have_distinct_names() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) end (entnext a))"); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget end)))"), "\"SEQEND\""); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + let mut blank = i.attribs[0].clone(); + blank.tag.clear(); + i.attribs.push(blank); + } + }) + .unwrap(); + assert_eq!(ok(&mut s, "(entget end)"), "nil"); + assert_eq!(ok(&mut s, "(setq b (entnext a)) (list (cdr (assoc 0 (entget b))) (eq b (entnext a)))"), "(\"ATTRIB\" T)"); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.attribs.truncate(1); + } + }) + .unwrap(); + assert_eq!(ok(&mut s, "(list (entget b) (cdr (assoc 0 (entget (entnext a)))))"), "(nil \"SEQEND\")"); +} + +#[test] +fn explode_and_burst_retire_the_removed_inserts_record_names() { + for command in ["explode", "burst"] { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) end (entnext (entnext a)))"); + let original = s.doc().unwrap().entity(h).unwrap().as_ref().clone(); + inserted(&mut s, json!({ "T1": "B1" })); + ok(&mut s, "(setq b (entnext i))"); + // A host can shorten the run before removal and later reuse the handle. + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.attribs.truncate(1); + } + }) + .unwrap(); + let result = s.execute(command, &json!({ "handles": [h.hex()] })).unwrap(); + assert!(!result["handles"].as_array().unwrap().is_empty(), "{command} creates pieces"); + assert!(s.doc().unwrap().entity(h).is_none(), "{command} removes the reference"); + s.doc_mut().unwrap().model.push(original); + assert_eq!(ok(&mut s, "(list (entget a) (entget end) (cdr (assoc 1 (entget b))))"), "(nil nil \"B1\")", "{command}"); + } +} + +#[test] +fn entmod_obeys_the_refedit_working_set_for_attrib_owners() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let editing = inserted(&mut s, json!({ "T1": "E1" })); + let outside = inserted(&mut s, json!({ "T1": "A1" })); + s.execute("refedit", &json!({ "handle": editing.hex() })).unwrap(); + let read = "(cdr (assoc 1 (entget (entnext i))))"; + let edit = r#"(progn (setq d (entget (entnext i))) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#; + assert_eq!(ok(&mut s, read), "\"A1\""); + assert_eq!(ok(&mut s, edit), "nil"); + assert_eq!(ok(&mut s, read), "\"A1\""); + s.execute("refset", &json!({ "add": [outside.hex()] })).unwrap(); + assert_ne!(ok(&mut s, edit), "nil"); + assert_eq!(ok(&mut s, read), "\"A2\""); +} + +#[test] +fn a_restored_reference_does_not_revive_an_old_name() { + // entdel of the reference, then entdel again to bring it back: the name given before the + // first entdel names nothing, also after the reference returns. + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil"); + assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil", "the name must not come back"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); + // ERASE, then OOPS: the same. Erasing expires the names it took with it. + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.execute("oops", &json!({})).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "OOPS must not revive the name"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); +} + +#[test] +fn erasing_another_object_keeps_an_attrib_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a))"); + s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap(); + let line = *s.doc().unwrap().model.handles().last().unwrap(); + // Erasing another object leaves the reference and its records as they were: the name holds + // and takes the value edit it always took. + s.execute("erase", &json!({ "handles": [line.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\""); + let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))"); + assert!(r.contains("(1 . \"A2\")"), "{r}"); + assert_eq!(attribute_values(&s), [("T1".into(), "A2".into())]); + // Erasing the reference itself ends its names, and OOPS bringing it back revives none. + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.execute("oops", &json!({})).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "the name of an erased reference stays dead"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\""); +} + +#[test] +fn entdel_of_another_object_keeps_an_attrib_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap(); + ok(&mut s, "(setq line (entlast))"); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget line)))"), "\"LINE\""); + ok(&mut s, "(entdel line)"); + assert_eq!(ok(&mut s, "(entget line)"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\""); +} + +#[test] +fn a_name_given_in_the_block_editor_never_resolves_in_the_host() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + s.execute("bedit", &json!({ "name": "K" })).unwrap(); + // A reference made in the editor's drawing, named there. The editor starts from the host's + // drawing, so its handle is the one the host gives its next new object. + s.execute("insert", &json!({ "name": "K", "at": [40, 40], "attribs": { "T1": "E1" } })).unwrap(); + let editor = *s.doc().unwrap().model.handles().last().unwrap(); + ok(&mut s, &format!("(setq a (entnext (handent \"{}\")))", editor.hex())); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"E1\""); + s.execute("bclose", &json!({ "save": false })).unwrap(); + // The host's next reference takes the handle the editor's reference had: the name given in + // the editor must not reach its ATTRIB, or `entmod` through it would edit the wrong one. + s.execute("insert", &json!({ "name": "K", "at": [80, 80], "attribs": { "T1": "H1" } })).unwrap(); + let host = *s.doc().unwrap().model.handles().last().unwrap(); + assert_eq!(host, editor, "the host takes the handle the editor's reference had"); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, "(entdel a)"), "nil"); + assert_eq!( + ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", host.hex())), + "\"H1\"", + "the host's own attribute is untouched" + ); +} + +#[test] +fn without_a_record_provider_entnext_walks_the_next_entity() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap(); + // A host that installed no provider has no records to name: the walk goes on to the next + // main entity as it always did, rather than answering nil at the reference. + let next = crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(entnext i)")); + assert_ne!(next, "nil"); + assert_eq!(crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(cdr (assoc 0 (entget (entnext i))))")), "\"LINE\""); +} + +#[test] +fn a_redo_does_not_revive_an_old_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a))"); + ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))"); + s.undo().unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.redo().unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "Redo must not revive the name"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\""); +} + +#[test] +fn a_block_replace_expires_an_old_attrib_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + // A replacement block with the same tag as K's first attribute: without the expiry, the old + // name would keep naming that place and return the new record. + s.cmdline( + "(progn (entmake '((0 . \"BLOCK\") (2 . \"L\") (70 . 2) (10 0.0 0.0 0.0))) \ + (entmake '((0 . \"ATTDEF\") (10 0.0 0.0 0.0) (40 . 2.5) (1 . \"Z1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \ + (entmake '((0 . \"ENDBLK\"))))", + ) + .unwrap(); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + s.execute("blockreplace", &json!({ "block": "K", "with": "L" })).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "-BLOCKREPLACE rebuilt the record"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); +} + +#[test] +fn a_reinsert_after_undo_takes_the_handle_and_no_old_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // U takes the reference back; INSERT then gives a new one the handle it had. + s.undo().unwrap(); + assert!(s.doc().unwrap().entity(h).is_none()); + let again = inserted(&mut s, json!({ "T1": "B1" })); + assert_eq!(again, h, "the same handle"); + assert_eq!(ok(&mut s, "(list (entget a) (cdr (assoc 1 (entget (entnext i)))))"), "(nil \"B1\")"); +} + +/// A drawing with one reference of `attribs` attributes (all value V), for the bounds. +fn drawing_with_attributes(attribs: usize) -> (Session, Handle) { + let text = |v: &str| 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: cadcraft_doc::HAlign::Left, + valign: cadcraft_doc::VAlign::Baseline, + backwards: false, + upside_down: false, + }; + let mut d = cadcraft_doc::Drawing::new_metric(); + let list = (0..attribs) + .map(|i| cadcraft_doc::Attrib { + tag: format!("T{i}"), + text: text("V"), + invisible: false, + constant: false, + prompt: String::new(), + props: cadcraft_doc::AttribProps::default(), + multiline: None, + modes: cadcraft_doc::AttribModes::default(), + }) + .collect(); + let insert = cadcraft_doc::Insert { block: "B".into(), attribs: list, ..cadcraft_doc::Insert::default() }; + let h = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(insert)).expect("add"); + let mut s = session(); + s.open_drawing(d, "attributes", None); + ok(&mut s, &format!("(setq i (handent \"{}\"))", h.hex())); + (s, h) +} + +/// The number of records a walk from `i` names. +const COUNT: &str = "(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"; + +#[test] +fn a_session_names_at_most_65536_records_and_nothing_changes() { + let (mut s, h) = drawing_with_attributes(65_537); + assert_eq!(ok(&mut s, COUNT), "65536"); + // The names given hold: a second walk is the same, and the drawing kept every attribute. + assert_eq!(ok(&mut s, COUNT), "65536"); + // Erasing and bringing the reference back frees the 65,536 names it held: the old name names + // nothing, and a new walk can name the records again. + ok(&mut s, "(setq a (entnext i))"); + ok(&mut s, "(progn (entdel i) (entdel i))"); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, COUNT), "65536"); + let d = s.doc().unwrap(); + let kept = d.entity(h).and_then(|e| match &e.kind { + cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.len()), + _ => None, + }); + assert_eq!(kept, Some(65_537)); +} + +#[test] +fn a_new_object_at_any_handle_is_never_a_record() { + // A hostile $HANDSEED at the top of the range: the line made after the walk takes that + // handle, and the record keeps its own name, which is no handle. + let (mut s, _) = drawing_with_attributes(1); + s.doc_mut().unwrap().handseed = u64::MAX - 1; + ok(&mut s, "(setq a (entnext i))"); + assert_eq!( + ok(&mut s, r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#), + "\"FFFFFFFFFFFFFFFE\"" + ); + assert_eq!( + ok(&mut s, "(list (cdr (assoc 0 (entget a))) (eq a (entlast)) (entdel a) (cdr (assoc 0 (entget (entlast)))))"), + "(\"ATTRIB\" nil nil \"LINE\")" + ); +} + +#[test] +fn objects_at_the_top_of_the_handle_range_walk_as_objects() { + let (mut s, _) = drawing_with_attributes(1); + { + let d = s.doc_mut().unwrap(); + d.handseed = u64::MAX; + for handle in [Handle(u64::MAX - 1), Handle(u64::MAX)] { + let line = + cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) }); + d.model.push(cadcraft_doc::Entity { handle, common: cadcraft_doc::Common::default(), kind: line }); + } + } + ok(&mut s, "(setq a (entnext i))"); + // The lines' handles are theirs: `entnext` of the first finds the second, then the end. + assert_eq!(ok(&mut s, "(equal (entnext (handent \"FFFFFFFFFFFFFFFE\")) (handent \"FFFFFFFFFFFFFFFF\"))"), "T"); + assert_eq!(ok(&mut s, "(entnext (handent \"FFFFFFFFFFFFFFFF\"))"), "nil"); + // The record, a table record and the lines each keep their own name. + assert_eq!( + ok(&mut s, "(list (cdr (assoc 0 (entget a))) (equal a (tblobjname \"LAYER\" \"0\")) (equal a (handent \"FFFFFFFFFFFFFFFE\")))"), + "(\"ATTRIB\" nil nil)" + ); +} + +#[test] +fn a_record_name_is_an_entity_name_but_no_handle() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) b (entnext a))"); + assert_eq!(ok(&mut s, "(type a)"), "ENAME"); + // The same record has the same name on every walk; another record and the reference have + // their own. + assert_eq!(ok(&mut s, "(list (eq a (entnext i)) (equal a (entnext i)) (eq a b) (eq a i) (equal a i))"), "(T T nil nil nil)"); + // It prints as the reference's handle, a dot and its number: never a handle's text. + let printed = ok(&mut s, "a"); + assert!(printed.starts_with(&format!("'), "{printed}"); + // No handle reaches it: its list has no group 5, and `handent` of the reference's handle is + // the reference. + assert_eq!(ok(&mut s, "(list (assoc 5 (entget a)) (eq a (handent (cdr (assoc 5 (entget i))))))"), "(nil nil)"); + // A DXF group cannot point at it: `entmake` of a list that does is refused. + assert_eq!(ok(&mut s, "(entmake (list '(0 . \"LINE\") '(10 0.0 0.0 0.0) '(11 1.0 0.0 0.0) (cons 340 a)))"), "nil"); +} + +#[test] +fn selection_sets_and_commands_take_no_record() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) ss (ssadd i))"); + // A selection set holds objects of the drawing; a record is not one on its own. + assert_eq!(ok(&mut s, "(list (ssadd a) (ssadd a ss) (sslength ss) (ssmemb a ss) (ssdel a ss) (sslength ss))"), "(nil nil 1 nil nil 1)"); + // A command given the name picks nothing: the reference stays, and the name holds. + ok(&mut s, "(command \"_.ERASE\" a \"\")"); + assert!(s.doc().unwrap().entity(h).is_some()); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\""); +} + +#[test] +fn entupd_of_a_record_answers_its_name_while_it_holds() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a))"); + assert_eq!(ok(&mut s, "(progn (entmod (subst (cons 1 \"A2\") (assoc 1 d) d)) (eq (entupd a) a))"), "T"); + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(entupd a)"), "nil"); +} + +#[test] +fn a_record_name_holds_while_commands_keep_its_record() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // Moving the reference, or changing its colour, keeps its records in their places. + s.execute("move", &json!({ "handles": [h.hex()], "delta": [5, 5] })).unwrap(); + s.execute("chprop", &json!({ "handles": [h.hex()], "color": 1 })).unwrap(); + assert_eq!(ok(&mut s, "(list (cdr (assoc 1 (entget a))) (eq a (entnext i)))"), "(\"A1\" T)"); +} + +#[test] +fn each_record_name_is_one_entry_and_walking_again_adds_none() { + const N: usize = 64; + let (mut s, _) = drawing_with_attributes(N); + let before = s.state().unwrap().doc.clone(); + ok(&mut s, "(setq e nil)"); + // The R3 pattern: each new name, then state access. Nothing is copied or replayed. + for _ in 0..=N { + ok(&mut s, "(setq e (if e (entnext e) (entnext i)))"); + let _ = s.state_mut().unwrap(); + } + let uid = s.state().unwrap().uid; + let held = |s: &Session| s.lisp.records.get(&uid).map_or(0, super::drawing::RecordNames::count); + assert_eq!(held(&s), N + 1, "the attributes and the SEQEND, one entry each"); + assert_eq!(ok(&mut s, COUNT), (N + 1).to_string()); + assert_eq!(held(&s), N + 1, "a walk again gives the same names"); + assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "naming changes nothing in the drawing"); + // Undo or redo ends them: the next walk starts over with as many. + s.execute("line", &json!({ "points": [[0, -4], [1, -4]] })).unwrap(); + s.undo().unwrap(); + assert_eq!(ok(&mut s, COUNT), (N + 1).to_string()); + assert_eq!(held(&s), N + 1); +} + +/// A saved drawing with one named attribute. The name comes from the command line, which does +/// not run the after-command pass. +fn clean_named() -> Session { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + { + let st = s.state_mut().unwrap(); + st.saved = st.doc.clone(); + st.undo.clear(); + st.redo.clear(); + } + s.cmdline("(setq a (entnext i))").unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\""); + assert!(!s.state().unwrap().is_dirty(), "naming from the command line saves nothing"); + s +} + +#[test] +fn issued_name_reads_keep_the_drawing_clean() { + let mut s = clean_named(); + s.cmdline("(getvar \"DBMOD\")").unwrap(); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved)); + // A programmatic read runs the after-command pass. That pass must not make a saved drawing dirty. + s.execute("lisp", &json!({ "code": "(entget a)" })).unwrap(); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved)); + assert_eq!(s.state().unwrap().undo.len(), 0, "a read is not an undo step"); +} + +#[test] +fn issued_name_selection_keeps_the_drawing_clean() { + let mut s = clean_named(); + let saved = s.state().unwrap().saved.clone(); + s.execute("select", &json!({ "clear": true })).unwrap(); + assert!(s.state().unwrap().selection.is_empty()); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved)); + assert!(!s.state().unwrap().is_dirty()); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); + assert_eq!(s.state().unwrap().undo.len(), 0, "clearing an empty selection is not an undo step"); +} + +#[test] +fn issued_name_undo_restores_the_saved_drawing() { + let mut s = clean_named(); + let saved = s.state().unwrap().saved.clone(); + // A selection change writes no undo step. If it also changes the drawing, the next command + // records that copy, and undo cannot return to the saved drawing. + s.execute("select", &json!({ "clear": true })).unwrap(); + assert_eq!(s.state().unwrap().undo.len(), 0); + s.execute("line", &json!({ "points": [[0, -3], [1, -3]] })).unwrap(); + assert!(s.undo().unwrap().is_some()); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved), "undo returns the saved drawing, not a reservation copy"); + assert!(!s.state().unwrap().is_dirty()); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); +} + +#[test] +fn a_name_given_in_the_host_never_resolves_in_the_block_editor() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + let mut same = cadcraft_doc::Entity::clone(s.doc().unwrap().entity(h).unwrap()); + if let cadcraft_doc::EntityKind::Insert(ins) = &mut same.kind + && let Some(at) = ins.attribs.first_mut() + { + at.text.value = "E1".into(); + } + s.execute("bedit", &json!({ "name": "K" })).unwrap(); + // An object of the editor's drawing with the handle the host's reference has: the host's + // name must not reach its ATTRIB. + s.doc_mut().unwrap().model.push(same); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.execute("bclose", &json!({ "save": false })).unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); +} + +#[test] +fn a_drawing_put_back_after_a_refused_change_ends_its_names() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let before = s.state().unwrap().doc.clone(); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // A change with a number that is not finite: the drawing goes back as it was, without the + // reference the name was given for. + let bad = cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(f64::NAN, 0.0, 0.0), b: cadcraft_geom::Vec3::ZERO }); + s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), bad).unwrap(); + assert!(s.refuse_non_finite(None, &before, &[], "line").is_err()); + assert!(s.doc().unwrap().entity(h).is_none()); + // The next reference takes the handle back: the old name names nothing in it. + assert_eq!(inserted(&mut s, json!({ "T1": "B1" })), h); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"B1\""); +} + +/// MOCORO's own Undo puts the drawing from before the Copy back, handle seed included. +/// The next Copy is given that handle again. The name of the removed copy's attribute +/// must not read it, walk from it, or change it. +#[test] +fn mocoro_undo_does_not_let_an_old_record_name_reach_the_next_copy() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok( + &mut s, + r#"(progn + (sssetfirst nil nil) + (command "_.MOCORO" i "" '(0 0) "_Copy" '(10 0)) + (setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c) v (cdr (assoc 1 (entget a)))) + (command "_Undo" "_Copy" '(20 0) "_eXit"))"#, + ); + // The name was given for a copy with a handle of its own, and it read that copy's attribute. + // The copy made after the Undo has the removed copy's handle. + assert_eq!(ok(&mut s, "(list (= ch (cdr (assoc 5 (entget i)))) v (= ch (cdr (assoc 5 (entget (entlast))))))"), "(nil \"A1\" T)"); + assert_eq!( + ok( + &mut s, + r#"(progn + (setq d (entget a) w (entnext a)) + (if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d))) + (list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"# + ), + "(T T \"A1\")" + ); +} + +/// A grip Copy's Undo is the same kind of restore: the next copy reuses the handle. +#[test] +fn grip_copy_undo_does_not_let_an_old_record_name_reach_the_next_copy() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + s.start_grip_edit(&[(h, 0)]).unwrap(); + // Enter leaves STRETCH for MOVE, which copies the reference whole. + s.input(crate::Input::Enter).unwrap(); + s.input(crate::Input::Keyword("Copy".into())).unwrap(); + s.input(crate::Input::Point(cadcraft_geom::Vec2::new(20.0, 10.0))).unwrap(); + // The name is given for a copy with a handle of its own, and it reads that copy's attribute. + assert_eq!( + ok( + &mut s, + r#"(progn + (setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c)) + (list (= ch (cdr (assoc 5 (entget i)))) (cdr (assoc 1 (entget a)))))"# + ), + "(nil \"A1\")" + ); + s.input(crate::Input::Keyword("Undo".into())).unwrap(); + s.input(crate::Input::Point(cadcraft_geom::Vec2::new(30.0, 10.0))).unwrap(); + assert_eq!(ok(&mut s, "(= ch (cdr (assoc 5 (entget (entlast)))))"), "T", "the next copy takes the removed copy's handle"); + assert_eq!( + ok( + &mut s, + r#"(progn + (setq d (entget a) w (entnext a)) + (if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d))) + (list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"# + ), + "(T T \"A1\")" + ); +} diff --git a/crates/engine/src/lisp/value.rs b/crates/engine/src/lisp/value.rs index fd95d2ec7..4ccf5d16c 100644 --- a/crates/engine/src/lisp/value.rs +++ b/crates/engine/src/lisp/value.rs @@ -12,7 +12,7 @@ //! ([`charge_bytes`]). use std::cell::Cell; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use cadcraft_doc::Handle; @@ -207,6 +207,26 @@ pub enum BuiltinKind { Special(super::eval::Special), } +/// The name AutoLISP gives an INSERT's ATTRIB or SEQEND (#1660). Those records have no handle of +/// their own in the drawing, so their names are not handles: `id` comes from one count for the +/// whole process and is never given again, so no object of any drawing, and no other record, +/// ever has it. `owner` is the reference's handle, for printing. What a name stands for is kept +/// by the session; a name that no longer holds names nothing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RecordName { + pub(crate) owner: Handle, + pub(crate) id: u64, +} + +impl RecordName { + /// A name never given before, for a record of `owner`; `None` once the count runs out. + pub(crate) fn fresh(owner: Handle) -> Option { + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)).ok()?; + Some(RecordName { owner, id }) + } +} + #[derive(Clone, Debug, Default)] pub enum Value { #[default] @@ -217,6 +237,8 @@ pub enum Value { Sym(Sym), Cons(Arc), Ename(Handle), + /// An INSERT's ATTRIB or SEQEND (#1660): an entity name that is no handle. + Record(RecordName), PickSet(PickSet), File(u32), Subr(&'static Builtin), @@ -310,7 +332,7 @@ impl Value { Value::Str(_) => "STR", Value::Sym(_) => "SYM", Value::Cons(_) => "LIST", - Value::Ename(_) => "ENAME", + Value::Ename(_) | Value::Record(_) => "ENAME", Value::PickSet(_) => "PICKSET", Value::File(_) => "FILE", Value::Subr(_) => "SUBR", @@ -423,6 +445,7 @@ fn atom_equal(a: &Value, b: &Value, fuzz: f64) -> bool { (Value::Str(x), Value::Str(y)) => x == y, (Value::Sym(x), Value::Sym(y)) => x == y, (Value::Ename(x), Value::Ename(y)) => x == y, + (Value::Record(x), Value::Record(y)) => x == y, (Value::File(x), Value::File(y)) => x == y, (Value::PickSet(x), Value::PickSet(y)) => x.id == y.id, (Value::Subr(x), Value::Subr(y)) => std::ptr::eq(*x, *y), @@ -567,6 +590,8 @@ fn write_value(out: &mut String, v: &Value, escape: bool, depth: usize) { out.push(')'); } Value::Ename(h) => out.push_str(&format!("", h.0)), + // The reference's handle, a dot and the record's number: never a handle's text. + Value::Record(r) => out.push_str(&format!("", r.owner.0, r.id)), Value::PickSet(p) => out.push_str(&format!("", p.id)), Value::File(f) => out.push_str(&format!("#")), Value::Subr(b) => out.push_str(&format!("#", "0", b.name)), diff --git a/crates/engine/src/mtext_edit.rs b/crates/engine/src/mtext_edit.rs index 103178472..4d33a5b6d 100644 --- a/crates/engine/src/mtext_edit.rs +++ b/crates/engine/src/mtext_edit.rs @@ -437,7 +437,7 @@ impl Formatted { out.push_str("\\P"); } if *props != emitted { - out.push_str(&props.code()); + out.push_str(&props.code_after(&emitted)); emitted = props.clone(); } let end = chars.iter().skip(i).position(|c| *c == '\n').map_or(chars.len(), |n| i + n); @@ -664,4 +664,53 @@ mod tests { assert!(Formatted::fits(&format!("{}a{}", "{".repeat(64), "}".repeat(64)))); assert!(!Formatted::fits(&format!("{}a{}", "{".repeat(65), "}".repeat(65)))); } + + #[test] + fn mixed_paragraph_line_spacing_reset_survives_textedit_roundtrip() { + let mut s = crate::Session::new(); + let res = s + .execute( + "mtext", + &serde_json::json!({ + "at": [0.0, 0.0], + "height": 0.2, + "text": "\\pxsm1.5;First\\P\\pxs*;Second\\PThird", + }), + ) + .unwrap(); + let handle = res["handle"].as_str().unwrap().to_string(); + let doc_handle = cadcraft_doc::Handle::parse_hex(&handle).unwrap(); + let orig_contents = match &s.doc().unwrap().entity(doc_handle).unwrap().kind { + cadcraft_doc::EntityKind::MText(m) => m.contents.clone(), + _ => panic!("expected MText"), + }; + + let mut f = Formatted::from_contents_with_height(&orig_contents, Some(0.2)); + assert!(f.set_text("First\nSecond edited\nThird", &CharFmt::default())); + let edited = f.to_contents(); + s.execute("textedit", &serde_json::json!({"handle": handle, "text": edited})).unwrap(); + + let saved_contents = match &s.doc().unwrap().entity(doc_handle).unwrap().kind { + cadcraft_doc::EntityKind::MText(m) => m.contents.clone(), + _ => panic!("expected MText"), + }; + let reopened = Formatted::from_contents_with_height(&saved_contents, Some(0.2)); + assert_eq!(reopened.para(0).line_spacing, Some(cadcraft_fonts::ParaLineSpacing::Multiple(1.5)), "{saved_contents}"); + assert_eq!(reopened.para(1).line_spacing, None, "{saved_contents}"); + assert_eq!(reopened.para(2).line_spacing, None, "{saved_contents}"); + + let p_08 = cadcraft_fonts::MTextParams { + line_spacing: 0.8, + line_spacing_exact: false, + ..cadcraft_fonts::MTextParams::new(cadcraft_geom::Vec2::ZERO, 0.2) + }; + let saved_layout = cadcraft_fonts::layout_mtext_with(&saved_contents, &p_08); + let all_15 = cadcraft_fonts::layout_mtext_with("\\pxsm1.5;First\\PSecond edited\\PThird", &p_08); + assert!( + saved_layout.bounds.height() < all_15.bounds.height() - 0.05, + "saved={:?} vs all_15={:?} ({saved_contents})", + saved_layout.bounds.height(), + all_15.bounds.height() + ); + } } diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index f2d46d9ca..88cf625c3 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -83,6 +83,10 @@ pub struct Prompt { /// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area. #[serde(skip_serializing_if = "std::ops::Not::not")] pub corner: bool, + /// Dynamic Input asks for this point as X and Y, whatever DYNPIFORMAT says: a rectangle's size + /// (RECTANG's other corner), as the reference application does. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub xy: bool, /// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip /// index): Dynamic Input shows its dimensions ([`crate::grip_dims`]). #[serde(skip_serializing_if = "Option::is_none")] @@ -192,6 +196,11 @@ impl Prompt { self.corner = true; self } + /// Dynamic Input asks for X and Y (the `xy` field). + pub fn xy(mut self) -> Self { + self.xy = true; + self + } /// Asks for a distance from the base (the `distance` field). pub fn distance(mut self) -> Self { self.distance = true; diff --git a/crates/engine/src/properties.rs b/crates/engine/src/properties.rs index a889d0173..7a46bd633 100644 --- a/crates/engine/src/properties.rs +++ b/crates/engine/src/properties.rs @@ -365,7 +365,12 @@ fn text_groups(c: &Ctx, ents: &[&Entity], texts: &[&Text]) -> Vec { c.row("positionY", "Position Y", Kind::Distance, texts.iter().map(|t| json!(t.justify_point().y))), c.row("positionZ", "Position Z", Kind::Distance, texts.iter().map(|t| json!(t.insert.z))), ]; - vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }] + // The text's own effects (new text takes them from its style). + let misc = vec![ + c.row("upsideDown", "Upside down", Kind::Bool, texts.iter().map(|t| json!(t.upside_down))), + c.row("backwards", "Backwards", Kind::Bool, texts.iter().map(|t| json!(t.backwards))), + ]; + vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }, Group { name: "Misc", rows: misc }] } fn mtext_groups(c: &Ctx, ents: &[&Entity], mts: &[&MText]) -> Vec { diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index bd6772f26..5673b84b3 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -48,6 +48,8 @@ fn text(at: Vec2, h: f64, s: &str) -> EntityKind { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }) } @@ -214,7 +216,7 @@ pub fn bracket() -> Drawing { add(on("Notes"), text(Vec2::new(4.1, -0.3), 0.16, "FRONT VIEW")); add( on("Notes"), - EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }), + EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None, background: None }), ); let tb0 = Vec2::new(14.0, -0.5); add(on("Title"), lwpoly(rect_vertices(tb0, tb0 + Vec2::new(4.0, 2.0)), true)); diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index fef9443b2..07f277079 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -1,6 +1,6 @@ //! Hit testing and window/crossing selection. -use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds}; +use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, ViewportBounds, entity_bounds}; use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon}; use crate::spatial::{self, SpatialIndex}; @@ -13,8 +13,19 @@ fn draws_a_block(e: &Entity) -> bool { /// Polylines approximating an entity for hit testing, tessellated at `tol`. pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { + hit_polylines_in(d, e, &mut ViewportBounds::new(&[]), tol, true) +} + +/// [`hit_polylines`] through the layout viewport `view`: the parts of a block reference on the +/// layers frozen in that viewport are not drawn there, so they are not hit, and the box around a +/// dimension or multileader is the box around the parts that are drawn ([`bounds_in`]). A +/// dimension's definition points stay, as [`ViewportBounds`] says. With `room` the rectangle a +/// dimension is hit along keeps the room of the text the viewport leaves out ([`outline_in`]), as +/// a selection that touches the dimension tests it; without, it is the box of what the viewport +/// draws, as a selection that must hold the dimension tests it. +fn hit_polylines_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, tol: f64, room: bool) -> Vec> { if matches!(e.kind, EntityKind::Insert(_)) { - let list = insert_geometry(d, e, tol); + let list = insert_geometry(d, e, tol, view.frozen()); return list .prims .iter() @@ -57,19 +68,21 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { { // Text-like objects are hit inside their box; a dimension kept as read that draws its // block, like a dimension. - let b = entity_bounds(d, e, 0); + let b = bounds_in(d, e, None, view); if b.is_empty() { return Vec::new(); } let c = b.corners(); let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]]; if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::MLeader(_)) || draws_a_block(e) { - let list = cadcraft_render::build_entities( + let list = cadcraft_render::build_entities_in_viewport( d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, text: false, linetypes: false, ..Default::default() }, + view.frozen(), ); v = list.prims.iter().map(|p| list.points(p).to_vec()).collect(); + let c = if room { outline_in(d, e, view, b) } else { b }.corners(); v.push(vec![c[0], c[1], c[2], c[3], c[0]]); } v @@ -122,8 +135,46 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { } } -fn insert_geometry(d: &Drawing, e: &Entity, tol: f64) -> cadcraft_render::DisplayList { - cadcraft_render::build_entities(d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() }) +/// The rectangle a selection through the layout viewport `view` hits `e` along, where `b` is the +/// box of what that viewport draws of it ([`bounds_in`]): `b`, and for a dimension drawn from a +/// block also the room of the text in that block that the viewport leaves out +/// ([`ViewportBounds::leaves_out`]) and the drawing itself shows. Without the text the box ends at +/// the dimension line, so a side of the rectangle would run through the place of the text, and a +/// crossing window there, which touched nothing while the rectangle held the text, would take the +/// dimension by that side. Text the drawing hides (its own invisible flag, a layer frozen for the +/// whole drawing or turned off) had no room in the rectangle before a viewport was counted, and +/// has none here. A selection that only has to touch the dimension tests this rectangle, its box +/// test first included ([`touch_box_in`]). A window and a window polygon still need only what the +/// viewport draws inside them ([`in_window_in`], [`select_polygon_in`]). +fn outline_in(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, b: Bounds2) -> Bounds2 { + let EntityKind::Dimension(dm) = &e.kind else { return b }; + if view.frozen().is_empty() { + return b; + } + let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) else { return b }; + let at = dm.insertion_point.xy(); + let shown = |part: &Entity| part.common.visible && d.layer(&part.common.layer).is_none_or(|l| !l.frozen && l.on); + let mut out = b; + for part in + blk.entities.iter().filter(|part| matches!(part.kind, EntityKind::Text(_) | EntityKind::MText(_)) && view.leaves_out(part) && shown(part)) + { + let t = entity_bounds(d, part, 0); + if !t.is_empty() { + out = out.union(&Bounds2::from_points([t.min + at, t.max + at])); + } + } + out +} + +/// What the layout viewport that freezes the layers in `frozen` draws of the block reference `e` +/// (none frozen: what the drawing shows), for hit testing at `tol`. +fn insert_geometry(d: &Drawing, e: &Entity, tol: f64, frozen: &[String]) -> cadcraft_render::DisplayList { + cadcraft_render::build_entities_in_viewport( + d, + std::iter::once(e), + &cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() }, + frozen, + ) } /// The part of an image its clips leave showing, as triangles (three points each); empty when a @@ -141,8 +192,10 @@ fn shown_image_tris(img: &cadcraft_render::DImage) -> Vec { tris } -fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64) -> bool { - let list = insert_geometry(d, e, tol); +/// Whether a fill or an image of the block reference `e` reaches into the box `bx`, of what the +/// layout viewport that freezes the layers in `frozen` draws of it ([`insert_geometry`]). +fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64, frozen: &[String]) -> bool { + let list = insert_geometry(d, e, tol, frozen); list.prims.iter().any(|p| { if let cadcraft_render::Kind::Image { index } = p.kind { let Some(img) = list.images.get(index as usize) else { return false }; @@ -169,11 +222,17 @@ fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 { /// Distance from `p` to the entity (0 inside text boxes and solid fills). pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { - let polys = hit_polylines(d, e, tol); + entity_distance_in(d, e, &mut ViewportBounds::new(&[]), p, tol) +} + +/// [`entity_distance`] through the layout viewport `view`: to what that viewport draws of the +/// entity ([`hit_polylines_in`]). +fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, p: Vec2, tol: f64) -> f64 { + let polys = hit_polylines_in(d, e, view, tol, true); let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min); let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_)) || matches!(e.kind, EntityKind::Tolerance(_)); - if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, p) { + if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, view, p) { best = 0.0; } // A solid hatch fills its loops with odd parity under its island style, as it is drawn, not @@ -194,8 +253,10 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { /// Whether `p` is on the text of a dimension or multileader: inside the box around its words, /// turned with the text, as plain text is hit anywhere inside its box. Their other geometry is /// hit along its lines, so without this the cursor found the object only between the letters' -/// edges and the lines. -fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool { +/// edges and the lines. Text in a dimension's block that `view` leaves out +/// ([`ViewportBounds::leaves_out`]) does not count: the viewport does not draw text on a layer +/// frozen in it, and a pick in its box finds nothing there, as in AutoCAD. +fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool { match &e.kind { // A dimension with a block (as AutoCAD saves them) is drawn from that block: its text is // the text there, not the text the dimension's own geometry would place. @@ -203,7 +264,7 @@ fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool { // The block draws translated by the insertion point (group 12): test there (#2634). Some(blk) => { let p = p - dm.insertion_point.xy(); - blk.entities.iter().any(|be| match &be.kind { + blk.entities.iter().filter(|be| !view.leaves_out(be)).any(|be| match &be.kind { EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p), EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p), _ => false, @@ -380,6 +441,26 @@ pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor: pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Bounds2 { known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0))) } +/// The box a selection made through the layout viewport `view` tests `e` against: the box of +/// what that viewport draws of it. `known` is the box the spatial index holds, of what the +/// drawing shows; it stands unless the viewport freezes layers and `e` draws a block (a block +/// reference, a dimension, a multileader), whose contents on those layers the viewport leaves +/// out. That box is never larger than `known`, so the index still finds every candidate. The +/// frame of blank text stays in it, as in [`bounds_of`]. +fn bounds_in<'a>(d: &'a Drawing, e: &Entity, known: Option, view: &mut ViewportBounds<'a>) -> Bounds2 { + let from_a_block = matches!(e.kind, EntityKind::Insert(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_)); + if from_a_block && !view.frozen().is_empty() { pick_bounds(d, e, view.entity_bounds(d, e)) } else { bounds_of(d, e, known) } +} + +/// The box a selection through `view` that only has to touch `e` (a pick, a crossing window, a +/// fence, a crossing polygon) tests before its hit geometry: [`bounds_in`] with the room +/// [`outline_in`] keeps, so a side of the rectangle a dimension is hit along that lies in that +/// room is not passed over. A selection that must hold `e` tests [`bounds_in`] itself. +fn touch_box_in<'a>(d: &'a Drawing, e: &Entity, known: Option, view: &mut ViewportBounds<'a>) -> Bounds2 { + let b = bounds_in(d, e, known, view); + outline_in(d, e, view, b) +} + pub(crate) fn is_infinite(e: &Entity) -> bool { matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) } @@ -423,6 +504,13 @@ pub fn pick_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, aperture: pick_with(d, space, &ix, frozen, p, aperture) } +/// Candidates [`pick_with`] takes from the tree and sorts; with more, it reads the index topmost +/// first instead (see [`SpatialIndex::top_down`]). +const PICK_SORTED_MAX: usize = 1024; +/// Entities [`pick_with`] reads topmost first before it sorts the tree's candidates after all: a +/// few microseconds when none of them is a hit. +const PICK_TOP_SCAN: usize = 4096; + pub(crate) fn pick_with( d: &Drawing, space: &Space, @@ -430,22 +518,65 @@ pub(crate) fn pick_with( frozen: &[String], p: Vec2, aperture: f64, +) -> Option { + pick_scanning(d, space, ix, frozen, p, aperture, PICK_SORTED_MAX, PICK_TOP_SCAN) +} + +/// [`pick_with`] with its limits: up to `sorted_max` candidates are sorted, more are read topmost +/// first, up to `budget` of them, before the rest are sorted. +#[allow(clippy::too_many_arguments)] +pub(crate) fn pick_scanning( + d: &Drawing, + space: &Space, + ix: &Option>, + frozen: &[String], + p: Vec2, + aperture: f64, + sorted_max: usize, + budget: usize, ) -> Option { let probe = Bounds2::new(p, p).expand(aperture); + let query = probe.expand(aperture); + // One viewport's boxes serve every candidate, from whichever of the readings below asks. + let view = std::cell::RefCell::new(ViewportBounds::new(frozen)); + let hit = |e: &Entity, known: Option| { + let view = &mut *view.borrow_mut(); + selectable(d, e, frozen) + && (is_infinite(e) || touch_box_in(d, e, known, view).expand(aperture).intersects(&probe)) + && entity_distance_in(d, e, view, p, aperture / 4.0) <= aperture + }; // Candidates come topmost first: the first within the aperture is the one. - for (e, known) in candidates(d, space, ix, &probe.expand(aperture), true, true)? { - if !selectable(d, e, frozen) { - continue; - } - let infinite = is_infinite(e); - if !infinite && !bounds_of(d, e, known).expand(aperture).intersects(&probe) { - continue; - } - if entity_distance(d, e, p, aperture / 4.0) <= aperture { - return Some(e.handle); + let topmost = |ix: &SpatialIndex, cands: Vec, below: u32| { + cands + .into_iter() + .rev() + .filter(|i| *i < below) + .filter_map(|i| ix.entity(i).map(|e| (e, ix.bounds(i)))) + .find(|(e, b)| hit(e, Some(*b))) + .map(|(e, _)| e.handle) + }; + if let Some(ix) = ix { + match ix.query_at_most(&query, true, sorted_max) { + Some(Some(cands)) => return topmost(ix, cands, u32::MAX), + // Many candidates: the drawing is shown small and the aperture covers much of it. The + // topmost hit is usually near the top of the draw order: look there first, and sort + // the tree's candidates only to test the ones below those already examined. + Some(None) => { + if let Some(mut top) = ix.top_down(&query, true, budget) { + if let Some((_, e, _)) = top.by_ref().find(|(_, e, b)| hit(e, Some(*b))) { + return Some(e.handle); + } + let floor = top.floor(); + if floor == 0 { + return None; + } + return topmost(ix, ix.query(&query, true)?, floor); + } + } + None => {} } } - None + candidates(d, space, ix, &query, true, true)?.find(|(e, known)| hit(e, *known)).map(|(e, _)| e.handle) } /// Every entity within `aperture` of `p`, topmost first (so the first is what [`pick`] chooses): @@ -459,9 +590,13 @@ pub fn pick_all_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, apert let ix = spatial::index(d, space); let probe = Bounds2::new(p, p).expand(aperture); let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() }; + let mut view = ViewportBounds::new(frozen); cands - .filter(|(e, known)| selectable(d, e, frozen) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe))) - .filter(|(e, _)| entity_distance(d, e, p, aperture / 4.0) <= aperture) + .filter(|(e, known)| { + selectable(d, e, frozen) + && (is_infinite(e) || touch_box_in(d, e, *known, &mut view).expand(aperture).intersects(&probe)) + && entity_distance_in(d, e, &mut view, p, aperture / 4.0) <= aperture + }) .map(|(e, _)| e.handle) .collect() } @@ -508,7 +643,8 @@ pub(crate) fn select_window_with( ) -> Vec { let Some(cands) = candidates(d, space, ix, &bx, crossing, false) else { return Vec::new() }; let tol = window_tol(&bx); - cands.filter(|(e, known)| selectable(d, e, frozen) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect() + let mut view = ViewportBounds::new(frozen); + cands.filter(|(e, known)| selectable(d, e, frozen) && in_window_in(d, e, *known, &mut view, &bx, crossing, tol)).map(|(e, _)| e.handle).collect() } /// The tessellation tolerance window and crossing tests use for a box. @@ -519,15 +655,29 @@ pub(crate) fn window_tol(bx: &Bounds2) -> f64 { /// Whether a window box (`crossing` false: entirely inside) or a crossing box (inside or /// touching its geometry, not just its bounding box) selects `e`. pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option, bx: &Bounds2, crossing: bool, tol: f64) -> bool { + in_window_in(d, e, known, &mut ViewportBounds::new(&[]), bx, crossing, tol) +} + +/// [`in_window`] through the layout viewport `view`: a block reference is inside the box, or +/// touches it, by the parts that viewport draws ([`bounds_in`], [`hit_polylines_in`]). +fn in_window_in<'a>( + d: &'a Drawing, + e: &Entity, + known: Option, + view: &mut ViewportBounds<'a>, + bx: &Bounds2, + crossing: bool, + tol: f64, +) -> bool { let infinite = is_infinite(e); - let eb = bounds_of(d, e, known); + let eb = bounds_in(d, e, known, view); if !infinite && bx.contains_box(&eb) { return true; } - if !crossing || (!infinite && !eb.intersects(bx)) { + if !crossing || (!infinite && !outline_in(d, e, view, eb).intersects(bx)) { return false; } - let polys = hit_polylines(d, e, tol); + let polys = hit_polylines_in(d, e, view, tol, true); let hit = polys.iter().any(|pl| { if pl.len() == 1 { pl.first().is_some_and(|p| bx.contains(*p)) @@ -538,7 +688,7 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option, bx: &Bo // A crossing box inside a text bounding rectangle selects the text. if hit || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_))) - || (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol)) + || (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol, view.frozen())) { return true; } @@ -582,13 +732,14 @@ pub(crate) fn select_fence_with( let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0; let probe = fb.expand(tol); let Some(cands) = candidates(d, space, ix, &probe, true, false) else { return Vec::new() }; + let mut view = ViewportBounds::new(frozen); let mut out = Vec::new(); for (e, known) in cands { // Infinite objects have no useful bounds; like window selection, test their geometry directly. - if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) { + if !selectable(d, e, frozen) || (!is_infinite(e) && !touch_box_in(d, e, known, &mut view).intersects(&probe)) { continue; } - let polys = hit_polylines(d, e, tol); + let polys = hit_polylines_in(d, e, &mut view, tol, true); let hit = fence.windows(2).any(|f| { let (Some(a), Some(b)) = (f.first(), f.get(1)) else { return false }; let fl = Line::new(*a, *b); @@ -619,17 +770,18 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[ let Some(cands) = candidates(d, space, &ix, &pb, crossing, false) else { return Vec::new() }; let edges: Vec = poly.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?))).chain(poly.last().map(|l| Line::new(*l, *first))).collect(); + let mut view = ViewportBounds::new(frozen); let mut out = Vec::new(); for (e, known) in cands { let infinite = is_infinite(e); if !selectable(d, e, frozen) || (infinite && !crossing) { continue; } - let eb = bounds_of(d, e, known); + let eb = if crossing { touch_box_in(d, e, known, &mut view) } else { bounds_in(d, e, known, &mut view) }; if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } { continue; } - let polys = hit_polylines(d, e, tol); + let polys = hit_polylines_in(d, e, &mut view, tol, crossing); let crosses = polys.iter().any(|pl| { pl.windows(2).any(|w| { w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some())) @@ -810,6 +962,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }) } diff --git a/crates/engine/src/session/cmdline.rs b/crates/engine/src/session/cmdline.rs index 695616a6f..e05c0cd8a 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -16,6 +16,21 @@ impl Session { self.input_line(t, false) } + /// Whether Space with `typed` on the command line types a space instead of submitting: at a + /// free-text prompt, or inside an unclosed parenthesised LISP expression where the command + /// line evaluates one. + pub fn space_is_text(&self, typed: &str) -> bool { + if self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point && !p.accept.number) { + return true; + } + let accepts_lisp = match self.current_prompt() { + None => self.lisp_prompt().is_none(), + Some(p) => !p.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo(), + }; + let rest = if self.running.is_none() { typed.trim_start() } else { typed }; + accepts_lisp && matches!(lisp_token_end(rest), Some(None)) + } + /// One line of input: each space ends an input and an empty input (two spaces in a row, a /// trailing space, an empty line) is Enter, which at `Command:` repeats the last command. In a /// script, a free-text prompt (TEXT/MTEXT contents) takes the rest of the line, a prompt with @@ -25,6 +40,11 @@ impl Session { let mut rest = line; let mut first = true; loop { + // A script's next input goes to what the routine an earlier one started waits for, or + // comes after that routine: carry it on first, as the window's frames would. + if script { + self.lisp_run_until_input(); + } if self.running.is_none() { if !script && !first { return Ok(()); @@ -187,7 +207,14 @@ impl Session { return Err(EngineError::BadParams { cmd: "script".into(), msg: "a script is already running; nested scripts are not supported".into() }); } self.in_script = true; + // A script that a LISP routine started (`(command "_.script" …)`) feeds its own lines: they + // are not the routine's input, so a command they start answers as from a script. + let program_input = std::mem::replace(&mut self.program_input, false); let r = self.script_lines(text); + self.program_input = program_input; + // The routine the last input started or answered runs on too: with no window, nothing + // would carry it on once the script returns. + self.lisp_run_until_input(); self.in_script = false; r } @@ -213,41 +240,105 @@ fn lisp_expression(t: &str) -> bool { } /// The next command-line input in `rest` and what follows it: up to a space or tab, except that -/// a LISP expression runs to its closing parenthesis (spaces and quoted strings inside it). +/// a LISP expression runs to its closing parenthesis (spaces, quoted strings and comments +/// inside it). fn next_token(rest: &str) -> (&str, Option<&str>) { - let lead = rest.len() - rest.trim_start_matches('!').len(); - if rest.get(lead..).is_some_and(|r| r.starts_with('(')) { - let (mut depth, mut in_str, mut escaped) = (0i32, false, false); - for (i, c) in rest.char_indices().skip(lead) { - if in_str { - match (escaped, c) { - (true, _) => escaped = false, - (false, '\\') => escaped = true, - (false, '"') => in_str = false, - _ => {} - } - continue; - } - match c { - '"' => in_str = true, - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - let end = i + 1; - // As after any input, a space ends it and a trailing one is Enter. - let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m)); - return (&rest[..end], more); - } - } - _ => {} - } + match lisp_token_end(rest) { + Some(Some(end)) => { + // As after any input, a space ends it and a trailing one is Enter. + let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m)); + (&rest[..end], more) } // Unbalanced: all of it (the reader reports the error). - return (rest, None); + Some(None) => (rest, None), + None => match rest.split_once([' ', '\t']) { + Some((tok, more)) => (tok, Some(more)), + None => (rest, None), + }, } - match rest.split_once([' ', '\t']) { - Some((tok, more)) => (tok, Some(more)), - None => (rest, None), +} + +/// For `rest` starting a parenthesised LISP form (`(…` or `!(…`), the byte offset past its +/// matching `)`, or `Some(None)` while it is still open; `None` when `rest` is not one. +fn lisp_token_end(rest: &str) -> Option> { + let lead = rest.len() - rest.trim_start_matches('!').len(); + let body = rest.get(lead..)?; + if !body.starts_with('(') { + return None; + } + let mut depth = 0i32; + let mut in_str = false; + let mut chars = body.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + if in_str { + match c { + '\\' => { + chars.next(); + } + '"' => in_str = false, + _ => {} + } + continue; + } + match c { + ';' if chars.peek().is_some_and(|(_, n)| *n == '|') => { + chars.next(); + while let Some((_, bc)) = chars.next() { + if bc == '|' && chars.peek().is_some_and(|(_, n)| *n == ';') { + chars.next(); + break; + } + } + } + ';' => { + for (_, lc) in chars.by_ref() { + if lc == '\n' { + break; + } + } + } + '"' => in_str = true, + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + return Some(Some(lead + i + 1)); + } + } + _ => {} + } + } + Some(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn open_lisp_forms_treat_space_as_text_only_where_lisp_evaluates() { + let mut s = Session::new(); + assert!(s.space_is_text("(+ 1")); + assert!(s.space_is_text(" (+ 1")); + assert!(s.space_is_text("!(+ 1")); + assert!(s.space_is_text("(princ \"a ) b\"")); + assert!(s.space_is_text("(princ ;| ) |; 1")); + assert!(s.space_is_text("(+ 1 ; )")); + assert!(!s.space_is_text("(+ 1 ; )\n 2)")); + assert!(!s.space_is_text("(+ 1 2)")); + assert!(!s.space_is_text("!x")); + assert!(!s.space_is_text("line")); + assert_eq!(next_token("(+ 1 ;| ) |; 2) rest"), ("(+ 1 ;| ) |; 2)", Some("rest"))); + assert_eq!(next_token("(+ 1 ; )\n 2) rest"), ("(+ 1 ; )\n 2)", Some("rest"))); + + s.cmdline("circle").unwrap(); + assert!(s.space_is_text("(list 1")); + assert!(!s.space_is_text("(list 1 2)")); + s.cancel(); + + // Prompts inside a waiting LISP routine (`getpoint`) do not evaluate LISP expressions. + s.cmdline("(getpoint)").unwrap(); + assert!(!s.space_is_text("(+ 1")); + s.cancel(); } } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 74e2a9f6e..8ee6a36f3 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -16,7 +16,7 @@ impl Session { if let Some((doc, sel, uid)) = before && let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) { - st.doc = doc; + st.restore_drawing(doc); st.selection = sel; } Err(EngineError::Internal(id.into(), crate::guard::message(&*p))) @@ -50,7 +50,7 @@ impl Session { if let Some((doc, sel, uid)) = &before && let Some(st) = self.docs.iter_mut().find(|d| d.uid == *uid) { - st.doc = doc.clone(); + st.restore_drawing(doc.clone()); st.selection = sel.clone(); } return Err(EngineError::Internal(id.into(), msg)); @@ -104,10 +104,17 @@ impl Session { /// Take the last step back. Inside a LISP routine, the routine's last command first; past /// those, the drawing's step before the routine, which then starts from there. pub fn undo(&mut self) -> Result> { + // A REFCLOSE Save that wrote an xref's file stops U inside a routine as it does outside. + if let Some(why) = self.lisp_undo_barrier() { + return Err(EngineError::Other(why)); + } if let Some(label) = self.lisp_take_back(false) { return Ok(Some(label)); } let st = self.state_mut()?; + if let Some(why) = st.undo.last().and_then(|snap| cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)) { + return Err(EngineError::Other(why)); + } let Some(snap) = st.undo.pop() else { return Ok(None) }; let cur = st.swap_in(snap); let label = cur.label.clone(); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 7ac401090..003068a63 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -78,6 +78,15 @@ impl Session { self.command_origin } + /// Whether an AutoLISP routine is feeding the command line now: the `(command …)` call it makes, + /// or the token it types into a command that is already running. A script's own lines are the + /// program's input too ([`Session::start`] records [`Origin::Program`] for them), so this tells a + /// routine's call from a script's line, and a routine's call inside a script is this, not the + /// script's. + pub fn lisp_program_input(&self) -> bool { + self.program_input + } + /// Start a command by name or alias as if typed at the command line. A script's commands are /// the program's ([`Origin::Program`]), as those of [`Session::start_programmatic`] are, and so /// is a command started by a token a LISP routine feeds through [`Session::typed`]: `(command @@ -233,6 +242,13 @@ impl Session { if input == Input::Enter && let Some(last) = self.last_command.clone() { + // Why: `pastetable` has no standalone `interactive` factory because its TSV + // payload comes from the clipboard; repeat it with the last pasted payload. + if last == "pastetable" + && let Some((tsv, th)) = self.last_paste_table.clone() + { + return self.start_paste_table(&tsv, th); + } return self.start(&last); } return Ok(()); @@ -463,7 +479,7 @@ impl Session { Err(EngineError::Internal(id, m)) => { // Restore and end the command. if let Ok(st) = self.state_mut() { - st.doc = run.before.clone(); + st.restore_drawing(run.before.clone()); } self.echo(format!("Internal error in {id}: {m}")); self.resume_suspended(); @@ -485,7 +501,7 @@ impl Session { let (id, before, selection) = (run.id.clone(), run.before.clone(), run.selection_before.clone()); if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.finish_guarded(run, cancelled))) { if let Ok(st) = self.state_mut() { - st.doc = before; + st.restore_drawing(before); st.selection = selection; } self.echo(format!("Internal error in {id}: {}", crate::guard::message(&*p))); diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 35bcae4df..89579a749 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -83,6 +83,9 @@ pub struct Settings { /// PICKSTYLE: bit 1 picks whole selectable groups ([`cmd::groups`]), bit 2 associative hatches /// with their boundaries (stored, not used yet). pub pickstyle: u8, + /// GROUPDISPLAYMODE: how groups are displayed when selected: + /// 0 individual object grips only, 1 single center grip and bounding box, 2 both (default). + pub groupdisplaymode: u8, pub gripsize: f64, pub cursorsize: f64, /// MAXARRAY: the most objects one array command creates (items × selected objects). @@ -185,6 +188,7 @@ impl Default for Settings { copymode: false, pickdrag: true, pickstyle: 1, + groupdisplaymode: 2, gripsize: 5.0, cursorsize: 5.0, maxarray: 100_000, diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index f913dcee4..d70ee03c6 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -582,7 +582,10 @@ fn gather_in( } } let mut sink = Sink { osmode, aperture, probe, cands: &mut cands, near: &mut near_prims }; - sink.object(&e.kind, None); + // A record kept as read snaps to its graphics one by one, below. + if !matches!(e.kind, EntityKind::Unknown(_)) { + sink.object(&e.kind, None); + } // A block reference snaps to the objects inside it, placed by its transform. if let EntityKind::Insert(ins) = &e.kind { block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m))); @@ -590,14 +593,10 @@ fn gather_in( if let EntityKind::Dimension(dm) = &e.kind { sink.dimension(d, dm, &mut budget, frozen); } - // A dimension kept as read draws its block through a reference in its graphics (#3438), - // and snaps to the objects inside it the same way. + // A proxy snaps to what its graphics draw, and a dimension kept as read to the objects of + // the block it draws through a reference in them (#3438). if let EntityKind::Unknown(u) = &e.kind { - for g in &u.graphics { - if let EntityKind::Insert(ins) = &g.kind { - block_leaves(d, ins, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m))); - } - } + graphics_leaves(d, u, &Mat3::IDENTITY, 0, &mut budget, frozen, &mut |k, m| sink.object(k, Some(m))); } } Some((cands, near_prims)) @@ -908,10 +907,7 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut return; } *budget -= 1; - // Objects on layer 0 take the reference's layer, which is visible. - if !be.common.visible - || (be.common.layer != "0" && (!d.is_visible(be) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&be.common.layer)))) - { + if !drawn_inside(d, be, frozen) { continue; } match &be.kind { @@ -921,14 +917,7 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => { block_leaves(d, &dimension_reference(blk, dm), &mm, depth + 1, budget, frozen, f); } - k @ EntityKind::Unknown(u) => { - f(k, &mm); - for g in &u.graphics { - if let EntityKind::Insert(inner) = &g.kind { - block_leaves(d, inner, &mm, depth + 1, budget, frozen, f); - } - } - } + EntityKind::Unknown(u) => graphics_leaves(d, u, &mm, depth + 1, budget, frozen, f), k => f(k, &mm), } } @@ -936,6 +925,37 @@ fn block_leaves(d: &Drawing, ins: &Insert, m: &Mat3, depth: usize, budget: &mut } } +/// Whether `e`, inside a block reference or a record's graphics, is drawn: not hidden, and on +/// layer 0 (which takes the visible layer of what holds it) or a layer that is on and not frozen. +fn drawn_inside(d: &Drawing, e: &cadcraft_doc::Entity, frozen: &[String]) -> bool { + e.common.visible && (e.common.layer == "0" || (d.is_visible(e) && !frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)))) +} + +/// Calls `f` with each object the graphics of a record kept as read draw (a proxy's, #2697, or a +/// kept dimension's reference to its block, #3438) and the transform `m` placing it, as the +/// renderer draws them: like a block's contents, so graphics on a layer that is off or frozen +/// are left out. The fill hatches are too: each filled shape's outline is drawn as well, and the +/// hatch's sides would offer snaps inside it. +fn graphics_leaves( + d: &Drawing, + u: &cadcraft_doc::Unknown, + m: &Mat3, + depth: usize, + budget: &mut usize, + frozen: &[String], + f: &mut dyn FnMut(&EntityKind, &Mat3), +) { + for g in &u.graphics { + if matches!(g.kind, EntityKind::Hatch(_)) || !drawn_inside(d, g, frozen) { + continue; + } + match &g.kind { + EntityKind::Insert(inner) => block_leaves(d, inner, m, depth, budget, frozen, f), + k => f(k, m), + } + } +} + /// The reference that places a dimension's block as the renderer draws it: the block holds world /// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved /// dimension; #2634). @@ -1277,6 +1297,52 @@ mod tests { assert_eq!(nearest_with_direction(&d, &Space::Model, Vec2::new(5.0, 30.1), 0.5, &["HIDDEN".to_string()], Handle(0)), None); } + /// A proxy snaps to its graphics as the renderer draws them: not to those on a layer that is + /// off or frozen (in the drawing or the viewport), though the proxy's own layer is visible; + /// those on layer 0 take the proxy's. Inside a block the same, beside a visible line that keeps + /// the block in reach. + #[test] + fn proxy_graphics_on_hidden_layers_offer_no_snaps() { + let mut d = drawing(); + for (name, on, frozen) in [("OFF", false, false), ("ICE", true, true), ("VP", true, false)] { + d.ensure_layer(name); + let l = d.layer_mut(name).unwrap(); + (l.on, l.frozen) = (on, frozen); + } + let line = |layer: &str, y: f64| cadcraft_doc::Entity { + common: Common { layer: layer.into(), ..Common::default() }, + ..cadcraft_doc::Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) })) + }; + let graphics = vec![line("OFF", 20.0), line("0", 25.0), line("ICE", 30.0), line("VP", 35.0)]; + let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics }); + d.add(&Space::Model, Common::default(), proxy.clone()).unwrap(); + let mut blk = cadcraft_doc::Block::new("PROXIES"); + blk.entities.push(cadcraft_doc::Entity::new(Handle(1), proxy)); + blk.entities.push(line("0", 21.0)); + d.blocks.insert("PROXIES".into(), std::sync::Arc::new(blk)); + let ins = cadcraft_doc::Insert { + block: "PROXIES".into(), + insert: Vec3::new(100.0, 0.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + ..Default::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + let frozen = ["vp".to_string()]; + let end = |x: f64, y: f64| { + let at = Vec2::new(x, y); + osnap_in(&d, &Space::Model, &None, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen, None) + .into_iter() + .any(|h| h.point.dist(at) < 1e-9) + }; + for x in [10.0, 110.0] { + assert!(end(x, 25.0), "layer 0 at {x}"); + for y in [20.0, 30.0, 35.0] { + assert!(!end(x, y), "hidden at ({x}, {y})"); + } + } + assert!(end(110.0, 21.0), "the block's own line"); + } + #[test] fn endpoint_and_mid() { let d = drawing(); @@ -1308,6 +1374,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); } @@ -1339,6 +1406,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); } @@ -1422,6 +1490,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); } diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 490bafb21..c8dac83fc 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -18,7 +18,7 @@ use std::sync::{Arc, Mutex}; use cadcraft_doc::{Block, BlockBoundsCache, DimStyle, Drawing, Entity, EntityKind, EntityStore, Space, entity_bounds_cached}; use cadcraft_geom::Bounds2; use rstar::primitives::{GeomWithData, Rectangle}; -use rstar::{AABB, RTree}; +use rstar::{AABB, Envelope, RTree, RTreeObject}; /// Spaces with fewer entities than this are scanned directly (building an index costs more). pub const MIN_INDEXED: usize = 256; @@ -39,6 +39,21 @@ struct ChunkIx { bounds: Vec, /// Local indices of xlines and rays (unbounded; always candidates for pick and crossing). infinite: Vec, + /// The union of the chunk's tree items (`None` when none is bounded): [`TopDown`] skips a + /// chunk whose union misses the query. + envelope: Option>, +} + +/// The tree envelope of an entity's bounds, as [`ChunkIx::items`] stores it (`None` when empty). +fn rect(b: &Bounds2) -> Option> { + (!b.is_empty()).then(|| Rectangle::from_corners([b.min.x, b.min.y], [b.max.x, b.max.y]).envelope()) +} + +/// Whether the tree item for bounds `b` touches `env`, by the tree's own (closed) intersection +/// test, without building the item. +fn touches(b: &Bounds2, env: &AABB<[f64; 2]>) -> bool { + let (lo, hi) = (env.lower(), env.upper()); + !b.is_empty() && b.min.x <= hi[0] && b.max.x >= lo[0] && b.min.y <= hi[1] && b.max.y >= lo[1] } impl ChunkIx { @@ -56,9 +71,10 @@ impl ChunkIx { let b = entity_bounds_cached(d, e, 0, &mut cache); crate::select::pick_bounds(d, e, b) }) - .collect(); + .collect::>(); + let envelope = bounds.iter().filter_map(rect).reduce(|a, b| a.merged(&b)); let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - ChunkIx { serial, key, ents: items.to_vec(), bounds, infinite } + ChunkIx { serial, key, ents: items.to_vec(), bounds, infinite, envelope } } fn items(&self) -> impl Iterator + '_ { self.bounds.iter().enumerate().filter(|(_, b)| !b.is_empty()).map(|(i, b)| { @@ -74,6 +90,8 @@ pub struct SpatialIndex { blocks: BTreeMap>, dim_styles: Vec, dimscale: f64, + /// ATTMODE: a block reference takes room for the constant attribute values it shows. + attmode: i64, /// Annotation scale factor and ANNOALLVISIBLE: annotative objects measure at that scale. anno: (u64, bool), /// Layers turned off or frozen: block contents on them take no room in their inserts. @@ -126,7 +144,7 @@ impl SpatialIndex { } /// Build, reusing `prev` for chunks the two stores share (only when the bounds context — - /// blocks, dimension styles, DIMSCALE, hidden layers — is the same). + /// blocks, dimension styles, DIMSCALE, ATTMODE, hidden layers — is the same). fn build_from(d: &Drawing, store: &EntityStore, prev: Option<&SpatialIndex>) -> SpatialIndex { let prev = prev.filter(|p| p.same_context(d)); let old: std::collections::HashMap> = @@ -164,6 +182,7 @@ impl SpatialIndex { blocks: (*d.blocks).clone(), dim_styles: d.dim_styles.to_vec(), dimscale: d.header.f64("DIMSCALE", 1.0), + attmode: d.header.i64("ATTMODE", 1), anno: anno_key(d), hidden_layers: hidden_layers(d).map(str::to_owned).collect(), chunks, @@ -178,6 +197,7 @@ impl SpatialIndex { self.blocks.len() == d.blocks.len() && self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b)) && self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits() + && self.attmode == d.header.i64("ATTMODE", 1) && self.dim_styles == *d.dim_styles && self.anno == anno_key(d) && self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d)) @@ -211,23 +231,120 @@ impl SpatialIndex { /// Draw indices (ascending) of entities whose bounds touch `b`, optionally with the infinite /// lines. Returns `None` for a non-finite query box (callers fall back to a full scan). pub fn query(&self, b: &Bounds2, with_infinite: bool) -> Option> { + self.query_at_most(b, with_infinite, usize::MAX).map(Option::unwrap_or_default) + } + + /// [`Self::query`], giving up (`Some(None)`) as soon as more than `cap` tree items touch `b`, + /// so a caller can choose another way to read a large result. + pub fn query_at_most(&self, b: &Bounds2, with_infinite: bool, cap: usize) -> Option>> { if b.is_empty() { - return Some(if with_infinite { self.infinite.clone() } else { Vec::new() }); + return Some(Some(if with_infinite { self.infinite.clone() } else { Vec::new() })); } - if !(b.min.is_finite() && b.max.is_finite()) { - return None; + let env = query_envelope(b)?; + let mut out: Vec = Vec::new(); + for it in self.tree.locate_in_envelope_intersecting(env) { + if out.len() >= cap { + return Some(None); + } + if let Some(off) = self.offsets.get(&it.data.0) { + out.push(off + it.data.1); + } } - // Pad a little so rounding in the callers' own predicates never loses a candidate. - let pad = (b.width() + b.height()) * 1e-9 + (b.min.x.abs() + b.min.y.abs() + b.max.x.abs() + b.max.y.abs()) * 1e-12 + 1e-300; - let env = AABB::from_corners([b.min.x - pad, b.min.y - pad], [b.max.x + pad, b.max.y + pad]); - let mut out: Vec = - self.tree.locate_in_envelope_intersecting(env).filter_map(|it| self.offsets.get(&it.data.0).map(|off| off + it.data.1)).collect(); if with_infinite { out.extend_from_slice(&self.infinite); } out.sort_unstable(); out.dedup(); - Some(out) + Some(Some(out)) + } + + /// The entities [`Self::query`] finds for `b`, topmost (highest draw index) first, read from + /// the chunks from the last one down instead of collected from the tree and sorted, examining + /// at most `budget` entities. A pick wants only the topmost hit: when the drawing is shown + /// small, its aperture covers most of it and the tree returns nearly every entity on each + /// pointer move, while the topmost hit is usually among the first few examined here. `None` + /// for an empty or non-finite box (callers use `query`'s own handling of those). + pub fn top_down(&self, b: &Bounds2, with_infinite: bool, budget: usize) -> Option> { + if b.is_empty() { + return None; + } + let env = query_envelope(b)?; + let len = u32::try_from(self.len).unwrap_or(u32::MAX); + Some(TopDown { ix: self, env, infinite: with_infinite, next_chunk: self.chunks.len(), cur: None, floor: len, budget }) + } +} + +/// The padded tree envelope [`SpatialIndex::query`] searches for `b`; `None` when `b` isn't finite. +fn query_envelope(b: &Bounds2) -> Option> { + if !(b.min.is_finite() && b.max.is_finite()) { + return None; + } + // Pad a little so rounding in the callers' own predicates never loses a candidate. + let pad = (b.width() + b.height()) * 1e-9 + (b.min.x.abs() + b.min.y.abs() + b.max.x.abs() + b.max.y.abs()) * 1e-12 + 1e-300; + Some(AABB::from_corners([b.min.x - pad, b.min.y - pad], [b.max.x + pad, b.max.y + pad])) +} + +/// Candidates of a query box, topmost first, with their draw index and bounds (see +/// [`SpatialIndex::top_down`]). It stops when every entity is examined or the budget runs out; +/// [`TopDown::floor`] then says where the rest of the candidates begin. +pub struct TopDown<'a> { + ix: &'a SpatialIndex, + env: AABB<[f64; 2]>, + infinite: bool, + /// Chunks not entered yet: `chunks[..next_chunk]`. + next_chunk: usize, + /// The chunk being read and how many of its entities are left to examine. + cur: Option<(usize, usize)>, + /// Every entity at or above this draw index has been examined. + floor: u32, + budget: usize, +} + +impl TopDown<'_> { + /// The draw index below which nothing has been examined: candidates still to test are the + /// ones [`SpatialIndex::query`] returns below it. 0 once every entity has been examined. + pub fn floor(&self) -> u32 { + self.floor + } +} + +impl<'a> Iterator for TopDown<'a> { + type Item = (u32, &'a Arc, Bounds2); + + fn next(&mut self) -> Option { + let ix = self.ix; + loop { + if let Some((c, left)) = self.cur + && left > 0 + { + if self.budget == 0 { + return None; + } + self.budget -= 1; + let local = left - 1; + self.cur = Some((c, local)); + let (off, chunk) = ix.chunks.get(c)?; + let i = off.saturating_add(u32::try_from(local).unwrap_or(u32::MAX)); + self.floor = i; + let e = chunk.ents.get(local)?; + let b = chunk.bounds.get(local).copied().unwrap_or(Bounds2::EMPTY); + let touches = touches(&b, &self.env); + if touches || (self.infinite && matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))) { + return Some((i, e, b)); + } + continue; + } + let c = self.next_chunk.checked_sub(1)?; + self.next_chunk = c; + let (off, chunk) = ix.chunks.get(c)?; + let touches = chunk.envelope.is_some_and(|r| r.intersects(&self.env)) || (self.infinite && !chunk.infinite.is_empty()); + if touches { + self.cur = Some((c, chunk.ents.len())); + } else { + self.cur = None; + self.floor = *off; + } + } } } @@ -311,7 +428,9 @@ mod tests { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, + xref_stamp: None, }; blk.entities .push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 }))); @@ -353,6 +472,8 @@ mod tests { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), 6 => EntityKind::Point(cadcraft_doc::Point { p: v3(x, y), angle: 0.0 }), 7 => EntityKind::Insert(Insert { @@ -434,6 +555,91 @@ mod tests { } } + /// A drawing added in spatial order (rows of short lines), so most chunks cover a small area. + fn rows(n: usize) -> Drawing { + let mut d = Drawing::new_imperial(); + for i in 0..n { + let (x, y) = ((i % 100) as f64, (i / 100) as f64); + d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: v3(x, y), b: v3(x + 0.6, y + 0.3) })).unwrap(); + } + d + } + + /// Reading candidates topmost first from the chunks finds exactly what the tree finds, in + /// reverse draw order, and `floor` marks where an interrupted read stopped. + #[test] + fn top_down_matches_query_in_reverse() { + for d in [drawing(13, 3000), rows(5000)] { + let ix = SpatialIndex::build(&d, &d.model); + assert!(ix.chunks.len() > 2, "test needs several chunks ({})", ix.chunks.len()); + let mut r = Rng(77); + for k in 0..60 { + let c = Vec2::new(r.r(-10.0, 110.0), r.r(-10.0, 110.0)); + let half = [0.2, 3.0, 40.0, 500.0][k % 4]; + let b = Bounds2::new(c, c).expand(half); + let all: Vec = ix.query(&b, true).unwrap().into_iter().rev().collect(); + let got: Vec = ix.top_down(&b, true, usize::MAX).unwrap().map(|(i, _, _)| i).collect(); + assert_eq!(got, all, "box {b:?}"); + for budget in [0, 1, 37, 1500] { + let mut top = ix.top_down(&b, true, budget).unwrap(); + let seen: Vec = top.by_ref().map(|(i, _, _)| i).collect(); + let floor = top.floor(); + let mut joined = seen; + joined.extend(all.iter().copied().filter(|i| *i < floor)); + assert_eq!(joined, all, "box {b:?} budget {budget}"); + } + } + } + } + + /// Picks with any sorting limit and top-down budget, including apertures covering most of the drawing (a + /// drawing shown small), match the scan without an index. + #[test] + fn pick_parity_with_scan_at_every_budget() { + for d in [drawing(29, 3000), rows(5000)] { + let ix = forced(&d); + let mut r = Rng(31); + let mut hits = 0; + for k in 0..240 { + let p = Vec2::new(r.r(-5.0, 105.0), r.r(-5.0, 105.0)); + let ap = [0.05, 0.3, 1.5, 30.0][k % 4]; + let want = select::pick_with(&d, &Space::Model, &None, &[], p, ap); + for (sorted_max, budget) in [(0, 0), (0, 1), (0, 50), (0, usize::MAX), (3, 7), (1024, 4096), (usize::MAX, 0)] { + let got = select::pick_scanning(&d, &Space::Model, &ix, &[], p, ap, sorted_max, budget); + assert_eq!(got, want, "p {p:?} ap {ap} sorted_max {sorted_max} budget {budget}"); + } + hits += usize::from(want.is_some()); + } + assert!(hits > 40, "test should exercise hits ({hits})"); + } + } + + /// Past 1,024 candidates a pick through a viewport skips the layers frozen there, both where + /// it reads the index topmost first and where it sorts the candidates below those it read. + #[test] + fn a_frozen_layer_is_skipped_on_the_topmost_first_path() { + let mut d = Drawing::new_imperial(); + d.ensure_layer("FROZEN"); + let mut handles = Vec::new(); + for i in 0..2000 { + let common = if i >= 1990 { Common { layer: "FROZEN".into(), ..Common::default() } } else { Common::default() }; + let y = f64::from(i) * 1e-4; + handles.push(d.add(&Space::Model, common, EntityKind::Line(cadcraft_doc::Line { a: v3(0.0, y), b: v3(10.0, y) })).unwrap()); + } + let (topmost, shown) = (handles[1999], handles[1989]); + let ix = forced(&d); + let (p, ap) = (Vec2::new(5.0, 0.1), 0.5); + let query = Bounds2::new(p, p).expand(2.0 * ap); + assert!(matches!(ix.as_ref().unwrap().query_at_most(&query, true, 1024), Some(None)), "test needs more than 1024 candidates"); + let frozen = ["frozen".to_string()]; + assert_eq!(select::pick_with(&d, &Space::Model, &ix, &[], p, ap), Some(topmost)); + assert_eq!(select::pick_with(&d, &Space::Model, &ix, &frozen, p, ap), Some(shown), "topmost-first read"); + assert_eq!(select::pick_with(&d, &Space::Model, &None, &frozen, p, ap), Some(shown), "no index"); + for budget in [0, 1, 3, 9] { + assert_eq!(select::pick_scanning(&d, &Space::Model, &ix, &frozen, p, ap, 1024, budget), Some(shown), "below the floor, budget {budget}"); + } + } + #[test] fn window_and_fence_parity_with_scan() { for seed in [5, 23] { @@ -570,6 +776,76 @@ mod tests { assert_eq!(select::select_window(&d, &Space::Model, small, false), vec![h]); } + /// ATTMODE decides whether a reference shows its block's constant attribute values, and so + /// whether they take room in its bounds, without touching the space or the block table: the + /// index must not be reused across a change of it. + #[test] + fn index_follows_attmode_for_constant_attribute_values() { + let mut d = Drawing::new_imperial(); + let mut blk = (**drawing(1, 0).blocks.get("B").unwrap()).clone(); + let text = cadcraft_doc::Text { + insert: v3(0.0, 500.0), + align_pt: None, + height: 1.0, + value: "C4".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + backwards: false, + upside_down: false, + }; + let def = cadcraft_doc::Attrib { + tag: "C".into(), + text, + invisible: false, + constant: true, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }; + blk.entities.push(Entity { handle: cadcraft_doc::Handle(2_000_000), common: Common::default(), kind: EntityKind::AttDef(def) }); + d.blocks.insert("B".into(), Arc::new(blk)); + for i in 0..MIN_INDEXED { + let x = 1000.0 + i as f64; + d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: v3(x, 0.0), b: v3(x, 1.0) })).unwrap(); + } + let insert = Insert { + block: "B".into(), + insert: v3(0.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap(); + d.header.set_i64("ATTMODE", 0); + let hidden = SpatialIndex::build(&d, &d.model); + + d.header.set_i64("ATTMODE", 1); + assert!(!hidden.matches(&d, &d.model)); + let reused = SpatialIndex::build_from(&d, &d.model, Some(&hidden)); + let fresh = SpatialIndex::build(&d, &d.model); + let last = u32::try_from(MIN_INDEXED).unwrap(); + assert_eq!(reused.bounds(last), fresh.bounds(last)); + assert_ne!(fresh.bounds(last), hidden.bounds(last), "the value shown at ATTMODE 1 takes room"); + + // The top-down picker skips a chunk whose cached envelope misses the query: a box at the + // value, far above everything else, must reach the reference through the reused index. + let at_value = Bounds2::new(Vec2::new(-1.0, 499.0), Vec2::new(3.0, 502.0)); + let top = |ix: &SpatialIndex| ix.top_down(&at_value, false, usize::MAX).unwrap().map(|(i, _, _)| i).collect::>(); + assert_eq!(top(&reused), vec![last], "the reference is found at its value"); + assert_eq!(top(&reused), top(&fresh)); + assert_eq!(Some(top(&reused)), reused.query(&at_value, false), "as the tree finds it"); + assert!(top(&hidden).is_empty(), "nothing is there while the value is hidden"); + } #[test] fn small_spaces_are_scanned() { let d = drawing(1, MIN_INDEXED - 1); diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index a491fb7d8..7b3cd2389 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use crate::{EngineError, Result, Session}; +use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale}; mod table; @@ -11,6 +12,8 @@ const SESSION_VARS: &[&str] = &[ "ATTREQ", "OSMODE", "OSNAPHATCH", + "HPSPACE", + "HPDOUBLE", "ANNOAUTOSCALE", "ORTHOMODE", "POLARMODE", @@ -62,6 +65,7 @@ const SESSION_VARS: &[&str] = &[ "COPYMODE", "PICKDRAG", "PICKSTYLE", + "GROUPDISPLAYMODE", "GRIPSIZE", "CURSORSIZE", "MAXARRAY", @@ -84,6 +88,8 @@ pub fn get(s: &Session, name: &str) -> Option { let v = match n.as_str() { "OSMODE" => json!(st.osmode), "OSNAPHATCH" => json!(i32::from(st.osnaphatch)), + "HPSPACE" => json!(s.last_used.hatch_spacing), + "HPDOUBLE" => json!(i32::from(s.last_used.hatch_double)), // AutoCAD's values: positive on, negative off (4 = every annotative object). "ANNOAUTOSCALE" => json!(if st.annoautoscale { 4 } else { -4 }), // Paper units per drawing unit of the current annotation scale (1:50 → 0.02). @@ -144,6 +150,7 @@ pub fn get(s: &Session, name: &str) -> Option { "COPYMODE" => json!(i32::from(st.copymode)), "PICKDRAG" => json!(i32::from(st.pickdrag) * 2), "PICKSTYLE" => json!(st.pickstyle), + "GROUPDISPLAYMODE" => json!(st.groupdisplaymode), "GRIPSIZE" => json!(st.gripsize), "CURSORSIZE" => json!(st.cursorsize), "MAXARRAY" => json!(st.maxarray), @@ -326,6 +333,13 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { // The `color` command's input: ByLayer, ByBlock, a name, an index or a true colour. "CECOLOR" => crate::cmd::set_current_color_value(s, v).ok_or_else(bad)?, "OSNAPHATCH" => st.osnaphatch = as_bool(v).ok_or_else(bad)?, + "HPSPACE" => { + s.last_used.hatch_spacing = as_f64(v).filter(|f| is_supported_hatch_pattern_scale(*f)).ok_or_else(|| EngineError::BadParams { + cmd: "setvar".into(), + msg: format!("HPSPACE must be greater than {MIN_HATCH_PATTERN_SCALE:e} drawing units"), + })?; + } + "HPDOUBLE" => s.last_used.hatch_double = table::int_value(v).filter(|i| (0..=1).contains(i)).ok_or_else(bad)? == 1, "ANNOAUTOSCALE" => st.annoautoscale = as_i(v).filter(|i| (-4..=4).contains(i)).ok_or_else(bad)? > 0, // A scale of the drawing's list; ANNOAUTOSCALE adds it to the annotative objects. "CANNOSCALE" => crate::cmd::annoscale::set_current(s, v.as_str().ok_or_else(bad)?)?, @@ -399,6 +413,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { "COPYMODE" => st.copymode = small(v, 1).ok_or_else(bad)? == 1, "PICKDRAG" => st.pickdrag = as_i(v).filter(|b| matches!(b, 0 | 2)).map(|b| b == 2).ok_or_else(bad)?, "PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?, + "GROUPDISPLAYMODE" => st.groupdisplaymode = small(v, 2).ok_or_else(bad)?, "GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0), "CURSORSIZE" => st.cursorsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 100.0), "MAXARRAY" => st.maxarray = as_f64(v).ok_or_else(bad)?.clamp(100.0, 10_000_000.0) as u64, diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index cab35c0b9..2795408d7 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -66,6 +66,8 @@ const HEADER: &[(&str, Kind, Def)] = &[ // Negative: Through (OFFSET picks a point). ("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)), ("OFFSETERASE", Kind::Choice(&[0, 1]), Def::Int(0)), + // 0: extend offset lines to meet at corners; 1: fill the gap with an arc; 2: with a chamfer. + ("OFFSETGAPTYPE", Kind::Choice(&[0, 1, 2]), Def::Int(0)), ("OFFSETLAYER", Kind::Choice(&[0, 1]), Def::Int(0)), // The width a new polyline starts at; PLINE's Width and Halfwidth answers set it. ("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)), @@ -83,6 +85,8 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), // XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted. ("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)), + // How much objects outside the working set fade while a reference is edited in place (REFEDIT). + ("XFADECTL", Kind::Int(0, 90), Def::Int(50)), ]; /// The standard lineweights in hundredths of a millimetre. @@ -140,7 +144,7 @@ pub(super) fn get(s: &Session, name: &str) -> Option { }) } -fn int_value(v: &Value) -> Option { +pub(super) fn int_value(v: &Value) -> Option { match v { Value::Number(n) => n.as_i64().or_else(|| n.as_f64().filter(|f| f.fract() == 0.0 && f.abs() < 1e15).map(|f| f as i64)), Value::Bool(b) => Some(i64::from(*b)), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c2b527021..2976c0125 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -532,6 +532,264 @@ fn scale_reference_typed_and_picked() { assert!(end(&s).near(Vec2::new(50.0, 0.0), 1e-9)); } +#[test] +fn scale_reference_points_and_copy() { + fn line_ends(s: &Session) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) => Some(l.b.xy()), + _ => None, + }) + .collect() + } + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + // Reference 10 via two points, then Points option with two points of length 30 -> (30, 0). + for t in ["scale", "all", "", "0,0", "r", "0,0", "10,0"] { + s.cmdline(t).unwrap(); + } + let p = s.current_prompt().unwrap(); + assert_eq!(p.message, "Specify new length"); + assert!(p.keywords.contains(&"Points".to_string())); + assert!(p.keywords.contains(&"Copy".to_string())); + s.cmdline("p").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify first point"); + s.cmdline("5,5").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify second point"); + s.cmdline("5,35").unwrap(); + assert!(s.running.is_none()); + assert!(line_ends(&s)[0].near(Vec2::new(30.0, 0.0), 1e-9)); + + // Coinciding Points are rejected without leaving the second-point prompt; a valid point completes. + for t in ["scale", "all", "", "0,0", "r", "30", "p", "5,5", "5,5"] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_some()); + assert_eq!(s.current_prompt().unwrap().message, "Specify second point"); + s.cmdline("5,25").unwrap(); + assert!(s.running.is_none()); + assert!(line_ends(&s)[0].near(Vec2::new(20.0, 0.0), 1e-9)); + + // Copy entered inside Reference mode before reference length keeps the original and adds a scaled copy. + for t in ["scale", "all", "", "0,0", "r", "c", "20", "40"] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_none()); + let ends = line_ends(&s); + assert_eq!(ends.len(), 2); + assert!(ends.iter().any(|p| p.near(Vec2::new(20.0, 0.0), 1e-9))); + assert!(ends.iter().any(|p| p.near(Vec2::new(40.0, 0.0), 1e-9))); + + // Copy entered at "Specify new length" combined with Points scales a copy. + for t in ["scale", "l", "", "0,0", "r", "40", "c", "p", "0,0", "10,0"] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_none()); + let ends = line_ends(&s); + assert_eq!(ends.len(), 3); + assert!(ends.iter().any(|p| p.near(Vec2::new(10.0, 0.0), 1e-9))); +} + +#[test] +fn hot_grip_scale_scales_heights_and_thickness() { + let mut s = Session::new(); + let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap(); + let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + let h2 = s + .doc_mut() + .unwrap() + .add( + &cadcraft_doc::Space::Model, + cadcraft_doc::Common::default(), + EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(10.0, 0.0, 5.0), b: cadcraft_geom::Vec3::new(15.0, 0.0, 8.0) }), + ) + .unwrap(); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + e.common.thickness = 3.0; + if let EntityKind::Text(t) = &mut e.kind { + t.insert.z = 5.0; + } + }) + .unwrap(); + s.set_selection(vec![h, h2]); + s.start_grip_edit(&[(h, 0)]).unwrap(); + // STRETCH -> MOVE -> ROTATE -> SCALE + for _ in 0..3 { + s.input(Input::Enter).unwrap(); + } + assert!(s.current_prompt().unwrap().message.contains("** SCALE **")); + s.cmdline("2").unwrap(); + assert!(s.running.is_none()); + let e = s.doc().unwrap().entity(h).unwrap(); + assert_eq!(e.common.thickness, 6.0); + let EntityKind::Text(t) = &e.kind else { panic!("expected text") }; + assert_eq!(t.height, 4.0); + // Selected grip is the SCALE base point and must remain stationary in all three coordinates. + assert!((t.insert.x - 10.0).abs() < 1e-9); + assert!(t.insert.y.abs() < 1e-9); + assert!((t.insert.z - 5.0).abs() < 1e-9); + + let EntityKind::Line(l) = &s.doc().unwrap().entity(h2).unwrap().kind else { panic!("expected line") }; + assert!((l.a.x - 10.0).abs() < 1e-9 && l.a.y.abs() < 1e-9 && (l.a.z - 5.0).abs() < 1e-9); + assert!((l.b.x - 20.0).abs() < 1e-9 && l.b.y.abs() < 1e-9 && (l.b.z - 11.0).abs() < 1e-9); + + // JSON `grip.scale` using `index` also keeps the selected grip stationary in 3D. + s.execute("grip.scale", &json!({"handles": [h.hex()], "index": 0, "factor": 0.5})).unwrap(); + let e = s.doc().unwrap().entity(h).unwrap(); + assert_eq!(e.common.thickness, 3.0); + let EntityKind::Text(t) = &e.kind else { panic!("expected text") }; + assert_eq!(t.height, 2.0); + assert!((t.insert.x - 10.0).abs() < 1e-9 && t.insert.y.abs() < 1e-9 && (t.insert.z - 5.0).abs() < 1e-9); +} + +#[test] +fn scale_reference_preview_and_drag() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + + // Plain SCALE preview and drag. + for t in ["scale", "all", "", "0,0"] { + s.cmdline(t).unwrap(); + } + assert_eq!(s.preview(Vec2::new(2.0, 0.0)).len(), 2); + let (d, extra) = s.drag(Vec2::new(2.0, 0.0)).unwrap(); + assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(20.0, 0.0), 1e-9)); + assert_eq!(extra.len(), 1); + + // Enter accepts default reference length 1.0, then drag/preview at new length, then Points option. + for t in ["r", ""] { + s.cmdline(t).unwrap(); + } + assert_eq!(s.current_prompt().unwrap().message, "Specify new length"); + let (d, extra) = s.drag(Vec2::new(3.0, 0.0)).unwrap(); + assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(30.0, 0.0), 1e-9)); + assert!(matches!(&extra[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::ZERO, 1e-9) && l.b.xy().near(Vec2::new(3.0, 0.0), 1e-9))); + assert_eq!(s.preview(Vec2::new(3.0, 0.0)).len(), 2); + + s.cmdline("p").unwrap(); + assert!(s.drag(Vec2::new(5.0, 0.0)).is_none()); + assert!(s.preview(Vec2::new(5.0, 0.0)).is_empty()); + s.cmdline("5,5").unwrap(); + let (d, extra) = s.drag(Vec2::new(5.0, 7.0)).unwrap(); + assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(20.0, 0.0), 1e-9)); + assert!(matches!(&extra[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::new(5.0, 5.0), 1e-9) && l.b.xy().near(Vec2::new(5.0, 7.0), 1e-9))); + assert_eq!(s.preview(Vec2::new(5.0, 7.0)).len(), 2); + s.cmdline("").unwrap(); + assert!(s.running.is_none()); +} + +#[test] +fn select_then_reference_cancel_and_previews() { + fn line_end(s: &Session) -> Vec2 { + let e = s.doc().unwrap().model.iter().next().unwrap(); + let EntityKind::Line(l) = &e.kind else { panic!("expected line") }; + l.b.xy() + } + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + + // Reference before length is given: no drag/preview; after first point, only rubber-band preview; Enter cancels. + for t in ["scale", "all", "", "0,0", "r"] { + s.cmdline(t).unwrap(); + } + assert!(s.drag(Vec2::new(5.0, 0.0)).is_none()); + assert!(s.preview(Vec2::new(5.0, 0.0)).is_empty()); + s.cmdline("0,0").unwrap(); + let pv = s.preview(Vec2::new(5.0, 0.0)); + assert_eq!(pv.len(), 1); + assert!(matches!(&pv[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::ZERO, 1e-9) && l.b.xy().near(Vec2::new(5.0, 0.0), 1e-9))); + assert!(s.drag(Vec2::new(5.0, 0.0)).is_none()); + s.cmdline("").unwrap(); + assert!(s.running.is_none()); + assert!(line_end(&s).near(Vec2::new(10.0, 0.0), 1e-9)); + + // COPY and ROTATE previews also emit transformed geometry plus rubber-band. + for cmd in ["copy", "rotate"] { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + for t in [cmd, "all", "", "0,0"] { + s.cmdline(t).unwrap(); + } + assert_eq!(s.preview(Vec2::new(4.0, 3.0)).len(), 2); + s.input(Input::Cancel).unwrap(); + } +} + +#[test] +fn hot_grip_scale_and_reference_point_picks() { + let mut s = Session::new(); + let rl = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let l = cadcraft_doc::Handle::parse_hex(rl["handles"][0].as_str().unwrap()).unwrap(); + let rt = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap(); + let t = cadcraft_doc::Handle::parse_hex(rt["handle"].as_str().unwrap()).unwrap(); + s.doc_mut().unwrap().modify_entity(t, |e| e.common.thickness = 3.0).unwrap(); + + // Hot-grip SCALE: coincident point is rejected; valid point scales line, text height, and thickness. + s.set_selection(vec![l, t]); + s.start_grip_edit(&[(l, 0)]).unwrap(); + for _ in 0..3 { + s.input(Input::Enter).unwrap(); + } + s.cmdline("0,0").unwrap(); + assert!(s.running.is_some()); + s.cmdline("2,0").unwrap(); + assert!(s.running.is_none()); + let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") }; + assert!(ln.b.xy().near(Vec2::new(20.0, 0.0), 1e-9)); + let te = s.doc().unwrap().entity(t).unwrap(); + assert_eq!(te.common.thickness, 6.0); + let EntityKind::Text(tx) = &te.kind else { panic!("expected text") }; + assert_eq!(tx.height, 4.0); + + // Hot-grip SCALE Reference: zero new length point is rejected; valid point scales back by 0.5. + s.set_selection(vec![l, t]); + s.start_grip_edit(&[(l, 0)]).unwrap(); + for _ in 0..3 { + s.input(Input::Enter).unwrap(); + } + for cmd in ["r", "20", "0,0"] { + s.cmdline(cmd).unwrap(); + } + assert!(s.running.is_some()); + s.cmdline("10,0").unwrap(); + assert!(s.running.is_none()); + let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") }; + assert!(ln.b.xy().near(Vec2::new(10.0, 0.0), 1e-9)); + let te = s.doc().unwrap().entity(t).unwrap(); + assert_eq!(te.common.thickness, 3.0); + let EntityKind::Text(tx) = &te.kind else { panic!("expected text") }; + assert_eq!(tx.height, 2.0); + + // Hot-grip ROTATE Reference with picked new-angle point. + s.set_selection(vec![l]); + s.start_grip_edit(&[(l, 0)]).unwrap(); + for _ in 0..2 { + s.input(Input::Enter).unwrap(); + } + for cmd in ["r", "0", "0,10"] { + s.cmdline(cmd).unwrap(); + } + assert!(s.running.is_none()); + let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") }; + assert!(ln.b.xy().near(Vec2::new(0.0, 10.0), 1e-9)); + + // Hot-grip MIRROR with coincident point is rejected; eXit ends cleanly. + s.set_selection(vec![l]); + s.start_grip_edit(&[(l, 0)]).unwrap(); + for _ in 0..4 { + s.input(Input::Enter).unwrap(); + } + s.cmdline("0,0").unwrap(); + assert!(s.running.is_some()); + s.cmdline("x").unwrap(); + assert!(s.running.is_none()); +} + #[test] fn layers_and_properties() { let mut s = Session::new(); diff --git a/crates/engine/tests/audit.rs b/crates/engine/tests/audit.rs index f3d046b7c..de997c39a 100644 --- a/crates/engine/tests/audit.rs +++ b/crates/engine/tests/audit.rs @@ -68,6 +68,8 @@ fn corrupt(d: &mut Drawing) -> (Handle, Handle) { style: "Vanished".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), ); raw(d, &Space::Model, on("0"), insert("Nowhere")); @@ -224,6 +226,54 @@ fn audit_at_the_command_line_asks_before_fixing() { assert_eq!(s.execute("audit", &json!({})).unwrap()["errors"], 0); } +/// Many multileaders and tables naming styles the drawing lacks, among many styles, are audited in +/// linear time (#1924). As before, each is set to Standard, and one naming a style in other case is +/// left as it is. The names share their first 200 bytes, so comparing two costs about that. +#[test] +fn many_objects_naming_missing_styles_audit_quickly() { + use cadcraft_engine::doc::{MLeader, MLeaderStyle, Table, TableStyle}; + const N: usize = 10_000; + let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199)); + let missing = |kind: char| format!("{kind}{}z{:05}", "x".repeat(199), 0); + let mleader = |style: String| { + EntityKind::MLeader(MLeader { + leaders: vec![vec![Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)]], + landing: Vec3::new(2.0, 1.0, 0.0), + dogleg: 0.5, + text: None, + style, + arrow_size: 1.0, + spline: false, + block: None, + }) + }; + let table = |style: String| EntityKind::Table(Table { style, ..Table::default() }); + let mut d = Drawing::new_imperial(); + d.mleader_styles.extend((0..N).map(|i| MLeaderStyle { name: name('M', i), ..MLeaderStyle::default() })); + d.table_styles.extend((0..N).map(|i| TableStyle { name: name('T', i), ..TableStyle::default() })); + for _ in 0..N { + raw(&mut d, &Space::Model, Common::default(), mleader(missing('M'))); + raw(&mut d, &Space::Model, Common::default(), table(missing('T'))); + } + raw(&mut d, &Space::Model, Common::default(), mleader(name('M', N - 1).to_ascii_uppercase())); + raw(&mut d, &Space::Model, Common::default(), table(name('T', N - 1).to_ascii_uppercase())); + let started = std::time::Instant::now(); + cadcraft_engine::audit::repair(&mut d); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + let styles: Vec<&str> = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::MLeader(m) => Some(m.style.as_str()), + EntityKind::Table(t) => Some(t.style.as_str()), + _ => None, + }) + .collect(); + assert_eq!(styles.len(), 2 * N + 2); + assert!(styles[..2 * N].iter().all(|s| *s == "Standard"), "a missing style is set to Standard"); + assert_eq!(styles[2 * N..], [name('M', N - 1).to_ascii_uppercase(), name('T', N - 1).to_ascii_uppercase()]); +} + #[test] fn missing_standard_entries_and_layer_zero_are_recreated() { let mut s = Session::new(); diff --git a/crates/engine/tests/drawing_lock.rs b/crates/engine/tests/drawing_lock.rs new file mode 100644 index 000000000..0c41c6f12 --- /dev/null +++ b/crates/engine/tests/drawing_lock.rs @@ -0,0 +1,107 @@ +//! Drawing locks (#540): an app with a drawing open keeps a lock beside it; another app opening +//! the same drawing is told who has it, without taking the lock; the lock goes when the drawing +//! closes, and a stale one is taken over. + +use std::time::{Duration, SystemTime}; + +use cadcraft_engine::Session; +use cadcraft_engine::autosave::{self, Autosaver}; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::drawlock::{Locks, holder, lock_path}; +use serde_json::json; + +fn session_with(path: &str) -> Session { + set_io(IoHooks { + read: |b, n| cadcraft_io::read(b, n).map_err(|e| e.to_string()), + write: |d, n| cadcraft_io::write(d, n).map_err(|e| e.to_string()), + plot: None, + }); + let mut s = Session::new(); + s.execute("open", &json!({ "path": path })).unwrap(); + s +} + +#[test] +fn a_second_app_is_told_who_has_the_drawing_and_the_lock_follows_the_first() { + let dir = std::env::temp_dir().join(format!("cadcraft-lock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Shared Plan.dxf"); + std::fs::write(&file, cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_metric(), "x.dxf").unwrap()).unwrap(); + let path = file.to_string_lossy().to_string(); + let now = Duration::ZERO; + + let mut a = session_with(&path); + let mut la = Locks::with_heartbeat(now); + la.sync(&a, "1-a"); + assert!(lock_path(&file).file_name().unwrap().to_string_lossy().starts_with(".Shared Plan.dxf")); + assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string())); + assert!(la.take_notes().is_empty()); + + // A second app opening it is told, and the lock stays the first app's. + let b = session_with(&path); + let mut lb = Locks::with_heartbeat(now); + lb.sync(&b, "2-b"); + let notes = lb.take_notes(); + assert_eq!(notes.len(), 1, "{notes:?}"); + assert!(notes[0].starts_with("Shared Plan.dxf is also open by ") && notes[0].contains("UTC"), "{}", notes[0]); + lb.sync(&b, "2-b"); + assert!(lb.take_notes().is_empty(), "said once"); + assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string())); + // WHOHAS names the holder. + let mut b = b; + // A `path` that isn't a file path is refused, not taken as the current drawing. + assert!(b.execute("whohas", &json!({ "path": 7 })).is_err()); + let r = b.execute("whohas", &json!({})).unwrap(); + assert_eq!(r["holder"]["instance"], "1-a"); + + // Releasing what isn't ours leaves it alone. + lb.release_all("2-b"); + assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string())); + + // The first app closes the drawing: its lock goes, and the second takes it. + a.execute("close", &json!({})).unwrap(); + la.sync(&a, "1-a"); + assert!(holder(&file).is_none()); + lb.sync(&b, "2-b"); + assert_eq!(holder(&file).map(|h| h.instance), Some("2-b".to_string())); + + // A lock left by a crashed app (not touched for a while) is taken over without a note. + let stale = SystemTime::now() - Duration::from_secs(cadcraft_engine::drawlock::STALE_SECS + 60); + std::fs::OpenOptions::new().write(true).open(lock_path(&file)).unwrap().set_modified(stale).unwrap(); + assert!(holder(&file).is_none(), "stale"); + let c = session_with(&path); + let mut lc = Locks::with_heartbeat(now); + lc.sync(&c, "3-c"); + assert!(lc.take_notes().is_empty()); + assert_eq!(holder(&file).map(|h| h.instance), Some("3-c".to_string())); + // The app whose lock was taken over notices on its next heartbeat and doesn't touch it. + lb.sync(&b, "2-b"); + assert_eq!(lb.take_notes().len(), 1, "told who has it now"); + assert_eq!(holder(&file).map(|h| h.instance), Some("3-c".to_string())); + lc.release_all("3-c"); + assert!(!lock_path(&file).exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An idle app with every drawing saved (and SAVETIME 0) still wakes up for the lock heartbeat: +/// otherwise its lock goes stale and another app takes the drawing over without a word. +#[test] +fn an_idle_app_wakes_up_for_the_lock_heartbeat() { + let dir = std::env::temp_dir().join(format!("cadcraft-lock-idle-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Saved Plan.dxf"); + std::fs::write(&file, cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_metric(), "x.dxf").unwrap()).unwrap(); + let s = session_with(&file.to_string_lossy()); + assert!(!s.docs.iter().any(|d| d.is_dirty()), "nothing to autosave"); + autosave::set_savetime(0); + let beat = Duration::from_secs(2); + let mut a = Autosaver::new("1-idle").with_locks(Locks::with_heartbeat(beat)); + let wait = a.tick(&s); + assert_eq!(holder(&file).map(|h| h.instance), Some("1-idle".to_string())); + assert!(wait.is_some_and(|d| d <= beat), "{wait:?}"); + a.shutdown(); + assert!(!lock_path(&file).exists()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/export_version_real.rs b/crates/engine/tests/export_version_real.rs new file mode 100644 index 000000000..36143d9c0 --- /dev/null +++ b/crates/engine/tests/export_version_real.rs @@ -0,0 +1,109 @@ +//! #3213, with the real DXF and DWG readers and writers: a drawing read from a 2013 DXF (AC1027) +//! exported or saved as a 2000 DXF or DWG says AC1015, and a plain export keeps the drawing's own +//! version. +//! +//! In its own test binary, not `tests/it`, because it installs the real io hooks. The hooks are +//! process-wide and set once (`set_io` and `set_write_as` keep the first value), so in `tests/it` +//! they would change what the other tests' saves, exports and opens do, by test order. They also +//! cannot share a binary with `save_version.rs`, whose stub writer must be the one installed. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, base64_decode, set_io, set_write_as}; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +fn install() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + 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()) + }); +} + +/// The `$ACADVER` an exported DXF declares. +fn acadver(r: &serde_json::Value) -> String { + header_version(&String::from_utf8(base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap()) +} + +/// The version a DWG file's bytes open with ("AC1015" for 2000). +fn dwg_version(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes.get(..6).unwrap_or_default()).into_owned() +} + +/// The radii of the circles in the active drawing. +fn radii(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }).collect() +} + +/// The `$ACADVER` in the header of the DXF text `text`. +fn header_version(text: &str) -> String { + let mut lines = text.lines().map(str::trim); + while let Some(l) = lines.next() { + if l == "$ACADVER" { + lines.next(); + return lines.next().unwrap_or_default().to_string(); + } + } + String::new() +} + +#[test] +fn a_2013_drawing_exports_as_a_2000_dxf() { + install(); + // Removed when the test ends, even when an assertion fails. + let dir = TempDir::new("export-version"); + let file = dir.path_str("plan.dxf"); + let mut s = Session::new(); + s.cmdline("circle 0,0 5").unwrap(); + s.execute("saveas", &json!({ "path": file, "version": "2013" })).unwrap(); + s.execute("open", &json!({ "path": file })).unwrap(); + + assert_eq!(acadver(&s.execute("export", &json!({ "format": "dxf" })).unwrap()), "AC1027"); + assert_eq!(acadver(&s.execute("export", &json!({ "format": "dxf", "version": "2000" })).unwrap()), "AC1015"); +} + +#[test] +fn a_2013_drawing_saved_as_2000_says_ac1015() { + install(); + let dir = TempDir::new("saveas-version"); + let (file, copy) = (dir.path_str("plan.dxf"), dir.path_str("plan-2000.dxf")); + let mut s = Session::new(); + s.cmdline("circle 0,0 5").unwrap(); + s.execute("saveas", &json!({ "path": file, "version": "2013" })).unwrap(); + s.execute("open", &json!({ "path": file })).unwrap(); + + s.execute("saveas", &json!({ "path": copy, "version": "2000" })).unwrap(); + assert_eq!(header_version(&std::fs::read_to_string(©).unwrap()), "AC1015"); +} + +/// The DWG writer itself writes the chosen version: the file opens with AC1015, not the 2013 +/// drawing's AC1027, and reads back with its circle. +#[test] +fn a_2013_drawing_exports_and_saves_as_a_2000_dwg() { + install(); + // The drawing is the test's own, so the DWG conversion may run in this process. + cadcraft_io::dwg_worker::allow_in_process(); + let dir = TempDir::new("dwg-version"); + let (file, copy) = (dir.path_str("plan.dxf"), dir.path_str("plan-2000.dwg")); + let mut s = Session::new(); + s.cmdline("circle 0,0 5").unwrap(); + s.execute("saveas", &json!({ "path": file, "version": "2013" })).unwrap(); + s.execute("open", &json!({ "path": file })).unwrap(); + + let exported = |s: &mut Session, p: serde_json::Value| base64_decode(s.execute("export", &p).unwrap()["data"].as_str().unwrap()).unwrap(); + assert_eq!(dwg_version(&exported(&mut s, json!({ "format": "dwg" }))), "AC1027"); + assert_eq!(dwg_version(&exported(&mut s, json!({ "format": "dwg", "version": "2000" }))), "AC1015"); + + s.execute("saveas", &json!({ "path": copy, "version": "2000" })).unwrap(); + assert_eq!(dwg_version(&std::fs::read(©).unwrap()), "AC1015"); + s.execute("open", &json!({ "path": copy })).unwrap(); + assert_eq!(radii(&s), [5.0]); +} diff --git a/crates/engine/tests/insert_file.rs b/crates/engine/tests/insert_file.rs index 23e5d5581..839694000 100644 --- a/crates/engine/tests/insert_file.rs +++ b/crates/engine/tests/insert_file.rs @@ -150,6 +150,29 @@ fn a_drawing_file_becomes_a_block_with_its_insbase_and_tables() { assert_eq!(inserts(&s).len(), n); } +#[test] +fn expert_two_or_more_redefines_a_file_block_without_asking() { + // #2995: with EXPERT 2 or more the "already exists. Redefine it?" question is not asked; it + // is answered Yes, so the next INSERT of the same file finishes and the block is redefined + // from the file as it is now. + hooks(); + let dir = TempDir::new("insert-file-expert"); + let bolt = dir.file("bolt.dxf", "10,10"); + let mut s = Session::new(); + s.script(&format!("-INSERT {bolt} 0,0 1 1 0\n")).unwrap(); + s.execute("setvar", &json!({ "name": "EXPERT", "value": 2 })).unwrap(); + dir.file("bolt.dxf", "0,0"); + s.script(&format!("-INSERT {bolt} 20,0 1 1 0\n")).unwrap(); + assert!(s.running.is_none(), "INSERT finished: {}", s.prompt_text()); + assert_eq!(inserts(&s).len(), 2); + assert_eq!(s.doc().unwrap().block("bolt").unwrap().base, Vec3::ZERO, "redefined from the file"); + + // EXPERT 1 still asks. + s.execute("setvar", &json!({ "name": "EXPERT", "value": 1 })).unwrap(); + s.cmdline(&format!("-INSERT {bolt}")).unwrap(); + assert!(s.prompt_text().contains("Redefine"), "{}", s.prompt_text()); +} + #[test] fn exploded_json_insert_is_one_undo_step() { for params in [json!({ "name": "*B", "at": [5, 5] }), json!({ "name": "B", "at": [5, 5], "explode": true })] { diff --git a/crates/engine/tests/insert_file_field.rs b/crates/engine/tests/insert_file_field.rs index 1365f88b5..c49499602 100644 --- a/crates/engine/tests/insert_file_field.rs +++ b/crates/engine/tests/insert_file_field.rs @@ -41,6 +41,8 @@ fn read(bytes: &[u8], _name: &str) -> Result { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; let def = Attrib { tag: "NUMBER".into(), diff --git a/crates/engine/tests/it/attedit_prompts.rs b/crates/engine/tests/it/attedit_prompts.rs index 1739a7365..7d3122dcc 100644 --- a/crates/engine/tests/it/attedit_prompts.rs +++ b/crates/engine/tests/it/attedit_prompts.rs @@ -118,6 +118,80 @@ fn attribute_tags_match_in_any_case_and_unknown_tags_are_reported() { assert_eq!(r, json!({"changed": 1})); } +#[test] +fn attedit_takes_a_selected_block_reference_at_once() { + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({}))); + s.set_selection(vec![h]); + s.cmdline("attedit").unwrap(); + assert!(s.prompt_text().contains("Enter value for T "), "{}", s.prompt_text()); + type_lines(&mut s, &["picked", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!((value(&s, h, "T"), value(&s, h, "U")), ("picked".into(), "u".into())); +} + +#[test] +fn attedit_leaves_constant_attributes_and_locked_references_alone() { + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({}))); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.attribs[1].constant = true; + } + }) + .unwrap(); + let rows = cadcraft_engine::attributes(s.doc().unwrap(), h); + assert_eq!(rows.iter().map(|r| (r.tag.as_str(), r.editable)).collect::>(), [("T", true), ("U", false)]); + + let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "t2", "U": "u2"}})).unwrap(); + assert_eq!((r["changed"].clone(), r["constantTags"].clone()), (json!(1), json!(["U"]))); + assert_eq!((value(&s, h, "T"), value(&s, h, "U")), ("t2".into(), "u".into())); + // One undo step. + s.undo().unwrap(); + assert_eq!(value(&s, h, "T"), "one"); + + // Not a block reference, a value too long, a locked layer. + let line = s.execute("line", &json!({"points": [[0, 50], [10, 50]]})).unwrap()["handles"][0].clone(); + assert!(s.execute("attedit", &json!({"handle": line, "values": {"T": "x"}})).is_err()); + assert!(s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "x".repeat(70_000)}})).is_err()); + s.execute("layer.set", &json!({"name": "0", "locked": true})).unwrap(); + let e = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "x"}})).unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(value(&s, h, "T"), "one"); +} + +#[test] +fn attedit_at_changes_one_of_two_attributes_sharing_a_tag() { + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({}))); + // As a DXF reference may carry them: the second attribute's tag is T too. + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.attribs[1].tag = "T".into(); + } + }) + .unwrap(); + let values = |s: &Session| -> Vec { + let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") }; + i.attribs.iter().map(|a| a.text.value.clone()).collect() + }; + let r = s.execute("attedit", &json!({"handle": h.hex(), "at": {"1": "second"}})).unwrap(); + assert_eq!(r, json!({"changed": 1})); + assert_eq!(values(&s), ["one", "second"]); + // By tag, every attribute with it, as before. + s.execute("attedit", &json!({"handle": h.hex(), "values": {"t": "both"}})).unwrap(); + assert_eq!(values(&s), ["both", "both"]); + // Hostile places are refused and change nothing. + for at in [json!({"2": "x"}), json!({"-1": "x"}), json!({"one": "x"}), json!({"0": [1]}), json!([1]), json!({"18446744073709551616": "x"})] { + assert!(s.execute("attedit", &json!({"handle": h.hex(), "at": at})).is_err(), "{at}"); + } + assert_eq!(values(&s), ["both", "both"]); +} + /// -ATTEDIT Position moves an aligned or fit attribute without losing its baseline: both of its /// points move by the same offset (setting both to the picked point would leave no direction or /// length to fit the text between). @@ -230,6 +304,7 @@ fn dash_attedit_edits_a_multiline_attributes_text() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; set_t(&mut s, h, |a| a.multiline = Some(MultilineAttrib { mtext: mtext.clone(), read_as: "abc".into() })); let before = attrib_t(&s, h).text.insert; @@ -263,6 +338,7 @@ fn dash_attedit_defaults_of_a_multiline_attribute_come_from_its_multiline_text() line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; set_t(&mut s, h, |a| { a.text.height = 1.25; diff --git a/crates/engine/tests/it/attrib_modes.rs b/crates/engine/tests/it/attrib_modes.rs index 260f842c9..7401a221d 100644 --- a/crates/engine/tests/it/attrib_modes.rs +++ b/crates/engine/tests/it/attrib_modes.rs @@ -22,6 +22,8 @@ fn references_take_lock_position_from_the_definition() { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; let modes = AttribModes { verify: true, preset: true, lock_position: true }; let def = Attrib { @@ -59,6 +61,8 @@ fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; let multiline = multiline.then(|| { let mtext = MText { @@ -72,6 +76,7 @@ fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") } }); diff --git a/crates/engine/tests/it/attrib_names.rs b/crates/engine/tests/it/attrib_names.rs new file mode 100644 index 000000000..2ae35aef9 --- /dev/null +++ b/crates/engine/tests/it/attrib_names.rs @@ -0,0 +1,203 @@ +//! AutoLISP's name of an INSERT's ATTRIB keeps naming that attribute when a command, another +//! session, another document or another thread gives out handles in the drawing or in a copy of +//! it, and installs the result (#1660). + +use std::sync::Arc; + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{EntityCodec, IoHooks, set_entity_codec, set_entity_sub_record, set_io, set_object_records}; +use cadcraft_engine::doc::geom::Vec3; +use cadcraft_engine::doc::{Block, Common, Drawing, Entity, EntityKind, Handle, Line, Space}; +use cadcraft_engine::lisp::value::to_text; +use serde_json::json; + +use crate::temp_dir::TempDir; + +fn session() -> Session { + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + set_entity_sub_record(cadcraft_io::entity_sub_record); + set_object_records(cadcraft_io::object_records); + set_io(IoHooks { + read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|e| e.to_string()), + write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|e| e.to_string()), + plot: None, + }); + Session::new() +} + +fn eval(s: &mut Session, code: &str) -> String { + match s.lisp_eval(code, false, true, Vec::new()) { + Ok(Some(Ok(v))) => to_text(&v, true), + Ok(Some(Err(e))) => panic!("{code}: {e}"), + Ok(None) => panic!("{code}: did not finish"), + Err(e) => panic!("{code}: {e}"), + } +} + +/// Block K with one attribute, one reference, and `i` naming that reference. +fn attributed() -> Session { + let mut s = session(); + s.cmdline( + "(progn (entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) \ + (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 1.0))) \ + (entmake '((0 . \"ATTDEF\") (10 0.0 5.0 0.0) (40 . 2.5) (1 . \"D1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \ + (entmake '((0 . \"ENDBLK\"))))", + ) + .unwrap(); + let ins = s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": { "T1": "A1" } })).unwrap(); + let href = ins["handle"].as_str().unwrap(); + eval(&mut s, &format!("(setq i (handent \"{href}\"))")); + s +} + +/// The command line names the reference's first ATTRIB `a`, with `$HANDSEED` one below the top: +/// the next handle the drawing, or a copy of it, gives out. The command line does not run the +/// after-command pass. +fn name_at_top(s: &mut Session) { + s.doc_mut().unwrap().handseed = u64::MAX - 1; + s.cmdline("(setq a (entnext i))").unwrap(); + assert_eq!(eval(s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\""); +} + +/// Every object's handle: model space, layouts and block definitions. +fn every_handle(d: &Drawing) -> Vec { + let mut v = d.model.handles(); + for l in &d.layouts { + v.extend(l.entities.handles()); + } + for b in d.blocks.values() { + v.extend(b.entities.handles()); + } + v +} + +/// `a` still names the attribute, and no object of the drawing is `a`: whatever handles were +/// given out, each object keeps its own name. +fn assert_kept(s: &mut Session) { + assert_eq!( + eval(s, "(list (cdr (assoc 0 (entget a))) (cdr (assoc 1 (entget a))))"), + "(\"ATTRIB\" \"A1\")", + "the old name still means the attribute" + ); + let handles = every_handle(s.doc().unwrap()); + for h in handles { + let hex = h.hex(); + assert_eq!(eval(s, &format!("(eq a (handent \"{hex}\"))")), "nil", "object {hex} is not the attribute"); + } +} + +/// A line added to `d` with the drawing's next handle. +fn add_line(d: &mut Drawing) -> Handle { + d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).unwrap() +} + +/// After a copy of the drawing took `line`, the name still means the attribute and the line is +/// the line. +fn assert_line_and_name(s: &mut Session, line: Handle) { + assert_kept(s); + let hex = line.hex(); + assert_eq!(eval(s, &format!("(cdr (assoc 0 (entget (handent \"{hex}\"))))")), "\"LINE\""); +} + +fn one_line(dir: &TempDir) -> String { + let mut d = Drawing::new_metric(); + add_line(&mut d); + dir.file("one-line.dxf", cadcraft_io::write_dxf(&d)) +} + +#[test] +fn another_sessions_read_leaves_a_record_name_alone() { + // Session A names an attribute and keeps a copy of its drawing; session B, which named + // nothing, is read; then A's copy gives out a handle and A installs it. + let mut a = attributed(); + let b = attributed(); + name_at_top(&mut a); + let mut copy = a.doc().unwrap().clone(); + let _ = b.doc().unwrap(); + let line = add_line(&mut copy); + *a.doc_mut().unwrap() = copy; + assert_line_and_name(&mut a, line); +} + +#[test] +fn a_copy_edited_on_another_thread_leaves_a_record_name_alone() { + let mut a = attributed(); + name_at_top(&mut a); + let copy = a.doc().unwrap().clone(); + let (copy, line) = std::thread::spawn(move || { + let mut copy = copy; + let line = add_line(&mut copy); + (copy, line) + }) + .join() + .unwrap(); + *a.doc_mut().unwrap() = copy; + assert_line_and_name(&mut a, line); +} + +#[test] +fn a_copy_made_while_another_document_is_current_leaves_a_record_name_alone() { + let mut s = attributed(); + name_at_top(&mut s); + let first = s.active; + let mut copy = s.doc().unwrap().clone(); + s.open_drawing(Drawing::new_metric(), "other", None); + let _ = s.doc().unwrap(); + let line = add_line(&mut copy); + s.active = first; + *s.doc_mut().unwrap() = copy; + assert_line_and_name(&mut s, line); +} + +#[test] +fn insert_from_file_keeps_an_attrib_name() { + let mut s = attributed(); + name_at_top(&mut s); + let dir = TempDir::new("attrib-insert"); + let path = one_line(&dir); + s.execute("insert", &json!({ "file": path, "name": "SRC", "at": [4.0, 4.0] })).unwrap(); + assert_kept(&mut s); +} + +#[test] +fn xattach_keeps_an_attrib_name() { + let mut s = attributed(); + name_at_top(&mut s); + let dir = TempDir::new("attrib-xref"); + let path = one_line(&dir); + s.execute("xattach", &json!({ "path": path, "name": "XR", "at": [8.0, 8.0] })).unwrap(); + assert_kept(&mut s); +} + +#[test] +fn audit_fix_keeps_an_attrib_name() { + let mut s = attributed(); + { + let d = s.doc_mut().unwrap(); + let line = Entity::new(Handle(0xABC), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })); + d.model.push(line.clone()); + let mut b = Block::new("DUP"); + b.entities.push(line); + d.blocks.insert("DUP".into(), Arc::new(b)); + } + name_at_top(&mut s); + s.execute("audit", &json!({ "fix": true })).unwrap(); + assert_kept(&mut s); +} + +#[test] +fn refclose_keeps_an_attrib_name() { + let mut s = attributed(); + s.cmdline( + "(progn (entmake '((0 . \"BLOCK\") (2 . \"R\") (70 . 0) (10 0.0 0.0 0.0))) \ + (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 2.0 0.0 0.0))) \ + (entmake '((0 . \"ENDBLK\"))))", + ) + .unwrap(); + let r = s.execute("insert", &json!({ "name": "R", "at": [0, 0] })).unwrap(); + s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap(); + s.execute("line", &json!({ "points": [[0, 1], [3, 1]] })).unwrap(); + name_at_top(&mut s); + s.execute("refclose", &json!({ "save": true })).unwrap(); + assert_kept(&mut s); +} diff --git a/crates/engine/tests/it/attribute_tag_matching.rs b/crates/engine/tests/it/attribute_tag_matching.rs index f06cfd2b4..5e69c4a99 100644 --- a/crates/engine/tests/it/attribute_tag_matching.rs +++ b/crates/engine/tests/it/attribute_tag_matching.rs @@ -65,9 +65,9 @@ fn burst_matches_many_attributes_without_comparing_every_pair() { #[test] fn attsync_matches_many_definitions_without_comparing_every_pair() { let (mut s, h) = reference(N); - let t = std::time::Instant::now(); + // The adjacent engine unit test checks exact indexed lookup work; this keeps + // the same end-to-end ATTSYNC fixture and its result checks. s.execute("attsync", &json!({"name": "B"})).unwrap(); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); // An attribute for each definition (T and the N others), with its default value: the // reference carried none of their tags. let a = attribs(&s, h); diff --git a/crates/engine/tests/it/draworder.rs b/crates/engine/tests/it/draworder.rs index 6dec0bccc..f717ca32d 100644 --- a/crates/engine/tests/it/draworder.rs +++ b/crates/engine/tests/it/draworder.rs @@ -145,3 +145,53 @@ fn texttofront_and_hatchtoback() { s.cmdline("").unwrap(); assert!(s.log.iter().any(|l| l.contains("2 object(s) brought to front")), "{:?}", s.log); } + +#[test] +fn texttofront_and_hatchtoback_across_all_spaces() { + let mut s = Session::new(); + // In Model space: 1 line, 1 hatch, 1 text. + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap(); + s.execute("text", &json!({ "at": [0, 0], "height": 2, "text": "MText1" })).unwrap(); + + // Create a paper space layout and switch to it. + s.execute("layout.new", &json!({ "name": "Sheet1", "viewport": false })).unwrap(); + s.execute("layout.set", &json!({ "name": "Sheet1" })).unwrap(); + + // In Sheet1 paper space: 1 line, 1 hatch, 1 text. + s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [20, 20] })).unwrap(); + s.execute("hatch", &json!({ "points": [[10, 10]], "pattern": "SOLID" })).unwrap(); + s.execute("text", &json!({ "at": [0, 0], "height": 3, "text": "PText1" })).unwrap(); + + // Move hatches to the front in both spaces first. + let m_hatch = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle; + let p_layout = s.doc().unwrap().layouts.iter().find(|l| l.name == "Sheet1").unwrap(); + let p_hatch = p_layout.entities.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle; + + s.execute("layout.set", &json!({ "name": "Model" })).unwrap(); + s.execute("draworder.front", &json!({ "handles": [m_hatch.hex()] })).unwrap(); + s.execute("layout.set", &json!({ "name": "Sheet1" })).unwrap(); + s.execute("draworder.front", &json!({ "handles": [p_hatch.hex()] })).unwrap(); + + // HATCHTOBACK acts across ALL spaces: model space AND layouts. + let r = s.execute("hatchtoback", &json!({})).unwrap(); + assert_eq!(r["moved"], 2, "hatches sent to back in both model space and paper layout"); + + let doc = s.doc().unwrap(); + let m_first = doc.model.iter().next().unwrap(); + assert!(matches!(m_first.kind, EntityKind::Hatch(_)), "model space hatch is back"); + let l_first = doc.layouts.iter().find(|l| l.name == "Sheet1").unwrap().entities.iter().next().unwrap(); + assert!(matches!(l_first.kind, EntityKind::Hatch(_)), "paper space hatch is back"); + + // TEXTTOFRONT acts across ALL spaces: brings text in both model space and paper layout to front. + let r = s.execute("texttofront", &json!({ "objects": "text" })).unwrap(); + assert_eq!(r["moved"], 2, "texts brought to front in both model space and paper layout"); + + let doc = s.doc().unwrap(); + let m_last = doc.model.iter().last().unwrap(); + assert!(matches!(m_last.kind, EntityKind::Text(_)), "model space text is front"); + let l_last = doc.layouts.iter().find(|l| l.name == "Sheet1").unwrap().entities.iter().last().unwrap(); + assert!(matches!(l_last.kind, EntityKind::Text(_)), "paper space text is front"); +} diff --git a/crates/engine/tests/it/dynamic_block_data.rs b/crates/engine/tests/it/dynamic_block_data.rs index 2e3f0baaa..0eee819bb 100644 --- a/crates/engine/tests/it/dynamic_block_data.rs +++ b/crates/engine/tests/it/dynamic_block_data.rs @@ -14,10 +14,19 @@ fn obj(handle: u64, kind: &str, tags: &[(i32, &str)]) -> ForeignObject { /// A session whose block "Door" has a visibility parameter with two states. fn session() -> Session { + session_with(false) +} + +/// [`session`], with an attribute NO (default "1") in Door when `attribute`. +fn session_with(attribute: bool) -> Session { let mut s = Session::new(); - let l = s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap()["handles"][0].clone(); - s.execute("block", &json!({ "name": "Door", "base": [0, 0], "handles": [l] })).unwrap(); - let line = s.doc().unwrap().block("Door").unwrap().entities.handles()[0].hex(); + let mut hs = vec![s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap()["handles"][0].clone()]; + if attribute { + hs.push(s.execute("attdef", &json!({ "tag": "NO", "prompt": "Door number", "default": "1", "at": [0, 1] })).unwrap()["handle"].clone()); + } + s.execute("block", &json!({ "name": "Door", "base": [0, 0], "handles": hs })).unwrap(); + let b = s.doc().unwrap().block("Door").unwrap().clone(); + let line = b.entities.iter().find(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Line(_))).unwrap().handle.hex(); let mut f = Foreign::default(); f.records.insert(("BLOCK_RECORD".into(), "DOOR".into()), ForeignExtra { xdict: Some(Handle(0xF00)), ..Default::default() }); f.objects.push(obj(0xF00, "DICTIONARY", &[(100, "AcDbDictionary"), (3, "ACAD_ENHANCEDBLOCK"), (360, "F01")])); @@ -142,3 +151,30 @@ fn a_visibility_state_is_changed_in_one_undo_step() { assert!(s.execute("blocks.reference.set", &p).is_err(), "{p}"); } } + +#[test] +fn a_dynamic_block_references_attributes_are_edited_and_refedit_says_why_not() { + let mut s = session_with(true); + let insert = s.doc().unwrap().model.handles()[0]; + let value = |s: &Session| match s.doc().unwrap().entity(insert).map(|e| e.kind.clone()) { + Some(cadcraft_engine::doc::EntityKind::Insert(i)) => (i.block, i.attribs.iter().map(|a| a.text.value.clone()).collect::>()), + other => panic!("{other:?}"), + }; + assert_eq!(value(&s).1, ["1"]); + // A visibility state change makes the reference show an anonymous copy (*U). + s.execute("blocks.reference.set", &json!({ "handle": insert.hex(), "name": "Visibility1", "value": "Closed" })).unwrap(); + assert!(value(&s).0.starts_with("*U")); + let rows = cadcraft_engine::attributes(s.doc().unwrap(), insert); + assert_eq!((rows[0].tag.as_str(), rows[0].prompt.as_str(), rows[0].editable), ("NO", "Door number", true)); + + let r = s.execute("attedit", &json!({ "handle": insert.hex(), "values": { "no": "12" } })).unwrap(); + assert_eq!(r["changed"], 1); + assert_eq!(value(&s).1, ["12"]); + // The value stays through another change of state. + s.execute("blocks.reference.set", &json!({ "handle": insert.hex(), "name": "Visibility1", "value": "Open" })).unwrap(); + assert_eq!(value(&s).1, ["12"]); + + // REFEDIT names the dynamic block and where to edit it instead of "*U… is generated geometry". + let e = s.execute("refedit", &json!({ "handles": [insert.hex()] })).unwrap_err().to_string(); + assert!(e.contains("\"Door\" is a dynamic block") && e.contains("BEDIT"), "{e}"); +} diff --git a/crates/engine/tests/it/extrim.rs b/crates/engine/tests/it/extrim.rs index ca5c7ce4e..0d61ee603 100644 --- a/crates/engine/tests/it/extrim.rs +++ b/crates/engine/tests/it/extrim.rs @@ -218,18 +218,46 @@ fn one_undo_restores_everything() { } #[test] -fn never_leaves_a_piece_of_no_length() { +fn a_short_piece_on_the_kept_side_stays_as_trim_leaves_it() { + // Landing review of #2808: only pieces of no length go; a short one that has length stays. let mut s = Session::new(); let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]); - // Starts a hair below the edge: trimming above would leave a sliver. + // Starts a hair below the edge: trimming above leaves that hair. line(&mut s, [5.0, -1e-8], [5.0, 5.0]); - extrim(&mut s, &edge, [5.0, 3.0]); + let v = extrim(&mut s, &edge, [5.0, 3.0]); + assert_eq!(v["trimmed"], 1, "{v}"); let d = s.doc().unwrap(); - for e in d.model.iter() { - if let EntityKind::Line(l) = &e.kind { - assert!(l.a.xy().dist(l.b.xy()) > 1e-6, "sliver left: {l:?}"); - } - } + let hairs: Vec = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) if (l.a.x - 5.0).abs() < 1e-9 => Some(l.a.xy().dist(l.b.xy())), + _ => None, + }) + .collect(); + assert_eq!(hairs.len(), 1, "{hairs:?}"); + assert!((hairs[0] - 1e-8).abs() < 1e-12, "{hairs:?}"); +} + +#[test] +fn a_stretch_shorter_than_trims_on_cut_tolerance_is_left_and_reported() { + // Landing review of #2808: TRIM passes over a cut within 5e-7 of the pick and runs on to the + // next one, so it would take more than the planned stretch. Such a stretch is left instead. + let mut s = Session::new(); + // A short edge, so the trace runs closer to it than that. + let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]); + // A polyline that pokes 4e-7 above the edge, comes back down and then rises well above it. + let verts = json!([[0.003, -5.0], [0.003, 4e-7], [0.0031, -5.0], [0.0031, 5.0]]); + s.execute("pline", &json!({ "vertices": verts })).unwrap(); + line(&mut s, [0.007, -5.0], [0.007, 5.0]); + let v = extrim(&mut s, &edge, [0.005, 3.0]); + assert_eq!(v["trimmed"], 1, "the line: {v}"); + assert_eq!(v["skipped"]["uncut"], 1, "the polyline: {v}"); + assert_eq!(v["skipped"]["partly"], 1, "its tall stretch is still cut: {v}"); + // The polyline's start is still there: the poke's trim didn't run on to the rise. + let start = Vec2::new(0.003, -5.0); + assert!(points_but(&s, &edge).iter().any(|p| p.near(start, 1e-9)), "the start below the edge was taken"); + assert!(top_but(&s, &edge) < 1e-6, "{}", top_but(&s, &edge)); } #[test] @@ -520,3 +548,113 @@ fn large_radius_arcs_weaving_through_a_short_edge_lose_every_stretch_on_the_side .fold(f64::NEG_INFINITY, f64::max); assert!(above <= 1e-6, "a stretch above the edge was left: {above:e}"); } + +#[test] +fn the_preview_cap_counts_drawn_parts_not_objects() { + // One zigzag polyline with `k` teeth above the edge loses `k` stretches: one object, `k` parts + // to draw. The preview draws up to 2000 parts (landing review of #2808). + for (k, previewed) in [(1999usize, true), (2001, false)] { + let mut s = Session::new(); + let edge = line(&mut s, [-1.0, 0.0], [2.0 * k as f64 + 1.0, 0.0]); + let verts: Vec<[f64; 2]> = (0..=2 * k).map(|i| [i as f64, if i % 2 == 0 { -1.0 } else { 1.0 }]).collect(); + s.execute("pline", &json!({ "vertices": verts })).unwrap(); + s.set_selection(Vec::new()); + s.start("extrim").unwrap(); + s.input(Input::Pick(vec![Handle::parse_hex(&edge).unwrap()])).unwrap(); + let shown = s.preview(Vec2::new(5.0, 3.0)); + assert_eq!(!shown.is_empty(), previewed, "{k} teeth: {} shown", shown.len()); + // Past the cap the trim itself still takes every tooth. + s.input(Input::Point(Vec2::new(5.0, 3.0))).unwrap(); + assert!(top_but(&s, &edge) <= 1e-6, "{k} teeth: {}", top_but(&s, &edge)); + } +} + +#[test] +fn a_short_piece_far_from_the_origin_stays_too() { + // #3526 review: the deletion test is no tolerance that grows with the distance from the + // origin. Near x = 1e9 a 1e-5 piece is a real piece. + let mut s = Session::new(); + let edge = line(&mut s, [1e9, 0.0], [1e9 + 10.0, 0.0]); + line(&mut s, [1e9 + 5.0, -1e-5], [1e9 + 5.0, 5.0]); + let v = extrim(&mut s, &edge, [1e9 + 5.0, 3.0]); + assert_eq!(v["trimmed"], 1, "{v}"); + let d = s.doc().unwrap(); + let kept: Vec = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) if (l.a.x - (1e9 + 5.0)).abs() < 1e-6 => Some(l.a.xy().dist(l.b.xy())), + _ => None, + }) + .collect(); + assert_eq!(kept.len(), 1, "{kept:?}"); + assert!((kept[0] - 1e-5).abs() < 1e-9, "{kept:?}"); +} + +#[test] +fn the_preview_leaves_out_a_stretch_the_trim_leaves() { + // #3526 review: the poke too short for TRIM to cut alone is not previewed as going. + let mut s = Session::new(); + let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]); + let verts = json!([[0.003, -5.0], [0.003, 4e-7], [0.0031, -5.0], [0.0031, 5.0]]); + s.execute("pline", &json!({ "vertices": verts })).unwrap(); + s.set_selection(Vec::new()); + s.start("extrim").unwrap(); + s.input(Input::Pick(vec![Handle::parse_hex(&edge).unwrap()])).unwrap(); + let shown = s.preview(Vec2::new(0.005, 3.0)); + let xs: Vec = shown + .iter() + .flat_map(|e| match &e.kind { + EntityKind::LwPolyline(p) => p.vertices.iter().map(|v| v.p.x).collect(), + _ => Vec::new(), + }) + .collect(); + assert!(!xs.is_empty(), "the rise is previewed"); + assert!(xs.iter().all(|x| *x > 0.00305), "the poke is not: {xs:?}"); +} + +#[test] +fn the_preview_cap_counts_only_parts_it_draws() { + // #3526 review: stretches too short to trim are not drawn, so they don't count toward the cap. + // 2001 pokes 4e-7 above a short edge, and one line rising well above it. + let mut s = Session::new(); + let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]); + for i in 0..2001 { + let x = 0.0005 + i as f64 * 4e-6; + line(&mut s, [x, -5.0], [x, 4e-7]); + } + line(&mut s, [0.009, -5.0], [0.009, 5.0]); + s.set_selection(Vec::new()); + s.start("extrim").unwrap(); + s.input(Input::Pick(vec![Handle::parse_hex(&edge).unwrap()])).unwrap(); + let shown = s.preview(Vec2::new(0.005, 3.0)); + assert_eq!(shown.len(), 1, "only the rise is drawn, under the cap"); +} + +#[test] +fn a_stretch_trim_can_cut_alone_is_cut_however_short() { + // #3526 review: a stretch is left only where TRIM would pass over its cut (within 5e-7 of the + // pick, plus the tracing's margin), not twice that. This one is 1.5e-6 long: the pick is + // 7.5e-7 from the cut, and TRIM cuts it. + let mut s = Session::new(); + let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]); + line(&mut s, [0.005, -0.005], [0.005, 1.5e-6]); + let v = extrim(&mut s, &edge, [0.005, 3.0]); + assert_eq!(v["trimmed"], 1, "{v}"); + assert_eq!(v["skipped"]["uncut"], 0, "{v}"); + assert!(top_but(&s, &edge) <= 1e-12, "{}", top_but(&s, &edge)); +} + +#[test] +fn a_folded_stretch_is_measured_along_itself() { + // #3526 review: the pick of this stretch is 1.5e-6 from its end straight across, where the + // polyline folds back, but two units from the cut along it: TRIM cuts it, and so does EXTRIM. + let mut s = Session::new(); + let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]); + let verts = json!([[1.0, -1.0], [1.0, 2.0], [1.5, 2.0], [1.5, 2.5], [1.0, 2.5], [1.0, 2.000001]]); + s.execute("pline", &json!({ "vertices": verts })).unwrap(); + let v = extrim(&mut s, &edge, [5.0, 3.0]); + assert_eq!(v["trimmed"], 1, "{v}"); + assert_eq!(v["skipped"]["uncut"], 0, "{v}"); + assert!(top_but(&s, &edge) <= 1e-9, "the stretch above the edge is gone: {}", top_but(&s, &edge)); +} diff --git a/crates/engine/tests/it/groups.rs b/crates/engine/tests/it/groups.rs index 76135d98c..9128ec9bd 100644 --- a/crates/engine/tests/it/groups.rs +++ b/crates/engine/tests/it/groups.rs @@ -155,3 +155,50 @@ fn erased_members_leave_groups() { s.cmdline("").unwrap(); assert_eq!(groups(&s).iter().map(|g| g.0.as_str()).collect::>(), ["B"]); } + +#[test] +fn copy_whole_group_replicates_group() { + let (mut s, hs) = three_lines(); + s.execute("group", &json!({ "name": "Pair", "description": "two lines", "handles": hex(&hs[..2]) })).unwrap(); + assert_eq!(s.doc().unwrap().groups.len(), 1); + + // Copying both members with COPY creates a new unnamed group *A1. + let r = s.execute("copy", &json!({ "handles": hex(&hs[..2]), "delta": [0, 20] })).unwrap(); + let copied: Vec = r["handles"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); + assert_eq!(copied.len(), 2); + let gs = groups(&s); + assert_eq!(gs.len(), 2, "a new group was created for the copied pair"); + assert_eq!(gs[1].0, "*A1"); + assert_eq!(gs[1].1, "two lines"); + assert_eq!(hex(&gs[1].2), copied); + + // Copying only ONE member of the group does not create another group. + s.execute("copy", &json!({ "handles": [hs[0].hex()], "delta": [0, 40] })).unwrap(); + assert_eq!(s.doc().unwrap().groups.len(), 2, "partial copy does not replicate group"); + + // Copying to clipboard and pasting also replicates the whole group. + s.set_selection(vec![hs[0], hs[1]]); + s.execute("copyclip", &json!({})).unwrap(); + let r = s.execute("pasteclip", &json!({ "at": [50, 50] })).unwrap(); + let pasted: Vec = r["handles"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); + let gs = groups(&s); + assert_eq!(gs.len(), 3, "pasting whole group replicates it"); + assert_eq!(gs[2].0, "*A2"); + assert_eq!(hex(&gs[2].2), pasted); +} + +#[test] +fn groupdisplaymode_sysvar() { + let mut s = Session::new(); + let v = s.execute("getvar", &json!({ "name": "GROUPDISPLAYMODE" })).unwrap(); + assert_eq!(v["value"], 2, "GROUPDISPLAYMODE defaults to 2"); + + s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": 0 })).unwrap(); + assert_eq!(s.settings.groupdisplaymode, 0); + + s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": 1 })).unwrap(); + assert_eq!(s.settings.groupdisplaymode, 1); + + assert!(s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": 3 })).is_err()); + assert!(s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": -1 })).is_err()); +} diff --git a/crates/engine/tests/it/hatch_arcs.rs b/crates/engine/tests/it/hatch_arcs.rs new file mode 100644 index 000000000..623fbd234 --- /dev/null +++ b/crates/engine/tests/it/hatch_arcs.rs @@ -0,0 +1,298 @@ +//! A hatch made by picking an internal point keeps the arcs of its boundary (#1167): the traced +//! outline comes from flattened curves, and its runs along a circle, an arc or a polyline's arc +//! segment become arcs again, so AREA on the hatch equals AREA on the objects. Only edges traced +//! from those circular pieces become arcs: a line or an ellipse near a circle stays as it is. + +use std::f64::consts::PI; + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle, Hatch, HatchLoop}; +use cadcraft_engine::geom::Polyline; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> String { + v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap().to_string() +} + +fn hatch(s: &Session, h: &str) -> Hatch { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::Hatch(x) => x.clone(), + k => panic!("not a hatch: {k:?}"), + } +} + +fn pl(l: &HatchLoop) -> Polyline { + Polyline { vertices: l.vertices.clone(), closed: true } +} + +/// Filled area, exact with bulges: outer loops minus islands. +fn area(h: &Hatch) -> f64 { + h.loops.iter().map(|l| pl(l).area().abs() * if l.outer { 1.0 } else { -1.0 }).sum() +} + +fn bulges(l: &HatchLoop) -> usize { + l.vertices.iter().filter(|v| v.bulge.abs() > 1e-9).count() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 * (1.0 + b.abs()) +} + +fn hatch_at(s: &mut Session, points: &[[f64; 2]]) -> String { + handle(&s.execute("hatch", &json!({ "points": points, "pattern": "SOLID" })).unwrap()) +} + +#[test] +fn a_circle_hatched_inside_is_two_half_circles_with_the_circles_area() { + let mut s = Session::new(); + let c = handle(&s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap()); + let h = { + let hh = hatch_at(&mut s, &[[50.0, 50.0]]); + hatch(&s, &hh) + }; + let l = &h.loops[0]; + assert_eq!(l.vertices.len(), 2, "{:?}", l.vertices); + assert!(l.vertices.iter().all(|v| (v.bulge.abs() - 1.0).abs() < 1e-12)); + assert!(close(area(&h), PI * 1600.0), "{}", area(&h)); + assert!(h.associative && l.sources.iter().any(|x| x.hex() == c)); + // Typed at the command line, as in the report. + let mut s = Session::new(); + s.script("CIRCLE 50,50 40\n-HATCH P SOLID\n50,50\n\n").unwrap(); + let h = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Hatch(x) = &e.kind { Some(x.clone()) } else { None }).unwrap(); + assert!(close(area(&h), PI * 1600.0), "{}", area(&h)); +} + +#[test] +fn a_rounded_rectangle_keeps_its_arc_as_one_polyline_or_as_lines_and_an_arc() { + // 100 x 50 with a semicircular right side: 5000 + π·25²/2. + let want = 5000.0 + PI * 625.0 / 2.0; + let mut s = Session::new(); + s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [100, 0], "bulge": 1.0 }, [100, 50], [0, 50]], "closed": true })).unwrap(); + let h = { + let hh = hatch_at(&mut s, &[[50.0, 25.0]]); + hatch(&s, &hh) + }; + assert_eq!(h.loops[0].vertices.len(), 4, "{:?}", h.loops[0].vertices); + assert_eq!(bulges(&h.loops[0]), 1); + assert!(close(area(&h), want), "{}", area(&h)); + // The same shape as three lines and an arc, then moved with its objects. + let mut s = Session::new(); + let mut objs = Vec::new(); + for (a, b) in [([0, 0], [100, 0]), ([100, 50], [0, 50]), ([0, 50], [0, 0])] { + objs.push(handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())); + } + objs.push(handle(&s.execute("arc", &json!({ "center": [100, 25], "radius": 25, "start": -90, "end": 90 })).unwrap())); + let hh = hatch_at(&mut s, &[[50.0, 25.0]]); + let h = hatch(&s, &hh); + assert_eq!(bulges(&h.loops[0]), 1); + assert!(close(area(&h), want), "{}", area(&h)); + objs.push(hh.clone()); + s.execute("move", &json!({ "handles": objs, "delta": [7, 3] })).unwrap(); + let h = hatch(&s, &hh); + assert_eq!(bulges(&h.loops[0]), 1, "{:?}", h.loops[0].vertices); + assert!(close(area(&h), want), "{}", area(&h)); +} + +/// A circle of radius 10 at the origin cut by a line `y = c`: the cap above it and the rest. +fn cut_circle(c: f64) -> (Session, f64, f64) { + let mut s = Session::new(); + s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap(); + s.execute("line", &json!({ "points": [[-20, c], [20, c]] })).unwrap(); + let theta = 2.0 * (c / 10.0).acos(); + let cap = 50.0 * (theta - theta.sin()); + (s, cap, PI * 100.0 - cap) +} + +#[test] +fn a_circle_cut_by_a_line_gives_the_exact_segments_even_for_a_shallow_cut() { + // (A cut shallower than the flattening tolerance finds no boundary, as before.) + for c in [3.0, 9.9, 9.99] { + let (mut s, cap, rest) = cut_circle(c); + let top = { + let hh = hatch_at(&mut s, &[[0.0, (c + 10.0) / 2.0]]); + hatch(&s, &hh) + }; + let bottom = { + let hh = hatch_at(&mut s, &[[0.0, 0.0]]); + hatch(&s, &hh) + }; + assert!(close(area(&top), cap), "cap at {c}: {} vs {cap}", area(&top)); + assert!(close(area(&bottom), rest), "rest at {c}: {} vs {rest}", area(&bottom)); + // Every point of both outlines stays on or inside the circle and on its side of the line. + for (h, above) in [(&top, true), (&bottom, false)] { + for q in pl(&h.loops[0]).tessellate(1e-4) { + assert!(q.len() <= 10.0 + 1e-6, "{q:?} outside the circle (cut at {c})"); + assert!(if above { q.y >= c - 1e-6 } else { q.y <= c + 1e-6 }, "{q:?} past the line (cut at {c})"); + } + } + } +} + +#[test] +fn an_ellipse_or_a_line_next_to_a_circle_is_not_taken_for_it() { + // An ellipse a hair wider than the circle crosses it four times; the region inside both is + // bounded by circle arcs and ellipse pieces, which stay flattened. + let mut s = Session::new(); + s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap(); + s.execute("ellipse", &json!({ "center": [0, 0], "major": [10.05, 0], "ratio": 0.99 })).unwrap(); + let h = { + let hh = hatch_at(&mut s, &[[0.0, 0.0]]); + hatch(&s, &hh) + }; + // Within the flattening tolerance of both curves, as the flattened outline was: where the + // two cross at a shallow angle the corner is only known to that tolerance. + let tol = 2.0 * (s.doc().unwrap().extents(&cadcraft_engine::doc::Space::Model).width() + 20.1) / 20000.0; + for q in pl(&h.loops[0]).tessellate(1e-4) { + assert!(q.len() <= 10.0 + tol, "{q:?} outside the circle"); + let r = 10.05 * (q.x * q.x + q.y * q.y / (0.99 * 0.99)).sqrt() / 10.05; + assert!(r <= 10.05 + tol, "{q:?} outside the ellipse"); + } + // A line just outside the circle, tangent-close: the hatch inside the circle is the circle. + let mut s = Session::new(); + s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap(); + s.execute("line", &json!({ "points": [[-20, 10.0001], [20, 10.0001]] })).unwrap(); + let h = { + let hh = hatch_at(&mut s, &[[0.0, 0.0]]); + hatch(&s, &hh) + }; + assert!(close(area(&h), PI * 100.0), "{}", area(&h)); +} + +#[test] +fn one_hatch_inside_and_around_a_circle_fills_both() { + // Picked inside the circle and in the square around it: the circle is filled too. + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap(); + s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap(); + let hh = hatch_at(&mut s, &[[50.0, 50.0], [5.0, 5.0]]); + let h = hatch(&s, &hh); + assert!(close(filled(&h), 10000.0), "{} from {:?}", filled(&h), h.loops.iter().map(|l| (l.outer, l.vertices.len())).collect::>()); + // As drawn and as AREA measures it: the circle's outer loop and island cancel, the square + // is filled whole. + let drawn = cadcraft_engine::render::hatch_fill_loops(&h, 1e-3); + let centre = cadcraft_engine::geom::Vec2::new(50.0, 50.0); + assert_eq!(drawn.iter().filter(|l| cadcraft_engine::geom::point_in_polygon(l, centre)).count() % 2, 1, "the circle is filled"); + let a = s.execute("area", &json!({ "handle": hh })).unwrap()["area"].as_f64().unwrap(); + assert!(close(a, 10000.0), "{a}"); + // The same with a square inside the square (exact on main too, so merged there). + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap(); + s.execute("rectang", &json!({ "p1": [40, 40], "p2": [60, 60] })).unwrap(); + let hh = hatch_at(&mut s, &[[50.0, 50.0], [5.0, 5.0]]); + let h = hatch(&s, &hh); + assert!(close(filled(&h), 10000.0), "{}", filled(&h)); +} + +/// The area the even-odd fill covers: points on a fine grid inside an odd number of loops. +fn filled(h: &Hatch) -> f64 { + let polys: Vec> = h.loops.iter().map(|l| pl(l).tessellate(1e-3)).collect(); + let n = 400; + let step = 100.0 / n as f64; + let mut inside = 0usize; + for i in 0..n { + for j in 0..n { + let q = cadcraft_engine::geom::Vec2::new((i as f64 + 0.5) * step, (j as f64 + 0.5) * step); + if polys.iter().filter(|p| cadcraft_engine::geom::point_in_polygon(p, q)).count() % 2 == 1 { + inside += 1; + } + } + } + inside as f64 * step * step +} + +/// HPORIGINMODE's corners take the circle's extents, not only its two vertices (a circle kept as +/// two half-circles spans its whole height). +#[test] +fn a_circles_hatch_origin_takes_its_extents() { + let mut s = Session::new(); + s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap(); + let h = handle(&s.execute("hatch", &json!({ "points": [[50, 50]], "pattern": "ANSI31", "originMode": "bottomLeft" })).unwrap()); + let o = hatch(&s, &h).origin; + assert!(close(o.x, 10.0) && close(o.y, 10.0), "{o:?}"); + let h = handle(&s.execute("hatch", &json!({ "points": [[50, 50]], "pattern": "ANSI31", "originMode": "topRight" })).unwrap()); + let o = hatch(&s, &h).origin; + assert!(close(o.x, 90.0) && close(o.y, 90.0), "{o:?}"); +} + +/// The polyline BOUNDARY makes keeps the arcs: a circle gives two half-circles, a rounded +/// rectangle one arc segment, each with the object's exact area. +#[test] +fn boundary_keeps_the_arcs() { + let lw = |s: &Session, h: &str| -> Polyline { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::LwPolyline(p) => Polyline { vertices: p.vertices.clone(), closed: p.closed }, + k => panic!("not a polyline: {k:?}"), + } + }; + let mut s = Session::new(); + s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap(); + let b = handle(&s.execute("boundary", &json!({ "points": [[50, 50]] })).unwrap()); + let p = lw(&s, &b); + assert_eq!(p.vertices.len(), 2, "{:?}", p.vertices); + assert!(p.vertices.iter().all(|v| (v.bulge.abs() - 1.0).abs() < 1e-12)); + assert!(close(p.area().abs(), PI * 1600.0), "{}", p.area()); + + let mut s = Session::new(); + s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [100, 0], "bulge": 1.0 }, [100, 50], [0, 50]], "closed": true })).unwrap(); + let b = handle(&s.execute("boundary", &json!({ "points": [[50, 25]] })).unwrap()); + let p = lw(&s, &b); + assert_eq!(p.vertices.iter().filter(|v| v.bulge.abs() > 1e-9).count(), 1, "{:?}", p.vertices); + assert!(close(p.area().abs(), 5000.0 + PI * 625.0 / 2.0), "{}", p.area()); +} + +/// HATCHEDIT adding a boundary the hatch already has (its island) changes nothing: a second copy +/// of the island would cancel it and fill the circle. +#[test] +fn hatchedit_adding_an_existing_island_keeps_it() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap(); + let c = handle(&s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap()); + // Not associative: its island is linked to nothing until the circle is added. + let hh = handle(&s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID", "associative": false })).unwrap()); + assert!(hatch(&s, &hh).loops.iter().all(|l| l.sources.is_empty())); + let before = hatch(&s, &hh).loops.len(); + s.execute("hatchedit", &json!({ "handles": [hh], "addBoundary": [c] })).unwrap(); + let h = hatch(&s, &hh); + assert_eq!(h.loops.len(), before, "{:?}", h.loops.iter().map(|l| (l.outer, l.vertices.len())).collect::>()); + let drawn = cadcraft_engine::render::hatch_fill_loops(&h, 1e-3); + let centre = cadcraft_engine::geom::Vec2::new(50.0, 50.0); + assert_eq!(drawn.iter().filter(|l| cadcraft_engine::geom::point_in_polygon(l, centre)).count() % 2, 0, "the island stays empty"); + // The island is linked to the circle that was added. + assert!( + h.loops.iter().any(|l| !l.outer && l.sources.iter().any(|x| x.hex() == c)), + "{:?}", + h.loops.iter().map(|l| (l.outer, l.sources.clone())).collect::>() + ); +} + +/// AREA tests a loop's nesting at an edge's middle, as the fill does: an island whose first vertex +/// lies on the outer loop (here on its right edge, where a vertex test says "outside") is still +/// subtracted. +#[test] +fn area_subtracts_an_island_touching_the_outer_loop() { + use cadcraft_engine::geom::{PolyVertex, Vec2}; + let lp = |pts: &[(f64, f64)], outer: bool| HatchLoop { + vertices: pts.iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), + outer, + boundary_flags: None, + sources: vec![], + }; + let mut s = Session::new(); + let h = Hatch { + loops: vec![lp(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)], true), lp(&[(10.0, 5.0), (5.0, 4.0), (5.0, 6.0)], false)], + pattern: "SOLID".into(), + solid: true, + scale: 1.0, + ..hatch_template(&mut s) + }; + let id = s.add_entity(EntityKind::Hatch(h)).unwrap(); + let a = s.execute("area", &json!({ "handle": id.hex() })).unwrap()["area"].as_f64().unwrap(); + assert!(close(a, 100.0 - 5.0), "{a}"); +} + +/// Any hatch's fields, to build one by hand. +fn hatch_template(s: &mut Session) -> Hatch { + s.execute("rectang", &json!({ "p1": [200, 200], "p2": [210, 210] })).unwrap(); + let hh = hatch_at(s, &[[205.0, 205.0]]); + hatch(s, &hh) +} diff --git a/crates/engine/tests/it/insert_attrib_entry.rs b/crates/engine/tests/it/insert_attrib_entry.rs index a4974b79b..5a5d3c035 100644 --- a/crates/engine/tests/it/insert_attrib_entry.rs +++ b/crates/engine/tests/it/insert_attrib_entry.rs @@ -26,6 +26,8 @@ fn def(tag: &str, prompt: &str, default: &str, y: f64, constant: bool, modes: At style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }, invisible: false, constant, diff --git a/crates/engine/tests/it/layer_cmdline.rs b/crates/engine/tests/it/layer_cmdline.rs index 30c97d739..8d5bf2fff 100644 --- a/crates/engine/tests/it/layer_cmdline.rs +++ b/crates/engine/tests/it/layer_cmdline.rs @@ -71,3 +71,29 @@ fn layer_commands_reject_unloaded_linetypes_and_duplicate_renames() { s.execute("layer.set", &json!({ "name": "A", "newName": "a", "linetype": "continuous" })).unwrap(); assert_eq!(s.doc().unwrap().layer("a").unwrap().linetype, "Continuous"); } + +#[test] +fn layer_cmdline_state_save_restore_rename_delete() { + let mut s = Session::new(); + s.execute("layer.new", &json!({ "name": "L1", "color": "1" })).unwrap(); + // Test -LAYER A (stAte) Save + s.script("-LAYER A S St1 \n\n").unwrap(); + assert!(s.doc().unwrap().layer_states.iter().any(|st| st.name == "St1")); + + // Modify layer L1 color + s.execute("layer.set", &json!({ "name": "L1", "color": "2" })).unwrap(); + assert_eq!(s.doc().unwrap().layer("L1").unwrap().color, cadcraft_color::Color::Index(2)); + + // Restore St1 + s.script("-LAYER A R St1 \n\n").unwrap(); + assert_eq!(s.doc().unwrap().layer("L1").unwrap().color, cadcraft_color::Color::Index(1)); + + // Rename St1 -> St2 (Name) + s.script("-LAYER A N St1 St2 \n\n").unwrap(); + assert!(s.doc().unwrap().layer_states.iter().any(|st| st.name == "St2")); + assert!(!s.doc().unwrap().layer_states.iter().any(|st| st.name == "St1")); + + // Delete St2 + s.script("-LAYER A D St2 \n\n").unwrap(); + assert!(!s.doc().unwrap().layer_states.iter().any(|st| st.name == "St2")); +} diff --git a/crates/engine/tests/it/leader_text_scale.rs b/crates/engine/tests/it/leader_text_scale.rs new file mode 100644 index 000000000..2e058ec50 --- /dev/null +++ b/crates/engine/tests/it/leader_text_scale.rs @@ -0,0 +1,33 @@ +//! #1056: a leader's annotation is drawn at the dimension text size, DIMTXT × DIMSCALE, like the +//! dimensions beside it. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +#[test] +fn leader_text_takes_dimscale() { + let mut s = Session::new(); + s.execute("dimstyle", &json!({"name": "S25", "current": true, "DIMSCALE": 25, "DIMTXT": 0.25, "DIMASZ": 0.2})).unwrap(); + s.execute("leader", &json!({"points": [[0, 0], [20, 20], [30, 20]], "text": "NOTE"})).unwrap(); + let h = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MText(m) = &e.kind { Some(m.height) } else { None }).unwrap(); + assert!((h - 6.25).abs() < 1e-9, "{h}"); +} + +/// An annotative dimension style: the annotation scale takes DIMSCALE's place, as for an +/// annotative dimension, so the text is DIMTXT high and annotative, scaled with the dimension. +#[test] +fn leader_text_of_an_annotative_style_is_annotative() { + let mut s = Session::new(); + s.execute("dimstyle", &json!({"name": "A", "current": true, "DIMSCALE": 2, "DIMTXT": 0.25, "annotative": true})).unwrap(); + s.execute("leader", &json!({"points": [[0, 0], [20, 20], [30, 20]], "text": "NOTE"})).unwrap(); + let d = s.doc().unwrap(); + let e = d.model.iter().find(|e| matches!(e.kind, EntityKind::MText(_))).unwrap(); + let EntityKind::MText(m) = &e.kind else { unreachable!() }; + assert!((m.height - 0.25).abs() < 1e-9, "{}", m.height); + assert!(cadcraft_engine::doc::is_annotative(e), "annotative like the style"); + // Drawn at an annotation scale of 1:50, it is as high as the dimension text: DIMTXT × 50. + let scaled = cadcraft_engine::doc::anno_scaled(e, 50.0); + let EntityKind::MText(m) = &scaled.kind else { unreachable!() }; + assert!((m.height - 12.5).abs() < 1e-9, "{}", m.height); +} diff --git a/crates/engine/tests/it/lisp_findfile.rs b/crates/engine/tests/it/lisp_findfile.rs index 410440177..a7e4c84c3 100644 --- a/crates/engine/tests/it/lisp_findfile.rs +++ b/crates/engine/tests/it/lisp_findfile.rs @@ -4,10 +4,7 @@ use cadcraft_engine::Session; use serde_json::json; -#[path = "../support/temp_dir.rs"] -mod temp_dir; - -use temp_dir::TempDir; +use crate::temp_dir::TempDir; /// `(findfile name)` as LISP prints it. fn findfile(name: &str) -> String { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 5cf01ee29..3d6679d95 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,3 +1,6 @@ +#[path = "../support/temp_dir.rs"] +mod temp_dir; + mod angle_prompts; mod angle_settings; mod annotate_options; @@ -12,6 +15,7 @@ mod attdef_command; mod attdisp_attsync; mod attedit_prompts; mod attrib_modes; +mod attrib_names; mod attrib_props; mod attribute_tag_matching; mod attribute_tools; @@ -71,6 +75,7 @@ mod grip_options; mod grip_selection; mod group_selection; mod groups; +mod hatch_arcs; mod hatch_assoc; mod hatch_dialog_helpers; mod hatch_generate_boundary; @@ -97,6 +102,7 @@ mod layoff_repeat; mod layout_prompts; mod leader_command; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod leader_text_scale; mod lisp_corpus; mod lisp_findfile; mod lisp_undo_in_routine; @@ -112,6 +118,7 @@ mod mleader_text_edit; mod mline; mod mocoro; mod modify_curves; +mod move_copy_deferred_base; mod mtext_columns; mod mtext_options; mod mtext_ortho; @@ -155,11 +162,14 @@ mod recent_commands; mod rectang_ortho; mod rectang_polygon_order; mod refedit; +mod refedit_xref; mod region; mod rename_cmdline; +mod revcloud_recognised; mod rotate_reference; mod rotation_grip_input; mod scale_offset_z; +mod scale_zero_factor; mod select_keywords; mod select_similar; mod select_underscore_keywords; @@ -186,6 +196,7 @@ mod table_formulas; mod table_styles; mod temp_tracking; mod text_commands; +mod text_generation_flags; mod text_left_justify; mod tolerance; mod transparent; @@ -199,11 +210,14 @@ mod trim_keeps_z_and_width; mod undo_count; mod undo_layout_tab; mod viewport_clip; +mod viewport_frozen_block_parts; mod viewport_frozen_selection; +mod viewport_ucs_copy; mod vplayer_prompts; mod vports; mod wipeout_grips; mod xclip; +mod xdata_api; mod xdata_follows_entity; mod zoom_keywords; mod zoom_viewport; diff --git a/crates/engine/tests/it/measure_distance_snapping.rs b/crates/engine/tests/it/measure_distance_snapping.rs index e392f4c40..6e7c1369c 100644 --- a/crates/engine/tests/it/measure_distance_snapping.rs +++ b/crates/engine/tests/it/measure_distance_snapping.rs @@ -27,6 +27,9 @@ fn drawing() -> (Drawing, Space) { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }), ) diff --git a/crates/engine/tests/it/modify_curves.rs b/crates/engine/tests/it/modify_curves.rs index cea710d72..7d71d8c92 100644 --- a/crates/engine/tests/it/modify_curves.rs +++ b/crates/engine/tests/it/modify_curves.rs @@ -567,6 +567,144 @@ fn fillet_and_chamfer_a_line_into_a_polyline() { assert_eq!(count(&s), 1); } +#[test] +fn a_line_crossing_a_polyline_end_segment_keeps_the_picked_side() { + // An L whose end segment a line crosses. Picked right of the crossing, the polyline keeps that + // part and drops the rest past the crossing, the line's picked part joining it (as AutoCAD). + let mut s = Session::new(); + let p = pline(&mut s, &[[0.0, 1.0], [0.0, 0.0], [4.0, 0.0]], false); + let l = h(&s.execute("line", &json!({ "points": [[2, -1], [2, 1.5]] })).unwrap()); + s.execute("fillet", &json!({ "h1": l, "p1": [2, 1], "h2": p, "p2": [3, 0], "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), vec![(2.0, 1.5, 0.0), (2.0, 0.0, 0.0), (4.0, 0.0, 0.0)]); + assert_eq!(count(&s), 1); + // Picked left of it, the L stays and the line's lower part joins. + let mut s = Session::new(); + let p = pline(&mut s, &[[0.0, 1.0], [0.0, 0.0], [4.0, 0.0]], false); + let _ = h(&s.execute("line", &json!({ "points": [[2, -1], [2, 1.5]] })).unwrap()); + s.script("FILLET R 0 1,0 2,-0.5\n").unwrap(); + assert_eq!(verts(&s, &p), vec![(0.0, 1.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, -1.0, 0.0)]); +} + +#[test] +fn fillet_joins_two_polylines_at_their_end_segments() { + // A wall line short of the corner and an open outline ending under it: one polyline, as AutoCAD. + let mut s = Session::new(); + let a = pline(&mut s, &[[0.0, 8.55], [0.0, 1.25]], false); + let b = pline(&mut s, &[[0.15, 0.15], [1.0, 0.15], [1.0, 0.0], [0.0, 0.0]], false); + s.execute("fillet", &json!({ "h1": a, "p1": [0, 5], "h2": b, "p2": [0.5, 0], "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &a), vec![(0.0, 8.55, 0.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.15, 0.0), (0.15, 0.15, 0.0)]); + assert_eq!(count(&s), 1); + // The other picked first keeps its direction; a radius rounds the corner. + let mut s = Session::new(); + let a = pline(&mut s, &[[0.0, 8.0], [0.0, 2.0]], false); + let b = pline(&mut s, &[[5.0, 5.0], [5.0, 0.0], [1.0, 0.0]], false); + s.execute("fillet", &json!({ "h1": b, "p1": [3, 0], "h2": a, "p2": [0, 5], "radius": 1 })).unwrap(); + assert_eq!(verts(&s, &b), vec![(5.0, 5.0, 0.0), (5.0, 0.0, 0.0), (1.0, 0.0, -quarter()), (0.0, 1.0, 0.0), (0.0, 8.0, 0.0)]); + assert_eq!(count(&s), 1); +} + +#[test] +fn fillet_joins_a_polyline_end_segment_crossing_another_polylines_middle_segment() { + // As AutoCAD: each keeps its picked side of the crossing, the rest past it goes (here the + // stub below the crossing, and the middle segment's left part with the leg after it). + let mut s = Session::new(); + let a = pline(&mut s, &[[0.0, -0.4], [0.0, 0.15], [1.4, 0.15], [1.4, 1.9], [1.2, 1.9]], false); + let b = pline(&mut s, &[[3.4, -0.5], [3.4, 0.0], [-0.7, 0.0], [-0.7, -3.0]], false); + s.execute("fillet", &json!({ "h1": a, "p1": [0, 0.1], "h2": b, "p2": [2, 0], "radius": 0 })).unwrap(); + assert_eq!( + verts(&s, &a), + vec![(3.4, -0.5, 0.0), (3.4, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.15, 0.0), (1.4, 0.15, 0.0), (1.4, 1.9, 0.0), (1.2, 1.9, 0.0)] + ); + assert_eq!(count(&s), 1); +} + +/// A closed polyline filleted with a line opens at its first vertex, as AutoCAD does: the picked +/// side of the picked segment joins the line, either side, and the result is open. AutoCAD's +/// results for these shapes (a 4 x 3 RECTANG with a line short of it, crossing it, and level +/// with its right side). +#[test] +fn a_closed_polyline_opens_at_its_first_vertex_to_join_a_line() { + let rect = |s: &mut Session, x: f64| pline(s, &[[x, 0.0], [x + 4.0, 0.0], [x + 4.0, 3.0], [x, 3.0]], true); + let line = |s: &mut Session, a: [f64; 2], b: [f64; 2]| h(&s.execute("line", &json!({ "points": [a, b] })).unwrap()); + let open = |s: &Session, p: &str| match kind(s, p) { + EntityKind::LwPolyline(pl) => !pl.closed, + _ => false, + }; + // A line short of the top side, the top's left part picked. + let mut s = Session::new(); + let p = rect(&mut s, 0.0); + let l = line(&mut s, [2.0, 4.5], [2.0, 3.6]); + s.execute("fillet", &json!({ "h1": l, "p1": [2, 4.2], "h2": p, "p2": [1, 3], "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), vec![(2.0, 4.5, 0.0), (2.0, 3.0, 0.0), (0.0, 3.0, 0.0), (0.0, 0.0, 0.0)]); + assert!(open(&s, &p)); + assert_eq!(count(&s), 1); + // Its right part: the other way round the rectangle. + let mut s = Session::new(); + let p = rect(&mut s, 0.0); + let l = line(&mut s, [2.0, 4.5], [2.0, 3.6]); + s.execute("fillet", &json!({ "h1": l, "p1": [2, 4.2], "h2": p, "p2": [3, 3], "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), vec![(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 3.0, 0.0), (2.0, 3.0, 0.0), (2.0, 4.5, 0.0)]); + // A line crossing the top side, its inner part picked. + let mut s = Session::new(); + let p = rect(&mut s, 9.0); + let l = line(&mut s, [11.0, 1.8], [11.0, 4.5]); + s.execute("fillet", &json!({ "h1": l, "p1": [11, 2.2], "h2": p, "p2": [10, 3], "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), vec![(11.0, 1.8, 0.0), (11.0, 3.0, 0.0), (9.0, 3.0, 0.0), (9.0, 0.0, 0.0)]); + // A line level with the right side, below it or above it. + for (pick, want) in [ + ([22.0, 1.0], vec![(18.0, 0.0, 0.0), (22.0, 0.0, 0.0), (22.0, 2.5, 0.0), (23.5, 2.5, 0.0)]), + ([22.0, 2.8], vec![(23.5, 2.5, 0.0), (22.0, 2.5, 0.0), (22.0, 3.0, 0.0), (18.0, 3.0, 0.0), (18.0, 0.0, 0.0)]), + ] { + let mut s = Session::new(); + let p = rect(&mut s, 18.0); + let l = line(&mut s, [23.5, 2.5], [22.6, 2.5]); + s.execute("fillet", &json!({ "h1": l, "p1": [23.2, 2.5], "h2": p, "p2": pick, "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), want, "{pick:?}"); + } +} + +/// An arc segment crossed by a line is cut where they cross (radius 0), keeping its picked side, +/// with the bulge of what is left of it: AutoCAD's result for this shape. A line that misses +/// the arc, or a radius, is refused, as AutoCAD refuses them. +#[test] +fn an_arc_segment_crossed_by_a_line_is_cut_there() { + let shape = |s: &mut Session| { + let p = + h(&s.execute("pline", &json!({ "vertices": [[45, 0], { "p": [47, 0], "bulge": -0.4 }, [49, 0], [49, -1.5]], "closed": false })).unwrap()); + let l = h(&s.execute("line", &json!({ "points": [[48, -0.5], [48, 2.2]] })).unwrap()); + (p, l) + }; + let half = ((-4.0 * 0.4f64.atan() / 2.0 / 4.0).tan() * 1e9).round() / 1e9; + let mut s = Session::new(); + let (p, l) = shape(&mut s); + s.execute("fillet", &json!({ "h1": l, "p1": [48, 1.5], "h2": p, "p2": [48.8, 0.25], "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), vec![(48.0, 2.2, 0.0), (48.0, 0.4, half), (49.0, 0.0, 0.0), (49.0, -1.5, 0.0)]); + assert_eq!(count(&s), 1); + // The other side of the arc. + let mut s = Session::new(); + let (p, l) = shape(&mut s); + s.execute("fillet", &json!({ "h1": l, "p1": [48, 1.5], "h2": p, "p2": [47.2, 0.25], "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), vec![(45.0, 0.0, 0.0), (47.0, 0.0, half), (48.0, 0.4, 0.0), (48.0, 2.2, 0.0)]); + // A pick a little before the arc's start (within the pick box) keeps the start side. + let mut s = Session::new(); + let p = h(&s.execute("pline", &json!({ "vertices": [{ "p": [47, 0], "bulge": -0.4 }, [49, 0], [49, -1.5]], "closed": false })).unwrap()); + let l = h(&s.execute("line", &json!({ "points": [[48, -0.5], [48, 2.2]] })).unwrap()); + // On the arc's circle (centre 48,-1.05, radius 1.45), 2.4° before its start. + let a = (1.05f64).atan2(-1.0) + 2.4f64.to_radians(); + let pick = [48.0 + 1.45 * a.cos(), -1.05 + 1.45 * a.sin()]; + s.execute("fillet", &json!({ "h1": l, "p1": [48, 1.5], "h2": p, "p2": pick, "radius": 0 })).unwrap(); + assert_eq!(verts(&s, &p), vec![(47.0, 0.0, half), (48.0, 0.4, 0.0), (48.0, 2.2, 0.0)]); + // An end arc the line doesn't reach, at radius 0 or not: refused, nothing changed. + for r in [0.0, 0.3] { + let mut s = Session::new(); + let p = h(&s.execute("pline", &json!({ "vertices": [[27, 0], { "p": [29, 0], "bulge": 0.3 }, [30.2, 1.2]], "closed": false })).unwrap()); + let l = h(&s.execute("line", &json!({ "points": [[31.2, -0.5], [31.2, 3]] })).unwrap()); + let before = verts(&s, &p); + assert!(s.execute("fillet", &json!({ "h1": p, "p1": [29.8, 0.6], "h2": l, "p2": [31.2, 2.5], "radius": r })).is_err()); + assert_eq!(verts(&s, &p), before); + } +} + #[test] fn polyline_fillets_at_the_command_line_and_with_no_trim() { let mut s = Session::new(); @@ -592,7 +730,7 @@ fn polyline_fillet_refusals_leave_it_alone() { let c = h(&s.execute("circle", &json!({ "center": [30, 0], "radius": 1 })).unwrap()); let l = h(&s.execute("line", &json!({ "points": [[20, -5], [20, 5]] })).unwrap()); for q in [ - // Segments too far apart, the same segment, a circle, a middle segment with a line, too big. + // Segments too far apart, the same segment, a circle, a segment parallel to a line, too big. json!({ "h1": p, "p1": [5, 0], "h2": p, "p2": [0, 15], "radius": 1 }), json!({ "h1": p, "p1": [5, 0], "h2": p, "p2": [6, 0], "radius": 1 }), json!({ "h1": p, "p1": [5, 0], "h2": c, "p2": [31, 0], "radius": 1 }), diff --git a/crates/engine/tests/it/move_copy_deferred_base.rs b/crates/engine/tests/it/move_copy_deferred_base.rs new file mode 100644 index 000000000..e747f7ab2 --- /dev/null +++ b/crates/engine/tests/it/move_copy_deferred_base.rs @@ -0,0 +1,103 @@ +//! #3481: a perpendicular or tangent picked at MOVE's and COPY's base point prompt waits for the +//! second point, as LINE's first point does. The base is then the foot of the perpendicular from +//! the second point onto the object, or the tangent point seen from it. + +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::snap::{Deferred, SnapCurve, mode}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn handle(r: &Value) -> Handle { + Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap() +} + +/// The centers of every circle, sorted by x. +fn centers(s: &Session) -> Vec { + let mut v: Vec = + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.center.xy()) } else { None }).collect(); + v.sort_by(|a, b| a.x.total_cmp(&b.x)); + v +} + +/// A session with a circle at (20, 5) selected, and `command` started at its base point prompt. +fn at_base_point(command: &str) -> Session { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "COPYMODE", "value": 0 })).unwrap(); + let c = handle(&s.execute("circle", &json!({ "center": [20, 5], "radius": 1 })).unwrap()); + s.set_selection(vec![c]); + s.cmdline(command).unwrap(); + let prompt = s.current_prompt().unwrap(); + assert!(prompt.message.starts_with("Specify base point") && prompt.deferred, "{prompt:?}"); + s +} + +/// Perpendicular to the Y axis, picked at (0, 3). +fn per_y_axis() -> Deferred { + Deferred { mode: mode::PER, curve: SnapCurve::Line { a: Vec2::new(0.0, -10.0), b: Vec2::new(0.0, 10.0) }, at: Vec2::new(0.0, 3.0) } +} + +#[test] +fn move_resolves_a_perpendicular_base_from_the_second_point() { + let mut s = at_base_point("move"); + s.input(Input::Deferred(per_y_axis())).unwrap(); + assert!(s.running.is_some(), "still asking for the second point"); + // The foot of the perpendicular from (5, 7) is (0, 7): the circle moves by (5, 0). + s.cmdline("5,7").unwrap(); + assert!(s.running.is_none()); + assert_eq!(centers(&s), [Vec2::new(25.0, 5.0)]); +} + +#[test] +fn move_resolves_a_tangent_base_from_the_second_point() { + let mut s = at_base_point("move"); + let tan = Deferred { mode: mode::TAN, curve: SnapCurve::Circle { center: Vec2::ZERO, radius: 5.0 }, at: Vec2::new(3.0, 4.0) }; + s.input(Input::Deferred(tan)).unwrap(); + s.cmdline("10,0").unwrap(); + // The tangent point from (10, 0) on the side that was picked is (2.5, 4.33…). + let t = Vec2::new(2.5, 75f64.sqrt() / 2.0); + let moved = centers(&s)[0]; + assert!(moved.near(Vec2::new(20.0, 5.0) + (Vec2::new(10.0, 0.0) - t), 1e-9), "{moved:?}"); +} + +#[test] +fn copy_keeps_the_resolved_base_for_later_copies() { + let mut s = at_base_point("copy"); + s.input(Input::Deferred(per_y_axis())).unwrap(); + s.cmdline("5,7").unwrap(); + // The base is now (0, 7) for every further copy. + s.cmdline("10,7").unwrap(); + s.cmdline("").unwrap(); + assert_eq!(centers(&s), [Vec2::new(20.0, 5.0), Vec2::new(25.0, 5.0), Vec2::new(30.0, 5.0)]); +} + +#[test] +fn a_perpendicular_with_no_foot_from_the_second_point_asks_again() { + let mut s = at_base_point("move"); + let per = Deferred { mode: mode::PER, curve: SnapCurve::Arc { center: Vec2::ZERO, radius: 5.0, start: 0.0, end: 1.0 }, at: Vec2::new(4.0, 3.0) }; + s.input(Input::Deferred(per)).unwrap(); + // From (0, -8) the feet on the arc's circle are (0, ±5), both off the arc's sweep. + s.cmdline("0,-8").unwrap(); + // The prompt says why, as a fixed English sentence the interface translates. + let prompt = s.current_prompt().unwrap(); + assert_eq!(prompt.message, "No perpendicular from that point. Specify another second point"); + assert!(s.running.is_some() && centers(&s) == [Vec2::new(20.0, 5.0)], "nothing moved and it asks again"); + // Anything but a point keeps asking, without an untranslated line in the history. + s.input(Input::Text("x".into())).unwrap(); + assert!(s.running.is_some() && !s.log.iter().any(|l| l.contains("second point.")), "{:?}", s.log); + // A point with a foot then moves the circle: from (8, 6) the foot is (4, 3). + s.cmdline("8,6").unwrap(); + assert_eq!(centers(&s), [Vec2::new(24.0, 8.0)]); +} + +/// The same for a tangent: inside the circle there is no tangent point, and the prompt says so. +#[test] +fn a_tangent_with_no_tangent_point_from_the_second_point_asks_again() { + let mut s = at_base_point("move"); + let tan = Deferred { mode: mode::TAN, curve: SnapCurve::Circle { center: Vec2::ZERO, radius: 5.0 }, at: Vec2::new(3.0, 4.0) }; + s.input(Input::Deferred(tan)).unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify second point"); + s.cmdline("1,1").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "No tangent from that point. Specify another second point"); + assert!(s.running.is_some() && centers(&s) == [Vec2::new(20.0, 5.0)], "nothing moved and it asks again"); +} diff --git a/crates/engine/tests/it/mtext_columns.rs b/crates/engine/tests/it/mtext_columns.rs index 61420352a..d1fbff904 100644 --- a/crates/engine/tests/it/mtext_columns.rs +++ b/crates/engine/tests/it/mtext_columns.rs @@ -103,6 +103,7 @@ fn scale_scales_multileader_text_width_and_columns() { heights: vec![3.0, 4.0], flow_reversed: false, }), + background: None, }; let mut s = Session::new(); let ml = MLeader { diff --git a/crates/engine/tests/it/multiline_attributes.rs b/crates/engine/tests/it/multiline_attributes.rs index b7a7a7d0f..da2b20362 100644 --- a/crates/engine/tests/it/multiline_attributes.rs +++ b/crates/engine/tests/it/multiline_attributes.rs @@ -22,6 +22,8 @@ fn session() -> Session { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; let mtext = MText { insert: Vec3::new(10.0, 3.0, 0.0), @@ -34,6 +36,7 @@ fn session() -> Session { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let def = Attrib { tag: "LABEL".into(), diff --git a/crates/engine/tests/it/pick_text.rs b/crates/engine/tests/it/pick_text.rs index b0df6d8a3..157a7710d 100644 --- a/crates/engine/tests/it/pick_text.rs +++ b/crates/engine/tests/it/pick_text.rs @@ -103,7 +103,9 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, + xref_stamp: None, }; d.blocks.insert("*D1".into(), std::sync::Arc::new(block)); d.model.modify(dim, |e| { diff --git a/crates/engine/tests/it/properties_describe.rs b/crates/engine/tests/it/properties_describe.rs index 541dd5be9..824cd61b1 100644 --- a/crates/engine/tests/it/properties_describe.rs +++ b/crates/engine/tests/it/properties_describe.rs @@ -32,7 +32,7 @@ fn text_rows_share_values_and_vary() { let a = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 2.5 })).unwrap()); let b = handle(&s.execute("text", &json!({ "at": [0, 5], "text": "B", "height": 1, "justify": "MC" })).unwrap()); let one = describe(&mut s, json!({ "handles": [a] })); - assert_eq!(group_names(&one), ["General", "Text", "Geometry"]); + assert_eq!(group_names(&one), ["General", "Text", "Geometry", "Misc"]); let h = row(&one, "Text", "height"); assert_eq!((h["value"].as_f64(), h["display"].as_str(), h["kind"].as_str()), (Some(2.5), Some("2.5000"), Some("distance"))); assert_eq!(row(&one, "Text", "justify")["display"], "Left"); @@ -62,7 +62,7 @@ fn mixed_selections_show_general_rows_unless_filtered() { assert_eq!(row(&mixed, "General", "layer")["value"], "0"); let texts = describe(&mut s, json!({ "handles": [t, c], "type": "text" })); assert_eq!((texts["filter"].as_str(), texts["count"].as_u64()), (Some("Text"), Some(1))); - assert_eq!(group_names(&texts), ["General", "Text", "Geometry"]); + assert_eq!(group_names(&texts), ["General", "Text", "Geometry", "Misc"]); // An unknown filter describes everything. assert_eq!(describe(&mut s, json!({ "handles": [t, c], "type": "nope" }))["count"], 2); // Nothing selected, or handles that name nothing: no rows. diff --git a/crates/engine/tests/it/refedit.rs b/crates/engine/tests/it/refedit.rs index 0eb63c29f..3ea4a17bf 100644 --- a/crates/engine/tests/it/refedit.rs +++ b/crates/engine/tests/it/refedit.rs @@ -279,7 +279,7 @@ fn interactive_refedit_refset_and_refclose() { } #[test] -fn xrefs_are_refused_with_a_message() { +fn an_xref_that_is_not_loaded_is_refused_with_a_message() { let mut s = Session::new(); s.doc_mut().unwrap().blocks.insert( "X".into(), @@ -291,5 +291,6 @@ fn xrefs_are_refused_with_a_message() { ); let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0); let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err(); - assert!(e.to_string().contains("external reference"), "{e}"); + // Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be. + assert!(e.to_string().contains("not loaded"), "{e}"); } diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs new file mode 100644 index 000000000..91aad9e43 --- /dev/null +++ b/crates/engine/tests/it/refedit_xref.rs @@ -0,0 +1,1034 @@ +//! REFEDIT on xrefs and nested references (gap F2): the source drawing written back on REFCLOSE +//! Save (with a backup; refused for read-only, locked or changed files) and nesting levels. +//! Files go in a folder under Cargo's temporary directory for integration tests. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use cadcraft_engine::cmd::file::{IoHooks, Version, set_io, set_write_as}; +use cadcraft_engine::doc::geom::{Vec2, Vec3}; +use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, Insert, Layer, Line, XrefStatus}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn hooks() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + 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()) + }); +} + +/// A fresh folder for one test, removed when the test ends however it ends (a skip, a failed +/// assertion). +struct Folder(PathBuf); + +impl std::ops::Deref for Folder { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn folder(tag: &str) -> Folder { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("refedit-xref").join(format!("{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Folder(dir) +} + +fn save(d: &Drawing, path: &Path) { + std::fs::write(path, cadcraft_io::write(d, path).unwrap()).unwrap(); +} + +fn read(path: &Path) -> Drawing { + cadcraft_io::read(&std::fs::read(path).unwrap(), path).unwrap() +} + +fn line(d: &mut Drawing, layer: &str, a: (f64, f64), b: (f64, f64)) -> Handle { + let h = d.new_handle(); + let mut e = Entity::new(h, EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) })); + e.common.layer = layer.into(); + d.model.push(e); + h +} + +fn insert(block: &str, at: Vec3) -> Insert { + Insert { + block: block.into(), + insert: at, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + } +} + +/// A site plan: a line on layer Walls and a reference to its block Tree (a circle). +fn site() -> (Drawing, Handle) { + let mut d = Drawing::new_metric(); + d.layers.push(Layer { name: "Walls".into(), ..Layer::default() }); + let wall = line(&mut d, "Walls", (0.0, 0.0), (10.0, 0.0)); + let mut tree = Block::new("Tree"); + let c = d.new_handle(); + tree.entities.push(Entity::new(c, EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 }))); + d.blocks.insert("Tree".into(), Arc::new(tree)); + let h = d.new_handle(); + d.model.push(Entity::new(h, EntityKind::Insert(insert("Tree", Vec3::new(5.0, 0.0, 0.0))))); + (d, wall) +} + +/// A host drawing (saved as host.dxf) with site.dxf attached at (100, 0). +fn attached(tag: &str) -> (Session, Folder, Handle, String) { + hooks(); + let dir = folder(tag); + let (d, wall) = site(); + save(&d, &dir.join("site.dxf")); + let host = dir.join("host.dxf"); + save(&Drawing::new_metric(), &host); + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + let r = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap(); + let insert = r["handle"].as_str().unwrap().to_string(); + (s, dir, wall, insert) +} + +fn hx(v: Value) -> String { + v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_string() +} + +fn working(r: &Value) -> Vec { + r["working"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() +} + +fn find_line(s: &Session, hs: &[String]) -> String { + let d = s.doc().unwrap(); + hs.iter().find(|h| matches!(d.entity(Handle::parse_hex(h).unwrap()).unwrap().kind, EntityKind::Line(_))).unwrap().clone() +} + +#[test] +fn editing_an_xref_writes_its_drawing_back_with_a_backup() { + let (mut s, dir, wall, insert) = attached("save"); + let file = dir.join("site.dxf"); + // A layer of the host only, current for what is drawn during the edit. + s.execute("layer.new", &json!({ "name": "Added", "current": true })).unwrap(); + let r = s.execute("refedit", &json!({ "handle": insert })).unwrap(); + assert_eq!(r["xref"]["name"], "site"); + let work = working(&r); + assert_eq!(work.len(), 2); + // Everything but the working set is locked while editing, and drawn faded. + let l = find_line(&s, &work); + s.execute("move", &json!({ "handles": [l], "delta": [0, 5] })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(out["objects"], 3); + assert!(out.get("notSaved").is_none() && !s.log.iter().any(|m| m.contains("Not saved")), "the file keeps everything: no warning"); + assert!(out["file"].as_str().unwrap().ends_with("site.dxf")); + let bak = dir.join("site.dxf.bak"); + assert!(out["backup"].as_str().unwrap().ends_with("site.dxf.bak"), "{out}"); + assert_eq!(read(&bak).model.len(), 2, "the previous file is kept"); + // The file holds the edit, in its own coordinates, with the line's own handle. + let back = read(&file); + assert_eq!(back.model.len(), 3); + let moved = back.entity(wall).expect("the edited line keeps its handle"); + let EntityKind::Line(ln) = &moved.kind else { panic!() }; + assert!((ln.a.y - 5.0).abs() < 1e-9 && (ln.a.x).abs() < 1e-9, "{ln:?}"); + assert_eq!(moved.common.layer, "Walls", "the xref's layer loses its prefix"); + let new_line = back.model.iter().find(|e| matches!(&e.kind, EntityKind::Line(l) if (l.a.y - 20.0).abs() < 1e-9)).unwrap(); + assert_eq!(new_line.common.layer, "Added"); + assert!(back.layer("Added").is_some(), "a host layer the new line uses comes along"); + // The host shows the xref as written (loaded again), and nothing of the edit is left. + let d = s.doc().unwrap(); + assert!(d.refedit.is_none()); + assert_eq!(d.block("site").unwrap().entities.len(), 3); + assert_eq!(d.block("site").unwrap().xref_status, XrefStatus::Loaded); +} + +#[test] +fn a_block_of_the_xref_is_written_into_that_block() { + let (mut s, dir, _, insert) = attached("nested"); + let levels = s.execute("refedit.levels", &json!({ "handle": insert })).unwrap(); + let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["site", "site|Tree"]); + let r = s.execute("refedit", &json!({ "handle": insert, "nested": "site|Tree" })).unwrap(); + assert_eq!(r["block"], "site|Tree"); + assert_eq!(r["path"].as_array().unwrap().len(), 1); + assert!(r["faded"].as_u64().unwrap() >= 1, "the site's other objects stand faded around it"); + let c = working(&r)[0].clone(); + // The circle shows at the tree's place in the drawing: (100 + 5, 0). + let EntityKind::Circle(circle) = &s.doc().unwrap().entity(Handle::parse_hex(&c).unwrap()).unwrap().kind else { panic!() }; + assert!((circle.center.x - 105.0).abs() < 1e-9); + s.execute("scale", &json!({ "handles": [c], "base": [105, 0], "factor": 2 })).unwrap(); + s.execute("refclose", &json!({})).unwrap(); + let back = read(&dir.join("site.dxf")); + let EntityKind::Circle(c) = &back.block("Tree").unwrap().entities.iter().next().unwrap().kind else { panic!() }; + assert!((c.radius - 2.0).abs() < 1e-9); +} + +#[test] +fn locked_read_only_or_changed_files_are_not_overwritten() { + // A lock file of another program: refused at the start. + let (mut s, dir, _, insert) = attached("locked"); + let file = dir.join("site.dxf"); + std::fs::write(dir.join("site.dwl"), b"lock").unwrap(); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("open in another program"), "{e}"); + std::fs::remove_file(dir.join("site.dwl")).unwrap(); + + // Changed on disk while editing: the save is refused, the edit stays, Discard ends it. + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + let mut other = read(&file); + line(&mut other, "0", (0.0, 50.0), (1.0, 50.0)); + std::thread::sleep(std::time::Duration::from_millis(20)); + save(&other, &file); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("changed since"), "{e}"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); + assert_eq!(read(&file).model.len(), 3, "the other program's change is kept"); + + // Changed since it was loaded: reload first. + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("since") && e.contains("reload"), "{e}"); + s.execute("-xref", &json!({ "option": "reload", "names": "site" })).unwrap(); + + // Read-only: refused. + let mut perm = std::fs::metadata(&file).unwrap().permissions(); + perm.set_readonly(true); + std::fs::set_permissions(&file, perm.clone()).unwrap(); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("read-only"), "{e}"); + #[allow(clippy::permissions_set_readonly_false)] + perm.set_readonly(false); + std::fs::set_permissions(&file, perm).unwrap(); + + // Open in another drawing tab of this session: refused. + s.execute("qsave", &json!({})).unwrap(); + let host = s.state().unwrap().path.clone().unwrap(); + s.execute("open", &json!({ "path": file.to_string_lossy() })).unwrap(); + s.execute("open", &json!({ "path": host })).unwrap(); + let ih = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().handle; + let e = s.execute("refedit", &json!({ "handle": ih.hex() })).unwrap_err().to_string(); + assert!(e.contains("another drawing tab"), "{e}"); +} + +#[test] +fn nested_block_references_are_picked_through_their_parents() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Inner", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let i = hx(s.execute("insert", &json!({ "name": "Inner", "at": [10, 0] })).unwrap()); + let l = hx(s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()); + s.execute("block", &json!({ "name": "Outer", "base": [0, 0], "handles": [i, l], "keep": "delete" })).unwrap(); + let o = hx(s.execute("insert", &json!({ "name": "Outer", "at": [100, 100] })).unwrap()); + + // At the command line: pick, Next to the nested level, OK. + s.start("refedit").unwrap(); + s.input(Input::Pick(vec![Handle::parse_hex(&o).unwrap()])).unwrap(); + assert!(s.prompt_text().contains("Select nesting level"), "{}", s.prompt_text()); + assert!(s.log.iter().any(|m| m.contains("Reference name: Outer"))); + s.input(Input::Enter).unwrap(); // Next + assert!(s.log.iter().any(|m| m.contains("Reference name: Inner"))); + s.cmdline("o").unwrap(); + let d = s.doc().unwrap(); + let r = d.refedit.clone().unwrap(); + assert_eq!(r.block, "Inner"); + assert_eq!(r.items.len(), 1); + assert_eq!(r.ghosts.len(), 1, "Outer's line stands faded"); + let EntityKind::Circle(circle) = &d.entity(r.items[0].copy).unwrap().kind else { panic!() }; + assert!(circle.center.xy().near(Vec2::new(110.0, 100.0), 1e-9)); + // Only the working set can change: Outer's faded line is locked. + s.execute("move", &json!({ "handles": [r.items[0].copy.hex()], "delta": [0, 3] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Circle(c) = &d.block("Inner").unwrap().entities.iter().next().unwrap().kind else { panic!() }; + assert!(c.center.xy().near(Vec2::new(0.0, 3.0), 1e-9), "{c:?}"); + assert_eq!(d.block("Outer").unwrap().entities.len(), 2, "the parent is untouched"); + // Bad paths are refused. + assert!(s.execute("refedit", &json!({ "handle": o, "path": ["FFFFF"] })).is_err()); + assert!(s.execute("refedit", &json!({ "handle": o, "path": "x" })).is_err()); + assert!(s.execute("refedit", &json!({ "handle": o, "nested": "Nope" })).is_err()); + let _ = Vec2::ZERO; +} + +/// A symbolic link at `link` to `target`; `None` where the system doesn't let a test make one +/// (Windows without the privilege), and the test is skipped there. CI runs it on Linux. +fn symlink(target: &Path, link: &Path) -> Option<()> { + #[cfg(unix)] + let made = std::os::unix::fs::symlink(target, link); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_file(target, link); + #[cfg(not(any(unix, windows)))] + let made: std::io::Result<()> = Err(std::io::Error::other("no symbolic links")); + match made { + Ok(()) => Some(()), + Err(e) => { + eprintln!("skipped: symbolic links can't be made here ({e})"); + None + } + } +} + +fn is_plain_file(p: &Path) -> bool { + std::fs::symlink_metadata(p).is_ok_and(|m| m.is_file()) +} + +/// Review of #2355: a link planted at the temporary or backup path beside the xref must not take +/// the write (CWE-59). Before, the new bytes went into `victim.txt` through `site.dxf.cadcraft-tmp` +/// and `site.dxf` itself became that link. +#[test] +fn links_planted_beside_the_xref_are_not_written_through() { + let (mut s, dir, _, insert) = attached("planted"); + let file = dir.join("site.dxf"); + let (victim, other) = (dir.join("victim.txt"), dir.join("other.txt")); + std::fs::write(&victim, b"victim").unwrap(); + std::fs::write(&other, b"other").unwrap(); + if symlink(&victim, &dir.join("site.dxf.cadcraft-tmp")).is_none() { + return; + } + symlink(&other, &dir.join("site.dxf.bak")).unwrap(); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(std::fs::read(&victim).unwrap(), b"victim", "nothing is written through the planted link"); + assert_eq!(std::fs::read(&other).unwrap(), b"other", "nor through a link at the backup"); + assert!(is_plain_file(&file), "the xref's file is still a file, not a link"); + assert_eq!(read(&file).model.len(), 3, "and holds the edit"); + assert!(is_plain_file(&dir.join("site.dxf.bak")), "the link at the backup is replaced by the backup"); + assert_eq!(read(&dir.join("site.dxf.bak")).model.len(), 2); +} + +/// Review of #2355: the xref's own path turned into a link to another file during the edit (here +/// a byte-identical copy with the same time, so the change check can't tell) is not written. +#[test] +fn an_xref_path_turned_into_a_link_during_the_edit_is_not_written() { + let (mut s, dir, _, insert) = attached("swapped"); + let file = dir.join("site.dxf"); + let elsewhere = dir.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + let target = elsewhere.join("victim.dxf"); + if symlink(&file, &dir.join("probe")).is_none() { + return; + } + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let modified = std::fs::metadata(&file).unwrap().modified().unwrap(); + std::fs::copy(&file, &target).unwrap(); + std::fs::OpenOptions::new().write(true).open(&target).unwrap().set_modified(modified).unwrap(); + std::fs::rename(&file, dir.join("moved.dxf")).unwrap(); + symlink(&target, &file).unwrap(); + let before = std::fs::read(&target).unwrap(); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("leads to another file"), "{e}"); + assert_eq!(std::fs::read(&target).unwrap(), before, "the link's target is untouched"); + assert!(!elsewhere.join("victim.dxf.bak").exists() && !dir.join("site.dxf.bak").exists(), "no backup either"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); +} + +/// Review of #2355: `site.dxf` and `site.dwg` in one folder both used to back up to `site.bak`, +/// so editing one and then the other lost the first one's old copy. They keep their own now, named +/// as SAVE names them (`site.dxf.bak`, `site.bak`). +#[test] +fn xrefs_of_one_name_in_one_folder_keep_their_own_backups() { + // These files are our own: DWG is read and written in this process. + cadcraft_io::dwg_worker::allow_in_process(); + hooks(); + let dir = folder("two-backups"); + let (d, _) = site(); + let (dxf, dwg) = (dir.join("site.dxf"), dir.join("site.dwg")); + save(&d, &dxf); + save(&d, &dwg); + let (old_dxf, old_dwg) = (std::fs::read(&dxf).unwrap(), std::fs::read(&dwg).unwrap()); + let host = dir.join("host.dxf"); + save(&Drawing::new_metric(), &host); + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + for (path, name, x) in [("site.dxf", "a", 0), ("site.dwg", "b", 100)] { + let r = s.execute("xattach", &json!({ "path": path, "name": name, "at": [x, 0] })).unwrap(); + s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap(); + s.execute("line", &json!({ "points": [[x, 20], [x + 10, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + } + assert_eq!(std::fs::read(dir.join("site.dxf.bak")).unwrap(), old_dxf, "the DXF's previous file"); + assert_eq!(std::fs::read(dir.join("site.bak")).unwrap(), old_dwg, "the DWG's previous file"); + assert_eq!((read(&dxf).model.len(), read(&dwg).model.len()), (3, 3), "both hold their edit"); +} + +/// A host drawing (host.dxf in `dir`) with `file` of `dir` attached as xref `name` at (100, 0). +fn host_with(dir: &Path, file: &str, name: &str) -> (Session, String) { + let host = dir.join("host.dxf"); + save(&Drawing::new_metric(), &host); + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + let r = s.execute("xattach", &json!({ "path": file, "name": name, "at": [100, 0] })).unwrap(); + (s, r["handle"].as_str().unwrap().to_string()) +} + +/// The `$ACADVER` an ASCII DXF declares. +fn dxf_version(bytes: &[u8]) -> Option { + let text = String::from_utf8_lossy(bytes); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + lines.windows(3).find(|w| w[0] == "$ACADVER" && w[1] == "1").map(|w| w[2].to_string()) +} + +/// Review of #2355: the xref was saved in the writer's default version (an R2000 DWG came back +/// as 2004, AC1018). It is written back in the version, and form, it was read in. +#[test] +fn an_xref_is_written_back_in_the_version_it_was_read_in() { + // These files are our own: DWG is read and written in this process. + cadcraft_io::dwg_worker::allow_in_process(); + hooks(); + let dir = folder("versions"); + let (d, _) = site(); + let write = |name: &str, version: Version, binary: bool| { + let p = dir.join(name); + let opts = cadcraft_io::SaveOptions { version: Some(version), binary }; + std::fs::write(&p, cadcraft_io::write_with(&d, &p, &opts).unwrap()).unwrap(); + p + }; + let dwg = write("old.dwg", Version::R2000, false); + let dxf = write("old.dxf", Version::R2004, false); + let bin = write("bin.dxf", Version::R2010, true); + assert_eq!((&std::fs::read(&dwg).unwrap()[..6], dxf_version(&std::fs::read(&dxf).unwrap()).as_deref()), (&b"AC1015"[..], Some("AC1018"))); + for (file, name) in [("old.dwg", "a"), ("old.dxf", "b"), ("bin.dxf", "c")] { + let (mut s, insert) = host_with(&dir, file, name); + let r = s.execute("refedit", &json!({ "handle": insert })).unwrap(); + assert_eq!(r["xref"]["binary"], file == "bin.dxf", "{r}"); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + } + let (dwg_bytes, dxf_bytes, bin_bytes) = (std::fs::read(&dwg).unwrap(), std::fs::read(&dxf).unwrap(), std::fs::read(&bin).unwrap()); + assert_eq!(&dwg_bytes[..6], b"AC1015", "the R2000 DWG stays R2000"); + assert_eq!(dxf_version(&dxf_bytes).as_deref(), Some("AC1018"), "the 2004 DXF stays 2004"); + assert!(bin_bytes.starts_with(b"AutoCAD Binary DXF"), "the binary DXF stays binary"); + assert_eq!(read(&bin).header.get("ACADVER").and_then(cadcraft_engine::doc::HVal::as_str), Some("AC1024"), "and 2010"); + assert_eq!((read(&dwg).model.len(), read(&dxf).model.len(), read(&bin).model.len()), (3, 3, 3), "each holds its edit"); +} + +/// Review of #2355: an R12 DXF xref came back as an R2000 one. CADCraft doesn't write R12, so the +/// edit is refused before it begins (no work lost), and the file is left as it is. +#[test] +fn an_xref_in_a_version_cadcraft_cannot_write_is_not_edited_in_place() { + hooks(); + let dir = folder("r12"); + let r12 = "0 +SECTION +2 +HEADER +9 +$ACADVER +1 +AC1009 +0 +ENDSEC +0 +SECTION +2 +ENTITIES +0 +LINE +8 +0 +10 +0 +20 +0 +11 +1 +21 +1 +0 +ENDSEC +0 +EOF +"; + std::fs::write(dir.join("r12.dxf"), r12).unwrap(); + let (mut s, insert) = host_with(&dir, "r12.dxf", "old"); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("AC1009") && e.contains("XOPEN"), "{e}"); + assert!(s.doc().unwrap().refedit.is_none()); + assert_eq!(std::fs::read_to_string(dir.join("r12.dxf")).unwrap(), r12, "the file is untouched"); +} + +/// Review of #2355: SAVE says what a file can't keep; the write-back said nothing. A 2013 DXF xref +/// holding a solid whose ACIS geometry is SAT text (no data store record) loses it when written: +/// the save says so, names it in `notSaved`, and points at the backup that still has it. +#[test] +fn what_the_xref_file_cannot_keep_is_reported() { + hooks(); + let dir = folder("lost"); + let dxf = "0 +SECTION +2 +HEADER +9 +$ACADVER +1 +AC1027 +0 +ENDSEC +0 +SECTION +2 +ENTITIES + 0 +LINE +5 +20 +8 +0 +10 +0 +20 +0 +11 +1 +21 +1 + 0 +3DSOLID +5 +21 +100 +AcDbEntity +8 +0 +100 +AcDbModelerGeometry +70 +1 +1 +400 0 1 0 + 0 +ENDSEC +0 +EOF +"; + std::fs::write(dir.join("solid.dxf"), dxf).unwrap(); + let (mut s, insert) = host_with(&dir, "solid.dxf", "solid"); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(out["notSaved"], json!({ "3DSOLID": 1 }), "{out}"); + let warning = s.log.iter().find(|m| m.contains("Not saved in the DXF file")).expect("a warning on the command line"); + assert!(warning.contains("1 3DSOLID") && warning.contains("solid.dxf.bak"), "{warning}"); + assert!(std::fs::read_to_string(dir.join("solid.dxf.bak")).unwrap().contains("3DSOLID"), "the backup still has it"); +} + +/// Review of #2355: a reference nested with different X and Y scales was offered as a level, and +/// OK then refused it. It isn't offered (nor anything below it); a uniformly scaled one is. +#[test] +fn nested_references_refedit_cannot_open_are_not_offered() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Leaf", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let uniform = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [10, 0], "scale": 2 })).unwrap()); + let stretched = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [20, 0], "scale": [2, 1] })).unwrap()); + s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [uniform, stretched], "keep": "delete" })).unwrap(); + let o = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0] })).unwrap()); + let levels = s.execute("refedit.levels", &json!({ "handle": o })).unwrap(); + let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Holder", "Leaf"], "{levels}"); + // The one offered opens. + let path = levels["levels"][1]["path"].clone(); + s.execute("refedit", &json!({ "handle": o, "path": path })).unwrap(); +} + +/// Review of #2355: the faded copies carried XFADECTL in their own transparency, so lowering +/// XFADECTL during the edit left them faded. They keep the object's own transparency now; the +/// fade is drawn from the current XFADECTL. +#[test] +fn faded_copies_keep_their_own_transparency() { + let mut s = Session::new(); + let a = hx(s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()); + let b = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Pair", "base": [0, 0], "handles": [a, b], "keep": "delete" })).unwrap(); + let i = hx(s.execute("insert", &json!({ "name": "Pair", "at": [0, 0] })).unwrap()); + let d = s.doc().unwrap(); + let blk = d.block("Pair").unwrap(); + let line = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle; + let own = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::Circle(_))).unwrap().common.transparency; + s.execute("refedit", &json!({ "handle": i, "objects": [line.hex()] })).unwrap(); + let d = s.doc().unwrap(); + let r = d.refedit.clone().unwrap(); + let ghost = d.entity(r.ghosts[0].0).unwrap(); + assert_eq!(ghost.common.transparency, own, "the circle's copy is faded by the renderer, not by its own transparency"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); +} + +/// Review of #2355: the xref's file opened in another tab after the edit began was overwritten +/// by REFCLOSE Save; the save is refused while it is open there. +#[test] +fn an_xref_opened_in_another_tab_during_the_edit_is_not_written() { + let (mut s, dir, _, insert) = attached("tab-later"); + let file = dir.join("site.dxf"); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let host = s.active; + s.execute("open", &json!({ "path": file.to_string_lossy() })).unwrap(); + s.execute("document.switch", &json!({ "index": host })).unwrap(); + let before = std::fs::read(&file).unwrap(); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("another drawing tab"), "{e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the file is untouched"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); +} + +/// Review of #2355: the "loaded" stamp was one per file for the whole process, so a second drawing +/// loading the xref later moved the first drawing's baseline. Here the file changes (same objects, +/// moved) after the first drawing loaded it: that drawing still shows the old geometry, and REFEDIT +/// there must refuse rather than pair the old geometry with the new file. +#[test] +fn each_drawing_keeps_its_own_xref_baseline() { + let (mut first, dir, _, insert) = attached("baseline"); + let file = dir.join("site.dxf"); + let mut moved = read(&file); + let h = moved.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle; + moved + .modify_entity(h, |e| { + if let EntityKind::Line(l) = &mut e.kind { + l.b.y += 1.0; + } + }) + .unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + save(&moved, &file); + // Another drawing loads the changed file. + let other_host = dir.join("other.dxf"); + save(&Drawing::new_metric(), &other_host); + let mut second = Session::new(); + second.execute("open", &json!({ "path": other_host.to_string_lossy() })).unwrap(); + let r = second.execute("xattach", &json!({ "path": "site.dxf", "at": [0, 0] })).unwrap(); + second.execute("refedit", &json!({ "handle": r["handle"] })).unwrap(); + second.execute("refclose", &json!({ "option": "discard" })).unwrap(); + // The first drawing loaded the earlier file. + let e = first.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("changed since") && e.contains("reload"), "{e}"); +} + +/// Review of #2355: multileader and table styles of the host that objects drawn during the edit +/// use were not copied into the xref's file, so they lost their style there. +#[test] +fn host_multileader_and_table_styles_come_along() { + let (mut s, dir, _, insert) = attached("styles"); + s.execute("mleaderstyle", &json!({ "name": "Callout", "textHeight": 7, "current": true })).unwrap(); + s.execute("tablestyle", &json!({ "name": "Schedule", "textHeight": 4, "current": true })).unwrap(); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("mleader", &json!({ "points": [[100, 30], [110, 40]], "text": "A" })).unwrap(); + s.execute("table", &json!({ "at": [120, 30], "rows": 1, "cols": 1 })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let back = read(&dir.join("site.dxf")); + let mleader = back.model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { Some(m.style.clone()) } else { None }).unwrap(); + let table = back.model.iter().find_map(|e| if let EntityKind::Table(t) = &e.kind { Some(t.style.clone()) } else { None }).unwrap(); + assert_eq!((mleader.as_str(), table.as_str()), ("Callout", "Schedule")); + let ml = back.mleader_styles.iter().find(|t| t.name == "Callout").expect("the multileader style is in the file"); + assert!((ml.text_height - 7.0).abs() < 1e-9); + let ts = back.table_styles.iter().find(|t| t.name == "Schedule").expect("the table style is in the file"); + assert!((ts.text_height - 4.0).abs() < 1e-9); +} + +/// Automation roots (#1472): an agent confined to its folders can't have REFCLOSE write an xref, or +/// the xref's `.bak`, outside its write root, and can't start an edit in place of one it may not +/// write. The refusals leave the xref, its backup and the host as they were. +#[test] +fn a_confined_session_does_not_write_an_xref_outside_its_write_root() { + use cadcraft_engine::file_access::{AutomationRoots, confine}; + let (mut s, dir, _, insert) = attached("confined"); + let file = dir.join("site.dxf"); + let before = std::fs::read(&file).unwrap(); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + // The xref's folder may be read but not written. + let roots = AutomationRoots::new(Some(&dir), Some(&out)).unwrap(); + + // REFEDIT of an xref it couldn't save is refused before the edit begins. + let e = confine(roots.as_ref(), || s.execute("refedit", &json!({ "handle": insert }))).unwrap_err().to_string(); + assert!(e.contains("outside") || e.contains("write"), "{e}"); + assert!(s.doc().unwrap().refedit.is_none(), "no edit began"); + + // An edit begun without the roots isn't written once they are in force. + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let e = confine(roots.as_ref(), || s.execute("refclose", &json!({ "option": "save" }))).unwrap_err().to_string(); + assert!(e.contains("outside") || e.contains("write"), "{e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the xref is unchanged"); + assert!(std::fs::symlink_metadata(dir.join("site.dxf.bak")).is_err(), "no backup was written"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + assert_eq!(s.doc().unwrap().block("site").unwrap().entities.len(), 2, "the host still shows the xref as it was"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); + + // Roots that don't reach the xref's folder: it isn't read for an edit either. + let elsewhere = dir.join("elsewhere"); + std::fs::create_dir_all(elsewhere.join("out")).unwrap(); + let roots = AutomationRoots::new(Some(&elsewhere), Some(&elsewhere.join("out"))).unwrap(); + let e = confine(roots.as_ref(), || s.execute("refedit", &json!({ "handle": insert }))).unwrap_err().to_string(); + assert!(s.doc().unwrap().refedit.is_none(), "no edit began: {e}"); + assert_eq!(std::fs::read(&file).unwrap(), before); +} + +/// The write-back reports what a file can't keep as SAVE does (`lost_writing`), not only solids +/// in a 2013 DXF: an R2000 DXF xref has no place for a proxy's separate strings (#3229), so the +/// save names the proxy it leaves out, with the DXF's reason and the backup that keeps it. +#[test] +fn a_proxy_an_r2000_dxf_xref_cannot_keep_is_reported() { + hooks(); + let dir = folder("proxy"); + let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n20\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nACAD_PROXY_ENTITY\n5\n21\n100\nAcDbEntity\n8\n0\n100\nAcDbProxyEntity\n90\n498\n91\n500\n162\n8\n161\n16\n310\nAABB\n0\nENDSEC\n0\nEOF\n"; + std::fs::write(dir.join("proxy.dxf"), dxf).unwrap(); + let (mut s, insert) = host_with(&dir, "proxy.dxf", "proxy"); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(out["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "{out}"); + let warning = s.log.iter().find(|m| m.contains("Not saved in the DXF file")).expect("a warning on the command line"); + assert!(warning.contains("before 2007") && warning.contains("1 ACAD_PROXY_ENTITY") && warning.contains("proxy.dxf.bak"), "{warning}"); +} + +/// Review of #2355: a reference to another xref of the host, added to the working set with +/// REFSET, would be written into the xref's drawing naming a block that drawing doesn't define. +/// The save is refused instead; the file, its backup and the edit stay as they were. +#[test] +fn a_reference_to_another_xref_of_the_host_is_not_written_into_the_xref() { + let (mut s, dir, _, insert) = attached("other-xref"); + let (other, _) = site(); + save(&other, &dir.join("other.dxf")); + let r = s.execute("xattach", &json!({ "path": "other.dxf", "at": [0, 100] })).unwrap(); + let other_insert = r["handle"].as_str().unwrap().to_string(); + let file = dir.join("site.dxf"); + let before = std::fs::read(&file).unwrap(); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("refset", &json!({ "add": [other_insert] })).unwrap(); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("\"other\""), "{e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the xref is unchanged"); + assert!(std::fs::symlink_metadata(dir.join("site.dxf.bak")).is_err(), "no backup was written"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); +} + +/// A dimension drawn during the edit with a host dimension style whose arrowhead is a block of +/// the host: the block comes along with the style, so the xref's drawing defines what it names. +#[test] +fn a_host_dimension_styles_arrow_block_comes_along() { + let (mut s, dir, _, insert) = attached("arrow-block"); + { + let d = s.doc_mut().unwrap(); + let mut pin = Block::new("Pin"); + let h = d.new_handle(); + pin.entities.push(Entity::new(h, EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 0.5 }))); + d.blocks.insert("Pin".into(), Arc::new(pin)); + d.dim_styles.push(cadcraft_engine::doc::DimStyle { name: "Pinned".into(), arrow_block: "Pin".into(), ..Default::default() }); + d.header.set_str("DIMSTYLE", "Pinned"); + } + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("dimlinear", &json!({ "p1": [100, 30], "p2": [110, 30], "at": [105, 40] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let back = read(&dir.join("site.dxf")); + assert_eq!(back.dim_style("Pinned").expect("the style comes along").arrow_block, "Pin"); + assert!(back.block("Pin").is_some(), "and the block its arrowheads are"); +} + +/// Whether `d`'s model holds a dimension attached to the objects it measures. +fn associative_dimensions(d: &Drawing) -> usize { + d.model.iter().filter(|e| matches!(&e.kind, EntityKind::Dimension(dm) if !dm.assoc.is_empty())).count() +} + +/// Review of #2355: loading an xref drops its dimensions' associations, so the write-back leaves +/// them out of the file. Until that is kept, the save says so, as for anything else the file +/// can't keep, and names the backup that still has them. A dimension drawn during the edit +/// attaches to the host's copies, whose handles mean nothing in the xref's file: it is written +/// without them, and counted too. +#[test] +fn dimension_associations_the_write_back_drops_are_reported() { + hooks(); + let dir = folder("assoc"); + let mut src = Session::new(); + src.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + src.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 5] })).unwrap(); + let file = dir.join("dims.dxf"); + src.execute("saveas", &json!({ "path": file.to_string_lossy() })).unwrap(); + assert_eq!(associative_dimensions(&read(&file)), 1, "the file has an associative dimension"); + + let (mut s, insert) = host_with(&dir, "dims.dxf", "dims"); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + // On the copy of the line, at (100, 0)..(110, 0) in the host. + s.execute("dimlinear", &json!({ "p1": [100, 0], "p2": [110, 0], "at": [105, -5] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(out["notSaved"]["dimension associations"], 2, "{out}"); + let warning = s.log.iter().find(|m| m.contains("dimension associations")).expect("a warning on the command line"); + assert!(warning.contains("dims.dxf.bak"), "{warning}"); + let back = read(&file); + assert_eq!(associative_dimensions(&back), 0, "{:?}", back.model.iter().map(|e| &e.kind).collect::>()); + assert_eq!(associative_dimensions(&read(&dir.join("dims.dxf.bak"))), 1, "the backup keeps them"); +} + +/// Review of #2355 (follow-up): a nested reference is offered only when the reference with +/// everything above it can be opened. Each of two uniform scales of 0.0001 is fine alone, but +/// together they flatten the inner block past what REFEDIT opens, so it isn't offered. +#[test] +fn a_nested_reference_too_small_with_its_parents_is_not_offered() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Leaf", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let tiny = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [0, 0], "scale": 0.0001 })).unwrap()); + let l = hx(s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap()); + s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [tiny, l], "keep": "delete" })).unwrap(); + let o = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0], "scale": 0.0001 })).unwrap()); + let levels = s.execute("refedit.levels", &json!({ "handle": o })).unwrap(); + let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Holder"], "{levels}"); +} + +/// Review of #3352: the outer reference wasn't checked when listing levels, so one scaled (2, 1) +/// offered the uniformly scaled reference nested in it, which REFEDIT then refused. An outer +/// reference REFEDIT can't open offers no level; one scaled equally still offers its children. +#[test] +fn an_outer_reference_refedit_cannot_open_offers_no_nested_level() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Leaf", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let leaf = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [10, 0] })).unwrap()); + s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [leaf], "keep": "delete" })).unwrap(); + let stretched = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0], "scale": [2, 1] })).unwrap()); + let e = s.execute("refedit.levels", &json!({ "handle": stretched })).unwrap_err().to_string(); + assert!(e.contains("scaled equally"), "{e}"); + let e = s.execute("refedit", &json!({ "handle": stretched, "nested": "Leaf" })).unwrap_err().to_string(); + assert!(e.contains("scaled equally"), "{e}"); + let uniform = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 50], "scale": 2 })).unwrap()); + let levels = s.execute("refedit.levels", &json!({ "handle": uniform })).unwrap(); + let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Holder", "Leaf"], "{levels}"); +} + +/// Review of #3352: an associative dimension of the xref erased during the edit was still +/// reported as written without its associations. Only dimensions that are written count. +#[test] +fn an_associative_dimension_erased_during_the_edit_is_not_reported() { + hooks(); + let dir = folder("assoc-erased"); + let mut src = Session::new(); + src.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + src.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 5] })).unwrap(); + let file = dir.join("dims.dxf"); + src.execute("saveas", &json!({ "path": file.to_string_lossy() })).unwrap(); + assert_eq!(associative_dimensions(&read(&file)), 1, "the file has an associative dimension"); + + let (mut s, insert) = host_with(&dir, "dims.dxf", "dims"); + let r = s.execute("refedit", &json!({ "handle": insert })).unwrap(); + let d = s.doc().unwrap(); + let dim = working(&r).into_iter().find(|h| matches!(d.entity(Handle::parse_hex(h).unwrap()).unwrap().kind, EntityKind::Dimension(_))).unwrap(); + s.execute("erase", &json!({ "handles": [dim] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert!(out.get("notSaved").is_none(), "{out}"); + assert!(!s.log.iter().any(|m| m.contains("dimension associations")), "{:?}", s.log); + assert!(!read(&file).model.iter().any(|e| matches!(e.kind, EntityKind::Dimension(_))), "the dimension is gone from the file"); +} + +/// Review of #3352: the write-back refuses a block name the edit brings in that the xref's drawing +/// doesn't define. A reference the file already had to a block it doesn't define is not the edit's +/// doing: the save goes ahead and keeps it as it was. +#[test] +fn a_dangling_reference_the_xref_file_already_had_is_saved_as_it_was() { + hooks(); + let dir = folder("dangling"); + let (mut d, _) = site(); + let h = d.new_handle(); + d.model.push(Entity::new(h, EntityKind::Insert(insert("Ghost", Vec3::new(3.0, 3.0, 0.0))))); + let file = dir.join("ghost.dxf"); + save(&d, &file); + let before = read(&file); + assert!(before.block("Ghost").is_none() && before.entity(h).is_some(), "the file names a block it doesn't define"); + let (mut s, ins) = host_with(&dir, "ghost.dxf", "ghost"); + s.execute("refedit", &json!({ "handle": ins })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let back = read(&file); + assert_eq!(back.model.len(), before.model.len() + 1, "the edit is written"); + let EntityKind::Insert(i) = &back.entity(h).expect("the reference is kept").kind else { panic!() }; + assert_eq!((i.block.as_str(), i.insert), ("Ghost", Vec3::new(3.0, 3.0, 0.0)), "as it was"); + assert!(back.block("Ghost").is_none(), "and nothing is made up for it"); +} + +/// Review of #3352: a host linetype copied into the xref's drawing came without the text style its +/// text elements name, so the file named a style it doesn't define. The style comes along. +#[test] +fn a_host_linetype_brings_the_text_styles_its_dashes_use() { + use cadcraft_engine::doc::{DashElement, Linetype, TextStyle}; + let (mut s, dir, _, insert) = attached("ltype-style"); + { + let d = s.doc_mut().unwrap(); + d.text_styles.push(TextStyle { name: "Marks".into(), ..TextStyle::default() }); + let mut text = DashElement::dash(0.0); + text.text = Some("G".into()); + text.style = Some("Marks".into()); + let pattern = vec![DashElement::dash(5.0), DashElement::dash(-1.0), text, DashElement::dash(-1.0)]; + d.linetypes.push(Linetype { name: "Gas".into(), description: "Gas ---- G ----".into(), pattern }); + } + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + let l = Handle::parse_hex(&hx(s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap())).unwrap(); + s.doc_mut().unwrap().modify_entity(l, |e| e.common.linetype = "Gas".into()).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let back = read(&dir.join("site.dxf")); + let gas = back.linetype("Gas").expect("the linetype is in the file"); + assert!(gas.pattern.iter().any(|e| e.style.as_deref().is_some_and(|n| n.eq_ignore_ascii_case("Marks"))), "{gas:?}"); + assert!(back.text_style("Marks").is_some(), "and the text style it uses"); +} + +/// The xref valve.dxf (a site plan, plus a block Valve: a line) attached as "plant" to a new host +/// in `dir`, with `valve` (given the file as read) as the host's own block Valve and a reference +/// to it at (120, 30). Returns the session, the xref's reference and the host's Valve reference. +fn host_with_its_own_valve(dir: &Path, valve: impl FnOnce(&Drawing) -> Block) -> (Session, String, String) { + let (mut d, _) = site(); + let mut b = Block::new("Valve"); + let h = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(2.0, 0.0, 0.0) }))); + d.blocks.insert("Valve".into(), Arc::new(b)); + save(&d, &dir.join("valve.dxf")); + let (mut s, ins) = host_with(dir, "valve.dxf", "plant"); + let own = valve(&read(&dir.join("valve.dxf"))); + s.doc_mut().unwrap().blocks.insert("Valve".into(), Arc::new(own)); + let v = s.execute("insert", &json!({ "name": "Valve", "at": [120, 30] })).unwrap(); + (s, ins, hx(v)) +} + +/// Review of #3352: the host and the xref's drawing both define a block Valve, differently. A +/// reference to the host's Valve added with REFSET was written under that name, so in the file it +/// showed the file's Valve. The save is refused, naming the block; nothing is written. +#[test] +fn a_host_block_that_differs_from_the_xrefs_block_of_that_name_is_not_written() { + hooks(); + let dir = folder("valve-differs"); + let (mut s, ins, v) = host_with_its_own_valve(&dir, |_| { + let mut b = Block::new("Valve"); + b.entities.push(Entity::new(Handle(0x500), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 }))); + b + }); + let file = dir.join("valve.dxf"); + let before = std::fs::read(&file).unwrap(); + s.execute("refedit", &json!({ "handle": ins })).unwrap(); + s.execute("refset", &json!({ "add": [v] })).unwrap(); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("\"Valve\""), "{e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the xref is unchanged"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); +} + +/// Review of #3352: a host block defined exactly as the xref's block of that name is the same +/// block: a reference to it is written, naming the file's own definition. +#[test] +fn a_host_block_identical_to_the_xrefs_block_of_that_name_is_written() { + hooks(); + let dir = folder("valve-same"); + let (mut s, ins, v) = host_with_its_own_valve(&dir, |file| (**file.block("Valve").unwrap()).clone()); + s.execute("refedit", &json!({ "handle": ins })).unwrap(); + s.execute("refset", &json!({ "add": [v] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let back = read(&dir.join("valve.dxf")); + assert!(back.model.iter().any(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block == "Valve")), "the reference is written"); + let valve = back.block("Valve").unwrap(); + assert_eq!(valve.entities.len(), 1); + assert!(matches!(valve.entities.iter().next().unwrap().kind, EntityKind::Line(_)), "the file's Valve is unchanged"); +} + +/// Review of #3352: REFEDIT on a reference with several columns or rows (one object, many +/// instances) opened the first instance and hid them all. It is refused, saying why; nested in a +/// block, such a reference isn't offered as a level. +#[test] +fn a_reference_with_several_columns_or_rows_is_not_edited_in_place() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Leaf", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let grid = |s: &mut Session, at: [f64; 2], cols: u32, rows: u32| { + let h = Handle::parse_hex(&hx(s.execute("insert", &json!({ "name": "Leaf", "at": at })).unwrap())).unwrap(); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + (i.cols, i.rows, i.col_spacing, i.row_spacing) = (cols, rows, 5.0, 5.0); + } + }) + .unwrap(); + h.hex() + }; + for (cols, rows) in [(3, 1), (1, 2)] { + let h = grid(&mut s, [0.0, 0.0], cols, rows); + let e = s.execute("refedit", &json!({ "handle": h })).unwrap_err().to_string(); + assert!(e.contains("columns or rows"), "{e}"); + let d = s.doc().unwrap(); + assert!(d.refedit.is_none() && d.entity(Handle::parse_hex(&h).unwrap()).unwrap().common.visible, "nothing began, nothing hidden"); + } + // Nested: not offered, and refused through a path. + let multi = grid(&mut s, [10.0, 0.0], 2, 2); + let one = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [50, 0] })).unwrap()); + s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [multi, one], "keep": "delete" })).unwrap(); + let o = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0] })).unwrap()); + let levels = s.execute("refedit.levels", &json!({ "handle": o })).unwrap(); + assert_eq!(levels["levels"].as_array().unwrap().len(), 2, "Holder and the single Leaf: {levels}"); + let inner = + s.doc().unwrap().block("Holder").unwrap().entities.iter().find(|e| matches!(&e.kind, EntityKind::Insert(i) if i.cols > 1)).unwrap().handle; + let e = s.execute("refedit", &json!({ "handle": o, "path": [inner.hex()] })).unwrap_err().to_string(); + assert!(e.contains("columns or rows"), "{e}"); +} + +/// Review of #3352: a file dated before 1970 had no stamp (its time was counted from 1970), so it +/// always looked changed and REFEDIT refused it even after a reload. The time is kept as it is. +#[test] +fn an_xref_file_dated_before_1970_can_be_edited_in_place() { + let (mut s, dir, _, insert) = attached("pre-1970"); + let file = dir.join("site.dxf"); + let old = std::time::UNIX_EPOCH - std::time::Duration::from_secs(10 * 365 * 86_400); + let set = std::fs::OpenOptions::new().write(true).open(&file).and_then(|f| f.set_modified(old)); + if set.is_err() || std::fs::metadata(&file).and_then(|m| m.modified()).ok() != Some(old) { + eprintln!("skipped: this file system doesn't keep a time before 1970 ({set:?})"); + return; + } + s.execute("-xref", &json!({ "option": "reload", "names": "site" })).unwrap(); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(read(&file).model.len(), 3, "the edit is written"); +} + +/// Review of #3352: UNDO after a saved REFCLOSE brought the edit back, with the file's stamp from +/// before the save, so it could never be saved again. The save is an undo barrier: UNDO says the +/// edit was saved to its file and leaves the drawing as saved. A discarded edit still comes back. +#[test] +fn undo_after_a_saved_xref_edit_does_not_bring_the_edit_back() { + let (mut s, dir, _, insert) = attached("undo-saved"); + let file = dir.join("site.dxf"); + s.execute("line", &json!({ "points": [[0, 50], [10, 50]] })).unwrap(); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); + s.execute("undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().refedit.is_some(), "a discarded edit comes back with UNDO"); + + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let saved = std::fs::read(&file).unwrap(); + let e = s.execute("undo", &json!({})).unwrap_err().to_string(); + assert!(e.contains("saved to") && e.contains("site.dxf"), "{e}"); + let d = s.doc().unwrap(); + assert!(d.refedit.is_none(), "the edit doesn't come back"); + assert_eq!(d.block("site").unwrap().entities.len(), 3, "the host shows the xref as saved"); + assert_eq!(std::fs::read(&file).unwrap(), saved, "the file is as saved"); + // The xref can be edited and saved again. + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 30], [110, 30]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(read(&file).model.len(), 4); +} diff --git a/crates/engine/tests/it/rename_cmdline.rs b/crates/engine/tests/it/rename_cmdline.rs index 952d9dec9..dc5a426f4 100644 --- a/crates/engine/tests/it/rename_cmdline.rs +++ b/crates/engine/tests/it/rename_cmdline.rs @@ -82,6 +82,17 @@ fn rename_prompts_type_old_and_new_name() { assert!(s.running.is_none(), "{}", s.prompt_text()); assert!(s.log[n..].iter().any(|l| l.contains("Renaming a material is not available yet.")), "{:?}", &s.log[n..]); assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 2); + + // VPort configuration rename + s.doc_mut().unwrap().vports.push(cadcraft_doc::VportConfig { name: "MyVP".into(), tiles: vec![] }); + s.script("-RENAME VP MyVP NewVP\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let d = s.doc().unwrap(); + assert!(d.vports.iter().any(|v| v.name == "NewVP")); + assert!(!d.vports.iter().any(|v| v.name == "MyVP")); + + // Cannot rename *Active viewport configuration + assert!(s.execute("rename", &json!({ "table": "vport", "from": "*Active", "to": "Active2" })).is_err()); } /// What `script` adds to the log; the command has ended. diff --git a/crates/engine/tests/it/revcloud_recognised.rs b/crates/engine/tests/it/revcloud_recognised.rs new file mode 100644 index 000000000..31f8168b7 --- /dev/null +++ b/crates/engine/tests/it/revcloud_recognised.rs @@ -0,0 +1,85 @@ +//! Readers recognise a saved revision cloud (#1570): a closed polyline with `RevcloudProps` +//! xdata whose every arc has bulge 0.520567 (they accept 0.02 either way; 0.5 was just outside). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Drawing, EntityKind, Handle, RawTag}; +use serde_json::{Value, json}; + +const BULGE: f64 = 0.520567050552; + +fn h(v: &Value) -> Handle { + v["handle"].as_str().and_then(Handle::parse_hex).unwrap() +} + +fn last(s: &Session) -> Handle { + s.doc().unwrap().model.iter().last().map(|e| e.handle).unwrap() +} + +/// Types `lines` at the command line and returns the one entity that run created. The prompt +/// sequence must have finished: a stale script leaves a prompt waiting, and `last` would then be +/// the previous entity, whose XDATA this test would wrongly accept. Counts new handles, not +/// entities: Object mode erases the picked shape as it adds the cloud. +fn typed_cloud(s: &mut Session, lines: &[&str]) -> Handle { + let before: Vec = s.doc().unwrap().model.iter().map(|e| e.handle).collect(); + for l in lines { + s.cmdline(l).unwrap(); + } + assert!(!s.prompting(), "{lines:?} left a prompt waiting: {}", s.prompt_text()); + let new: Vec = s.doc().unwrap().model.iter().map(|e| e.handle).filter(|h| !before.contains(h)).collect(); + assert_eq!(new.len(), 1, "{lines:?} must create exactly one entity, got {new:?}"); + assert_eq!(last(s), new[0], "{lines:?}: the new cloud must be the last entity"); + new[0] +} + +fn props(xdata: &[RawTag]) -> Vec<(i32, String)> { + let start = xdata.iter().position(|t| t.code == 1001 && t.value == "RevcloudProps").expect("RevcloudProps xdata"); + xdata[start..].iter().take_while(|t| t.code != 1001 || t.value == "RevcloudProps").map(|t| (t.code, t.value.trim().to_string())).collect() +} + +/// The cloud `h` is what readers take for a cloud: closed, cloud bulges, `RevcloudProps`. +fn assert_cloud(d: &Drawing, h: Handle, arc_len: f64) { + let e = d.entity(h).unwrap(); + let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) }; + assert!(p.closed); + assert!(p.vertices.iter().all(|v| (v.bulge.abs() - BULGE).abs() < 1e-9), "{:?}", p.vertices); + let x = props(&e.common.xdata); + assert_eq!(x.len(), 3, "{x:?}"); + assert_eq!(x[1], (1070, "0".to_string())); + assert_eq!(x[2].0, 1040); + assert!((x[2].1.parse::().unwrap() - arc_len).abs() < 1e-12, "{x:?}"); +} + +#[test] +fn every_way_of_drawing_a_cloud_is_recognised() { + let mut s = Session::new(); + let rect = h(&s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 15})).unwrap()); + let poly = h(&s.execute("revcloud.polygonal", &json!({"points": [[0, 0], [0, 30], [30, 0]], "arcLength": 5})).unwrap()); + let rev = h(&s.execute("revcloud.freehand", &json!({"freehand": [[0, 0], [50, 0], [50, 50]], "arcLength": 10, "reverse": true})).unwrap()); + let circle = h(&s.execute("circle", &json!({"center": [200, 0], "radius": 20})).unwrap()); + let obj = h(&s.execute("revcloud", &json!({"handle": circle, "arcLength": 4})).unwrap()); + // Arc length asks the minimum and then the maximum (#1714). + let typed = typed_cloud(&mut s, &["revcloud a 2 2", "300,0 320,10"]); + s.execute("rectang", &json!({"p1": [400, 0], "p2": [420, 20]})).unwrap(); + // Object then asks "Reverse direction" after the pick. + let picked = typed_cloud(&mut s, &["revcloud a 3 3 o 400,10 n"]); + let d = s.doc().unwrap(); + for (h, a) in [(rect, 15.0), (poly, 5.0), (rev, 10.0), (obj, 4.0), (typed, 2.0), (picked, 3.0)] { + assert_cloud(d, h, a); + } + let EntityKind::LwPolyline(p) = &d.entity(rev).unwrap().kind else { panic!() }; + assert!(p.vertices.iter().all(|v| v.bulge < 0.0), "a reversed cloud keeps its arcs turned inward"); +} + +#[test] +fn a_saved_cloud_reads_back_as_a_cloud() { + let mut s = Session::new(); + s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 15})).unwrap(); + let text = cadcraft_io::write_dxf(s.doc().unwrap()); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let appid = lines.windows(2).any(|w| w[0] == "0" && w[1] == "APPID") + && lines.windows(4).any(|w| w[0] == "AcDbRegAppTableRecord" && w[1] == "2" && w[2] == "RevcloudProps"); + assert!(appid, "RevcloudProps is a registered application"); + let read = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let cloud = read.model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap(); + assert_cloud(&read, cloud, 15.0); +} diff --git a/crates/engine/tests/it/scale_zero_factor.rs b/crates/engine/tests/it/scale_zero_factor.rs new file mode 100644 index 000000000..3bcd857ea --- /dev/null +++ b/crates/engine/tests/it/scale_zero_factor.rs @@ -0,0 +1,26 @@ +//! SCALE: a factor point on the base point is rejected and the prompt stays (#3475). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; + +fn length(s: &Session) -> f64 { + s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.a.xy().dist(l.b.xy())) } else { None }).unwrap() +} + +#[test] +fn scale_factor_point_on_base_point_keeps_the_prompt() { + let mut s = Session::new(); + s.cmdline("LINE 0,0 10,0").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("SCALE").unwrap(); + s.cmdline("ALL").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("0,0").unwrap(); + let before = length(&s); + let _ = s.cmdline("0,0"); + assert!(s.running.is_some(), "the command ended: {:?}", s.log); + assert_eq!(length(&s), before); + assert!(!s.selection().is_empty(), "the selection was cleared"); + s.cmdline("0,3").unwrap(); + assert!(length(&s) > before, "line not scaled: {}", length(&s)); +} diff --git a/crates/engine/tests/it/setvar_coverage.rs b/crates/engine/tests/it/setvar_coverage.rs index e5d9a7a26..3f147cd47 100644 --- a/crates/engine/tests/it/setvar_coverage.rs +++ b/crates/engine/tests/it/setvar_coverage.rs @@ -19,11 +19,14 @@ fn defaults_are_the_ones_the_commands_use() { for (name, v) in [ ("POLYSIDES", json!(4)), ("OFFSETDIST", json!(-1.0)), + ("OFFSETGAPTYPE", json!(0)), ("TRIMMODE", json!(1)), ("PROJMODE", json!(1)), ("EDGEMODE", json!(0)), + ("HPDOUBLE", json!(0)), ("HPNAME", json!("ANSI31")), ("HPSCALE", json!(1.0)), + ("HPSPACE", json!(1.0)), ("HPANG", json!(0.0)), ("DONUTID", json!(0.5)), ("DONUTOD", json!(1.0)), @@ -40,7 +43,7 @@ fn defaults_are_the_ones_the_commands_use() { // Lowercase names work; the list shows the new variables and the dimension variables. assert_eq!(getvar(&mut s, "circlerad"), json!(0.0)); let all = cadcraft_engine::sysvars::list(&s); - for n in ["POLYSIDES", "SPLINESEGS", "CHAMFERD", "TRANSPARENCYDISPLAY", "DIMASZ", "OSMODE", "CLAYER"] { + for n in ["POLYSIDES", "SPLINESEGS", "CHAMFERD", "TRANSPARENCYDISPLAY", "DIMASZ", "OSMODE", "CLAYER", "HPSPACE", "HPDOUBLE"] { assert!(all.get(n).is_some(), "{n} listed"); } } @@ -77,10 +80,14 @@ fn bad_values_and_unknown_names_are_refused() { ("POLYSIDES", json!(2)), ("POLYSIDES", json!(5000)), ("TRIMMODE", json!(3)), + ("OFFSETGAPTYPE", json!(3)), ("LWDEFAULT", json!(26)), ("LAYLOCKFADECTL", json!(91)), ("LAYLOCKFADECTL", json!(-91)), ("HPSCALE", json!(0)), + ("HPSPACE", json!(0)), + ("HPDOUBLE", json!(2)), + ("HPDOUBLE", json!(0.5)), ("HPNAME", json!("NO-SUCH-PATTERN")), ("DONUTOD", json!(0)), ("CIRCLERAD", json!(-1)), diff --git a/crates/engine/tests/it/snap_annotations.rs b/crates/engine/tests/it/snap_annotations.rs index 97bf0ac28..2b82acb9b 100644 --- a/crates/engine/tests/it/snap_annotations.rs +++ b/crates/engine/tests/it/snap_annotations.rs @@ -54,6 +54,8 @@ fn justified_text_snaps_and_grips_at_its_alignment_point() { style: "Standard".into(), halign: HAlign::Right, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }; s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Text(t.clone())).unwrap(); assert_eq!(snap_at(&s, Vec2::new(10.0, 0.0), mode::INS), Some((Vec2::new(10.0, 0.0), mode::INS))); diff --git a/crates/engine/tests/it/text_generation_flags.rs b/crates/engine/tests/it/text_generation_flags.rs new file mode 100644 index 000000000..f092f73f8 --- /dev/null +++ b/crates/engine/tests/it/text_generation_flags.rs @@ -0,0 +1,113 @@ +//! TEXT's own Backwards and Upside down (DXF 71 generation flags): new text and attribute +//! definitions take them from their style, later style changes leave existing text alone, the +//! Properties palette shows and sets them, and DXF keeps them. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Text}; +use cadcraft_engine::properties::describe; +use serde_json::{Value, json}; + +fn texts(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).collect() +} + +fn handles(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect() +} + +#[test] +fn new_text_takes_its_styles_effects_and_keeps_them() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Mirror", "backwards": true, "upsideDown": true })).unwrap(); + for l in ["TEXT", "0,0", "1", "0", "Typed", ""] { + s.cmdline(l).unwrap(); + } + s.execute("text", &json!({ "at": [0, 5], "text": "Json" })).unwrap(); + for t in texts(&s) { + assert!(t.backwards && t.upside_down, "{}", t.value); + } + // The style changing doesn't change text already placed. + s.execute("style", &json!({ "name": "Mirror", "backwards": false, "upsideDown": false })).unwrap(); + assert!(texts(&s).iter().all(|t| t.backwards && t.upside_down)); + s.execute("text", &json!({ "at": [0, 10], "text": "Plain" })).unwrap(); + let plain = &texts(&s)[2]; + assert!(!plain.backwards && !plain.upside_down); +} + +#[test] +fn attribute_definitions_take_the_style_too() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Tag", "backwards": true, "widthFactor": 0.75 })).unwrap(); + s.execute("attdef", &json!({ "tag": "NO", "prompt": "Number", "at": [0, 0], "height": 1 })).unwrap(); + let d = s.doc().unwrap(); + let a = d.model.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap(); + assert!(a.text.backwards && !a.text.upside_down); + assert_eq!(a.text.width_factor, 0.75); +} + +#[test] +fn the_palette_shows_and_sets_them() { + let mut s = Session::new(); + s.execute("text", &json!({ "at": [0, 0], "text": "a", "height": 1 })).unwrap(); + s.execute("text", &json!({ "at": [0, 5], "text": "b", "height": 1 })).unwrap(); + let hs = handles(&s); + let r = s.execute("properties.set", &json!({ "handles": [hs[0]], "backwards": true })).unwrap(); + assert_eq!(r["ignored"], json!([])); + let d = s.doc().unwrap(); + let handles: Vec<_> = d.model.iter().map(|e| e.handle).collect(); + let desc = serde_json::to_value(describe(d, &handles, None)).unwrap(); + let misc = desc["groups"].as_array().unwrap().iter().find(|g| g["name"] == "Misc").expect("a Misc group"); + let row = |key: &str| misc["rows"].as_array().unwrap().iter().find(|r| r["key"] == key).cloned().unwrap_or(Value::Null); + assert_eq!(row("backwards")["varies"], true); + assert_eq!(row("upsideDown")["value"], false); + s.execute("properties.set", &json!({ "handles": hs, "upsideDown": true, "backwards": false })).unwrap(); + assert!(texts(&s).iter().all(|t| t.upside_down && !t.backwards)); +} + +#[test] +fn dxf_keeps_them() { + let mut s = Session::new(); + s.execute("text", &json!({ "at": [0, 0], "text": "Plain", "height": 1 })).unwrap(); + s.execute("text", &json!({ "at": [0, 5], "text": "Both", "height": 1 })).unwrap(); + let both = handles(&s)[1].clone(); + s.execute("properties.set", &json!({ "handles": [both], "backwards": true, "upsideDown": true })).unwrap(); + let dxf = cadcraft_io::write_dxf(s.doc().unwrap()); + let back = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + let t: Vec = back.model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).collect(); + let by = |v: &str| t.iter().find(|x| x.value == v).unwrap().clone(); + assert!(!by("Plain").backwards && !by("Plain").upside_down); + assert!(by("Both").backwards && by("Both").upside_down); + // Flags of 0 aren't written; 6 is both. A text's groups run from its value (group 1) to the + // next entity (group 0). + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let flags = |v: &str| -> Option { + let at = lines.iter().position(|l| *l == v).unwrap(); + let mut i = at + 1; + while i + 1 < lines.len() && lines[i] != "0" { + if lines[i] == "71" { + return Some(lines[i + 1].to_string()); + } + i += 2; + } + None + }; + assert_eq!(flags("Both").as_deref(), Some("6")); + assert_eq!(flags("Plain"), None); +} + +#[test] +fn dxf_starts_justified_text_by_its_own_flags() { + // The same centered text twice, one backwards by its own flag (its style isn't): DXF group 10, + // the start of the baseline, is worked out with each text's flags, so the two differ. + let mut s = Session::new(); + for y in [0, 5] { + s.execute("text", &json!({ "at": [10, y], "text": "Same", "height": 1, "justify": "MC" })).unwrap(); + } + let back_one = handles(&s)[1].clone(); + s.execute("properties.set", &json!({ "handles": [back_one], "backwards": true })).unwrap(); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let starts: Vec<(bool, f64)> = + back.model.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some((t.backwards, t.insert.x)) } else { None }).collect(); + let x = |b: bool| starts.iter().find(|(f, _)| *f == b).unwrap().1; + assert!((x(true) - x(false)).abs() > 0.1, "{starts:?}"); +} diff --git a/crates/engine/tests/it/trim_highlight.rs b/crates/engine/tests/it/trim_highlight.rs index 583e32b36..69597f00b 100644 --- a/crates/engine/tests/it/trim_highlight.rs +++ b/crates/engine/tests/it/trim_highlight.rs @@ -310,3 +310,59 @@ fn a_fence_across_more_objects_than_the_preview_cap_shows_no_part() { s.input(Input::Enter).unwrap(); assert!((before - drawn(&s) - (CAP + 1) as f64 * 10.0).abs() < 1e-6, "every rung lost its middle"); } +#[test] +fn trim_shift_shows_the_opposite_piece_and_applies_it() { + let mut s = Session::new(); + line(&mut s, [4.0, -5.0], [4.0, 5.0]); + line(&mut s, [10.0, -5.0], [10.0, 5.0]); + let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]); + s.zoom_extents().unwrap(); + s.start("trim").unwrap(); + assert_eq!(ends(&s, l, [6.0, 0.0]), Some(vec![seg([4.0, 0.0], [8.0, 0.0])]), "shift up: the piece a click removes"); + s.shift_down = true; + assert_eq!(ends(&s, l, [6.0, 0.0]), Some(vec![seg([8.0, 0.0], [10.0, 0.0])]), "shift down: the opposite (extend) preview"); + s.shift_down = false; + assert_eq!(ends(&s, l, [6.0, 0.0]), Some(vec![seg([4.0, 0.0], [8.0, 0.0])]), "shift released: back to the trim preview"); + s.shift_down = true; + s.input(Input::Point(Vec2::new(6.0, 0.0))).unwrap(); + let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() }; + assert_eq!((x.b.x, x.b.y), (10.0, 0.0), "the shift pick applies the previewed extend"); +} + +#[test] +fn extend_shift_shows_the_opposite_piece_and_applies_it() { + let mut s = Session::new(); + line(&mut s, [4.0, -5.0], [4.0, 5.0]); + line(&mut s, [10.0, -5.0], [10.0, 5.0]); + let l = line(&mut s, [0.0, 0.0], [8.0, 0.0]); + s.zoom_extents().unwrap(); + s.start("extend").unwrap(); + assert_eq!(ends(&s, l, [6.0, 0.0]), Some(vec![seg([8.0, 0.0], [10.0, 0.0])]), "shift up: the stretch a click adds"); + s.shift_down = true; + assert_eq!(ends(&s, l, [6.0, 0.0]), Some(vec![seg([4.0, 0.0], [8.0, 0.0])]), "shift down: the opposite (trim) preview"); + s.shift_down = false; + assert_eq!(ends(&s, l, [6.0, 0.0]), Some(vec![seg([8.0, 0.0], [10.0, 0.0])]), "shift released: back to the extend preview"); + s.shift_down = true; + s.input(Input::Point(Vec2::new(6.0, 0.0))).unwrap(); + let EntityKind::Line(x) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!() }; + assert_eq!((x.b.x, x.b.y), (4.0, 0.0), "the shift pick applies the previewed trim"); +} + +#[test] +fn a_short_piece_far_from_the_origin_is_highlighted_and_removed_as_near_it() { + // #3382 landing review: the tolerance that merges nearby cuts must not grow with the distance + // from the origin, or a visible 0.5-unit piece near x = 1e9 is merged away. + for x0 in [0.0, 1e9] { + let mut s = Session::new(); + line(&mut s, [x0 + 5.0, -5.0], [x0 + 5.0, 5.0]); + line(&mut s, [x0 + 5.5, -5.0], [x0 + 5.5, 5.0]); + let l = line(&mut s, [x0, 0.0], [x0 + 10.0, 0.0]); + s.zoom_extents().unwrap(); + s.start("trim").unwrap(); + let shown = highlight(&s, l, [x0 + 5.25, 0.0]).unwrap_or_else(|| panic!("at {x0}: the whole line is highlighted")); + assert!((length(&shown) - 0.5).abs() < 1e-3, "at {x0}: {}", length(&shown)); + let before = drawn(&s); + s.input(Input::Point(Vec2::new(x0 + 5.25, 0.0))).unwrap(); + assert!((before - drawn(&s) - 0.5).abs() < 1e-3, "at {x0}: the click removes the same 0.5"); + } +} diff --git a/crates/engine/tests/it/viewport_frozen_block_parts.rs b/crates/engine/tests/it/viewport_frozen_block_parts.rs new file mode 100644 index 000000000..ee1dabfaa --- /dev/null +++ b/crates/engine/tests/it/viewport_frozen_block_parts.rs @@ -0,0 +1,1486 @@ +//! A block reference on a layer the active MSPACE viewport draws, with parts on a layer frozen in +//! that viewport ("VP Freeze"): the viewport does not draw those parts, so a selection made +//! through it does not hit the reference on them, and they take no room in the box a window +//! tests. AutoCAD 2022 was given the same objects and answers the cases asserted on them one by +//! one the same way through a viewport. Where it differs is what is taken through the rectangle +//! around a reference (#2991): the grid test only compares that between a layer frozen in the +//! viewport and one frozen for the whole drawing. In a viewport that does not freeze the layer +//! and on the Model tab everything is as before. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::Handle; +use cadcraft_engine::geom::{Bounds2, Vec2}; +use cadcraft_engine::select; +use serde_json::json; + +/// Draws a line from `a` to `b` on layer 0, or on "Hidden" when `hidden`, and returns its handle. +fn line(s: &mut Session, a: [f64; 2], b: [f64; 2], hidden: bool) -> Handle { + let r = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + let h = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap(); + if hidden { + to_hidden(s, h); + } + h +} + +/// Puts `h` on the layer "Hidden". +fn to_hidden(s: &mut Session, h: Handle) { + s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": "Hidden" })).unwrap(); + assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "Hidden"); +} + +/// Makes the block `name` of the objects `parts`, with its base at `base`, and returns the +/// reference to it that takes their place, on layer 0. +fn block(s: &mut Session, name: &str, base: [f64; 2], parts: &[Handle]) -> Handle { + let hs: Vec = parts.iter().map(|h| h.hex()).collect(); + let r = s.execute("block", &json!({ "name": name, "base": base, "handles": hs })).unwrap(); + let h = Handle::parse_hex(r["insert"].as_str().unwrap()).unwrap(); + assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "0"); + h +} + +/// Inserts the block `name` at `at` and returns the reference. +fn insert(s: &mut Session, name: &str, at: [f64; 2]) -> Handle { + let r = s.execute("insert", &json!({ "name": name, "at": at })).unwrap(); + Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap() +} + +/// Makes `viewport` the active MSPACE viewport. +fn enter(s: &mut Session, viewport: &str) { + s.execute("mspace", &json!({ "handle": viewport })).unwrap(); +} + +/// `hs` in handle order. +fn sorted(mut hs: Vec) -> Vec { + hs.sort_by_key(|h| h.0); + hs +} + +/// Five block references on layer 0 and two viewports, as AutoCAD was given them. +struct Parts { + /// The session, on the layout that holds the two viewports, in paper space. + s: Session, + /// One line on layer 0 from (0, 0) to (10, 0) and one on "Hidden" from (0, 5) to (10, 5). + r: Handle, + /// One line, on "Hidden", from (20, 5) to (30, 5): nothing of it is drawn where the layer is + /// frozen. The last object made. + h: Handle, + /// A reference to the block of `r` nested in another block: its lines run from (40, 0) to + /// (50, 0) on layer 0 and from (40, 5) to (50, 5) on "Hidden". + n: Handle, + /// A block of a reference to the block of `r` that is itself on "Hidden" (lines from (60, 0) + /// to (70, 0) and from (60, 5) to (70, 5), neither drawn where the layer is frozen) and of a + /// line on layer 0 from (60, 10) to (70, 10). + z: Handle, + /// Two lines on layer 0, from (80, 0) to (90, 0) and from (80, 10) to (90, 10), and between + /// them one on "Hidden" from (80, 5) to (90, 5): a part that is not drawn where the layer is + /// frozen, inside the box around the parts that are. + q: Handle, + /// The viewport that freezes "Hidden". + a: String, + /// The viewport that freezes nothing. + b: String, +} + +/// The drawing of [`Parts`], in paper space. With `crowded`, model space also holds enough lines, +/// far from the references, for selections to go through the spatial index instead of scanning +/// the space. +fn parts(crowded: bool) -> Parts { + let mut s = Session::new(); + s.execute("layer.new", &json!({ "name": "Hidden" })).unwrap(); + let on_0 = line(&mut s, [0.0, 0.0], [10.0, 0.0], false); + let on_hidden = line(&mut s, [0.0, 5.0], [10.0, 5.0], true); + let r = block(&mut s, "BP", [0.0, 0.0], &[on_0, on_hidden]); + let nested = insert(&mut s, "BP", [40.0, 0.0]); + let n = block(&mut s, "BN", [40.0, 0.0], &[nested]); + let child = insert(&mut s, "BP", [60.0, 0.0]); + to_hidden(&mut s, child); + let own = line(&mut s, [60.0, 10.0], [70.0, 10.0], false); + let z = block(&mut s, "BZ", [60.0, 0.0], &[child, own]); + let low = line(&mut s, [80.0, 0.0], [90.0, 0.0], false); + let high = line(&mut s, [80.0, 10.0], [90.0, 10.0], false); + let between = line(&mut s, [80.0, 5.0], [90.0, 5.0], true); + let q = block(&mut s, "BQ", [80.0, 0.0], &[low, high, between]); + if crowded { + let far: Vec<[f64; 2]> = (0..=cadcraft_engine::spatial::MIN_INDEXED).map(|i| [1000.0 + i as f64, 1000.0 + (i % 2) as f64]).collect(); + s.execute("line", &json!({ "points": far })).unwrap(); + } + let only_hidden = line(&mut s, [20.0, 5.0], [30.0, 5.0], true); + let h = block(&mut s, "BH", [20.0, 5.0], &[only_hidden]); + assert_eq!(s.doc().unwrap().model.len() >= cadcraft_engine::spatial::MIN_INDEXED, crowded, "whether model space is indexed"); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + let v = s.execute("mview", &json!({ "count": 2, "p1": [20, 20], "p2": [220, 120] })).unwrap(); + let (a, b) = (v["viewports"][0].as_str().unwrap().to_string(), v["viewports"][1].as_str().unwrap().to_string()); + s.execute("vplayer", &json!({ "handles": [a], "freeze": ["Hidden"] })).unwrap(); + Parts { s, r, h, n, z, q, a, b } +} + +/// What a pick at `p` finds where the session is: through the active viewport, or on its tab. +fn pick(s: &Session, p: [f64; 2]) -> Option { + let st = s.state().unwrap(); + select::pick_in(&st.doc, &st.edit_space(), st.viewport_frozen(), Vec2::new(p[0], p[1]), 0.2) +} + +/// Every object a pick at `p` finds where the session is, as selection cycling lists them. +fn pick_all(s: &Session, p: [f64; 2]) -> Vec { + let st = s.state().unwrap(); + sorted(select::pick_all_in(&st.doc, &st.edit_space(), st.viewport_frozen(), Vec2::new(p[0], p[1]), 0.2)) +} + +/// What a window from `a` to `b` takes where the session is (a crossing window with `crossing`). +fn window(s: &Session, a: [f64; 2], b: [f64; 2], crossing: bool) -> Vec { + let st = s.state().unwrap(); + let bx = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])); + sorted(select::select_window_in(&st.doc, &st.edit_space(), st.viewport_frozen(), bx, crossing)) +} + +/// The objects of the selection set the AutoLISP `code` returns (none for nil), in handle order. +fn lisp_set(s: &mut Session, code: &str) -> Vec { + use cadcraft_engine::lisp::value::Value as Lisp; + match s.lisp_eval(code, false, true, Vec::new()).unwrap() { + Some(Ok(Lisp::PickSet(set))) => sorted(set.items.lock().unwrap().clone()), + Some(Ok(Lisp::Nil)) => Vec::new(), + other => panic!("`{code}` returned {other:?}"), + } +} + +/// What a fence along `pts` takes where the session is. +fn fence(s: &Session, pts: &[[f64; 2]]) -> Vec { + let st = s.state().unwrap(); + let pts: Vec = pts.iter().map(|p| Vec2::new(p[0], p[1])).collect(); + sorted(select::select_fence_in(&st.doc, &st.edit_space(), st.viewport_frozen(), &pts)) +} + +/// What a window polygon through `pts` takes where the session is (a crossing polygon with +/// `crossing`). +fn polygon(s: &Session, pts: &[[f64; 2]], crossing: bool) -> Vec { + let st = s.state().unwrap(); + let pts: Vec = pts.iter().map(|p| Vec2::new(p[0], p[1])).collect(); + sorted(select::select_polygon_in(&st.doc, &st.edit_space(), st.viewport_frozen(), &pts, crossing)) +} + +/// A pick, selection cycling's list, a crossing window, a fence and a crossing polygon on the part +/// the viewport does not draw find nothing; neither does a pick on the side of the box around both parts, nor a +/// crossing window in the empty middle of that box, where the viewport draws nothing of the +/// reference. The part it draws is hit as before, and the other viewport hits both parts. The +/// same with and without the spatial index. +#[test] +fn a_reference_is_not_hit_on_a_part_the_viewport_does_not_draw() { + for crowded in [false, true] { + let Parts { mut s, r, a, b, .. } = parts(crowded); + let around = [[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0]]; + enter(&mut s, &a); + assert_eq!(pick(&s, [5.0, 5.0]), None, "a pick on the part that is not drawn (indexed: {crowded})"); + assert_eq!(pick_all(&s, [5.0, 5.0]), [], "selection cycling's list there (indexed: {crowded})"); + assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), [], "a crossing window over it (indexed: {crowded})"); + assert_eq!(fence(&s, &[[5.0, 4.0], [5.0, 6.0]]), [], "a fence across it (indexed: {crowded})"); + assert_eq!(polygon(&s, &around, true), [], "a crossing polygon over it (indexed: {crowded})"); + assert_eq!(pick(&s, [0.0, 2.5]), None, "a pick on the side of the box around both parts (indexed: {crowded})"); + assert_eq!(window(&s, [4.0, 2.0], [6.0, 3.0], true), [], "a crossing window between the parts (indexed: {crowded})"); + assert_eq!(pick(&s, [5.0, 0.0]), Some(r), "the part that is drawn (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "this viewport draws the part (indexed: {crowded})"); + assert_eq!(pick_all(&s, [5.0, 5.0]), [r]); + assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), [r]); + assert_eq!(fence(&s, &[[5.0, 4.0], [5.0, 6.0]]), [r]); + assert_eq!(polygon(&s, &around, true), [r]); + } +} + +/// A window and a window polygon around the drawn part alone take the reference: the part that +/// is not drawn takes no room in its box. A window around that part alone takes nothing. The +/// other viewport needs both parts inside the window, as before. +#[test] +fn a_window_takes_a_reference_by_the_parts_the_viewport_draws() { + for crowded in [false, true] { + let Parts { mut s, r, a, b, .. } = parts(crowded); + let around = [[-1.0, -1.0], [11.0, -1.0], [11.0, 1.0], [-1.0, 1.0]]; + enter(&mut s, &a); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r], "around the drawn part alone (indexed: {crowded})"); + assert_eq!(polygon(&s, &around, false), [r], "a window polygon around the drawn part alone (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, 4.0], [11.0, 6.0], false), [], "around the part that is not drawn (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 6.0], false), [r], "around both (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [], "this viewport draws both parts (indexed: {crowded})"); + assert_eq!(polygon(&s, &around, false), []); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 6.0], false), [r]); + } +} + +/// A reference whose every part is on the frozen layer has nothing drawn in the viewport: no +/// pick, window, crossing window or fence finds it there, and a window around it and three others +/// takes those three. It is still on a layer the viewport draws, so Select All takes it, and +/// Last takes such a reference when it is the last object made, as AutoCAD's All and Last do. The +/// other viewport finds it. +#[test] +fn a_reference_with_nothing_drawn_in_the_viewport_is_not_selected_there() { + for crowded in [false, true] { + let Parts { mut s, r, h, n, z, a, b, .. } = parts(crowded); + enter(&mut s, &a); + assert_eq!(pick(&s, [25.0, 5.0]), None, "a pick on its line (indexed: {crowded})"); + assert_eq!(window(&s, [24.0, 4.0], [26.0, 6.0], true), [], "a crossing window over its line (indexed: {crowded})"); + assert_eq!(fence(&s, &[[25.0, 4.0], [25.0, 6.0]]), [], "a fence across its line (indexed: {crowded})"); + assert_eq!(window(&s, [19.0, 4.0], [31.0, 6.0], false), [], "a window around it (indexed: {crowded})"); + assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], false), sorted(vec![r, n, z]), "a window around the four (indexed: {crowded})"); + assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], true), sorted(vec![r, n, z]), "a crossing window over the four (indexed: {crowded})"); + s.execute("selectall", &json!({})).unwrap(); + assert!(s.selection().contains(&h), "its own layer is drawn: Select All takes it (indexed: {crowded})"); + s.set_selection(Vec::new()); + // Another reference to that block, made through this viewport: the last object made. + let last = insert(&mut s, "BH", [20.0, 15.0]); + assert_eq!(pick(&s, [25.0, 15.0]), None, "nothing of it is drawn here either (indexed: {crowded})"); + assert_eq!(lisp_set(&mut s, "(ssget \"L\")"), [last], "its own layer is drawn: Last takes it (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [25.0, 5.0]), Some(h), "this viewport draws it (indexed: {crowded})"); + assert_eq!(window(&s, [19.0, 4.0], [31.0, 6.0], false), [h]); + assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], false), sorted(vec![r, h, n, z])); + } +} + +/// The same inside a nested reference: a part on the frozen layer two blocks deep is not hit and +/// takes no room, and a nested reference that is itself on the frozen layer brings none of its +/// lines, whatever their layers, while the rest of the block around it is hit and measured. +#[test] +fn a_nested_reference_follows_the_viewport_too() { + for crowded in [false, true] { + let Parts { mut s, n, z, a, b, .. } = parts(crowded); + enter(&mut s, &a); + assert_eq!(pick(&s, [45.0, 5.0]), None, "the nested part that is not drawn (indexed: {crowded})"); + assert_eq!(window(&s, [44.0, 4.0], [46.0, 6.0], true), [], "a crossing window over it (indexed: {crowded})"); + assert_eq!(pick(&s, [45.0, 0.0]), Some(n), "the nested part that is drawn (indexed: {crowded})"); + assert_eq!(window(&s, [39.0, -1.0], [51.0, 1.0], false), [n], "a window around the drawn nested part (indexed: {crowded})"); + assert_eq!(pick(&s, [65.0, 0.0]), None, "the layer 0 line of a nested reference on the frozen layer (indexed: {crowded})"); + assert_eq!(pick(&s, [65.0, 5.0]), None, "its other line (indexed: {crowded})"); + assert_eq!(window(&s, [64.0, -1.0], [66.0, 6.0], true), [], "a crossing window over that nested reference (indexed: {crowded})"); + assert_eq!(pick(&s, [65.0, 10.0]), Some(z), "the line beside it in the block (indexed: {crowded})"); + assert_eq!(window(&s, [59.0, 9.0], [71.0, 11.0], false), [z], "a window around that line alone (indexed: {crowded})"); + assert_eq!(window(&s, [59.0, -1.0], [71.0, 11.0], false), [z], "a window around the whole block (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [45.0, 5.0]), Some(n), "this viewport draws every part (indexed: {crowded})"); + assert_eq!(window(&s, [39.0, -1.0], [51.0, 1.0], false), []); + assert_eq!(pick(&s, [65.0, 0.0]), Some(z)); + assert_eq!(window(&s, [59.0, 9.0], [71.0, 11.0], false), []); + } +} + +/// A part that is not drawn can lie inside the box around the parts that are. A pick, selection +/// cycling's list and a fence on it find nothing there, although they are within that box; the drawn parts are hit, and a +/// window takes the reference when it holds both of them, not one alone. The hit geometry is what +/// decides here, not the box: without the viewport's layers in it the part is hit. +#[test] +fn a_part_that_is_not_drawn_is_not_hit_inside_the_box_of_the_drawn_parts() { + for crowded in [false, true] { + let Parts { mut s, q, a, b, .. } = parts(crowded); + enter(&mut s, &a); + assert_eq!(pick(&s, [85.0, 5.0]), None, "a pick on the part that is not drawn (indexed: {crowded})"); + assert_eq!(pick_all(&s, [85.0, 5.0]), [], "selection cycling's list there (indexed: {crowded})"); + assert_eq!(fence(&s, &[[85.0, 4.0], [85.0, 6.0]]), [], "a fence across it (indexed: {crowded})"); + assert_eq!(pick(&s, [85.0, 10.0]), Some(q), "a drawn part (indexed: {crowded})"); + assert_eq!(window(&s, [79.0, -1.0], [91.0, 11.0], false), [q], "a window around both drawn parts (indexed: {crowded})"); + assert_eq!(window(&s, [79.0, -1.0], [91.0, 1.0], false), [], "a window around one of them (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [85.0, 5.0]), Some(q), "this viewport draws the part (indexed: {crowded})"); + assert_eq!(pick_all(&s, [85.0, 5.0]), [q]); + assert_eq!(fence(&s, &[[85.0, 4.0], [85.0, 6.0]]), [q]); + } +} + +/// Freezing the layer in the viewport the session is in, and thawing it again, changes what the +/// next pick and the next window find: nothing is kept from before the change. With the spatial +/// index too, which is not rebuilt for a layer frozen in a viewport. +#[test] +fn freezing_and_thawing_the_layer_in_the_viewport_changes_what_is_hit_at_once() { + for crowded in [false, true] { + let Parts { mut s, r, b, .. } = parts(crowded); + enter(&mut s, &b); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "drawn here (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), []); + s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), None, "frozen in this viewport now (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r], "the part takes no room any more (indexed: {crowded})"); + s.execute("vplayer", &json!({ "handles": [b], "thaw": ["Hidden"] })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "thawed again (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [], "and it takes its room again (indexed: {crowded})"); + } +} + +/// What a user does goes through the same tests. A click on the part the viewport does not draw +/// is a click on nothing: it starts a selection window. A window dragged around the drawn part +/// alone takes the reference, and so does a click on that part. The `select` command's pick and +/// window answer the same way. +#[test] +fn clicks_and_the_select_command_see_the_parts_the_viewport_draws() { + for crowded in [false, true] { + let Parts { mut s, r, a, .. } = parts(crowded); + enter(&mut s, &a); + s.idle_click(Vec2::new(5.0, 5.0), false).unwrap(); + assert!(s.pending_window.is_some(), "a click on the part that is not drawn must be a click on nothing (indexed: {crowded})"); + // The other corner of that window, left to right around nothing. + s.idle_click(Vec2::new(6.0, 6.0), false).unwrap(); + assert_eq!(s.selection(), [], "a click on the part that is not drawn (indexed: {crowded})"); + s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap(); + s.idle_click(Vec2::new(11.0, 1.0), false).unwrap(); + assert_eq!(s.selection(), [r], "a window dragged around the drawn part alone (indexed: {crowded})"); + s.set_selection(Vec::new()); + s.idle_click(Vec2::new(5.0, 0.0), false).unwrap(); + assert_eq!(s.selection(), [r], "a click on the drawn part (indexed: {crowded})"); + s.set_selection(Vec::new()); + s.execute("select", &json!({ "at": [5, 5], "aperture": 0.5 })).unwrap(); + assert_eq!(s.selection(), [], "select at a point on the part that is not drawn (indexed: {crowded})"); + s.execute("select", &json!({ "window": [[-1, -1], [11, 1]] })).unwrap(); + assert_eq!(s.selection(), [r], "select by a window around the drawn part (indexed: {crowded})"); + } +} + +/// A clipped reference (XCLIP) with every part on the frozen layer is still selected by its clip +/// boundary, as AutoCAD 2022 selects it: a pick, a crossing window and a fence on the boundary +/// and a window around it take the reference, a pick on the part that is not drawn does not, and +/// a window must hold the whole boundary. The viewport draws the frame and nothing else of the +/// reference. The viewport that draws the layer selects it on its part too. +/// +/// With the frames hidden (XCLIPFRAME 0) the boundary is not drawn, and a reference is hit on +/// what is drawn (#3445), in any viewport: a pick, a crossing window and a fence on the boundary +/// take nothing, in the viewport that draws the layer as in the one that freezes it, and the +/// window around the boundary still takes the reference. AutoCAD 2022 selected it by the hidden +/// boundary too; that answer is not matched since #3445, here or outside a viewport. +#[test] +fn a_clipped_reference_with_no_part_drawn_is_selected_by_its_boundary() { + /// [`parts`] with one more reference to the block of `h`, at (20, 20), where its line runs + /// from (20, 20) to (30, 20), clipped to the rectangle from (18, 18) to (32, 22). The session + /// is left in the viewport that freezes nothing. + fn clipped(crowded: bool) -> (Parts, Handle) { + let mut p = parts(crowded); + enter(&mut p.s, &p.b); + let c = insert(&mut p.s, "BH", [20.0, 20.0]); + p.s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[18, 18], [32, 22]] })).unwrap(); + (p, c) + } + /// What six selections find: a pick on the reference's line, a pick on its boundary, a + /// crossing window and a fence over the boundary, a window around all of it, and a window + /// around the line alone, inside the boundary. + fn found(s: &Session) -> [Vec; 6] { + [ + pick(s, [25.0, 20.0]).into_iter().collect(), + pick(s, [18.0, 20.0]).into_iter().collect(), + window(s, [17.0, 19.0], [19.0, 21.0], true), + fence(s, &[[17.0, 20.0], [19.0, 20.0]]), + window(s, [15.0, 15.0], [35.0, 25.0], false), + window(s, [19.0, 19.0], [31.0, 21.0], false), + ] + } + /// Whether `v` lies on a side of the clip rectangle. + fn on_the_frame(v: Vec2) -> bool { + [v.x - 18.0, v.x - 32.0, v.y - 18.0, v.y - 22.0].iter().any(|d| d.abs() < 1e-9) + } + for crowded in [false, true] { + let (Parts { mut s, a, b, .. }, c) = clipped(crowded); + assert_eq!(found(&s), [vec![c], vec![c], vec![c], vec![c], vec![c], vec![]], "where the layer is drawn (indexed: {crowded})"); + enter(&mut s, &a); + let by_its_boundary = [vec![], vec![c], vec![c], vec![c], vec![c], vec![]]; + assert_eq!(found(&s), by_its_boundary, "through the viewport that freezes the layer (indexed: {crowded})"); + // That viewport draws the frame, and only the frame. + { + let st = s.state().unwrap(); + let reference = st.doc.entity(c).unwrap(); + let drawn = cadcraft_engine::render::build_entities_in_viewport( + &st.doc, + std::iter::once(&**reference), + &Default::default(), + st.viewport_frozen(), + ); + assert!(!drawn.verts.is_empty(), "the frame is drawn (indexed: {crowded})"); + assert!(drawn.verts.iter().all(|v| on_the_frame(Vec2::new(v.x, v.y))), "nothing but the frame is drawn (indexed: {crowded})"); + } + // With the frames hidden nothing of the reference is drawn here, so nothing of it is hit; + // the boundary is hit in neither viewport, and the window around it holds in both. + s.execute("xclipframe", &json!({ "value": 0 })).unwrap(); + assert_eq!(found(&s), [vec![], vec![], vec![], vec![], vec![c], vec![]], "with the frames hidden (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(found(&s), [vec![c], vec![], vec![], vec![], vec![c], vec![]], "the frames hidden, where the layer is drawn (indexed: {crowded})"); + } +} + +/// A clipped reference with a part on each layer, the clip showing a piece of both, with the +/// coordinates AutoCAD 2022 was given (here 100 to the right) and its answers. Through the +/// viewport the piece on the frozen layer is not hit; the drawn piece and the boundary are, the +/// part of the block the clip cuts away is not, and a window must hold the whole boundary. +#[test] +fn a_clipped_reference_with_a_part_drawn_is_selected_by_its_boundary_and_that_part() { + for crowded in [false, true] { + let Parts { mut s, a, b, .. } = parts(crowded); + enter(&mut s, &b); + // A line on layer 0 from (130, 30) to (160, 30) and one on "Hidden" 4 above it, clipped to + // the rectangle from (138, 27) to (152, 37). + let on_0 = line(&mut s, [130.0, 30.0], [160.0, 30.0], false); + let on_hidden = line(&mut s, [130.0, 34.0], [160.0, 34.0], true); + let c = block(&mut s, "BK", [130.0, 30.0], &[on_0, on_hidden]); + s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[138, 27], [152, 37]] })).unwrap(); + assert_eq!(pick(&s, [145.0, 34.0]), Some(c), "where the layer is drawn (indexed: {crowded})"); + enter(&mut s, &a); + assert_eq!(pick(&s, [145.0, 34.0]), None, "the piece that is not drawn (indexed: {crowded})"); + assert_eq!(pick(&s, [145.0, 30.0]), Some(c), "the drawn piece (indexed: {crowded})"); + assert_eq!(pick(&s, [133.0, 30.0]), None, "the layer 0 part where the clip cuts it away (indexed: {crowded})"); + assert_eq!(pick(&s, [145.0, 27.0]), Some(c), "the bottom side of the boundary (indexed: {crowded})"); + assert_eq!(pick(&s, [145.0, 37.0]), Some(c), "the top side of the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [144.0, 26.0], [146.0, 28.0], true), [c], "a crossing window over the bottom side (indexed: {crowded})"); + assert_eq!(window(&s, [137.0, 26.0], [153.0, 38.0], false), [c], "a window around the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [137.5, 29.0], [152.5, 31.0], false), [], "a window around the drawn piece alone (indexed: {crowded})"); + assert_eq!(window(&s, [137.0, 26.0], [153.0, 33.0], false), [], "a window around the lower half of the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [128.0, 26.0], [162.0, 38.0], false), [c], "a window around the whole block (indexed: {crowded})"); + } +} + +/// A reference with an inverted clip keeps the box the drawing gives it as well, so its frame, +/// which the viewport draws, here beside a part it does not draw, is still hit there: by a pick +/// and by a fence, neither of which comes near a side of that box. AutoCAD 2022 selects such a +/// reference by its frame too, and answers the pick on the drawn part and the two windows the +/// same way. The shape is the one AutoCAD was given, 80 to the right. This test passes without +/// the change as well: it holds what the change must leave alone, and fails when a clipped +/// reference is measured through the viewport like any other. +#[test] +fn an_inverted_clip_is_hit_on_its_frame_through_the_viewport() { + for crowded in [false, true] { + let Parts { mut s, a, b, .. } = parts(crowded); + enter(&mut s, &b); + // The block of `r` at (100, 20): a line on layer 0 from (100, 20) to (110, 20) and one on + // "Hidden" 5 above it. The clip hides what is inside the rectangle from (103, 23) to + // (107, 27), so the bottom side of its frame runs between the two lines. + let c = insert(&mut s, "BP", [100.0, 20.0]); + s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[103, 23], [107, 27]], "invert": true })).unwrap(); + assert_eq!(pick(&s, [105.0, 23.0]), Some(c), "where the layer is drawn (indexed: {crowded})"); + enter(&mut s, &a); + assert_eq!(pick(&s, [105.0, 23.0]), Some(c), "the bottom side of the frame (indexed: {crowded})"); + assert_eq!(fence(&s, &[[105.0, 22.5], [105.0, 23.5]]), [c], "a fence across it (indexed: {crowded})"); + assert_eq!(pick(&s, [101.0, 20.0]), Some(c), "the layer 0 part outside the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [99.0, 19.0], [111.0, 21.0], false), [], "a window around the drawn part alone (indexed: {crowded})"); + assert_eq!(window(&s, [99.0, 19.0], [111.0, 28.5], false), [c], "a window around both parts and the frame (indexed: {crowded})"); + } +} + +/// What a pick at `p` finds in the model space of `d` through a viewport that freezes the layers +/// in `frozen`, or on the Model tab with no layer. +fn picked(d: &cadcraft_engine::doc::Drawing, frozen: &[String], p: [f64; 2]) -> Option { + select::pick_in(d, &cadcraft_engine::doc::Space::Model, frozen, Vec2::new(p[0], p[1]), 0.2) +} + +/// What a window from `a` to `b` takes there ([`picked`]). +fn windowed(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec { + let area = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])); + select::select_window_in(d, &cadcraft_engine::doc::Space::Model, frozen, area, false) +} + +/// What a crossing window from `a` to `b` takes there ([`picked`]). +fn crossed(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec { + let area = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])); + select::select_window_in(d, &cadcraft_engine::doc::Space::Model, frozen, area, true) +} + +/// What a fence from `a` to `b` takes there ([`picked`]). +fn fenced(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec { + select::select_fence_in(d, &cadcraft_engine::doc::Space::Model, frozen, &[Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])]) +} + +/// The objects of the two tests about the layer Defpoints, built by hand in model space. +struct OnDefpoints { + /// The drawing that holds them. + d: cadcraft_engine::doc::Drawing, + /// A dimension like the one AutoCAD made for DIMLINEAR from (0, 5) to (40, 15), with the + /// dimension line at y = 40 and the extension lines starting 2 from those points. + dim: Handle, + /// A reference, 200 to the right, to a block that holds such a dimension. + holder: Handle, + /// A dimension like the one AutoCAD made for DIMORDINATE, here 100 higher: the feature 60 + /// right of the origin it measures from, and a leader 15 long. + ord: Handle, + /// A line on Defpoints from (50, 0) to (60, 0). + plain: Handle, + /// A reference at (70, -20) to a block with a line on layer 0 and, 5 above it, one on + /// Defpoints. + reference: Handle, + /// A reference at (100, -20) to a block with a line on layer 0 and, 3 above its middle, a + /// point on Defpoints: the shape AutoCAD was given. + pointed: Handle, + /// A reference at (100, -40) to a block with that point between two lines on layer 0, so + /// inside the box around them. + between: Handle, + /// A reference at (130, -40) to a block that holds a reference to that block. + deep: Handle, + /// A reference at (160, -40) to a block like that one, with the point on the layer "Hidden". + other: Handle, + /// The first dimension 300 to the right, with the first extension line of its block on + /// Defpoints. + moved: Handle, +} + +/// The drawing of [`OnDefpoints`]. With `crowded`, model space also holds enough lines, far from +/// those objects, for selections to go through the spatial index instead of scanning the space. +fn defpoints_objects(crowded: bool) -> OnDefpoints { + use cadcraft_engine::doc::{Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Insert, Line, Point, Space}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Defpoints"); + d.ensure_layer("Hidden"); + let line = |a: [f64; 2], b: [f64; 2]| EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }); + let point = |p: [f64; 2]| EntityKind::Point(Point { p: Vec3::new(p[0], p[1], 0.0), angle: 0.0 }); + let at = |p: [f64; 2]| Vec3::new(p[0], p[1], 0.0); + let measured = |kind: DimKind, defpt: [f64; 2], p13: [f64; 2], p14: [f64; 2], block: &str| Dimension { + kind, + defpt: at(defpt), + text_mid: Vec3::ZERO, + p13: at(p13), + p14: at(p14), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some(block.into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let mut define = |name: &str, parts: Vec<(EntityKind, &str)>| { + let mut block = Block::new(name); + for (i, (kind, layer)) in parts.into_iter().enumerate() { + let mut part = Entity::new(Handle(i as u64 + 1), kind); + part.common.layer = layer.into(); + block.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + }; + // *D1: the two extension lines, the dimension line and the three definition points. *D2 is + // the same for a second dimension, the one the block BDIM holds. + let made = || { + vec![ + (line([0.0, 7.0], [0.0, 40.18]), "0"), + (line([40.0, 17.0], [40.0, 40.18]), "0"), + (line([0.18, 40.0], [39.82, 40.0]), "0"), + (point([0.0, 5.0]), "Defpoints"), + (point([40.0, 15.0]), "Defpoints"), + (point([40.0, 40.0]), "Defpoints"), + ] + }; + define("*D1", made()); + define("*D2", made()); + define("BDIM", vec![(EntityKind::Dimension(measured(DimKind::Aligned, [40.0, 40.0], [0.0, 5.0], [40.0, 15.0], "*D2")), "0")]); + // *D3: the leader of an ordinate dimension and its three definition points: the feature at + // (60, 100), the leader's end and, 60 to the left of all that, the origin it measures from. + define( + "*D3", + vec![ + (line([60.0, 98.0], [60.0, 85.0]), "0"), + (point([60.0, 100.0]), "Defpoints"), + (point([60.0, 85.0]), "Defpoints"), + (point([0.0, 100.0]), "Defpoints"), + ], + ); + // BD: a line on layer 0 and, 5 above it, one on Defpoints. + define("BD", vec![(line([0.0, 0.0], [10.0, 0.0]), "0"), (line([0.0, 5.0], [10.0, 5.0]), "Defpoints")]); + // BQ: a line on layer 0 and, 3 above its middle, a point on Defpoints. BB: that point between + // two lines on layer 0, 6 apart. BN holds a reference to BB. BH is BB with the point on + // "Hidden". + let two_lines = + |layer: &'static str| vec![(line([0.0, 0.0], [10.0, 0.0]), "0"), (line([0.0, 6.0], [10.0, 6.0]), "0"), (point([5.0, 3.0]), layer)]; + define("BQ", vec![(line([0.0, 0.0], [10.0, 0.0]), "0"), (point([5.0, 3.0]), "Defpoints")]); + define("BB", two_lines("Defpoints")); + define("BN", vec![(EntityKind::Insert(Insert { block: "BB".into(), ..Insert::default() }), "0")]); + define("BH", two_lines("Hidden")); + // *D4: *D1 300 to the right, with its first extension line on Defpoints. + define( + "*D4", + vec![ + (line([300.0, 7.0], [300.0, 40.18]), "Defpoints"), + (line([340.0, 17.0], [340.0, 40.18]), "0"), + (line([300.18, 40.0], [339.82, 40.0]), "0"), + (point([300.0, 5.0]), "Defpoints"), + (point([340.0, 15.0]), "Defpoints"), + (point([340.0, 40.0]), "Defpoints"), + ], + ); + let model = Space::Model; + let dimension = measured(DimKind::Aligned, [40.0, 40.0], [0.0, 5.0], [40.0, 15.0], "*D1"); + let dim = d.add(&model, Common::default(), EntityKind::Dimension(dimension)).unwrap(); + let ordinate = measured(DimKind::Ordinate { x_type: true }, [0.0, 100.0], [60.0, 100.0], [60.0, 85.0], "*D3"); + let ord = d.add(&model, Common::default(), EntityKind::Dimension(ordinate)).unwrap(); + let held = Insert { block: "BDIM".into(), insert: Vec3::new(200.0, 0.0, 0.0), ..Insert::default() }; + let holder = d.add(&model, Common::default(), EntityKind::Insert(held)).unwrap(); + let on_the_layer = Common { layer: "Defpoints".into(), ..Common::default() }; + let plain = d.add(&model, on_the_layer, line([50.0, 0.0], [60.0, 0.0])).unwrap(); + let placed = Insert { block: "BD".into(), insert: Vec3::new(70.0, -20.0, 0.0), ..Insert::default() }; + let reference = d.add(&model, Common::default(), EntityKind::Insert(placed)).unwrap(); + let place = |block: &str, x: f64, y: f64| EntityKind::Insert(Insert { block: block.into(), insert: Vec3::new(x, y, 0.0), ..Insert::default() }); + let pointed = d.add(&model, Common::default(), place("BQ", 100.0, -20.0)).unwrap(); + let between = d.add(&model, Common::default(), place("BB", 100.0, -40.0)).unwrap(); + let deep = d.add(&model, Common::default(), place("BN", 130.0, -40.0)).unwrap(); + let other = d.add(&model, Common::default(), place("BH", 160.0, -40.0)).unwrap(); + let with_moved_line = measured(DimKind::Aligned, [340.0, 40.0], [300.0, 5.0], [340.0, 15.0], "*D4"); + let moved = d.add(&model, Common::default(), EntityKind::Dimension(with_moved_line)).unwrap(); + if crowded { + for i in 0..=cadcraft_engine::spatial::MIN_INDEXED { + let x = 1000.0 + i as f64; + d.add(&model, Common::default(), line([x, 1000.0], [x, 1001.0])).unwrap(); + } + } + assert_eq!(d.model.len() >= cadcraft_engine::spatial::MIN_INDEXED, crowded, "whether model space is indexed"); + OnDefpoints { d, dim, holder, ord, plain, reference, pointed, between, deep, other, moved } +} + +/// A dimension is selected on its definition points whatever is frozen: AutoCAD 2022 selects one +/// by a pick or a crossing window on such a point, and a window must hold the points, with the +/// layer Defpoints frozen in the viewport too. So the points on that layer in the block of a +/// dimension are not left out of what the dimension is hit on or of the room it takes. A line of +/// its block on Defpoints is left out, as AutoCAD does not select the dimension by it there. The +/// same holds for a dimension that is a part of a block, where the reference is what is selected, +/// and for the first definition point of an ordinate dimension, the origin it measures from, +/// which lies away from all the dimension draws. The +/// picks on the definition point of the dimension and of the one in a block hold the hit +/// geometry: they lie inside the box, away from its sides. The crossing windows on those points +/// reach a corner of the box as well. The origin of the ordinate dimension lies on a side of +/// that dimension's box, so the assertions on it hold the box. The windows that leave a +/// definition point out would take nothing without the points of the block too: a dimension's +/// box always takes in the definition points the dimension itself stores. The frozen layers are +/// given to the selection as a viewport gives them, with and without the spatial index. +#[test] +fn a_dimension_is_hit_on_its_definition_points_whatever_the_viewport_freezes() { + let through = ["Defpoints".to_string()]; + for crowded in [false, true] { + let OnDefpoints { d, dim, holder, ord, moved, .. } = defpoints_objects(crowded); + // The dimension, on its first definition point. + assert_eq!(picked(&d, &through, [0.0, 5.0]), Some(dim), "a pick on a definition point (indexed: {crowded})"); + assert_eq!(crossed(&d, &through, [-0.5, 4.5], [0.5, 5.5]), [dim], "a crossing window over it (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [-2.0, 6.0], [42.0, 43.0]), [], "a window that leaves it out (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [-2.0, 3.0], [42.0, 43.0]), [dim], "a window around all of the dimension (indexed: {crowded})"); + assert_eq!(picked(&d, &[], [0.0, 5.0]), Some(dim), "where the layer is drawn (indexed: {crowded})"); + assert_eq!(windowed(&d, &[], [-2.0, 6.0], [42.0, 43.0]), [], "indexed: {crowded}"); + // The dimension in a block: the reference, on the dimension's first definition point. The + // pick is what tells: it is not near a side of the reference's box. + assert_eq!(picked(&d, &through, [200.0, 5.0]), Some(holder), "a pick on the definition point of a dimension in a block (indexed: {crowded})"); + assert_eq!(crossed(&d, &through, [199.5, 4.5], [200.5, 5.5]), [holder], "a crossing window over it (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [198.0, 6.0], [242.0, 43.0]), [], "a window that leaves it out (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [198.0, 3.0], [242.0, 43.0]), [holder], "a window around all of the reference (indexed: {crowded})"); + assert_eq!(picked(&d, &[], [200.0, 5.0]), Some(holder), "where the layer is drawn (indexed: {crowded})"); + // The ordinate dimension, on the origin it measures from and on its feature point. + assert_eq!(picked(&d, &through, [0.0, 100.0]), Some(ord), "a pick on the origin point of an ordinate dimension (indexed: {crowded})"); + assert_eq!(crossed(&d, &through, [-0.5, 99.5], [0.5, 100.5]), [ord], "a crossing window over it (indexed: {crowded})"); + assert_eq!(picked(&d, &through, [60.0, 100.0]), Some(ord), "a pick on its feature point (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [30.0, 60.0], [90.0, 130.0]), [], "a window around all of it but the origin point (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [-5.0, 60.0], [90.0, 130.0]), [ord], "a window around all of it (indexed: {crowded})"); + assert_eq!(picked(&d, &[], [0.0, 100.0]), Some(ord), "where the layer is drawn (indexed: {crowded})"); + assert_eq!(windowed(&d, &[], [30.0, 60.0], [90.0, 130.0]), [], "indexed: {crowded}"); + // A dimension with a line of its block on Defpoints: the line follows the viewport, the + // definition points do not. + assert_eq!(picked(&d, &through, [300.0, 20.0]), None, "a line of a dimension's block on Defpoints (indexed: {crowded})"); + assert_eq!(picked(&d, &through, [300.0, 5.0]), Some(moved), "the definition point below it (indexed: {crowded})"); + assert_eq!(picked(&d, &[], [300.0, 20.0]), Some(moved), "where the layer is drawn (indexed: {crowded})"); + } +} + +/// A point on the layer Defpoints that is a part of a block counts like the definition points of +/// a dimension, which are such points: AutoCAD 2022 selects a reference by a pick or a crossing window on such +/// a point of its block, one block deeper too, and a window must hold the point, with Defpoints +/// frozen in the viewport. A point on another layer the viewport freezes is not hit. The first +/// reference has the shape AutoCAD was given, the point above the line: that point makes the top +/// side of the reference's box, so the assertions on it hold the box. The picks on the point +/// between two lines hold the hit geometry: they lie inside the box, away from its sides. The +/// frozen layers are given to the selection as a viewport gives them, with and without the +/// spatial index. +#[test] +fn a_reference_is_hit_on_a_point_on_defpoints_whatever_the_viewport_freezes() { + let through = ["Defpoints".to_string(), "Hidden".to_string()]; + for crowded in [false, true] { + let OnDefpoints { d, pointed, between, deep, other, .. } = defpoints_objects(crowded); + // The point above the line. + assert_eq!(picked(&d, &through, [105.0, -17.0]), Some(pointed), "a pick on the point (indexed: {crowded})"); + assert_eq!(crossed(&d, &through, [104.5, -17.5], [105.5, -16.5]), [pointed], "a crossing window over it (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [99.0, -21.0], [111.0, -19.0]), [], "a window around the line alone (indexed: {crowded})"); + assert_eq!(windowed(&d, &through, [99.0, -21.0], [111.0, -16.0]), [pointed], "a window around the line and the point (indexed: {crowded})"); + // The point inside the box of two drawn lines, and the same one block deeper. + assert_eq!(picked(&d, &through, [105.0, -37.0]), Some(between), "a pick on the point between two lines (indexed: {crowded})"); + assert_eq!(picked(&d, &through, [135.0, -37.0]), Some(deep), "the same one block deeper (indexed: {crowded})"); + // A point on the other layer the viewport freezes. + assert_eq!(picked(&d, &through, [165.0, -37.0]), None, "a point on another frozen layer (indexed: {crowded})"); + assert_eq!(picked(&d, &[], [165.0, -37.0]), Some(other), "where that layer is drawn (indexed: {crowded})"); + } +} + +/// A line on the layer Defpoints and a block's part on it follow the viewport as on any other +/// layer: where the viewport freezes Defpoints they are not hit and take no room, as in AutoCAD +/// 2022. Only a point on Defpoints inside a block is kept. With and without the spatial index. +#[test] +fn a_line_and_a_block_part_on_defpoints_follow_the_viewport() { + let through = ["Defpoints".to_string()]; + for crowded in [false, true] { + let OnDefpoints { d, plain, reference, .. } = defpoints_objects(crowded); + // A line on Defpoints. + assert_eq!(picked(&d, &through, [55.0, 0.0]), None, "a line on the layer the viewport freezes (indexed: {crowded})"); + assert_eq!(crossed(&d, &through, [54.0, -1.0], [56.0, 1.0]), [], "indexed: {crowded}"); + assert_eq!(picked(&d, &[], [55.0, 0.0]), Some(plain), "indexed: {crowded}"); + // A block's part on Defpoints. + assert_eq!(picked(&d, &through, [75.0, -15.0]), None, "a block's part on that layer (indexed: {crowded})"); + assert_eq!(crossed(&d, &through, [74.0, -16.0], [76.0, -14.0]), [], "indexed: {crowded}"); + assert_eq!(picked(&d, &through, [75.0, -20.0]), Some(reference), "indexed: {crowded}"); + assert_eq!(windowed(&d, &through, [69.0, -21.0], [81.0, -19.0]), [reference], "a window around its layer 0 part alone (indexed: {crowded})"); + assert_eq!(picked(&d, &[], [75.0, -15.0]), Some(reference), "indexed: {crowded}"); + assert_eq!(windowed(&d, &[], [69.0, -21.0], [81.0, -19.0]), [], "indexed: {crowded}"); + assert_eq!(windowed(&d, &[], [69.0, -21.0], [81.0, -14.0]), [reference], "indexed: {crowded}"); + } +} + +/// Other objects that draw a block, built by hand in model space with the coordinates AutoCAD +/// 2022 was given. +struct BlockDrawers { + /// The drawing that holds them. + d: cadcraft_engine::doc::Drawing, + /// A 2 x 2 array of references (MINSERT) from (0, -30), its rows 12 and its columns 15 apart. + array: Handle, + /// A reference at (70, 30) with an attribute on "Hidden" 4 above its line. + tagged: Handle, + /// An annotative reference at the origin, at the drawing's annotation scale. + scaled: Handle, + /// A multileader from (110, -20) to (130, 0) whose content is a block (here 100 to the + /// right of where AutoCAD had it). + leader: Handle, + /// A dimension along (150, -10) to (160, -10) whose block nests a reference, as the block of + /// a dimension with an arrowhead block does in AutoCAD. + dim: Handle, +} + +/// The drawing of [`BlockDrawers`]: every block has a line on layer 0 and, above it, one on +/// "Hidden", but for the one with the attribute, where the attribute is on "Hidden". +fn block_drawers() -> BlockDrawers { + use cadcraft_engine::doc::{ + AnnoScale, Attrib, AttribProps, Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, HAlign, Insert, Line, MLeader, Space, Text, + VAlign, + }; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let line = |handle: u64, a: [f64; 2], b: [f64; 2], layer: &str| { + let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) })); + part.common.layer = layer.into(); + part + }; + let reference = |block: &str, at: [f64; 2]| Insert { block: block.into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() }; + let mut define = |name: &str, parts: Vec| { + let mut block = Block::new(name); + for part in parts { + block.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + }; + // BP: a line on layer 0 and, 5 above it, one on "Hidden". BM: the same, 8 apart. BA: one line. + define("BP", vec![line(1, [0.0, 0.0], [10.0, 0.0], "0"), line(2, [0.0, 5.0], [10.0, 5.0], "Hidden")]); + define("BM", vec![line(1, [0.0, 0.0], [6.0, 0.0], "0"), line(2, [0.0, 8.0], [6.0, 8.0], "Hidden")]); + define("BA", vec![line(1, [0.0, 0.0], [10.0, 0.0], "0")]); + // *D9: what a dimension draws, here a reference to BP at (150, 0) and a line of its own. + let mut nested = Entity::new(Handle(1), EntityKind::Insert(reference("BP", [150.0, 0.0]))); + nested.common.layer = "0".into(); + define("*D9", vec![nested, line(2, [150.0, -10.0], [160.0, -10.0], "0")]); + let model = Space::Model; + // A 2 x 2 array of BP from (0, -30), its rows 12 and its columns 15 apart. + let grid = Insert { cols: 2, rows: 2, col_spacing: 15.0, row_spacing: 12.0, ..reference("BP", [0.0, -30.0]) }; + let array = d.add(&model, Common::default(), EntityKind::Insert(grid)).unwrap(); + // BA at (70, 30) with an attribute on "Hidden" 4 above its line. + let value = Text { + insert: Vec3::new(70.0, 34.0, 0.0), + align_pt: None, + height: 1.5, + value: "HHHH".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + backwards: false, + upside_down: false, + }; + let attribute = Attrib { + tag: "TAG".into(), + text: value, + invisible: false, + constant: false, + prompt: String::new(), + props: AttribProps { layer: Some("Hidden".into()), ..Default::default() }, + multiline: None, + modes: Default::default(), + }; + let tagged = d.add(&model, Common::default(), EntityKind::Insert(Insert { attribs: vec![attribute], ..reference("BA", [70.0, 30.0]) })).unwrap(); + // An annotative reference to BP at the origin, at the drawing's annotation scale. + let annotative = Common { anno_scales: vec![AnnoScale::unit()], ..Common::default() }; + let scaled = d.add(&model, annotative, EntityKind::Insert(reference("BP", [0.0, 0.0]))).unwrap(); + // A multileader from (110, -20) to (130, 0) with BM at (127.36, -4), where AutoCAD put it. + let leader = MLeader { + leaders: vec![vec![Vec3::new(110.0, -20.0, 0.0)]], + landing: Vec3::new(130.0, 0.0, 0.0), + dogleg: 0.36, + text: None, + style: "Standard".into(), + arrow_size: 0.18, + spline: false, + block: Some(reference("BM", [127.36, -4.0])), + }; + let leader = d.add(&model, Common::default(), EntityKind::MLeader(leader)).unwrap(); + // A dimension along (150, -10) to (160, -10) that draws *D9. + let dimension = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(160.0, -10.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::new(150.0, -10.0, 0.0), + p14: Vec3::new(160.0, -10.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("*D9".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let dim = d.add(&model, Common::default(), EntityKind::Dimension(dimension)).unwrap(); + BlockDrawers { d, array, tagged, scaled, leader, dim } +} + +/// An array of references (MINSERT) and a reference with an attribute on the frozen layer follow +/// the viewport as a plain reference does: the parts and the attribute on the frozen layer are +/// not hit and take no room in a window. They have the coordinates AutoCAD 2022 was given and its +/// answers. The frozen layers are given to the selection as a viewport gives them. +#[test] +fn arrays_and_attributes_follow_the_viewport() { + let BlockDrawers { d, array, tagged, .. } = block_drawers(); + let through = ["Hidden".to_string()]; + // The array: the "Hidden" part of no copy is hit, and a window needs the layer 0 parts only. + assert_eq!(picked(&d, &through, [5.0, -30.0]), Some(array), "the layer 0 part of the first copy"); + assert_eq!(picked(&d, &through, [5.0, -25.0]), None, "the part of the first copy that is not drawn"); + assert_eq!(picked(&d, &through, [20.0, -13.0]), None, "the part of the last copy that is not drawn"); + assert_eq!(picked(&d, &through, [20.0, -18.0]), Some(array), "the layer 0 part of the last copy"); + assert_eq!(crossed(&d, &through, [19.0, -14.0], [21.0, -12.0]), [], "a crossing window over the last copy's part that is not drawn"); + assert_eq!(windowed(&d, &through, [-1.0, -31.0], [26.0, -17.0]), [array], "a window around all but the upper row's parts that are not drawn"); + assert_eq!(picked(&d, &[], [20.0, -13.0]), Some(array), "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [-1.0, -31.0], [26.0, -17.0]), []); + assert_eq!(windowed(&d, &[], [-1.0, -31.0], [26.0, -12.0]), [array]); + + // The attribute: not hit, and no room taken. + assert_eq!(picked(&d, &through, [75.0, 30.0]), Some(tagged)); + assert_eq!(crossed(&d, &through, [70.0, 33.5], [76.0, 36.0]), [], "a crossing window over the attribute that is not drawn"); + assert_eq!(fenced(&d, &through, [71.0, 33.0], [71.0, 37.0]), [], "a fence across it"); + assert_eq!(windowed(&d, &through, [69.0, 29.0], [81.0, 31.0]), [tagged], "a window around the line alone"); + assert_eq!(crossed(&d, &[], [70.0, 33.5], [76.0, 36.0]), [tagged], "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [69.0, 29.0], [81.0, 31.0]), []); + assert_eq!(windowed(&d, &[], [69.0, 29.0], [81.0, 37.0]), [tagged]); +} + +/// An annotative reference, a multileader whose content is a block and a dimension whose block +/// nests a reference follow the viewport too: their parts on the frozen layer are not hit and +/// take no room in a window. The first two have the coordinates AutoCAD 2022 was given and its +/// answers. The frozen layers are given to the selection as a viewport gives them. +#[test] +fn annotative_references_multileaders_and_dimensions_follow_the_viewport() { + let BlockDrawers { d, scaled, leader, dim, .. } = block_drawers(); + let through = ["Hidden".to_string()]; + // The annotative reference. + assert_eq!(picked(&d, &through, [5.0, 5.0]), None, "the part of the annotative reference that is not drawn"); + assert_eq!(picked(&d, &through, [5.0, 0.0]), Some(scaled)); + assert_eq!(crossed(&d, &through, [4.0, 4.0], [6.0, 6.0]), []); + assert_eq!(fenced(&d, &through, [5.0, 4.0], [5.0, 6.0]), []); + assert_eq!(windowed(&d, &through, [-1.0, -1.0], [11.0, 1.0]), [scaled], "a window around its layer 0 part alone"); + assert_eq!(picked(&d, &[], [5.0, 5.0]), Some(scaled), "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [-1.0, -1.0], [11.0, 1.0]), []); + + // The multileader: its block's part on "Hidden" lies from (127.36, 4) to (133.36, 4). + assert_eq!(picked(&d, &through, [130.36, 4.0]), None, "the part of the multileader's block that is not drawn"); + assert_eq!(picked(&d, &through, [130.36, -4.0]), Some(leader), "the layer 0 part of its block"); + assert_eq!(picked(&d, &through, [120.0, -10.0]), Some(leader), "its leader line"); + assert_eq!(crossed(&d, &through, [129.65, 3.29], [131.07, 4.71]), []); + assert_eq!(fenced(&d, &through, [130.36, 3.0], [130.36, 5.0]), []); + assert_eq!(windowed(&d, &through, [108.0, -22.0], [135.36, 2.0]), [leader], "a window around its leader and the layer 0 part"); + assert_eq!(picked(&d, &[], [130.36, 4.0]), Some(leader), "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [108.0, -22.0], [135.36, 2.0]), []); + assert_eq!(windowed(&d, &[], [108.0, -22.0], [135.36, 6.0]), [leader]); + + // The dimension: the nested reference's part on "Hidden" lies from (150, 5) to (160, 5). + assert_eq!(picked(&d, &through, [155.0, 5.0]), None, "the part of the reference nested in the dimension's block that is not drawn"); + assert_eq!(crossed(&d, &through, [154.0, 4.0], [156.0, 6.0]), []); + assert_eq!(picked(&d, &through, [155.0, 0.0]), Some(dim), "the layer 0 part of that reference"); + assert_eq!(picked(&d, &[], [155.0, 5.0]), Some(dim), "where the layer is drawn"); +} + +/// Other objects whose block holds a point on the layer Defpoints, and a clipped reference inside +/// a block, built by hand in model space with the coordinates AutoCAD 2022 was given. +struct PointHolders { + /// The drawing that holds them. + d: cadcraft_engine::doc::Drawing, + /// A 2 x 2 array of references (MINSERT) from (0, -30), its rows 12 and its columns 15 apart, + /// to a block with a line on layer 0 and, 3 above its middle, a point on Defpoints. + array: Handle, + /// An annotative reference to that block at (40, -30), at the drawing's annotation scale. + scaled: Handle, + /// A multileader from (60, -30) to (75, -15) whose content is a block with a line on layer 0 + /// and, 8 above its middle, a point on Defpoints, at (72.36, -19), where AutoCAD put it. + leader: Handle, + /// A reference at (0, 10) to a block with a line on layer 0, 20 long, and two points on + /// Defpoints 3 above it, clipped (XCLIP) to the rectangle from (-2, 7) to (10, 16): the point + /// at (5, 13) is inside the boundary, the one at (15, 13) outside. + clipped: Handle, + /// A reference to a block with a line on layer 0 from (30, 10) to (40, 10) and, at (30, 15), a + /// reference on "Hidden" to the block of the array. + nested: Handle, + /// A reference on "Hidden" at (50, 10) to the block of the array. + hidden: Handle, + /// A dimension on "Hidden" like the one AutoCAD made for DIMLINEAR from (70, 5) to (90, 5), + /// with the dimension line at y = 20 and the extension lines starting 2 from those points. + dim: Handle, + /// A reference to a block with a line on layer 0 from (60, 36) to (70, 36) and a reference to + /// a block of one line on "Hidden", from (60, 30) to (70, 30), clipped to the rectangle from + /// (58, 27) to (72, 33). + framed: Handle, +} + +/// The drawing of [`PointHolders`]. +fn point_holders() -> PointHolders { + use cadcraft_engine::doc::{ + AnnoScale, Block, ClipBoundary, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Insert, Line, MLeader, Point, Space, + }; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Defpoints"); + d.ensure_layer("Hidden"); + let line = |a: [f64; 2], b: [f64; 2]| EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }); + let point = |p: [f64; 2]| EntityKind::Point(Point { p: Vec3::new(p[0], p[1], 0.0), angle: 0.0 }); + let reference = |block: &str, at: [f64; 2]| Insert { block: block.into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() }; + // A clip rectangle, in the coordinates of the clipped reference's block. + let rectangle = |a: [f64; 2], b: [f64; 2]| Some(ClipBoundary::new(vec![Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])])); + let mut define = |name: &str, parts: Vec<(EntityKind, &str)>| { + let mut block = Block::new(name); + for (i, (kind, layer)) in parts.into_iter().enumerate() { + let mut part = Entity::new(Handle(i as u64 + 1), kind); + part.common.layer = layer.into(); + block.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + }; + // BQ: a line on layer 0 and, 3 above its middle, a point on Defpoints. BMQ: the same, shorter, + // with the point 8 above. BCQ: a line 20 long and two such points. + define("BQ", vec![(line([0.0, 0.0], [10.0, 0.0]), "0"), (point([5.0, 3.0]), "Defpoints")]); + define("BMQ", vec![(line([0.0, 0.0], [6.0, 0.0]), "0"), (point([3.0, 8.0]), "Defpoints")]); + define("BCQ", vec![(line([0.0, 0.0], [20.0, 0.0]), "0"), (point([5.0, 3.0]), "Defpoints"), (point([15.0, 3.0]), "Defpoints")]); + // BNF: a line on layer 0 and a reference on "Hidden" to BQ. + define("BNF", vec![(line([30.0, 10.0], [40.0, 10.0]), "0"), (EntityKind::Insert(reference("BQ", [30.0, 15.0])), "Hidden")]); + // *D5: the two extension lines, the dimension line and the three definition points. + define( + "*D5", + vec![ + (line([70.0, 7.0], [70.0, 20.18]), "0"), + (line([90.0, 7.0], [90.0, 20.18]), "0"), + (line([70.18, 20.0], [89.82, 20.0]), "0"), + (point([70.0, 5.0]), "Defpoints"), + (point([90.0, 5.0]), "Defpoints"), + (point([90.0, 20.0]), "Defpoints"), + ], + ); + // BC2: one line, on "Hidden". BNC: a reference to it, clipped, and a line on layer 0. + define("BC2", vec![(line([0.0, 0.0], [10.0, 0.0]), "Hidden")]); + let inner = Insert { clip: rectangle([-2.0, -3.0], [12.0, 3.0]), ..reference("BC2", [60.0, 30.0]) }; + define("BNC", vec![(EntityKind::Insert(inner), "0"), (line([60.0, 36.0], [70.0, 36.0]), "0")]); + let model = Space::Model; + let on_hidden = || Common { layer: "Hidden".into(), ..Common::default() }; + let grid = Insert { cols: 2, rows: 2, col_spacing: 15.0, row_spacing: 12.0, ..reference("BQ", [0.0, -30.0]) }; + let array = d.add(&model, Common::default(), EntityKind::Insert(grid)).unwrap(); + let annotative = Common { anno_scales: vec![AnnoScale::unit()], ..Common::default() }; + let scaled = d.add(&model, annotative, EntityKind::Insert(reference("BQ", [40.0, -30.0]))).unwrap(); + let leader = MLeader { + leaders: vec![vec![Vec3::new(60.0, -30.0, 0.0)]], + landing: Vec3::new(75.0, -15.0, 0.0), + dogleg: 0.36, + text: None, + style: "Standard".into(), + arrow_size: 0.18, + spline: false, + block: Some(reference("BMQ", [72.36, -19.0])), + }; + let leader = d.add(&model, Common::default(), EntityKind::MLeader(leader)).unwrap(); + let cut = Insert { clip: rectangle([-2.0, -3.0], [10.0, 6.0]), ..reference("BCQ", [0.0, 10.0]) }; + let clipped = d.add(&model, Common::default(), EntityKind::Insert(cut)).unwrap(); + let nested = d.add(&model, Common::default(), EntityKind::Insert(reference("BNF", [0.0, 0.0]))).unwrap(); + let hidden = d.add(&model, on_hidden(), EntityKind::Insert(reference("BQ", [50.0, 10.0]))).unwrap(); + let dimension = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(90.0, 20.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::new(70.0, 5.0, 0.0), + p14: Vec3::new(90.0, 5.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("*D5".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let dim = d.add(&model, on_hidden(), EntityKind::Dimension(dimension)).unwrap(); + let framed = d.add(&model, Common::default(), EntityKind::Insert(reference("BNC", [0.0, 0.0]))).unwrap(); + PointHolders { d, array, scaled, leader, clipped, nested, hidden, dim, framed } +} + +/// A point on the layer Defpoints counts in every object that draws a block: in the copies of an +/// array of references (MINSERT), in an annotative reference and in the block a multileader +/// shows. AutoCAD 2022 selects each by a pick and a crossing window on such a point with +/// Defpoints frozen in the viewport, and a window must hold the points. They have the +/// coordinates AutoCAD was given and its answers. The frozen layers are given to the selection +/// as a viewport gives them. +#[test] +fn a_point_on_defpoints_counts_in_arrays_annotative_references_and_multileaders() { + let PointHolders { d, array, scaled, leader, .. } = point_holders(); + let through = ["Defpoints".to_string(), "Hidden".to_string()]; + // The array: the points of the first and of the last copy. + assert_eq!(picked(&d, &through, [5.0, -27.0]), Some(array), "the point of the first copy"); + assert_eq!(picked(&d, &through, [20.0, -15.0]), Some(array), "the point of the last copy"); + assert_eq!(crossed(&d, &through, [19.5, -15.5], [20.5, -14.5]), [array], "a crossing window over the last copy's point"); + assert_eq!(windowed(&d, &through, [-1.0, -31.0], [26.0, -17.0]), [], "a window that leaves out the upper row's points"); + assert_eq!(windowed(&d, &through, [-1.0, -31.0], [26.0, -14.0]), [array], "a window around all of the array"); + // The annotative reference. + assert_eq!(picked(&d, &through, [45.0, -27.0]), Some(scaled), "the point of the annotative reference"); + assert_eq!(crossed(&d, &through, [44.5, -27.5], [45.5, -26.5]), [scaled], "a crossing window over it"); + assert_eq!(windowed(&d, &through, [39.0, -31.0], [51.0, -29.0]), [], "a window around its line alone"); + assert_eq!(windowed(&d, &through, [39.0, -31.0], [51.0, -26.0]), [scaled], "a window around its line and its point"); + // The multileader: the point of its block lies at (75.36, -11), its line runs from (72.36, -19). + assert_eq!(picked(&d, &through, [75.36, -11.0]), Some(leader), "the point of the multileader's block"); + assert_eq!(crossed(&d, &through, [74.86, -11.5], [75.86, -10.5]), [leader], "a crossing window over it"); + assert_eq!(picked(&d, &through, [75.36, -19.0]), Some(leader), "the line of its block"); + assert_eq!(windowed(&d, &through, [58.0, -32.0], [80.36, -13.0]), [], "a window around its leader and the block's line alone"); + assert_eq!(windowed(&d, &through, [58.0, -32.0], [80.36, -9.0]), [leader], "a window around all of it"); +} + +/// A point on Defpoints is kept only where its block is drawn. AutoCAD 2022 does not select a +/// clipped reference (XCLIP) by such a point outside the clip boundary, a reference by such a +/// point in a nested reference whose own layer the viewport freezes, or a reference or a +/// dimension that is itself on a layer the viewport freezes; inside the boundary of the clipped +/// reference the point is hit. They have the coordinates AutoCAD was given and its answers. The +/// frozen layers are given to the selection as a viewport gives them. +#[test] +fn a_point_on_defpoints_is_not_kept_where_its_block_is_not_drawn() { + let PointHolders { d, clipped, nested, hidden, dim, .. } = point_holders(); + let through = ["Defpoints".to_string(), "Hidden".to_string()]; + // The clipped reference: the point inside the boundary and the one outside. + assert_eq!(picked(&d, &through, [5.0, 13.0]), Some(clipped), "the point inside the clip boundary"); + assert_eq!(picked(&d, &through, [15.0, 13.0]), None, "the point outside the clip boundary"); + assert_eq!(crossed(&d, &through, [14.5, 12.5], [15.5, 13.5]), [], "a crossing window over it"); + assert_eq!(windowed(&d, &through, [-4.0, 5.0], [12.0, 18.0]), [clipped], "a window around the boundary"); + // The nested reference on "Hidden": nothing of it is drawn, its point included. + assert_eq!(picked(&d, &through, [35.0, 18.0]), None, "the point of a nested reference on a frozen layer"); + assert_eq!(crossed(&d, &through, [34.5, 17.5], [35.5, 18.5]), [], "a crossing window over it"); + assert_eq!(picked(&d, &through, [35.0, 15.0]), None, "the line of that nested reference"); + assert_eq!(picked(&d, &through, [35.0, 10.0]), Some(nested), "the reference's own line"); + assert_eq!(windowed(&d, &through, [29.0, 9.0], [41.0, 11.0]), [nested], "a window around its own line alone"); + assert_eq!(picked(&d, &[], [35.0, 18.0]), Some(nested), "where the layers are drawn"); + // A reference and a dimension that are on "Hidden" themselves. + assert_eq!(picked(&d, &through, [55.0, 13.0]), None, "the point of a reference on a frozen layer"); + assert_eq!(picked(&d, &through, [55.0, 10.0]), None, "its line"); + assert_eq!(picked(&d, &[], [55.0, 13.0]), Some(hidden), "where the layers are drawn"); + assert_eq!(picked(&d, &through, [70.0, 5.0]), None, "a definition point of a dimension on a frozen layer"); + assert_eq!(crossed(&d, &through, [69.5, 4.5], [70.5, 5.5]), [], "a crossing window over it"); + assert_eq!(picked(&d, &through, [75.0, 20.0]), None, "its dimension line"); + assert_eq!(picked(&d, &[], [70.0, 5.0]), Some(dim), "where the layers are drawn"); +} + +/// A clipped reference (XCLIP) that is a part of a block keeps its boundary as well: AutoCAD 2022 +/// selects the outer reference by a pick or a crossing window on the boundary of the clipped one +/// with every part inside it on a layer frozen in the viewport, and a window must hold that +/// boundary. A pick on the part that is not drawn takes nothing. The pick on the top side of the +/// boundary holds the hit geometry: it lies inside the outer reference's box, away from its +/// sides. The shape is the one AutoCAD was given. The frozen layers are given to the selection +/// as a viewport gives them. +#[test] +fn a_clipped_reference_inside_a_block_is_selected_by_its_boundary() { + let PointHolders { d, framed, .. } = point_holders(); + let through = ["Defpoints".to_string(), "Hidden".to_string()]; + assert_eq!(picked(&d, &through, [58.0, 30.0]), Some(framed), "the left side of the nested clip boundary"); + assert_eq!(picked(&d, &through, [65.0, 33.0]), Some(framed), "its top side"); + assert_eq!(crossed(&d, &through, [57.0, 29.0], [59.0, 31.0]), [framed], "a crossing window over its left side"); + assert_eq!(picked(&d, &through, [65.0, 30.0]), None, "the clipped reference's line, which is not drawn"); + assert_eq!(picked(&d, &through, [65.0, 36.0]), Some(framed), "the outer reference's own line"); + assert_eq!(windowed(&d, &through, [59.0, 35.0], [71.0, 37.0]), [], "a window around its own line alone"); + assert_eq!(windowed(&d, &through, [56.0, 25.0], [74.0, 38.0]), [framed], "a window around its own line and the boundary"); + assert_eq!(picked(&d, &[], [65.0, 30.0]), Some(framed), "where the layer is drawn"); +} + +/// A dimension is drawn from its block, and a crossing window inside the rectangle around a +/// dimension does not take it as one inside a block reference's does (#2991), so a dimension +/// shows what a crossing window itself tests. Over a part of that block the viewport does not +/// draw, between two parts it draws, the window takes nothing, and neither do a pick and a +/// fence; over a drawn part they take the dimension. The frozen layers are given to the +/// selection as a viewport gives them. +#[test] +fn a_crossing_window_tests_the_parts_the_viewport_draws() { + use cadcraft_engine::doc::{Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Line, Space}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let mut block = Block::new("*D1"); + for (handle, y, layer) in [(1, 0.0, "0"), (2, 10.0, "0"), (3, 5.0, "Hidden")] { + let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) })); + part.common.layer = layer.into(); + block.entities.push(part); + } + d.blocks.insert("*D1".into(), std::sync::Arc::new(block)); + let dimension = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(5.0, 1.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("*D1".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let dim = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dimension)).unwrap(); + let frozen = ["Hidden".to_string()]; + let (model, hidden_part, drawn_part) = (Space::Model, Vec2::new(5.0, 5.0), Vec2::new(5.0, 10.0)); + let over = |p: Vec2| Bounds2::new(Vec2::new(p.x - 1.0, p.y - 1.0), Vec2::new(p.x + 1.0, p.y + 1.0)); + let across = |p: Vec2| [Vec2::new(p.x, p.y - 1.0), Vec2::new(p.x, p.y + 1.0)]; + assert_eq!(select::select_window_in(&d, &model, &frozen, over(hidden_part), true), [], "a crossing window over the part that is not drawn"); + assert_eq!(select::pick_in(&d, &model, &frozen, hidden_part, 0.2), None, "a pick on it"); + assert_eq!(select::select_fence_in(&d, &model, &frozen, &across(hidden_part)), [], "a fence across it"); + assert_eq!(select::select_window_in(&d, &model, &frozen, over(drawn_part), true), [dim], "a crossing window over a drawn part"); + assert_eq!(select::pick_in(&d, &model, &frozen, drawn_part, 0.2), Some(dim)); + assert_eq!(select::select_window_in(&d, &model, &[], over(hidden_part), true), [dim], "where the layer is drawn"); + assert_eq!(select::pick_in(&d, &model, &[], hidden_part, 0.2), Some(dim)); + assert_eq!(select::select_fence_in(&d, &model, &[], &across(hidden_part)), [dim]); +} + +/// A proxy that is a part of a block draws its proxy graphics as the block draws its other parts, +/// so through a viewport the reference is measured and hit by the graphics that viewport draws: +/// with the proxy's line on a layer frozen there, a window around the reference's own line alone +/// takes it and a pick on the proxy's line finds nothing. Where the layer is drawn that window +/// misses the reference and the pick takes it. A proxy is never selected itself (it is kept as it +/// was read), so it counts only this way. The frozen layers are given to the selection as a +/// viewport gives them. +#[test] +fn a_proxy_in_a_block_counts_by_the_graphics_the_viewport_draws() { + use cadcraft_engine::doc::{Block, Common, Drawing, Entity, EntityKind, Insert, Line, Space, Unknown}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let line = |y: f64, layer: &str| { + let mut g = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) })); + g.common.layer = layer.into(); + g + }; + let proxy = Entity::new( + Handle(2), + EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![line(5.0, "Hidden")] }), + ); + let mut block = Block::new("BX"); + block.entities.push(Entity { handle: Handle(1), ..line(0.0, "0") }); + block.entities.push(proxy); + d.blocks.insert("BX".into(), std::sync::Arc::new(block)); + let reference = d.add(&Space::Model, Common::default(), EntityKind::Insert(Insert { block: "BX".into(), ..Insert::default() })).unwrap(); + let through = ["Hidden".to_string()]; + assert_eq!(windowed(&d, &through, [-1.0, -1.0], [11.0, 1.0]), [reference], "a window around the reference's own line alone"); + assert_eq!(picked(&d, &through, [5.0, 5.0]), None, "a pick on the proxy's line"); + assert_eq!(picked(&d, &through, [5.0, 0.0]), Some(reference), "a pick on the reference's own line"); + assert_eq!(windowed(&d, &[], [-1.0, -1.0], [11.0, 1.0]), [], "where the layer is drawn, the same window"); + assert_eq!(picked(&d, &[], [5.0, 5.0]), Some(reference), "and the same pick"); +} + +/// A constant attribute's value is drawn by every reference to its block, from the definition, +/// and counts in the reference's box. With the definition on a layer frozen in the viewport the +/// value is not drawn there: a window around the reference's line alone takes the reference and +/// a pick on the value finds nothing. Where the layer is drawn that window misses the reference +/// and the pick takes it. The frozen layers are given to the selection as a viewport gives them. +#[test] +fn a_constant_attribute_value_counts_where_the_viewport_draws_it() { + use cadcraft_engine::doc::{Attrib, Block, Common, Drawing, Entity, EntityKind, HAlign, Insert, Line, Space, Text, VAlign}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let value = Text { + insert: Vec3::new(0.0, 5.0, 0.0), + align_pt: None, + height: 2.0, + value: "HHHH".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + backwards: false, + upside_down: false, + }; + let constant = Attrib { + tag: "TAG".into(), + text: value, + invisible: false, + constant: true, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }; + let mut definition = Entity::new(Handle(2), EntityKind::AttDef(constant)); + definition.common.layer = "Hidden".into(); + let mut line = Entity::new(Handle(1), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) })); + line.common.layer = "0".into(); + let mut block = Block::new("BC"); + block.entities.push(line); + block.entities.push(definition); + d.blocks.insert("BC".into(), std::sync::Arc::new(block)); + let reference = d.add(&Space::Model, Common::default(), EntityKind::Insert(Insert { block: "BC".into(), ..Insert::default() })).unwrap(); + let through = ["Hidden".to_string()]; + let (around_the_line, on_the_value) = (([-1.0, -1.0], [11.0, 1.0]), [1.0, 6.0]); + assert_eq!(windowed(&d, &through, around_the_line.0, around_the_line.1), [reference], "a window around the reference's line alone"); + assert_eq!(picked(&d, &through, on_the_value), None, "a pick on the value that is not drawn"); + assert_eq!(picked(&d, &through, [5.0, 0.0]), Some(reference), "a pick on the line"); + assert_eq!(windowed(&d, &[], around_the_line.0, around_the_line.1), [], "where the layer is drawn, the same window"); + assert_eq!(picked(&d, &[], on_the_value), Some(reference), "and the same pick"); + assert_eq!(windowed(&d, &[], [-1.0, -1.0], [11.0, 9.0]), [reference], "and a window around the line and the value"); +} + +/// A horizontal dimension from (0, 5) and (40, 15), its line along y = 40, drawn from a block +/// built by hand with the coordinates of the block AutoCAD made, without the arrowheads and the +/// definition points: two extension lines and the two halves of the dimension line on layer 0, +/// and between them the text, 3 high, on the layer "Hidden". The drawing and the dimension. +fn dimension_with_its_text_on_hidden() -> (cadcraft_engine::doc::Drawing, Handle) { + use cadcraft_engine::doc::{Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Line, MText, Space}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + // A horizontal dimension from (0, 5) and (40, 15) with its line along y = 40 and text 3 high: + // two extension lines, the two halves of the dimension line, and the text between them. + let mut block = Block::new("*D5"); + let lines = [([0.0, 5.063], [0.0, 40.18]), ([40.0, 15.063], [40.0, 40.18]), ([2.0, 40.0], [12.462, 40.0]), ([38.0, 40.0], [27.538, 40.0])]; + for (handle, (a, b)) in (1..).zip(lines) { + let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) })); + part.common.layer = "0".into(); + block.entities.push(part); + } + let words = MText { + insert: Vec3::new(20.0, 40.0, 0.0), + height: 3.0, + width: 0.0, + attach: 5, + rotation: 0.0, + style: "Standard".into(), + contents: "\\A1;40.0000".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: None, + }; + let mut text = Entity::new(Handle(5), EntityKind::MText(words)); + text.common.layer = "Hidden".into(); + block.entities.push(text); + d.blocks.insert("*D5".into(), std::sync::Arc::new(block)); + let dimension = Dimension { + kind: DimKind::Linear { rotation: 0.0 }, + defpt: Vec3::new(40.0, 40.0, 0.0), + text_mid: Vec3::new(20.0, 40.0, 0.0), + p13: Vec3::new(0.0, 5.0, 0.0), + p14: Vec3::new(40.0, 15.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("*D5".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let dim = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dimension)).unwrap(); + (d, dim) +} + +/// A dimension is picked anywhere inside the box of its text, and that text is a part of its +/// block. Through a viewport that freezes the text's layer the text is not drawn: a pick in its +/// box finds nothing there and selection cycling lists nothing, while the lines of the dimension +/// are picked as before and a window around all of it takes it. Where the text is drawn a pick +/// in its middle takes the dimension. AutoCAD 2022 was given this dimension, with the text of +/// its block moved to "Hidden", and answers every case asserted here the same way +/// ([`dimension_with_its_text_on_hidden`]). The frozen layers are given to the selection as a +/// viewport gives them. +/// +/// A crossing window inside the box of that text takes nothing through the viewport, as it took +/// nothing before a selection counted the viewport's layers and as AutoCAD answers: the rectangle +/// around the dimension, which is hit along its sides (#2991), keeps the room of the text the +/// viewport leaves out, so no side of it runs through that box. Its top side, at the top of that room, is hit by a pick, selection cycling, a +/// crossing window, a fence and a crossing polygon beside the text, as where the text is drawn. A +/// window polygon takes what a window of the same shape takes. +/// +/// One answer of AutoCAD is not matched and not asserted: with the layer frozen for the whole +/// drawing or turned off it picks nothing in that box either, where CADCraft picks the dimension +/// as it did before this change, which leaves what a drawing-wide layer state does alone. +#[test] +fn a_dimension_is_not_picked_on_text_that_is_not_drawn() { + use cadcraft_engine::doc::Space; + let (d, dim) = dimension_with_its_text_on_hidden(); + let through = ["Hidden".to_string()]; + let (middle, dimension_line, extension_line) = ([20.0, 40.0], [3.0, 40.0], [0.0, 20.0]); + let cycled = |frozen: &[String], p: [f64; 2]| select::pick_all_in(&d, &Space::Model, frozen, Vec2::new(p[0], p[1]), 0.2); + // AutoCAD was picked at a grid of 27 points inside the box of the text (14.896 by 3.063 + // there) and took nothing at any of them: three rows of nine, each point more than 2 away + // from the lines. Its crossing window, from the third point of the lowest row to the seventh + // of the top row, took nothing either. + let grid: Vec<[f64; 2]> = (0..9).flat_map(|i| (0..3).map(move |j| [14.704 + 1.324 * f64::from(i), 39.387 + 0.613 * f64::from(j)])).collect(); + let inside_the_text = ([17.352, 39.387], [22.648, 40.613]); + assert_eq!(picked(&d, &[], middle), Some(dim), "where the text is drawn"); + assert_eq!(cycled(&[], middle), [dim]); + assert_eq!(picked(&d, &through, middle), None, "a pick in the middle of the text that is not drawn"); + assert_eq!(cycled(&through, middle), [], "selection cycling there"); + for p in grid { + assert_eq!(picked(&d, &through, p), None, "a pick inside the box of the text at {p:?}"); + } + assert_eq!(picked(&d, &through, dimension_line), Some(dim), "the dimension line"); + assert_eq!(picked(&d, &through, extension_line), Some(dim), "an extension line"); + assert_eq!(crossed(&d, &through, inside_the_text.0, inside_the_text.1), [], "a crossing window inside the box of the text that is not drawn"); + assert_eq!(crossed(&d, &through, [2.5, 39.0], [3.5, 41.0]), [dim], "a crossing window over the dimension line"); + assert_eq!(windowed(&d, &through, [-2.0, 3.0], [42.0, 43.0]), [dim], "a window around all of it"); + // The top side of the rectangle the dimension is hit along lies at the top of the text's + // room, beyond what the viewport draws, where it lay before: a selection that touches that + // side beside the text takes the dimension as it does where the text is drawn. + let top_side = [31.0, 42.49]; + let poly = |a: [f64; 2], b: [f64; 2]| [Vec2::new(a[0], a[1]), Vec2::new(b[0], a[1]), Vec2::new(b[0], b[1]), Vec2::new(a[0], b[1])]; + for frozen in [&through[..], &[]] { + let near = |dx: f64, dy: f64| [top_side[0] + dx, top_side[1] + dy]; + assert_eq!(picked(&d, frozen, top_side), Some(dim), "a pick on the top side, {frozen:?} frozen"); + assert_eq!(cycled(frozen, top_side), [dim], "selection cycling there, {frozen:?} frozen"); + assert_eq!(crossed(&d, frozen, near(-1.0, -0.5), near(1.0, 0.5)), [dim], "a crossing window over it, {frozen:?} frozen"); + assert_eq!(fenced(&d, frozen, near(0.0, -0.5), near(0.0, 0.5)), [dim], "a fence across it, {frozen:?} frozen"); + let crossing_polygon = select::select_polygon_in(&d, &Space::Model, frozen, &poly(near(-1.0, -0.5), near(1.0, 0.5)), true); + assert_eq!(crossing_polygon, [dim], "a crossing polygon over it, {frozen:?} frozen"); + } + // A window polygon takes what a window of the same shape takes, through the viewport too. + for (a, b) in [([-1.0, 4.0], [41.0, 41.0]), ([-2.0, 3.0], [42.0, 43.0])] { + for frozen in [&through[..], &[]] { + let window_polygon = select::select_polygon_in(&d, &Space::Model, frozen, &poly(a, b), false); + assert_eq!(window_polygon, windowed(&d, frozen, a, b), "a window polygon from {a:?} to {b:?}, {frozen:?} frozen"); + } + } +} + +/// Text the drawing itself hides (its layer frozen for the whole drawing, or turned off) had no +/// room in the rectangle a dimension is hit along before a viewport was counted, and a viewport +/// that freezes the layer as well gives it none: the selections that take the dimension by the +/// top side of that rectangle while only the viewport hides the text +/// ([`a_dimension_is_not_picked_on_text_that_is_not_drawn`]) take nothing there, through that +/// viewport as through one that freezes nothing, and the dimension line is hit as before. The +/// frozen layers are given to the selection as a viewport gives them. +#[test] +fn text_the_drawing_hides_keeps_no_room_in_a_dimensions_rectangle() { + use cadcraft_engine::doc::Space; + let (mut d, dim) = dimension_with_its_text_on_hidden(); + let through = ["Hidden".to_string()]; + let (top_side, dimension_line) = ([31.0, 42.49], [3.0, 40.0]); + let poly = |a: [f64; 2], b: [f64; 2]| [Vec2::new(a[0], a[1]), Vec2::new(b[0], a[1]), Vec2::new(b[0], b[1]), Vec2::new(a[0], b[1])]; + for off in [false, true] { + let layer = d.layer_mut("Hidden").unwrap(); + (layer.frozen, layer.on) = (!off, !off); + for frozen in [&through[..], &[]] { + let near = |dx: f64, dy: f64| [top_side[0] + dx, top_side[1] + dy]; + let hidden = format!("the layer {}, {frozen:?} frozen in the viewport", if off { "turned off" } else { "frozen for the drawing" }); + assert_eq!(picked(&d, frozen, top_side), None, "a pick on the top side, {hidden}"); + assert_eq!( + select::pick_all_in(&d, &Space::Model, frozen, Vec2::new(top_side[0], top_side[1]), 0.2), + [], + "selection cycling there, {hidden}" + ); + assert_eq!(crossed(&d, frozen, near(-1.0, -0.5), near(1.0, 0.5)), [], "a crossing window over it, {hidden}"); + assert_eq!(fenced(&d, frozen, near(0.0, -0.5), near(0.0, 0.5)), [], "a fence across it, {hidden}"); + let crossing_polygon = select::select_polygon_in(&d, &Space::Model, frozen, &poly(near(-1.0, -0.5), near(1.0, 0.5)), true); + assert_eq!(crossing_polygon, [], "a crossing polygon over it, {hidden}"); + assert_eq!(picked(&d, frozen, dimension_line), Some(dim), "the dimension line, {hidden}"); + } + } +} + +/// The selections of a grid across the five references, with what each finds: at every point a +/// pick, selection cycling's list, a crossing window, a fence, two windows and the two polygons. +fn probes(s: &Session) -> Vec<(String, Vec)> { + let mut out = Vec::new(); + for xi in -2..=92 { + for yi in -2..=12 { + let (x, y) = (f64::from(xi), f64::from(yi)); + out.push((format!("pick at ({x}, {y})"), pick(s, [x, y]).into_iter().collect())); + out.push((format!("cycling list at ({x}, {y})"), pick_all(s, [x, y]))); + out.push((format!("crossing window from ({x}, {y})"), window(s, [x, y], [x + 2.0, y + 2.0], true))); + out.push((format!("fence through ({x}, {y})"), fence(s, &[[x, y - 1.0], [x, y + 1.0]]))); + out.push((format!("low window from ({x}, {y})"), window(s, [x, y], [x + 13.0, y + 2.0], false))); + out.push((format!("tall window from ({x}, {y})"), window(s, [x, y], [x + 13.0, y + 12.0], false))); + out.push((format!("window polygon from ({x}, {y})"), polygon(s, &[[x, y], [x + 13.0, y], [x + 6.0, y + 3.0]], false))); + out.push((format!("crossing polygon from ({x}, {y})"), polygon(s, &[[x, y], [x + 2.0, y], [x + 1.0, y + 2.0]], true))); + } + } + out +} + +/// Through a viewport that freezes a layer every selection answers as it does on the Model tab +/// with that layer frozen for the whole drawing: each selection of a grid across the references, +/// with and without the spatial index. That holds for what is taken through the rectangle around +/// a reference too (#2991): it is the rectangle around the drawn parts in both, and a part that is +/// not drawn changes nothing inside it. +#[test] +fn a_layer_frozen_in_the_viewport_selects_as_one_frozen_for_the_drawing_does() { + for crowded in [false, true] { + let Parts { mut s, r, h, n, z, q, a, .. } = parts(crowded); + enter(&mut s, &a); + let through_the_viewport = probes(&s); + let Parts { s: mut model, r: r2, h: h2, n: n2, z: z2, q: q2, .. } = parts(crowded); + assert_eq!([r, h, n, z, q], [r2, h2, n2, z2, q2], "the two drawings must be made alike"); + model.execute("layout.set", &json!({ "name": "Model" })).unwrap(); + model.execute("layer.set", &json!({ "name": "Hidden", "frozen": true })).unwrap(); + let frozen_for_the_drawing = probes(&model); + assert_eq!(through_the_viewport.len(), frozen_for_the_drawing.len()); + for (through, frozen) in through_the_viewport.iter().zip(&frozen_for_the_drawing) { + assert_eq!(through, frozen, "through the viewport, then with the layer frozen for the drawing (indexed: {crowded})"); + } + // The grid does select: each reference with a drawn part many times, the one without never. + let times = |x: Handle| through_the_viewport.iter().filter(|(_, hs)| hs.contains(&x)).count(); + assert!([r, n, z, q].iter().all(|x| times(*x) > 50), "taken {:?} times (indexed: {crowded})", [r, n, z, q].map(times)); + assert_eq!(times(h), 0, "a reference with nothing drawn was selected (indexed: {crowded})"); + } +} + +/// Nothing changes where no viewport freezes the layer: on the Model tab both parts are hit and +/// both take room, and with the layer frozen for the whole drawing the part is left out there +/// as it always was. +#[test] +fn the_model_tab_and_a_layer_frozen_for_the_drawing_are_as_before() { + for crowded in [false, true] { + let Parts { mut s, r, h, .. } = parts(crowded); + s.execute("layout.set", &json!({ "name": "Model" })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "the Model tab draws both parts (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), []); + assert_eq!(pick(&s, [25.0, 5.0]), Some(h)); + s.execute("layer.set", &json!({ "name": "Hidden", "frozen": true })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), None, "frozen for the whole drawing (indexed: {crowded})"); + assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), []); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r]); + assert_eq!(pick(&s, [25.0, 5.0]), None); + assert_eq!(pick(&s, [5.0, 0.0]), Some(r)); + } +} diff --git a/crates/engine/tests/it/viewport_frozen_selection.rs b/crates/engine/tests/it/viewport_frozen_selection.rs index 317e1bc6e..cb339c131 100644 --- a/crates/engine/tests/it/viewport_frozen_selection.rs +++ b/crates/engine/tests/it/viewport_frozen_selection.rs @@ -781,3 +781,55 @@ fn a_small_and_a_large_selection_leave_out_the_same_objects() { s.set_selection(all.clone()); assert_eq!(s.selection(), all); } + +/// EXTRIM through a viewport leaves the objects on layers frozen there, as a fence through it +/// selects only what it draws (landing review of #2808). +#[test] +fn extrim_through_a_viewport_leaves_layers_frozen_there() { + for (frozen_here, hidden_trimmed) in [(true, false), (false, true)] { + let Sheet { mut s, shown, hidden, a, b } = sheet(); + enter(&mut s, if frozen_here { &a } else { &b }); + let edge = line(&mut s, [5.0, -5.0], [5.0, 5.0]); + s.execute("extrim", &json!({ "edge": edge.hex(), "side": [8.0, 1.0] })).unwrap(); + assert!(edited(&s, shown), "the drawn line is trimmed"); + assert_eq!(edited(&s, hidden), hidden_trimmed, "frozen in this viewport: {frozen_here}"); + } +} + +/// #3526 review: EXTRIM's preview follows a change of the frozen layers while it runs. +#[test] +fn extrims_preview_follows_the_frozen_layers_while_it_runs() { + let Sheet { mut s, b, .. } = sheet(); + enter(&mut s, &b); + let edge = line(&mut s, [5.0, -5.0], [5.0, 5.0]); + s.set_selection(Vec::new()); + s.start("extrim").unwrap(); + s.input(cadcraft_engine::Input::Pick(vec![edge])).unwrap(); + let side = Vec2::new(8.0, 1.0); + assert_eq!(s.preview(side).len(), 2, "both lines lose their right half"); + s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap(); + assert!(s.running.is_some(), "EXTRIM is still running"); + assert_eq!(s.preview(side).len(), 1, "the line now frozen here is left, and not previewed"); +} + +/// #3526 review: a cutting edge picked in paper space cuts nothing once MSPACE moves into a +/// viewport, so EXTRIM previews nothing there and the trim is refused with the drawing unchanged. +#[test] +fn an_extrim_edge_left_in_paper_space_previews_and_cuts_nothing_in_a_viewport() { + let Sheet { mut s, shown, hidden, b, .. } = sheet(); + // In paper space: an edge and one line crossing it, where model space has two. + let edge = line(&mut s, [5.0, -5.0], [5.0, 5.0]); + let paper = line(&mut s, [0.0, 0.0], [10.0, 0.0]); + s.set_selection(Vec::new()); + s.start("extrim").unwrap(); + s.input(cadcraft_engine::Input::Pick(vec![edge])).unwrap(); + let side = Vec2::new(8.0, 1.0); + assert_eq!(s.preview(side).len(), 1, "paper space: its one line"); + s.execute("mspace", &json!({ "handle": b })).unwrap(); + assert_eq!(s.space(), Space::Model); + assert!(s.viewport_frozen().is_empty(), "the viewport freezes nothing"); + assert!(s.running.is_some(), "EXTRIM is still running"); + assert!(s.preview(side).is_empty(), "the edge is not in model space: nothing previewed"); + let _ = s.input(cadcraft_engine::Input::Point(side)); + assert!(untouched(&s, shown) && untouched(&s, hidden) && untouched(&s, paper), "nothing was trimmed"); +} diff --git a/crates/engine/tests/it/viewport_ucs_copy.rs b/crates/engine/tests/it/viewport_ucs_copy.rs new file mode 100644 index 000000000..14fe9fb41 --- /dev/null +++ b/crates/engine/tests/it/viewport_ucs_copy.rs @@ -0,0 +1,86 @@ +//! COPY and MIRROR of a layout viewport keep its own UCS and its unmodelled settings (#1316): they +//! belong to the viewport, like its view. + +use cadcraft_doc::{EntityKind, Handle, RawTag, Space, Viewport, ViewportUcs}; +use cadcraft_engine::Session; +use cadcraft_geom::Vec3; +use serde_json::json; + +fn viewports(s: &Session) -> Vec<(Handle, Viewport)> { + let d = s.doc().unwrap(); + d.layout("Layout1") + .unwrap() + .entities + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Viewport(v) if v.id != 1 => Some((e.handle, v.clone())), + _ => None, + }) + .collect() +} + +fn ucs() -> ViewportUcs { + ViewportUcs { + origin: Vec3::new(100.0, 50.0, 0.0), + x_axis: Vec3::new(0.0, 1.0, 0.0), + y_axis: Vec3::new(-1.0, 0.0, 0.0), + elevation: 2.5, + ortho: 0, + named: Some("SITE".into()), + base: None, + } +} + +fn extra() -> Vec { + vec![RawTag { code: 1, value: "monochrome.ctb".into() }, RawTag { code: 15, value: "10.0".into() }, RawTag { code: 170, value: "2".into() }] +} + +/// Layout1 with one viewport that has its own UCS and settings. +fn session() -> (Session, Handle) { + let mut s = Session::new(); + s.new_drawing(true); + s.execute("line", &json!({"points": [[0, 0], [100, 100]]})).unwrap(); + s.execute("layout.set", &json!({"name": "Layout1"})).unwrap(); + let old: Vec = viewports(&s).iter().map(|(h, _)| h.hex()).collect(); + if !old.is_empty() { + s.execute("erase", &json!({"handles": old})).unwrap(); + } + s.execute("mview", &json!({"p1": [10, 10], "p2": [110, 80]})).unwrap(); + let (h, _) = viewports(&s).into_iter().next().unwrap(); + let d = s.doc_mut().unwrap(); + let store = d.space_mut(&Space::Paper("Layout1".into())).unwrap(); + let mut e = (**store.get(h).unwrap()).clone(); + if let EntityKind::Viewport(v) = &mut e.kind { + v.ucs = Some(ucs()); + v.ucs_per_viewport = true; + v.extra = extra(); + } + assert!(store.replace(e)); + (s, h) +} + +fn assert_kept(v: &Viewport) { + assert_eq!(v.ucs, Some(ucs())); + assert!(v.ucs_per_viewport); + assert_eq!(v.extra, extra()); +} + +#[test] +fn copy_keeps_a_viewport_s_ucs_and_settings() { + let (mut s, h) = session(); + s.execute("copy", &json!({"handles": [h.hex()], "delta": [150, 0]})).unwrap(); + let vps = viewports(&s); + assert_eq!(vps.len(), 2); + for (_, v) in &vps { + assert_kept(v); + } +} + +#[test] +fn mirror_keeps_a_viewport_s_ucs_and_settings() { + let (mut s, h) = session(); + s.execute("mirror", &json!({"handles": [h.hex()], "p1": [0, 100], "p2": [10, 100]})).unwrap(); + for (_, v) in &viewports(&s) { + assert_kept(v); + } +} diff --git a/crates/engine/tests/it/xdata_api.rs b/crates/engine/tests/it/xdata_api.rs new file mode 100644 index 000000000..0945acfe5 --- /dev/null +++ b/crates/engine/tests/it/xdata_api.rs @@ -0,0 +1,246 @@ +//! Extended data (xdata) through the API: `entities` shows it when asked (`xdata: true`, or an +//! application name that also filters), `properties` lists it, and `properties.set` replaces or +//! removes one application's data, checked as hostile input; what is set is written to DXF with +//! its APPID record and read back the same. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::{Value, json}; + +/// A LINE with a hyperlink and another application's data, a circle without any, and an +/// LWPOLYLINE with the second application's data. +const DXF: &str = "0\nSECTION\n2\nENTITIES\n\ +0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\ +1001\nPE_URL\n1000\nhttps://example.com/door-7\n1002\n{\n1000\nDoor 7\n1002\n}\n\ +1001\nACME_TAGS\n1000\nD-07\n1070\n3\n1040\n2.5\n1071\n70000\n1010\n1.5\n1020\n2.5\n1030\n0\n1005\n2B\n1004\n0AFF\n\ +0\nCIRCLE\n5\n2C\n8\n0\n10\n50\n20\n50\n30\n0\n40\n5\n\ +0\nLWPOLYLINE\n5\n2B\n8\n0\n90\n3\n70\n0\n10\n0\n20\n5\n10\n5\n20\n5\n10\n5\n20\n10\n\ +1001\nACME_TAGS\n1000\nP-01\n\ +0\nENDSEC\n0\nEOF\n"; + +fn session_from(dxf: &str) -> Session { + let d = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "xdata", None); + s +} + +fn entities(s: &mut Session, p: Value) -> Vec { + s.execute("entities", &p).unwrap()["entities"].as_array().unwrap().clone() +} + +fn handle_of(s: &Session, line: bool) -> String { + s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Line(_)) == line).map(|e| e.handle.hex()).unwrap() +} + +#[test] +fn entities_show_xdata_only_when_asked() { + let mut s = session_from(DXF); + let plain = entities(&mut s, json!({})); + assert_eq!(plain.len(), 3); + assert!(plain.iter().all(|e| e.get("xdata").is_none()), "{plain:?}"); + + let all = entities(&mut s, json!({"xdata": true})); + let line = all.iter().find(|e| e["type"] == "Line").unwrap(); + assert_eq!(line["xdata"]["PE_URL"], json!([[1000, "https://example.com/door-7"], [1002, "{"], [1000, "Door 7"], [1002, "}"]])); + assert_eq!( + line["xdata"]["ACME_TAGS"], + json!([[1000, "D-07"], [1070, 3], [1040, 2.5], [1071, 70000], [1010, [1.5, 2.5, 0.0]], [1005, "2B"], [1004, "0AFF"]]) + ); + assert!(all.iter().find(|e| e["type"] == "Circle").unwrap().get("xdata").is_none(), "no xdata, no key"); + assert_eq!(s.execute("entities", &json!({"xdata": false})).unwrap()["entities"], json!(plain)); + + // An application name keeps only the entities carrying its data and shows just that. + let acme = entities(&mut s, json!({"xdata": "acme_tags"})); + assert_eq!(acme.len(), 2); + assert!(acme.iter().all(|e| e["xdata"].as_object().unwrap().keys().eq(["ACME_TAGS"])), "{acme:?}"); + let r = s.execute("entities", &json!({"xdata": ["PE_URL"], "type": "Line"})).unwrap(); + assert_eq!((r["count"].as_u64(), r["returned"].as_u64()), (Some(1), Some(1))); + assert_eq!(s.execute("entities", &json!({"xdata": ["NOPE"]})).unwrap()["count"], 0); + for bad in [json!({"xdata": 1}), json!({"xdata": []}), json!({"xdata": [1]}), json!({"xdata": {"app": true}})] { + assert!(s.execute("entities", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn properties_set_replaces_removes_and_round_trips_through_dxf() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let h = handle_of(&s, true); + // A 1005 handle refers to an object of the drawing (here the line itself): saving remaps it + // with the other references, so one that refers to nothing would come back as 0. + let acme = json!([ + [1000, "D-07"], + [1002, "{"], + [1003, "0"], + [1004, "0aff"], + [1005, h.to_ascii_lowercase()], + [1010, [1.5, 2.5]], + [1011, [1, 2, 3]], + [1040, 2.5], + [1041, -1.0], + [1042, 1e3], + [1070, -3], + [1071, 70000], + [1002, "}"] + ]); + let want = json!([ + [1000, "D-07"], + [1002, "{"], + [1003, "0"], + [1004, "0AFF"], + [1005, h], + [1010, [1.5, 2.5, 0.0]], + [1011, [1.0, 2.0, 3.0]], + [1040, 2.5], + [1041, -1.0], + [1042, 1000.0], + [1070, -3], + [1071, 70000], + [1002, "}"] + ]); + let r = s.execute("properties.set", &json!({"handles": [h], "xdata": {"ACME": acme, "PE_URL": [[1000, "https://example.com"]]}})).unwrap(); + assert_eq!(r["changed"], 1); + let got = &entities(&mut s, json!({"xdata": true}))[0]["xdata"]; + assert_eq!(got["ACME"], want); + assert_eq!(got["PE_URL"], json!([[1000, "https://example.com"]])); + // `properties` lists it too. + let props = s.execute("properties", &json!({"handles": [h]})).unwrap(); + assert_eq!(props["objects"][0]["xdata"]["ACME"], want); + + // Saved and read back the same, with an APPID record for each application. + let text = cadcraft_io::write_dxf(s.doc().unwrap()); + let tags = craft_dxf::parse_ascii(&text).unwrap(); + let appids: Vec = + craft_dxf::records(&tags).iter().filter(|(k, _)| k == "APPID").filter_map(|(_, t)| t.iter().find(|t| t.code == 2).map(|t| t.str())).collect(); + assert!(appids.contains(&"ACME".to_string()) && appids.contains(&"PE_URL".to_string()), "{appids:?}"); + let mut back = session_from(&text); + assert_eq!(handle_of(&back, true), h, "the line keeps its handle"); + let again = &entities(&mut back, json!({"xdata": true}))[0]["xdata"]; + assert_eq!(again, got, "{text}"); + + // Replacing one application leaves the other; null removes; undo brings it back. + s.execute("properties.set", &json!({"handles": [h], "xdata": {"ACME": [[1070, 9]]}})).unwrap(); + let got = &entities(&mut s, json!({"xdata": true}))[0]["xdata"]; + assert_eq!(got, &json!({"ACME": [[1070, 9]], "PE_URL": [[1000, "https://example.com"]]})); + s.execute("properties.set", &json!({"handles": [h], "xdata": {"PE_URL": null, "ACME": []}})).unwrap(); + assert!(entities(&mut s, json!({"xdata": true}))[0].get("xdata").is_none()); + s.undo().unwrap(); + assert_eq!(entities(&mut s, json!({"xdata": true}))[0]["xdata"]["ACME"], json!([[1070, 9]])); + // The xdata of a drawing's own file comes with it and can be edited too. + let mut s = session_from(DXF); + let h = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).map(|e| e.handle.hex()).unwrap(); + s.execute("properties.set", &json!({"handles": [h], "xdata": {"acme_tags": [[1000, "P-02"]]}})).unwrap(); + assert_eq!(entities(&mut s, json!({"xdata": "ACME_TAGS", "type": "LwPolyline"}))[0]["xdata"], json!({"acme_tags": [[1000, "P-02"]]})); +} + +#[test] +fn bad_xdata_is_refused_and_changes_nothing() { + let mut s = session_from(DXF); + let h = handle_of(&s, true); + let before = entities(&mut s, json!({"xdata": true})); + let huge: Vec = std::iter::repeat_n(json!([1000, "x"]), cadcraft_engine::doc::MAX_XDATA_GROUPS + 1).collect(); + for bad in [ + json!([]), + json!("ACME"), + json!({"": [[1000, "x"]]}), + json!({"CADCRAFT": [[1000, "x"]]}), + json!({"bad*name": [[1000, "x"]]}), + json!({"ACME": "x"}), + json!({"ACME": [1000, "x"]}), + json!({"ACME": [[1000]]}), + json!({"ACME": [[1000, 5]]}), + json!({"ACME": [[1001, "B"]]}), + json!({"ACME": [[8, "0"]]}), + json!({"ACME": [[999, "x"]]}), + json!({"ACME": [[1072, 1]]}), + json!({"ACME": [["1000", "x"]]}), + json!({"ACME": [[1e300, "x"]]}), + json!({"ACME": [[1002, "("]]}), + json!({"ACME": [[1002, "}"]]}), + json!({"ACME": [[1002, "{"], [1000, "x"]]}), + json!({"ACME": [[1010, 1]]}), + json!({"ACME": [[1010, [1]]]}), + json!({"ACME": [[1010, [1, 2, 3, 4]]]}), + json!({"ACME": [[1010, [1, "y"]]]}), + json!({"ACME": [[1020, 1]]}), + json!({"ACME": [[1040, "1"]]}), + json!({"ACME": [[1040, null]]}), + json!({"ACME": [[1070, 1.5]]}), + json!({"ACME": [[1070, 40000]]}), + json!({"ACME": [[1071, 3000000000i64]]}), + json!({"ACME": [[1004, "ABC"]]}), + json!({"ACME": [[1004, "zz"]]}), + json!({"ACME": [[1005, ""]]}), + json!({"ACME": [[1005, "nothex"]]}), + json!({"ACME": [[1000, "x".repeat(256)]]}), + json!({"ACME": [[1000, "a\nb"]]}), + json!({"ACME": huge}), + ] { + let err = s.execute("properties.set", &json!({"handles": [h], "xdata": bad})).expect_err(&format!("{bad} must be refused")); + assert!(!err.to_string().is_empty()); + assert_eq!(entities(&mut s, json!({"xdata": true})), before, "{bad} changed something"); + } + // Together, two applications may not exceed what one object holds. + let full: Vec = std::iter::repeat_n(json!([1070, 1]), cadcraft_engine::doc::MAX_XDATA_GROUPS - 1).collect(); + s.execute("properties.set", &json!({"handles": [h], "xdata": {"PE_URL": null, "ACME_TAGS": null, "FULL": full}})).unwrap(); + let err = s.execute("properties.set", &json!({"handles": [h], "xdata": {"MORE": [[1070, 1]]}})).unwrap_err(); + assert!(err.to_string().contains("exceed"), "{err}"); + assert!(entities(&mut s, json!({"xdata": true}))[0]["xdata"].get("MORE").is_none()); +} + +#[test] +fn a_missing_handle_changes_nothing() { + // One handle that names no object fails the whole call before any object or the layer + // table changes: the other object keeps its data and the new layer is not created. + let mut s = session_from(DXF); + let h = handle_of(&s, true); + let before = entities(&mut s, json!({"xdata": true})); + let r = s.execute("properties.set", &json!({"handles": [h, "FFFF"], "layer": "NEWLAYER", "xdata": {"ACME": [[1000, "x"]]}})); + assert!(r.is_err(), "a missing handle is refused"); + assert_eq!(entities(&mut s, json!({"xdata": true})), before); + assert!(s.doc().unwrap().layer("NEWLAYER").is_none(), "no layer is left behind"); +} + +#[test] +fn runs_of_one_application_in_any_case_are_one_entry() { + // `ACME` and `acme` runs on one entity are one application (as `set_xdata_app` treats + // them): one JSON key with every group, and `properties.set` with that entry keeps them all. + let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\ + 1001\nACME\n1070\n1\n1001\nacme\n1070\n2\n1001\nOTHER\n1000\nx\n0\nENDSEC\n0\nEOF\n"; + let mut s = session_from(dxf); + let h = handle_of(&s, true); + let shown = entities(&mut s, json!({"xdata": true})); + assert_eq!(shown[0]["xdata"], json!({"ACME": [[1070, 1], [1070, 2]], "OTHER": [[1000, "x"]]})); + assert_eq!(entities(&mut s, json!({"xdata": "acme"}))[0]["xdata"], json!({"ACME": [[1070, 1], [1070, 2]]})); + s.execute("properties.set", &json!({"handles": [h], "xdata": shown[0]["xdata"]})).unwrap(); + assert_eq!(entities(&mut s, json!({"xdata": true}))[0]["xdata"], shown[0]["xdata"]); +} + +#[test] +fn acad_xdata_of_a_dimension_is_refused_and_kept_elsewhere() { + // A dimension's `ACAD` run is its DSTYLE overrides, written from the model and read back + // into them: raw `ACAD` groups on a dimension would be lost on save, so they are refused + // (nothing changes). On any other object `ACAD` is foreign data and survives a save. + let mut s = Session::new(); + s.script("dimlinear 0,0 10,0 5,-3\n").unwrap(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let dim = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).map(|e| e.handle.hex()).unwrap(); + let line = handle_of(&s, true); + s.execute("properties.set", &json!({"handles": [&dim], "textHeight": 5})).unwrap(); + let before = entities(&mut s, json!({"xdata": true})); + let r = s.execute("properties.set", &json!({"handles": [&dim], "xdata": {"ACAD": [[1000, "MINE"], [1070, 42]]}})); + assert!(r.is_err(), "ACAD on a dimension is refused"); + assert_eq!(entities(&mut s, json!({"xdata": true})), before); + s.execute("properties.set", &json!({"handles": [&line], "xdata": {"ACAD": [[1000, "MINE"], [1070, 42]]}})).unwrap(); + let bytes = cadcraft_io::write(s.doc().unwrap(), "acad.dxf").unwrap(); + let mut back = Session::empty(); + back.open_drawing(cadcraft_io::read_dxf(&bytes).unwrap(), "acad", None); + let kept = entities(&mut back, json!({"xdata": "ACAD"})); + assert_eq!(kept.len(), 1, "only the line carries raw ACAD data"); + assert_eq!(kept[0]["type"], "Line"); + assert_eq!(kept[0]["xdata"], json!({"ACAD": [[1000, "MINE"], [1070, 42]]})); + // The dimension's own override is still there after the round trip. + let dm = back.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap(); + assert!(matches!(&dm.kind, EntityKind::Dimension(d) if !d.overrides.is_empty()), "the DSTYLE overrides survive"); +} diff --git a/crates/engine/tests/plotters.rs b/crates/engine/tests/plotters.rs index 81aea1221..3c642b136 100644 --- a/crates/engine/tests/plotters.rs +++ b/crates/engine/tests/plotters.rs @@ -117,6 +117,108 @@ fn page_setup_takes_a_device_and_its_papers() { assert!(report["devices"].as_array().unwrap().iter().any(|d| d == "Plan Printer")); } +#[test] +/// A paper stored portrait keeps its printable area when the page names it landscape: the margins +/// turn back to the axes the user gave, and PLOT hands them on that way (#1266). +fn a_landscape_page_gets_the_papers_margins_back() { + let mut s = session(); + s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap(); + let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]}); + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap(); + // Stored portrait, 200 x 400, the side margins on the long axis. + let stored = |s: &mut Session| { + let r = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap(); + r["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").cloned().unwrap() + }; + let p = stored(&mut s); + assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(400.0))); + assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0])); + + s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0])); + // The 400 x 200 sheet's printable area is 100 x 200 mm, not the whole sheet. + let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap(); + let mm = |v: f64| v * sheet.unit_mm; + assert_eq!((mm(sheet.size.x), mm(sheet.size.y)), (400.0, 200.0)); + assert_eq!((mm(sheet.printable.min.x), mm(sheet.printable.min.y)), (150.0, 0.0)); + assert_eq!((mm(sheet.printable.max.x), mm(sheet.printable.max.y)), (250.0, 200.0)); + + // PLOT hands the margins on in the sheet's orientation. + let o = plotted(s.execute("plot", &json!({"layout": "Layout1", "paper": "Banner"})).unwrap()); + assert_eq!((o["width"].as_f64(), o["height"].as_f64()), (Some(200.0), Some(400.0))); + assert_eq!(o["margins"], json!([150.0, 0.0, 150.0, 0.0])); + + // Naming the paper landscape again at a new size keeps the margins' axes as well. + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 500, "height": 200}})) + .unwrap(); + let p = stored(&mut s); + assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(500.0))); + assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]), "the margins keep the short sides"); +} + +#[test] +/// A page set up on a landscape device paper keeps its printable area when a later PAGESETUP only +/// changes the orientation: no paper is copied, so the retained margins turn to the new sheet +/// instead of being saved against the wrong axes (#1266). +fn an_orientation_only_pagesetup_turns_the_retained_margins() { + let mut s = session(); + s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap(); + let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]}); + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap(); + // The landscape page carries the margins on its 400 mm sides: 150 mm left and right. + s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0])); + + // A second command changes only the orientation. The paper is not copied and no margins are + // given, so the retained margins turn to the 200 x 400 portrait sheet: 150 mm top and bottom, + // leaving the same 100 x 200 mm printable area rather than falling back to the whole sheet. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.paper.as_str(), page.margins_mm), ("Banner", [0.0, 150.0, 0.0, 150.0])); + let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap(); + let mm = |v: f64| v * sheet.unit_mm; + assert_eq!((mm(sheet.size.x), mm(sheet.size.y)), (200.0, 400.0)); + assert_eq!((mm(sheet.printable.min.x), mm(sheet.printable.min.y)), (0.0, 150.0)); + assert_eq!((mm(sheet.printable.max.x), mm(sheet.printable.max.y)), (200.0, 250.0)); +} + +#[test] +/// Asymmetric retained margins turn with an orientation-only PAGESETUP in the direction the page +/// turns — a portrait page turning landscape re-measures them on the landscape axes, and turning +/// back restores the stored margins — so the printable area does not depend on how the +/// orientation was reached (#1266). +fn an_orientation_turn_turns_asymmetric_margins_the_way_the_page_turns() { + let mut s = session(); + // A page setup's default orientation is landscape, so the page is named portrait first. + s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A4", "landscape": false, "margins": [10, 20, 30, 80]})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (210.0, 297.0, [10.0, 20.0, 30.0, 80.0])); + + // Portrait to landscape: the margins turn the way `set_paper` turns a device paper's, so the + // 10 mm left margin becomes the landscape sheet's 80 mm top margin and the printable area is + // the same rectangle on the turned sheet. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [80.0, 10.0, 20.0, 30.0], "the margins turn to the landscape axes"); + + // Landscape back to portrait restores the margins the page was set up with. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [10.0, 20.0, 30.0, 80.0], "the round trip keeps the margins"); + + // A landscape page turns the other way when it goes portrait: the margins are re-measured on + // the portrait sheet's axes, and turning back gives them the landscape reading again. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true, "margins": [1, 2, 3, 4]})).unwrap(); + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [2.0, 3.0, 4.0, 1.0], "the landscape margins turn back to the portrait axes"); + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [1.0, 2.0, 3.0, 4.0], "the second turn restores the landscape margins"); +} + #[test] /// PLOT and EXPORTPDF hand the hook the device's output, resolution, paper and margins, and a /// layout plots with its own page setup; unknown devices and papers are refused. @@ -239,3 +341,27 @@ fn plotwindow_picks_both_corners_with_ortho_on() { let c = hover(&mut s, Vec2::new(10.0, 4.0)); assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps the line horizontal: {c:?}"); } + +#[test] +fn paper_margins_are_checked_against_their_own_axis() { + let mut s = session(); + s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "png"})).unwrap(); + let paper = |margins: Value| json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200, "margins": margins}}); + // 250 mm of bottom + top margin leaves no printable height on a 200 mm paper. + assert!(s.execute("plottermanager", &paper(json!([0, 250, 0, 0]))).is_err()); + // 300 mm of left + right margin still leaves 100 mm of printable width on a 400 mm paper. + assert!(s.execute("plottermanager", &paper(json!([150, 0, 150, 0]))).is_ok()); + // The paper is stored portrait and the margins turn with it: the 100 x 200 printable area + // of the requested sheet stays 200 x 100 on the stored 200 x 400 one. + let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap(); + let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone(); + assert_eq!((banner["width"].as_f64().unwrap(), banner["height"].as_f64().unwrap()), (200.0, 400.0)); + assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0])); + // Setting the same sheet again without margins keeps them: the stored margins belong to the + // portrait sheet and turn back before the per-axis check. + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200}})) + .unwrap(); + let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap(); + let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone(); + assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0])); +} diff --git a/crates/engine/tests/rename_keeps_extras.rs b/crates/engine/tests/rename_keeps_extras.rs new file mode 100644 index 000000000..ecf28ae4e --- /dev/null +++ b/crates/engine/tests/rename_keeps_extras.rs @@ -0,0 +1,90 @@ +//! RENAME keeps what a renamed layer, block or style carries beyond what CADCraft models, as +//! AutoCAD does: other applications' xdata, its extension dictionary and reactors. A renamed +//! dynamic block stays dynamic, and saving writes the kept data on the new name. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::Drawing; +use cadcraft_engine::doc::dynblock::dynamic_block; +use serde_json::json; + +/// DXF text from lines of `code value` (the value may be empty). +fn dxf(src: &str) -> String { + let mut out = String::new(); + for line in src.lines().map(str::trim).filter(|l| !l.is_empty()) { + let (code, value) = line.split_once(' ').unwrap_or((line, "")); + out.push_str(&format!("{code}\n{value}\n")); + } + out +} + +/// The dynamic DOOR block drawing (its BLOCK_RECORD has an extension dictionary holding the +/// block's evaluation graph), plus a layer WALLS carrying another application's xdata. +fn session() -> Session { + let layer = "0 TABLE\n2 LAYER\n5 2\n330 0\n100 AcDbSymbolTable\n70 1\n\ + 0 LAYER\n5 10\n330 2\n100 AcDbSymbolTableRecord\n100 AcDbLayerTableRecord\n2 Walls\n70 0\n62 3\n6 Continuous\n\ + 1001 ACME_TAGS\n1000 W-01\n1070 7\n0 ENDTAB\n"; + let src = include_str!("../../io/tests/data/dynblock_door.txt").replace("\r\n", "\n").replacen( + "0 TABLE\n2 BLOCK_RECORD\n", + &format!("{layer}0 TABLE\n2 BLOCK_RECORD\n"), + 1, + ); + let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "rename", None); + s +} + +fn layer_xdata(d: &Drawing, name: &str) -> Vec<(i32, String)> { + let key = ("LAYER".to_string(), name.to_string()); + d.foreign.records.get(&key).map(|x| x.xdata.iter().map(|t| (t.code, t.value.trim().to_string())).collect()).unwrap_or_default() +} + +fn saved_and_read(s: &Session) -> Drawing { + cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap() +} + +fn acme() -> Vec<(i32, String)> { + vec![(1001, "ACME_TAGS".into()), (1000, "W-01".into()), (1070, "7".into())] +} + +#[test] +fn a_renamed_layer_keeps_its_xdata_through_a_save() { + let mut s = session(); + assert_eq!(layer_xdata(s.doc().unwrap(), "WALLS"), acme()); + s.execute("rename", &json!({ "table": "layer", "from": "Walls", "to": "Partitions" })).unwrap(); + assert_eq!(layer_xdata(s.doc().unwrap(), "PARTITIONS"), acme()); + let d = saved_and_read(&s); + assert!(d.layer("Partitions").is_some()); + assert_eq!(layer_xdata(&d, "PARTITIONS"), acme()); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(layer_xdata(s.doc().unwrap(), "WALLS"), acme(), "undo puts it back under the old name"); +} + +#[test] +fn a_renamed_dynamic_block_stays_dynamic_through_a_save() { + let mut s = session(); + let before = dynamic_block(s.doc().unwrap(), "Door").expect("Door is a dynamic block"); + s.execute("rename", &json!({ "table": "block", "from": "Door", "to": "Gate" })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.block("Gate").is_some() && d.block("Door").is_none()); + assert_eq!(dynamic_block(d, "Gate").map(|m| m.parameters.len()), Some(before.parameters.len())); + let d = saved_and_read(&s); + let after = dynamic_block(&d, "Gate").expect("Gate is still a dynamic block after a save"); + assert_eq!(after.parameters.len(), before.parameters.len()); + assert_eq!(after.actions.len(), before.actions.len()); +} + +#[test] +fn a_rename_that_only_changes_case_keeps_everything() { + let mut s = session(); + s.execute("rename", &json!({ "table": "layer", "from": "Walls", "to": "WALLS" })).unwrap(); + s.execute("rename", &json!({ "table": "block", "from": "Door", "to": "DOOR" })).unwrap(); + let d = saved_and_read(&s); + let layers: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).filter(|n| n.eq_ignore_ascii_case("walls")).collect(); + assert_eq!(layers, ["WALLS"], "the layer is saved under the new spelling"); + let blocks: Vec<(&str, &str)> = + d.blocks.iter().filter(|(k, _)| k.eq_ignore_ascii_case("door")).map(|(k, b)| (k.as_str(), b.name.as_str())).collect(); + assert_eq!(blocks, [("DOOR", "DOOR")], "the block is saved under the new spelling"); + assert_eq!(layer_xdata(&d, "WALLS"), acme()); + assert!(dynamic_block(&d, "Door").is_some()); +} diff --git a/crates/engine/tests/save_backup.rs b/crates/engine/tests/save_backup.rs index 36fad29d9..a8623359e 100644 --- a/crates/engine/tests/save_backup.rs +++ b/crates/engine/tests/save_backup.rs @@ -305,3 +305,36 @@ fn drawings_sharing_a_name_keep_their_own_backups() { assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak"); assert_eq!(name("x/plan.dwt"), "x/plan.dwt.bak"); } + +/// REFCLOSE Save writes an xref back the way SAVE writes a drawing: with ISAVEBAK off it keeps +/// no `.bak` (and reports none), with it on it keeps the previous file. +#[test] +fn an_xref_written_back_by_refclose_keeps_a_backup_as_save_does() { + let _g = saving(); + hooks(); + let dir = temp_dir("refclose"); + let site = dir.join("site.dxf"); + let mut x = Session::new(); + add_circle(&mut x, 0.0); + x.execute("saveas", &json!({ "path": site.to_string_lossy() })).unwrap(); + let host = dir.join("host.dxf"); + let mut s = Session::new(); + s.execute("saveas", &json!({ "path": host.to_string_lossy() })).unwrap(); + let insert = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap()["handle"].as_str().unwrap().to_string(); + let bak = backup_path(&site); + + cadcraft_engine::autosave::set_isavebak(false); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + add_circle(&mut s, 110.0); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(circles(&site), 2, "the edit is written"); + assert!(out["backup"].is_null() && !bak.exists(), "ISAVEBAK off keeps no backup: {out}"); + + cadcraft_engine::autosave::set_isavebak(true); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + add_circle(&mut s, 120.0); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!((circles(&site), circles(&bak)), (3, 2), "{out}"); + assert_eq!(files(&dir), ["host.dxf", "site.dxf", "site.dxf.bak"], "no staging files are left"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/save_version.rs b/crates/engine/tests/save_version.rs index 54bf0a6fe..48106bd21 100644 --- a/crates/engine/tests/save_version.rs +++ b/crates/engine/tests/save_version.rs @@ -96,3 +96,32 @@ fn opening_binary_dxf_keeps_it_binary() { assert!(!s.state().unwrap().binary_dxf); let _ = std::fs::remove_dir_all(&dir); } + +/// #3213: EXPORT to DXF or DWG takes the same version and binary options; the drawing keeps its +/// own version and name, and other formats refuse a version. +#[test] +fn export_takes_the_version_and_binary_options() { + install(); + let mut s = Session::new(); + s.cmdline("circle 0,0 5").unwrap(); + let data = |r: &serde_json::Value| String::from_utf8(base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap(); + + let r = s.execute("export", &json!({ "format": "dxf", "version": "2000" })).unwrap(); + assert_eq!(data(&r), "2000|false"); + assert_eq!(r["version"], json!("2000")); + assert_eq!(acadver(&s).as_deref(), Some("AC1032"), "an export leaves the drawing's version alone"); + let r = s.execute("export", &json!({ "format": "dwg", "version": 2004 })).unwrap(); + assert_eq!(data(&r), "2004|false"); + let r = s.execute("export", &json!({ "format": "dxf", "binary": true })).unwrap(); + assert_eq!(data(&r), "-|true"); + // Without options: the plain writer, at the drawing's own version. + let r = s.execute("export", &json!({ "format": "dxf" })).unwrap(); + assert_eq!(data(&r), "plain"); + assert!(r.get("version").is_none()); + + let err = |s: &mut Session, p: serde_json::Value| s.execute("export", &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({ "format": "svg", "version": "2000" })).contains("DXF and DWG")); + assert!(err(&mut s, json!({ "format": "dwg", "binary": true })).contains("DXF")); + assert!(err(&mut s, json!({ "format": "dxf", "version": "2005" })).contains("unknown version")); + assert!(s.state().unwrap().path.is_none(), "the drawing keeps its name"); +} diff --git a/crates/engine/tests/usage.rs b/crates/engine/tests/usage.rs index e70d9d638..178b39cf5 100644 --- a/crates/engine/tests/usage.rs +++ b/crates/engine/tests/usage.rs @@ -30,6 +30,8 @@ fn text(handle: u64, layer: &str, style: &str) -> Entity { style: style.into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), ); e.common = Common { layer: layer.into(), ..Common::default() }; diff --git a/crates/fonts/src/complex.rs b/crates/fonts/src/complex.rs index f6a19b567..1982702be 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -83,7 +83,21 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 let scale_x = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; let shear = oblique.tan().clamp(-10.0, 10.0); let stroke_scale = normalized_height / stroke::CAP; - let characters: Vec = chars.iter().map(|character| character.0).collect(); + // A character the text's face lacks is one of its substitutes when it has one, as in the + // left-to-right path. The bidi runs come from the text as decoded, before substitution: a + // substitute may be of another bidi class (⌀ and ∅ are neutral, Ø is left-to-right), and + // the line keeps the direction its own text gives it; the substitute is drawn at the same + // logical index. + let decoded: Vec = chars.iter().map(|character| character.0).collect(); + let characters: Vec = decoded + .iter() + .map(|&character| match primary { + Some(face) if !character.is_whitespace() && !face.has_glyph(character) => { + crate::substitutes(character).iter().copied().find(|&substitute| face.has_glyph(substitute)).unwrap_or(character) + } + _ => character, + }) + .collect(); let flags = |index: usize| chars.get(index).map_or((false, false), |character| (character.1, character.2)); let mut shaped = Shaped::default(); let mut points_left = ttf::MAX_SHAPED_POINTS; @@ -91,7 +105,7 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 let mut pen_x = 0.0; // Whether the rightmost glyph so far is a stroke-font glyph. let mut stroke_last = false; - for (run, rtl) in bidi::visual_runs(&characters, base_rtl) { + for (run, rtl) in bidi::visual_runs(&decoded, base_rtl) { let mut pieces = itemize(&characters, run, primary); if rtl { pieces.reverse(); @@ -150,9 +164,9 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 } } shaped.strokes.extend(crate::decorations(&spans, normalized_height)); - // A stroke-font glyph at the right end: the width leaves out its trailing gap, like - // `shape_stroke`. - shaped.width = if stroke_last { (pen_x - stroke::GAP * stroke_scale * scale_x).max(0.0) } else { pen_x }; + // A stroke-font glyph at the right end of a stroke-font line: the width leaves out its + // trailing gap, like `shape_stroke`. A TrueType line keeps it, like `ttf::shape`. + shaped.width = if stroke_last && primary.is_none() { (pen_x - stroke::GAP * stroke_scale * scale_x).max(0.0) } else { pen_x }; shaped } @@ -178,7 +192,9 @@ fn itemize(cs: &[char], run: Range, primary: Option<&Face>) -> Vec<(Src, } /// What draws `c`: the text's face when it has the character, else the previous fallback face, -/// else the first fallback font that has it (FONTFALLBACK, FONTALT, installed fonts). +/// else the first fallback font that has it (FONTFALLBACK, FONTALT, installed fonts), else the +/// stroke font when it has it; what no font has is the text's face's missing-glyph shape (a box +/// in the stroke font). fn resolve(c: char, primary: Option<&Face>, prev: Option<&Face>) -> Src { if let Some(p) = primary && (c.is_whitespace() || p.has_glyph(c)) @@ -193,6 +209,8 @@ fn resolve(c: char, primary: Option<&Face>, prev: Option<&Face>) -> Src { } match (ttf::fallback_for(c), primary) { (Some(f), _) => Src::Face(f), + // No font has it: the stroke font's glyph, as in the left-to-right path. + (None, _) if stroke::glyph(c).is_some() => Src::Stroke, // The text's font draws its own missing-glyph shape. (None, Some(p)) => Src::Face(p.clone()), (None, None) => Src::Missing, @@ -438,6 +456,30 @@ mod tests { assert!(!sh.strokes.iter().any(|s| s.len() == 5 && s.first() == s.last()), "no boxes for marks"); } + #[test] + fn a_face_lacking_what_no_font_has_gets_the_stroke_glyph() { + // A face that maps no character stands in for the text's font lacking one. What no + // installed font has either is the stroke font's glyph when it has one, as in the + // left-to-right path; what the stroke font lacks too, and whitespace, stay the face's. + let junk = Face { bytes: std::sync::Arc::new(b"not a font".to_vec()), index: 0 }; + let c = '\u{2300}'; + match ttf::fallback_for(c) { + None => assert!(matches!(resolve(c, Some(&junk), None), Src::Stroke), "the stroke font's glyph"), + Some(f) => assert!(matches!(resolve(c, Some(&junk), None), Src::Face(g) if g.same(&f)), "the fallback font's"), + } + assert!(matches!(resolve('\u{E000}', Some(&junk), None), Src::Face(_)), "the face's missing-glyph shape"); + assert!(matches!(resolve(' ', Some(&junk), None), Src::Face(_))); + assert!(matches!(resolve(c, None, None), Src::Stroke)); + if ttf::fallback_for(c).is_none() { + // Drawn as strokes, not a box, with the stroke font's advance; the trailing gap + // stays in the width, as `ttf::shape` keeps it. + let sh = shape(Some(&junk), "\u{05D0}\u{2300}", 1.0, 1.0, 0.0, None).unwrap_or_default(); + assert!(sh.strokes.iter().any(|s| s.len() == 2), "the slash of the diameter sign"); + assert!(!sh.strokes.iter().any(|s| s.len() == 5 && s.first() == s.last()), "no missing-glyph box"); + assert!(sh.width >= crate::char_advance(c) - 1e-9, "{}", sh.width); + } + } + /// An installed font that shapes Arabic (Persian), or `None` (the test then skips). fn arabic_face() -> Option { ttf::fallback_for('\u{0633}').filter(|f| f.has_glyph('\u{06CC}') && f.has_glyph('\u{067E}')) @@ -660,4 +702,78 @@ mod tests { assert!(shape(None, &long, 1.0, 1.0, 0.0, None).is_none()); assert!(crate::shape_stroke(&long, 1.0, 1.0, 0.0).width > 0.0); } + + /// A TrueType font that maps `chars` to glyphs 1, 2, ... in code point order (each with the + /// same advance) and nothing else: a character map and metrics, no outlines. Enough for + /// `has_glyph` and the shaper, with a coverage the test chooses, whatever fonts are installed. + fn font_mapping(chars: &[char]) -> Face { + // Big-endian fields: (width in bytes, value). + fn table(fields: &[(usize, i64)]) -> Vec { + fields.iter().flat_map(|&(w, x)| x.to_be_bytes()[8 - w..].to_vec()).collect() + } + let mut chars = chars.to_vec(); + chars.sort_unstable(); + chars.dedup(); + let n = i64::try_from(chars.len() + 1).unwrap(); + // head: version 1.0, revision, checksum adjustment, magic, flags, units per em; created, + // modified and bounds (zero); mac style, lowest ppem, direction hint, loca format, glyph + // data format. + let mut head = table(&[(2, 1), (2, 0), (4, 0x1_0000), (4, 0), (4, 0x5F0F_3CF5), (2, 0), (2, 1000)]); + head.extend(table(&[(8, 0), (8, 0), (8, 0), (2, 0), (2, 8), (2, 2), (2, 0), (2, 0)])); + // hhea: version 1.0, ascender, descender, line gap, max advance, min side bearings, + // max extent, caret slope and offset, reserved, metric format, number of h metrics. + let hhea = + table(&[(2, 1), (2, 0), (2, 800), (2, -200), (2, 0), (2, 500), (2, 0), (2, 0), (2, 500), (2, 1), (2, 0), (2, 0), (8, 0), (2, 0), (2, n)]); + let maxp = table(&[(4, 0x5000), (2, n)]); + let hmtx = table(&[(2, 500), (2, 0)].repeat(chars.len() + 1)); + // cmap: one (3, 10) format 12 subtable, one group per character, in code point order. + let groups: Vec<(usize, i64)> = chars + .iter() + .enumerate() + .flat_map(|(i, c)| [(4, i64::from(u32::from(*c))), (4, i64::from(u32::from(*c))), (4, i64::try_from(i + 1).unwrap())]) + .collect(); + let count = i64::try_from(chars.len()).unwrap(); + let mut cmap = table(&[(2, 0), (2, 1), (2, 3), (2, 10), (4, 12), (2, 12), (2, 0), (4, 16 + 12 * count), (4, 0), (4, count)]); + cmap.extend(table(&groups)); + let tables = [(b"cmap", cmap), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"maxp", maxp)]; + let mut font = table(&[(4, 0x1_0000), (2, 5), (2, 64), (2, 2), (2, 16)]); + let mut offset = 12 + 16 * tables.len(); + for (tag, t) in &tables { + font.extend_from_slice(*tag); + font.extend(table(&[(4, 0), (4, i64::try_from(offset).unwrap()), (4, i64::try_from(t.len()).unwrap())])); + offset += t.len().next_multiple_of(4); + } + for (_, t) in &tables { + font.extend_from_slice(t); + font.resize(font.len().next_multiple_of(4), 0); + } + Face { bytes: std::sync::Arc::new(font), index: 0 } + } + + #[test] + fn a_substitute_does_not_change_the_direction_of_the_line() { + // ⌀ and ∅ are bidi-neutral; Ø, drawn for them in a font that lacks both, is + // left-to-right. "⌀50 אב" reads right to left (its first strong character is Hebrew), + // so "50⌀" sits at the right end of the line. A font without ⌀ lays the line out the + // same way: the runs come from the text as decoded, not from the characters + // substituted for it, which would make Ø the first strong character and flip the line. + let s = "%%u\u{2300}50%%u \u{05D0}\u{05D1}"; + assert_eq!(bidi::base_rtl(&crate::decode_controls(s).iter().map(|c| c.0).collect::()), Some(true)); + let shared: Vec = "Ø50 \u{05D0}\u{05D1}".chars().collect(); + let has = font_mapping(&[&['\u{2300}'][..], &shared].concat()); + let lacks = font_mapping(&shared); + assert!(has.has_glyph('\u{2300}') && !lacks.has_glyph('\u{2300}') && !lacks.has_glyph('\u{2205}') && lacks.has_glyph('Ø')); + let with = shape(Some(&has), s, 1.0, 1.0, 0.0, None).unwrap(); + let without = shape(Some(&lacks), s, 1.0, 1.0, 0.0, None).unwrap(); + // The underline follows "⌀50" wherever the line puts it; nothing else is a stroke. + let underline = |sh: &Shaped| { + assert_eq!(sh.strokes.len(), 1, "{:?}", sh.strokes); + (sh.strokes[0][0].x, sh.strokes[0][1].x) + }; + let (x0, x1) = underline(&with); + assert!(x0 > 0.3 * with.width && (x1 - with.width).abs() < 1e-9, "at the right end: {x0}..{x1} of {}", with.width); + let (y0, y1) = underline(&without); + assert!((y0 - x0).abs() < 1e-9 && (y1 - x1).abs() < 1e-9, "{y0}..{y1}, not {x0}..{x1}"); + assert!((without.width - with.width).abs() < 1e-9); + } } diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index f64945799..1aee50569 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -27,7 +27,7 @@ pub mod windows; use cadcraft_geom::{Bounds2, Vec2}; -pub use mtext::para::{DEFAULT_TAB, ListStyle, MTextColumnSpec, ParaAlign, ParaProps, Paragraphs, TabKind, list_contents}; +pub use mtext::para::{DEFAULT_TAB, ListStyle, MTextColumnSpec, ParaAlign, ParaLineSpacing, ParaProps, Paragraphs, TabKind, list_contents}; pub use mtext::{MTextColor, MTextLayout, MTextParams, MTextPiece, layout_mtext, layout_mtext_with, plain_mtext}; mod craft_fonts; @@ -93,6 +93,18 @@ pub fn decode_controls(text: &str) -> Vec<(char, bool, bool)> { out } +/// Characters a font may show in place of `c` when it lacks it, best first: the diameter sign +/// (`%%c`, U+2300), which many TrueType fonts lack, as the empty set (U+2205, what some files +/// store it as) or Ø (U+00D8, in every Latin font). All three read as the diameter sign in +/// drawing text, and any of them beats the font's missing-glyph box (#1608). +pub fn substitutes(c: char) -> &'static [char] { + match c { + '⌀' => &['∅', 'Ø'], + '∅' => &['⌀', 'Ø'], + _ => &[], + } +} + /// The character of a `\U+XXXX` escape (four hex digits) starting at `chars[i]`. pub(crate) fn unicode_escape(chars: &[char], i: usize) -> Option { if chars.get(i) != Some(&'\\') || !matches!(chars.get(i + 1), Some('U' | 'u')) || chars.get(i + 2) != Some(&'+') { @@ -258,7 +270,7 @@ pub fn shape_stroke_dir(text: &str, height: f64, width_factor: f64, oblique: f64 } /// Draw stroke-font glyph `spec` with its left edge at `x` (`sc` = text height / cap height). -fn draw_stroke_glyph(out: &mut Shaped, spec: &str, x: f64, sc: f64, wf: f64, shear: f64) { +pub(crate) fn draw_stroke_glyph(out: &mut Shaped, spec: &str, x: f64, sc: f64, wf: f64, shear: f64) { for st in stroke::strokes(spec) { let pts: Vec = st.iter().map(|(gx, gy)| Vec2::new(x + (gx * sc * wf) + gy * sc * shear, gy * sc)).collect(); if pts.len() == 1 { @@ -789,6 +801,32 @@ mod tests { assert_eq!(decode_controls("%%").len(), 2); } + /// #1608: the diameter sign a font lacks is shown as its empty set or Ø, in that order; no + /// other character has substitutes. + #[test] + fn diameter_sign_substitutes_in_order() { + assert_eq!(substitutes('⌀'), &['∅', 'Ø']); + assert_eq!(substitutes('∅'), &['⌀', 'Ø']); + for c in ['Ø', 'ø', 'A', '°', '\u{E000}'] { + assert!(substitutes(c).is_empty(), "{c:?}"); + } + let has = |c: char| c == 'Ø'; + assert_eq!(substitutes('⌀').iter().copied().find(|&s| has(s)), Some('Ø')); + let has = |c: char| c == '∅' || c == 'Ø'; + assert_eq!(substitutes('⌀').iter().copied().find(|&s| has(s)), Some('∅')); + } + + /// The stroke font draws U+2205 (what some files store `%%c` as) as its diameter sign, not + /// as a missing-glyph box or a fallback font's glyph. + #[test] + fn empty_set_is_the_stroke_diameter_sign() { + let a = shape_stroke("\u{2205}50", 1.0, 1.0, 0.0); + assert_eq!(a, shape_stroke("\u{2300}50", 1.0, 1.0, 0.0)); + assert_eq!(a, shape_stroke("%%c50", 1.0, 1.0, 0.0)); + assert!(a.glyphs.is_empty(), "no fallback glyphs"); + assert!((line_width("\u{2205}50", 1.0, 1.0) - a.width).abs() < 1e-9); + } + #[test] fn line_metrics_scale_with_height() { let a = layout_line("HELLO", 1.0, 1.0, 0.0); @@ -847,6 +885,47 @@ mod ttf_tests { assert!((maxy - 1.0).abs() < 0.1, "cap height ~ text height, got {maxy}"); } + /// #1608: `%%c` in a text style whose TrueType font has neither U+2300 nor U+2205 (Arial, + /// Liberation Sans, Times...) is that font's Ø, not its missing-glyph box; so is U+2205, + /// which some files store the symbol as. Skips cleanly when no such font is installed. + #[test] + fn diameter_sign_in_a_font_without_it_is_its_o_slash() { + let fonts = ["LiberationSans-Regular", "Arial", "Helvetica", "Verdana", "Times New Roman", "LiberationSerif-Regular"]; + let Some(face) = + fonts.iter().filter_map(|n| crate::ttf::find(n)).find(|f| !f.has_glyph('\u{2300}') && !f.has_glyph('\u{2205}') && f.has_glyph('Ø')) + else { + return; + }; + let o_slash = crate::ttf::shape(&face, "Ø50", 1.0, 1.0, 0.0).unwrap(); + for s in ["%%c50", "\u{2300}50", "\u{2205}50"] { + let sh = crate::ttf::shape(&face, s, 1.0, 1.0, 0.0).unwrap(); + assert_eq!(sh.glyphs, o_slash.glyphs, "{s}"); + assert_eq!(sh.text.first().map(|t| (t.gid, t.ch)), o_slash.text.first().map(|t| (t.gid, t.ch)), "{s}: the PDF glyph"); + assert!((crate::ttf::width(&face, s, 1.0, 1.0).unwrap() - o_slash.width).abs() < 1e-9, "{s}"); + } + // The same on a line with right-to-left text (the shaped path): the face's Ø, not the + // stroke font's last resort, at the same width. The line keeps the order its own text + // gives it: "⌀50 א" reads right to left (⌀ is bidi-neutral, Ø left-to-right), so the Ø + // is its rightmost glyph, where a font with ⌀ puts the sign; "Ø50 א" reads left to right. + let rtl = crate::complex::shape(Some(&face), "\u{2300}50 \u{5D0}", 1.0, 1.0, 0.0, None).unwrap(); + let o_rtl = crate::complex::shape(Some(&face), "Ø50 \u{5D0}", 1.0, 1.0, 0.0, None).unwrap(); + let x0 = |g: &[Vec]| g.iter().flatten().map(|p| p.x).fold(f64::MAX, f64::min); + let same_shape = |a: &[Vec], b: &[Vec]| { + let (ax, bx) = (x0(a), x0(b)); + a.len() == b.len() + && a.iter().zip(b).all(|(c, d)| { + c.len() == d.len() && c.iter().zip(d).all(|(p, q)| (p.x - ax - (q.x - bx)).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9) + }) + }; + // Empty glyphs (the space) keep a slot for text export but have no position to compare. + let rightmost = rtl.glyphs.iter().filter(|g| !g.is_empty()).max_by(|a, b| x0(a).total_cmp(&x0(b))).unwrap(); + assert!(same_shape(rightmost, o_slash.glyphs.first().unwrap()), "the face's Ø at the right end"); + assert!(same_shape(o_rtl.glyphs.first().unwrap(), o_slash.glyphs.first().unwrap()), "Ø at the left end of a left-to-right line"); + assert_eq!(rtl.glyphs.len(), o_rtl.glyphs.len()); + assert!((rtl.width - o_rtl.width).abs() < 1e-9); + assert!(rtl.strokes.is_empty(), "no stroke-font glyphs"); + } + #[test] fn stroke_names_are_not_ttf() { assert!(crate::ttf::find("txt.shx").is_none()); diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index 6a9b3709b..d141ef2c1 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -1,7 +1,7 @@ //! MTEXT paragraph formatting and columns: the `\p…;` paragraph codes (first-line, left and -//! right indents, tab stops, alignment, space before and after), tab characters (bulleted and -//! numbered lists are a label, a tab and a hanging indent), column breaks (`\N`) and text -//! flowing through static or dynamic columns. +//! right indents, tab stops, alignment, line spacing, space before and after), tab characters +//! (bulleted and numbered lists are a label, a tab and a hanging indent), column breaks (`\N`) +//! and text flowing through static or dynamic columns. //! //! Contents without any of these lay out exactly as in [`super::layout_mtext_with`]'s plain path. @@ -56,6 +56,17 @@ pub enum ParaAlign { Distributed, } +/// A paragraph's line spacing override (`\pxs…;`), overriding the entity's line spacing. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ParaLineSpacing { + /// `sm`: multiple spacing (grows for taller inline characters). + Multiple(f64), + /// `se`: exact spacing (uses the entity text height regardless of inline height changes). + Exact(f64), + /// `sd`: at-least spacing (grows for taller inline characters). + AtLeast(f64), +} + /// Paragraph properties set by `\p…;`. Indents and tab stops are in drawing units (as in /// `AutoCAD` files: `\pi4.86;` indents the first line by 4.86 units), space before and after in /// text heights. They stay in effect for the following paragraphs until another `\p` changes them. @@ -69,6 +80,8 @@ pub struct ParaProps { pub right: f64, /// `q`: alignment. pub align: ParaAlign, + /// `s`: paragraph line spacing (`None` uses the entity's line spacing). + pub line_spacing: Option, /// `t`: tab stops from the left edge, ascending. pub tabs: Vec<(f64, TabKind)>, /// `b`: space before the paragraph. @@ -140,6 +153,25 @@ impl ParaProps { Some(_) => self.align, } } + 's' => { + let rest = rest.trim(); + if rest.is_empty() || rest == "*" { + self.line_spacing = None; + } else if let Some((mode, val)) = rest.split_at_checked(1) { + let val = val.trim(); + let val = val.strip_suffix(['x', 'X']).unwrap_or(val).trim(); + let factor = || num(val).filter(|v| *v > 0.0 && *v <= MAX_UNITS).map(super::sane_line_spacing); + match mode { + "m" | "e" | "d" if val == "*" => self.line_spacing = None, + "m" => self.line_spacing = factor().map(ParaLineSpacing::Multiple).or(self.line_spacing), + "e" => self.line_spacing = factor().map(ParaLineSpacing::Exact).or(self.line_spacing), + "d" => self.line_spacing = factor().map(ParaLineSpacing::AtLeast).or(self.line_spacing), + "b" => self.before = units(val).unwrap_or(self.before).max(0.0), + "a" => self.after = units(val).unwrap_or(self.after).max(0.0), + _ => {} + } + } + } 't' => { self.tabs.clear(); in_tabs = true; @@ -171,15 +203,24 @@ impl ParaProps { /// The `\p…;` code for these properties: the indents, then the right indent, spacing and /// alignment where they aren't the default, then the tab stops. pub fn code(&self) -> String { + self.code_after(&Self::default()) + } + + /// The `\p…;` code for these properties following `prev`: emits explicit resets (`s*`, `b0`, + /// `a0`) when a paragraph drops an earlier override back to the default. + pub fn code_after(&self, prev: &Self) -> String { let n = |v: f64| { let s = format!("{v:.4}"); let s = s.trim_end_matches('0').trim_end_matches('.'); if s == "-0" { "0".to_string() } else { s.to_string() } }; let mut items = vec![format!("i{}", n(self.first)), format!("l{}", n(self.left))]; - for (key, v) in [('r', self.right), ('b', self.before), ('a', self.after)] { - if v > 0.0 { - items.push(format!("{key}{}", n(v))); + if self.right > 0.0 { + items.push(format!("r{}", n(self.right))); + } + for (key, v, prev_v) in [('b', self.before, prev.before), ('a', self.after, prev.after)] { + if v > 0.0 || prev_v > 0.0 { + items.push(format!("{key}{}", n(v.max(0.0)))); } } let q = match self.align { @@ -191,6 +232,14 @@ impl ParaProps { ParaAlign::Distributed => Some("qd"), }; items.extend(q.map(String::from)); + let s = match self.line_spacing { + Some(ParaLineSpacing::Multiple(v)) => Some(format!("sm{}", n(v))), + Some(ParaLineSpacing::Exact(v)) => Some(format!("se{}", n(v))), + Some(ParaLineSpacing::AtLeast(v)) => Some(format!("sd{}", n(v))), + None if prev.line_spacing.is_some() => Some("s*".to_string()), + None => None, + }; + items.extend(s); for (i, (p, k)) in self.tabs.iter().enumerate() { let kind = match k { TabKind::Left => "", @@ -315,7 +364,7 @@ impl Paragraphs { } static DEFAULT_PROPS: ParaProps = - ParaProps { first: 0.0, left: 0.0, right: 0.0, align: ParaAlign::Default, tabs: Vec::new(), before: 0.0, after: 0.0 }; + ParaProps { first: 0.0, left: 0.0, right: 0.0, align: ParaAlign::Default, line_spacing: None, tabs: Vec::new(), before: 0.0, after: 0.0 }; /// Contents or columns that need the paragraph layout. pub(super) fn needed(contents: &str, p: &MTextParams) -> bool { @@ -602,11 +651,18 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL let mut col_bottom = vec![0.0f64]; let mut prev_para: Option = None; for line in &lines { + let pp = paragraphs.props(line.para); let line_height = if line.max_h > 0.0 { line.max_h } else { height }; let new_para = prev_para != Some(line.para); - let before = if new_para && prev_para.is_some() { paragraphs.props(line.para).before * height } else { 0.0 }; - let step_h = if params.line_spacing_exact { height } else { line_height }; - let pitch = |first: bool| if first { line_height } else { step_h * 5.0 / 3.0 * line_spacing + before }; + let before = if new_para && prev_para.is_some() { pp.before * height } else { 0.0 }; + let (exact, factor, floor) = match pp.line_spacing { + Some(ParaLineSpacing::Multiple(v)) => (false, super::sane_line_spacing(v), 0.0), + Some(ParaLineSpacing::AtLeast(v)) => (false, super::sane_line_spacing(v), height), + Some(ParaLineSpacing::Exact(v)) => (true, super::sane_line_spacing(v), 0.0), + None => (params.line_spacing_exact, line_spacing, 0.0), + }; + let step_h = if exact { height } else { line_height.max(floor) }; + let pitch = |first: bool| if first { line_height } else { step_h * 5.0 / 3.0 * factor + before }; let column_height = col_height(column); if !first_in_col && column + 1 < max_cols && (force || (column_height > 0.0 && current_y + pitch(false) > column_height + 1e-9)) { column += 1; @@ -761,8 +817,73 @@ mod tests { assert_eq!(pp.tabs, vec![(2.0, TabKind::Left), (4.0, TabKind::Center), (6.0, TabKind::Right), (8.0, TabKind::Decimal)]); assert_eq!(pp.align, ParaAlign::Center); assert!((pp.before - 0.5).abs() < f64::EPSILON); + assert_eq!(pp.line_spacing, None); + pp.apply("sm1.5,sb0.25,sa0.75"); + assert_eq!(pp.line_spacing, Some(ParaLineSpacing::Multiple(1.5))); + assert!((pp.before - 0.25).abs() < f64::EPSILON); + assert!((pp.after - 0.75).abs() < f64::EPSILON); let mut back = ParaProps::default(); back.apply(pp.code().trim_start_matches("\\p").trim_end_matches(';')); assert_eq!(back, pp); + + for (code, expected) in [ + ("se1.25", Some(ParaLineSpacing::Exact(1.25))), + ("sd0.8", Some(ParaLineSpacing::AtLeast(0.8))), + ("sm2x", Some(ParaLineSpacing::Multiple(2.0))), + ("s*", None), + ] { + pp.apply(code); + assert_eq!(pp.line_spacing, expected, "{code}"); + let mut round = ParaProps::default(); + round.apply(pp.code().trim_start_matches("\\p").trim_end_matches(';')); + assert_eq!(round, pp, "{code}"); + } + } + + #[test] + fn paragraph_line_spacing_overrides_entity_factor() { + let p_08 = MTextParams { line_spacing: 0.8, line_spacing_exact: false, ..MTextParams::new(Vec2::ZERO, 0.2) }; + let p_10 = MTextParams { line_spacing: 1.0, line_spacing_exact: false, ..MTextParams::new(Vec2::ZERO, 0.2) }; + let overridden = super::super::layout_mtext_with("\\pxsm1;{AAA ONE\\PBBB TWO\\PCCC THREE}", &p_08); + let reference = super::super::layout_mtext_with("{AAA ONE\\PBBB TWO\\PCCC THREE}", &p_10); + assert!( + overridden.bounds.min.dist(reference.bounds.min) < 1e-9 && overridden.bounds.max.dist(reference.bounds.max) < 1e-9, + "bounds {:?} vs {:?}", + overridden.bounds, + reference.bounds + ); + assert_eq!(overridden.strokes.len(), reference.strokes.len()); + for (a, b) in overridden.strokes.iter().flatten().zip(reference.strokes.iter().flatten()) { + assert!(a.dist(*b) < 1e-9, "{a:?} vs {b:?}"); + } + + // Exact mode keeps fixed pitch even over a taller inline character; Multiple and AtLeast expand. + let p_exact = MTextParams { line_spacing: 1.0, line_spacing_exact: true, ..MTextParams::new(Vec2::ZERO, 0.2) }; + let exact_para = super::super::layout_mtext_with("\\pxse1;A\\P{\\H2x;B}\\PC", &p_08); + let exact_ref = super::super::layout_mtext_with("A\\P{\\H2x;B}\\PC", &p_exact); + assert!(exact_para.bounds.min.dist(exact_ref.bounds.min) < 1e-9); + let at_least_para = super::super::layout_mtext_with("\\pxsd1;A\\P{\\H2x;B}\\PC", &p_08); + assert!(at_least_para.bounds.height() > exact_para.bounds.height() + 0.1); + + // AtLeast floors step height at entity height when inline runs are shorter; Multiple scales down. + let at_least_short = super::super::layout_mtext_with("\\pxsd1;A\\P{\\H0.5x;B}\\PC", &p_08); + let multiple_short = super::super::layout_mtext_with("\\pxsm1;A\\P{\\H0.5x;B}\\PC", &p_08); + let at_least_plain = super::super::layout_mtext_with("\\pxsd1;A\\PB\\PC", &p_08); + assert!((at_least_short.bounds.height() - at_least_plain.bounds.height()).abs() < 1e-9); + assert!(multiple_short.bounds.height() < at_least_short.bounds.height() - 0.05); + + // `\pxs*;` reverts to the entity's line spacing factor for subsequent paragraphs. + let reset = super::super::layout_mtext_with("\\pxsm1;A\\PB\\P\\pxs*;C", &p_08); + let all_one = super::super::layout_mtext_with("\\pxsm1;A\\PB\\PC", &p_08); + assert!(reset.bounds.height() < all_one.bounds.height() - 0.05); + + // `code_after` emits explicit resets (`s*`, `b0`, `a0`) when dropping overrides from `prev`. + let mut prev = ParaProps::default(); + prev.apply("sm1.5,sb0.25,sa0.75"); + let default = ParaProps::default(); + let reset_code = default.code_after(&prev); + let mut applied = prev.clone(); + applied.apply(reset_code.trim_start_matches("\\p").trim_end_matches(';')); + assert_eq!(applied, default, "reset code: {reset_code}"); } } diff --git a/crates/fonts/src/stroke.rs b/crates/fonts/src/stroke.rs index 80512f3f8..b81545aee 100644 --- a/crates/fonts/src/stroke.rs +++ b/crates/fonts/src/stroke.rs @@ -108,7 +108,7 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { '~' => (4.0, "0g1h3f4g"), '°' => (2.0, "1i0h1g2h1i"), '±' => (4.0, "2e2i 0g4g 0d4d"), - 'Ø' | 'ø' | '⌀' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"), + 'Ø' | 'ø' | '⌀' | '∅' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"), '•' => (2.0, "1d0e1f2e1d 0e2e 1d1f"), // Original Latin diacritics, composed from our own letter bodies and marks. '\u{00C0}' => (4.0, concat!("0c2i4c 1f3f", " 1k3j")), diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index a3b8b3017..67cf592e1 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -89,12 +89,17 @@ impl Face { self.font().is_some_and(|f| f.charmap().map(c).is_some()) } /// The family name, as the font gives it (the typographic family, else the family when that - /// is missing or blank). + /// is missing or blank). A record that reads as blank (empty, or in an encoding that is not + /// decoded, such as a Mac name in Shift-JIS) is passed over for the next one with the same id. pub fn family_name(&self) -> Option { let f = self.font()?; [skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME].into_iter().find_map(|id| { - let s = f.localized_strings(id).next()?.to_string(); - Some(s.chars().filter(|c| !c.is_control()).take(80).collect::()).filter(|s| !s.trim().is_empty()) + // At most MAX_NAME_RECORDS records per id, each read up to MAX_NAME_CHARS characters, + // as in `names`. + f.localized_strings(id).take(MAX_NAME_RECORDS).find_map(|s| { + let s = s.chars().take(MAX_NAME_CHARS).filter(|c| !c.is_control()).take(80).collect::(); + (!s.trim().is_empty()).then_some(s) + }) }) } /// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the @@ -1361,13 +1366,32 @@ pub(crate) fn fallback_glyph(c: char) -> Option> { Some(glyph(&f, c)).filter(|g| g.mapped) } -/// The glyph of `c` in `face`, or from a fallback font when `face` lacks it. -fn glyph_or_fallback(face: &Face, c: char) -> Arc { +/// The glyph of `c` in `face`, or from a fallback font when `face` lacks it, and the character +/// it shows: a character the face lacks is one of its [`crate::substitutes`] in the face when it +/// has one, before a fallback font is tried. +fn glyph_or_fallback(face: &Face, c: char) -> (Arc, char) { let g = glyph(face, c); if g.mapped || c.is_whitespace() { - return g; + return (g, c); } - fallback_glyph(c).unwrap_or(g) + if let Some(s) = crate::substitutes(c).iter().copied().find(|&s| face.has_glyph(s)) { + return (glyph(face, s), s); + } + (fallback_glyph(c).unwrap_or(g), c) +} + +/// The stroke font's glyph of `c`, when no font has it (`g` is a missing-glyph shape): drawn in +/// place of the face's box. +fn stroke_glyph(g: &GlyphOutline, c: char) -> Option<&'static str> { + if g.mapped || c.is_whitespace() { + return None; + } + crate::stroke::glyph(c).map(|(_, spec)| spec) +} + +/// Advance of `c` drawn as `g`, or by the stroke font when no font has it. +fn advance(g: &GlyphOutline, c: char, h: f64, wf: f64) -> f64 { + if stroke_glyph(g, c).is_some() { crate::char_advance(c) * h * wf } else { g.advance * h / g.cap * wf } } /// The [`crate::TextGlyph`] of a glyph placed like [`place_glyph`] does (its outline index is @@ -1423,7 +1447,9 @@ pub(crate) fn place_glyph_at(g: &GlyphOutline, origin: Vec2, scale: f64, wf: f64 /// Shape one line with a TrueType face: closed glyph contours grouped per glyph (baseline at /// y = 0, x from 0) plus `%%u`/`%%o` decorations as strokes. Text height = cap height. -/// Characters the face lacks come from a fallback font, scaled to its own cap height. +/// Characters the face lacks come from a fallback font, scaled to its own cap height; those no +/// font has are drawn by the stroke font when it has them (as strokes), else as the face's +/// missing-glyph shape. pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) -> Option { shape_dir(face, s, height, width_factor, oblique, None) } @@ -1451,14 +1477,16 @@ pub fn shape_dir(face: &Face, s: &str, height: f64, width_factor: f64, oblique: if crate::bidi::is_format_control(c) { continue; } - let g = glyph_or_fallback(face, c); - if !c.is_whitespace() + let (g, shown) = glyph_or_fallback(face, c); + if let Some(spec) = stroke_glyph(&g, c) { + crate::draw_stroke_glyph(&mut out, spec, x, h / crate::stroke::CAP, wf, shear); + } else if !c.is_whitespace() && let Some(contours) = place_glyph_budgeted(&g, x, h, wf, shear, &mut points_left) { // Even an empty mapped glyph needs a valid outline slot for text export. - out.push_glyph(contours, text_glyph(&g, c, x, h, wf, shear)); + out.push_glyph(contours, text_glyph(&g, shown, x, h, wf, shear)); } - let adv = g.advance * h / g.cap * wf; + let adv = advance(&g, c, h, wf); spans.push((x, x + adv, under, over)); x += adv; } @@ -1480,10 +1508,7 @@ pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option); + + /// A font file holding only a `name` table with `records`, which is all reading names parses. + fn font_with_names(records: &[Record]) -> Vec { + let count = u16::try_from(records.len()).unwrap(); + let mut name: Vec = [0, count, 6 + 12 * count].into_iter().flat_map(u16::to_be_bytes).collect(); + let mut strings = Vec::new(); + for (platform, encoding, language, id, text) in records { + let (len, offset) = (u16::try_from(text.len()).unwrap(), u16::try_from(strings.len()).unwrap()); + name.extend([*platform, *encoding, *language, *id, len, offset].into_iter().flat_map(u16::to_be_bytes)); + strings.extend_from_slice(text); + } + name.extend(strings); + // TrueType table directory with one table record; the table follows at byte 28. + let mut font = 0x0001_0000u32.to_be_bytes().to_vec(); + font.extend([1u16, 16, 0, 0].into_iter().flat_map(u16::to_be_bytes)); + font.extend(b"name"); + font.extend([0, 28, u32::try_from(name.len()).unwrap()].into_iter().flat_map(u32::to_be_bytes)); + font.extend(name); + font + } + + fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_be_bytes).collect() + } + /// Reading a user font's names for a list keeps none of its bytes and uses none of the load - /// budget. (Font folders themselves are process-wide: `tests/ttf_font_folders.rs`.) + /// budget. The font file is written here, so the check does not depend on which fonts are + /// installed. (Font folders themselves are process-wide: `tests/ttf_font_folders.rs`.) #[cfg(not(target_arch = "wasm32"))] #[test] fn reading_a_user_fonts_names_keeps_no_font_bytes() { - let Some(src) = scan().into_values().find(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("ttf"))) else { return }; + /// A folder of this test's own, made here so nothing else put it there first, and removed + /// with the font in it when the test ends, also when it fails. + struct TestDir(std::path::PathBuf); + impl Drop for TestDir { + /// Removes the folder and all it holds. + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let mut attempt = 0u32; + let dir = loop { + let dir = std::env::temp_dir().join(format!("cadcraft-face-names-{}-{attempt}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => break TestDir(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => attempt += 1, + Err(e) => panic!("{}: {e}", dir.display()), + } + }; + let path = dir.0.join("face.ttf"); + std::fs::write(&path, font_with_names(&[(3, 1, 0x409, 1, utf16("Face Family"))])).unwrap(); let mut db = Db::default(); db.user.insert("face".into()); - db.paths.insert("face".into(), Source::File(src)); - assert!(db.face_names("face").is_some_and(|n| n.family.is_some())); + db.paths.insert("face".into(), Source::File(path)); + let family = db.face_names("face").and_then(|n| n.family.clone()); + assert_eq!(family.as_deref(), Some("Face Family"), "the names are read from the file"); assert!(db.files.is_empty() && db.loaded_bytes == 0); } + /// A family name is read past name records that read as blank: an empty Unicode-platform + /// record before the Mac and Windows names (the shape of some installed fonts), or a Mac name + /// in Shift-JIS, which is not decoded. + #[test] + fn a_family_name_is_read_past_blank_name_records() { + let family = |records: &[Record]| faces(&Arc::new(font_with_names(records))).first().and_then(Face::family_name); + let empty = (0, 0, 0, 1, Vec::new()); + let mac = (1, 0, 0, 1, b"Face Family".to_vec()); + let windows = (3, 1, 0x409, 1, utf16("Face Family")); + assert_eq!(family(&[empty.clone(), mac, windows.clone()]).as_deref(), Some("Face Family")); + // Fullwidth "MS" in Shift-JIS: Mac platform 1, Japanese encoding 1, language 11. + let sjis = |id| (1, 1, 11, id, vec![0x82, 0x6C, 0x82, 0x72]); + assert_eq!(family(&[sjis(1), windows]).as_deref(), Some("Face Family")); + // The typographic family still comes first when its first record reads as blank. + let typographic = [empty.clone(), sjis(16), (3, 1, 0x409, 1, utf16("Face")), (3, 1, 0x409, 16, utf16("Face Family"))]; + assert_eq!(family(&typographic).as_deref(), Some("Face Family")); + assert_eq!(family(&[empty, (1, 0, 0, 1, b" ".to_vec()), sjis(1)]), None, "no name that can be read"); + } + /// One unreadable user font file with the family does not stop the search: the next file /// that has the family is still read. #[test] diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index bc320f584..542c6180e 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -45,9 +45,10 @@ pub fn norm_angle(a: f64) -> f64 { } /// Counter-clockwise sweep from `start` to `end`, in `(0, 2π]`. +/// Only (numerically) equal angles give a full turn; tiny genuine sweeps are kept. pub fn ccw_sweep(start: f64, end: f64) -> f64 { let s = norm_angle(end - start); - if s <= EPS { TAU } else { s } + if s <= 1e-14 { TAU } else { s } } /// True when angle `a` lies on the CCW sweep from `start` to `end` (inclusive, with tolerance). diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index 12ff47220..7131835fb 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -33,6 +33,9 @@ pub struct Boundary { pub islands: Vec, /// Indices into the input polylines that make up `outer`, ascending. pub outer_sources: Vec, + /// The input polyline of each edge of `outer` (`outer[i]` to the next vertex), `None` for a + /// gap bridged with HPGAPTOL. + pub outer_edges: Vec>, } /// One island: the outside outline of a connected group of curves. @@ -42,6 +45,8 @@ pub struct Island { pub outline: Vec, /// Indices into the input polylines that make up the group, ascending. pub sources: Vec, + /// The input polyline of each edge of `outline`, as [`Boundary::outer_edges`]. + pub edges: Vec>, } #[expect( @@ -62,6 +67,8 @@ struct Graph { src: Vec<(usize, usize)>, /// The input polyline of every edge (lower vertex index first). edge_src: HashMap<(usize, usize), usize>, + /// Edges that bridge a gap between curve ends (HPGAPTOL), lower vertex index first. + gap: std::collections::HashSet<(usize, usize)>, } /// Records the crossing of segments `i` and `j`, if any, as split parameters on both. @@ -210,7 +217,7 @@ fn build_with(polys: &[Vec], tol: f64, find_splits: impl Fn(&[(Vec2, Vec2) let bb = Bounds2::from_points(segs.iter().flat_map(|(a, b)| [*a, *b])); let n = segs.len(); let splits = find_splits(&segs, &bb)?; - let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new() }; + let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new(), gap: Default::default() }; let mut index: HashMap<(i64, i64), usize> = HashMap::new(); let mut vid = |p: Vec2, g: &mut Graph| -> usize { let k = key(p, bb.min, tol); @@ -295,6 +302,7 @@ fn build_gap(polys: &[Vec], tol: f64, gap: f64) -> Option { if let Some(k) = owner { g.edge_src.insert((u.min(v), u.max(v)), k); } + g.gap.insert((u.min(v), u.max(v))); if let Some(f) = joined.get_mut(i) { *f = true; } @@ -342,6 +350,17 @@ fn points(g: &Graph, ids: &[usize]) -> Option> { ids.iter().map(|&i| g.pts.get(i).copied()).collect() } +/// The input polyline of each edge of the closed loop `ids` (`None` for a bridged gap). +fn edge_owners(g: &Graph, ids: &[usize]) -> Vec> { + ids.iter() + .zip(ids.iter().cycle().skip(1)) + .map(|(&u, &v)| { + let k = (u.min(v), u.max(v)); + if g.gap.contains(&k) { None } else { g.edge_src.get(&k).copied() } + }) + .collect() +} + /// The face around `p`, as vertex indices (counter-clockwise). #[expect(clippy::many_single_char_names, reason = "Ray/edge traversal keeps conventional graph and point notation.")] fn outer_face(g: &Graph, p: Vec2) -> Option> { @@ -420,12 +439,12 @@ fn prune(g: &Graph) -> Graph { } } } - Graph { pts: g.pts.clone(), adj, src: Vec::new(), edge_src: HashMap::new() } + Graph { pts: g.pts.clone(), adj, src: Vec::new(), edge_src: g.edge_src.clone(), gap: g.gap.clone() } } /// The outline of the outside of a group of curves on cycles, traced counter-clockwise from its /// leftmost (then lowest) vertex `u`, giving up after `steps` edges. -fn outside(core: &Graph, u: usize, steps: usize) -> Option> { +fn outside(core: &Graph, u: usize, steps: usize) -> Option<(Vec, Vec>)> { let pu = *core.pts.get(u)?; // Every neighbour lies to the right of the leftmost vertex; the one turned furthest // counter-clockwise has the outside of the group on its left. @@ -436,9 +455,9 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option> { }) }; let w = core.adj.get(u).into_iter().flatten().filter_map(|w| Some((signed(w)?, *w))).max_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, w)| w)?; - let mut lp = trace(core, u, w, steps).and_then(|ids| points(core, &ids))?; - lp.reverse(); - Some(lp) + let mut ids = trace(core, u, w, steps)?; + ids.reverse(); + Some((points(core, &ids)?, edge_owners(core, &ids))) } /// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`). @@ -497,7 +516,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { continue; } let steps = edges.get(&c).copied().unwrap_or(0).saturating_add(4); - let Some(lp) = outside(&core, u, steps) else { continue }; + let Some((lp, edges)) = outside(&core, u, steps) else { continue }; let area = shoelace(&lp); let ib = Bounds2::from_points(lp.iter().copied()); if lp.len() < 3 || !area.is_finite() || area <= 0.0 || !ob.contains_box(&ib) { @@ -511,7 +530,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { let mut src = sources.remove(&c).unwrap_or_default(); src.sort_unstable(); src.dedup(); - out.push(Island { outline: lp, sources: src }); + out.push(Island { outline: lp, sources: src, edges }); } Some(out) } @@ -619,8 +638,14 @@ pub fn enclosing_loop(polys: &[Vec], p: Vec2, tol: f64) -> Option], p: Vec2, tol: f64, gap: f64) -> Option> { + enclosing_loop_edges_gap(polys, p, tol, gap).map(|(lp, _)| lp) +} + +/// [`enclosing_loop_gap`] with the input polyline of each edge, as [`Boundary::outer_edges`]. +pub fn enclosing_loop_edges_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option<(Vec, Vec>)> { let g = build_gap(polys, tol, gap)?; - points(&g, &outer_face(&g, p)?) + let ids = outer_face(&g, p)?; + Some((points(&g, &ids)?, edge_owners(&g, &ids))) } /// The closed loop enclosing `p` plus the islands inside it, or `None` when `p` isn't enclosed. @@ -638,14 +663,20 @@ pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Opti ids.iter().zip(ids.iter().cycle().skip(1)).filter_map(|(&u, &v)| g.edge_src.get(&(u.min(v), u.max(v))).copied()).collect(); outer_sources.sort_unstable(); outer_sources.dedup(); - Some(Boundary { outer, islands, outer_sources }) + let outer_edges = edge_owners(&g, &ids); + Some(Boundary { outer, islands, outer_sources, outer_edges }) } /// The outside outline of curves that together enclose an area (counter-clockwise, dangling /// ends removed), or `None` when they enclose nothing or form more than one separate group. /// Gaps of up to `gap` between curve ends are closed (HPGAPTOL). -#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")] pub fn outline(polys: &[Vec], tol: f64, gap: f64) -> Option> { + outline_edges(polys, tol, gap).map(|(lp, _)| lp) +} + +/// [`outline`] with the input polyline of each edge, as [`Boundary::outer_edges`]. +#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")] +pub fn outline_edges(polys: &[Vec], tol: f64, gap: f64) -> Option<(Vec, Vec>)> { let g = build_gap(polys, tol, gap)?; let core = prune(&g); let comp = components(&core); @@ -667,8 +698,8 @@ pub fn outline(polys: &[Vec], tol: f64, gap: f64) -> Option> { start = Some(u); } } - let lp = outside(&core, start?, edges.saturating_add(4))?; - (lp.len() >= 3 && shoelace(&lp) > 0.0).then_some(lp) + let (lp, owners) = outside(&core, start?, edges.saturating_add(4))?; + (lp.len() >= 3 && shoelace(&lp) > 0.0).then_some((lp, owners)) } /// A point strictly inside a closed polygon (either orientation), for re-finding the face a @@ -1075,6 +1106,34 @@ mod tests { assert!(interior_point(&[Vec2::new(f64::NAN, 0.0); 4]).is_none()); } + #[test] + fn edges_name_their_input_polyline_and_bridged_gaps_none() { + // A square of four separate sides; the right side stops short of the top (a gap). + let sides = vec![ + vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)], + vec![Vec2::new(10.0, 0.0), Vec2::new(10.0, 9.9)], + vec![Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)], + vec![Vec2::new(0.0, 10.0), Vec2::new(0.0, 0.0)], + ]; + let b = boundary_at_gap(&sides, Vec2::new(5.0, 5.0), 1e-9, 0.5).unwrap(); + assert_eq!(b.outer_edges.len(), b.outer.len()); + // Each edge names the side it lies on; the bridged gap names none. + for (i, e) in b.outer_edges.iter().enumerate() { + let (a, c) = (b.outer[i], b.outer[(i + 1) % b.outer.len()]); + match e { + Some(k) => { + let s = &sides[*k]; + let on = |q: Vec2| crate::Line::new(s[0], s[1]).closest(q).dist(q) < 1e-9; + assert!(on(a) && on(c), "edge {i} not on side {k}"); + } + None => assert!(a.dist(c) < 0.5 + 1e-9, "only the gap is unnamed"), + } + } + assert_eq!(b.outer_edges.iter().filter(|e| e.is_none()).count(), 1); + let (lp, edges) = outline_edges(&sides, 1e-9, 0.5).unwrap(); + assert_eq!(lp.len(), edges.len()); + } + #[test] fn gap_tolerance_closes_small_gaps() { // Four lines with 0.5 gaps at two corners. diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index b0c9d2a33..7036f200a 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -81,6 +81,36 @@ impl Spline { speed > 0.0 && d0.near(d1, 1e-9 * speed) && self.eval(lo).near(self.eval(hi), 1e-9 * speed * (hi - lo)) } + /// 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. Only points + /// that really repeat count: with wrapping knots but a different tail, every control point is + /// its own, even when only the last repeats the first. + pub fn distinct_controls(&self) -> usize { + let n = self.control.len(); + let u = n.saturating_sub(self.degree); + let tail_repeats = || u > 0 && self.control.iter().zip(self.control.iter().skip(u)).all(|(a, b)| a.near(*b, 1e-12)); + if self.wraps() && tail_repeats() { + u + } else if self.closed && !self.wraps() && n > 2 && self.control.first().zip(self.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) { + n - 1 + } else { + n + } + } + + /// Indices holding distinct control point `j` (with its repeats). + pub fn control_copies(&self, j: usize) -> Vec { + let (n, u) = (self.control.len(), self.distinct_controls()); + if j >= u { + return Vec::new(); + } + let mut out = vec![j]; + if u < n { + out.extend((j + u..n).step_by(u.max(1))); + } + out + } + pub fn is_valid(&self) -> bool { let n = self.control.len(); n > self.degree diff --git a/crates/geom/src/spline/tests.rs b/crates/geom/src/spline/tests.rs index 001615fff..1f325d727 100644 --- a/crates/geom/src/spline/tests.rs +++ b/crates/geom/src/spline/tests.rs @@ -603,3 +603,36 @@ fn the_cyclic_matrix_of_a_closed_fit_keeps_the_full_sweep() { assert_same_solution(&a, &b, &format!("cyclic n={n}")); } } + +/// Control points count as copies only where they repeat: a closed spline whose knots wrap but +/// whose last control points don't repeat the first ones keeps every control point its own. +#[test] +fn only_repeated_control_points_are_copies() { + let v = Vec2::new; + let square = [v(0.0, 0.0), v(4.0, 0.0), v(4.0, 4.0), v(0.0, 4.0)]; + let wraps = Spline { + degree: 2, + knots: (0..9).map(f64::from).collect(), + control: square.iter().chain(&square[..2]).copied().collect(), + closed: true, + ..Spline::default() + }; + assert!(wraps.wraps() && wraps.distinct_controls() < wraps.control.len()); + assert_eq!(wraps.control_copies(0), [0, 4]); + + let tail = Spline { + degree: 2, + knots: vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0], + control: square.iter().copied().chain([v(2.0, 0.0)]).collect(), + closed: true, + ..Spline::default() + }; + assert!(tail.is_valid() && tail.wraps()); + assert_eq!(tail.distinct_controls(), tail.control.len()); + assert_eq!(tail.control_copies(0), [0]); + + let first_again = Spline { control: square.iter().copied().chain([v(0.0, 0.0)]).collect(), ..tail }; + assert!(first_again.is_valid() && first_again.wraps()); + assert_eq!(first_again.distinct_controls(), first_again.control.len()); + assert_eq!(first_again.control_copies(0), [0]); +} diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 2de0d4691..6ffde2b11 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -432,3 +432,16 @@ fn open_polyline_centroid_ignores_last_bulge() { let after = pl.centroid().unwrap(); assert!(before.near(after, 1e-9), "{before:?} -> {after:?}"); } + +#[test] +fn tiny_arc_sweep_is_not_a_full_circle() { + for x in [0.0, 1.0, 5.5] { + assert!(close(ccw_sweep(x, x), TAU)); + } + assert!((ccw_sweep(0.0, 5e-10) - 5e-10).abs() < 1e-15, "{}", ccw_sweep(0.0, 5e-10)); + let a = Arc::new(Vec2::new(0.0, 0.0), 1e6, 0.0, 5e-10); + assert!((a.len() - 5e-4).abs() < 1e-6, "{}", a.len()); + assert!(a.contains_angle(2.5e-10)); + assert!(!a.contains_angle(1.0)); + assert!(a.mid_point().near(Vec2::new(1e6, 0.0), 1e-2)); +} diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs new file mode 100644 index 000000000..7e6e23e1e --- /dev/null +++ b/crates/io/src/dxf_anno.rs @@ -0,0 +1,507 @@ +//! Annotative text, MText, dimensions and multileaders in DXF, as AutoCAD keeps them. An annotative object +//! carries `AcadAnnotative` xdata and, in its extension dictionary under +//! `AcDbContextDataManager`, a dictionary `ACDB_ANNOTATIONSCALES` with one "object context data" +//! object per annotation scale it supports (`*A1`, `*A2`…). Each context names its SCALE object +//! (340), says whether it is the default one (290 = 1, the scale the object's own groups are +//! written at) and holds what changes with the scale: a text's insertion and alignment points, an +//! MText's insertion point, width and columns, a dimension's text position and the anonymous `*D` +//! block with its geometry at that scale, a multileader's whole `CONTEXT_DATA{` body at that +//! scale. +//! +//! CADCraft keeps an annotative object at paper size with the list of scales it supports +//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a +//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the +//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it: +//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model. +//! +//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format +//! (before annotation scaling) don't get contexts. + +use std::collections::{BTreeSet, HashMap}; + +use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MLeader, MTextColumnType, Text, VAlign}; +use cadcraft_geom::Vec3; +use craft_dxf::{SectionRef, Tag}; + +/// The context classes: (DXF record name, C++ class name). +const TEXT: (&str, &str) = ("ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "AcDbTextObjectContextData"); +const MTEXT: (&str, &str) = ("ACDB_MTEXTOBJECTCONTEXTDATA_CLASS", "AcDbMTextObjectContextData"); +const ALDIM: (&str, &str) = ("ACDB_ALDIMOBJECTCONTEXTDATA_CLASS", "AcDbAlignedDimensionObjectContextData"); +const ANGDIM: (&str, &str) = ("ACDB_ANGDIMOBJECTCONTEXTDATA_CLASS", "AcDbAngularDimensionObjectContextData"); +const RADIM: (&str, &str) = ("ACDB_RADIMOBJECTCONTEXTDATA_CLASS", "AcDbRadialDimensionObjectContextData"); +const DMDIM: (&str, &str) = ("ACDB_DMDIMOBJECTCONTEXTDATA_CLASS", "AcDbDiametricDimensionObjectContextData"); +const ORDDIM: (&str, &str) = ("ACDB_ORDDIMOBJECTCONTEXTDATA_CLASS", "AcDbOrdinateDimensionObjectContextData"); +const MLEADER: (&str, &str) = ("ACDB_MLEADEROBJECTCONTEXTDATA_CLASS", "AcDbMLeaderObjectContextData"); + +/// The extension dictionary entry and the dictionary of contexts. +const MANAGER_KEY: &str = "AcDbContextDataManager"; +const SCALES_KEY: &str = "ACDB_ANNOTATIONSCALES"; + +/// Most contexts read per object (hostile files). +const MAX_CONTEXTS: usize = cadcraft_doc::MAX_SCALES; + +/// Whether `e` (in model space or a layout) is written with annotation scale contexts: annotative +/// text, MText, dimensions and multileaders. +pub(crate) fn has_contexts(e: &Entity) -> bool { + cadcraft_doc::is_annotative(e) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_)) +} + +/// The scales `e` is written at (valid, each name once) and which of them is the default: the +/// current annotation scale when `e` supports it, else its first. +pub(crate) fn scales(d: &Drawing, e: &Entity) -> (Vec, usize) { + let mut out: Vec = Vec::new(); + for s in e.common.anno_scales.iter().filter(|s| s.is_valid() && !s.name.trim().is_empty()) { + if !out.iter().any(|x| x.name.eq_ignore_ascii_case(&s.name)) { + out.push(s.clone()); + } + } + let current = d.current_anno_scale(); + let default = out.iter().position(|s| s.name.eq_ignore_ascii_case(¤t.name)).unwrap_or(0); + (out, default) +} + +/// Whether text placed by its alignment point (group 11) rather than its start point (10). +fn by_alignment(t: &Text) -> bool { + t.align_pt.is_some() && !matches!((t.halign, t.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)) +} + +/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see +/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its +/// alignment point. A dimension's definition gets that scale (DIMSCALE). +pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity { + let mut out = cadcraft_doc::anno_scaled(e, f); + if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind) + && by_alignment(paper) + && let Some(a) = paper.align_pt + { + t.insert = a + (paper.insert - a) * f; + } + out +} + +/// One context: its handle, the SCALE object's handle and the scale. +pub(crate) struct Context { + handle: String, + scale: String, + factor: f64, + default: bool, + /// A dimension's `*D` block at this scale. + block: Option, +} + +/// The objects written for one annotative object. +pub(crate) struct Obj { + /// Its extension dictionary (shared with a dimension's DIMASSOC). + pub xdict: String, + /// Whether the extension dictionary is written here (not with the DIMASSOC). + pub own_xdict: bool, + pub manager: String, + dict: String, + contexts: Vec, +} + +/// The annotative objects of a file being written, by entity handle. +#[derive(Default)] +pub(crate) struct Plan { + pub objs: HashMap, +} + +impl Plan { + /// The context classes the file uses (for its CLASSES section). + pub fn classes(&self, d: &Drawing) -> Vec<(&'static str, &'static str)> { + let mut out = BTreeSet::new(); + for h in self.objs.keys() { + if let Some(e) = d.entity(*h) { + out.insert(class_of(e)); + } + } + out.into_iter().flatten().collect() + } +} + +fn class_of(e: &Entity) -> Option<(&'static str, &'static str)> { + Some(match &e.kind { + EntityKind::Text(_) => TEXT, + EntityKind::MText(_) => MTEXT, + EntityKind::MLeader(_) => MLEADER, + EntityKind::Dimension(dm) => match dm.kind { + DimKind::Linear { .. } | DimKind::Aligned | DimKind::ArcLength => ALDIM, + DimKind::Angular | DimKind::Angular3P => ANGDIM, + DimKind::Radius => RADIM, + DimKind::Diameter => DMDIM, + DimKind::Ordinate { .. } => ORDDIM, + }, + _ => return None, + }) +} + +/// Plan the objects of `e` (annotative, see [`has_contexts`]): `scale_handle` gives each scale's +/// SCALE object, `xdict` the extension dictionary it already has (a dimension's DIMASSOC), +/// `blocks` a dimension's `*D` block at each of [`scales`], and `next` new handles. `None` when +/// no scale has a SCALE object. +pub(crate) fn plan_one( + d: &Drawing, + e: &Entity, + scale_handle: impl Fn(&str) -> Option, + xdict: Option, + blocks: Option<&[String]>, + mut next: impl FnMut() -> String, +) -> Option { + let (scales, default) = scales(d, e); + let mut contexts = Vec::new(); + for (i, s) in scales.iter().enumerate() { + let Some(scale) = scale_handle(&s.name) else { continue }; + let block = blocks.and_then(|b| b.get(i)).cloned(); + contexts.push(Context { handle: String::new(), scale, factor: s.factor(), default: i == default, block }); + } + if contexts.is_empty() { + return None; + } + if !contexts.iter().any(|c| c.default) + && let Some(c) = contexts.first_mut() + { + c.default = true; + } + let own_xdict = xdict.is_none(); + let xdict = xdict.unwrap_or_else(&mut next); + let (manager, dict) = (next(), next()); + for c in &mut contexts { + c.handle = next(); + } + Some(Obj { xdict, own_xdict, manager, dict, contexts }) +} + +/// The factor `e` is written at (its default context's). +pub(crate) fn default_factor(o: &Obj) -> f64 { + o.contexts.iter().find(|c| c.default).map_or(1.0, |c| c.factor) +} + +/// `AcadAnnotative` xdata marking an annotative object. +pub(crate) fn xdata() -> Vec { + vec![Tag::s(1001, "AcadAnnotative"), Tag::s(1000, "AnnotativeData"), Tag::s(1002, "{"), Tag::i(1070, 1), Tag::i(1070, 1), Tag::s(1002, "}")] +} + +/// The extension dictionary entry of `o`'s context manager (key and handle groups). +pub(crate) fn xdict_entry(o: &Obj) -> Vec { + vec![Tag::s(3, MANAGER_KEY), Tag::s(360, o.manager.clone())] +} + +fn p(out: &mut Vec, c: i32, v: Vec3, z: bool) { + out.push(Tag::f(c, v.x)); + out.push(Tag::f(c + 10, v.y)); + if z { + out.push(Tag::f(c + 20, v.z)); + } +} + +/// A dictionary record: handle, reactor and owner `owner`, hard-owner flag 281 = 1, `entries`. +fn dictionary(out: &mut Vec, h: &str, owner: &str, cloning: bool, entries: &[(String, i32, String)]) { + out.push(Tag::s(0, "DICTIONARY")); + out.push(Tag::s(5, h)); + out.extend([Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, owner), Tag::s(102, "}")]); + out.push(Tag::s(330, owner)); + out.push(Tag::s(100, "AcDbDictionary")); + if cloning { + out.push(Tag::i(280, 1)); + } + out.push(Tag::i(281, 1)); + for (k, code, v) in entries { + out.push(Tag::s(3, k.clone())); + out.push(Tag::s(*code, v.clone())); + } +} + +/// The objects of annotative object `e` planned as `o`: its extension dictionary (unless the +/// DIMASSOC's holds the manager), the context manager, the dictionary of contexts and the +/// contexts. `mleader` gives a multileader's groups as the entity writer writes them. +pub(crate) fn objects(d: &Drawing, e: &Entity, o: &Obj, mleader: &dyn Fn(&MLeader) -> Vec) -> Vec { + let mut out = Vec::new(); + let eh = e.handle.hex(); + if o.own_xdict { + dictionary(&mut out, &o.xdict, &eh, true, &[(MANAGER_KEY.to_string(), 360, o.manager.clone())]); + } + dictionary(&mut out, &o.manager, &o.xdict, false, &[(SCALES_KEY.to_string(), 350, o.dict.clone())]); + let keyed: Vec<(String, i32, String)> = o.contexts.iter().enumerate().map(|(i, c)| (format!("*A{}", i + 1), 350, c.handle.clone())).collect(); + dictionary(&mut out, &o.dict, &o.manager, false, &keyed); + let Some((class, _)) = class_of(e) else { return out }; + for c in &o.contexts { + out.push(Tag::s(0, class)); + out.push(Tag::s(5, c.handle.clone())); + out.extend([Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, o.dict.clone()), Tag::s(102, "}")]); + out.push(Tag::s(330, o.dict.clone())); + out.push(Tag::s(100, "AcDbObjectContextData")); + out.push(Tag::i(70, 4)); + out.push(Tag::i(290, i64::from(c.default))); + out.push(Tag::s(100, "AcDbAnnotScaleObjectContextData")); + out.push(Tag::s(340, c.scale.clone())); + context_groups(&mut out, d, &at_scale(e, c.factor), c, mleader); + } + out +} + +/// What a context holds of `e` (already at the context's scale). +fn context_groups(out: &mut Vec, d: &Drawing, e: &Entity, c: &Context, mleader: &dyn Fn(&MLeader) -> Vec) { + match &e.kind { + // The multileader's `CONTEXT_DATA{` body, without its braces. + EntityKind::MLeader(m) => { + let mut tags = mleader(m); + mleader_at(&mut tags, c.factor); + let open = tags.iter().position(|t| t.code == 300 && t.str().trim_start().starts_with("CONTEXT_DATA")); + let close = tags.iter().position(|t| t.code == 301); + if let (Some(a), Some(b)) = (open, close) + && a < b + { + out.extend(tags.get(a + 1..b).unwrap_or(&[]).iter().cloned()); + } + } + EntityKind::Text(t) => { + let h = match t.halign { + HAlign::Left => 0, + HAlign::Center => 1, + HAlign::Right => 2, + HAlign::Aligned => 3, + HAlign::Middle => 4, + HAlign::Fit => 5, + }; + out.push(Tag::i(70, h)); + out.push(Tag::f(50, t.rotation.to_degrees())); + p(out, 10, t.insert, false); + p(out, 11, t.align_pt.unwrap_or(Vec3::ZERO), false); + } + EntityKind::MText(t) => { + out.push(Tag::i(70, i64::from(t.attach))); + p(out, 10, Vec3::new(t.rotation.cos(), t.rotation.sin(), 0.0), true); + p(out, 11, t.insert, true); + // Reference rectangle (40, 41) and an estimate of the text's extents (42, 43): AutoCAD + // lays the text out again. + let lines = t.contents.split("\\P").count().max(1) as f64; + let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1) as f64; + out.push(Tag::f(40, t.width)); + out.push(Tag::f(41, 0.0)); + out.push(Tag::f(42, if t.width > 0.0 { t.width } else { t.height * 0.8 * longest })); + out.push(Tag::f(43, t.height * 1.66 * lines)); + match &t.columns { + None => out.push(Tag::i(71, 0)), + Some(cols) => { + let dynamic = cols.kind == MTextColumnType::Dynamic; + let manual = dynamic && !cols.auto_height; + out.push(Tag::i(71, if dynamic { 2 } else { 1 })); + out.push(Tag::i(72, if manual { cols.heights.len() as i64 } else { i64::from(cols.count.max(1)) })); + out.push(Tag::f(44, t.width)); + out.push(Tag::f(45, cols.gutter)); + out.push(Tag::i(73, i64::from(cols.auto_height))); + out.push(Tag::i(74, i64::from(cols.flow_reversed))); + if manual { + out.extend(cols.heights.iter().map(|h| Tag::f(46, *h))); + } + } + } + } + EntityKind::Dimension(dm) => { + out.push(Tag::s(100, "AcDbDimensionObjectContextData")); + out.push(Tag::s(2, c.block.clone().unwrap_or_default())); + out.push(Tag::i(293, 0)); + let text = if dm.user_text_pos { dm.text_mid } else { cadcraft_render::dimension_in(d, dm).text_pos.to3(0.0) }; + p(out, 10, text, false); + out.push(Tag::i(294, i64::from(!dm.user_text_pos))); + out.push(Tag::f(140, dm.text_rotation)); + for code in [298, 291, 70, 292, 71, 280, 295, 296, 297] { + out.push(Tag::i(code, 0)); + } + let Some((_, sub)) = class_of(e) else { return }; + out.push(Tag::s(100, sub)); + let pts: &[(i32, Vec3)] = match dm.kind { + DimKind::Linear { .. } | DimKind::Aligned | DimKind::ArcLength | DimKind::Angular3P => &[(11, dm.defpt)], + DimKind::Angular => &[(11, dm.p16)], + DimKind::Radius => &[(11, dm.p15)], + DimKind::Diameter => &[(11, dm.p15), (12, dm.defpt)], + DimKind::Ordinate { .. } => &[(11, dm.defpt), (12, dm.p14)], + }; + for (code, v) in pts { + p(out, *code, *v, true); + } + } + _ => {} + } +} + +/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) at annotation +/// scale `f`: its context's overall scale (40) is `f` and its landing gap (145) is at that scale. +pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) { + let Some(open) = tags.iter().position(|t| t.code == 300 && t.str().trim_start().starts_with("CONTEXT_DATA")) else { return }; + let (mut scale, mut gap) = (false, false); + for t in tags.iter_mut().skip(open + 1) { + match t.code { + // The context's own groups end where its leaders start. + 302 | 301 => break, + 40 if !scale => { + *t = Tag::f(40, f); + scale = true; + } + 145 if !gap => { + *t = Tag::f(145, t.f64() * f); + gap = true; + } + _ => {} + } + } +} + +// --------------------------------------------------------------------------------------------- +// Reading + +/// A record's groups before its xdata. +fn own(tags: &[Tag]) -> &[Tag] { + tags.get(..tags.iter().position(|t| t.code >= 1000).unwrap_or(tags.len())).unwrap_or(&[]) +} + +/// A handle as the key of the maps below. +fn key(s: &str) -> Option { + Handle::parse_hex(s.trim()).filter(|h| h.0 != 0) +} + +/// The extension dictionary of a record (`{ACAD_XDICTIONARY` group). +fn xdict_of(tags: &[Tag]) -> Option { + let i = own(tags).iter().position(|t| t.code == 102 && t.str().trim() == "{ACAD_XDICTIONARY")?; + tags.get(i + 1).filter(|t| t.code == 360).and_then(|t| key(&t.str())) +} + +/// A dictionary's entry `name` (case-insensitive). +fn entry(tags: &[Tag], name: &str) -> Option { + let g = own(tags); + let i = g.iter().position(|t| t.code == 3 && t.str().trim().eq_ignore_ascii_case(name))?; + g.get(i + 1).filter(|t| matches!(t.code, 350 | 360)).and_then(|t| key(&t.str())) +} + +/// Every entry of a dictionary. +fn all_entries(tags: &[Tag]) -> Vec { + own(tags).iter().filter(|t| matches!(t.code, 350 | 360)).filter_map(|t| key(&t.str())).take(MAX_CONTEXTS).collect() +} + +/// Read the annotation scale contexts of the text, MText and dimensions of model space and the +/// layouts: each becomes annotative with the scales of its contexts (in their order), and +/// its sizes are taken back to paper size from the default scale. Contexts of other objects, and +/// contexts whose scale is unknown, are passed over. +pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) { + let Some(objects) = secs.iter().find(|s| s.name == "OBJECTS") else { return }; + let mut objs: HashMap = HashMap::new(); + each_record(objects.tags, |kind, tags| { + if let Some(h) = own(tags).iter().find(|t| t.code == 5).and_then(|t| key(&t.str())) { + objs.entry(h).or_insert((kind.to_ascii_uppercase(), tags)); + } + }); + current_scale(&objs, d); + if !objs.values().any(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) { + return; + } + let scales: HashMap = + objs.iter().filter(|(_, (k, _))| k == "SCALE").filter_map(|(h, (_, t))| Some((*h, crate::dxf_ext::read_scale(own(t))?))).collect(); + // The entities that may have contexts: their extension dictionaries. + let mut found: Vec<(Handle, Handle)> = Vec::new(); + for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") { + each_record(s.tags, |kind, tags| { + if !matches!(kind, "TEXT" | "MTEXT" | "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" | "MULTILEADER") { + return; + } + let h = own(tags).iter().find(|t| t.code == 5).and_then(|t| key(&t.str())); + if let (Some(h), Some(x)) = (h, xdict_of(tags)) { + found.push((h, x)); + } + }); + } + for (h, xdict) in found { + let Some(e) = d.entity(h) else { continue }; + if !matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_)) { + continue; + } + let dict = objs + .get(&xdict) + .and_then(|(_, t)| entry(t, MANAGER_KEY)) + .and_then(|m| objs.get(&m)) + .and_then(|(_, t)| entry(t, SCALES_KEY)) + .and_then(|s| objs.get(&s)); + let Some((_, dict)) = dict else { continue }; + let mut list: Vec<(AnnoScale, bool)> = Vec::new(); + for c in all_entries(dict) { + let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue }; + let g = own(t); + let scale = g.iter().find(|t| t.code == 340).and_then(|t| key(&t.str())).and_then(|s| scales.get(&s)); + let default = g.iter().find(|t| t.code == 290).is_some_and(|t| t.i64() != 0); + if let Some(s) = scale + && !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name)) + { + list.push((s.clone(), default)); + } + } + if list.is_empty() { + continue; + } + // The object's groups were written at the default context's scale. + let f = list.iter().find(|(_, default)| *default).or(list.first()).map_or(1.0, |(s, _)| s.factor()); + let list: Vec = list.into_iter().map(|(s, _)| s).collect(); + let _ = d.modify_entity(h, |e| { + e.common.anno_scales = list; + to_paper(e, f); + }); + } +} + +/// The current annotation scale as AutoCAD keeps it: in the named object dictionary's +/// `AcDbVariableDictionary`, a DICTIONARYVAR `CANNOSCALE` with the scale's name (group 1). It is +/// newer than CADCraft's own record when AutoCAD saved the file last (AutoCAD keeps that record as +/// it was), and CADCraft writes the two alike. A name the scale list lacks is passed over. +fn current_scale(objs: &HashMap, d: &mut Drawing) { + let root = objs.iter().filter(|(_, (k, t))| k == "DICTIONARY" && own(t).iter().find(|t| t.code == 330).is_some_and(|o| o.str().trim() == "0")); + let Some((_, (_, root))) = root.min_by_key(|(h, _)| h.0) else { return }; + let var = entry(root, "AcDbVariableDictionary").and_then(|v| objs.get(&v)).and_then(|(_, t)| entry(t, "CANNOSCALE")).and_then(|c| objs.get(&c)); + let Some(name) = var.and_then(|(_, t)| own(t).iter().find(|t| t.code == 1).map(Tag::str)) else { return }; + let name = name.trim(); + if d.anno_scale(name).is_some_and(AnnoScale::is_valid) { + d.header.set_str("CANNOSCALE", name); + } +} + +/// Take an object written at annotation scale `f` back to paper size (the inverse of +/// [`at_scale`]). +fn to_paper(e: &mut Entity, f: f64) { + if !(f.is_finite() && f > 0.0) || (f - 1.0).abs() < 1e-12 { + return; + } + let inv = 1.0 / f; + match &mut e.kind { + EntityKind::Text(t) => { + if by_alignment(t) + && let Some(a) = t.align_pt + { + t.insert = a + (t.insert - a) * inv; + } + t.height *= inv; + } + EntityKind::MText(t) => { + t.height *= inv; + t.width *= inv; + if let Some(c) = &mut t.columns { + c.scale(inv); + } + } + // Its sizes, and its content's place about the landing, scale linearly. + EntityKind::MLeader(_) => e.kind = cadcraft_doc::anno_scaled(e, inv).kind, + _ => {} + } +} + +/// Call `f` with each record (type, groups after its `0` group) of a section. +fn each_record<'a>(tags: &'a [Tag], mut f: impl FnMut(&str, &'a [Tag])) { + let mut open: Option<(String, usize)> = None; + for (i, t) in tags.iter().enumerate() { + if t.code == 0 { + if let Some((k, s)) = open.take() { + f(&k, tags.get(s..i).unwrap_or(&[])); + } + open = Some((t.str(), i + 1)); + } + } + if let Some((k, s)) = open { + f(&k, tags.get(s..).unwrap_or(&[])); + } +} diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs index 5e239e85c..a50f4d602 100644 --- a/crates/io/src/dxf_clip.rs +++ b/crates/io/src/dxf_clip.rs @@ -3,7 +3,8 @@ //! The filter holds the boundary vertices in the reference's coordinates (group 70 the count, //! 10/20 the vertices), whether clipping is on (71), the front and back clip (72/73, 40/41) and //! two 3×4 matrices (group 40, row by row): the inverse of the reference's transform, which takes -//! the boundary into the block's coordinates, and the boundary's own transform (identity here). +//! the boundary into the block's coordinates, and the boundary's own transform (composed with +//! the inverse transform when non-identity, e.g. on clipboard-pasted block references). //! //! An inverted clip ("Invert clip") is marked as the reference app writes it in a file: the //! filter has an extension dictionary whose `ACAD_XREC_ROUNDTRIP` entry is an XRECORD holding @@ -15,7 +16,7 @@ //! written. The record goes through DWG as it is. //! //! Reading takes the planar filters the model can hold out of the kept foreign data and puts them -//! on the references ([`read`]); others (front/back clipping, a skewed boundary transform) stay +//! on the references ([`read`]); others (front/back clipping, non-planar extrusion, sheared boundary transform) stay //! foreign and are written back untouched. Writing adds the dictionaries and the filter of every //! clipped reference to a copy of the drawing's foreign data ([`prepare`]), which the raw-data //! writer (#528) then places on the reference. @@ -164,9 +165,22 @@ fn roundtrip(f: &Foreign, idx: &Index, filter: &ForeignObject) -> Option= 2).then_some(boundary) } -/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates; with `boundary`, the -/// clip is inverted and that is its outline (in the filter's coordinates). `None` for anything -/// the model can't hold as it is (it then stays foreign). +/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates. +/// +/// Per the Autodesk DXF Reference for `SPATIAL_FILTER`: +/// - Group 40 (first 12 values): 3×4 matrix representing the inverse of the block reference +/// transformation (maps coordinates from WCS to block local space). +/// - Group 40 (second 12 values): 3×4 matrix representing the transformation into the coordinate +/// system of the clip boundary ($WCS \to \text{Boundary}$). +/// +/// Since boundary vertices (group 10/20) are stored in the clip boundary's coordinate system, +/// transforming them into the block's local coordinates requires inverting the boundary transform +/// ($\text{Boundary} \to WCS$) and then applying the inverse block transform ($WCS \to \text{Block}$): +/// $P_{\text{block}} = M_{\text{inverse}} \times (M_{\text{boundary\_xf}})^{-1} \times P_{\text{boundary}}$. +/// In code: `boundary_xf.inverse()?.then(inverse)`. +/// +/// With `boundary`, the clip is inverted and that is its outline (in the filter's coordinates). +/// Returns `None` for unsupported configurations (e.g. non-planar extrusion, front/back clipping depth). fn parse_filter(o: &ForeignObject, boundary: Option<&[Vec2]>) -> Option { let count = usize::try_from(number(&o.tags, 70)? as i64).ok()?; if !(2..=MAX_CLIP_VERTICES).contains(&count) { @@ -180,30 +194,47 @@ fn parse_filter(o: &ForeignObject, boundary: Option<&[Vec2]>) -> Option = o.tags.iter().filter(|t| t.code == 40).map(|t| t.value.trim().parse::().unwrap_or(f64::NAN)).collect(); - let (inverse, own) = match m.len() { + let (inverse, boundary_xf) = match m.len() { 24 => (matrix_2d(m.get(..12)?)?, matrix_2d(m.get(12..)?)?), // Without matrices the vertices are taken as the block's own. 0 => (Mat3::IDENTITY, Mat3::IDENTITY), _ => return None, }; - if (own.a - 1.0).abs() > 1e-9 - || own.b.abs() > 1e-9 - || own.c.abs() > 1e-9 - || (own.d - 1.0).abs() > 1e-9 - || own.e.abs() > 1e-9 - || own.f.abs() > 1e-9 - { + // Reject sheared/skewed boundary transforms that cannot be losslessly represented. + // Scale-independent orthogonality check: |u . v| > 1e-4 * |u| * |v| + let u_len = (boundary_xf.a * boundary_xf.a + boundary_xf.b * boundary_xf.b).sqrt(); + let v_len = (boundary_xf.c * boundary_xf.c + boundary_xf.d * boundary_xf.d).sqrt(); + if u_len <= 1e-9 || v_len <= 1e-9 { return None; } - let own = vertices(&o.tags, count)?; - let outline = boundary.unwrap_or(&own); - if !(2..=MAX_CLIP_VERTICES).contains(&outline.len()) { + let dot = boundary_xf.a * boundary_xf.c + boundary_xf.b * boundary_xf.d; + if dot.abs() > 1e-4 * u_len * v_len { return None; } - let points: Vec = outline.iter().map(|p| inverse.apply(*p)).collect(); + let verts = vertices(&o.tags, count)?; + let raw_outline = boundary.unwrap_or(&verts); + if !(2..=MAX_CLIP_VERTICES).contains(&raw_outline.len()) { + return None; + } + let net = boundary_xf.inverse()?.then(inverse); + // Expand a 2-corner rectangle to 4 corners whenever the net transform from boundary space + // to block space introduces rotation, preserving its rotated orientation in block space. + let rotated_rect; + let net_rotated = net.b.abs() > 1e-9 || net.c.abs() > 1e-9; + let outline = match raw_outline { + [a, b] if net_rotated => { + rotated_rect = vec![*a, Vec2::new(b.x, a.y), *b, Vec2::new(a.x, b.y)]; + &rotated_rect[..] + } + other => other, + }; + let mut points: Vec = outline.iter().map(|p| net.apply(*p)).collect(); if !points.iter().all(|p| p.is_finite()) { return None; } + if let [a, b] = points.as_slice() { + points = vec![Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))]; + } let inverted = boundary.is_some() || number(&o.tags, 290).is_some_and(|v| v != 0.0); let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted }; cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some().then_some(clip) @@ -318,6 +349,25 @@ fn dictionary(h: Handle, owner: Handle) -> ForeignObject { } } +/// The boundary transform (`boundary_xf`) and boundary-space vertices for `clip`. +/// +/// A 2-vertex `SPATIAL_FILTER` defines an axis-aligned rectangle in `boundary_xf` space, with +/// vertices ordered lower-left then upper-right per the DXF specification. When the reference is +/// rotated, a 2-point block-space rectangle is axis-aligned in a frame rotated by +/// `-to_world.rotation()` (orthogonal even under non-uniform or mirrored scale), and the two +/// transformed corners are canonicalized to `(min_x, min_y)` then `(max_x, max_y)` in that +/// boundary frame. Polyline boundaries (`len > 2`) keep their transformed vertex order. +fn filter_geometry(clip: &ClipBoundary, to_world: &Mat3) -> (Mat3, Vec) { + let block_space_rect = clip.points.len() == 2 && (to_world.b.abs() > 1e-9 || to_world.c.abs() > 1e-9); + let boundary_xf = if block_space_rect { Mat3::rotate(-to_world.rotation()) } else { Mat3::IDENTITY }; + let pts_xf = to_world.then(boundary_xf); + let mut points: Vec = clip.points.iter().map(|p| pts_xf.apply(*p)).collect(); + if let [a, b] = points.as_slice() { + points = vec![Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))]; + } + (boundary_xf, points) +} + /// The SPATIAL_FILTER of `clip`; `xdict` is its extension dictionary (an inverted clip's). /// No group 290: the reference app discards a file whose filter has one. fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3, inverse: &Mat3, xdict: Option) -> ForeignObject { @@ -326,14 +376,14 @@ fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3 tags.extend([raw(102, "{ACAD_XDICTIONARY"), raw(360, x.hex()), raw(102, "}")]); } tags.extend([raw(330, owner.hex()), raw(100, "AcDbFilter"), raw(100, "AcDbSpatialFilter"), raw(70, clip.points.len())]); - for p in &clip.points { - let q = to_world.apply(*p); + let (boundary_xf, points) = filter_geometry(clip, to_world); + for q in points { tags.push(raw(10, q.x)); tags.push(raw(20, q.y)); } tags.extend([raw(210, 0.0), raw(220, 0.0), raw(230, 1.0), raw(11, 0.0), raw(21, 0.0), raw(31, 0.0)]); tags.extend([raw(71, i32::from(clip.enabled)), raw(72, 0), raw(73, 0)]); - for v in matrix_values(inverse).into_iter().chain(matrix_values(&Mat3::IDENTITY)) { + for v in matrix_values(inverse).into_iter().chain(matrix_values(&boundary_xf)) { tags.push(raw(40, v)); } ForeignObject { handle: h, kind: "SPATIAL_FILTER".into(), tags } @@ -417,7 +467,7 @@ pub(crate) fn prepare(d: &Drawing) -> Option { let mut own = dictionary(x, sf); own.tags.extend([raw(3, ROUNDTRIP_KEY), raw(360, r.hex())]); add(own); - let world: Vec = clip.points.iter().map(|p| to_world.apply(*p)).collect(); + let (_, world) = filter_geometry(&clip, &to_world); add(roundtrip_record(r, x, &world)); } } @@ -548,4 +598,228 @@ mod tests { assert!(parse_filter(&filter, None).is_none(), "{count}"); } } + + /// Builds a mock SPATIAL_FILTER [`ForeignObject`] with a 10×10 rectangle boundary: + /// (0,0), (10,0), (10,10), (0,10). + fn make_test_filter(inverse: &Mat3, own: &Mat3) -> ForeignObject { + let mut tags = vec![ + raw(100, "AcDbFilter"), + raw(100, "AcDbSpatialFilter"), + raw(70, 4), + raw(10, 0.0), + raw(20, 0.0), + raw(10, 10.0), + raw(20, 0.0), + raw(10, 10.0), + raw(20, 10.0), + raw(10, 0.0), + raw(20, 10.0), + raw(210, 0.0), + raw(220, 0.0), + raw(230, 1.0), + raw(71, 1), + raw(72, 0), + raw(73, 0), + ]; + for v in matrix_values(inverse).into_iter().chain(matrix_values(own)) { + tags.push(raw(40, v)); + } + ForeignObject { handle: Handle(0x100), kind: "SPATIAL_FILTER".into(), tags } + } + + /// Baseline check: verifies `parse_filter` accepts filters where the boundary matrix is identity. + #[test] + fn parse_filter_accepts_identity_boundary_transform() { + // Baseline: parse_filter accepts filters where the second matrix is Identity. + let filter = make_test_filter(&Mat3::IDENTITY, &Mat3::IDENTITY); + let parsed = parse_filter(&filter, None); + assert!(parsed.is_some(), "Baseline filter with identity own matrix must be accepted"); + } + + /// Regression test: verifies `parse_filter` preserves filters with a non-identity translation matrix. + #[test] + fn parse_filter_preserves_non_identity_boundary_transform() { + // WHY: + // SPATIAL_FILTER can contain two transformation matrices. + // parse_filter previously rejected every non-identity `own` matrix, + // causing an otherwise valid clipping definition to be discarded. + // + // Matrix 2 transforms WCS into boundary coordinates; its inverse transforms + // boundary coordinates into WCS, mapping (0..10, 0..10) shifted by (-100, -50). + + let inverse = Mat3::IDENTITY; + let own = Mat3::translate(Vec2::new(100.0, 50.0)); + + let filter = make_test_filter(&inverse, &own); + let parsed = parse_filter(&filter, None); + + assert!(parsed.is_some(), "A valid non-identity boundary transform must not cause the filter to be discarded"); + let clip = parsed.unwrap(); + assert_eq!(clip.points.len(), 4); + assert!(clip.points[0].near(Vec2::new(-100.0, -50.0), 1e-9)); + assert!(clip.points[1].near(Vec2::new(-90.0, -50.0), 1e-9)); + assert!(clip.points[2].near(Vec2::new(-90.0, -40.0), 1e-9)); + assert!(clip.points[3].near(Vec2::new(-100.0, -40.0), 1e-9)); + } + + /// Verifies `boundary_xf.inverse()?.then(inverse)` correctly composes rotation, scaling, and translation. + #[test] + fn parse_filter_applies_rotation_and_scale_boundary_transform() { + let boundary_xf = Mat3::scale(2.0, 2.0).then(Mat3::rotate(std::f64::consts::FRAC_PI_2)).then(Mat3::translate(Vec2::new(50.0, 20.0))); + let inverse = Mat3::translate(Vec2::new(-10.0, -5.0)); + + let filter = make_test_filter(&inverse, &boundary_xf); + let parsed = parse_filter(&filter, None); + + assert!(parsed.is_some(), "Combined scale, rotation, and translation boundary transform must be parsed"); + let clip = parsed.unwrap(); + assert_eq!(clip.points.len(), 4); + assert!(clip.points[0].near(Vec2::new(-20.0, 20.0), 1e-9)); + assert!(clip.points[1].near(Vec2::new(-20.0, 15.0), 1e-9)); + assert!(clip.points[2].near(Vec2::new(-15.0, 15.0), 1e-9)); + assert!(clip.points[3].near(Vec2::new(-15.0, 20.0), 1e-9)); + } + /// Verifies `parse_filter` rejects sheared boundary matrices to preserve foreign data. + #[test] + fn parse_filter_rejects_sheared_boundary_transform() { + let inverse = Mat3::IDENTITY; + // Non-orthogonal shear matrix: (x' = x + 0.5y, y' = y) + let shear = Mat3 { a: 1.0, b: 0.0, c: 0.5, d: 1.0, e: 0.0, f: 0.0 }; + let filter = make_test_filter(&inverse, &shear); + assert!(parse_filter(&filter, None).is_none(), "Sheared transforms must be rejected to stay foreign"); + } + + /// Verifies that an explicit boundary slice (e.g. inverted clip) is transformed correctly. + #[test] + fn parse_filter_applies_transform_to_inverted_boundary() { + let inverse = Mat3::translate(Vec2::new(-10.0, 0.0)); + let boundary_xf = Mat3::translate(Vec2::new(50.0, 0.0)); + let filter = make_test_filter(&inverse, &boundary_xf); + + let explicit_boundary = vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0)]; + let parsed = parse_filter(&filter, Some(&explicit_boundary)); + assert!(parsed.is_some()); + let clip = parsed.unwrap(); + assert!(clip.inverted); + // Explicit boundary points transformed by net: (x - 50 - 10) = x - 60 + assert_eq!(clip.points.len(), 3); + assert!(clip.points[0].near(Vec2::new(-60.0, 0.0), 1e-9)); + assert!(clip.points[1].near(Vec2::new(-50.0, 0.0), 1e-9)); + assert!(clip.points[2].near(Vec2::new(-50.0, 10.0), 1e-9)); + } + /// Verifies that small-scale sheared transforms are rejected by the scale-independent guard. + #[test] + fn parse_filter_rejects_small_scale_sheared_boundary_transform() { + // WHY: + // A sheared transform with tiny scale factors (e.g. u = (0.001, 0), v = (0.0005, 0.001)) + // yields a small absolute dot product (5e-7), which would bypass a naive absolute tolerance. + // The orthogonality guard is scale-independent (|u . v| > 1e-4 * |u| * |v|) so that + // non-orthogonal shears are consistently rejected across all coordinate scales. + let inverse = Mat3::IDENTITY; + let small_shear = Mat3 { a: 0.001, b: 0.0, c: 0.0005, d: 0.001, e: 0.0, f: 0.0 }; + let filter = make_test_filter(&inverse, &small_shear); + assert!(parse_filter(&filter, None).is_none(), "Small-scale sheared transform must be rejected"); + } + + /// Verifies that a 2-corner rectangle rotated by 30°, 45°, 60°, or 90° (whether via + /// `boundary_xf` or via `inverse` with an unrotated/translated `boundary_xf`) expands + /// to an exact 4-corner orthogonal rectangle in block coordinates without collapsing or skewing. + #[test] + fn parse_filter_expands_rotated_two_corner_boundary() { + for deg in [30.0_f64, 45.0, 60.0, 90.0] { + let rot = Mat3::rotate(deg.to_radians()); + let trans = Mat3::translate(Vec2::new(15.0, -10.0)); + for (inverse, boundary_xf) in [(Mat3::IDENTITY, rot), (rot, Mat3::IDENTITY), (rot, trans)] { + let mut tags = vec![ + raw(100, "AcDbFilter"), + raw(100, "AcDbSpatialFilter"), + raw(70, 2), + raw(10, 0.0), + raw(20, 0.0), + raw(10, 10.0), + raw(20, 20.0), + raw(210, 0.0), + raw(220, 0.0), + raw(230, 1.0), + raw(71, 1), + raw(72, 0), + raw(73, 0), + ]; + for v in matrix_values(&inverse).into_iter().chain(matrix_values(&boundary_xf)) { + tags.push(raw(40, v)); + } + let filter = ForeignObject { handle: Handle(0x102), kind: "SPATIAL_FILTER".into(), tags }; + let clip = parse_filter(&filter, None).expect("rotated 2-corner clip must not collapse"); + assert_eq!(clip.points.len(), 4, "angle {deg}°"); + let e01 = clip.points[1] - clip.points[0]; + let e12 = clip.points[2] - clip.points[1]; + assert!((e01.len() - 10.0).abs() < 1e-9, "width preserved at {deg}°"); + assert!((e12.len() - 20.0).abs() < 1e-9, "height preserved at {deg}°"); + assert!(e01.dot(e12).abs() < 1e-9, "right angle preserved at {deg}°"); + } + } + } + + #[test] + fn spatial_filter_canonicalizes_mirrored_two_point_corners_in_boundary_space() { + let clip = ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]); + for (sx, sy, rot) in [(-2.0, 3.0, 0.0), (2.0, -3.0, 0.0), (-2.0, -3.0, 0.0), (-2.0, 3.0, 0.3)] { + let to_world = Mat3::translate(Vec2::new(10.0, 20.0)).then_before(Mat3::rotate(rot)).then_before(Mat3::scale(sx, sy)); + let inverse = to_world.inverse().unwrap(); + let sf = spatial_filter(Handle(0x10), Handle(0x1), &clip, &to_world, &inverse, None); + let verts = vertices(&sf.tags, 2).unwrap(); + assert_eq!(verts.len(), 2); + assert!(verts[0].x < verts[1].x && verts[0].y < verts[1].y, "expected lower-left < upper-right for ({sx},{sy},{rot}): {verts:?}"); + } + + // Polyline boundaries (> 2 vertices) must preserve their transformed vertex order. + let poly = ClipBoundary::new(vec![Vec2::new(3.0, 2.5), Vec2::new(-1.0, 2.5), Vec2::new(1.0, -1.0)]); + let to_world = Mat3::scale(-2.0, 3.0); + let (_, pts) = filter_geometry(&poly, &to_world); + assert_eq!(pts, vec![Vec2::new(-6.0, 7.5), Vec2::new(2.0, 7.5), Vec2::new(-2.0, -3.0)]); + } + + #[test] + fn prepare_canonicalizes_inverted_mirrored_companion_record() { + let mut d = Drawing::new_metric(); + d.blocks.insert("B".into(), Arc::new(cadcraft_doc::Block::new("B"))); + let clip = ClipBoundary { inverted: true, ..ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]) }; + let ins = cadcraft_doc::Insert { + block: "B".into(), + insert: cadcraft_geom::Vec3::new(10.0, 20.0, 0.0), + scale: cadcraft_geom::Vec3::new(-2.0, 3.0, 1.0), + rotation: 0.3, + clip: Some(clip), + ..Default::default() + }; + d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + + let out = prepare(&d).unwrap(); + let sf = out.foreign.objects.iter().find(|o| o.kind == "SPATIAL_FILTER").unwrap(); + let sf_verts = vertices(&sf.tags, 2).unwrap(); + assert!(sf_verts[0].x < sf_verts[1].x && sf_verts[0].y < sf_verts[1].y); + + let xr = out.foreign.objects.iter().find(|o| o.kind == "XRECORD").unwrap(); + let xrec_list = |marker: &str| -> Vec { + let start = xr.tags.iter().position(|t| t.code == 102 && t.value == marker).unwrap() + 1; + let end = xr.tags[start..].iter().position(|t| t.code == 102).map_or(xr.tags.len(), |n| start + n); + let mut pts = Vec::new(); + let mut x = None; + for t in &xr.tags[start..end] { + if t.code == 10 { + x = t.value.parse::().ok(); + } else if t.code == 20 + && let (Some(px), Ok(py)) = (x.take(), t.value.parse::()) + { + pts.push(Vec2::new(px, py)); + } + } + pts + }; + let rt = xrec_list(ROUNDTRIP); + let cmp = xrec_list(COMPARE); + assert_eq!((rt.len(), cmp.len()), (2, 2)); + assert!(rt[0].near(sf_verts[0], 1e-9) && rt[1].near(sf_verts[1], 1e-9)); + assert!(cmp[0].near(sf_verts[0], 1e-9) && cmp[1].near(sf_verts[1], 1e-9)); + } } diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index b97d61405..d441dfd30 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -38,6 +38,16 @@ pub(crate) const MLEADER_STYLE_KEY: &str = "CADCRAFT_MLEADERSTYLE"; /// Named-object-dictionary key of the XRECORD holding model space's current UCS name ($UCSNAME, /// which the DWG bridge drops). pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME"; +/// Header-value key of the `*Active` VPORT records' group 72 ("Circle sides" in the DXF +/// Reference, VPORT), kept as the file has it so that a save writes it back. CADCraft gives it no +/// meaning of its own, and a drawing that stores none is written without it. +pub(crate) const VPORT_CIRCLE_SIDES_KEY: &str = "CADCRAFT_VPORT_CIRCLE_SIDES"; + +/// `v` when a VPORT group 72 can hold it: a 16-bit integer, the type of groups 60-79 (DXF +/// Reference, Group Code Value Types). +pub(crate) fn circle_sides(v: i64) -> Option { + i16::try_from(v).ok().map(i64::from) +} /// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding): /// only then is the current UCS still that named one, read or written. The origin may differ by @@ -101,6 +111,40 @@ impl<'a> UcsNames<'a> { } } +/// The entries of a list (a table's records, a drawing's styles), by name with its ASCII letters +/// lower-cased, each name at the position of its first entry. A later record of a name replaces +/// the first, which keeps its place and takes the later record's name. Each record or lookup is +/// then a map lookup, not a scan of the list: a file of N records, or of N objects each naming one +/// of N styles, cost N² name comparisons (#1924). Ordered by name rather than hashed, so its cost +/// does not depend on hash keys. +#[derive(Default)] +pub(crate) struct ByName(std::collections::BTreeMap); + +impl ByName { + /// The entries the list starts with; the first of a name is the one kept. + pub(crate) fn new(list: &[T], name: impl Fn(&T) -> &str) -> Self { + ByName(list.iter().enumerate().rev().map(|(i, t)| (name(t).to_ascii_lowercase(), i)).collect()) + } + + /// Put `item`, named `name`, in place of the first entry of that name, else at the end. + pub(crate) fn put(&mut self, list: &mut Vec, name: &str, item: T) { + let key = name.to_ascii_lowercase(); + match self.0.get(&key).and_then(|&i| list.get_mut(i)) { + Some(x) => *x = item, + None => { + self.0.insert(key, list.len()); + list.push(item); + } + } + } + + /// The position of the first entry named `name` (ignoring ASCII case), while the list has + /// changed only through [`ByName::put`] since [`ByName::new`]. + pub(crate) fn position(&self, name: &str) -> Option { + self.0.get(&name.to_ascii_lowercase()).copied() + } +} + /// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative /// to their lengths, so short but square axes are fine). Read and written by the same rule. pub(crate) fn usable_axes(x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool { @@ -657,6 +701,41 @@ pub(crate) fn read_layer_colors(tags: &[Tag]) -> Vec<(String, Color)> { names.as_chunks::<2>().0.iter().filter_map(|[name, color]| Some((name.clone(), Color::parse(color)?))).collect() } +/// A viewport's named and base UCS as CADCraft xdata: `1000 VPUCS`, `1002 {`, `1000 named`, +/// `1000 base` (empty for none), `1002 }`. Groups 345 and 346 say the same, but the DWG bridge +/// drops them. +pub(crate) fn ucs_xdata(named: Option<&str>, base: Option<&str>) -> Vec { + vec![Tag::s(1000, "VPUCS"), Tag::s(1002, "{"), Tag::s(1000, named.unwrap_or_default()), Tag::s(1000, base.unwrap_or_default()), Tag::s(1002, "}")] +} + +/// The named and base UCS written by [`ucs_xdata`]; `(None, None)` for files from other writers. +pub(crate) fn read_ucs_names(tags: &[Tag]) -> (Option, Option) { + let list = xdata_list(xdata(tags, APP), "VPUCS"); + let mut names = list.iter().filter(|t| t.code == 1000).map(Tag::str).map(|s| Some(s).filter(|s| !s.trim().is_empty())); + (names.next().flatten(), names.next().flatten()) +} + +/// A copy of a viewport's unmodelled groups ([`cadcraft_doc::Viewport::extra`]) that aren't +/// references, as CADCraft xdata: `1000 VPEXTRA`, `1002 {`, then per group `1000 code` and +/// `1000 value`, `1002 }`. The groups themselves are in the record; the DWG bridge drops some +/// of them (the plot style sheet, shade plot and lighting), and this copy brings them back. +pub(crate) fn extra_xdata(extra: &[cadcraft_doc::RawTag]) -> Vec { + let mut v = vec![Tag::s(1000, "VPEXTRA"), Tag::s(1002, "{")]; + for t in extra.iter().filter(|t| !crate::dxf_raw::is_pointer(t.code)) { + v.push(Tag::s(1000, t.code.to_string())); + v.push(Tag::s(1000, t.value.clone())); + } + v.push(Tag::s(1002, "}")); + v +} + +/// The groups written by [`extra_xdata`]; empty for files from other writers, bad pairs skipped. +pub(crate) fn read_extra(tags: &[Tag]) -> Vec<(i32, String)> { + let list = xdata_list(xdata(tags, APP), "VPEXTRA"); + let items: Vec = list.iter().take(MAX_XDATA_ITEMS * 2).filter(|t| t.code == 1000).map(Tag::str).collect(); + items.as_chunks::<2>().0.iter().filter_map(|[code, value]| Some((code.trim().parse::().ok()?, value.clone()))).collect() +} + const POINT_NAMES: [&str; 5] = ["defpt", "p13", "p14", "p15", "p16"]; /// Associativity links from CADCraft xdata; malformed links are skipped. @@ -870,8 +949,9 @@ struct AnnoObject { const MAX_ANNO_OBJECTS: usize = 1_000_000; /// JSON chunks for the annotative scaling XRECORD, or `None` when nothing differs from a new -/// drawing (1:1, ANNOALLVISIBLE 1, no annotative objects or blocks). -pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing) -> Option> { +/// drawing (1:1, ANNOALLVISIBLE 1, no annotative objects or blocks). With `contexts` the objects +/// written with AutoCAD's annotation scale contexts (`dxf_anno`) are left to them. +pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option> { let cannoscale = d.header.str("CANNOSCALE", "1:1"); let annoallvisible = d.header.i64("ANNOALLVISIBLE", 1); let blocks: Vec = d.blocks.values().filter(|b| b.annotative).map(|b| b.name.clone()).collect(); @@ -879,7 +959,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing) -> Option> { .model .iter() .chain(d.layouts.iter().flat_map(|l| l.entities.iter())) - .filter(|e| cadcraft_doc::is_annotative(e)) + .filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e))) .map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() }) .collect(); if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() { diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index 1f8e6fbe5..52a5be370 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -310,6 +310,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { line_spacing: pos(p.line_spacing).unwrap_or(1.0), line_spacing_exact: p.line_spacing_style == Some(2), columns: None, + background: None, } }); let block = has_block.then(|| { @@ -453,9 +454,12 @@ fn attribs(d: &Drawing, ins: &Insert, values: &[(String, String)]) -> Vec { /// MLEADERSTYLE handle. pub style: String, + /// The drawing's style of the multileader's style name (the first of that name, ignoring + /// case), when it has one. + pub style_def: Option<&'a MLeaderStyle>, /// STYLE record handle of the text. pub text_style: Option, /// BLOCK_RECORD handle of the content block. @@ -463,7 +467,7 @@ pub(crate) struct Refs { } /// The groups of a MULTILEADER record after its `AcDbMLeader` marker. -pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec { +pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs<'_>) -> Vec { let mut t: Vec = Vec::new(); let s = |t: &mut Vec, c: i32, v: &str| t.push(Tag::s(c, v)); let f = |t: &mut Vec, c: i32, v: f64| t.push(Tag::f(c, v)); @@ -473,7 +477,7 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec { t.push(Tag::f(c + 10, v.y)); t.push(Tag::f(c + 20, v.z)); }; - let style = d.mleader_styles.iter().find(|x| x.name.eq_ignore_ascii_case(&m.style)).cloned().unwrap_or_default(); + let style = r.style_def.cloned().unwrap_or_default(); // Block content wins over text when an entity has both (DXF has one content type). let block = m.block.as_ref().zip(r.block.as_ref()); let text = if block.is_some() { None } else { m.text.as_ref() }; diff --git a/crates/io/src/dxf_mline.rs b/crates/io/src/dxf_mline.rs index 099b9da9d..c2c87a958 100644 --- a/crates/io/src/dxf_mline.rs +++ b/crates/io/src/dxf_mline.rs @@ -286,7 +286,9 @@ fn read_style(tags: &[Tag]) -> Option { let mut fill = Color::ByLayer; for t in body { match t.code { - 2 => st.name = t.str(), + // Trimmed, as the writer writes it and as multilines look it up: a padded name kept + // as read was missed by its multilines' lookup, so a save wrote a second style of it. + 2 => st.name = t.str().trim().to_string(), 3 => st.description = t.str(), 70 => flags = t.i64(), 51 => st.start_caps.angle = t.f64().to_radians(), @@ -345,11 +347,11 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) { } }); } + // A later style of a name replaces the first. + let mut names = crate::dxf_ext::ByName::new(&d.mline_styles, |s| &s.name); for st in styles { - match d.mline_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&st.name)) { - Some(x) => *x = st, - None => d.mline_styles.push(st), - } + let name = st.name.clone(); + names.put(&mut d.mline_styles, &name, st); } let by_name: HashMap = d.mline_styles.iter().map(|s| (key(&s.name), s.clone())).collect(); fill(&mut d.model, &by_name); @@ -384,12 +386,14 @@ pub(crate) struct Plan { pub dict: String, /// Each style and its MLINESTYLE handle. styles: Vec<(MLineStyle, String)>, + /// The positions of the styles by name. + names: crate::dxf_ext::ByName, } impl Plan { /// The MLINESTYLE handle of style `name` (STANDARD's when it is missing). pub fn handle(&self, name: &str) -> String { - let find = |n: &str| self.styles.iter().find(|(s, _)| s.name.eq_ignore_ascii_case(n.trim())).map(|(_, h)| h.clone()); + let find = |n: &str| self.names.position(n.trim()).and_then(|i| self.styles.get(i)).map(|(_, h)| h.clone()); find(name).or_else(|| find(STANDARD_MLINE_STYLE)).unwrap_or_else(|| "0".into()) } } @@ -400,15 +404,18 @@ pub(crate) fn plan<'a>(d: &Drawing, every: impl Iterator, mut if !list.iter().any(|s| s.name.eq_ignore_ascii_case(STANDARD_MLINE_STYLE)) { list.insert(0, MLineStyle::default()); } + let mut names = crate::dxf_ext::ByName::new(&list, |s| &s.name); for e in every { if let EntityKind::MLine(m) = &e.kind - && !list.iter().any(|s| s.name.eq_ignore_ascii_case(m.style.trim())) + && names.position(m.style.trim()).is_none() { - list.push(MLineStyle { name: m.style.trim().to_string(), ..m.def.clone() }); + names.put(&mut list, m.style.trim(), MLineStyle { name: m.style.trim().to_string(), ..m.def.clone() }); } } let dict = new_handle(); - Plan { dict, styles: list.into_iter().filter(|s| !s.name.trim().is_empty()).map(|s| (s, new_handle())).collect() } + let styles: Vec<(MLineStyle, String)> = list.into_iter().filter(|s| !s.name.trim().is_empty()).map(|s| (s, new_handle())).collect(); + let names = crate::dxf_ext::ByName::new(&styles, |(s, _)| &s.name); + Plan { dict, styles, names } } /// The `ACAD_MLINESTYLE` dictionary (owned by the root dictionary `root`) and its styles. diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index a2c22d29d..5a7c14a55 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -42,14 +42,39 @@ const MODELLED_KEYS: &[&str] = &[ /// drawing). const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_LAYERSTATES", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"]; -/// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides -/// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. -const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; +/// The annotation scale contexts of a block reference are kept, though: CADCraft doesn't model a +/// reference's scale at each annotation scale, and without them AutoCAD scales an annotative +/// reference once more by the current annotation scale. They are refreshed from the reference +/// when written ([`block_contexts`]). +const CONTEXTS_KEY: &str = "ACDBCONTEXTDATAMANAGER"; + +/// The handles of the drawing's block references. +fn insert_handles(d: &Drawing) -> HashSet { + all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect() +} + +/// Whether the object `tags` belongs to a block reference (`inserts`) or one of its attributes +/// (an ATTRIB in `ids`): their extension dictionaries keep annotation scale contexts. +fn of_insert(tags: &[Tag], inserts: &HashSet, ids: &HashMap) -> bool { + head(tags).owner.is_some_and(|o| inserts.contains(&o) || ids.get(&o).is_some_and(|k| k.0 == "ATTRIB")) +} + +/// Whether extension dictionary entry `key` is left to CADCraft's model, in the extension +/// dictionary of a block reference (`of_insert`) or of something else. +fn modelled_xdict_key(key: &str, of_insert: bool) -> bool { + let k = up(key); + MODELLED_XDICT_KEYS.contains(&k.as_str()) && !(of_insert && k == CONTEXTS_KEY) +} + +/// Applications whose xdata CADCraft reads and writes itself +/// ([`cadcraft_doc::RESERVED_XDATA_APPS`]). `ACAD` holds dimension overrides (DSTYLE) on +/// dimensions and dimension styles; elsewhere it is kept. +const OWN_APPS: &[&str] = cadcraft_doc::RESERVED_XDATA_APPS; /// Most objects kept from one file. const MAX_OBJECTS: usize = 1_000_000; /// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object). -const MAX_XDATA_GROUPS: usize = 16_384; +const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS; /// Longest ownership chain followed. const MAX_DEPTH: usize = 64; @@ -91,20 +116,20 @@ fn handle(s: &str) -> Option { } /// Group codes whose values are handles of other objects (DXF Reference, group code ranges). -fn is_pointer(code: i32) -> bool { +pub(crate) fn is_pointer(code: i32) -> bool { matches!(code, 320..=369 | 390..=399 | 480..=481 | 1005) } /// The records of a run of tags: (type, index of the record's `0` group, groups after it). -fn split(tags: &[Tag]) -> Vec<(String, usize, &[Tag])> { +fn split(tags: &[Tag]) -> Recs<'_> { let mut out = Vec::new(); - let mut open: Option<(String, usize)> = None; + let mut open: Option<(&str, usize)> = None; for (i, t) in tags.iter().enumerate() { if t.code == 0 { if let Some((k, s)) = open.take() { out.push((k, s, tags.get(s + 1..i).unwrap_or(&[]))); } - open = Some((t.str(), i)); + open = Some((t.str_ref().unwrap_or_default(), i)); } } if let Some((k, s)) = open { @@ -113,7 +138,7 @@ fn split(tags: &[Tag]) -> Vec<(String, usize, &[Tag])> { out } -type Recs<'a> = Vec<(String, usize, &'a [Tag])>; +type Recs<'a> = Vec<(&'a str, usize, &'a [Tag])>; /// A record's handle, owner, reactors and extension dictionary (groups before its xdata). #[derive(Default)] @@ -131,23 +156,29 @@ fn head(tags: &[Tag]) -> Head { for t in tags.iter().take_while(|t| t.code < 1000) { match (t.code, group.as_deref()) { (102, _) => { - let v = t.str(); - group = v.trim().strip_prefix('{').map(str::to_string); + group = t.str_ref().and_then(|v| v.trim().strip_prefix('{')).map(str::to_string); h.has_reactors |= group.as_deref() == Some("ACAD_REACTORS"); } - (_, Some("ACAD_REACTORS")) => h.reactors.push(norm(&t.str())), + (_, Some("ACAD_REACTORS")) => h.reactors.extend(t.str_ref().map(norm)), (_, Some("ACAD_XDICTIONARY")) if h.xdict.is_none() => { - h.xdict = Some(norm(&t.str())); + h.xdict = t.str_ref().map(norm); } (_, Some(_)) => {} - (5 | 105, None) if h.handle.is_none() => h.handle = Some(norm(&t.str())), - (330, None) if h.owner.is_none() => h.owner = Some(norm(&t.str())), + (5 | 105, None) if h.handle.is_none() => h.handle = t.str_ref().map(norm), + (330, None) if h.owner.is_none() => h.owner = t.str_ref().map(norm), _ => {} } } h } +/// Whether a record has any `102` group (reactors, an extension dictionary or an application's +/// own group). Without one [`head`] finds no reactors and no extension dictionary, so the scan +/// and its handle text are spared: most entities of a large drawing have none (#1076). +fn has_groups(tags: &[Tag]) -> bool { + tags.iter().take_while(|t| t.code < 1000).any(|t| t.code == 102) +} + fn val(tags: &[Tag], code: i32) -> Option { tags.iter().take_while(|t| t.code < 1000).find(|t| t.code == code).map(Tag::str) } @@ -181,22 +212,27 @@ fn modelled_key(key: &str) -> bool { /// The roles of a file's handles (see [`ForeignKey`]): table records and tables by type and /// name, blocks by name, the named object dictionary, its entries, and their entries. -fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap { +fn identities(tables: &Recs, blocks: &Recs, entities: &Recs, objects: &Recs) -> HashMap { let mut out: HashMap = HashMap::new(); let mut put = |h: Option, k: ForeignKey| { if let Some(h) = h { out.entry(h).or_insert(k); } }; + // Attributes (written with new handles each time) by their reference and tag. + let attribs: Vec<&[Tag]> = blocks.iter().chain(entities).filter(|(k, _, _)| *k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { + put(head(t).handle, ("ATTRIB".into(), key)); + } for (kind, _, t) in tables { let name = up(&val(t, 2).unwrap_or_default()); - if kind == "TABLE" || !name.is_empty() { - put(head(t).handle, (if kind == "TABLE" { "TABLE".into() } else { kind.clone() }, name)); + if *kind == "TABLE" || !name.is_empty() { + put(head(t).handle, (if *kind == "TABLE" { "TABLE".into() } else { kind.to_string() }, name)); } } let mut block = String::new(); for (kind, _, t) in blocks { - match kind.as_str() { + match *kind { "BLOCK" => { block = up(&val(t, 2).unwrap_or_default()); put(head(t).handle, ("BLOCK".into(), block.clone())); @@ -205,9 +241,16 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap {} } } + // Annotation scales by name (written again from the model, maybe under other keys): what + // annotation scale contexts refer to. + for (kind, _, t) in objects.iter().filter(|(k, _, _)| k.eq_ignore_ascii_case("SCALE")) { + if let Some(name) = val(t, 300).filter(|n| !n.trim().is_empty()) { + put(head(t).handle, (kind.to_ascii_uppercase(), up(&name))); + } + } let Some((_, _, root)) = objects.first().filter(|(k, _, _)| is_dictionary(k)) else { return out }; put(head(root).handle, ("NOD".into(), String::new())); - let by_handle: HashMap = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (k.as_str(), *t)))).rev().collect(); + let by_handle: HashMap = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (*k, *t)))).rev().collect(); for (key, h) in entries(root) { put(Some(h.clone()), ("NOD".into(), up(&key))); if let Some((k, t)) = by_handle.get(&h) @@ -232,7 +275,7 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { let len = rest.get(i + 1..).map_or(0, |r| r.iter().position(|t| t.code == 1001).unwrap_or(r.len())); let chunk = rest.get(i..i + 1 + len).unwrap_or(&[]); i += 1 + len; - let app = up(&first.str()); + let app = first.str_ref().map(up).unwrap_or_default(); let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE")); if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS { continue; @@ -240,10 +283,10 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { let mut depth = 0i32; let mut ok = true; for t in chunk.iter().skip(1) { - match (t.code, t.str().trim()) { + match (t.code, t.str_ref().map(str::trim)) { (c, _) if c < 1000 => ok = false, - (1002, "{") => depth += 1, - (1002, "}") => { + (1002, Some("{")) => depth += 1, + (1002, Some("}")) => { depth -= 1; ok &= depth >= 0; } @@ -259,7 +302,7 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { /// The groups of an entity's AcDbEntity subclass (after `100 AcDbEntity`, up to the next `100`). fn entity_groups(tags: &[Tag]) -> &[Tag] { - let Some(start) = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbEntity") else { return &[] }; + let Some(start) = tags.iter().position(|t| t.code == 100 && t.str_ref().is_some_and(|s| s.trim() == "AcDbEntity")) else { return &[] }; let rest = tags.get(start + 1..).unwrap_or(&[]); let end = rest.iter().position(|t| t.code == 100 || t.code >= 1000).unwrap_or(rest.len()); rest.get(..end).unwrap_or(&[]) @@ -268,7 +311,7 @@ fn entity_groups(tags: &[Tag]) -> &[Tag] { /// What an entity record (`entity`) or a table record carries beyond the model; reactors and /// the extension dictionary only when kept (`kept`). fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet) -> ForeignExtra { - let h = head(tags); + let h = if has_groups(tags) { head(tags) } else { Head::default() }; let mut x = ForeignExtra { xdict: h.xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)), reactors: h.reactors.iter().filter(|r| kept.contains(*r)).filter_map(|r| handle(r)).collect(), @@ -328,13 +371,13 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { let (classes, tables, blocks, entities, objects) = (get("CLASSES"), get("TABLES"), get("BLOCKS"), get("ENTITIES"), get("OBJECTS")); // The drawing's entities by handle: whether each is of a type CADCraft doesn't model. let ents = entity_types(d); - let ids = identities(&tables, &blocks, &objects); + let ids = identities(&tables, &blocks, &entities, &objects); // Extension dictionaries of entities and records: owner → dictionary. let xdict_of = extension_dictionaries(&tables, &blocks, &entities); // Objects by handle: the first of each, and none that has an entity's handle. let mut by_handle: HashMap = HashMap::new(); for (i, (_, _, t)) in objects.iter().enumerate() { - if let Some(h) = head(t).handle.filter(|h| handle(h).is_some() && !ents.contains_key(h)) { + if let Some(h) = head(t).handle.filter(|h| handle(h).is_some_and(|hh| !ents.contains_key(&hh))) { by_handle.entry(h).or_insert(i); } } @@ -347,9 +390,12 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { let Some((_, _, t)) = objects.get(k) else { return false }; let hd = head(t); let (Some(h), Some(o)) = (hd.handle, hd.owner) else { return false }; - !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (ents.contains_key(&o) || ids.contains_key(&o)) + !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (handle(&o).is_some_and(|oh| ents.contains_key(&oh)) || ids.contains_key(&o)) }; - let memo = retained_objects(&objects, &ents, &ids, &by_handle, root.as_deref(), &root_entries, &xdict_of); + // Block references and their attributes (their extension dictionaries keep annotation scale + // contexts). + let inserts = insert_handles(d); + let memo = retained_objects(&objects, &ents, &ids, &by_handle, (root.as_deref(), &root_entries), &xdict_of, &inserts); let mut f = Foreign::default(); let mut kept: HashSet = HashSet::new(); for (i, (kind, _, t)) in objects.iter().enumerate() { @@ -359,7 +405,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { let Some(h) = head(t).handle.and_then(|h| handle(&h)) else { continue }; let mut tags: Vec = t.iter().map(raw).collect(); if is_xdict(i) { - strip_entries(&mut tags); + strip_entries(&mut tags, of_insert(t, &inserts, &ids)); } if head(t).owner == root && let Some(key) = root_key(&h.hex()) @@ -367,18 +413,17 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { f.dictionary.push((key, h)); } kept.insert(h.hex()); - f.objects.push(ForeignObject { handle: h, kind: kind.clone(), tags }); + f.objects.push(ForeignObject { handle: h, kind: kind.to_string(), tags }); } // Extras of entities, tables, table records and blocks. let mut xdata_of: HashMap> = HashMap::new(); for (kind, _, t) in blocks.iter().chain(&entities) { - if matches!(kind.as_str(), "BLOCK" | "ENDBLK") { + if matches!(*kind, "BLOCK" | "ENDBLK") { continue; } - let Some(h) = head(t).handle else { continue }; - let Some(&unknown) = ents.get(&h) else { continue }; + let Some(hh) = head(t).handle.as_deref().and_then(handle) else { continue }; + let Some(&unknown) = ents.get(&hh) else { continue }; let mut x = extra(kind, t, true, unknown, &kept); - let Some(hh) = handle(&h) else { continue }; // Xdata belongs to the entity itself (it follows the entity's copies). let xd = std::mem::take(&mut x.xdata); if !xd.is_empty() { @@ -389,13 +434,15 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } } put_xdata(d, xdata_of); - for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { + keep_attrib_dictionaries(&mut f, (&blocks, &entities), &kept); + for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| *k == "BLOCK")) { let Some(key) = head(t).handle.and_then(|h| ids.get(&h).cloned()) else { continue }; - let x = extra(kind, t, kind == "BLOCK", false, &kept); + let x = extra(kind, t, *kind == "BLOCK", false, &kept); if !x.is_empty() { f.records.entry(key).or_insert(x); } } + keep_placements(&mut f, d); // The classes of kept objects and of entities of types CADCraft doesn't model. let mut types: HashSet = f.objects.iter().map(|o| up(&o.kind)).collect(); types.extend(all_entities(d).filter_map(|e| match &e.kind { @@ -405,7 +452,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { // A proxy's class is the one its group 91 numbers in the file's CLASSES: keep it too, and the // file's class order, by which saving renumbers the proxy. let class_order: Vec = - classes.iter().filter(|(k, _, _)| k == "CLASS").take(MAX_OBJECTS).map(|(_, _, t)| up(&val(t, 1).unwrap_or_default())).collect(); + classes.iter().filter(|(k, _, _)| *k == "CLASS").take(MAX_OBJECTS).map(|(_, _, t)| up(&val(t, 1).unwrap_or_default())).collect(); let mut proxies = false; let proxy_tags = f.objects.iter().filter(|o| is_proxy(&o.kind)).map(|o| &o.tags); let proxy_tags = proxy_tags.chain(all_entities(d).filter_map(|e| match &e.kind { @@ -419,11 +466,11 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } } if proxies { - f.complete_class_table = classes.iter().filter(|(k, _, _)| k == "CLASS").count() <= MAX_OBJECTS; + f.complete_class_table = classes.iter().filter(|(k, _, _)| *k == "CLASS").count() <= MAX_OBJECTS; f.class_order = class_order; } for (kind, _, t) in &classes { - if kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS { + if *kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS { f.classes.push(t.iter().map(raw).collect()); } } @@ -439,6 +486,9 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } for e in all_entities(d) { note(&e.common.xdata); + if let EntityKind::Viewport(v) = &e.kind { + note(&v.extra); + } } for e in all_entities(d) { if let EntityKind::Unknown(u) = &e.kind { @@ -459,10 +509,16 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } // Added after the version: registered applications alone are no kept objects whose groups // the DWG writer must read as the file's version, and nearly every file has some (ACAD). - let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string()); + let appids = tables.iter().filter(|(k, _, _)| *k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string()); f.appids = appids.take(MAX_OBJECTS).collect(); // The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`). - f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect(); + f.handles = ids + .iter() + .filter_map(|(h, k)| Some((handle(h)?, k))) + .filter(|(h, _)| !ents.contains_key(h)) + .map(|(h, k)| (h, k.clone())) + .take(MAX_OBJECTS) + .collect(); if !f.is_empty() || !f.handles.is_empty() { d.foreign = Arc::new(f); } @@ -478,22 +534,22 @@ fn file_version(secs: &[SectionRef<'_>]) -> Option { (!value.is_empty()).then(|| value.to_string()) } -fn entity_types(drawing: &Drawing) -> HashMap { +fn entity_types(drawing: &Drawing) -> HashMap { let mut types = HashMap::new(); for entity in all_entities(drawing) { - types.entry(entity.handle.hex()).or_insert(matches!(entity.kind, EntityKind::Unknown(_))); + types.entry(entity.handle).or_insert(matches!(entity.kind, EntityKind::Unknown(_))); } types } fn extension_dictionaries( - tables: &[(String, usize, &[Tag])], - blocks: &[(String, usize, &[Tag])], - entities: &[(String, usize, &[Tag])], + tables: &[(&str, usize, &[Tag])], + blocks: &[(&str, usize, &[Tag])], + entities: &[(&str, usize, &[Tag])], ) -> HashMap { let mut dictionaries = HashMap::new(); for (kind, _, tags) in tables.iter().chain(blocks).chain(entities) { - if kind == "ENDBLK" { + if *kind == "ENDBLK" || !has_groups(tags) { continue; } let header = head(tags); @@ -504,6 +560,39 @@ fn extension_dictionaries( dictionaries } +/// Attributes' extension dictionaries (their annotation scale contexts), by attribute. +fn keep_attrib_dictionaries(f: &mut Foreign, (blocks, entities): (&Recs, &Recs), kept: &HashSet) { + let attribs: Vec<&[Tag]> = blocks.iter().chain(entities).filter(|(k, _, _)| *k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { + if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { + f.records.entry(("ATTRIB".into(), key)).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); + } + } +} + +/// Block references whose extension dictionaries are kept (their annotation scale contexts), as +/// read: where the reference and its attributes were. +fn keep_placements(f: &mut Foreign, d: &Drawing) { + for e in all_entities(d) { + if let EntityKind::Insert(ins) = &e.kind + && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) + { + let attribs = ins + .attribs + .iter() + .map(|a| cadcraft_doc::foreign::KeptAttrib { + tag: a.tag.clone(), + insert: a.text.insert, + align: a.text.align_pt.unwrap_or(a.text.insert), + rotation: a.text.rotation, + }) + .collect(); + f.placements + .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); + } + } +} + /// The root dictionary's key for each entry handle (the first key when several name one handle), /// built once: a lookup per object scanning the entries made a large dictionary quadratic. fn root_key_index(root_entries: &[(String, String)]) -> HashMap<&str, &str> { @@ -516,13 +605,13 @@ fn root_key_index(root_entries: &[(String, String)]) -> HashMap<&str, &str> { /// Determine which objects belong to unmodelled dictionary entries or owners. fn retained_objects( - objects: &[(String, usize, &[Tag])], - entities: &HashMap, + objects: &[(&str, usize, &[Tag])], + entities: &HashMap, records: &HashMap, by_handle: &HashMap, - root: Option<&str>, - root_entries: &[(String, String)], + (root, root_entries): (Option<&str>, &[(String, String)]), xdict_of: &HashMap, + inserts: &HashSet, ) -> HashMap { let root_keys = root_key_index(root_entries); let root_key = |handle: &str| root_keys.get(handle).copied(); @@ -530,10 +619,12 @@ fn retained_objects( let Some((_, _, tags)) = objects.get(index) else { return false }; let header = head(tags); let (Some(handle), Some(owner)) = (header.handle, header.owner) else { return false }; - !by_handle.contains_key(&owner) && xdict_of.get(&owner) == Some(&handle) && (entities.contains_key(&owner) || records.contains_key(&owner)) + !by_handle.contains_key(&owner) + && xdict_of.get(&owner) == Some(&handle) + && (self::handle(&owner).is_some_and(|owner| entities.contains_key(&owner)) || records.contains_key(&owner)) }; let modelled_entry = |tags: &[Tag], handle: &str| { - entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && MODELLED_XDICT_KEYS.contains(&up(key).as_str())) + entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && modelled_xdict_key(key, of_insert(tags, inserts, records))) }; // is_xdict reads the whole record; a dictionary that owns many objects (ACAD_GROUP with // hundreds of thousands of groups) would be read once per child (#862). @@ -576,9 +667,9 @@ fn retained_objects( continue; } if is_xdict(current) { - break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); + break entries(tags).iter().any(|(key, _)| !modelled_xdict_key(key, of_insert(tags, inserts, records))); } - break entities.get(&owner) == Some(&true); + break self::handle(&owner).and_then(|owner| entities.get(&owner)) == Some(&true); }; for visited in path { retained.insert(visited, keep); @@ -786,12 +877,512 @@ fn constraint_nodes(sec: &[Tag]) -> Option> { Some(out) } -/// Drop a dictionary's modelled entries (key and handle) from its groups. -fn strip_entries(tags: &mut Vec) { +/// The identities across saves (an attribute's handle is new each time) of ATTRIB records, in +/// order: the reference's handle, the tag and the attribute's place among the reference's +/// attributes with that tag (a block can have two attributes with one tag; reading and writing +/// keep their order). +fn attrib_keys<'a>(attribs: impl Iterator) -> Vec { + let mut seen: HashMap = HashMap::new(); + attribs + .map(|t| { + let base = format!("{}/{}", head(t).owner.unwrap_or_default(), up(&val(t, 2).unwrap_or_default())); + let n = seen.entry(base.clone()).or_insert(0); + let key = format!("{base}/{n}"); + *n += 1; + key + }) + .collect() +} + +/// An attribute's identity ([`attrib_keys`]) split: its reference, tag and place among the +/// reference's attributes with that tag. +fn split_attrib_key(key: &str) -> Option<(Handle, &str, usize)> { + let (ins, rest) = key.split_once('/')?; + let (tag, nth) = rest.rsplit_once('/')?; + Some((Handle::parse_hex(ins)?, tag, nth.parse().ok()?)) +} + +/// The kept annotation scale contexts of block references, brought up to date with each +/// reference (see [`CONTEXTS_KEY`]). A context holds the reference's insertion point, rotation +/// (degrees) and scale at one annotation scale; the default context (group 290 = 1) was the +/// reference itself when the file was read, so each context moves, turns and scales by what the +/// reference did since. Only the contexts of references that changed are returned (by handle). +fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> HashMap { + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + // The entity a kept object belongs to: the owner past the kept dictionaries. + let owner_entity = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Handle::parse_hex(o), + None => return None, + } + } + None + }; + // The contexts of each reference, together (they share their dictionary). + let mut by_parent: BTreeMap> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")) { + if let Some(p) = owners.get(&o.handle.hex()) { + by_parent.entry(p.clone()).or_default().push(o); + } + } + let mut out = HashMap::new(); + for list in by_parent.values() { + let Some(first) = list.first() else { continue }; + let Some(h) = owner_entity(&first.handle.hex()) else { continue }; + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { continue }; + // The reference as read: kept when it was read, else (data made before that was kept) + // its default context. + let (at0, z0, rot0, scale0) = match f.placements.get(&h) { + Some(p) => (p.insert.xy(), p.insert.z, p.rotation, [p.scale.x, p.scale.y, p.scale.z]), + None => { + let def = list.iter().find(|o| is_default(o)).unwrap_or(first); + let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; + let s = |code: i32, now: f64| num(def, code).unwrap_or(now); + let rot = num(def, 50).unwrap_or(0.0).to_radians(); + ( + cadcraft_doc::geom::Vec2::new(x0, y0), + num(def, 30).unwrap_or(0.0), + rot, + [s(41, ins.scale.x), s(42, ins.scale.y), s(43, ins.scale.z)], + ) + } + }; + let turn = ins.rotation - rot0; + let ratio = |then: f64, now: f64| if then.abs() > 1e-12 { now / then } else { 1.0 }; + let ratios = [(41, ratio(scale0[0], ins.scale.x)), (42, ratio(scale0[1], ins.scale.y)), (43, ratio(scale0[2], ins.scale.z))]; + // A move in elevation alone is a change too. + let unchanged = (ins.insert.xy() - at0).len() < 1e-9 + && (ins.insert.z - z0).abs() < 1e-9 + && turn.abs() < 1e-12 + && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); + if unchanged || !ratios.iter().all(|(_, r)| r.is_finite()) || !turn.is_finite() { + continue; + } + for c in list { + let mut o = (*c).clone(); + // Its offset from where the reference was moves as the reference did: back into the + // reference's frame then, scaled (a mirror flips it), turned to its frame now. + let at = match (num(c, 10), num(c, 20)) { + (Some(x), Some(y)) => { + let off = (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(-rot0); + ins.insert.xy() + cadcraft_doc::geom::Vec2::new(off.x * ratios[0].1, off.y * ratios[1].1).rotate(ins.rotation) + } + _ => ins.insert.xy(), + }; + // Its height above or below the reference as read is kept, scaled with it. + let z = num(c, 30).map_or(ins.insert.z, |cz| ins.insert.z + (cz - z0) * ratios[2].1); + for t in &mut o.tags { + let v = match t.code { + 10 => Some(at.x), + 20 => Some(at.y), + 30 => Some(z), + 50 => num(c, 50).map(|r| r + turn.to_degrees()), + 41..=43 => ratios.iter().find(|(k, _)| *k == t.code).and_then(|(k, r)| num(c, *k).map(|s| s * r)), + _ => None, + }; + if let Some(v) = v.filter(|v| v.is_finite()) { + t.value = v.to_string(); + } + } + out.insert(o.handle.hex(), o); + } + } + out +} + +/// The kept annotation scale contexts of block references' attributes, brought up to date. A +/// context holds the attribute's insertion and alignment points (10, 11) and rotation (50) at one +/// annotation scale. It keeps its own place in the block at that scale (as read, through the +/// reference's context for the same scale), moved by what the attribute did in the block since +/// (seen in its default context, 290 = 1), and is placed by the reference's context as it is now +/// (`block`: the reference contexts [`block_contexts`] refreshed). Only changed contexts are +/// returned (by handle). +fn attribute_contexts( + f: &Foreign, + d: &Drawing, + owners: &HashMap, + block: &HashMap, +) -> HashMap { + use cadcraft_doc::geom::{Mat3, Vec2}; + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + let text = |o: &ForeignObject, code: i32| o.tags.iter().find(|t| t.code == code).map(|t| norm(&t.value)); + // The last kept object up the owner chain (an extension dictionary) and its owner. + let top = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Some((cur, o.clone())), + None => return None, + } + } + None + }; + let attribs = attribute_xdicts(f); + // A reference's context at each scale, as read and as written: (insertion, degrees, scale). + type Place = (Vec2, f64, (f64, f64)); + let place = + |o: &ForeignObject| -> Option { Some((Vec2::new(num(o, 10)?, num(o, 20)?), num(o, 50).unwrap_or(0.0), (num(o, 41)?, num(o, 42)?))) }; + let mut read: HashMap<(Handle, String), Place> = HashMap::new(); + let mut now: HashMap<(Handle, String), Place> = HashMap::new(); + for o in f.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")) { + let (Some((_, r)), Some(s)) = (top(&o.handle.hex()), text(o, 340)) else { continue }; + let Some(r) = Handle::parse_hex(&r) else { continue }; + if let Some(p) = place(o) { + read.insert((r, s.clone()), p); + } + if let Some(p) = place(block.get(&o.handle.hex()).unwrap_or(o)) { + now.insert((r, s), p); + } + } + // The block-to-drawing transform of a reference placed at `p` (its block's base `base`). + let matrix = |ins: &cadcraft_doc::Insert, base: Vec2, p: Place| { + let mut i = ins.clone(); + i.insert = p.0.to3(ins.insert.z); + i.rotation = p.1.to_radians(); + i.scale = cadcraft_doc::geom::Vec3::new(p.2.0, p.2.1, ins.scale.z); + i.transform(base) + }; + // Each attribute's contexts, together. + let mut by_attrib: BTreeMap> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| up(&o.kind).contains("ATTRIBUTEOBJECTCONTEXTDATA")) { + if let Some((xd, _)) = top(&o.handle.hex()) { + by_attrib.entry(xd).or_default().push(o); + } + } + let mut out = HashMap::new(); + for (xd, list) in &by_attrib { + let Some((r, tag, nth)) = attribs.get(xd) else { continue }; + let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; + let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; + let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); + let Some(to_block_now) = ins.transform(base).inverse() else { continue }; + let Some(def) = list.iter().find(|o| is_default(o)).or(list.first()) else { continue }; + let at = |o: &ForeignObject, x: i32| Some(Vec2::new(num(o, x)?, num(o, x + 10)?)); + // What the attribute did in the block since: its default context then, the attribute now. + let Some(def_place) = text(def, 340).and_then(|s| read.get(&(*r, s))).copied() else { continue }; + let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; + let now_ins = to_block_now.apply(a.text.insert.xy()); + let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); + // The attribute as read (the same tag and place among its tag), in its reference as read, + // when that was kept: its points in the block and its rotation from the reference's + // (degrees). Else its default context in the reference's. + let kept = f.placements.get(r).and_then(|p| { + let k = p.attribs.iter().filter(|k| up(&k.tag) == *tag).nth(*nth)?; + let then = matrix(ins, base, (p.insert.xy(), p.rotation.to_degrees(), (p.scale.x, p.scale.y))).inverse()?; + Some((then.apply(k.insert.xy()), then.apply(k.align.xy()), k.rotation.to_degrees() - p.rotation.to_degrees())) + }); + let then = + kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?), num(def, 50).unwrap_or(0.0) - def_place.1))); + let Some((then_ins, then_align, then_turn)) = then else { continue }; + let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - then_turn; + for c in list { + let Some(s) = text(c, 340) else { continue }; + let (Some(was), Some(is)) = (read.get(&(*r, s.clone())).copied(), now.get(&(*r, s)).copied()) else { continue }; + let (Some(from), to): (Option, Mat3) = (matrix(ins, base, was).inverse(), matrix(ins, base, is)) else { continue }; + let moved = |x: i32, delta: Vec2| at(c, x).map(|p| to.apply(from.apply(p) + delta)); + let (new_ins, new_align) = (moved(10, now_ins - then_ins), moved(11, now_align - then_align)); + let rot = num(c, 50).map(|v| v + (is.1 - was.1) + turn); + let mut o = (*c).clone(); + let mut changed = false; + for t in &mut o.tags { + let v = match t.code { + 10 => new_ins.map(|p| p.x), + 20 => new_ins.map(|p| p.y), + 11 => new_align.map(|p| p.x), + 21 => new_align.map(|p| p.y), + 50 => rot, + _ => None, + }; + if let Some(v) = v.filter(|v| v.is_finite()) + && t.value.trim().parse::().map_or(true, |old| (old - v).abs() > 1e-9) + { + t.value = v.to_string(); + changed = true; + } + } + if changed { + out.insert(o.handle.hex(), o); + } + } + } + out +} + +/// Whether a kept context is its object's default one: its first 290 group (of +/// AcDbObjectContextData) is 1. An attribute context has a later 290 group of its own. +fn is_default(o: &ForeignObject) -> bool { + o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1") +} + +fn is_blkref_context(kind: &str) -> bool { + kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") +} + +fn is_attribute_context(kind: &str) -> bool { + up(kind).contains("ATTRIBUTEOBJECTCONTEXTDATA") +} + +/// Attributes' kept extension dictionaries: (reference, tag, place among the reference's +/// attributes with that tag), by dictionary handle. +fn attribute_xdicts(f: &Foreign) -> HashMap { + f.records + .iter() + .filter(|(k, _)| k.0 == "ATTRIB") + .filter_map(|(k, x)| { + let (ins, tag, nth) = split_attrib_key(&k.1)?; + Some((x.xdict?.hex(), (ins, tag.to_string(), nth))) + }) + .collect() +} + +/// The kept contexts of block references and their attributes, in line with the drawing's +/// scales ([`reconcile`]). +#[derive(Default)] +struct Reconciled { + /// Contexts not written: their scale is gone from the drawing's scale list, or their + /// reference is annotative in CADCraft's model and no longer supports it. + dropped: HashSet, + /// New contexts for the scales such a reference supports without a context, with stand-in + /// handles above every handle in use (`above`); their dictionaries list them. + added: Vec, + /// The SCALE objects the added contexts name (group 340): stand-in handle → the scale's role. + scales: HashMap, +} + +/// Bring the kept contexts of block references and their attributes (`contexts`: those already +/// refreshed, by handle) in line with the scales: a context whose SCALE is not written (deleted +/// from the drawing's list) goes. A reference CADCraft's model keeps annotative (it supports +/// scales, [`cadcraft_doc::Common::anno_scales`]) has a context for exactly the scales it +/// supports: one per new scale is made from its default context, scaled by the ratio of the two +/// scales about the reference's insertion point (as AutoCAD adds a scale). One context of each +/// reference stays the default (290 = 1). Changed dictionaries and contexts go into `contexts`. +/// New objects take stand-in handles above `above` and the kept objects' and targets' handles +/// (AutoCAD writes handles above 2^48, so no range is free by itself). +fn reconcile( + f: &Foreign, + d: &Drawing, + owners: &HashMap, + roles: &HashMap, + contexts: &mut HashMap, + above: u64, +) -> Reconciled { + use cadcraft_doc::geom::Vec2; + let mut out = Reconciled::default(); + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + // The written scale a context names (upper case), if its SCALE is written. + let scale_of = |o: &ForeignObject| -> Option { + let v = o.tags.iter().find(|t| t.code == 340)?; + let k = f.targets.get(&handle(&norm(&v.value))?)?; + (k.0 == "SCALE" && roles.contains_key(k)).then(|| k.1.clone()) + }; + let set_default = |o: &mut ForeignObject, on: bool| { + if let Some(t) = o.tags.iter_mut().find(|t| t.code == 290) { + t.value = if on { "1" } else { "0" }.into(); + } + }; + // The last kept object up the owner chain (an extension dictionary) and its owner. + let top = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Some((cur, o.clone())), + None => return None, + } + } + None + }; + let attribs = attribute_xdicts(f); + // The contexts (as refreshed) by their dictionary, with the reference they belong to and + // whether they are an attribute's. + let mut groups: BTreeMap)> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| is_blkref_context(&o.kind) || is_attribute_context(&o.kind)) { + let h = o.handle.hex(); + let (Some(parent), Some((xd, owner))) = (owners.get(&h), top(&h)) else { continue }; + let attribute = is_attribute_context(&o.kind); + let reference = if attribute { attribs.get(&xd).map(|a| a.0) } else { Handle::parse_hex(&owner) }; + let Some(reference) = reference else { continue }; + groups.entry(parent.clone()).or_insert((reference, attribute, Vec::new())).2.push(contexts.get(&h).unwrap_or(o).clone()); + } + let mut next = f.objects.iter().map(|o| o.handle.0).chain(f.targets.keys().map(|h| h.0)).fold(above, u64::max); + let mut fresh = || { + next = next.saturating_add(1); + format!("{next:X}") + }; + // Each reference's template for new contexts: (scale, insertion point) of its default + // context, else of its first, among those whose scale is still written. + let mut ref_default: HashMap = HashMap::new(); + for (r, attribute, list) in groups.values() { + let written: Vec<&ForeignObject> = list.iter().filter(|o| scale_of(o).is_some()).collect(); + if let (false, Some(def)) = (attribute, written.iter().find(|o| is_default(o)).or(written.first())) + && let (Some(s), Some(x), Some(y)) = (scale_of(def), num(def, 10), num(def, 20)) + { + ref_default.insert(*r, (s, Vec2::new(x, y))); + } + } + let current = up(&d.current_anno_scale().name); + for (dict, (r, attribute, list)) in &groups { + let e = d.entity(*r).filter(|e| matches!(e.kind, EntityKind::Insert(_)) && cadcraft_doc::is_annotative(e)); + // The scales the reference supports, when CADCraft's model says (each written once). + let mut wanted: Vec = Vec::new(); + for s in e.map(|e| e.common.anno_scales.as_slice()).unwrap_or_default() { + let n = up(&s.name); + if s.is_valid() && roles.contains_key(&("SCALE".to_string(), n.clone())) && !wanted.contains(&n) { + wanted.push(n); + } + } + let mut have: Vec<(String, ForeignObject)> = Vec::new(); + for c in list { + match scale_of(c) { + Some(s) if e.is_none() || (wanted.contains(&s) && !have.iter().any(|(x, _)| *x == s)) => have.push((s, c.clone())), + _ => { + out.dropped.insert(c.handle.hex()); + } + } + } + // New contexts, from the context at the reference's default scale. + let mut added: Vec<(String, ForeignObject)> = Vec::new(); + if let Some(e) = e + && let Some((def_scale, at)) = ref_default.get(r) + && let Some(template) = list.iter().find(|c| scale_of(c).as_ref() == Some(def_scale)) + { + let factor = |name: &str| { + d.scales + .iter() + .chain(&e.common.anno_scales) + .find(|s| up(&s.name) == name) + .map(cadcraft_doc::AnnoScale::factor) + .filter(|f| f.is_finite() && *f > 0.0) + }; + for s in wanted.iter().filter(|s| !have.iter().any(|(x, _)| x == *s)) { + let (Some(to), Some(from)) = (factor(s), factor(def_scale)) else { continue }; + let k = to / from; + let (h, scale) = (fresh(), fresh()); + let mut o = template.clone(); + o.handle = Handle::parse_hex(&h).unwrap_or(o.handle); + for t in &mut o.tags { + let v = t.value.trim().parse::().ok().filter(|v| v.is_finite()); + let new = match (t.code, v) { + (5, _) => Some(h.clone()), + (340, _) => Some(scale.clone()), + (41..=43, Some(v)) if !attribute => Some((v * k).to_string()), + // An attribute's points scale about the reference's insertion point. + (10 | 11, Some(v)) if *attribute => Some((at.x + (v - at.x) * k).to_string()), + (20 | 21, Some(v)) if *attribute => Some((at.y + (v - at.y) * k).to_string()), + _ => None, + }; + if let Some(new) = new { + t.value = new; + } + } + set_default(&mut o, false); + out.scales.insert(scale, ("SCALE".into(), s.clone())); + added.push((s.clone(), o)); + } + } + // One default: the one kept, else the current scale's, else the first. + if !have.iter().chain(&added).any(|(_, o)| is_default(o)) { + let pick = have.iter().chain(&added).position(|(s, _)| *s == current).unwrap_or(0); + if let Some((_, o)) = have.get_mut(pick) { + set_default(o, true); + contexts.insert(o.handle.hex(), o.clone()); + } else if let Some((_, o)) = added.get_mut(pick.saturating_sub(have.len())) { + set_default(o, true); + } + } + if added.is_empty() { + continue; + } + // The dictionary lists the new contexts (as `*A`, after its own). + let Some(mut dobj) = contexts.get(dict).or_else(|| f.objects.iter().find(|o| o.handle.hex() == *dict)).cloned() else { continue }; + let mut n = dobj + .tags + .iter() + .filter(|t| t.code == 3) + .filter_map(|t| t.value.trim().strip_prefix("*A").and_then(|n| n.parse::().ok())) + .max() + .unwrap_or(0); + let at = dobj.tags.iter().position(|t| t.code >= 1000).unwrap_or(dobj.tags.len()); + let mut entries = Vec::new(); + for (_, o) in &added { + n = n.saturating_add(1); + entries.push(RawTag { code: 3, value: format!("*A{n}") }); + entries.push(RawTag { code: 350, value: o.handle.hex() }); + } + dobj.tags.splice(at..at, entries); + contexts.insert(dict.clone(), dobj); + out.added.extend(added.into_iter().map(|(_, o)| o)); + } + out +} + +/// AutoCAD's current annotation scale, kept with its variable dictionary (the named object +/// dictionary's `AcDbVariableDictionary`, a DICTIONARYVAR `CANNOSCALE` with the scale's name in +/// group 1), brought up to date with the drawing's: AutoCAD opens the drawing at that scale. It +/// names the scale the contexts are written at ([`Drawing::current_anno_scale`]), 1:1 when the +/// drawing's names none of its scales. `None` when the file had none. +fn current_scale(f: &Foreign, d: &Drawing) -> Option<(String, ForeignObject)> { + let vars = f.dictionary.iter().find(|(k, _)| k.trim().eq_ignore_ascii_case("AcDbVariableDictionary"))?.1; + let object = |h: &str| f.objects.iter().find(|o| o.handle.hex() == norm(h)); + let dict = object(&vars.hex())?; + let at = dict.tags.iter().position(|t| t.code == 3 && t.value.trim().eq_ignore_ascii_case("CANNOSCALE"))?; + let var = dict.tags.get(at + 1).filter(|t| matches!(t.code, 350 | 360))?; + let mut o = object(&var.value)?.clone(); + let name = d.current_anno_scale().name; + let value = o.tags.iter_mut().find(|t| t.code == 1)?; + value.value = name; + Some((o.handle.hex(), o)) +} + +/// The kept annotation scale context objects (each `AcDbContextDataManager` an extension +/// dictionary lists, and everything owned below it), by handle: what a DWG save leaves out. The +/// dictionaries that list them drop the entry when the manager isn't written. +fn kept_context_objects(f: &Foreign, own: &HashMap>) -> HashSet { + let mut managers: HashSet = HashSet::new(); + for o in f.objects.iter().filter(|o| is_dictionary(&o.kind)) { + for w in o.tags.windows(2) { + if let [k, v] = w + && k.code == 3 + && up(&k.value) == CONTEXTS_KEY + && matches!(v.code, 350 | 360) + { + managers.insert(norm(&v.value)); + } + } + } + let under = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + if managers.contains(&cur) { + return true; + } + match own.get(&cur).cloned().flatten() { + Some(o) => cur = o, + None => return false, + } + } + false + }; + f.objects.iter().map(|o| o.handle.hex()).filter(|h| under(h)).collect() +} + +/// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: +/// it is a block reference's). +fn strip_entries(tags: &mut Vec, of_insert: bool) { let mut out = Vec::with_capacity(tags.len()); let mut i = 0; while let Some(t) = tags.get(i) { - if t.code == 3 && MODELLED_XDICT_KEYS.contains(&up(&t.value).as_str()) && tags.get(i + 1).is_some_and(|n| matches!(n.code, 350 | 360)) { + if t.code == 3 && modelled_xdict_key(&t.value, of_insert) && tags.get(i + 1).is_some_and(|n| matches!(n.code, 350 | 360)) { i += 2; continue; } @@ -861,6 +1452,53 @@ struct Rec { end: usize, } +/// The written attributes' identities ([`attrib_keys`]), by record start. +fn written_attribs(recs: &[Rec], tags: &[Tag]) -> HashMap { + let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); + let attrib_recs: Vec<&Rec> = recs.iter().filter(|r| matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind == "ATTRIB").collect(); + attrib_recs.iter().map(|r| r.start).zip(attrib_keys(attrib_recs.iter().map(|r| body(r)))).collect() +} + +/// The kept annotation scale contexts of block references and their attributes, up to date with +/// the references and in line with the drawing's scales ([`reconcile`]); the new objects' owners +/// join `owners`. +fn refreshed_contexts( + f: &Foreign, + d: &Drawing, + owners: &mut HashMap, + roles: &HashMap, + tags: &[Tag], +) -> (HashMap, Reconciled) { + let mut contexts = block_contexts(f, d, owners); + let attribute = attribute_contexts(f, d, owners, &contexts); + contexts.extend(attribute); + contexts.extend(current_scale(f, d)); + let rec = reconcile(f, d, owners, roles, &mut contexts, seed(tags).max(max_handle(tags))); + for o in &rec.added { + if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { + owners.insert(o.handle.hex(), norm(&parent.value)); + } + } + (contexts, rec) +} + +/// The kept annotation scale contexts as [`finish`] writes them: brought up to date +/// ([`refreshed_contexts`]), or for the DWG bridge, which doesn't carry them into a DWG yet +/// (storytold/craft-libs#2005), all of them dropped, as before they were kept. +fn contexts_for( + f: &Foreign, + d: &Drawing, + (owners, own): (&mut HashMap, &HashMap>), + roles: &HashMap, + tags: &[Tag], + bridge: bool, +) -> (HashMap, Reconciled) { + if bridge { + return (HashMap::new(), Reconciled { dropped: kept_context_objects(f, own), ..Reconciled::default() }); + } + refreshed_contexts(f, d, owners, roles, tags) +} + fn written_records(tags: &[Tag]) -> Vec { let mut out: Vec = Vec::new(); let mut sec = String::new(); @@ -868,7 +1506,7 @@ fn written_records(tags: &[Tag]) -> Vec { if kind == "SECTION" { sec = body.iter().find(|t| t.code == 2).map(Tag::str).unwrap_or_default(); } - out.push(Rec { sec: sec.clone(), kind, start, end: start + 1 + body.len() }); + out.push(Rec { sec: sec.clone(), kind: kind.to_string(), start, end: start + 1 + body.len() }); if out.last().is_some_and(|r| r.kind == "ENDSEC") { sec.clear(); } @@ -890,16 +1528,17 @@ pub fn object_records(d: &Drawing) -> Vec { let recs = written_records(&tags); let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); let by_sec = |name: &str| -> Recs { - recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect() + recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), r.start, body(r))).collect() }; let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS")); - let ids = identities(&tables, &blocks, &objects); - let tables = tables.iter().filter(|(k, _, _)| k != "ENDTAB"); - let blocks = blocks.iter().filter(|(k, _, _)| k == "BLOCK"); + // Only non-graphic records are listed: no attribute identities are needed. + let ids = identities(&tables, &blocks, &Vec::new(), &objects); + let tables = tables.iter().filter(|(k, _, _)| *k != "ENDTAB"); + let blocks = blocks.iter().filter(|(k, _, _)| *k == "BLOCK"); tables .chain(blocks) .chain(objects.iter()) - .map(|(kind, _, t)| (kind.clone(), t.to_vec(), head(t).handle.and_then(|h| ids.get(&h).cloned()))) + .map(|(kind, _, t)| (kind.to_string(), t.to_vec(), head(t).handle.and_then(|h| ids.get(&h).cloned()))) .collect() } @@ -981,6 +1620,8 @@ struct Map<'a> { roles: HashMap, /// Entities in the written file. entities: HashSet, + /// Stand-in handles of the scales new contexts name ([`Reconciled::scales`]). + scales: &'a HashMap, } impl Map<'_> { @@ -994,6 +1635,9 @@ impl Map<'_> { if self.raw.contains(&v) { return self.alive.get(&v).cloned(); } + if let Some(role) = self.scales.get(&v) { + return self.roles.get(role).cloned(); + } let h = handle(&v)?; if let Some(role) = self.f.targets.get(&h) { return self.roles.get(role).cloned(); @@ -1085,10 +1729,19 @@ impl Map<'_> { } /// The extras of a written record, if the drawing keeps any for it. -fn extra_for<'a>(f: &'a Foreign, xd: &XdataOf, rec: &Rec, body: &[Tag], block: &str) -> Option> { +fn extra_for<'a>( + f: &'a Foreign, + xd: &XdataOf, + attribs: &HashMap, + rec: &Rec, + body: &[Tag], + block: &str, +) -> Option> { match (rec.sec.as_str(), rec.kind.as_str()) { ("BLOCKS", "BLOCK") => f.records.get(&("BLOCK".to_string(), block.to_string())).map(Cow::Borrowed), ("BLOCKS", "ENDBLK") => None, + // An attribute by its reference and tag (its handle is new). + ("ENTITIES" | "BLOCKS", "ATTRIB") => f.records.get(&("ATTRIB".to_string(), attribs.get(&rec.start)?.clone())).map(Cow::Borrowed), ("ENTITIES" | "BLOCKS", _) => entity_extra(f, xd, handle(&head(body).handle?)?), ("TABLES", kind) => { let name = up(&val(body, 2).unwrap_or_default()); @@ -1098,17 +1751,41 @@ fn extra_for<'a>(f: &'a Foreign, xd: &XdataOf, rec: &Rec, body: &[Tag], block: & } } -/// Entities' own xdata ([`cadcraft_doc::Common::xdata`]), by handle. -type XdataOf<'a> = HashMap; +/// What an entity carries itself (so its copies carry it too), by handle: its xdata +/// ([`cadcraft_doc::Common::xdata`]) and a viewport's unmodelled groups +/// ([`cadcraft_doc::Viewport::extra`]). +type XdataOf<'a> = HashMap>; -/// The extras of entity `h`: what the drawing keeps for it, with the entity's own xdata. +#[derive(Clone, Copy)] +struct Own<'a> { + xdata: &'a [RawTag], + tail: &'a [RawTag], +} + +/// The [`Own`] data of every entity that carries any. +fn own_data(d: &Drawing) -> XdataOf<'_> { + all_entities(d) + .filter_map(|e| { + let tail: &[RawTag] = match &e.kind { + EntityKind::Viewport(v) => &v.extra, + _ => &[], + }; + (!e.common.xdata.is_empty() || !tail.is_empty()).then_some((e.handle, Own { xdata: &e.common.xdata, tail })) + }) + .collect() +} + +/// The extras of entity `h`: what the drawing keeps for it, with what the entity carries itself. fn entity_extra<'a>(f: &'a Foreign, xd: &XdataOf, h: Handle) -> Option> { let kept = f.entities.get(&h); match xd.get(&h) { None => kept.map(Cow::Borrowed), - Some(xdata) => { + Some(own) => { let mut x = kept.cloned().unwrap_or_default(); - x.xdata = xdata.to_vec(); + if !own.xdata.is_empty() { + x.xdata = own.xdata.to_vec(); + } + x.tail = own.tail.to_vec(); Some(Cow::Owned(x)) } } @@ -1168,21 +1845,22 @@ pub(crate) fn finish( modern: bool, target_modern: bool, strings: bool, + bridge: bool, ) -> HashSet { let f = d.foreign.as_ref(); let unknown = unknown_handles(d); - let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect(); + let xd = own_data(d); if f.is_empty() && unknown.is_empty() && xd.is_empty() { return HashSet::new(); } let recs = written_records(tags); let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); let by_sec = |name: &str| -> Recs { - recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect() + recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), r.start, body(r))).collect() }; - let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS")); + let (tables, blocks, entities, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("ENTITIES"), by_sec("OBJECTS")); let mut roles: HashMap = HashMap::new(); - for (h, k) in identities(&tables, &blocks, &objects) { + for (h, k) in identities(&tables, &blocks, &entities, &objects) { roles.entry(k).or_insert(h); } let mut written: HashSet = recs.iter().filter_map(|r| head(body(r)).handle).collect(); @@ -1223,20 +1901,19 @@ pub(crate) fn finish( let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s); let root_keys: HashSet = objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default(); - let (mut attached, merged) = kept_dictionaries(f, &xd, &recs, tags); + let attribs = written_attribs(&recs, tags); + let (mut attached, merged) = kept_dictionaries(f, &xd, &attribs, &recs, tags); for (_, t) in planned.values().flatten() { let x = head(t.get(1..).unwrap_or(&[])).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h)); attached.extend(x.and_then(|x| x.xdict).map(Handle::hex)); } - // Which kept objects are written: those whose owner chain ends at a written owner. - let objs: HashMap = f.objects.iter().map(|o| (o.handle.hex(), o)).collect(); let dict_entries: HashMap = f.dictionary.iter().map(|(k, h)| (h.hex(), k.as_str())).collect(); let nod = f.targets.iter().filter(|(_, k)| k.0 == "NOD" && k.1.is_empty()).map(|(h, _)| h.hex()).collect::>(); let hard = hard_owners( f.objects.iter().map(|o| (o.handle.hex(), o.tags.iter().take_while(|t| t.code < 1000).filter(|t| t.code == 360).map(|t| t.value.trim()))), ); // Each kept object's own owner (group 330), read one record at a time. - let own: HashMap> = f + let mut own: HashMap> = f .objects .iter() .map(|o| { @@ -1244,6 +1921,16 @@ pub(crate) fn finish( (o.handle.hex(), head(&t).owner) }) .collect(); + // Annotation scale contexts brought up to date follow owner chains by group 330, and give the + // records they add an owner. + let mut owners: HashMap = own.iter().filter_map(|(h, o)| Some((h.clone(), o.clone()?))).collect(); + let (contexts, rec) = contexts_for(f, d, (&mut owners, &own), &roles, tags, bridge); + for o in &rec.added { + own.insert(o.handle.hex(), owners.get(&o.handle.hex()).cloned()); + } + let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect(); + // Which kept objects are written: those whose owner chain ends at a written owner. + let objs: HashMap = all.iter().map(|o| (o.handle.hex(), *o)).collect(); let mut alive_memo = settle(&hard, |kept: &HashMap| { // Keep established live paths available to descendants during this pass as well. let mut alive_memo: HashMap = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect(); @@ -1255,7 +1942,7 @@ pub(crate) fn finish( for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) { alive_memo.insert(o.handle.hex(), false); } - for o in &f.objects { + for o in &all { let mut path: Vec = Vec::new(); let mut cur = o.handle.hex(); let verdict = loop { @@ -1285,6 +1972,7 @@ pub(crate) fn finish( } alive_memo }); + alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), false))); // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop // the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an // active dependency with its group 330 remapped to "0" breaks the associative reactor invariant. @@ -1350,7 +2038,7 @@ pub(crate) fn finish( let placed = planned.values().flatten().filter_map(|(_, t)| head(t.get(1..).unwrap_or(&[])).handle); fresh.used.extend(placed.filter_map(|h| Handle::parse_hex(&h)).map(|h| h.0)); let mut alive: HashMap = HashMap::new(); - for o in f.objects.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) { + for o in all.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) { alive.insert(o.handle.hex(), format!("{:X}", fresh.take())); } // A merged dictionary is not written: what pointed at it points at the written one. @@ -1360,7 +2048,7 @@ pub(crate) fn finish( } } let merged_into: HashMap = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect(); - let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities }; + let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities, scales: &rec.scales }; let mut out: Vec = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::()); let mut block = String::new(); for r in &recs { @@ -1372,7 +2060,8 @@ pub(crate) fn finish( continue; } if r.kind == "ENDSEC" && r.sec == "OBJECTS" { - for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.contains_key(&o.handle.hex())) { + for o in all.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.contains_key(&o.handle.hex())) { + let o = contexts.get(&o.handle.hex()).unwrap_or(*o); let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten(); match number { Some(n) => { @@ -1395,7 +2084,7 @@ pub(crate) fn finish( record(&map, &ur, ub, x.as_deref(), Some(extra), false, &mut out); } out.extend(tags.get(r.start).cloned()); - let x = extra_for(f, &xd, r, b, &block); + let x = extra_for(f, &xd, &attribs, r, b, &block); let joined = joined_into(&merged_into, b); if x.is_none() && Some(r.start) != root && joined.is_none() { out.extend(b.iter().map(|tag| { @@ -1422,7 +2111,13 @@ pub(crate) fn finish( /// Kept extension dictionaries of written records: those that go on a record without its own, /// and those whose entries join the one the writer gave a table (the LAYER table's, holding the /// layer states) as kept dictionary → the written one. -fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> (HashSet, HashMap) { +fn kept_dictionaries( + f: &Foreign, + xd: &XdataOf, + attribs: &HashMap, + recs: &[Rec], + tags: &[Tag], +) -> (HashSet, HashMap) { let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); let mut block = String::new(); let mut attached: HashSet = HashSet::new(); @@ -1431,7 +2126,7 @@ fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> ( if r.kind == "BLOCK" { block = up(&val(body(r), 2).unwrap_or_default()); } - let Some(kept) = extra_for(f, xd, r, body(r), &block).and_then(|x| x.xdict) else { continue }; + let Some(kept) = extra_for(f, xd, attribs, r, body(r), &block).and_then(|x| x.xdict) else { continue }; match head(body(r)).xdict { None => { attached.insert(kept.hex()); @@ -1516,8 +2211,14 @@ fn plan_unknown( }; let br = |name: &str| roles.get(&("BLOCK_RECORD".to_string(), up(name))).cloned(); let first_at = |s: &cadcraft_doc::EntityStore| s.iter().find_map(|e| at.get(&e.handle.hex()).copied()); - // The LAYER table as written: proxy graphics name layers by their index in it (#3094). - let written_layers: Vec = recs.iter().filter(|r| r.sec == "TABLES" && r.kind == "LAYER").filter_map(|r| val(body(r), 2)).collect(); + // The LAYER and LTYPE tables as written: proxy graphics name layers and linetypes by their + // index in them (#3094), linetypes without ByBlock and ByLayer. + let table = |kind: &str| -> Vec { recs.iter().filter(|r| r.sec == "TABLES" && r.kind == kind).filter_map(|r| val(body(r), 2)).collect() }; + let written_layers = table("LAYER"); + let mut written_linetypes = table("LTYPE"); + written_linetypes.retain(|n| !n.eq_ignore_ascii_case("ByBlock") && !n.eq_ignore_ascii_case("ByLayer")); + let read_order = cadcraft_doc::TableOrder { layers: &d.proxy_layers, linetypes: &d.proxy_linetypes }; + let written_order = cadcraft_doc::TableOrder { layers: &written_layers, linetypes: &written_linetypes }; let layouts = d.paper_space_layouts(); // (entities, owner, paper space, end of the space, section) let mut stores: Vec<(&cadcraft_doc::EntityStore, Option, bool, Option, &str)> = Vec::new(); @@ -1545,7 +2246,7 @@ fn plan_unknown( { continue; } - let remapped = u.with_proxy_layers(&d.proxy_layers, &written_layers).map(|tags| Unknown { tags, ..u.clone() }); + let remapped = u.with_proxy_tables(read_order, written_order).map(|tags| Unknown { tags, ..u.clone() }); let t = unknown_entity(remapped.as_ref().unwrap_or(u), e, &owner, paper); if !t.is_empty() { pending.push((sec.to_string(), t)); @@ -1622,6 +2323,7 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti if i == xdata_at && let Some(x) = x { + out.extend(x.tail.iter().map(|p| map.group(p))); xdata(map, x, &own_apps, out); } if t.code == 102 { @@ -1667,6 +2369,7 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti out.extend(x.props.iter().map(|p| map.group(p))); } if xdata_at == b.len() { + out.extend(x.tail.iter().map(|p| map.group(p))); xdata(map, x, &own_apps, out); } } diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index a892f5b35..6d653ba0a 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -7,7 +7,8 @@ use cadcraft_doc::{ Arc, AssocSnap, Attrib, AttribModes, AttribProps, Block, Circle, Common, DashElement, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Ellipse, Entity, EntityKind, Face3d, Gradient, Group, HAlign, HVal, Handle, Hatch, HatchLoop, Helix, HelixConstrain, Insert, Layer, Layout, Leader, Line, Linetype, Lineweight, LwPolyline, MAX_FRAME_CHARS, MLeaderStyle, MText, MultilineAttrib, NamedView, PageSetup, Point, Polyline3d, RawTag, - RayLine, Solid, Table, TableCell, Text, TextStyle, Tolerance, Transparency, Ucs, Unknown, VAlign, Viewport, VportConfig, VportTile, Wipeout, + RayLine, Solid, Table, TableCell, Text, TextStyle, Tolerance, Transparency, Ucs, Unknown, VAlign, Viewport, ViewportUcs, VportConfig, VportTile, + Wipeout, }; use cadcraft_geom::{PolyVertex, Spline, Vec2, Vec3}; use craft_dxf::{Tag, record_slices, section_slices}; @@ -24,8 +25,8 @@ mod tables; mod text; use document::{ - HandlePolicy, apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, - read_objects, setup_layouts, + HandlePolicy, append, apply_sortents, count_skipped, dropped_paper_views, out_of_memory, outside_sections, parse_entities, place_blocks, + place_entities, read_blocks, read_objects, setup_layouts, }; #[cfg(test)] use entities::acad_table; @@ -35,6 +36,15 @@ use tables::{header, tables}; pub(crate) mod mtext_dxf; +/// A block record's properties (see [`Rx::block_props`]). +#[derive(Clone, Copy, Default)] +struct BlockProps { + units: u8, + explodable: bool, + scale_uniformly: bool, + annotative: bool, +} + /// Handle maps and references gathered while reading. #[derive(Default)] struct Rx { @@ -44,8 +54,9 @@ struct Rx { brs: HashMap, /// LTYPE record handle (upper case) → linetype name (DIMLTYPE, DIMLTEX1, DIMLTEX2). ltypes: HashMap, - /// Upper-case block name → (insertion units, explodable) from its BLOCK_RECORD. - block_props: HashMap, + /// Upper-case block name → its BLOCK_RECORD's properties: units (70), explodable (280), + /// scale uniformly (281) and annotative (`AcadAnnotative` xdata). + block_props: HashMap, /// Upper-case names of anonymous `*T` blocks drawn by ACAD_TABLE entities. table_blocks: std::collections::HashSet, /// Upper-case block names used by INSERTs. @@ -65,8 +76,10 @@ struct Rx { /// Layer, linetype and text style names in the order of the file's tables, which proxy /// graphics refer to by index (the drawing's own tables are ordered differently). proxy_tables: cadcraft_doc::ProxyTables, - /// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345). + /// UCS record handle (upper case) → UCS name (VIEWPORT groups 345 and 346). ucss: HashMap, + /// Upper-case UCS name → UCS name, for a viewport that names its UCS in CADCraft's xdata. + ucs_names: HashMap, /// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport /// (PAPERVIEW) the reader dropped. paper_views_dropped: Vec<(Option, bool, Option)>, @@ -78,6 +91,10 @@ struct Rx { linetypes_cut: usize, /// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case). image_defs: HashMap, + /// Tests: refuse room for more than this many entities in one list, to grow it or to move it + /// into the drawing, as an allocator out of memory refuses, so the error paths run without + /// exhausting memory. `None` when reading. + entities_refused_past: Option, } /// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned` @@ -160,7 +177,7 @@ fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) { /// Read a DXF file into a drawing. pub fn read(bytes: &[u8]) -> Result { - read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS) + read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None) } /// A block definition read from BLOCKS: name, base point, description, entities (owner, paper @@ -168,12 +185,13 @@ pub fn read(bytes: &[u8]) -> Result { type BlockDef = (String, Vec3, String, Vec<(Option, bool, Entity)>, i64); /// A layout read from OBJECTS: name, tab order, paper block handle and page setup. -/// A LAYOUT object: name, tab order, block record, page setup and its limits (groups 10/11). -type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>); +/// A LAYOUT object: name, tab order, block record, page setup, its limits (groups 10/11) and +/// its own flags (group 70 after the AcDbLayout marker). +type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>, Option); /// Import DXF sections while sharing one materialized-table-cell budget and one hatch curve-point -/// budget across blocks and entity sections. -fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) -> Result { +/// budget across blocks and entity sections. `entities_refused_past` is for tests (see `Rx`). +fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize, entities_refused_past: Option) -> Result { let tags = craft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?; let secs = section_slices(&tags); if secs.is_empty() { @@ -183,7 +201,8 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) d.layouts.clear(); // A file without $INSUNITS declares no units (#1209); only new drawings take the template's. d.header.set_i64("INSUNITS", 0); - let mut rx = Rx { pstyles: plot_style_names(&secs), curves: hatch::CurvePoints { left: curve_points, cut: 0 }, ..Rx::default() }; + let mut rx = + Rx { pstyles: plot_style_names(&secs), curves: hatch::CurvePoints { left: curve_points, cut: 0 }, entities_refused_past, ..Rx::default() }; let mut blocks: Vec = Vec::new(); let mut layout_objs: Vec = Vec::new(); let mut entities = Vec::new(); @@ -193,12 +212,12 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) // Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also // assigns one to a block entity. This preserves top-level references while letting block // handles be repaired before their deferred fixups are recorded. - let reserved_entity_handles: HashSet = secs - .iter() - .filter(|s| s.name == "ENTITIES") - .flat_map(|s| record_slices(s.tags)) - .filter_map(|(_, tags)| common::T(tags).s(5).and_then(|h| Handle::parse_hex(&h))) - .collect(); + let mut reserved_entity_handles: HashSet = HashSet::new(); + let entity_records = secs.iter().filter(|s| s.name == "ENTITIES").flat_map(|s| record_slices(s.tags)); + for h in entity_records.filter_map(|(_, tags)| tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex)) { + reserved_entity_handles.try_reserve(1).map_err(|_| out_of_memory(reserved_entity_handles.len().saturating_add(1), "entity handles"))?; + reserved_entity_handles.insert(h); + } let mut objs = Objects::default(); // Every handle another program's file already uses is taken before anything gets a new one: // its $HANDSEED can be lower than its handles, and entities made while reading (the faces of @@ -207,7 +226,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) // (#495), so for it only the entity records are reserved. Handles in the reserved band are // reserved for allocation rather than followed (#913): a handle-less entity read before the // section that names one is placed would otherwise be given it and replace the record (#1276). - let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY)); + let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str_ref() == Some(crate::dxf_ext::HANDSEED_KEY))); if ours { // Its table and object records are numbered above its seed and rebuilt on save (#495), // so only its entities are reserved. Reading is section by section: an entity that has @@ -218,7 +237,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) if matches!(kind.as_str(), "BLOCK" | "ENDBLK") { continue; } - if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(t.str().trim())) { + if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex) { d.bump_handseed(h); d.reserve_handle(h); } @@ -227,7 +246,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) for s in &secs { let entity_section = s.name == "BLOCKS" || s.name == "ENTITIES"; for t in s.tags.iter().filter(|t| t.code == 5 || t.code == 105) { - if let Some(h) = Handle::parse_hex(t.str().trim()) { + if let Some(h) = t.str_ref().and_then(Handle::parse_hex) { d.bump_handseed(h); if entity_section { d.reserve_handle(h); @@ -242,20 +261,23 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) match s.name { "HEADER" => header(s.tags, &mut d), "TABLES" => tables(s.tags, &mut d, &mut rx), - "BLOCKS" => { - blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles)) - } + "BLOCKS" => append( + &mut blocks, + read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles)?, + "block definitions", + )?, // A damaged file may split its entities over several ENTITIES sections (#865). "ENTITIES" => { let mut n = 0; - entities.extend(parse_entities( + let list = parse_entities( &record_slices(s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left, &mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true }, - )); + )?; + append(&mut entities, list, "entities")?; count_skipped(&mut skipped, "ENTITIES", n); } "OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs), @@ -269,6 +291,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) // removing or adding layers doesn't move them (#3094). d.proxy_layers.clone_from(&rx.proxy_tables.layers); keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]); + d.proxy_linetypes.clone_from(&rx.proxy_tables.linetypes); // A proxy text takes the first style on its font, so the styles keep the file's order too. let styles: Vec = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect(); keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]); @@ -276,14 +299,17 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) // are numbered above it and rebuilt on save, so following $HANDSEED would drift every save. let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim())); let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx); - place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout); - place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout); + place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout)?; + place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout)?; draw_kept_dimensions_from_their_blocks(&mut d); number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout)); apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); crate::dxf_image::resolve(&secs, &mut d, &rx.image_defs); crate::dxf_mline::resolve(&secs, &mut d); + // Annotation scale contexts, after CADCraft's own record (they are newer when AutoCAD edited + // the file since). + crate::dxf_anno::resolve(&secs, &mut d); // Keep handles unique against the header's seed. let seed = d.header.str("HANDSEED", ""); if let Some(h) = own_seed.or_else(|| Handle::parse_hex(&seed)) { @@ -399,7 +425,7 @@ mod table_budget_tests { let dxf = format!( "0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nTEST\n10\n0\n20\n0\n{table}0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nEOF\n" ); - let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS).unwrap(); + let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None).unwrap(); let block = d.block("TEST").unwrap(); let count = |e: &Entity| match &e.kind { EntityKind::Table(t) => t.cells.iter().map(Vec::len).sum::(), @@ -443,10 +469,10 @@ mod hatch_budget_tests { #[test] fn hatch_curves_stop_at_the_read_budget_and_say_so() { let dxf = format!("0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", spline_hatch(10), spline_hatch(10)); - let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS).unwrap(); + let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None).unwrap(); assert!(full.read_notes.is_empty(), "{:?}", full.read_notes); assert!(hatch_points(&full) > 20_000, "{}", hatch_points(&full)); - let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000).unwrap(); + let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None).unwrap(); // The budget is checked before each edge: the last one sampled may pass it by its own // points (at most about 4,000); every edge after it is its four control points. assert!(hatch_points(&d) <= 1000 + 4001 + 20 * 4, "{}", hatch_points(&d)); @@ -454,3 +480,134 @@ mod hatch_budget_tests { assert!(matches!(d.read_notes.as_slice(), [note] if note.contains("2 hatches")), "{:?}", d.read_notes); } } + +#[cfg(test)] +mod entity_list_tests { + use super::*; + /// Vertices, attributes and SEQEND fold into the record before them, so they reserve no slots. + #[test] + fn follower_records_reserve_no_entity_slots() -> Result<()> { + let rec = |kind: &str, tags: Vec| (kind.to_string(), tags); + let mut recs = vec![rec("POLYLINE", vec![Tag::s(8, "0"), Tag::i(66, 1)])]; + for x in 0..200 { + recs.push(rec("VERTEX", vec![Tag::s(8, "0"), Tag::f(10, f64::from(x)), Tag::f(20, 0.0)])); + } + recs.push(rec("SEQEND", vec![Tag::s(8, "0")])); + recs.push(rec("LINE", vec![Tag::s(8, "0"), Tag::f(11, 1.0)])); + let recs: Vec<(String, &[Tag])> = recs.iter().map(|(kind, tags)| (kind.clone(), tags.as_slice())).collect(); + let mut d = Drawing::new_imperial(); + let (mut rx, mut skipped, mut cells) = (Rx::default(), 0, 100); + let (mut seen, reserved) = (HashSet::new(), HashSet::new()); + let mut hp = HandlePolicy { seen: &mut seen, reserved: &reserved, source_wins: true }; + let out = parse_entities(&recs, &mut d, &mut rx, &mut skipped, &mut cells, &mut hp)?; + assert_eq!(out.len(), 2, "the polyline and the line"); + assert!(out.capacity() < 10, "capacity {}", out.capacity()); + Ok(()) + } + + /// The reservation stops at its cap, and one that can't be had is an error, not an abort. + #[test] + fn entity_list_reservation_is_capped_and_fallible() -> Result<()> { + use document::entity_list; + assert_eq!(entity_list(100, 8)?.capacity(), 8); + assert_eq!(entity_list(5, 8)?.capacity(), 5); + assert_eq!(entity_list(0, 8)?.capacity(), 0); + assert!(matches!(entity_list(usize::MAX / 2, usize::MAX), Err(IoError::Format(m)) if m.contains("out of memory"))); + Ok(()) + } + + /// Past the reservation cap a list grows as entities come, but no further than its records + /// can fill: a last doubling would leave up to half of it spare, memory a drawing near the + /// limit doesn't have. + #[test] + fn a_long_entity_list_ends_within_its_record_count() -> Result<()> { + let n = document::MAX_RESERVED_ENTITIES + 100; + let line = vec![Tag::s(8, "0"), Tag::f(11, 1.0)]; + let recs: Vec<(String, &[Tag])> = (0..n).map(|_| ("LINE".to_string(), line.as_slice())).collect(); + let mut d = Drawing::new_imperial(); + let (mut rx, mut skipped, mut cells) = (Rx::default(), 0, 100); + let (mut seen, reserved) = (HashSet::new(), HashSet::new()); + let mut hp = HandlePolicy { seen: &mut seen, reserved: &reserved, source_wins: true }; + let out = parse_entities(&recs, &mut d, &mut rx, &mut skipped, &mut cells, &mut hp)?; + assert_eq!(out.len(), n); + assert!(out.capacity() <= recs.len(), "room for {} entities from {} records", out.capacity(), recs.len()); + Ok(()) + } + + /// A full list doubles below its record count, stops at the count, and doubles again past it + /// (a mesh's faces); room for many at once is room for all of them. A reservation that can't + /// be had, or one past the test ceiling, is an error rather than an abort. + #[test] + fn entity_room_doubles_up_to_the_record_count() -> Result<()> { + use document::{entity_list, entity_room}; + let (common, kind) = entity("LINE", &[Tag::s(8, "0")]).expect("a line"); + let full = |n: usize| -> Result, bool, Entity)>> { + let mut v = entity_list(n, n)?; + v.extend((1..=n as u64).map(|h| (None, false, Entity { handle: Handle(h), common: common.clone(), kind: kind.clone() }))); + Ok(v) + }; + let room = |n: usize, records: usize, more: usize| -> Result { + let mut v = full(n)?; + entity_room(&mut v, records, more, None)?; + Ok(v.capacity()) + }; + assert!(room(4, 100, 1)? >= 8, "below the count a full list doubles"); + assert_eq!(room(64, 100, 1)?, 100, "and stops at the count"); + assert!(room(100, 100, 1)? >= 200, "past the count it doubles again"); + assert!(room(4, 100, 300)? >= 304, "room for a mesh's faces comes at once"); + let mut v = full(4)?; + entity_room(&mut v, 100, 4, None)?; + let (cap, free) = (v.capacity(), v.capacity() - v.len()); + entity_room(&mut v, 100, free, None)?; + assert_eq!(v.capacity(), cap, "room already there asks for nothing more"); + let mut v = full(1)?; + assert!(matches!(entity_room(&mut v, usize::MAX, usize::MAX / 2, None), Err(IoError::Format(m)) if m.contains("out of memory"))); + let mut v = full(4)?; + assert!(matches!(entity_room(&mut v, 100, 1, Some(7)), Err(IoError::Format(m)) if m.contains("out of memory"))); + entity_room(&mut v, 100, 1, Some(8))?; + Ok(()) + } + + /// A polygon mesh's faces join the list together, so room for all of them is asked for at + /// once: faces past a refused reservation are an error, not grown into by a push. + #[test] + fn a_mesh_asks_room_for_all_its_faces() -> Result<()> { + let rec = |kind: &str, tags: Vec| (kind.to_string(), tags); + let mut recs = vec![rec("POLYLINE", vec![Tag::s(8, "0"), Tag::i(66, 1), Tag::i(70, 16), Tag::i(71, 3), Tag::i(72, 3)])]; + for i in 0..9 { + recs.push(rec( + "VERTEX", + vec![Tag::s(8, "0"), Tag::i(70, 64), Tag::f(10, f64::from(i % 3)), Tag::f(20, f64::from(i / 3)), Tag::f(30, 0.0)], + )); + } + recs.push(rec("SEQEND", vec![Tag::s(8, "0")])); + let recs: Vec<(String, &[Tag])> = recs.iter().map(|(kind, tags)| (kind.clone(), tags.as_slice())).collect(); + let parse = |refused_past| { + let mut d = Drawing::new_imperial(); + let (mut rx, mut skipped, mut cells) = (Rx { entities_refused_past: refused_past, ..Rx::default() }, 0, 100); + let (mut seen, reserved) = (HashSet::new(), HashSet::new()); + let mut hp = HandlePolicy { seen: &mut seen, reserved: &reserved, source_wins: true }; + parse_entities(&recs, &mut d, &mut rx, &mut skipped, &mut cells, &mut hp) + }; + assert_eq!(parse(None)?.len(), 4, "a 3 by 3 mesh has 4 faces"); + assert_eq!(parse(Some(4))?.len(), 4); + assert!(matches!(parse(Some(3)), Err(IoError::Format(m)) if m.contains("out of memory"))); + Ok(()) + } + + /// Each list checks the drawing has room for it before it moves in: ENTITIES, and model + /// space, paper space and other blocks alike. A refused check stops the read with an error. + #[test] + fn each_list_checks_its_room_before_it_moves_into_the_drawing() { + let lines = "0\nLINE\n8\n0\n11\n1\n".repeat(3); + let block = |name: &str| format!("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n{name}\n10\n0\n20\n0\n{lines}0\nENDBLK\n0\nENDSEC\n0\nEOF\n"); + let files = [format!("0\nSECTION\n2\nENTITIES\n{lines}0\nENDSEC\n0\nEOF\n"), block("*Model_Space"), block("*Paper_Space"), block("B")]; + for dxf in &files { + let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past); + let d = open(Some(3)).unwrap(); + let in_layouts: usize = d.layouts.iter().map(|l| l.entities.len()).sum(); + assert_eq!(d.model.len() + in_layouts + d.block("B").map_or(0, |b| b.entities.len()), 3, "{dxf}"); + assert!(matches!(open(Some(2)), Err(IoError::Format(m)) if m.contains("out of memory")), "{dxf}"); + } + } +} diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 3bafa85bc..a00b52a47 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -4,6 +4,7 @@ use super::common::T; use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity, reference_left_tilted}; use super::objects::{MAX_OBJECTS, Objects, page_setup}; use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices}; +use crate::{IoError, Result}; /// Allocate an entity handle that is unique within the DXF, including against handles assigned /// to earlier malformed or generated entities. @@ -45,6 +46,80 @@ pub(super) struct HandlePolicy<'a> { pub source_wins: bool, } +/// Most entities an entity list reserves room for before its records are read. The record count +/// is bounded by the tag limit, but a file of tiny records could still ask for gigabytes (an +/// entry takes several hundred bytes) before any record is admitted. Drawings of up to this many +/// entities are sized in one step; larger ones grow as entities are admitted ([`entity_room`]). +/// At the cap the reservation is about 46 MiB (728 bytes an entry on 64-bit targets). +pub(super) const MAX_RESERVED_ENTITIES: usize = 1 << 16; + +/// The error for memory the allocator refused: the read stops with it, where an ordinary push +/// would abort the process. +pub(super) fn out_of_memory(n: usize, what: &str) -> IoError { + IoError::Format(format!("DXF: out of memory reserving {n} {what}")) +} + +/// An empty entity list with room for `records` entities, or `cap` if that is fewer. A refused +/// reservation is an error rather than an abort. +pub(super) fn entity_list(records: usize, cap: usize) -> Result, bool, Entity)>> { + let mut out = Vec::new(); + let n = records.min(cap); + out.try_reserve_exact(n).map_err(|_| out_of_memory(n, "entities"))?; + Ok(out) +} + +/// Make room for `n` more entities in `out`, a list read from `records` records (followers not +/// counted). A full list doubles, as a push would, but no further than its records can fill, so +/// it ends at about its final length rather than with a last doubling's spare half; only the +/// faces of a polygon mesh take it past that count, and from there it doubles as usual. A +/// reservation the allocator refuses, or one past `refused_past` (set only by tests), is an +/// error rather than an abort. +pub(super) fn entity_room(out: &mut Vec<(Option, bool, Entity)>, records: usize, n: usize, refused_past: Option) -> Result<()> { + let needed = out.len().saturating_add(n); + if needed <= out.capacity() { + return Ok(()); + } + let fill = if records > out.len() { records } else { usize::MAX }; + let target = out.capacity().saturating_mul(2).min(fill).max(needed); + if refused_past.is_some_and(|most| target > most) { + return Err(out_of_memory(target, "entities")); + } + out.try_reserve_exact(target - out.len()).map_err(|_| out_of_memory(target, "entities")) +} + +/// Add the list a section gives to those read before it (a damaged file may repeat a section, +/// #865). The first list is taken as it is, not copied; a later one is added in a fallible +/// reservation. +pub(super) fn append(all: &mut Vec, more: Vec, what: &str) -> Result<()> { + if all.is_empty() { + *all = more; + return Ok(()); + } + all.try_reserve(more.len()).map_err(|_| out_of_memory(all.len().saturating_add(more.len()), what))?; + all.extend(more); + Ok(()) +} + +/// Check, before entities read into a list move into the drawing, that the drawing has room for +/// `n` of them as it keeps them: each in a shared allocation of its own, with a slot in its +/// space's draw order and an entry in that space's handle index. Those allocations are small and +/// can't report failure, and the list holds its copy until the last one is made, so their memory +/// is asked for here in one fallible reservation and given back at once for them to use. It is a +/// check, not a guarantee (the sizes below are estimates), but a drawing whose entities clearly +/// don't fit stops with an error rather than aborting part way through. Past `refused_past` (set +/// only by tests) the room is refused too. +fn room_to_place(n: usize, refused_past: Option) -> Result<()> { + if refused_past.is_some_and(|most| n > most) { + return Err(out_of_memory(n, "entities in the drawing")); + } + // The shared allocation (its two counts and the entity) and about what an allocator adds to + // each allocation, the draw-order slot, and an index entry with the spare room a hash table + // keeps. + const PER_ENTITY: usize = size_of::() + 4 * size_of::() + size_of::>() + 2 * size_of::<(Handle, u32)>(); + let mut probe: Vec = Vec::new(); + probe.try_reserve_exact(n.saturating_mul(PER_ENTITY)).map_err(|_| out_of_memory(n, "entities in the drawing")) +} + pub(super) fn parse_entities( recs: &[(String, &[Tag])], d: &mut Drawing, @@ -52,14 +127,19 @@ pub(super) fn parse_entities( skipped: &mut usize, table_cells_left: &mut usize, hp: &mut HandlePolicy<'_>, -) -> Vec<(Option, bool, Entity)> { - let mut out = Vec::new(); +) -> Result, bool, Entity)>> { + // Every record but a polyline's vertices, a reference's attributes and their SEQEND becomes + // at most one entity (`recs` is already in memory, bounded by the tag limit), so the list is + // sized once rather than moved at every doubling, up to MAX_RESERVED_ENTITIES; past that, and + // for mesh faces past the count, it grows fallibly as entities are admitted (`entity_room`). + let records = recs.iter().filter(|(kind, _)| !matches!(kind.as_str(), "VERTEX" | "ATTRIB" | "SEQEND")).count(); + let mut out = entity_list(records, MAX_RESERVED_ENTITIES)?; let mut i = 0; while let Some((kind, tags)) = recs.get(i) { let t = T(tags); let owner = crate::dxf_ext::owner(tags); let paper = t.i(67) == Some(1); - let handle = t.s(5).and_then(|h| Handle::parse_hex(&h)); + let handle = tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex); if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) { rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone())); } @@ -98,6 +178,11 @@ pub(super) fn parse_entities( _ => {} } if let Some((c, mut k)) = kindent { + // Room for the entity and a mesh's faces, in the list and among the handles seen, + // before either grows: a drawing too large for memory is an error, not an abort. + let n = 1 + extra.len(); + entity_room(&mut out, records, n, rx.entities_refused_past)?; + hp.seen.try_reserve(n).map_err(|_| out_of_memory(hp.seen.len().saturating_add(n), "entity handles"))?; let h = match handle { // A file's handles keep their identity, however high they are (#913, #939). Some(h) => { @@ -110,19 +195,23 @@ pub(super) fn parse_entities( None => fresh_entity_handle(d, hp.seen, hp.reserved), }; entity_extras(kind, tags, h, &mut k, rx); - let more: Vec<_> = extra - .into_iter() - .map(|f| (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, hp.seen, hp.reserved), common: c.clone(), kind: f })) - .collect(); + // The faces go straight into the room reserved for them, after the entity, with fresh + // handles in face order. + let faces = (!extra.is_empty()).then(|| (owner.clone(), c.clone())); out.push((owner, paper, Entity { handle: h, common: c, kind: k })); - out.extend(more); + if let Some((owner, c)) = faces { + for f in extra { + let handle = fresh_entity_handle(d, hp.seen, hp.reserved); + out.push((owner.clone(), paper, Entity { handle, common: c.clone(), kind: f })); + } + } } else if kind == "HATCH" { // Without boundary data. The other records `entity` returns nothing for are read // elsewhere (the writer's paper viewport, the loops of a region). *skipped = skipped.saturating_add(1); } } - out + Ok(out) } /// Read the BLOCKS section: the xref paths of external blocks, then each block's entities. @@ -134,7 +223,7 @@ pub(super) fn read_blocks( skipped: &mut std::collections::BTreeMap, seen_handles: &mut HashSet, reserved_handles: &HashSet, -) -> Vec { +) -> Result> { let recs = record_slices(tags); for (k, tg) in &recs { let t = T(tg); @@ -166,8 +255,9 @@ pub(super) fn read_blocks( &mut n, table_cells_left, &mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false }, - ); + )?; rx.block = None; + blocks.try_reserve(1).map_err(|_| out_of_memory(blocks.len().saturating_add(1), "block definitions"))?; blocks.push((name, base, description, ents, xref)); i = j + 1; } else { @@ -179,22 +269,31 @@ pub(super) fn read_blocks( } } count_skipped(skipped, "BLOCKS", n); - blocks + Ok(blocks) } /// Read the OBJECTS section into `objs`, and each LAYOUT into `layout_objs`. -pub(super) fn read_objects(tags: &[Tag], objs: &mut Objects, layout_objs: &mut Vec) { +pub(super) fn read_objects<'a>(tags: &'a [Tag], objs: &mut Objects<'a>, layout_objs: &mut Vec) { for (k, tg) in record_slices(tags) { objs.add(&k, tg); if k == "LAYOUT" { // Fields after the AcDbLayout marker (AcDbPlotSettings also has a code 1). - let start = tg.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0); + let marker = tg.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout"); + let start = marker.unwrap_or(0); let tail = tg.get(start..).unwrap_or(&[]); let t = T(tail); // LAYOUT has two 330s: owner dict and the block record; take the last. let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default(); let plot = T(tg.get(..start).unwrap_or(&[])); - layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot, tg), limits(&t))); + layout_objs.push(( + t.s(1).unwrap_or_default(), + t.i(71).unwrap_or(0) as u32, + br.to_ascii_uppercase(), + page_setup(&plot, tg), + limits(&t), + // Its own flags only after the marker: without it, the first 70 is the plot flags. + marker.and_then(|_| t.i(70)), + )); } } } @@ -212,12 +311,13 @@ fn limits(t: &T) -> Option<(Vec2, Vec2)> { pub(super) fn setup_layouts(d: &mut Drawing, layout_objs: &mut [LayoutDef], rx: &Rx) -> (HashMap, String) { let mut paper_block_for: HashMap = HashMap::new(); layout_objs.sort_by_key(|l| l.1); - for (name, order, br, page, limits) in layout_objs.iter() { + for (name, order, br, page, limits, flags) in layout_objs.iter() { if name.eq_ignore_ascii_case("Model") { d.model_page = Some(page.clone()); + d.model_layout_flags = *flags; continue; } - d.layouts.push(Layout { page: page.clone(), limits: *limits, ..Layout::new(name, *order) }); + d.layouts.push(Layout { page: page.clone(), limits: *limits, flags: *flags, ..Layout::new(name, *order) }); if let Some(bname) = rx.brs.get(br) { paper_block_for.insert(bname.to_ascii_uppercase(), name.clone()); } @@ -266,12 +366,19 @@ pub(super) fn layout_positions(d: &Drawing) -> std::collections::BTreeMap, rx: &mut Rx, paper_block_for: &HashMap, first_layout: &str) { +pub(super) fn place_blocks( + d: &mut Drawing, + blocks: Vec, + rx: &mut Rx, + paper_block_for: &HashMap, + first_layout: &str, +) -> Result<()> { let mut layers = LayerSet::new(d); let layout_at = layout_positions(d); for (name, base, description, ents, xref) in blocks { let up = name.to_ascii_uppercase(); if up == "*MODEL_SPACE" { + room_to_place(ents.len(), rx.entities_refused_past)?; for (_, _, e) in ents { layers.ensure(d, &e.common.layer); d.model.push(e); @@ -281,6 +388,7 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, if up.starts_with("*PAPER_SPACE") { let lname = paper_block_for.get(&up).map_or(first_layout, String::as_str); if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) { + room_to_place(ents.len(), rx.entities_refused_past)?; for (_, _, e) in ents { l.entities.push(e); } @@ -300,13 +408,14 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, let mut b = Block::new(&name); b.base = base; b.description = description; - if let Some(&(units, explodable)) = rx.block_props.get(&up) { - (b.units, b.explodable) = (units, explodable); + if let Some(p) = rx.block_props.get(&up) { + (b.units, b.explodable, b.scale_uniformly, b.annotative) = (p.units, p.explodable, p.scale_uniformly, p.annotative); } if xref & 4 != 0 { b.xref_path = Some(String::new()); b.xref_overlay = xref & 8 != 0; } else { + room_to_place(ents.len(), rx.entities_refused_past)?; for (_, _, e) in ents { b.entities.push(e); } @@ -319,6 +428,7 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, } d.blocks.insert(name, std::sync::Arc::new(b)); } + Ok(()) } /// The layout an entity record belongs to: paper space when flagged (67=1) or owned by a @@ -336,7 +446,8 @@ pub(super) fn place_entities( rx: &Rx, paper_block_for: &HashMap, first_layout: &str, -) { +) -> Result<()> { + room_to_place(entities.len(), rx.entities_refused_past)?; let mut layers = LayerSet::new(d); let layout_at = layout_positions(d); for (owner, paper, e) in entities { @@ -350,6 +461,7 @@ pub(super) fn place_entities( None => d.model.push(e), } } + Ok(()) } /// Layouts whose generated sheet viewport (PAPERVIEW) the reader dropped: their viewports keep diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 3f2b427ac..c43507007 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -5,10 +5,144 @@ use super::text::{attdef, attrib_modes, attrib_props, flatten_tilted, mtext_from use super::{ Arc, Attrib, Circle, Common, DimKind, Dimension, Ellipse, EntityKind, Face3d, Handle, HashMap, Helix, HelixConstrain, Insert, Leader, Line, LwPolyline, MAX_FRAME_CHARS, Point, PolyVertex, Polyline3d, RawTag, RayLine, Rx, Solid, Spline, Table, TableCell, Tag, Tolerance, Unknown, Vec2, - Vec3, Viewport, Wipeout, record_slices, + Vec3, Viewport, ViewportUcs, Wipeout, record_slices, }; use cadcraft_doc::PolyfaceMesh; +/// VIEWPORT groups that are not kept raw in [`Viewport::extra`]: those read into the model, and +/// the view twist, direction and target (51, 16, 17), which say where the view centre is measured +/// from: carried along while the centre is written in drawing coordinates, they would move the +/// view on the next read. +const VIEWPORT_NOT_EXTRA: &[i32] = &[ + 10, 20, 30, 40, 41, 68, 69, 12, 22, 45, 90, 340, 341, 331, 71, 110, 120, 130, 111, 121, 131, 112, 122, 132, 79, 146, 345, 346, 51, 16, 26, 36, + 17, 27, 37, +]; + +/// The values a viewport nobody set anything on has for the groups below: what the DWG writer +/// (the bridge's) puts in every viewport, and the DXF Reference's defaults. A group at its default +/// is not "extra" data: a default viewport reads back with no extras, a changed one keeps its +/// group. Each entry is a group code with its default; `(x, y)` pairs (13/23 snap base, +/// 14/24 snap spacing, 15/25 grid spacing) are default only together. +const VIEWPORT_DEFAULTS: &[(i32, f64)] = &[ + (13, 0.0), + (23, 0.0), + (14, 10.0), + (24, 10.0), + (15, 10.0), + (25, 10.0), + // Lens length, front and back clip planes, snap angle, circle sides, render mode, major grid. + (42, 50.0), + (43, 0.0), + (44, 0.0), + (50, 0.0), + (72, 1000.0), + (281, 0.0), + (61, 5.0), + // Shade plot mode. + (170, 0.0), +]; + +/// The group that goes with `code` in a coordinate pair (13/23, 14/24, 15/25). +fn pair_of(code: i32) -> Option { + match code { + 13..=15 => Some(code + 10), + 23..=25 => Some(code - 10), + _ => None, + } +} + +/// Is the group `code` of `groups` at its default (see [`VIEWPORT_DEFAULTS`])? A value that +/// doesn't read as a number is not. +fn at_default(groups: &[RawTag], code: i32, value: &str) -> bool { + let is = |c: i32, v: &str| { + VIEWPORT_DEFAULTS.iter().find(|(k, _)| *k == c).is_some_and(|(_, d)| v.trim().parse::().is_ok_and(|x| (x - d).abs() < 1e-9)) + }; + is(code, value) + && match pair_of(code) { + Some(other) => groups.iter().find(|t| t.code == other).is_some_and(|t| is(other, &t.value)), + None => true, + } +} + +/// Most groups kept raw on one viewport (a VIEWPORT record has about forty). +const MAX_VIEWPORT_EXTRA: usize = 512; + +/// The groups of a VIEWPORT's own subclass (after `100 AcDbViewport`, before any xdata). +fn viewport_groups(tags: &[Tag]) -> &[Tag] { + let Some(start) = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbViewport") else { return &[] }; + let rest = tags.get(start + 1..).unwrap_or(&[]); + rest.get(..rest.iter().position(|t| t.code == 100 || t.code >= 1000).unwrap_or(rest.len())).unwrap_or(&[]) +} + +/// A VIEWPORT's own UCS (groups 110–112, 79, 146), if it has one. The named and base UCS (345, +/// 346) are table handles, resolved once the UCS table is known ([`entity_extras`]). +fn viewport_ucs(tags: &[Tag]) -> Option { + let g = viewport_groups(tags); + // Any UCS group, the base UCS handle (346) alone too: a viewport that only names its base + // UCS keeps it. + if !g.iter().any(|t| matches!(t.code, 110 | 111 | 112 | 345 | 346)) { + return None; + } + let t = T(g); + let has = |c: i32| g.iter().any(|t| t.code == c); + let (origin, x_axis, y_axis) = + (t.p(110), if has(111) { t.p(111) } else { Vec3::new(1.0, 0.0, 0.0) }, if has(112) { t.p(112) } else { Vec3::new(0.0, 1.0, 0.0) }); + // Unreadable numbers come through as 0, so a broken axis is one with no length. + let finite = [origin, x_axis, y_axis].iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()); + if !finite || x_axis.len() <= 1e-12 || y_axis.len() <= 1e-12 { + return None; + } + // The World UCS of a viewport that names no UCS and keeps none of its own (UCSVP 0) is what a + // viewport nobody gave a UCS reads as (a DWG writes one for every viewport): no UCS. + let ortho = t.i(79).unwrap_or(0); + let nothing_named = !g.iter().any(|t| matches!(t.code, 345 | 346)) && crate::dxf_ext::read_ucs_names(tags) == (None, None); + let identity = origin.len() <= 1e-12 + && (x_axis - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 + && (y_axis - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12 + && t.f(146).unwrap_or(0.0) == 0.0 + && ortho == 0; + if identity && nothing_named && t.i(71) != Some(1) { + return None; + } + Some(ViewportUcs { + origin, + x_axis, + y_axis, + elevation: t.f(146).filter(|e| e.is_finite()).unwrap_or(0.0), + ortho: t.i(79).and_then(|o| u8::try_from(o).ok()).filter(|o| *o <= 6).unwrap_or(0), + named: None, + base: None, + }) +} + +/// A VIEWPORT's groups CADCraft doesn't model, as read ([`VIEWPORT_NOT_EXTRA`]), plus those of +/// CADCraft's xdata copy that the record lacks (a DWG drops some). +fn viewport_extra(tags: &[Tag]) -> Vec { + // Only groups that can stand inside the AcDbViewport subclass: no record start (0), handle (5, + // 105), subclass (100), group brace (102) or xdata (1000 on), which written back would break + // the record or give it a second handle. + let own_group = |code: i32| (1..1000).contains(&code) && !matches!(code, 5 | 100 | 102 | 105); + // The record's own pointer groups stay: they are remapped with the record. + let mut out: Vec = viewport_groups(tags) + .iter() + .filter(|t| own_group(t.code) && !VIEWPORT_NOT_EXTRA.contains(&t.code)) + .take(MAX_VIEWPORT_EXTRA) + .map(|t| RawTag { code: t.code, value: t.str() }) + .collect(); + for (code, value) in crate::dxf_ext::read_extra(tags) { + if out.len() >= MAX_VIEWPORT_EXTRA { + break; + } + if own_group(code) && !VIEWPORT_NOT_EXTRA.contains(&code) && !crate::dxf_raw::is_pointer(code) && !out.iter().any(|t| t.code == code) { + out.push(RawTag { code, value }); + } + } + let keep: Vec = out.iter().map(|t| !at_default(&out, t.code, &t.value)).collect(); + let mut keep = keep.into_iter(); + out.retain(|_| keep.next().unwrap_or(true)); + out +} + /// Parse one entity record. POLYLINE/INSERT followers are handled by the caller. pub(super) fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> { entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default()) @@ -303,7 +437,9 @@ pub(super) fn entity_with_table_budget( v.p.x = -v.p.x; v.bulge = -v.bulge; } + let ocs_angle = h.angle; h.angle = cadcraft_geom::norm_angle(std::f64::consts::PI - h.angle); + super::hatch::mirror_pattern_lines(&mut h.pattern_lines, h.origin, h.scale, ocs_angle, h.angle); } k } @@ -328,6 +464,9 @@ pub(super) fn entity_with_table_budget( clip: t.s(340).and_then(|h| Handle::parse_hex(&h)).filter(|h| h.0 != 0 && t.i(90).unwrap_or(0) & 65536 != 0), on: t.i(90).unwrap_or(0) & 131072 == 0, twist, + ucs: viewport_ucs(tags), + ucs_per_viewport: t.i(71) == Some(1), + extra: viewport_extra(tags), } }), "WIPEOUT" => { @@ -502,10 +641,10 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option { if in_entity { break; } - in_entity = t.str() == "AcDbEntity"; + in_entity = t.str_ref() == Some("AcDbEntity"); } else if in_entity { match t.code { - 390 => return rx.pstyles.get(&t.str().trim().to_ascii_uppercase()).cloned(), + 390 => return rx.pstyles.get(&t.str_ref().unwrap_or_default().trim().to_ascii_uppercase()).cloned(), 380 => by_block = t.i64() == 1, _ => {} } @@ -582,6 +721,16 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK let named = handles.filter_map(|t| rx.layers.get(&t.str().trim().to_ascii_uppercase())); let mut seen = std::collections::HashSet::new(); v.frozen_layers = named.chain(&v.frozen_layers).filter(|n| seen.insert(n.to_ascii_uppercase())).cloned().collect(); + // The named and base UCS, by name: groups 345 and 346, else CADCraft's xdata (which a + // DWG keeps when they are dropped). A name that isn't in the UCS table: none. + if let Some(u) = &mut v.ucs { + let t = T(viewport_groups(tags)); + let by_handle = |code: i32| t.s(code).and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase()).cloned()); + let (xn, xb) = crate::dxf_ext::read_ucs_names(tags); + let known = |n: Option| n.and_then(|n| rx.ucs_names.get(&n.to_ascii_uppercase()).cloned()); + u.named = by_handle(345).or_else(|| known(xn)); + u.base = by_handle(346).or_else(|| known(xb)); + } } _ => {} } diff --git a/crates/io/src/dxf_read/hatch.rs b/crates/io/src/dxf_read/hatch.rs index c0651572c..193982413 100644 --- a/crates/io/src/dxf_read/hatch.rs +++ b/crates/io/src/dxf_read/hatch.rs @@ -86,7 +86,18 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option Vec { let Some(at) = tags.iter().position(|x| x.code == 78) else { return Vec::new() }; - let scale = if scale.is_finite() && scale > 1e-9 { scale } else { 1.0 }; + let scale = cadcraft_doc::library::effective_hatch_pattern_scale(scale); let angle = if angle.is_finite() { angle } else { 0.0 }; // Raw lines: angle (degrees), base, offset, dashes. let mut raw: Vec<(f64, Vec2, Vec2, Vec)> = Vec::new(); @@ -374,6 +385,30 @@ fn pattern_definition(tags: &[Tag], scale: f64, angle: f64, origin: Vec2) -> Vec .collect() } +/// The pattern lines of a hatch read in a mirrored OCS (extrusion (0,0,-1)) turned into the world +/// frame its boundary was mirrored into: each line as the file drew it (angle, base point and +/// offset at hatch angle `ocs_angle`) is mirrored in x, then kept the library's way for the +/// mirrored hatch angle `world_angle`. Without this, lines at an angle other than the hatch's +/// kept their unmirrored direction and position against a mirrored boundary (issue #3120). +pub(super) fn mirror_pattern_lines(lines: &mut [cadcraft_doc::library::PatternLine], origin: Vec2, scale: f64, ocs_angle: f64, world_angle: f64) { + // The same fallbacks as `pattern_definition` used when it stored the lines. + let scale = if scale.is_finite() && scale > 1e-9 { scale } else { 1.0 }; + let ocs_angle = if ocs_angle.is_finite() { ocs_angle } else { 0.0 }; + let world_angle = if world_angle.is_finite() { world_angle } else { 0.0 }; + let mirror = |v: Vec2| Vec2::new(-v.x, v.y); + for line in lines { + let file_angle = line.angle.to_radians() + ocs_angle; + let base = mirror(origin + Vec2::new(line.origin.0, line.origin.1).rotate(ocs_angle) * scale); + let offset = mirror(Vec2::new(line.delta.0, line.delta.1).rotate(file_angle) * scale); + let angle = std::f64::consts::PI - file_angle; + let local = (base - origin).rotate(-world_angle) * (1.0 / scale); + let delta = offset.rotate(-angle) * (1.0 / scale); + line.angle = (angle - world_angle).to_degrees(); + line.origin = (local.x, local.y); + line.delta = (delta.x, delta.y); + } +} + /// Hatch origin and background colour from `CADCRAFT` xdata: `1000 HATCH`, `1011` origin, /// `1000` background colour name (empty for none). Defaults when absent. fn hatch_xdata(tags: &[Tag]) -> (Vec2, Option) { diff --git a/crates/io/src/dxf_read/objects.rs b/crates/io/src/dxf_read/objects.rs index 7d5706280..a0fc149c4 100644 --- a/crates/io/src/dxf_read/objects.rs +++ b/crates/io/src/dxf_read/objects.rs @@ -2,10 +2,15 @@ use super::common::T; use super::dimassoc::dimassoc; use super::document::sortents_table; use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Ucs, Vec2, Vec3}; +use crate::dxf_ext::ByName; /// Non-graphical objects applied once every entity is placed. +/// +/// The records it keeps until then are slices of the file's tag list, which the reader holds +/// for as long as this lives, not copies of it: a file of large records would otherwise hold +/// their groups twice while it opens (#1922). #[derive(Default)] -pub(super) struct Objects { +pub(super) struct Objects<'a> { /// Dictionary entry handle (upper case) → entry name. names: HashMap, /// (dictionary handle, entry handle), both upper case, in the order the dictionaries list them. @@ -13,17 +18,17 @@ pub(super) struct Objects { /// SCALE objects (the annotation scale list), in file order. scales: Vec, /// XRECORD handle (upper case) → its groups. - xrecords: HashMap>, + xrecords: HashMap, /// XRECORD handles in file order. xrecord_order: Vec, /// TABLESTYLE objects: (handle, groups). - table_styles: Vec<(String, Vec)>, + table_styles: Vec<(String, &'a [Tag])>, /// DIMASSOC objects. - dimassocs: Vec>, + dimassocs: Vec<&'a [Tag]>, /// MLEADERSTYLE objects: (handle, groups). - mleader_styles: Vec<(String, Vec)>, + mleader_styles: Vec<(String, &'a [Tag])>, /// GROUP objects: (handle, groups). - groups: Vec<(String, Vec)>, + groups: Vec<(String, &'a [Tag])>, /// Saved paper-space views of layouts: (layout name, view). layout_views: Vec<(String, (Vec2, f64))>, /// Layouts' current UCSs: (layout name, origin, X axis, Y axis, named UCS record handle). @@ -36,8 +41,8 @@ pub(super) struct Objects { pub(super) const MAX_OBJECTS: usize = 1_000_000; -impl Objects { - pub(super) fn add(&mut self, kind: &str, tags: &[Tag]) { +impl<'a> Objects<'a> { + pub(super) fn add(&mut self, kind: &str, tags: &'a [Tag]) { let h = T(tags).s(5).map(|h| h.trim().to_ascii_uppercase()).unwrap_or_default(); match kind { "SCALE" if self.scales.len() < cadcraft_doc::MAX_SCALES => { @@ -68,14 +73,14 @@ impl Objects { } } "XRECORD" if self.xrecords.len() < MAX_OBJECTS => { - if self.xrecords.insert(h.clone(), tags.to_vec()).is_none() { + if self.xrecords.insert(h.clone(), tags).is_none() { self.xrecord_order.push(h); } } - "TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags.to_vec())), - "DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags.to_vec()), - "MLEADERSTYLE" if self.mleader_styles.len() < MAX_OBJECTS => self.mleader_styles.push((h, tags.to_vec())), - "GROUP" if self.groups.len() < MAX_OBJECTS => self.groups.push((h, tags.to_vec())), + "TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags)), + "DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags), + "MLEADERSTYLE" if self.mleader_styles.len() < MAX_OBJECTS => self.mleader_styles.push((h, tags)), + "GROUP" if self.groups.len() < MAX_OBJECTS => self.groups.push((h, tags)), "WIPEOUTVARIABLES" => self.wipeout_frame = T(tags).i(70).filter(|v| (0..=2).contains(v)), "SORTENTSTABLE" if self.sortents.len() < MAX_OBJECTS => { if let Some(t) = sortents_table(tags) { @@ -127,10 +132,10 @@ impl Objects { let ours = |tags: &[Tag]| owner(tags).is_some_and(|o| dicts.contains(o.as_str())); // By lower-case name: the first entry's name and the last entry's record, in dictionary order. let mut first: HashMap = HashMap::new(); - let mut last: HashMap> = HashMap::new(); + let mut last: HashMap = HashMap::new(); for (dict, h) in &self.entry_order { if dicts.contains(dict.as_str()) - && let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h)) + && let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h).copied()) && ours(tags) { first.entry(name.to_ascii_lowercase()).or_insert(name); @@ -141,7 +146,7 @@ impl Objects { let mut taken = std::collections::HashSet::new(); let mut budget = crate::dxf_layer_states::MAX_COPIED_BYTES; for h in &self.xrecord_order { - let (Some(tags), Some(name)) = (self.xrecords.get(h), self.names.get(h)) else { continue }; + let (Some(tags), Some(name)) = (self.xrecords.get(h).copied(), self.names.get(h)) else { continue }; if out.len() >= crate::dxf_ext::MAX_LAYER_STATES { break; } @@ -218,14 +223,13 @@ impl Objects { } fn apply_table_styles(&self, d: &mut Drawing) { - // Table styles (named by their ACAD_TABLESTYLE dictionary entries). + // Table styles (named by their ACAD_TABLESTYLE dictionary entries); a later style of a + // name replaces the first. + let mut by_name = ByName::new(&d.table_styles, |s| &s.name); for (h, tags) in &self.table_styles { let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue }; let st = crate::dxf_table::read_table_style(name, tags); - match d.table_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(name)) { - Some(x) => *x = st, - None => d.table_styles.push(st), - } + by_name.put(&mut d.table_styles, name, st); } } @@ -236,10 +240,7 @@ impl Objects { // style's, so every cell style height applies as it is. let height = { let style = name.as_deref().unwrap_or("Standard"); - d.table_styles - .iter() - .find(|s| s.name.eq_ignore_ascii_case(style)) - .map_or(cadcraft_doc::TableStyle::default().text_height, |s| s.text_height) + d.table_styles.by_name(style).map_or(cadcraft_doc::TableStyle::default().text_height, |s| s.text_height) }; let _ = d.modify_entity(*h, |e| { if let EntityKind::Table(t) = &mut e.kind { @@ -253,7 +254,9 @@ impl Objects { } fn apply_mleader_styles(&self, d: &mut Drawing, rx: &Rx) { - // Multileader styles (named by their ACAD_MLEADERSTYLE dictionary entries). + // Multileader styles (named by their ACAD_MLEADERSTYLE dictionary entries); a later style + // of a name replaces the first. + let mut by_name = ByName::new(&d.mleader_styles, |s| &s.name); for (h, tags) in &self.mleader_styles { let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue }; let t = T(tags); @@ -269,10 +272,7 @@ impl Objects { text_style: text_style.unwrap_or(def.text_style), annotative: t.i(296).unwrap_or(0) != 0, }; - match d.mleader_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(name)) { - Some(x) => *x = st, - None => d.mleader_styles.push(st), - } + by_name.put(&mut d.mleader_styles, name, st); } } @@ -471,3 +471,61 @@ fn layout_view(tags: &[Tag]) -> Option<(Vec2, f64)> { let g = |c: i32| list.iter().find(|t| t.code == c).map(Tag::f64).filter(|v| v.is_finite()); Some((Vec2::new(g(1010)?, g(1020)?), g(1040)?)) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A file from another writer with one record of each kind [`Objects`] keeps until the drawing + /// is built: a LINE, a linear DIMENSION whose DIMASSOC ties its first point to the line's + /// start, and, named in the root dictionary, CADCraft's current multileader style record (an + /// XRECORD), a table style, a multileader style and a group holding the line. + const DXF: &str = "0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n5\n1F\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\ + 0\nDIMENSION\n5\n2A\n8\n0\n100\nAcDbDimension\n10\n10\n20\n5\n30\n0\n70\n0\n\ + 100\nAcDbAlignedDimension\n13\n0\n23\n0\n33\n0\n14\n10\n24\n0\n34\n0\n100\nAcDbRotatedDimension\n\ + 0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n\ + 3\nCADCRAFT_MLEADERSTYLE\n350\nA1\n3\nMine\n350\nA2\n3\nArrows\n350\nA4\n3\nPair\n350\nA5\n\ + 0\nXRECORD\n5\nA1\n330\nC\n100\nAcDbXrecord\n280\n1\n1\nArrows\n\ + 0\nTABLESTYLE\n5\nA2\n330\nC\n100\nAcDbTableStyle\n3\nmine\n\ + 0\nDIMASSOC\n5\nA3\n330\n0\n100\nAcDbDimAssoc\n330\n2A\n90\n1\n1\nAcDbOsnapPointRef\n72\n13\n331\n1F\n\ + 0\nMLEADERSTYLE\n5\nA4\n330\nC\n100\nAcDbMLeaderStyle\n44\n2.5\n\ + 0\nGROUP\n5\nA5\n330\nC\n100\nAcDbGroup\n300\nnote\n70\n0\n71\n1\n340\n1F\n\ + 0\nENDSEC\n0\nEOF\n"; + + /// The kept records are slices of the file's tag list, not copies of it (#1922): a file of + /// large records would otherwise hold their groups twice while it opens. + #[test] + fn kept_records_are_slices_of_the_tag_list() { + let tags = craft_dxf::parse(DXF.as_bytes()).unwrap(); + let section = craft_dxf::section_slices(&tags).into_iter().find(|s| s.name == "OBJECTS").unwrap(); + let mut objs = Objects::default(); + crate::dxf_read::document::read_objects(section.tags, &mut objs, &mut Vec::new()); + let list = tags.as_ptr_range(); + let kept: [(&str, &[Tag]); 5] = [ + ("XRECORD", objs.xrecords["A1"]), + ("TABLESTYLE", objs.table_styles[0].1), + ("DIMASSOC", objs.dimassocs[0]), + ("MLEADERSTYLE", objs.mleader_styles[0].1), + ("GROUP", objs.groups[0].1), + ]; + for (kind, record) in kept { + assert!(record.first().is_some_and(|t| t.code == 5), "{kind}: the whole record, from its handle"); + assert!(list.contains(&record.as_ptr()), "{kind} is a copy of the tag list"); + } + } + + /// Each kind of kept record still reaches the drawing. + #[test] + fn each_kept_record_kind_reaches_the_drawing() { + let d = crate::dxf_read::read(DXF.as_bytes()).unwrap(); + let line = Handle::parse_hex("1F").unwrap(); + assert_eq!(d.header.str("CMLEADERSTYLE", ""), "Arrows", "XRECORD"); + assert!(d.table_styles.iter().any(|s| s.name == "Mine"), "TABLESTYLE"); + let dim = d.entity(Handle::parse_hex("2A").unwrap()).map(|e| &e.kind); + assert!(matches!(dim, Some(EntityKind::Dimension(dm)) if dm.assoc.iter().any(|a| a.handle == line && a.point == "p13")), "DIMASSOC: {dim:?}"); + assert!(d.mleader_styles.iter().any(|s| s.name == "Arrows" && (s.arrow_size - 2.5).abs() < 1e-9), "MLEADERSTYLE"); + assert!(d.groups.iter().any(|g| g.name == "Pair" && g.description == "note" && g.members == [line]), "GROUP"); + } +} diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 3268f0e15..8c521df66 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -1,9 +1,10 @@ use super::common::T; use super::objects::MAX_OBJECTS; use super::{ - Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, - VportConfig, VportTile, record_slices, + BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, + Vec3, VportConfig, VportTile, record_slices, }; +use crate::dxf_ext::ByName; use cadcraft_fonts::windows::windows_font; use craft_dxf::lin_pat::MAX_LINETYPE_ELEMENTS; @@ -114,10 +115,12 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { // The same for linetypes (first definition wins) and text styles (last definition wins). let mut linetype_names: std::collections::HashSet = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect(); let mut style_index: HashMap = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect(); - // And for dimension styles, views and UCSs (a later record replaces the first of its name). + // And for dimension styles, views and UCSs (a later record replaces the first of its name), + // and viewport configurations (a record adds a tile to the first of its name). let mut dim_style_names = ByName::new(&d.dim_styles, |s| &s.name); let mut view_names = ByName::new(&d.views, |v| &v.name); let mut ucs_names = ByName::new(&d.ucss, |u| &u.name); + let mut vport_names = ByName::new(&d.vports, |c| &c.name); for (kind, tg) in recs { let t = T(tg); match kind.as_str() { @@ -205,7 +208,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { // The first *ACTIVE viewport holds the current snap/grid settings. "VPORT" if !active_vport && t.s(2).is_some_and(|n| n.trim().eq_ignore_ascii_case("*ACTIVE")) => { active_vport = true; - vport_record(d, &t, true); + vport_record(d, &mut vport_names, &t, true); for (name, code) in [("SNAPUNIT", 14), ("GRIDUNIT", 15)] { if let (Some(x), Some(y)) = (t.f(code), t.f(code + 10)) { let p = Vec2::new(x, y); @@ -221,6 +224,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { d.header.set("SNAPBASE", HVal::Point(Vec3::new(x, y, 0.0))); } ucsicon(d, &t); + circle_sides(d, &t); if let Some(a) = t.f(50).filter(|a| a.is_finite()) { d.header.set_f64("SNAPANG", a); } @@ -280,7 +284,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { st.apply_fields(&fields); dim_style_names.put(&mut d.dim_styles, &name, st); } - "VPORT" => vport_record(d, &t, false), + "VPORT" => vport_record(d, &mut vport_names, &t, false), _ => {} } } @@ -290,32 +294,6 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active()) || c.tiles.first().is_some_and(|t| t.twist != 0.0)); } -/// The records of one table read so far, by name with its ASCII letters lower-cased. A later -/// record of a name replaces the first, which keeps its place and takes the later record's name. -/// Each record is then a map lookup, not a scan of the records before it: a file of N records cost -/// N² name comparisons (#1924). Ordered by name rather than hashed, so its cost does not depend on -/// hash keys. -struct ByName(std::collections::BTreeMap); - -impl ByName { - /// The entries the table starts with; the first of a name is the one kept. - fn new(list: &[T], name: impl Fn(&T) -> &str) -> Self { - ByName(list.iter().enumerate().rev().map(|(i, t)| (name(t).to_ascii_lowercase(), i)).collect()) - } - - /// Put `item`, named `name`, in place of the first entry of that name, else at the end. - fn put(&mut self, list: &mut Vec, name: &str, item: T) { - let key = name.to_ascii_lowercase(); - match self.0.get(&key).and_then(|&i| list.get_mut(i)) { - Some(x) => *x = item, - None => { - self.0.insert(key, list.len()); - list.push(item); - } - } - } -} - fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) { for (kind, tags) in recs { let table = T(tags); @@ -339,7 +317,13 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) { } "BLOCK_RECORD" => { let units = table.i(70).and_then(|units| u8::try_from(units).ok()).unwrap_or(0); - rx.block_props.insert(name.to_ascii_uppercase(), (units, table.i(280).unwrap_or(1) != 0)); + let props = BlockProps { + units, + explodable: table.i(280).unwrap_or(1) != 0, + scale_uniformly: table.i(281).unwrap_or(0) != 0, + annotative: annotative(tags), + }; + rx.block_props.insert(name.to_ascii_uppercase(), props); if let Some(array) = crate::dxf_ext::read_array(tags) { rx.block_arrays.insert(name.to_ascii_uppercase(), array); } @@ -356,6 +340,7 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) { rx.layers.insert(handle.trim().to_ascii_uppercase(), name); } "UCS" => { + rx.ucs_names.entry(name.to_ascii_uppercase()).or_insert_with(|| name.clone()); rx.ucss.insert(handle.trim().to_ascii_uppercase(), name); } _ => {} @@ -370,13 +355,22 @@ fn ucsicon(d: &mut Drawing, t: &T) { } } +/// The `*ACTIVE` VPORT's group 72 ("Circle sides"), kept so that a save writes it back +/// ([`crate::dxf_ext::VPORT_CIRCLE_SIDES_KEY`]); one that is not a 16-bit integer is left out. +fn circle_sides(d: &mut Drawing, t: &T) { + if let Some(v) = t.i(72).and_then(crate::dxf_ext::circle_sides) { + d.header.set_i64(crate::dxf_ext::VPORT_CIRCLE_SIDES_KEY, v); + } +} + /// Most tiles a viewport configuration keeps. const MAX_VPORT_TILES: usize = 64; /// A VPORT record: one tile of the configuration it names (`*ACTIVE` the one shown). Corners /// are fractions of the drawing area; unusable tiles are skipped. `first_active`: this is the -/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view. -fn vport_record(d: &mut Drawing, t: &T, first_active: bool) { +/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view. `names`: the +/// configurations read so far by name. +fn vport_record(d: &mut Drawing, names: &mut ByName, t: &T, first_active: bool) { let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default(); // View twist (group 51, degrees). let twist = t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians())); @@ -413,10 +407,13 @@ fn vport_record(d: &mut Drawing, t: &T, first_active: bool) { let tile = VportTile { min: clamp(min), max: clamp(max), center, height, aspect, twist }; let name = if name.eq_ignore_ascii_case(VportConfig::ACTIVE) { VportConfig::ACTIVE.to_string() } else { name }; let room = d.vports.len() < MAX_OBJECTS; - match d.vports.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&name)) { + match names.position(&name).and_then(|i| d.vports.get_mut(i)) { Some(c) if c.tiles.len() < MAX_VPORT_TILES => c.tiles.push(tile), Some(_) => {} - None if room => d.vports.push(VportConfig { name, tiles: vec![tile] }), + None if room => { + let config = VportConfig { name: name.clone(), tiles: vec![tile] }; + names.put(&mut d.vports, &name, config); + } None => {} } } diff --git a/crates/io/src/dxf_read/text.rs b/crates/io/src/dxf_read/text.rs index 84f5273ea..2e5a6d001 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -73,6 +73,16 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText { a => a, }; } + let background = own.i(90).filter(|&m| (m & 0x03) != 0).map(|m| { + let mask = (m & 0x03) as u8; + let color = if let Some(tc) = own.i(421) { + Some(cadcraft_color::Color::True(cadcraft_color::Rgb::from_u32(tc as u32))) + } else { + own.i(63).map(|aci| cadcraft_color::Color::from_aci(aci as i16)) + }; + let scale = own.fd(45, 1.5).clamp(1.0, 5.0); + cadcraft_doc::MTextBackground { mask, color, scale } + }); MText { insert: t.p(10), height: t.fd(40, 0.2).max(1e-9), @@ -89,6 +99,7 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText { line_spacing: t.fd(44, 1.0), line_spacing_exact: t.i(73) == Some(2), columns: columns.map(|(c, _)| c), + background, } } @@ -108,6 +119,10 @@ pub(super) fn text_from(t: &T) -> Text { _ => VAlign::Baseline, }; let align = if t.f(11).is_some() { Some(t.p(11)) } else { None }; + // Text generation flags (AcDbText's 71): 2 backwards, 4 upside down. An attribute's own + // subclass has a 71 of its own (its multiline flag), so only the groups before it count. + let text_groups = t.0.iter().position(|g| g.code == 100 && g.str().trim().starts_with("AcDbAttribute")).and_then(|i| t.0.get(..i)); + let generation = T(text_groups.unwrap_or(t.0)).i(71).unwrap_or(0); let mut text = Text { insert: t.p(10), align_pt: if h == HAlign::Left && v == VAlign::Baseline { None } else { align }, @@ -119,6 +134,8 @@ pub(super) fn text_from(t: &T) -> Text { style: t.s(7).unwrap_or_else(|| "Standard".into()), halign: h, valign: v, + backwards: generation & 2 != 0, + upside_down: generation & 4 != 0, }; let n = Vec3::new(t.fd(210, 0.0), t.fd(220, 0.0), t.fd(230, 1.0)); if n.z < 0.0 { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 9b9ee8107..973d865d4 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -19,6 +19,8 @@ use crate::dxf_ext::{self, DimVal, K}; mod assoc; mod blocks; mod common; +#[cfg(test)] +pub(crate) use common::{attdef_definition_visits, reset_attdef_definition_visits}; mod ctx; mod entity; mod header; @@ -48,7 +50,7 @@ struct W { pstyles: HashMap, /// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports). layers: HashMap, - /// Upper-case UCS name → its UCS table record handle (group 345 of layouts and viewports). + /// Upper-case UCS name → its UCS table record handle (groups 345 and 346 of viewports). ucss: HashMap, /// Active VPORT group-345 tags (their index in `t`) waiting for the handle of the named UCS /// (upper case) they refer to, filled in after the UCS table is written. @@ -56,6 +58,9 @@ struct W { /// Persistent reactors of source geometry: the associative hatches and DIMASSOC objects /// that follow it (groups `{ACAD_REACTORS 330 …}`). reactors: HashMap>, + /// Extension dictionaries of annotative objects (their annotation scale contexts, see + /// [`crate::dxf_anno`]), by object; a dimension's DIMASSOC dictionary is written by its own. + xdicts: HashMap, } /// Where the writer's own records (tables, objects, dictionaries) start numbering: above every @@ -163,6 +168,45 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec, std::collections::Hash (tags, kept) } +/// One record written after an entity's own, at `index`: an INSERT's ATTRIB, then its SEQEND +/// (items of a POLYLINE's sequence are not records `entnext` reaches yet). The record's type name +/// and groups without its `0` group; its handle (5) and owner (330) are left out: it has no +/// handle of its own in the drawing (the writer makes one per file), and its owner is the entity. +/// `None` past the last record, and for an entity written as a single record. AutoLISP's +/// `entnext` and `entget` read one record at a time through it, never writing the entity's other +/// records. +pub fn entity_sub_record(d: &Drawing, e: &Entity, index: usize) -> Option<(String, Vec)> { + let cadcraft_doc::EntityKind::Insert(i) = &e.kind else { return None }; + if i.attribs.is_empty() { + return None; + } + let mut w = W { + t: Vec::new(), + next: d.handseed.max(0x100).saturating_add(0x1000), + used: HashSet::new(), + pstyles: HashMap::new(), + layers: HashMap::new(), + ucss: HashMap::new(), + vport_ucs: Vec::new(), + reactors: HashMap::new(), + xdicts: HashMap::new(), + }; + let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() }; + match i.attribs.get(index) { + Some(a) => { + let base = d.block(&i.block).and_then(|b| common::attdef_base(b, &a.tag)); + entity::attrib_record(&mut w, d, e, index, a, base, &cx); + } + None if index == i.attribs.len() => entity::seqend_record(&mut w, e), + None => return None, + } + let mut tags = w.t.into_iter(); + let kind = tags.next().filter(|t| t.code == 0).map(|t| t.value.as_str())?; + let mut tags: Vec = tags.filter(|t| t.code != 5 && t.code != 330).collect(); + // Strings as AutoLISP sees them (`10^2`, not the file's `10^ 2`), as in `entity_groups`. + crate::dxf_read::mtext_dxf::map_text_groups(&kind, &mut tags, crate::dxf_read::mtext_dxf::decode_line); + Some((kind, tags)) +} /// The most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in /// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256), /// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so). @@ -276,6 +320,7 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec) { ucss: HashMap::new(), vport_ucs: Vec::new(), reactors: HashMap::new(), + xdicts: HashMap::new(), }; let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() }; let paper = d.space_of(e.handle).is_some_and(|s| !matches!(s, cadcraft_doc::Space::Model)); diff --git a/crates/io/src/dxf_write/blocks.rs b/crates/io/src/dxf_write/blocks.rs index 0b48a164c..40c65ee8d 100644 --- a/crates/io/src/dxf_write/blocks.rs +++ b/crates/io/src/dxf_write/blocks.rs @@ -129,21 +129,25 @@ pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Ve for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) { out.extend(line_entities(i, l)); } - if !g.value.is_empty() { + // The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD + // writes it (#1055). + let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone()); + for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) { out.push(Entity { handle: Handle(0), - common: text_c, + common: text_c.clone(), kind: EntityKind::MText(MText { - insert: g.text_pos.to3(0.0), + insert: at.to3(0.0), height: g.text_height, width: 0.0, attach: 5, rotation: g.text_angle, style: style.text_style.clone(), - contents: g.mtext_contents(), + contents: cadcraft_render::DimGeometry::mtext_code(&contents), line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), }); } @@ -198,6 +202,7 @@ pub(crate) fn table_block_entities(d: &Drawing, t: &Table, layer: &str) -> Vec>, + /// Tags held in all, for [`MAX_INDEXED_TAGS`]. + tags: usize, + /// States of definitions with more distinct tags than [`MAX_INDEXED_TAGS`], so a read of one + /// goes straight to [`scan_attdef`] without building and dropping an index again. + too_large: std::collections::HashSet, +} + +thread_local! { + static ATTDEF_INDEXES: RefCell = RefCell::new(AttdefIndexes::default()); + /// Entities of a block definition examined while matching an attribute to its ATTDEF. + #[cfg(test)] + static ATTDEF_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The first ATTDEF of each tag in `block`, by upper-case tag, when there are at most `budget` +/// distinct tags. `None` when another distinct tag would pass `budget`: the partial map is +/// dropped, so a prefix is not stored in place of the definition. +fn attdef_index_within(block: &Block, budget: usize) -> Option> { + let mut by_tag = BTreeMap::new(); + for e in block.entities.iter() { + count_attdef_visit(); + if let EntityKind::AttDef(ad) = &e.kind { + let key = ad.tag.to_ascii_uppercase(); + if by_tag.contains_key(&key) { + continue; + } + if by_tag.len() >= budget { + return None; + } + by_tag.insert(key, e.handle); + } + } + Some(by_tag) +} + +/// The first ATTDEF of `block` whose tag matches `tag`, ignoring ASCII case: one pass over the +/// definition at most, stopping at the match. Nothing from the scan is stored. +fn scan_attdef(block: &Block, tag: &str) -> Option { + for e in block.entities.iter() { + count_attdef_visit(); + if let EntityKind::AttDef(ad) = &e.kind + && ad.tag.eq_ignore_ascii_case(tag) + { + return Some(e.handle); + } + } + None +} + +/// The definition properties of the first ATTDEF in `block` whose tag matches `tag`, ignoring +/// ASCII case. Each state of a block's entities that fits in [`MAX_INDEXED_TAGS`] is read once +/// on a thread: later attributes, of this reference or another, find their definition in its +/// index. A definition with more distinct tags is not stored: the first read of that state builds +/// at most [`MAX_INDEXED_TAGS`] index entries, then gives up and remembers the state; every read +/// of it scans the definition once at most, stopping at the first match. +pub(super) fn attdef_base<'a>(block: &'a Block, tag: &str) -> Option<&'a Common> { + let token = block.entities.content_token(); + let want = tag.to_ascii_uppercase(); + let found = ATTDEF_INDEXES + .try_with(|cell| { + let Ok(mut ix) = cell.try_borrow_mut() else { return scan_attdef(block, tag) }; + if let Some(by_tag) = ix.by_store.get(&token) { + return by_tag.get(&want).copied(); + } + if ix.too_large.contains(&token) { + return scan_attdef(block, tag); + } + let Some(by_tag) = attdef_index_within(block, MAX_INDEXED_TAGS) else { + if ix.too_large.len() >= MAX_TOO_LARGE { + ix.too_large.clear(); + } + ix.too_large.insert(token); + return scan_attdef(block, tag); + }; + let found = by_tag.get(&want).copied(); + let cost = by_tag.len().max(1); + if ix.tags.saturating_add(cost) > MAX_INDEXED_TAGS { + ix.by_store.clear(); + ix.tags = 0; + } + ix.tags = ix.tags.saturating_add(cost); + ix.by_store.insert(token, by_tag); + found + }) + .unwrap_or_else(|_| scan_attdef(block, tag)); + block.entities.get(found?).map(|e| &e.common) +} + +/// One more definition entity examined (counted in tests). +fn count_attdef_visit() { + #[cfg(test)] + ATTDEF_VISITS.with(|n| n.set(n.get().saturating_add(1))); +} + +/// How many definition entities attribute reads have examined on this thread. +#[cfg(test)] +pub(crate) fn attdef_definition_visits() -> u64 { + ATTDEF_VISITS.with(std::cell::Cell::get) +} + +/// Start a definition-visit count from zero. +#[cfg(test)] +pub(crate) fn reset_attdef_definition_visits() { + ATTDEF_VISITS.with(|n| n.set(0)); +} + +/// `AcadAnnotative` xdata marking an annotative style or block. pub(super) fn annotative_xdata(w: &mut W) { w.s(1001, "AcadAnnotative"); w.s(1000, "AnnotativeData"); @@ -25,6 +154,7 @@ pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) { ucss: HashMap::new(), vport_ucs: Vec::new(), reactors: HashMap::new(), + xdicts: HashMap::new(), }; let mut sah = false; for (k, v) in &dm.overrides { @@ -92,8 +222,8 @@ pub(super) fn common_x(w: &mut W, e: &Entity, owner: &str, paper: bool, subclass let rs: Vec<&str> = reactors.iter().map(String::as_str).collect(); w.group("ACAD_REACTORS", 330, &rs); } - if let Some(a) = assoc { - w.group("ACAD_XDICTIONARY", 360, &[&a.xdict]); + if let Some(xd) = assoc.map(|a| a.xdict.clone()).or_else(|| w.xdicts.get(&e.handle).cloned()) { + w.group("ACAD_XDICTIONARY", 360, &[&xd]); } w.s(330, owner); w.s(100, "AcDbEntity"); @@ -145,14 +275,12 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) { } } -/// The properties attribute `a` of block reference `e` is drawn with: its own, else its -/// definition's, from the block's definitions by tag `defs`; an attribute defined on layer 0 is on -/// the reference's layer. Also the definition's properties. -pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap, &Entity>, a: &Attrib) -> (Common, Common) { - let def = defs.get(&cadcraft_doc::TagKey(&a.tag)); - let base = def.map(|de| de.common.clone()).unwrap_or_default(); +/// Attribute `a` takes its own properties over its definition's. A layer 0 inherited from the +/// definition takes the reference's layer; an explicit layer 0 stays. Return both properties. +pub(super) fn attrib_common(e: &Entity, a: &Attrib, base: Option<&Common>) -> (Common, Common) { + let base = base.cloned().unwrap_or_default(); let mut c = a.props.over(&base); - if c.layer == "0" { + if a.props.layer.is_none() && c.layer == "0" { c.layer.clone_from(&e.common.layer); } (c, base) @@ -244,8 +372,9 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 { oblique: t.oblique, h, v, - backwards: ts.backwards, - upside_down: ts.upside_down, + // The text's own flags, as it's drawn and as group 71 says. + backwards: t.backwards, + upside_down: t.upside_down, }; let q = cadcraft_fonts::baseline_start(&cadcraft_fonts::TextFont::resolve(&ts.font), &t.value, &p); // Justification recalculates the baseline in XY; group 10 keeps its own elevation. @@ -338,6 +467,11 @@ pub(super) fn text_tags( w.f(51, t.oblique.to_degrees()); } w.s(7, &t.style); + // Text generation flags: 2 backwards, 4 upside down. + let generation = if t.backwards { 2 } else { 0 } | if t.upside_down { 4 } else { 0 }; + if generation != 0 { + w.i(71, generation); + } let h = match t.halign { HAlign::Left => 0, HAlign::Center => 1, diff --git a/crates/io/src/dxf_write/ctx.rs b/crates/io/src/dxf_write/ctx.rs index dd0b67f2a..1c76cea0a 100644 --- a/crates/io/src/dxf_write/ctx.rs +++ b/crates/io/src/dxf_write/ctx.rs @@ -1,4 +1,5 @@ -use super::{DimVal, Handle, HashMap, K, Vec3, Version, dxf_ext}; +use super::{DimVal, Drawing, Entity, Handle, HashMap, K, MLeader, Tag, Vec3, Version, W, dxf_ext}; +use crate::dxf_ext::ByName; /// The `DIMASSOC` object of an associative dimension (stored in the dimension's extension /// dictionary under `ACAD_DIMASSOC`). @@ -44,8 +45,14 @@ pub(super) struct Ctx { pub(super) tables: HashMap, /// Table style name → TABLESTYLE handle (the first is the fallback). pub(super) table_styles: Vec<(String, String)>, - /// Multileader style name → MLEADERSTYLE handle (the first is the fallback). + /// The positions of [`Ctx::table_styles`] by name. + pub(super) table_style_names: ByName, + /// Multileader style name → MLEADERSTYLE handle (the first is the fallback): the drawing's + /// multileader styles in order, or Standard alone when it has none. pub(super) mleader_styles: Vec<(String, String)>, + /// The positions of [`Ctx::mleader_styles`] by name: those of the drawing's multileader styles + /// too, when it has any. + pub(super) mleader_style_names: ByName, /// Upper-case block name → BLOCK_RECORD handle (multileader block content). pub(super) block_records: HashMap, /// Raster images' IMAGEDEF, IMAGEDEF_REACTOR and dictionary handles. @@ -59,6 +66,8 @@ pub(super) struct Ctx { pub(super) frozen_341: bool, /// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists). pub(super) legacy_columns: bool, + /// Annotative text, MText and dimensions: their annotation scale contexts. + pub(super) anno: crate::dxf_anno::Plan, /// Saved layer states in AutoCAD's form (the LAYER table's extension dictionary). pub(super) layer_states: crate::dxf_layer_states::Plan, } @@ -69,6 +78,27 @@ impl Ctx { pub(super) fn native_mleader(&self) -> bool { self.target >= Version::R2007 } + /// Annotative object `e` as its groups are written: at its default annotation scale (`None`: + /// not written with contexts, as it is). + pub(super) fn at_default(&self, e: &Entity) -> Option { + self.anno.objs.get(&e.handle).map(|o| crate::dxf_anno::at_scale(e, crate::dxf_anno::default_factor(o))) + } + /// A native MULTILEADER's groups after its `AcDbMLeader` marker. + pub(super) fn mleader_tags(&self, d: &Drawing, m: &MLeader) -> Vec { + let refs = crate::dxf_mleader::Refs { + style: self.mleader_style(&m.style), + style_def: self.mleader_style_def(d, &m.style), + text_style: m.text.as_ref().and_then(|t| self.style(&t.style)), + block: m.block.as_ref().and_then(|b| self.block_records.get(&b.block.to_ascii_uppercase()).cloned()), + }; + crate::dxf_mleader::entity_tags(d, m, &refs) + } + /// `AcadAnnotative` xdata of an object written with contexts. + pub(super) fn anno_xdata(&self, w: &mut W, e: &Entity) { + if self.anno.objs.contains_key(&e.handle) { + w.xdata(crate::dxf_anno::xdata()); + } + } pub(super) fn style(&self, name: &str) -> Option { self.styles.get(&name.to_ascii_uppercase()).cloned() } @@ -76,14 +106,23 @@ impl Ctx { self.arrows.get(&name.trim().to_ascii_uppercase()).cloned() } pub(super) fn table_style(&self, name: &str) -> String { - Self::named(&self.table_styles, name) + Self::named(&self.table_styles, &self.table_style_names, name) } pub(super) fn mleader_style(&self, name: &str) -> String { - Self::named(&self.mleader_styles, name) + Self::named(&self.mleader_styles, &self.mleader_style_names, name) } - /// The handle of the style `name` in `styles`, or of the first one. - fn named(styles: &[(String, String)], name: &str) -> String { - styles.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).or_else(|| styles.first()).map(|(_, h)| h.clone()).unwrap_or_else(|| "0".into()) + /// The drawing's multileader style named `name` (the first of that name, ignoring case). + pub(super) fn mleader_style_def<'d>(&self, d: &'d cadcraft_doc::Drawing, name: &str) -> Option<&'d cadcraft_doc::MLeaderStyle> { + if self.mleader_styles.is_empty() { + // No styles planned (one entity's groups, for AutoLISP): look in the drawing. + return d.mleader_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name)); + } + self.mleader_style_names.position(name).and_then(|i| d.mleader_styles.get(i)) + } + /// The handle of the style `name` in `styles` (the first of that name, ignoring case, found + /// through `names`, their positions by name), or of the first one. + fn named(styles: &[(String, String)], names: &ByName, name: &str) -> String { + names.position(name).and_then(|i| styles.get(i)).or_else(|| styles.first()).map(|(_, h)| h.clone()).unwrap_or_else(|| "0".into()) } /// A dimension variable encoded with this file's handles; integers outside the 16-bit /// range of their groups are dropped. diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 54e38edd0..fb7494983 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -3,7 +3,8 @@ use super::common::{attrib_common, common, common_x, dim_xdata, layer_and_props, use super::ctx::Ctx; use super::layout::paper_view; use super::{ - Bounds2, Color, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3, Version, W, dxf_ext, + Attrib, Bounds2, Color, Common, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3, + Version, W, dxf_ext, }; /// The persistent reactors of boundary objects: each source object of an associative hatch in @@ -303,10 +304,16 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { match &e.kind { EntityKind::Text(t) => { + let scaled = cx.at_default(e); + let t = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::Text(s)) => s, + _ => t, + }; w.s(0, "TEXT"); common(w, e, owner, paper, "AcDbText"); thickness(w, e); text_tags(w, d, t, None, None, (e.handle, 0)); + cx.anno_xdata(w, e); } // Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS. EntityKind::Region(r) => { @@ -332,6 +339,11 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo } } EntityKind::MText(t) => { + let scaled = cx.at_default(e); + let t = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::MText(s)) => s, + _ => t, + }; w.s(0, "MTEXT"); common(w, e, owner, paper, "AcDbMText"); w.p(10, t.insert); @@ -357,7 +369,32 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo // Line spacing style: 1 = at least, 2 = exactly. w.i(73, if t.line_spacing_exact { 2 } else { 1 }); w.f(44, t.line_spacing); + // Why: Strict DXF parsers (e.g. AutoCAD 2027) reject conditional MTEXT background tags + // (63/421/45) when group 90 disables the mask or color bit; emit only tags active for + // the current bitmask, and keep them before column tags (75/101) where the reader stops. + if let Some(bg) = &t.background { + let mask = bg.mask & 0x03; + if mask != 0 { + w.i(90, i64::from(mask)); + let uses_window_bg = (mask & 2) != 0; + if !uses_window_bg + && (mask & 1) != 0 + && let Some(c) = bg.color + { + match c { + Color::True(rgb) => { + w.i(63, i64::from(cadcraft_color::nearest_aci(rgb))); + w.i(421, i64::from(rgb.to_u32())); + } + c => w.i(63, i64::from(c.to_aci())), + } + } + let scale = if bg.scale.is_finite() { bg.scale.clamp(1.0, 5.0) } else { 1.5 }; + w.f(45, scale); + } + } w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t, cx.target >= Version::R2018 && !cx.legacy_columns)); + cx.anno_xdata(w, e); } _ => {} } @@ -389,33 +426,45 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b // The block's definitions by tag, gathered once for all the attributes (#1923). let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default(); for (index, a) in i.attribs.iter().enumerate() { - let ah = w.h(); - w.s(0, "ATTRIB"); - w.s(5, ah); - w.s(330, e.handle.hex()); - w.s(100, "AcDbEntity"); - let (c, base) = attrib_common(e, &defs, a); - layer_and_props(w, &c, Some(&base)); - // Hidden with its definition (a dynamic block's visibility state hides it). - if !base.visible { - w.i(60, 1); - } - w.s(100, "AcDbText"); - text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index)); - if cx.target >= Version::R2007 { - multiline_tags(w, a, false); - } + let base = defs.get(&cadcraft_doc::TagKey(&a.tag)).map(|de| &de.common); + attrib_record(w, d, e, index, a, base, cx); } - let sh = w.h(); - w.s(0, "SEQEND"); - w.s(5, sh); - w.s(330, e.handle.hex()); - w.s(100, "AcDbEntity"); - w.s(8, &e.common.layer); + seqend_record(w, e); } } } +/// One ATTRIB record of the block reference `e`, for its attribute `a` (as written after its +/// INSERT): its handle is a new one, its owner the reference's. +pub(super) fn attrib_record(w: &mut W, d: &Drawing, e: &Entity, index: usize, a: &Attrib, base: Option<&Common>, cx: &Ctx) { + let ah = w.h(); + w.s(0, "ATTRIB"); + w.s(5, ah); + w.s(330, e.handle.hex()); + w.s(100, "AcDbEntity"); + let (c, base) = attrib_common(e, a, base); + layer_and_props(w, &c, Some(&base)); + // Hidden with its definition (a dynamic block's visibility state hides it). + if !base.visible { + w.i(60, 1); + } + w.s(100, "AcDbText"); + text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index)); + if cx.target >= Version::R2007 { + multiline_tags(w, a, false); + } +} + +/// The SEQEND record that ends a block reference's attributes (written after its last ATTRIB). +pub(super) fn seqend_record(w: &mut W, e: &Entity) { + let sh = w.h(); + w.s(0, "SEQEND"); + w.s(5, sh); + w.s(330, e.handle.hex()); + w.s(100, "AcDbEntity"); + w.s(8, &e.common.layer); +} + fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { if let EntityKind::Dimension(dm) = &e.kind { w.s(0, "DIMENSION"); @@ -424,7 +473,13 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper w.s(2, bname); w.p(10, dm.defpt); let style = d.dim_style(&dm.style).cloned().unwrap_or_default(); - let g = cadcraft_render::dimension_geometry(dm, &style, d.header.f64("DIMSCALE", 1.0)); + // An annotative dimension's text is where its default scale puts it. + let scaled = cx.at_default(e); + let at = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::Dimension(s)) => s, + _ => dm, + }; + let g = cadcraft_render::dimension_geometry(at, &style, d.header.f64("DIMSCALE", 1.0)); w.p(11, if dm.user_text_pos { dm.text_mid } else { g.text_pos.to3(0.0) }); // Group 12: a block read from a file keeps the dimension's moved-by offset (AutoCAD // draws the block translated by it); regenerated geometry already sits where the @@ -444,8 +499,18 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper DimKind::ArcLength => 1, }; w.i(70, ty | 32 | if dm.user_text_pos { 128 } else { 0 }); - // The actual measurement (read-only in DXF): AutoLISP's entget shows it. - w.f(42, g.measurement); + // The actual measurement (read-only in DXF): AutoLISP's entget shows it. Linear + // measurements carry DIMLFAC; angles are radians. A negative factor means 1.0 in model + // space and its absolute value in paper space (Autodesk's model/paper-space rule). + let measurement = match dm.kind { + DimKind::Angular | DimKind::Angular3P => g.measurement, + _ => { + let factor = style.with_overrides(&dm.overrides).linear_factor; + let factor = if factor < 0.0 { if paper { factor.abs() } else { 1.0 } } else { factor }; + g.measurement * factor + } + }; + w.f(42, measurement); if !dm.text.is_empty() { w.s(1, crate::dxf_read::mtext_dxf::encode_line(&dm.text)); } @@ -500,6 +565,7 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper } } dim_xdata(w, dm, cx); + cx.anno_xdata(w, e); } } @@ -557,7 +623,7 @@ fn write_table_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: b w.i(93, 4); w.i(90, 4); } - let chars: Vec = cell.filter(|_| !cx.modern_table_values || !covered).map(|x| x.text.chars().collect()).unwrap_or_default(); + let chars: Vec = cell.map(|x| x.text.chars().collect()).unwrap_or_default(); let chunks: Vec = chars.chunks(250).map(|c| c.iter().collect()).collect(); let n = chunks.len(); for (i, ch) in chunks.iter().enumerate() { @@ -595,14 +661,19 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap match &e.kind { EntityKind::MLeader(m) if !cx.native_mleader() => mleader_fallback(w, d, e, m, owner, paper, cx), EntityKind::MLeader(m) => { + let scaled = cx.at_default(e); + let m = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::MLeader(s)) => s, + _ => m, + }; w.s(0, "MULTILEADER"); common(w, e, owner, paper, "AcDbMLeader"); - let refs = crate::dxf_mleader::Refs { - style: cx.mleader_style(&m.style), - text_style: m.text.as_ref().and_then(|t| cx.style(&t.style)), - block: m.block.as_ref().and_then(|b| cx.block_records.get(&b.block.to_ascii_uppercase()).cloned()), - }; - w.t.extend(crate::dxf_mleader::entity_tags(d, m, &refs)); + let mut tags = cx.mleader_tags(d, m); + if let Some(o) = cx.anno.objs.get(&e.handle) { + crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o)); + } + w.t.extend(tags); + cx.anno_xdata(w, e); } EntityKind::Leader(l) => { w.s(0, "LEADER"); @@ -661,7 +732,11 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo w.i(71, i64::from(h.associative)); w.i(91, h.loops.len() as i64); for l in &h.loops { - w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (4 | 8 | 16))); + // Polyline (2), External (1) from `outer`, and Textbox (8) and Outermost (16) as read. + // Not Derived (4): a derived path needs the hatch's pixel size (group 47) before its + // seed points, and a hatch does not keep one. As reported in #3664, AutoCAD refuses a + // file with the bit and no size, and draws pattern fills solid with a stand-in size. + w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (8 | 16))); let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0); w.i(72, i64::from(has_bulge)); w.i(73, 1); @@ -683,33 +758,44 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo } } w.i(75, i64::from(h.style)); - w.i(76, 1); + // Pattern type: 0 for a user-defined hatch (its lines come from its angle, spacing and + // double flag, groups 52, 41 and 77); 1 for a predefined (library) pattern. + let user = cadcraft_doc::library::is_user_pattern(&h.pattern); + w.i(76, if user { 0 } else { 1 }); // Angle, scale and double flag are a pattern fill's: AutoCAD 2024 writes none of them on a // solid or gradient fill, and refuses a file whose solid HATCH has any of them ("Error: // expected group code 98", the whole drawing discarded; measured). if !h.solid { w.f(52, h.angle.to_degrees()); w.f(41, h.scale); - w.i(77, 0); // The lines read from the file, else the library's pattern of that name. let lines = if h.pattern_lines.is_empty() { cadcraft_doc::library::pattern_for(d, &h.pattern).map(|p| p.lines).unwrap_or_default() } else { h.pattern_lines.clone() }; + // Double hatch area (group 77): a user-defined hatch's second family, at right angles. + w.i(77, i64::from(user && lines.len() > 1)); + // The number of pattern definition lines, then each line's angle, base point, offset + // and dashes, scaled and rotated as the hatch draws them. The DXF Reference has no + // user-defined exception: its families are listed here as any pattern's are, and a + // reader given 78 = 0 has no lines to draw. w.i(78, lines.len() as i64); + // The scale the renderer and the reader use: one too small to draw is 1, so a resave + // writes the lines it read back. + let k = cadcraft_doc::library::effective_hatch_pattern_scale(h.scale); for pl in lines { let ang = pl.angle.to_radians() + h.angle; w.f(53, ang.to_degrees()); - let o = h.origin + Vec2::new(pl.origin.0, pl.origin.1).rotate(h.angle) * h.scale; + let o = h.origin + Vec2::new(pl.origin.0, pl.origin.1).rotate(h.angle) * k; w.f(43, o.x); w.f(44, o.y); - let dl = Vec2::new(pl.delta.0, pl.delta.1).rotate(ang) * h.scale; + let dl = Vec2::new(pl.delta.0, pl.delta.1).rotate(ang) * k; w.f(45, dl.x); w.f(46, dl.y); w.i(79, pl.dashes.len() as i64); for dsh in pl.dashes { - w.f(49, dsh * h.scale); + w.f(49, dsh * k); } } } @@ -758,8 +844,30 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: if let Some(h) = clip { w.s(340, h.hex()); } - // One CADCraft xdata group holds both lists: readers stop at the first group of an app. - if !unrecorded.is_empty() || !v.layer_colors.is_empty() { + // The viewport's own UCS. Its other unmodelled groups (`extra`) go in after this, just + // before the xdata (dxf_raw::finish). + if v.ucs.is_some() || v.ucs_per_viewport { + w.i(71, i64::from(v.ucs_per_viewport)); + } + // The named and base UCS that are still in the UCS table. + let mut ucs_names = (None, None); + if let Some(u) = &v.ucs { + w.p(110, u.origin); + w.p(111, u.x_axis); + w.p(112, u.y_axis); + w.i(79, i64::from(u.ortho)); + w.f(146, u.elevation); + ucs_names = (live_ucs(&w.ucss, &u.named), live_ucs(&w.ucss, &u.base)); + for (code, name) in [(345, &ucs_names.0), (346, &ucs_names.1)] { + if let Some((_, h)) = name { + w.s(code, h.clone()); + } + } + } + let has_ucs_names = ucs_names.0.is_some() || ucs_names.1.is_some(); + let has_extra = v.extra.iter().any(|t| !crate::dxf_raw::is_pointer(t.code)); + // One CADCraft xdata group holds all the lists: readers stop at the first group of an app. + if !unrecorded.is_empty() || !v.layer_colors.is_empty() || has_ucs_names || has_extra { w.s(1001, dxf_ext::APP); if !unrecorded.is_empty() { w.xdata(dxf_ext::frozen_xdata(&unrecorded)); @@ -767,6 +875,12 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: if !v.layer_colors.is_empty() { w.xdata(dxf_ext::layer_colors_xdata(&v.layer_colors)); } + if has_ucs_names { + w.xdata(dxf_ext::ucs_xdata(ucs_names.0.map(|(n, _)| n), ucs_names.1.map(|(n, _)| n))); + } + if has_extra { + w.xdata(dxf_ext::extra_xdata(&v.extra)); + } } } } @@ -919,3 +1033,9 @@ fn hatch_xdata(w: &mut W, h: &Hatch) { w.p(1011, h.origin.to3(0.0)); w.s(1000, h.background.map(Color::name).unwrap_or_default()); } + +/// A viewport's named or base UCS with its record handle, if the UCS table still has it. +fn live_ucs<'a>(ucss: &HashMap, name: &'a Option) -> Option<(&'a str, String)> { + let n = name.as_deref()?; + Some((n, ucss.get(&n.to_ascii_uppercase())?.clone())) +} diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index ba78891e9..d4a40e97d 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -120,6 +120,8 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { records.extend(d.vports.iter().filter(|c| !c.is_active() && !c.name.is_empty()).flat_map(|c| c.tiles.iter().map(|t| (c.name.as_str(), t)))); let th = table_head(w, "VPORT", records.len()); let finite = |p: Vec2, or: Vec2| if p.is_finite() { p } else { or }; + // The `*Active` records' group 72 as the drawing was read with it, if it was. + let circle_sides = d.header.get(dxf_ext::VPORT_CIRCLE_SIDES_KEY).and_then(|v| v.as_i64()).and_then(dxf_ext::circle_sides); for (name, t) in records { record_head(w, "VPORT", &th, "AcDbViewportTableRecord"); w.s(2, name); @@ -139,6 +141,10 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { w.f(42, 50.0); w.f(50, d.header.f64("SNAPANG", 0.0)); w.f(51, twist.to_degrees()); + // Circle sides ([`dxf_ext::VPORT_CIRCLE_SIDES_KEY`]), carried as read on the `*Active` records. + if let Some(v) = circle_sides.filter(|_| name == VportConfig::ACTIVE) { + w.i(72, v); + } // UCSICON: bit 1 shows the icon, bit 2 puts it at the UCS origin. A setting of the shown // configuration (there is no header variable for it). if name == VportConfig::ACTIVE { diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index a2363e2f2..7f630cfb1 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -277,6 +277,7 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) { ucss: HashMap::new(), vport_ucs: Vec::new(), reactors: HashMap::new(), + xdicts: HashMap::new(), }; for (field, code, kind) in dxf_ext::DIM_CODES { let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue }; @@ -347,7 +348,7 @@ fn write_header(w: &mut W, d: &Drawing, version: Version) -> usize { seed_pos } -fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) { +fn write_classes(w: &mut W, d: &Drawing, cx: &Ctx, every: &[&Entity], wipeout_vars: bool) { w.s(0, "SECTION"); w.s(2, "CLASSES"); let mut classes = vec![ @@ -371,6 +372,9 @@ fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) { if every.iter().any(|e| matches!(e.kind, EntityKind::Wipeout(_))) { classes.push(("WIPEOUT", "AcDbWipeout", 127, true)); } + if wipeout_vars { + classes.push(("WIPEOUTVARIABLES", "AcDbWipeoutVariables", 0, false)); + } if !cx.images.is_empty() { classes.push(("IMAGE", "AcDbRasterImage", 127, true)); classes.push(("IMAGEDEF", "AcDbRasterImageDef", 0, false)); @@ -378,6 +382,9 @@ fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) { classes.push(("RASTERVARIABLES", "AcDbRasterVariables", 0, false)); } classes.push(("SCALE", "AcDbScale", 0, false)); + for (dxf_name, cpp) in cx.anno.classes(d) { + classes.push((dxf_name, cpp, 1153, false)); + } for (dxf_name, cpp, proxy, is_entity) in classes { w.s(0, "CLASS"); w.s(1, dxf_name); @@ -448,6 +455,16 @@ fn plot_layout_flags(page: &PageSetup, standard: bool, model: bool) -> i64 { kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 } } +/// A LAYOUT object's own flags (group 70 after AcDbLayout; DXF Reference, LAYOUT: 1 is the +/// layout's PSLTSCALE and 2 its LIMCHECK, each the value while it is current): the bits the file +/// had, else the drawing's PSLTSCALE, which CADCraft draws every layout with, and LIMCHECK off, as +/// CADCraft has no limits check. Other bits have no meaning in the Reference and are not written. +fn layout_flags(d: &Drawing, kept: Option) -> i64 { + const PSLTSCALE: i64 = 1; + const LIMCHECK: i64 = 2; + kept.unwrap_or_else(|| if d.header.i64("PSLTSCALE", 1) != 0 { PSLTSCALE } else { 0 }) & (PSLTSCALE | LIMCHECK) +} + fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) { let d = context.drawing; let layout_dict = context.dictionary; @@ -625,6 +642,8 @@ struct ObjectWritePlan<'a> { table_style_dict: &'a String, pstyle_dict: &'a String, scale_dict: &'a String, + /// The WIPEOUTVARIABLES object's handle and its frame flag (0 or 1), when the drawing sets WIPEOUTFRAME. + wipeout_vars: Option<(&'a String, i64)>, model_layout: &'a String, ms_br: &'a String, ps_brs: &'a [(String, String, &'a Layout)], @@ -670,7 +689,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { name: "Model", tab: 0, block_record: ms_br, - flags: 1, + flags: layout_flags(d, d.model_layout_flags), page: d.model_page.as_ref().unwrap_or(&model_page), view: None, ucs: None, @@ -688,7 +707,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { name: &l.name, tab: i64::from(l.tab_order.max(1)), block_record: brh, - flags: 1, + flags: layout_flags(d, l.flags), page: &l.page, view: l.view, ucs: l.ucs.as_ref(), @@ -715,6 +734,7 @@ fn write_root_group_objects( let pstyle_dict = plan.pstyle_dict; let scale_dict = plan.scale_dict; let xrecords = plan.xrecords; + let wipeout_vars = plan.wipeout_vars; w.s(0, "SECTION"); w.s(2, "OBJECTS"); w.s(0, "DICTIONARY"); @@ -746,6 +766,10 @@ fn write_root_group_objects( } w.s(3, "ACAD_SCALELIST"); w.s(350, scale_dict.clone()); + if let Some((h, _)) = wipeout_vars { + w.s(3, "ACAD_WIPEOUT_VARS"); + w.s(350, h.clone()); + } w.s(0, "DICTIONARY"); w.s(5, group_dict); w.s(330, root_dict.clone()); @@ -839,9 +863,19 @@ fn write_named_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { } } scale_list(w, scales, scale_dict, root_dict); + // The wipeout frame flag (#3440): 0 no frame, 1 display frame. + if let Some((h, frame)) = plan.wipeout_vars { + w.s(0, "WIPEOUTVARIABLES"); + w.s(5, h.clone()); + w.group("ACAD_REACTORS", 330, &[root_dict]); + w.s(330, root_dict.clone()); + w.s(100, "AcDbWipeoutVariables"); + w.i(70, frame); + } } -fn write_associative_objects(w: &mut W, cx: &Ctx) { +fn write_associative_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { + let cx = plan.cx; // Dimension associativity: extension dictionary + DIMASSOC per dimension. let mut assoc: Vec<(&Handle, &AssocObj)> = cx.assoc.iter().collect(); assoc.sort_by_key(|(h, _)| **h); @@ -856,6 +890,10 @@ fn write_associative_objects(w: &mut W, cx: &Ctx) { w.i(281, 1); w.s(3, "ACAD_DIMASSOC"); w.s(360, a.handle.clone()); + // An annotative dimension's contexts share the dictionary. + if let Some(o) = cx.anno.objs.get(dim) { + w.t.extend(crate::dxf_anno::xdict_entry(o)); + } w.s(0, "DIMASSOC"); w.s(5, a.handle.clone()); w.group("ACAD_REACTORS", 330, &[&a.xdict]); @@ -885,6 +923,17 @@ fn write_associative_objects(w: &mut W, cx: &Ctx) { } } +/// The annotation scale contexts of annotative text, MText and dimensions. +fn write_annotation_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { + let mut annos: Vec<(&Handle, &crate::dxf_anno::Obj)> = plan.cx.anno.objs.iter().collect(); + annos.sort_by_key(|(h, _)| **h); + for (h, o) in annos { + if let Some(e) = plan.d.entity(*h) { + w.t.extend(crate::dxf_anno::objects(plan.d, e, o, &|m| plan.cx.mleader_tags(plan.d, m))); + } + } +} + fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) { // Groups (members that still exist) and multileader styles. let group_owner = plan.group_dict.clone(); @@ -905,25 +954,114 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) { crate::dxf_layer_states::objects(&plan.cx.layer_states, &plan.d.layer_states, &refs) }; w.t.extend(layer_states); - write_associative_objects(w, plan.cx); + write_associative_objects(w, &plan); + write_annotation_objects(w, &plan); write_layout_objects(w, &plan); // Raster image definitions. w.t.extend(crate::dxf_image::objects(&plan.cx.images, plan.root_dict)); w.s(0, "ENDSEC"); } +/// The next free `*D` block name at or after `*D{n}`. +fn fresh_dim_name(d: &Drawing, n: &mut usize) -> String { + let mut name = format!("*D{n}"); + while d.block(&name).is_some() { + *n += 1; + name = format!("*D{n}"); + } + *n += 1; + name +} + +type DimDef = (String, String, Vec); + +/// An annotative dimension's blocks, one per annotation scale (its default scale's is the +/// dimension's own); `None` when it has no scales. +fn annotative_dimension_blocks( + d: &Drawing, + e: &Entity, + n: &mut usize, + w: &mut W, + (cx, dim_defs): (&mut Ctx, &mut Vec), +) -> Option> { + // Only dimensions have a block per scale (text and multileaders have none). + if !matches!(e.kind, EntityKind::Dimension(_)) { + return None; + } + let (scales, default) = crate::dxf_anno::scales(d, e); + let mut names = Vec::new(); + for s in &scales { + let at = crate::dxf_anno::at_scale(e, s.factor()); + let EntityKind::Dimension(sdm) = &at.kind else { continue }; + let ents = dim_block_entities(d, sdm, &e.common.layer); + let name = fresh_dim_name(d, n); + dim_defs.push((name.clone(), w.h(), ents)); + names.push(name); + } + cx.dim_blocks.insert(e.handle, names.get(default)?.clone()); + Some(names) +} + +/// The dimensions' anonymous blocks, and the blocks of each annotative dimension by scale (from +/// The scales annotative text, MText and dimensions support that the drawing's scale list lacks +/// (each context names its SCALE object, so they are added to the list written). +fn missing_anno_scales(d: &Drawing, all_spaces: &[&EntityStore]) -> Vec { + let mut extra: Vec = Vec::new(); + for e in all_spaces.iter().flat_map(|s| s.iter()).filter(|e| crate::dxf_anno::has_contexts(e)) { + for s in crate::dxf_anno::scales(d, e).0 { + let known = |x: &cadcraft_doc::AnnoScale| x.is_valid() && x.name.eq_ignore_ascii_case(&s.name); + if !d.scales.iter().any(known) && !extra.iter().any(known) && extra.len() < cadcraft_doc::MAX_SCALES { + extra.push(s); + } + } + } + extra +} + +/// Plan the annotation scale contexts of annotative text, MText and dimensions: their objects in +/// `cx.anno`, and the extension dictionaries made for them in `w.xdicts`. +fn plan_anno_contexts( + d: &Drawing, + all_spaces: &[&EntityStore], + scales: &[(&cadcraft_doc::AnnoScale, String)], + anno_dim_blocks: &HashMap>, + w: &mut W, + cx: &mut Ctx, +) { + let scale_handle = |name: &str| scales.iter().find(|(s, _)| s.name.eq_ignore_ascii_case(name)).map(|(_, h)| h.clone()); + for e in all_spaces.iter().flat_map(|s| s.iter()).filter(|e| crate::dxf_anno::has_contexts(e)) { + let xdict = cx.assoc.get(&e.handle).map(|a| a.xdict.clone()); + let blocks = anno_dim_blocks.get(&e.handle).map(Vec::as_slice); + if let Some(o) = crate::dxf_anno::plan_one(d, e, scale_handle, xdict, blocks, || w.h()) { + if o.own_xdict { + w.xdicts.insert(e.handle, o.xdict.clone()); + } + cx.anno.objs.insert(e.handle, o); + } + } +} + +/// AutoCAD 2008, the 2007 format: `contexts`). fn dimension_block_definitions( d: &Drawing, all_spaces: &[&EntityStore], - dim_plan: &super::blocks::DimBlockPlan, + (dim_plan, contexts): (&super::blocks::DimBlockPlan, bool), w: &mut W, cx: &mut Ctx, -) -> Vec<(String, String, Vec)> { +) -> (Vec, HashMap>) { let mut dim_defs = Vec::new(); + let mut anno_dim_blocks: HashMap> = HashMap::new(); let mut n = 1; let mut reused_handles = std::collections::HashSet::new(); for st in all_spaces { for e in st.iter() { + if contexts + && crate::dxf_anno::has_contexts(e) + && let Some(names) = annotative_dimension_blocks(d, e, &mut n, w, (cx, &mut dim_defs)) + { + anno_dim_blocks.insert(e.handle, names); + continue; + } if let EntityKind::Dimension(dm) = &e.kind { let reused = dim_plan.reuse.get(&e.handle); let ents: Vec; @@ -944,13 +1082,7 @@ fn dimension_block_definitions( } None => { ents = dim_block_entities(d, dm, &e.common.layer); - let mut name = format!("*D{n}"); - while d.block(&name).is_some() { - n += 1; - name = format!("*D{n}"); - } - n += 1; - name + fresh_dim_name(d, &mut n) } }; let brh = w.h(); @@ -959,7 +1091,7 @@ fn dimension_block_definitions( } } } - dim_defs + (dim_defs, anno_dim_blocks) } fn arrow_block_definitions( @@ -1094,6 +1226,7 @@ pub(super) fn tags_kept_for( ucss: HashMap::new(), vport_ucs: Vec::new(), reactors: hatch_reactors(d), + xdicts: HashMap::new(), }; // Pre-allocate handles for block records. let paper_layouts = d.paper_space_layouts(); @@ -1119,7 +1252,11 @@ pub(super) fn tags_kept_for( let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, modern_table_values: !bridge && version >= Version::R2007, ..Ctx::default() }; cx.block_records = user_blocks.iter().map(|(n, h, _)| (n.to_ascii_uppercase(), h.clone())).collect(); let all_spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect(); - let mut dim_defs = dimension_block_definitions(d, &all_spaces, &dim_plan, &mut w, &mut cx); + // Annotation scale contexts (from AutoCAD 2008, the 2007 format). Not through the DWG bridge + // yet, which doesn't convert them (storytold/craft-libs#2005): a DWG keeps CADCraft's own + // record of the scales instead, as an older format does. + let contexts = target >= Version::R2007 && !bridge; + let (mut dim_defs, anno_dim_blocks) = dimension_block_definitions(d, &all_spaces, (&dim_plan, contexts), &mut w, &mut cx); // Every entity, including block contents (for arrows, tables and overrides). let every: Vec<&Entity> = all_spaces .iter() @@ -1135,9 +1272,11 @@ pub(super) fn tags_kept_for( let default_table_style = [TableStyle::default()]; let table_styles: &[TableStyle] = if d.table_styles.is_empty() { &default_table_style } else { &d.table_styles }; cx.table_styles = table_styles.iter().map(|s| (s.name.clone(), w.h())).collect(); + cx.table_style_names = crate::dxf_ext::ByName::new(&cx.table_styles, |(n, _)| n); let default_mleader_style = [MLeaderStyle::default()]; let mleader_styles: &[MLeaderStyle] = if d.mleader_styles.is_empty() { &default_mleader_style } else { &d.mleader_styles }; cx.mleader_styles = mleader_styles.iter().map(|s| (s.name.clone(), w.h())).collect(); + cx.mleader_style_names = crate::dxf_ext::ByName::new(&cx.mleader_styles, |(n, _)| n); let root_dict = w.h(); let group_dict = w.h(); let layout_dict = w.h(); @@ -1165,12 +1304,41 @@ pub(super) fn tags_kept_for( if let Some(chunks) = dxf_ext::plot_style_chunks(&d.plot_style_tables) { xrecords.push((dxf_ext::PLOT_STYLES_KEY, w.h(), chunks)); } - if let Some(chunks) = dxf_ext::anno_chunks(d) { + if let Some(chunks) = dxf_ext::anno_chunks(d, contexts) { xrecords.push((dxf_ext::ANNOTATION_KEY, w.h(), chunks)); } // The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects. let scale_dict = w.h(); - let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect(); + // Only a drawing that holds WIPEOUTFRAME (set, or read from a file) gets the object. The DXF + // Reference gives its flag two values, 0 (no frame) and 1 (display frame). "Shown but not + // plotted" (2) displays the frames, so it is written as 1: where a file keeps the third state + // is not documented. A file whose own object already says what the drawing holds, or what + // would be written for it, keeps that object instead (the kept objects are written back as + // read, with what other applications hung on them), so opening and saving it changes nothing. + let file_flag = d + .foreign + .objects + .iter() + .find(|o| o.kind == "WIPEOUTVARIABLES") + .and_then(|o| o.tags.iter().find(|t| t.code == 70)) + .and_then(|t| t.value.trim().parse::().ok()); + let wipeout_frame = d + .header + .get("WIPEOUTFRAME") + .and_then(HVal::as_i64) + .filter(|v| (0..=2).contains(v)) + .filter(|v| file_flag != Some(*v)) + .map(|v| v.min(1)) + .filter(|flag| file_flag != Some(*flag)); + let wipeout_handle = wipeout_frame.map(|_| w.h()); + // Scales annotative objects support that the list lacks are added to it (each context names + // its SCALE object). + let extra_scales = if contexts { missing_anno_scales(d, &all_spaces) } else { Vec::new() }; + let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = + d.scales.iter().filter(|s| s.is_valid()).chain(extra_scales.iter()).map(|s| (s, w.h())).collect(); + if contexts { + plan_anno_contexts(d, &all_spaces, &scales, &anno_dim_blocks, &mut w, &mut cx); + } // Plot style names used by layers and objects (Normal always), each a placeholder object; in // a drawing of named plot styles also those of the layers of saved layer states, which name // theirs by placeholder. @@ -1194,7 +1362,7 @@ pub(super) fn tags_kept_for( let seed_pos = write_header(&mut w, d, version); - write_classes(&mut w, &cx, &every); + write_classes(&mut w, d, &cx, &every, wipeout_frame.is_some()); let max_dashes = bridge.then_some(super::DWG_MAX_LINETYPE_ELEMENTS); let (ltype_handles, linetypes_cut) = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model), max_dashes }); @@ -1209,10 +1377,18 @@ pub(super) fn tags_kept_for( w.s(100, "AcDbBlockTableRecord"); w.s(2, name); w.s(340, layout.unwrap_or("0")); - // User blocks: insertion units (70) and explodability (280). + // User blocks: insertion units (70), explodability (280), uniform scaling (281) and + // whether references are annotative (`AcadAnnotative` xdata: without it AutoCAD scales + // the references by their units instead of the annotation scale). Not in a DWG yet: the + // bridge drops the references' contexts, and the flag alone would have AutoCAD scale them + // by the annotation scale once more (storytold/craft-libs#2005). if let Some(b) = blk { w.i(70, i64::from(b.units)); w.i(280, i64::from(b.explodable)); + w.i(281, i64::from(b.scale_uniformly)); + if b.annotative && !bridge { + annotative_xdata(w); + } if let Some(a) = &b.array { w.s(1001, dxf_ext::APP); w.xdata(dxf_ext::array_xdata(a)); @@ -1323,6 +1499,7 @@ pub(super) fn tags_kept_for( table_style_dict: &table_style_dict, pstyle_dict: &pstyle_dict, scale_dict: &scale_dict, + wipeout_vars: wipeout_handle.as_ref().zip(wipeout_frame), model_layout: &model_layout, ms_br: &ms_br, ps_brs: &ps_brs, @@ -1346,7 +1523,7 @@ pub(super) fn tags_kept_for( // no data store, so a solid whose geometry is only there is left out of it. // The DWG bridge keeps proxies in the DWG's own layout. let strings = bridge || version >= Version::R2007; - let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings); + let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings, bridge); // Kept constraint groups go in the order their reader expects: a DXF's own version. The // bridge's R2000 text is read as the version its kept groups came from when that is newer // (craft-dwg's `encode_kept_noted` declares it), so there they stay as read. diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b175c21f9..776e6d7fb 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -7,6 +7,8 @@ mod dwg_hatch; /// What a DXF file holds that CADCraft doesn't model, kept and written back (#528). mod dxf_raw; +/// Annotative text, MText and dimensions: AutoCAD's annotation scale contexts. +mod dxf_anno; /// XCLIP boundaries as SPATIAL_FILTER objects. mod dxf_clip; mod dxf_ext; @@ -38,7 +40,7 @@ pub use cadcraft_doc::Format; pub use craft_dxf::Version; pub use dxf_raw::{ObjectRecord, object_records}; pub use dxf_read::entity_from_groups; -pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost}; +pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, entity_sub_record, proxies_lost}; pub use pdf::{PdfOptions, pdf, plot}; /// How a drawing is saved as DXF or DWG. diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index fcaab1b0a..e97f81a64 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -36,6 +36,7 @@ use kr::text::{GlyphId, KrillaGlyph}; use crate::{IoError, Result}; mod fonts; +mod outline; /// PDF points per millimetre. const PT_PER_MM: f64 = 72.0 / 25.4; @@ -61,7 +62,8 @@ const MAX_TEXT: usize = 1000; pub struct PdfOptions { /// Plot style table name, replacing the page setup's (`"None"` plots without one). pub plot_style_table: Option, - /// Paper name from [`cadcraft_render::PAPER_SIZES`] (`"A4"`, `"Letter"`, `"ANSI B"`…). + /// Paper name from [`cadcraft_render::PAPER_SIZES`] (`"A4"`, `"Letter"`, `"ANSI B"`, `"B4 (JIS)"`, + /// `"Japanese Postcard"`…). pub paper: Option, /// Custom paper size in millimetres (portrait width, height). pub paper_mm: Option<(f64, f64)>, @@ -866,7 +868,7 @@ fn krilla_failure(e: KrillaError) -> Failure { /// transparent primitive is stroked on its own (one path is painted once), so where /// primitives overlap they build up, as in PNG plots and on screen. Block contents and /// viewport contents share their reference's handle, so this goes by primitive, not by object. -/// Each filled primitive is one path of its triangles. +/// Each filled primitive is one path: the outline of its triangles. /// /// Primitives that stand for a glyph in an embeddable font (see [`fonts::Fonts`]) are written /// as text instead: the glyph at font size 1 under its glyph matrix (the matrix axes are one @@ -982,14 +984,16 @@ fn stroke_run(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder) } } -/// Fill a set of triangles, clipped to the plot area. +/// Fill a set of triangles, clipped to the plot area, as the loops of their outline (see +/// [`outline`]), which fill the same as the triangles with far less path data. fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, raw: &[Vec2], rgb: Rgb, t: u8) { let mapped: Vec = raw.iter().map(|q| p.map.pt(*q)).collect(); // With a vertex out of range, keep the parts inside the plot area. let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, &p.clip_pt) }; + let tris: Vec<[outline::Pt; 3]> = tris.as_chunks::<3>().0.iter().filter_map(|[a, b, c]| Some([coord(*a)?, coord(*b)?, coord(*c)?])).collect(); + let rings = outline::loops(&tris).unwrap_or_else(|| tris.iter().map(|t| t.to_vec()).collect()); let mut pb = PathBuilder::new(); - for tri in tris.as_chunks::<3>().0 { - let Some(v) = tri.iter().map(|q| coord(*q)).collect::>>() else { continue }; + for v in &rings { for (j, (x, y)) in v.iter().enumerate() { if j == 0 { pb.move_to(*x, *y); diff --git a/crates/io/src/pdf/outline.rs b/crates/io/src/pdf/outline.rs new file mode 100644 index 000000000..91b32dded --- /dev/null +++ b/crates/io/src/pdf/outline.rs @@ -0,0 +1,202 @@ +//! The outline of a set of filled triangles: closed loops that fill, under the nonzero rule, +//! exactly what the triangles fill as one path of one subpath each. +//! +//! A filled path's nonzero winding number at a point is the sum, over its directed edges, of +//! the crossings of a ray from the point. So it depends only on how many times each directed +//! edge occurs, less the times it occurs reversed. An edge shared by two neighbouring +//! triangles in opposite directions cancels, and so does a zero-length edge. What is left +//! enters each vertex as often as it leaves it (each triangle does, and a cancelled pair takes +//! one entry and one exit from both its ends), so it splits into closed loops, and any such +//! split winds the same as the triangles everywhere off the edges. This holds for overlapping +//! triangles, mixed orientations, zero-area triangles and T-junctions alike: edges that do not +//! pair stay in the outline, which is then larger but still fills the same. +//! +//! Vertices are matched by the exact bits of the `f32` coordinates that are written, never by a +//! tolerance, so two distinct written points are never merged. + +/// A written vertex. +pub(super) type Pt = (f32, f32); + +/// The bits of a vertex, the key it is matched by. +fn key(p: Pt) -> u64 { + (u64::from(p.0.to_bits()) << 32) | u64::from(p.1.to_bits()) +} + +/// The loops (each closed back to its first vertex) whose nonzero fill is that of `tris`, or +/// `None` when they cannot be traced (which the reasoning above rules out; the caller then +/// writes the triangles). Time is `O(n log n)` and memory `O(n)` in the triangle count. +pub(super) fn loops(tris: &[[Pt; 3]]) -> Option>> { + let mut keys: Vec = tris.iter().flatten().map(|p| key(*p)).collect(); + keys.sort_unstable(); + keys.dedup(); + let pts: Vec = keys.iter().map(|k| (f32::from_bits((k >> 32) as u32), f32::from_bits(*k as u32))).collect(); + let id = |p: &Pt| keys.binary_search(&key(*p)).ok().and_then(|i| u32::try_from(i).ok()); + // Each edge as (lower id, higher id, +1 when it runs from the lower to the higher). + let mut undirected: Vec<(u32, u32, i8)> = Vec::with_capacity(tris.len().saturating_mul(3)); + for t in tris { + let v = [id(&t[0])?, id(&t[1])?, id(&t[2])?]; + for (a, b) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])] { + match a.cmp(&b) { + std::cmp::Ordering::Less => undirected.push((a, b, 1)), + std::cmp::Ordering::Greater => undirected.push((b, a, -1)), + std::cmp::Ordering::Equal => {} + } + } + } + undirected.sort_unstable_by_key(|e| (e.0, e.1)); + // What is left of each edge once opposite directions cancel, by start vertex. + let mut edges: Vec<(u32, u32)> = Vec::new(); + for run in undirected.chunk_by(|x, y| (x.0, x.1) == (y.0, y.1)) { + let Some(&(a, b, _)) = run.first() else { continue }; + let net: i64 = run.iter().map(|e| i64::from(e.2)).sum(); + let e = if net > 0 { (a, b) } else { (b, a) }; + edges.extend(std::iter::repeat_n(e, usize::try_from(net.unsigned_abs()).ok()?)); + } + drop(undirected); + edges.sort_unstable(); + // `next[v]..end[v]`: the unused edges leaving vertex `v`. + let mut end = vec![0usize; pts.len()]; + for e in &edges { + *end.get_mut(e.0 as usize)? += 1; + } + let mut next = vec![0usize; pts.len()]; + let mut at = 0usize; + for (n, e) in next.iter_mut().zip(end.iter_mut()) { + *n = at; + at += *e; + *e = at; + } + let mut out = Vec::new(); + for start in 0..pts.len() { + while next.get(start)? < end.get(start)? { + // Follow unused edges from `start` until one leads back to it. Each step uses an + // edge, so this ends; balance means only `start` can be left with no edge out. + let mut ring = vec![*pts.get(start)?]; + let mut cur = start; + loop { + let i = *next.get(cur)?; + if i >= *end.get(cur)? { + return None; + } + *next.get_mut(cur)? += 1; + let to = edges.get(i)?.1 as usize; + if to == start { + break; + } + ring.push(*pts.get(to)?); + cur = to; + } + out.push(ring); + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Fill paths of one subpath per closed ring with the nonzero rule, as a PDF viewer would. + /// Aliased, so a pixel is filled exactly when the winding at its sample point is nonzero; + /// with anti-aliasing, coverage sums along the triangles' inner edges round differently by + /// a level in a few pixels. + fn raster(rings: &[Vec]) -> Vec { + let mut pb = tiny_skia::PathBuilder::new(); + for r in rings { + for (j, (x, y)) in r.iter().enumerate() { + if j == 0 { + pb.move_to(*x, *y); + } else { + pb.line_to(*x, *y); + } + } + pb.close(); + } + let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap(); + if let Some(path) = pb.finish() { + let mut paint = tiny_skia::Paint::default(); + paint.set_color_rgba8(0, 0, 0, 255); + paint.anti_alias = false; + pm.fill_path(&path, &paint, tiny_skia::FillRule::Winding, tiny_skia::Transform::identity(), None); + } + pm.data().to_vec() + } + + fn soup(tris: &[[Pt; 3]]) -> Vec> { + tris.iter().map(|t| t.to_vec()).collect() + } + + fn vertices(rings: &[Vec]) -> usize { + rings.iter().map(Vec::len).sum() + } + + /// A fan of a regular polygon around its centre, `n` triangles. + fn fan(c: Pt, r: f32, n: usize, ccw: bool) -> Vec<[Pt; 3]> { + let p = |i: usize| { + let a = std::f32::consts::TAU * (i % n) as f32 / n as f32; + (c.0 + r * a.cos(), c.1 + r * a.sin()) + }; + (0..n).map(|i| if ccw { [c, p(i), p(i + 1)] } else { [c, p(i + 1), p(i)] }).collect() + } + + /// The outline fills the same pixels as the triangles, and is no larger. + fn same_fill(tris: &[[Pt; 3]]) -> Vec> { + let rings = loops(tris).expect("traced"); + let (a, b) = (raster(&rings), raster(&soup(tris))); + let differ = a.iter().zip(&b).filter(|(x, y)| x != y).count(); + assert_eq!(differ, 0, "{rings:?}"); + assert!(vertices(&rings) <= 3 * tris.len()); + rings + } + + #[test] + fn a_fan_becomes_its_rim() { + let tris = fan((32.0, 32.0), 25.0, 40, true); + let rings = same_fill(&tris); + assert_eq!(rings.len(), 1); + assert!(vertices(&rings) < tris.len() + 1, "{} vertices for {} triangles", vertices(&rings), tris.len()); + } + + #[test] + fn a_ring_with_a_hole_keeps_the_hole() { + // A square annulus: outer 8..56, hole 24..40, as eight triangles. + let (o0, o1, i0, i1) = (8.0, 56.0, 24.0, 40.0); + let q = |a: Pt, b: Pt, c: Pt, d: Pt| [[a, b, c], [a, c, d]]; + let mut tris = Vec::new(); + tris.extend(q((o0, o0), (o1, o0), (i1, i0), (i0, i0))); + tris.extend(q((o1, o0), (o1, o1), (i1, i1), (i1, i0))); + tris.extend(q((o1, o1), (o0, o1), (i0, i1), (i1, i1))); + tris.extend(q((o0, o1), (o0, o0), (i0, i0), (i0, i1))); + let rings = same_fill(&tris); + assert_eq!(rings.len(), 2, "{rings:?}"); + let centre = raster(&rings)[(32 * 64 + 32) * 4 + 3]; + assert_eq!(centre, 0, "the hole stays empty"); + } + + #[test] + fn mixed_orientations_overlaps_degenerates_and_t_junctions_fill_the_same() { + let mut tris = fan((20.0, 20.0), 15.0, 12, true); + // Overlapping, the other way round: where they overlap the windings cancel. + tris.extend(fan((34.0, 30.0), 15.0, 9, false)); + // The same triangle twice. + tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]); + tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]); + // A T-junction: one big triangle beside two that split its edge. + tris.push([(2.0, 50.0), (2.0, 62.0), (14.0, 56.0)]); + tris.push([(2.0, 50.0), (-4.0, 53.0), (2.0, 56.0)]); + tris.push([(2.0, 56.0), (-4.0, 59.0), (2.0, 62.0)]); + // Zero-area triangles: collinear, and with a repeated vertex. + tris.push([(5.0, 5.0), (10.0, 10.0), (15.0, 15.0)]); + tris.push([(30.0, 5.0), (30.0, 5.0), (40.0, 8.0)]); + // Vertices a rounding step apart are not merged. + tris.push([(50.0, 10.0), (60.0, 10.0), (55.0, 20.0)]); + tris.push([(60.0, 10.0), (50.0, 10.000_001), (55.0, 2.0)]); + same_fill(&tris); + } + + #[test] + fn nothing_in_nothing_out() { + assert_eq!(loops(&[]), Some(Vec::new())); + assert_eq!(loops(&[[(1.0, 1.0); 3]]), Some(Vec::new())); + } +} diff --git a/crates/io/src/pdf_read.rs b/crates/io/src/pdf_read.rs index 8f7e85208..22a0b1c6d 100644 --- a/crates/io/src/pdf_read.rs +++ b/crates/io/src/pdf_read.rs @@ -687,6 +687,8 @@ impl Collector { style: "Standard".into(), halign: if fit_end.is_some() { HAlign::Fit } else { HAlign::Left }, valign: Default::default(), + backwards: false, + upside_down: false, }; self.add(LAYER_TEXT, run.color, Lineweight::ByLayer, EntityKind::Text(text), 1); } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 01341acf1..47dcf6816 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -40,6 +40,8 @@ fn sample() -> Drawing { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }), ) .unwrap(); @@ -57,6 +59,7 @@ fn sample() -> Drawing { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), ) .unwrap(); @@ -271,6 +274,8 @@ fn block_definition_properties_and_constant_attdefs_roundtrip() { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }; let attdef = |tag: &str, invisible: bool, constant: bool| Attrib { tag: tag.into(), @@ -506,6 +511,315 @@ fn a_layouts_named_ucs_is_the_first_of_its_name_with_its_frame() { assert_eq!(names.named("front", Vec3::new(1.0, 0.0, 0.0), x, y).map(|u| u.name.as_str()), Some("FRONT")); } +/// Many distinct table and multileader style names read in linear time, with the duplicate rule +/// kept: a later style of a name in other case replaces the first, which keeps its place and takes +/// the later style's name, also the Standard style a drawing starts with (#1924). The names share +/// their first 200 bytes, so comparing two costs about that. +#[test] +fn many_distinct_table_and_multileader_style_names_read_quickly() { + const N: usize = 20_000; + let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199)); + // Each style: a dictionary entry naming its handle, and the object (TABLESTYLE margin 40 or + // MLEADERSTYLE arrow size 44 set to `v`). + let mut entries = String::new(); + let mut objects = String::new(); + let mut h = 0x1000; + let mut style = |kind: &str, n: &str, v: f64| { + h += 1; + entries.push_str(&format!("3\n{n}\n350\n{h:X}\n")); + let own = if kind == "TABLESTYLE" { format!("100\nAcDbTableStyle\n40\n{v}\n") } else { format!("100\nAcDbMLeaderStyle\n44\n{v}\n") }; + objects.push_str(&format!("0\n{kind}\n5\n{h:X}\n{own}")); + }; + for (kind, k) in [("TABLESTYLE", 'T'), ("MLEADERSTYLE", 'M')] { + for i in 0..N { + style(kind, &name(k, i), 1.0); + } + style(kind, &name(k, 0).to_ascii_uppercase(), 2.0); + style(kind, "STANDARD", 3.0); + } + let t = format!("0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nA0\n100\nAcDbDictionary\n{entries}{objects}0\nENDSEC\n0\nEOF\n"); + let started = std::time::Instant::now(); + let d = read(t.as_bytes(), "many.dxf").unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + let tables: Vec<(&str, f64)> = d.table_styles.iter().map(|s| (s.name.as_str(), s.margin)).collect(); + let mleaders: Vec<(&str, f64)> = d.mleader_styles.iter().map(|s| (s.name.as_str(), s.arrow_size)).collect(); + for (styles, k) in [(tables, 'T'), (mleaders, 'M')] { + assert_eq!(styles.len(), N + 1); + assert_eq!(styles.first(), Some(&("STANDARD", 3.0))); + assert_eq!(styles.get(1), Some(&(name(k, 0).to_ascii_uppercase().as_str(), 2.0))); + assert_eq!(styles.get(2), Some(&(name(k, 1).as_str(), 1.0))); + } +} + +/// The most multiline styles a file can hold, with long names, read in linear time, with the +/// duplicate rule kept: a later style of a name in other case replaces the first, which keeps its +/// place and takes the later style's name, also the STANDARD style a drawing starts with (#1924). +/// The names share their first 1 000 bytes, so comparing two costs about that. +#[test] +fn many_multiline_style_names_read_quickly() { + const N: usize = 9_998; + let name = |i: usize| format!("L{}{i:06}", "x".repeat(999)); + let style = |n: &str, description: &str| format!("0\nMLINESTYLE\n100\nAcDbMlineStyle\n2\n{n}\n70\n0\n3\n{description}\n71\n1\n49\n0\n"); + let mut t = String::from("0\nSECTION\n2\nOBJECTS\n"); + for i in 0..N { + t.push_str(&style(&name(i), "first")); + } + t.push_str(&style(&name(0).to_ascii_uppercase(), "second")); + t.push_str(&style("standard", "third")); + t.push_str("0\nENDSEC\n0\nEOF\n"); + let started = std::time::Instant::now(); + let d = read(t.as_bytes(), "mlines.dxf").unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + let styles: Vec<(&str, &str)> = d.mline_styles.iter().map(|s| (s.name.as_str(), s.description.as_str())).collect(); + assert_eq!(styles.len(), N + 1); + assert_eq!(styles.first(), Some(&("standard", "third"))); + assert_eq!(styles.get(1), Some(&(name(0).to_ascii_uppercase().as_str(), "second"))); + assert_eq!(styles.get(2), Some(&(name(1).as_str(), "first"))); +} + +/// Many viewport configurations read in linear time, with the rule kept: a record adds a tile to +/// the first configuration of its name, in any case, which keeps its own name, also from a later +/// TABLES section (#1924). The names share their first 200 bytes, so comparing two costs about +/// that. +#[test] +fn many_viewport_configurations_read_quickly() { + const N: usize = 20_000; + let name = |i: usize| format!("V{}{i:06}", "x".repeat(199)); + let record = |n: &str, x: f64| format!("0\nVPORT\n2\n{n}\n70\n0\n10\n0\n20\n0\n11\n1\n21\n1\n12\n{x}\n22\n0\n40\n10\n41\n1\n"); + let mut t = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n"); + for i in 0..N { + t.push_str(&record(&name(i), 1.0)); + } + t.push_str(&record(&name(0).to_ascii_uppercase(), 2.0)); + t.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n"); + t.push_str(&record(&name(1).to_ascii_uppercase(), 3.0)); + t.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n"); + let started = std::time::Instant::now(); + let d = read(t.as_bytes(), "vports.dxf").unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + let configs: Vec<(&str, Vec)> = + d.vports.iter().filter(|c| c.name.starts_with('V')).map(|c| (c.name.as_str(), c.tiles.iter().map(|t| t.center.x).collect())).collect(); + assert_eq!(configs.len(), N); + assert_eq!(configs.first(), Some(&(name(0).as_str(), vec![1.0, 2.0]))); + assert_eq!(configs.get(1), Some(&(name(1).as_str(), vec![1.0, 3.0]))); + assert_eq!(configs.get(2), Some(&(name(2).as_str(), vec![1.0]))); +} + +/// The value of group `code` in each record of type `kind` (its first, if repeated), in file order. +fn first_groups(p: &[(String, String)], kind: &str, code: &str) -> Vec { + let mut out = Vec::new(); + let (mut inside, mut found) = (false, false); + for (c, v) in p { + if c == "0" { + (inside, found) = (v.trim() == kind, false); + } else if inside && !found && c == code { + out.push(v.trim().to_string()); + found = true; + } + } + out +} + +/// Every dictionary entry: its handle to its name. +fn entry_names(p: &[(String, String)]) -> std::collections::HashMap { + let mut out = std::collections::HashMap::new(); + let (mut inside, mut name) = (false, None); + for (c, v) in p { + match c.as_str() { + "0" => (inside, name) = (v.trim() == "DICTIONARY", None), + "3" if inside => name = Some(v.trim().to_string()), + "350" | "360" if inside => { + if let Some(n) = name.take() { + out.insert(v.trim().to_string(), n); + } + } + _ => {} + } + } + out +} + +/// Saving many multileaders among many multileader styles takes linear time (#1924), and each is +/// written as before: pointing at the first style of its name (ignoring case), else at the +/// drawing's first style, with the landing gap of the first style of its name, else the default +/// one. The names share their first 200 bytes, so comparing two costs about that. +#[test] +fn many_multileaders_among_many_styles_save_quickly() { + const N: usize = 10_000; + let name = |i: usize| format!("M{}{i:06}", "x".repeat(199)); + let missing = |i: usize| format!("M{}z{i:05}", "x".repeat(199)); + let mut d = Drawing::new_imperial(); + if let Some(first) = d.mleader_styles.first_mut() { + first.landing_gap = 0.25; + } + d.mleader_styles.extend((0..N).map(|i| MLeaderStyle { name: name(i), landing_gap: 0.5, ..MLeaderStyle::default() })); + d.mleader_styles.push(MLeaderStyle { name: name(N - 1).to_ascii_uppercase(), landing_gap: 0.75, ..MLeaderStyle::default() }); + let mleader = |style: String, x: f64| { + EntityKind::MLeader(MLeader { + leaders: vec![vec![Vec3::new(x, 0.0, 0.0), Vec3::new(x + 1.0, 1.0, 0.0)]], + landing: Vec3::new(x + 2.0, 1.0, 0.0), + dogleg: 0.5, + text: None, + style, + arrow_size: 1.0, + spline: false, + block: None, + }) + }; + for i in 0..N { + d.add(&Space::Model, Common::default(), mleader(missing(i), i as f64)).unwrap(); + } + d.add(&Space::Model, Common::default(), mleader(name(N - 1).to_ascii_uppercase(), -1.0)).unwrap(); + // As a MULTILEADER (R2007 and later): older files get a LEADER and its content instead. + let started = std::time::Instant::now(); + let saved = dxf_2018(&d); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + let p = pairs(&saved); + let entries = entry_names(&p); + let styles: Vec<&str> = first_groups(&p, "MULTILEADER", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect(); + let gaps: Vec = first_groups(&p, "MULTILEADER", "145").iter().filter_map(|v| v.parse().ok()).collect(); + assert_eq!((styles.len(), gaps.len()), (N + 1, N + 1)); + let default_gap = MLeaderStyle::default().landing_gap; + assert!(styles[..N].iter().all(|s| *s == "Standard"), "a missing style points at the first style"); + assert!(gaps[..N].iter().all(|g| *g == default_gap), "a missing style writes the default landing gap"); + assert_eq!((styles[N], gaps[N]), (name(N - 1).as_str(), 0.5), "the first style of the name"); +} + +/// A multileader's own groups (AutoLISP's entity data) carry its style's landing gap, found +/// without the styles a save plans. +#[test] +fn a_multileaders_entity_groups_have_its_styles_landing_gap() { + let mut d = Drawing::new_imperial(); + d.mleader_styles.push(MLeaderStyle { name: "Notes".into(), landing_gap: 0.5, ..MLeaderStyle::default() }); + let m = MLeader { + leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0)]], + landing: Vec3::new(2.0, 1.0, 0.0), + dogleg: 0.5, + text: None, + style: "NOTES".into(), + arrow_size: 1.0, + spline: false, + block: None, + }; + let h = d.add(&Space::Model, Common::default(), EntityKind::MLeader(m)).unwrap(); + let e = d.entity(h).unwrap().clone(); + let (kind, tags) = entity_groups(&d, &e); + assert_eq!(kind, "MULTILEADER"); + assert_eq!(tags.iter().find(|t| t.code == 145).map(|t| t.f64()), Some(0.5)); +} + +/// Many tables from another writer naming a table style the file lacks, among many table styles, +/// read and save in linear time (#1924). Each table takes the text height of the style of its +/// name (ignoring case), else the default one, as before, and is saved pointing at that style, +/// else at the drawing's first one. The names share their first 200 bytes. +#[test] +fn many_tables_among_many_table_styles_read_and_save_quickly() { + const N: usize = 10_000; + let name = |i: usize| format!("T{}{i:06}", "x".repeat(199)); + let missing = format!("T{}z{:05}", "x".repeat(199), 0); + let upper = name(N - 1).to_ascii_uppercase(); + // Tables whose style (342) is a dictionary entry with no TABLESTYLE: the missing name for the + // first N, the last style's name in upper case for the last one. + let mut t = String::from("0\nSECTION\n2\nENTITIES\n"); + for i in 0..=N { + let style = if i < N { "F0000" } else { "F0001" }; + t.push_str(&format!( + "0\nACAD_TABLE\n5\n{:X}\n100\nAcDbBlockReference\n10\n{i}\n20\n0\n30\n0\n100\nAcDbTable\n342\n{style}\n91\n1\n92\n1\n141\n1\n142\n1\n", + 0x100000 + i + )); + } + t.push_str(&format!( + "0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nA0\n100\nAcDbDictionary\n3\n{missing}\n350\nF0000\n3\n{upper}\n350\nF0001\n" + )); + for i in 0..N { + t.push_str(&format!("3\n{}\n350\n{:X}\n", name(i), 0x10000 + i)); + } + for i in 0..N { + t.push_str(&format!("0\nTABLESTYLE\n5\n{:X}\n100\nAcDbTableStyle\n7\n\n140\n0.5\n", 0x10000 + i)); + } + t.push_str("0\nENDSEC\n0\nEOF\n"); + let started = std::time::Instant::now(); + let d = read(t.as_bytes(), "tables.dxf").unwrap(); + let saved = write_dxf(&d); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + let tables: Vec<(&str, f64)> = + d.model.iter().filter_map(|e| if let EntityKind::Table(t) = &e.kind { Some((t.style.as_str(), t.text_height)) } else { None }).collect(); + let default_height = TableStyle::default().text_height; + assert_eq!(tables.len(), N + 1); + assert!(tables[..N].iter().all(|t| *t == (missing.as_str(), default_height)), "a missing style gives the default height"); + assert_eq!(tables[N], (upper.as_str(), 0.5), "the style of the name in other case"); + let p = pairs(&saved); + let entries = entry_names(&p); + let styles: Vec<&str> = first_groups(&p, "ACAD_TABLE", "342").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect(); + assert_eq!(styles.len(), N + 1); + assert!(styles[..N].iter().all(|s| *s == "Standard"), "a missing style points at the first style"); + assert_eq!(styles[N], name(N - 1)); +} + +/// Saving many multilines that each name a style the drawing lacks takes linear time (#1924). As +/// before, each missing style is written once, with the elements of the first multiline naming it, +/// and each multiline points at the first style of its name, ignoring case and surrounding spaces, +/// or at STANDARD when it names none. +#[test] +fn many_multilines_naming_missing_styles_save_quickly() { + const N: usize = 10_000; + let missing = |i: usize| format!("L{}{i:06}", "x".repeat(199)); + let mut d = Drawing::new_imperial(); + let mline = |style: String, x: f64| { + let def = MLineStyle { name: style.clone(), ..MLineStyle::default() }; + let vertex = |x: f64| MLineVertex { p: Vec3::new(x, 0.0, 0.0), cuts: Vec::new() }; + EntityKind::MLine(MLine { + style, + def, + scale: 1.0, + justification: MLineJust::default(), + closed: false, + no_start_caps: false, + no_end_caps: false, + vertices: vec![vertex(x), vertex(x + 1.0)], + }) + }; + for i in 0..N { + d.add(&Space::Model, Common::default(), mline(missing(i), i as f64)).unwrap(); + } + d.add(&Space::Model, Common::default(), mline(missing(N - 1).to_ascii_uppercase(), -1.0)).unwrap(); + let mut padded = mline(format!(" {} ", missing(0)), -2.0); + if let EntityKind::MLine(m) = &mut padded { + m.def.elements = vec![MLineElement { offset: 0.25, ..MLineElement::default() }]; + } + d.add(&Space::Model, Common::default(), padded).unwrap(); + d.add(&Space::Model, Common::default(), mline(" ".into(), -3.0)).unwrap(); + let started = std::time::Instant::now(); + let saved = write_dxf(&d); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + let p = pairs(&saved); + let entries = entry_names(&p); + let styles: Vec<&str> = first_groups(&p, "MLINE", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect(); + let want: Vec = (0..N).map(missing).chain([missing(N - 1), missing(0), "STANDARD".into()]).collect(); + assert_eq!(styles, want); + assert_eq!(first_groups(&p, "MLINESTYLE", "2").len(), N + 1, "STANDARD and each missing style once"); + let offsets: Vec = first_groups(&p, "MLINESTYLE", "49").iter().filter_map(|v| v.parse().ok()).collect(); + assert!(offsets.len() == N + 1 && !offsets.contains(&0.25), "a later multiline does not change the style"); +} + +/// A multiline style whose name has spaces around it in the file is read with the name trimmed, so +/// its multilines, whose lookup trims, find it: a save writes it once and points them at it. +#[test] +fn a_padded_multiline_style_name_is_saved_once() { + let t = "0\nSECTION\n2\nENTITIES\n0\nMLINE\n5\n100\n100\nAcDbEntity\n8\n0\n100\nAcDbMline\n2\n Road \n40\n1\n70\n0\n71\n1\n72\n2\n73\n2\n\ + 10\n0\n20\n0\n30\n0\n11\n0\n21\n0\n31\n0\n12\n1\n22\n0\n32\n0\n13\n0\n23\n1\n33\n0\n74\n2\n41\n0\n41\n0\n75\n0\n74\n2\n41\n0\n41\n0\n75\n0\n\ + 11\n1\n21\n0\n31\n0\n12\n1\n22\n0\n32\n0\n13\n0\n23\n1\n33\n0\n74\n2\n41\n0\n41\n0\n75\n0\n74\n2\n41\n0\n41\n0\n75\n0\n\ + 0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nMLINESTYLE\n5\n200\n100\nAcDbMlineStyle\n2\n Road \n70\n0\n3\npadded\n71\n2\n\ + 49\n0.25\n62\n256\n6\nBYLAYER\n49\n-0.25\n62\n256\n6\nBYLAYER\n0\nENDSEC\n0\nEOF\n"; + let d = read(t.as_bytes(), "padded.dxf").unwrap(); + assert_eq!(d.mline_styles.iter().map(|s| s.name.as_str()).collect::>(), ["STANDARD", "Road"]); + let p = pairs(&write_dxf(&d)); + let entries = entry_names(&p); + assert_eq!(first_groups(&p, "MLINESTYLE", "2"), ["STANDARD", "Road"], "one Road style"); + let styles: Vec<&str> = first_groups(&p, "MLINE", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect(); + assert_eq!(styles, ["Road"]); +} + /// Many layouts with every paper-space object in one of the last of them read in linear time. /// Each object goes to the first layout of its exact name, as before: not to an earlier one whose /// name differs only in case, nor to a later one of the same name (#1924). @@ -715,6 +1029,47 @@ fn pdf_model_fitted_to_sheet() { assert!(write(&d, "x.pdf").unwrap().starts_with(b"%PDF")); } +/// Paper sizes reach the PDF page: the bare B4/B5/B6 are the ISO sizes, the JIS ones are reachable +/// by their explicit names, and the Japanese postcards/envelopes/四六判 plot at theirs. +#[test] +fn pdf_plot_jis_and_japanese_paper_sizes() { + let d = sample(); + for (name, w, h) in [ + ("B4", 708.66, 1000.63), + ("B4 (ISO)", 708.66, 1000.63), + ("B5", 498.90, 708.66), + ("B5-iso", 498.90, 708.66), + ("B6", 354.33, 498.90), + ("B6 (ISO)", 354.33, 498.90), + ("B4 (JIS)", 728.50, 1031.81), + ("JIS B4", 728.50, 1031.81), + ("B5 (JIS)", 515.91, 728.50), + ("b5-jis", 515.91, 728.50), + ("B6 (JIS)", 362.83, 515.91), + ("Japanese Postcard", 283.46, 419.53), + ("はがき", 283.46, 419.53), + ("Japanese Double Postcard", 419.53, 566.93), + ("往復はがき", 419.53, 566.93), + ("Japanese Envelope #3", 340.16, 666.14), + ("長形3号", 340.16, 666.14), + ("Japanese Envelope Kaku #2", 680.31, 941.10), + ("角形2号", 680.31, 941.10), + ("四六判", 360.00, 532.91), + ] { + let bytes = plot(&d, &Space::Model, &serde_json::json!({"paper": name, "landscape": false})).unwrap(); + check_pdf(&bytes); + let (got_w, got_h) = media_box(&bytes); + assert!((got_w - w).abs() < 0.01 && (got_h - h).abs() < 0.01, "{name}: {got_w} x {got_h}, wanted {w} x {h}"); + } + // The ambiguous bare postcard aliases are gone. + assert!(plot(&d, &Space::Model, &serde_json::json!({"paper": "Postcard"})).is_err()); + assert!(plot(&d, &Space::Model, &serde_json::json!({"paper": "Double Postcard"})).is_err()); + // Existing ISO values and the unknown-name error are unchanged. + let (w, h) = media_box(&plot(&d, &Space::Model, &serde_json::json!({"paper": "A3", "landscape": false})).unwrap()); + assert!((w - 841.89).abs() < 0.01 && (h - 1190.55).abs() < 0.01, "A3: {w} x {h}"); + assert!(plot(&d, &Space::Model, &serde_json::json!({"paper": "Z9"})).is_err()); +} + #[test] fn pdf_layout_one_to_one_with_viewport() { let mut d = sample(); @@ -735,6 +1090,9 @@ fn pdf_layout_one_to_one_with_viewport() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }), ) @@ -1110,6 +1468,9 @@ fn viewport_frozen_layers_roundtrip() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) }; @@ -1298,6 +1659,9 @@ fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }); d.add(&paper, Common::default(), vp).unwrap(); @@ -1442,6 +1806,9 @@ fn viewport_layer_colors_roundtrip() { layer_colors: colors, clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) }; @@ -2166,6 +2533,8 @@ fn intl_text(value: &str) -> Text { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, } } @@ -2698,6 +3067,7 @@ fn intl_sample() -> Drawing { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), ) .unwrap(); @@ -2942,6 +3312,7 @@ fn mleader_is_written_as_multileader() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let m = cadcraft_doc::MLeader { leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]], @@ -2976,6 +3347,8 @@ fn attdef_prompt_survives_dxf_roundtrip() { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }; let attdef = |prompt: &str| { EntityKind::AttDef(Attrib { @@ -3445,6 +3818,31 @@ fn mirrored_hatch_extrusion_flips_boundary() { } } +/// Issue #3120: a mirrored HATCH's pattern lines mirror with its boundary. The file draws one +/// line at 55° from (1, 0.5) with offset (-0.2, 0.3) in its OCS; under extrusion (0,0,-1) that +/// is a line at 125° from (-1, 0.5) with offset (0.2, 0.3) in the world. Before, only the hatch +/// angle was mirrored and the line stayed at 55° - 10° + 170° = 215° (35°), off its true slant. +#[test] +fn mirrored_hatch_mirrors_its_pattern_lines() { + let text = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n-1\n2\nMYPAT\n70\n0\n71\n0\n91\n1\n\ + 92\n2\n72\n0\n73\n1\n93\n4\n10\n1\n20\n0\n10\n3\n20\n0\n10\n3\n20\n2\n10\n1\n20\n2\n97\n0\n75\n0\n76\n1\n\ + 52\n10\n41\n2\n77\n0\n78\n1\n53\n55\n43\n1\n44\n0.5\n45\n-0.2\n46\n0.3\n79\n2\n49\n0.5\n49\n-0.25\n98\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "h.dxf").unwrap(); + let h = first(&d, |k| if let EntityKind::Hatch(h) = k { Some(h.clone()) } else { None }); + assert!((h.angle.to_degrees() - 170.0).abs() < 1e-9, "hatch angle {}", h.angle.to_degrees()); + let [l] = h.pattern_lines.as_slice() else { panic!("one pattern line: {:?}", h.pattern_lines) }; + // The line in the world, the way the renderer and the writer place it. + let ang = l.angle.to_radians() + h.angle; + let base = h.origin + Vec2::new(l.origin.0, l.origin.1).rotate(h.angle) * h.scale; + let offset = Vec2::new(l.delta.0, l.delta.1).rotate(ang) * h.scale; + let dir = cadcraft_geom::norm_angle(ang).to_degrees(); + assert!((dir - 125.0).abs() < 1e-9, "line direction {dir}"); + assert!(base.near(Vec2::new(-1.0, 0.5), 1e-9), "base point {base:?}"); + assert!(offset.near(Vec2::new(0.2, 0.3), 1e-9), "offset {offset:?}"); + let dashes: Vec = l.dashes.iter().map(|d| d * h.scale).collect(); + assert_eq!(dashes, vec![0.5, -0.25]); +} + /// Issue #1886: a HATCH in a tilted plane (a terrain face) is drawn as seen from above, not turned /// about the origin. With extrusion (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and /// y = (0, √3/2, 1/2): the square (1,0)..(3,2) lies over (-3,0)..(-1,√3), from z 0 up to z 1. @@ -5089,3 +5487,324 @@ fn a_layer_state_saved_before_masks_restores_everything() { let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect(); assert_eq!(got, [("S", LayerState::ALL, "", "")]); } + +/// The value of group `code` in `tags`. +fn tag_text(tags: &[craft_dxf::Tag], code: i32) -> Option { + tags.iter().find(|t| t.code == code).map(craft_dxf::Tag::str) +} + +/// An INSERT with two attributes, for the records written after it (#1660). +fn insert_with_attribs() -> (Drawing, Handle) { + let text = |value: &str| Text { + insert: Vec3::new(1.0, 2.0, 0.0), + align_pt: None, + height: 2.5, + value: value.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + backwards: false, + upside_down: false, + }; + let attrib = |tag: &str, value: &str| Attrib { + tag: tag.into(), + text: text(value), + invisible: false, + constant: false, + prompt: String::new(), + props: AttribProps::default(), + multiline: None, + modes: AttribModes::default(), + }; + let mut d = Drawing::new_metric(); + let insert = + Insert { block: "B".into(), insert: Vec3::new(10.0, 10.0, 0.0), attribs: vec![attrib("T1", "A1"), attrib("T2", "A2")], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + (d, h) +} + +#[test] +fn an_inserts_records_are_read_one_at_a_time() { + let (mut d, h) = insert_with_attribs(); + let e = d.entity(h).expect("the reference"); + // The reference's own list is its record, with no attribute in it. + let (kind, own) = entity_groups(&d, e); + assert_eq!(kind, "INSERT"); + assert_eq!(tag_text(&own, 66).as_deref(), Some("1")); + // The records after it: each attribute, then the SEQEND. + let first = entity_sub_record(&d, e, 0).expect("the first attribute"); + assert_eq!(first.0, "ATTRIB"); + assert_eq!((tag_text(&first.1, 2).as_deref(), tag_text(&first.1, 1).as_deref()), (Some("T1"), Some("A1"))); + assert_eq!(tag_text(&first.1, 10).as_deref(), Some("1.0"), "its place is written as for the file"); + let second = entity_sub_record(&d, e, 1).expect("the second attribute"); + assert_eq!((tag_text(&second.1, 2).as_deref(), tag_text(&second.1, 1).as_deref()), (Some("T2"), Some("A2"))); + let seqend = entity_sub_record(&d, e, 2).expect("the SEQEND"); + assert_eq!(seqend.0, "SEQEND"); + assert!(entity_sub_record(&d, e, 3).is_none(), "past the last record"); + // They have no handle or owner of their own in the drawing: their names are LISP's. + for tags in [&first.1, &second.1, &seqend.1] { + assert!(tags.iter().all(|t| t.code != 5 && t.code != 330), "{tags:?}"); + } + // An entity with no records after it has none, at any index. + let line = d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).expect("line"); + let e = d.entity(line).expect("the line"); + assert!(entity_sub_record(&d, e, 0).is_none()); +} + +#[test] +fn an_attributes_value_reads_as_lisp_text() { + let (mut d, h) = insert_with_attribs(); + // A caret is written `^ ` and read back as the caret LISP typed: what `entget` lists is + // what `entmod` takes again. + d.modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind + && let Some(a) = i.attribs.first_mut() + { + a.text.value = "10^2".into(); + } + }) + .expect("modify"); + let e = d.entity(h).expect("the reference"); + let (_, tags) = entity_sub_record(&d, e, 0).expect("the first attribute"); + assert_eq!(tag_text(&tags, 1).as_deref(), Some("10^2")); +} + +/// Reading every attribute of one reference examines the block definition once, and an edit of +/// the definition once more. +#[test] +fn reading_attributes_scans_the_definition_once() { + const M: usize = 32; + let tags: Vec = (0..M).map(|i| format!("T{i}")).collect(); + let mut d = Drawing::new_metric(); + let h = add_attributed(&mut d, "B", 1, &tags, "WALLS"); + crate::dxf_write::reset_attdef_definition_visits(); + let e = d.entity(h).expect("the reference").clone(); + for i in 0..M { + let (kind, tags) = entity_sub_record(&d, &e, i).expect("attribute"); + assert_eq!(kind, "ATTRIB"); + assert_eq!(tag_text(&tags, 8).as_deref(), Some("WALLS")); + } + assert_eq!(crate::dxf_write::attdef_definition_visits(), M as u64, "one pass over the definition, not one scan per attribute"); + // An edit of the definition is read on the next read, with one more pass. + set_attdef_layer(&mut d, "B", "DOOR"); + let before = crate::dxf_write::attdef_definition_visits(); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("DOOR")); + assert_eq!(crate::dxf_write::attdef_definition_visits() - before, M as u64, "the edit builds the index once"); +} + +/// An attribute with value V and `tag`, for the definition tests below. +fn plain_attrib(tag: &str) -> Attrib { + Attrib { + tag: tag.into(), + text: Text { + insert: 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: HAlign::Left, + valign: VAlign::Baseline, + backwards: false, + upside_down: false, + }, + invisible: false, + constant: false, + prompt: String::new(), + props: AttribProps::default(), + multiline: None, + modes: AttribModes::default(), + } +} + +/// Block `name` with an ATTDEF per tag on `layer`, its handles from `first` up, and a reference +/// to it with the same attributes. The reference's handle. +fn add_attributed(d: &mut Drawing, name: &str, first: u64, tags: &[String], layer: &str) -> Handle { + let mut block = Block::new(name); + for (i, tag) in tags.iter().enumerate() { + let mut e = Entity::new(Handle(first + i as u64), EntityKind::AttDef(plain_attrib(tag))); + e.common.layer = layer.into(); + block.entities.push(e); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + let insert = Insert { block: name.into(), attribs: tags.iter().map(|t| plain_attrib(t)).collect(), ..Insert::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add") +} + +/// Block `name`'s first ATTDEF moved to `layer`: one edit of the definition's store. +fn set_attdef_layer(d: &mut Drawing, name: &str, layer: &str) { + let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block")); + let h = b.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).expect("an ATTDEF"); + assert!(b.entities.modify(h, |e| e.common.layer = layer.into())); +} + +/// Block B with ATTDEF T on layer BASE and ATTDEF U on layer DOOR, and a reference to it with +/// both attributes. The reference's handle. +fn add_on_two_layers(d: &mut Drawing) -> Handle { + let h = add_attributed(d, "B", 1, &["T".to_string(), "U".to_string()], "DOOR"); + set_attdef_layer(d, "B", "BASE"); + h +} + +/// Block `name`'s ATTDEFs given `tags` in their order, so a tag can pass to another ATTDEF's +/// handle: one edit of the definition's store for each ATTDEF. +fn set_attdef_tags(d: &mut Drawing, name: &str, tags: &[&str]) { + let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block")); + let handles: Vec = b.entities.iter().filter(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).collect(); + assert_eq!(handles.len(), tags.len(), "a tag for each ATTDEF"); + for (h, tag) in handles.into_iter().zip(tags) { + assert!(b.entities.modify(h, |e| { + if let EntityKind::AttDef(ad) = &mut e.kind { + ad.tag = (*tag).into(); + } + })); + } +} + +/// The layer reference `h`'s first ATTRIB record is read on. +fn read_attrib_layer(d: &Drawing, h: Handle) -> Option { + let e = d.entity(h)?; + let (_, tags) = entity_sub_record(d, e, 0)?; + tag_text(&tags, 8) +} + +/// The layer the first ATTRIB of `d`'s DXF is written on. +fn written_attrib_layer(d: &Drawing) -> Option { + let text = write_dxf(d); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let at = lines.windows(2).position(|w| w == ["0", "ATTRIB"])?; + let pairs = lines.get(at + 2..)?.chunks(2); + pairs.take_while(|p| p.first() != Some(&"0")).find(|p| p.first() == Some(&"8")).and_then(|p| p.get(1)).map(|s| s.to_string()) +} + +/// Two copies of one drawing, each with its definition edited: each reads and writes its own +/// definition's properties, whichever was read first. T stays with the first ATTDEF in one copy +/// and passes to the second in the other, so an index kept from one copy names the wrong ATTDEF +/// in the other. +#[test] +fn copies_edited_apart_read_their_own_definitions() { + let mut d = Drawing::new_metric(); + let h = add_on_two_layers(&mut d); + let (mut a, mut b) = (d.clone(), d.clone()); + set_attdef_layer(&mut a, "B", "WALLS"); + set_attdef_tags(&mut b, "B", &["U", "T"]); + assert_eq!(read_attrib_layer(&a, h).as_deref(), Some("WALLS")); + assert_eq!(read_attrib_layer(&b, h).as_deref(), Some("DOOR"), "the other copy's edit is its own"); + assert_eq!(written_attrib_layer(&b).as_deref(), Some("DOOR")); + assert_eq!(written_attrib_layer(&a).as_deref(), Some("WALLS")); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("BASE"), "the drawing both came from is unchanged"); +} + +/// Undo back to a state, then a different edit of the definition: the edit that was undone is +/// not read or written again. The second edit passes T to the other ATTDEF, so the index of +/// the undone edit names the wrong one. +#[test] +fn an_edit_after_undo_reads_its_own_definition() { + let mut d = Drawing::new_metric(); + let h = add_on_two_layers(&mut d); + let mut undone = d.clone(); + set_attdef_layer(&mut undone, "B", "WALLS"); + assert_eq!(read_attrib_layer(&undone, h).as_deref(), Some("WALLS")); + // Undo: the drawing before the edit, then another edit, read nothing in between. + let mut redone = d.clone(); + set_attdef_tags(&mut redone, "B", &["U", "T"]); + assert_eq!(written_attrib_layer(&redone).as_deref(), Some("DOOR")); + assert_eq!(read_attrib_layer(&redone, h).as_deref(), Some("DOOR")); +} + +/// Reads that alternate between two references of two blocks examine each definition once. +#[test] +fn alternating_definitions_are_each_indexed_once() { + const M: usize = 64; + let tags: Vec = (0..M).map(|i| format!("T{i}")).collect(); + let mut d = Drawing::new_metric(); + let first = add_attributed(&mut d, "B1", 1, &tags, "ONE"); + let second = add_attributed(&mut d, "B2", 1 + M as u64, &tags, "TWO"); + let (first, second) = (d.entity(first).expect("first").clone(), d.entity(second).expect("second").clone()); + crate::dxf_write::reset_attdef_definition_visits(); + for i in 0..M { + for (e, layer) in [(&first, "ONE"), (&second, "TWO")] { + let (_, tags) = entity_sub_record(&d, e, i).expect("attribute"); + assert_eq!(tag_text(&tags, 8).as_deref(), Some(layer)); + } + } + assert_eq!(crate::dxf_write::attdef_definition_visits(), 2 * M as u64, "each definition is read once, not once per read"); +} + +/// Of two ATTDEFs whose tags differ only in case, the first is the attribute's definition. +#[test] +fn the_first_definition_of_a_tag_in_any_case_is_used() { + let mut block = Block::new("C"); + for (i, (tag, layer)) in [("t", "FIRST"), ("T", "SECOND")].into_iter().enumerate() { + let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag))); + e.common.layer = layer.into(); + block.entities.push(e); + } + let mut d = Drawing::new_metric(); + d.blocks.insert("C".into(), std::sync::Arc::new(block)); + let insert = Insert { block: "C".into(), attribs: vec![plain_attrib("T")], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST")); +} + +/// A definition with more distinct tags than the index may store (`1 << 18`) is not cached. +/// The first read builds and drops one bounded index and remembers the state; later reads go +/// straight to one scan that stops at the first match. The first ATTDEF of the tag still wins, +/// in any case. +#[test] +fn an_oversized_definition_is_not_indexed() { + const LIMIT: usize = 1 << 18; + // One extra distinct tag past the budget, plus a second ATTDEF of the first tag in + // another case, so the first match is not the only entity of that tag. + let mut tags = Vec::with_capacity(LIMIT + 2); + tags.push("Ab".to_string()); + tags.push("AB".to_string()); + for i in 0..LIMIT { + tags.push(format!("U{i}")); + } + let mut block = Block::new("HUGE"); + for (i, tag) in tags.iter().enumerate() { + let layer = if i == 0 { "FIRST" } else { "SECOND" }; + let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag))); + e.common.layer = layer.into(); + block.entities.push(e); + } + let mut d = Drawing::new_metric(); + d.blocks.insert("HUGE".into(), std::sync::Arc::new(block)); + let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib("ab")], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + crate::dxf_write::reset_attdef_definition_visits(); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST")); + let first = crate::dxf_write::attdef_definition_visits(); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST")); + let second = crate::dxf_write::attdef_definition_visits() - first; + // The failed index walks every entity (the last tag is the one past the budget), then + // the scan reads the first entity, where the tag matches. + assert_eq!(first, (LIMIT as u64) + 3, "one bounded pass, then the first match"); + assert_eq!(second, 1, "the state is remembered as too large: the next read scans to the first match only"); +} + +/// An attribute whose ATTDEF lies past the index budget, at the end of an oversized definition, +/// still reads and writes that definition's properties: the scan for a definition past the +/// budget covers all of it. +#[test] +fn a_definition_past_the_index_budget_matches_its_last_tag() { + const LIMIT: usize = 1 << 18; + let mut block = Block::new("HUGE"); + for i in 0..=LIMIT { + let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(&format!("U{i}")))); + e.common.layer = if i == LIMIT { "LAST".into() } else { "OTHER".into() }; + block.entities.push(e); + } + let mut d = Drawing::new_metric(); + d.blocks.insert("HUGE".into(), std::sync::Arc::new(block)); + let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib(&format!("u{LIMIT}"))], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("LAST"), "entget reads the matching definition"); + assert_eq!(written_attrib_layer(&d).as_deref(), Some("LAST"), "the written ATTRIB keeps the definition's layer"); +} diff --git a/crates/io/tests/it/acad_interop.rs b/crates/io/tests/it/acad_interop.rs index ab0434a48..b3ecd29e3 100644 --- a/crates/io/tests/it/acad_interop.rs +++ b/crates/io/tests/it/acad_interop.rs @@ -32,6 +32,8 @@ fn text(value: &str, at: Vec3, h: HAlign, v: VAlign) -> EntityKind { style: "Standard".into(), halign: h, valign: v, + backwards: false, + upside_down: false, }) } @@ -220,6 +222,8 @@ fn justified_text_made_here_writes_its_baseline_start_for_every_justification() style: "Standard".into(), halign: h, valign: v, + backwards: false, + upside_down: false, }; d.add(&Space::Model, Common::default(), EntityKind::Text(t.clone())).unwrap(); made.push(t); @@ -241,6 +245,94 @@ fn justified_text_made_here_writes_its_baseline_start_for_every_justification() assert_eq!(text_starts(&write_dxf(&back)), starts); } +fn with_linear_factor(mut d: Drawing, factor: f64) -> Drawing { + d.dim_styles.last_mut().expect("S25").linear_factor = factor; + d +} + +#[test] +fn stored_linear_measurements_include_dimlfac_but_angles_stay_in_radians() { + let linear_case = with_linear_factor(linear(0.0), 100.0); + assert!((stored_measurement(&linear_case) - 10000.0).abs() < 1e-7, "linear and its DIMLFAC=100 style"); + let aligned = with_linear_factor(s25(DimKind::Aligned, Vec3::ZERO, Vec3::new(3.0, 4.0, 0.0), Vec3::new(0.0, -5.0, 0.0)), 100.0); + assert!((stored_measurement(&aligned) - 500.0).abs() < 1e-7, "aligned"); + let radius = with_linear_factor(s25(DimKind::Radius, Vec3::ZERO, Vec3::ZERO, Vec3::ZERO), 100.0); + let radius = { + let mut d = radius; + let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle; + d.modify_entity(h, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.p15 = Vec3::new(2.5, 0.0, 0.0); + } + }) + .unwrap(); + d + }; + assert!((stored_measurement(&radius) - 250.0).abs() < 1e-7, "radius"); + let diameter = with_linear_factor(s25(DimKind::Diameter, Vec3::ZERO, Vec3::ZERO, Vec3::ZERO), 100.0); + let diameter = { + let mut d = diameter; + let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle; + d.modify_entity(h, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.p15 = Vec3::new(5.0, 0.0, 0.0); + } + }) + .unwrap(); + d + }; + assert!((stored_measurement(&diameter) - 500.0).abs() < 1e-7, "diameter"); + let ordinate = with_linear_factor(s25(DimKind::Ordinate { x_type: true }, Vec3::new(4.0, 0.0, 0.0), Vec3::new(5.0, 1.0, 0.0), Vec3::ZERO), 100.0); + let ordinate_measurement = stored_measurement_dxf(&ordinate); + assert!((ordinate_measurement - 400.0).abs() < 1e-7, "ordinate: {ordinate_measurement}"); + let arc = with_linear_factor( + s25( + DimKind::ArcLength, + Vec3::new(2.0, 0.0, 0.0), + Vec3::new(0.0, 2.0, 0.0), + Vec3::new(std::f64::consts::SQRT_2, std::f64::consts::SQRT_2, 0.0), + ), + 100.0, + ); + assert!((stored_measurement_dxf(&arc) - std::f64::consts::PI * 100.0).abs() < 1e-7, "arc length"); + let overridden = with_linear_factor(linear(0.0), 100.0); + let overridden = { + let mut d = overridden; + let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle; + d.modify_entity(h, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.overrides.insert("DIMLFAC".into(), serde_json::json!(2.0)); + } + }) + .unwrap(); + d + }; + assert!((stored_measurement(&overridden) - 200.0).abs() < 1e-9, "a dimension's own DIMLFAC override wins"); + let angular = with_linear_factor(s25(DimKind::Angular3P, polar(0.0, 20.0), polar(90.0, 20.0), polar(45.0, 15.0)), 100.0); + assert!((stored_measurement(&angular) - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "DIMLFAC never scales an angle"); + let control = with_linear_factor(linear(0.0), 1.0); + assert!((stored_measurement(&control) - 100.0).abs() < 1e-9, "DIMLFAC=1 keeps the raw measurement"); +} + +#[test] +fn negative_dimlfac_follows_the_dimension_space() { + let model = with_linear_factor(linear(0.0), -2.0); + assert!((stored_measurement(&model) - 100.0).abs() < 1e-9, "model space uses 1.0 when DIMLFAC is negative"); + + let entity = model.model.iter().next().expect("the linear dimension"); + let mut paper = Drawing::new_metric(); + paper.dim_styles = model.dim_styles.clone(); + paper.add(&Space::Paper("Layout1".into()), entity.common.clone(), entity.kind.clone()).unwrap(); + assert!((stored_measurement(&paper) - 200.0).abs() < 1e-9, "paper space uses the absolute DIMLFAC"); +} + +/// Group 42 in CADCraft's direct DXF output. +fn stored_measurement_dxf(d: &Drawing) -> f64 { + let t = tags(&write_dxf(d)); + let dim = t.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap(); + t[dim..].iter().find(|(c, _)| *c == 42).unwrap().1.parse().unwrap() +} + /// Group 42 of a dimension in the DXF AutoCAD reads from `d`'s DWG. fn stored_measurement(d: &Drawing) -> f64 { cadcraft_io::dwg_worker::allow_in_process(); diff --git a/crates/io/tests/it/annotative_block_contexts.rs b/crates/io/tests/it/annotative_block_contexts.rs new file mode 100644 index 000000000..545d8b7ba --- /dev/null +++ b/crates/io/tests/it/annotative_block_contexts.rs @@ -0,0 +1,782 @@ +//! An annotative block survives a save: its BLOCK_RECORD keeps the `AcadAnnotative` xdata and +//! uniform scaling (281), and a reference keeps its annotation scale contexts (the reference's +//! scale at each annotation scale), pointing at the same scales and following the reference when +//! it is moved, turned or scaled. Without them AutoCAD scales the reference by its units, or once +//! more by the current annotation scale. +//! +//! The fixture is synthetic: block SIGN (metres) with one line, a reference at (10, 20) scaled 5, +//! and its contexts for 1:5 (default, scale 5) and 1:1 (scale 1). + +use cadcraft_doc::geom::Vec2; +use cadcraft_doc::{Drawing, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +const FIXTURE: &str = " +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $INSUNITS +70 6 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 1 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 SIGN +70 6 +280 1 +281 1 +1001 AcadAnnotative +1000 AnnotativeData +1002 { +1070 1 +1070 1 +1002 } +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 SIGN +70 0 +10 0 +20 0 +30 0 +3 SIGN +1 +0 LINE +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbLine +10 0 +20 0 +30 0 +11 1 +21 0 +31 0 +0 ENDBLK +5 22 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 INSERT +5 40 +102 {ACAD_XDICTIONARY +360 41 +102 } +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockReference +2 SIGN +10 10 +20 20 +30 0 +41 5 +42 5 +43 5 +50 0 +66 1 +0 ATTRIB +5 70 +102 {ACAD_XDICTIONARY +360 71 +102 } +330 40 +100 AcDbEntity +8 0 +100 AcDbText +10 15 +20 30 +30 0 +40 1 +1 X +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND +5 77 +330 40 +100 AcDbEntity +8 0 +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +3 ACAD_SCALELIST +350 50 +0 DICTIONARY +5 50 +330 C +100 AcDbDictionary +281 1 +3 A0 +350 51 +3 A1 +350 52 +0 SCALE +5 51 +330 50 +100 AcDbScale +70 0 +300 1:1 +140 1 +141 1 +290 0 +0 SCALE +5 52 +330 50 +100 AcDbScale +70 0 +300 1:5 +140 1 +141 5 +290 0 +0 DICTIONARY +5 41 +330 40 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 42 +0 DICTIONARY +5 42 +330 41 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 43 +0 DICTIONARY +5 43 +330 42 +100 AcDbDictionary +281 1 +3 *A1 +350 44 +3 *A2 +350 45 +0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS +5 44 +330 43 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 52 +50 0 +10 10 +20 20 +30 0 +41 5 +42 5 +43 5 +0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS +5 45 +330 43 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 51 +50 0 +10 10 +20 20 +30 0 +41 1 +42 1 +43 1 +0 DICTIONARY +5 71 +330 70 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 73 +0 DICTIONARY +5 73 +330 71 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 74 +0 DICTIONARY +5 74 +330 73 +100 AcDbDictionary +281 1 +3 *A1 +350 75 +3 *A2 +350 76 +0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS +5 75 +330 74 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 52 +70 0 +50 0 +10 15 +20 30 +11 15 +21 30 +290 0 +0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS +5 76 +330 74 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 51 +70 0 +50 0 +10 11 +20 22 +11 11 +21 22 +290 0 +0 ENDSEC +0 EOF +"; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// A written file's records: (type, groups). +fn records(text: &str) -> Vec<(String, Vec<(i32, String)>)> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec<(String, Vec<(i32, String)>)> = Vec::new(); + for pair in lines.chunks(2) { + let (Some(code), Some(value)) = (pair.first().and_then(|c| c.parse::().ok()), pair.get(1)) else { continue }; + if code == 0 { + out.push((value.to_string(), Vec::new())); + } else if let Some((_, tags)) = out.last_mut() { + tags.push((code, value.to_string())); + } + } + out +} + +fn get(tags: &[(i32, String)], code: i32) -> Option<&str> { + tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str()) +} + +/// The written block reference contexts: (scale name, default, insertion, rotation, x scale). +fn contexts(text: &str) -> Vec<(String, bool, Vec2, f64, f64)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN); + recs.iter() + .filter(|(k, _)| k == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| { + let scale = get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(); + (scale, get(t, 290) == Some("1"), Vec2::new(num(t, 10), num(t, 20)), num(t, 50), num(t, 41)) + }) + .collect() +} + +/// The written attribute contexts: (scale name, insertion point), and the ATTRIB they hang on +/// (its tag, through its extension dictionary). +fn attribute_contexts(text: &str) -> Vec<(String, Vec2)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN); + recs.iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| (get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(), Vec2::new(num(t, 10), num(t, 20)))) + .collect() +} + +fn read() -> Drawing { + read_dxf(dxf(FIXTURE).as_bytes()).unwrap() +} + +#[test] +fn an_annotative_block_keeps_its_record_and_its_reference_s_contexts() { + let d = read(); + let b = d.block("SIGN").unwrap(); + assert!(b.annotative && b.scale_uniformly && b.units == 6); + let text = write_dxf(&d); + // The record: units, uniform scaling and the annotative flag. + let recs = records(&text); + let (_, rec) = recs.iter().find(|(k, t)| k == "BLOCK_RECORD" && get(t, 2) == Some("SIGN")).unwrap(); + assert_eq!((get(rec, 70), get(rec, 281)), (Some("6"), Some("1"))); + assert!(rec.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"), "{rec:?}"); + // The contexts, as read, at the same scales. + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got, [("1:1".to_string(), false, 1.0), ("1:5".to_string(), true, 5.0)]); + assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0) && c.3 == 0.0)); + // Read back: still annotative. + assert!(read_dxf(text.as_bytes()).unwrap().block("SIGN").unwrap().annotative); + // The attribute's contexts, on the written attribute (its handle is new), as read. + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); + let recs = records(&text); + let (_, attrib) = recs.iter().find(|(k, t)| k == "ATTRIB" && get(t, 2) == Some("TAG")).unwrap(); + assert!(attrib.iter().any(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY"), "{attrib:?}"); +} + +#[test] +fn an_attribute_s_contexts_follow_its_reference() { + // Moved 5 along x and scaled 2 (the attribute with it, as MOVE and SCALE move it): at 1:5 + // the attribute goes to (15 + 10, 20 + 20); at 1:1, through the reference's 1:1 context (now + // at (15, 20), scale 2), to (15 + 2, 20 + 4). + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + i.scale = i.scale * 2.0; + for a in &mut i.attribs { + a.text.insert = cadcraft_doc::geom::Vec3::new(25.0, 40.0, 0.0); + a.text.align_pt = Some(a.text.insert); + } + } + }) + .unwrap(); + let mut actx = attribute_contexts(&write_dxf(&d)); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + assert_eq!(actx.len(), 2); + assert!(near(actx[0].1, 17.0, 24.0), "1:1 {:?}", actx[0]); + assert!(near(actx[1].1, 25.0, 40.0), "1:5 {:?}", actx[1]); +} + +#[test] +fn a_reference_s_contexts_follow_it_when_it_is_moved_turned_and_scaled() { + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + i.rotation = 30f64.to_radians(); + i.scale = i.scale * 2.0; + } + }) + .unwrap(); + let mut ctx = contexts(&write_dxf(&d)); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + for (scale, _, at, rot, sx) in &ctx { + assert!((at.x - 15.0).abs() < 1e-9 && (at.y - 20.0).abs() < 1e-9, "{scale}: {at:?}"); + assert!((rot - 30.0).abs() < 1e-9, "{scale}: {rot}"); + // Each context doubles: 1 → 2 at 1:1, 5 → 10 at 1:5. + let want = if scale == "1:1" { 2.0 } else { 10.0 }; + assert!((sx - want).abs() < 1e-9, "{scale}: {sx}"); + } + assert_eq!(ctx.len(), 2); +} + +/// A reference's annotation contexts as CADCraft's model keeps them: (scale's SCALE handle, +/// rotation, x scale) of each, by the order kept. +fn kept_contexts(d: &Drawing) -> Vec<(f64, f64)> { + let num = |o: &cadcraft_doc::foreign::ForeignObject, c: i32| { + o.tags.iter().find(|t| t.code == c).and_then(|t| t.value.trim().parse::().ok()).unwrap_or(f64::NAN) + }; + d.foreign.objects.iter().filter(|o| o.kind == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS").map(|o| (num(o, 50), num(o, 41))).collect() +} + +/// A DWG save leaves the reference's contexts out, and the block's annotative flag with them: +/// the DWG bridge doesn't convert block reference contexts yet (storytold/craft-libs#2005), and +/// the flag without them would have AutoCAD scale the reference by the annotation scale once +/// more. The reference comes back at its own scale; DXF keeps both. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_dwg_save_leaves_the_reference_s_contexts_out() { + cadcraft_io::dwg_worker::allow_in_process(); + let d = read(); + let r = Handle::parse_hex("40").unwrap(); + let scale = |d: &Drawing| match d.entity(r).map(|e| &e.kind) { + Some(cadcraft_doc::EntityKind::Insert(i)) => i.scale.x, + _ => f64::NAN, + }; + let back = cadcraft_io::read(&cadcraft_io::write(&d, "x.dwg").unwrap(), "x.dwg").unwrap(); + assert!(kept_contexts(&back).is_empty(), "{:?}", kept_contexts(&back)); + assert!((scale(&back) - scale(&d)).abs() < 1e-9, "{} vs {}", scale(&back), scale(&d)); + assert!(!kept_contexts(&read_dxf(write_dxf(&d).as_bytes()).unwrap()).is_empty(), "DXF keeps them"); +} + +/// Every written ACDB_ANNOTATIONSCALES dictionary entry names a written context, and every +/// written context is listed once. +fn listed_contexts(text: &str) -> usize { + let recs = records(text); + let handles: std::collections::HashSet<&str> = + recs.iter().filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")).filter_map(|(_, t)| get(t, 5)).collect(); + let mut listed = 0; + for (_, t) in recs.iter().filter(|(k, _)| k == "DICTIONARY") { + for (c, v) in t { + if *c == 350 && handles.contains(v.as_str()) { + listed += 1; + } + } + } + assert_eq!(listed, handles.len(), "contexts listed in their dictionaries"); + listed +} + +#[test] +fn a_context_whose_scale_was_deleted_is_not_written() { + let mut d = read(); + d.scales.retain(|s| s.name != "1:1"); + let text = write_dxf(&d); + let ctx = contexts(&text); + assert_eq!(ctx.iter().map(|c| (c.0.as_str(), c.1)).collect::>(), [("1:5", true)]); + let actx = attribute_contexts(&text); + assert_eq!(actx.iter().map(|c| c.0.as_str()).collect::>(), ["1:5"]); + assert_eq!(listed_contexts(&text), 2); +} + +#[test] +fn an_annotative_reference_s_contexts_follow_its_scales() { + // CADCraft's model makes the reference annotative at 1:5 and a new 1:2 (1:1 no longer): + // the 1:1 contexts go, 1:2 ones are made from the default 1:5 ones, scaled 2/5 about the + // reference's insertion point. + let mut d = read(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.push(half.clone()); + let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![five, half]).unwrap(); + let text = write_dxf(&d); + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!((got[0].0.as_str(), got[0].1), ("1:2", false)); + assert!((got[0].2 - 2.0).abs() < 1e-9, "{got:?}"); + assert_eq!(got[1], ("1:5".to_string(), true, 5.0)); + assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0))); + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx.len(), 2, "{actx:?}"); + assert_eq!(actx[0].0, "1:2"); + assert!((actx[0].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); + assert_eq!(actx[1], ("1:5".to_string(), Vec2::new(15.0, 30.0))); + assert_eq!(listed_contexts(&text), 4); + // Read back, the reference keeps them (and nothing points at a missing scale). + let back = read_dxf(text.as_bytes()).unwrap(); + assert!(contexts(&write_dxf(&back)).iter().all(|c| c.0 != "?")); +} + +/// The fixture with every handle moved up to just past 2^48 (AutoCAD writes handles that high): +/// the reference (40) lands on 2^48 + 1. +fn far_handles(src: &str) -> String { + const SHIFT: u64 = (1 << 48) - 0x3F; + let is_handle = |code: i32| matches!(code, 5 | 105 | 320..=369 | 390..=399 | 480 | 481 | 1005); + let mut out = String::new(); + for line in src.lines() { + let (code, value) = line.trim().split_once(' ').unwrap_or((line.trim(), "")); + let moved = match (code.parse::(), u64::from_str_radix(value, 16)) { + (Ok(c), Ok(h)) if is_handle(c) && h != 0 => format!("{:X}", h + SHIFT), + _ => value.to_string(), + }; + out.push_str(&format!("{code} {moved}\n")); + } + out +} + +#[test] +fn new_contexts_get_their_own_handles_when_the_file_s_are_above_2_pow_48() { + // As in the test above, but every file handle is above 2^48: the new 1:2 contexts and their + // scale take handles no other object has. + let mut d = read_dxf(dxf(&far_handles(FIXTURE)).as_bytes()).unwrap(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.push(half.clone()); + let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap(); + let reference = Handle::parse_hex("1000000000001").unwrap(); + d.modify_entity(reference, |e| e.common.anno_scales = vec![five, half]).unwrap(); + let text = write_dxf(&d); + let mut names: Vec = contexts(&text).into_iter().map(|c| c.0).collect(); + names.sort(); + assert_eq!(names, ["1:2", "1:5"]); + assert_eq!(attribute_contexts(&text).len(), 2); + let mut handles: Vec = records(&text).iter().filter_map(|(_, t)| get(t, 5).map(str::to_string)).collect(); + let n = handles.len(); + handles.sort(); + handles.dedup(); + assert_eq!(handles.len(), n, "every written handle is unique"); +} + +#[test] +fn two_attributes_with_one_tag_keep_their_own_contexts() { + // A second attribute TAG on the reference, with its own extension dictionary (no contexts + // in it): each written ATTRIB gets its own dictionary, the first keeps the contexts. + let second = " +0 ATTRIB +5 80 +102 {ACAD_XDICTIONARY +360 81 +102 } +330 40 +100 AcDbEntity +8 0 +100 AcDbText +10 1 +20 2 +30 0 +40 1 +1 Y +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND"; + let objs = " +0 DICTIONARY +5 81 +330 80 +100 AcDbDictionary +280 1 +281 1 +3 OTHER +360 82 +0 XRECORD +5 82 +330 81 +100 AcDbXrecord +1 kept +0 ENDSEC +0 EOF"; + let src = FIXTURE.replacen("0 SEQEND", second, 1); + let at = src.rfind("0 ENDSEC").unwrap(); + let src = format!("{}{objs}", &src[..at]); + let d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let text = write_dxf(&d); + let recs = records(&text); + let xdict = |t: &[(i32, String)]| { + let i = t.iter().position(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY")?; + t.get(i + 1).map(|(_, v)| v.clone()) + }; + let attribs: Vec<(String, Option)> = + recs.iter().filter(|(k, _)| k == "ATTRIB").map(|(_, t)| (get(t, 1).unwrap_or_default().to_string(), xdict(t))).collect(); + assert_eq!(attribs.len(), 2, "{attribs:?}"); + let (x, y) = (attribs[0].1.clone().unwrap(), attribs[1].1.clone().unwrap()); + assert_ne!(x, y, "{attribs:?}"); + // The first attribute's dictionary leads to its contexts, the second's to the xrecord. + let owner_of = |h: &str| recs.iter().find(|(_, t)| get(t, 5) == Some(h)).and_then(|(_, t)| get(t, 330)).map(str::to_string); + let xrec = recs.iter().find(|(k, t)| k == "XRECORD" && get(t, 1) == Some("kept")).map(|(_, t)| get(t, 5).unwrap().to_string()).unwrap(); + assert_eq!(owner_of(&xrec), Some(y)); + assert_eq!(attribute_contexts(&text).len(), 2); +} + +#[test] +fn new_contexts_come_from_one_whose_scale_remains() { + // The default context's scale (1:5) is deleted, and the reference is annotative at 1:1 and a + // new 1:2: the 1:2 contexts are made from the 1:1 ones (scale 1 → 2 about the insertion + // point), and 1:1 becomes the default. + let mut d = read(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.retain(|s| s.name != "1:5"); + d.scales.push(half.clone()); + let one = d.scales.iter().find(|s| s.name == "1:1").cloned().unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![one, half]).unwrap(); + let text = write_dxf(&d); + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got, [("1:1".to_string(), true, 1.0), ("1:2".to_string(), false, 2.0)]); + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx.len(), 2, "{actx:?}"); + assert_eq!(actx[0], ("1:1".to_string(), Vec2::new(11.0, 22.0))); + assert_eq!(actx[1].0, "1:2"); + assert!((actx[1].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); + assert_eq!(listed_contexts(&text), 4); +} + +/// The written context of the block reference at scale `name`: (insertion, rotation). +fn context_at(text: &str, name: &str) -> (Vec2, f64) { + contexts(text).into_iter().find(|c| c.0 == name).map(|c| (c.2, c.3)).unwrap() +} + +#[test] +fn an_unchanged_reference_keeps_its_contexts_when_its_default_one_is_elsewhere() { + // The reference sits at (11, 20) while its default context says (10, 20): saved unchanged, + // every context is written as read (what moves them is what the reference did since). + let d = read_dxf(dxf(&FIXTURE.replace("2 SIGN\n10 10\n20 20\n30 0\n41 5", "2 SIGN\n10 11\n20 20\n30 0\n41 5")).as_bytes()).unwrap(); + let text = write_dxf(&d); + for scale in ["1:1", "1:5"] { + assert_eq!(context_at(&text, scale).0, Vec2::new(10.0, 20.0), "{scale}"); + } + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); +} + +#[test] +fn a_context_s_own_offset_scales_turns_and_mirrors_with_the_reference() { + // The 1:1 context sits 2 to the right of the reference. Scaled 2 and turned 90°, it is 4 + // above; mirrored (x scale -5), 2 to the left. + let src = FIXTURE.replace("340 51\n50 0\n10 10", "340 51\n50 0\n10 12"); + let edit = |f: &dyn Fn(&mut cadcraft_doc::Insert)| { + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + f(i); + } + }) + .unwrap(); + write_dxf(&d) + }; + let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + let text = edit(&|i| { + i.scale = i.scale * 2.0; + i.rotation = 90f64.to_radians(); + }); + let (at, rot) = context_at(&text, "1:1"); + assert!(near(at, 10.0, 24.0) && (rot - 90.0).abs() < 1e-9, "{at:?} {rot}"); + let text = edit(&|i| i.scale.x = -i.scale.x); + let (at, _) = context_at(&text, "1:1"); + assert!(near(at, 8.0, 20.0), "{at:?}"); +} + +#[test] +fn the_default_context_is_the_one_whose_first_290_is_1() { + // The 1:1 attribute context comes first, turned 10° in its reference, with its own later + // 290 set: the 1:5 one is still the default, so an unchanged save keeps the 10°. + let at = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 76").unwrap(); + let end = FIXTURE.find("0 ENDSEC\n0 EOF").unwrap(); + let second = FIXTURE[at..end].replace("50 0\n10 11", "50 10\n10 11").replace("21 22\n290 0", "21 22\n290 1"); + let first = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 75").unwrap(); + let src = format!("{}{second}{}{}", &FIXTURE[..first], &FIXTURE[first..at], &FIXTURE[end..]); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + // Moved, so the attribute contexts are brought up to date. + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + for a in &mut i.attribs { + a.text.insert = a.text.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + a.text.align_pt = Some(a.text.insert); + } + } + }) + .unwrap(); + let text = write_dxf(&d); + let recs = records(&text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let rot = recs + .iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .find(|(_, t)| get(t, 340).and_then(|h| scales.get(h)) == Some(&"1:1")) + .and_then(|(_, t)| get(t, 50)) + .and_then(|v| v.parse::().ok()) + .unwrap(); + assert!((rot - 10.0).abs() < 1e-9, "{rot}"); +} + +#[test] +fn an_unchanged_attribute_turned_at_the_current_scale_keeps_its_contexts_rotation() { + // The ATTRIB is turned 20° (it is the attribute at the file's current scale) while its default + // context says 0°: saved unchanged, no context turns (what turns them is what the attribute + // did since it was read). + let d = read_dxf(dxf(&FIXTURE.replace("1 X\n", "1 X\n50 20\n")).as_bytes()).unwrap(); + let text = write_dxf(&d); + let rots: Vec = records(&text) + .iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .filter_map(|(_, t)| get(t, 50).and_then(|v| v.parse::().ok())) + .collect(); + assert_eq!(rots.len(), 2, "{rots:?}"); + assert!(rots.iter().all(|r| r.abs() < 1e-9), "{rots:?}"); +} + +#[test] +fn an_attribute_s_contexts_stay_when_the_reference_s_attributes_are_reordered() { + // A second attribute OTHER after TAG, then the reference's attributes reversed (as a block + // redefinition's attribute sync can): TAG is found as read by its tag, so saved otherwise + // unchanged its contexts don't move. + let other = "1 X\n100 AcDbAttribute\n2 TAG\n70 0\n0 ATTRIB\n5 80\n330 40\n100 AcDbEntity\n8 0\n100 AcDbText\n10 1\n20 2\n30 0\n40 1\n1 Y\n100 AcDbAttribute\n2 OTHER\n70 0\n"; + let src = FIXTURE.replacen("1 X\n100 AcDbAttribute\n2 TAG\n70 0\n", other, 1); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + assert_eq!(i.attribs.len(), 2); + i.attribs.reverse(); + } + }) + .unwrap(); + let mut actx = attribute_contexts(&write_dxf(&d)); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); +} + +/// Each written block reference context's elevation (group 30), by scale name. +fn context_heights(text: &str) -> Vec<(String, f64)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let mut out: Vec<(String, f64)> = recs + .iter() + .filter(|(k, _)| k == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| { + let scale = get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(); + (scale, get(t, 30).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN)) + }) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +#[test] +fn a_reference_moved_only_in_elevation_takes_its_contexts_along_at_their_own_heights() { + // The 1:1 context 2 units above the reference, as read. + let src = FIXTURE.replace("10 10\n20 20\n30 0\n41 1\n", "10 10\n20 20\n30 2\n41 1\n"); + assert_ne!(src, FIXTURE); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert.z += 3.0; + } + }) + .unwrap(); + let written = write_dxf(&d); + let near = |h: &[(String, f64)], scale: &str, z: f64| h.iter().any(|(s, v)| s == scale && (v - z).abs() < 1e-9); + let h = context_heights(&written); + assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "both rise by 3, the 1:1 one staying 2 above: {h:?}"); + // Saved and opened again, then saved unchanged: the heights stay. + let again = write_dxf(&read_dxf(written.as_bytes()).unwrap()); + let h = context_heights(&again); + assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "{h:?}"); +} diff --git a/crates/io/tests/it/annotative_roundtrip.rs b/crates/io/tests/it/annotative_roundtrip.rs index 52cd6e762..b69803dbc 100644 --- a/crates/io/tests/it/annotative_roundtrip.rs +++ b/crates/io/tests/it/annotative_roundtrip.rs @@ -20,6 +20,8 @@ fn text(value: &str) -> EntityKind { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }) } diff --git a/crates/io/tests/it/annotative_text_contexts.rs b/crates/io/tests/it/annotative_text_contexts.rs new file mode 100644 index 000000000..dd8ca9098 --- /dev/null +++ b/crates/io/tests/it/annotative_text_contexts.rs @@ -0,0 +1,800 @@ +//! Annotative text, MText and dimensions survive a save with their annotation scales: each is +//! written at its default scale with AutoCAD's `AcadAnnotative` xdata and one annotation scale +//! context per scale (a dimension's naming its geometry block at that scale), and read back from +//! the contexts at paper size. Without them AutoCAD shows the objects at one size at every scale, +//! and CADCraft read them as plain objects at the default scale's size. +//! +//! The fixture is synthetic: a TEXT (right-justified), an MTEXT and an aligned DIMENSION, each +//! annotative at 1:2 (default) and 1:10, in AutoCAD's layout of the records. + +use cadcraft_doc::{AnnoScale, Common, DimKind, Dimension, Drawing, EntityKind, HAlign, Handle, Space, Text, VAlign}; +use cadcraft_geom::Vec3; + +const FIXTURE: &str = " +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $CANNOSCALE +1 1:2 +0 ENDSEC +0 SECTION +2 ENTITIES +0 TEXT +5 30 +102 {ACAD_XDICTIONARY +360 31 +102 } +330 1F +100 AcDbEntity +8 0 +100 AcDbText +10 16 +20 0 +30 0 +40 2.5 +1 RIGHT +72 2 +11 30 +21 0 +31 0 +100 AcDbText +1001 AcadAnnotative +1000 AnnotativeData +1002 { +1070 1 +1070 1 +1002 } +0 MTEXT +5 40 +102 {ACAD_XDICTIONARY +360 41 +102 } +330 1F +100 AcDbEntity +8 0 +100 AcDbMText +10 0 +20 10 +30 0 +40 2.5 +41 20 +71 1 +72 5 +1 Multi +1001 AcadAnnotative +1000 AnnotativeData +1002 { +1070 1 +1070 1 +1002 } +0 DIMENSION +5 50 +102 {ACAD_XDICTIONARY +360 51 +102 } +330 1F +100 AcDbEntity +8 0 +100 AcDbDimension +2 *D1 +10 10 +20 25 +30 0 +11 5 +21 25 +31 0 +70 33 +3 Standard +100 AcDbAlignedDimension +13 0 +23 20 +33 0 +14 10 +24 20 +34 0 +1001 AcadAnnotative +1000 AnnotativeData +1002 { +1070 1 +1070 1 +1002 } +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +3 ACAD_SCALELIST +350 10 +0 DICTIONARY +5 10 +330 C +100 AcDbDictionary +281 1 +3 A0 +350 11 +3 A1 +350 12 +3 A2 +350 13 +0 SCALE +5 11 +330 10 +100 AcDbScale +70 0 +300 1:1 +140 1 +141 1 +290 1 +0 SCALE +5 12 +330 10 +100 AcDbScale +70 0 +300 1:2 +140 1 +141 2 +290 0 +0 SCALE +5 13 +330 10 +100 AcDbScale +70 0 +300 1:10 +140 1 +141 10 +290 0 +0 DICTIONARY +5 31 +330 30 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 32 +0 DICTIONARY +5 32 +330 31 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 33 +0 DICTIONARY +5 33 +330 32 +100 AcDbDictionary +281 1 +3 *A1 +350 34 +3 *A2 +350 35 +0 ACDB_TEXTOBJECTCONTEXTDATA_CLASS +5 34 +330 33 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 12 +70 2 +50 0 +10 16 +20 0 +11 30 +21 0 +0 ACDB_TEXTOBJECTCONTEXTDATA_CLASS +5 35 +330 33 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 13 +70 2 +50 0 +10 -40 +20 0 +11 30 +21 0 +0 DICTIONARY +5 41 +330 40 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 42 +0 DICTIONARY +5 42 +330 41 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 43 +0 DICTIONARY +5 43 +330 42 +100 AcDbDictionary +281 1 +3 *A1 +350 44 +3 *A2 +350 45 +0 ACDB_MTEXTOBJECTCONTEXTDATA_CLASS +5 44 +330 43 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 12 +70 1 +10 1 +20 0 +30 0 +11 0 +21 10 +31 0 +40 20 +41 0 +42 8.75 +43 2.5 +71 0 +0 ACDB_MTEXTOBJECTCONTEXTDATA_CLASS +5 45 +330 43 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 13 +70 1 +10 1 +20 0 +30 0 +11 0 +21 10 +31 0 +40 100 +41 0 +42 43.75 +43 12.5 +71 0 +0 DICTIONARY +5 51 +330 50 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 52 +0 DICTIONARY +5 52 +330 51 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 53 +0 DICTIONARY +5 53 +330 52 +100 AcDbDictionary +281 1 +3 *A1 +350 54 +3 *A2 +350 55 +0 ACDB_ALDIMOBJECTCONTEXTDATA_CLASS +5 54 +330 53 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 12 +100 AcDbDimensionObjectContextData +2 *D1 +293 0 +10 5 +20 25 +294 1 +140 0 +100 AcDbAlignedDimensionObjectContextData +11 10 +21 25 +31 0 +0 ACDB_ALDIMOBJECTCONTEXTDATA_CLASS +5 55 +330 53 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 13 +100 AcDbDimensionObjectContextData +2 *D2 +293 0 +10 5 +20 25 +294 1 +140 0 +100 AcDbAlignedDimensionObjectContextData +11 10 +21 25 +31 0 +0 ENDSEC +0 EOF +"; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +type Rec = (String, Vec<(i32, String)>); + +/// A written file's records: (type, groups). +fn records(text: &str) -> Vec { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec = Vec::new(); + for pair in lines.chunks(2) { + let (Some(code), Some(value)) = (pair.first().and_then(|c| c.parse::().ok()), pair.get(1)) else { continue }; + if code == 0 { + out.push((value.to_string(), Vec::new())); + } else if let Some((_, tags)) = out.last_mut() { + tags.push((code, value.to_string())); + } + } + out +} + +fn get(tags: &[(i32, String)], code: i32) -> Option<&str> { + tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str()) +} + +fn num(tags: &[(i32, String)], code: i32) -> f64 { + get(tags, code).and_then(|v| v.trim().parse::().ok()).unwrap_or(f64::NAN) +} + +/// A written context: (class, scale name, default, groups after the scale). +struct Ctx { + class: String, + scale: String, + default: bool, + tags: Vec<(i32, String)>, +} + +/// The contexts written for the object with handle `owner` (through its extension dictionary, +/// context manager and dictionary of contexts). +fn contexts_of(text: &str, owner: &str) -> Vec { + let recs = records(text); + let by_handle: std::collections::HashMap<&str, &Rec> = recs.iter().filter_map(|r| Some((get(&r.1, 5)?, r))).collect(); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let entry = |h: &str, key: &str| -> Option { + let t = &by_handle.get(h)?.1; + let i = t.iter().position(|(c, v)| *c == 3 && v.eq_ignore_ascii_case(key))?; + t.get(i + 1).map(|(_, v)| v.clone()) + }; + let Some(ent) = by_handle.get(owner) else { return Vec::new() }; + let xd = ent.1.iter().skip_while(|(c, v)| !(*c == 102 && v == "{ACAD_XDICTIONARY")).nth(1).map(|(_, v)| v.clone()); + let Some(dict) = xd.and_then(|x| entry(&x, "AcDbContextDataManager")).and_then(|m| entry(&m, "ACDB_ANNOTATIONSCALES")) else { + return Vec::new(); + }; + let Some(d) = by_handle.get(dict.as_str()) else { return Vec::new() }; + d.1.iter() + .filter(|(c, _)| *c == 350) + .filter_map(|(_, h)| by_handle.get(h.as_str())) + .map(|(class, t)| { + let at = t.iter().position(|(c, _)| *c == 340).unwrap_or(0); + Ctx { + class: class.clone(), + scale: get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(), + default: get(t, 290) == Some("1"), + tags: t.get(at + 1..).unwrap_or(&[]).to_vec(), + } + }) + .collect() +} + +fn names(d: &Drawing, h: &str) -> Vec { + d.entity(Handle::parse_hex(h).unwrap()).unwrap().common.anno_scales.iter().map(|s| s.name.clone()).collect() +} + +fn read() -> Drawing { + cadcraft_io::read_dxf(dxf(FIXTURE).as_bytes()).unwrap() +} + +fn save(d: &Drawing) -> String { + String::from_utf8(cadcraft_io::write(d, "x.dxf").unwrap()).unwrap() +} + +#[test] +fn contexts_make_text_mtext_and_dimensions_annotative_at_paper_size() { + let d = read(); + for h in ["30", "40", "50"] { + assert_eq!(names(&d, h), ["1:2", "1:10"], "{h}"); + } + let Some(EntityKind::Text(t)) = d.entity(Handle(0x30)).map(|e| &e.kind) else { panic!("text") }; + // 2.5 at 1:2: 1.25 on paper. The start point moves with the size about the alignment point. + assert!((t.height - 1.25).abs() < 1e-12, "{}", t.height); + assert!((t.insert.x - 23.0).abs() < 1e-12, "{:?}", t.insert); + let Some(EntityKind::MText(m)) = d.entity(Handle(0x40)).map(|e| &e.kind) else { panic!("mtext") }; + assert!((m.height - 1.25).abs() < 1e-12 && (m.width - 10.0).abs() < 1e-12, "{} {}", m.height, m.width); +} + +#[test] +fn each_object_is_written_at_its_default_scale_with_a_context_per_scale() { + let text = save(&read()); + let recs = records(&text); + let ent = |h: &str| recs.iter().find(|(_, t)| get(t, 5) == Some(h)).unwrap(); + // The current scale (1:2) is the default: the groups are at its size. + assert_eq!(num(&ent("30").1, 40), 2.5); + assert_eq!(num(&ent("40").1, 40), 2.5); + assert_eq!(num(&ent("40").1, 41), 20.0); + for h in ["30", "40", "50"] { + assert!(ent(h).1.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"), "{h}"); + let ctx = contexts_of(&text, h); + let got: Vec<(&str, bool)> = ctx.iter().map(|c| (c.scale.as_str(), c.default)).collect(); + assert_eq!(got, [("1:2", true), ("1:10", false)], "{h}"); + } + let text_ctx = contexts_of(&text, "30"); + assert!(text_ctx.iter().all(|c| c.class == "ACDB_TEXTOBJECTCONTEXTDATA_CLASS")); + // Right-justified: the alignment point stays, the start point moves with the size. + let starts: Vec<(f64, f64)> = text_ctx.iter().map(|c| (num(&c.tags, 10), num(&c.tags, 11))).collect(); + assert_eq!(starts, [(16.0, 30.0), (-40.0, 30.0)]); + let widths: Vec = contexts_of(&text, "40").iter().map(|c| num(&c.tags, 40)).collect(); + assert_eq!(widths, [20.0, 100.0]); + // A dimension's contexts name its geometry block at each scale; the default one is its own. + let dim = contexts_of(&text, "50"); + assert!(dim.iter().all(|c| c.class == "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS")); + let blocks: Vec = dim.iter().map(|c| get(&c.tags, 2).unwrap().to_string()).collect(); + assert_eq!(get(&ent("50").1, 2), Some(blocks[0].as_str())); + let text_height = |block: &str| { + let start = recs.iter().position(|(k, t)| k == "BLOCK" && get(t, 2) == Some(block)).unwrap(); + let end = start + recs[start..].iter().position(|(k, _)| k == "ENDBLK").unwrap(); + recs[start..end].iter().find(|(k, _)| k == "MTEXT").map(|(_, t)| num(t, 40)).unwrap() + }; + let (h2, h10) = (text_height(&blocks[0]), text_height(&blocks[1])); + assert!((h10 / h2 - 5.0).abs() < 1e-9, "{h2} {h10}"); + // Only the dimension has blocks per scale: no empty `*D` block for the text or the MText. + let d_blocks: Vec<&str> = recs.iter().filter(|(k, _)| k == "BLOCK").filter_map(|(_, t)| get(t, 2)).filter(|n| n.starts_with("*D")).collect(); + assert_eq!(d_blocks.len(), 2, "{d_blocks:?}"); + for name in &d_blocks { + let start = recs.iter().position(|(k, t)| k == "BLOCK" && get(t, 2) == Some(name)).unwrap(); + assert_ne!(recs.get(start + 1).map(|(k, _)| k.as_str()), Some("ENDBLK"), "{name} is empty"); + } + // Each context class is declared. + for class in ["ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "ACDB_MTEXTOBJECTCONTEXTDATA_CLASS", "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS"] { + assert!(recs.iter().any(|(k, t)| k == "CLASS" && get(t, 1) == Some(class)), "{class}"); + } +} + +#[test] +fn a_saved_drawing_reads_back_the_same() { + let d = read(); + let back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap(); + for h in ["30", "40", "50"] { + let (a, b) = (d.entity(Handle::parse_hex(h).unwrap()).unwrap(), back.entity(Handle::parse_hex(h).unwrap()).unwrap()); + assert_eq!(a.common.anno_scales, b.common.anno_scales, "{h}"); + // A justified text's start point is worked out from its alignment point on save, as + // AutoCAD does; the rest reads back as it was. + let mut kind = a.kind.clone(); + if let (EntityKind::Text(t), EntityKind::Text(u)) = (&mut kind, &b.kind) + && t.align_pt.is_some() + { + t.insert = u.insert; + } + if !matches!(a.kind, EntityKind::Dimension(_)) { + assert_eq!(kind, b.kind, "{h}"); + } + } + // Saved again, it reads back exactly. + let again = cadcraft_io::read_dxf(save(&back).as_bytes()).unwrap(); + for h in ["30", "40"] { + let h = Handle::parse_hex(h).unwrap(); + assert_eq!(back.entity(h).unwrap().kind, again.entity(h).unwrap().kind); + } + // Saved again, the file is the same: nothing piles up. + assert_eq!(contexts_of(&save(&back), "30").len(), 2); +} + +/// A drawing made in CADCraft: text and a dimension at 1:1 and 1:50, 1:50 current. +fn made() -> Drawing { + let mut d = Drawing::default(); + d.header.set_str("CANNOSCALE", "1:50"); + let scales = vec![AnnoScale::new("1:1", 1.0, 1.0), AnnoScale::new("1:50", 1.0, 50.0)]; + let common = Common { anno_scales: scales.clone(), ..Common::default() }; + let t = Text { + insert: Vec3::ZERO, + align_pt: None, + height: 2.5, + value: "NOTE".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + backwards: false, + upside_down: false, + }; + d.add(&Space::Model, common.clone(), EntityKind::Text(t)).unwrap(); + let dm = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(100.0, 20.0, 0.0), + text_mid: Vec3::new(50.0, 20.0, 0.0), + p13: Vec3::ZERO, + p14: Vec3::new(100.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 100.0, + text_rotation: 0.0, + user_text_pos: false, + block: None, + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + d.add(&Space::Model, common, EntityKind::Dimension(dm)).unwrap(); + d +} + +#[test] +fn objects_made_in_cadcraft_get_contexts_and_read_back() { + let d = made(); + let text = save(&d); + let recs = records(&text); + let handles: Vec = d.model.iter().map(|e| e.handle.hex()).collect(); + let t = recs.iter().find(|(_, t)| get(t, 5) == Some(handles[0].as_str())).unwrap(); + // Written at 1:50, the current scale: 2.5 on paper is 125. + assert_eq!(num(&t.1, 40), 125.0); + for h in &handles { + let got: Vec<(String, bool)> = contexts_of(&text, h).into_iter().map(|c| (c.scale, c.default)).collect(); + assert_eq!(got, [("1:1".to_string(), false), ("1:50".to_string(), true)], "{h}"); + } + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + for (a, b) in d.model.iter().zip(back.model.iter()) { + assert_eq!(a.common.anno_scales, b.common.anno_scales); + } + let Some(EntityKind::Text(t)) = back.model.iter().next().map(|e| &e.kind) else { panic!("text") }; + assert!((t.height - 2.5).abs() < 1e-9, "{}", t.height); +} + +#[test] +fn a_scale_missing_from_the_list_is_added_to_it() { + let mut d = made(); + d.scales.retain(|s| s.name != "1:50"); + let text = save(&d); + assert!(records(&text).iter().any(|(k, t)| k == "SCALE" && get(t, 300) == Some("1:50"))); + let h = d.model.iter().next().unwrap().handle.hex(); + assert_eq!(contexts_of(&text, &h).len(), 2); +} + +#[test] +fn files_older_than_annotation_scaling_keep_cadcraft_s_record() { + let d = made(); + let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2004), binary: false }; + let bytes = cadcraft_io::write_with(&d, "x.dxf", &opts).unwrap(); + let text = String::from_utf8_lossy(&bytes); + assert!(!text.contains("OBJECTCONTEXTDATA")); + let back = cadcraft_io::read_dxf(&bytes).unwrap(); + for (a, b) in d.model.iter().zip(back.model.iter()) { + assert_eq!(a.common.anno_scales, b.common.anno_scales); + if let (EntityKind::Text(x), EntityKind::Text(y)) = (&a.kind, &b.kind) { + assert_eq!(x.height, y.height); + } + } +} + +#[test] +fn a_dimension_s_associativity_and_contexts_share_its_dictionary() { + let mut d = made(); + let line = + d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(100.0, 0.0, 0.0) })).unwrap(); + let dim = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle; + d.modify_entity(dim, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.assoc = vec![ + cadcraft_doc::DimAssoc { point: "p13".into(), handle: line, snap: cadcraft_doc::AssocSnap::Start }, + cadcraft_doc::DimAssoc { point: "p14".into(), handle: line, snap: cadcraft_doc::AssocSnap::End }, + ]; + } + }) + .unwrap(); + let text = save(&d); + let recs = records(&text); + let ent = recs.iter().find(|(k, t)| k == "DIMENSION" && get(t, 5) == Some(dim.hex().as_str())).unwrap(); + let xdicts = ent.1.iter().filter(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY").count(); + assert_eq!(xdicts, 1); + assert_eq!(contexts_of(&text, &dim.hex()).len(), 2); + let xd = ent.1.iter().skip_while(|(c, v)| !(*c == 102 && v == "{ACAD_XDICTIONARY")).nth(1).unwrap().1.clone(); + let dict = recs.iter().find(|(_, t)| get(t, 5) == Some(xd.as_str())).unwrap(); + assert!(dict.1.iter().any(|(c, v)| *c == 3 && v == "ACAD_DIMASSOC")); +} + +#[test] +fn hostile_contexts_do_not_panic() { + // Contexts naming no scale, a scale of zero, a missing dictionary and a cycle. + let src = dxf(FIXTURE) + .replace("340\n13\n", "340\n99\n") + .replace("141\n2\n", "141\n0\n") + .replace("360\n42\n", "360\n41\n") + .replace("350\n53\n", "350\n51\n"); + let d = cadcraft_io::read_dxf(src.as_bytes()).unwrap(); + for h in ["30", "40", "50"] { + let n = names(&d, h); + assert!(n.len() <= 1, "{h}: {n:?}"); + } + // Saved and opened again: the same scales, every context naming a written SCALE. + let text = save(&d); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + for h in ["30", "40", "50"] { + assert_eq!(names(&back, h), names(&d, h), "{h}"); + for c in contexts_of(&text, h) { + assert_ne!(c.scale, "?", "{h}: a context names a missing SCALE"); + } + } +} + +/// A DWG keeps the objects' scales in CADCraft's own record, not in AutoCAD's contexts: the DWG +/// bridge doesn't convert those yet (storytold/craft-libs#2005). The scales, the paper sizes and +/// a turned text's rotation come back; the contexts' round trip through DWG follows with the +/// bridge. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn text_mtext_and_dimensions_keep_their_scales_through_dwg() { + cadcraft_io::dwg_worker::allow_in_process(); + let mut d = read(); + d.modify_entity(Handle(0x30), |e| { + if let EntityKind::Text(t) = &mut e.kind { + t.rotation = 30f64.to_radians(); + } + }) + .unwrap(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + for kind in ["text", "mtext", "dimension"] { + let e = back.model.iter().find(|e| { + matches!((&e.kind, kind), (EntityKind::Text(_), "text") | (EntityKind::MText(_), "mtext") | (EntityKind::Dimension(_), "dimension")) + }); + let e = e.unwrap_or_else(|| panic!("{kind}")); + let got: Vec<&str> = e.common.anno_scales.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(got, ["1:2", "1:10"], "{kind}"); + if let EntityKind::Text(t) = &e.kind { + assert!((t.height - 1.25).abs() < 1e-9 && (t.rotation.to_degrees() - 30.0).abs() < 1e-9, "{t:?}"); + } + } + let dxf = craft_dwg::dwg_to_dxf(&dwg).unwrap(); + let recs = records(&String::from_utf8_lossy(&dxf)); + assert!(!recs.iter().any(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")), "no contexts in the DWG"); +} + +/// A drawing made in CADCraft with an annotative multileader (text 2.5 on paper, 1:1 and 1:10, +/// 1:10 current). +fn with_mleader() -> (Drawing, Handle) { + let mut d = Drawing::default(); + d.header.set_str("CANNOSCALE", "1:10"); + let common = Common { anno_scales: vec![AnnoScale::new("1:1", 1.0, 1.0), AnnoScale::new("1:10", 1.0, 10.0)], ..Common::default() }; + let text = cadcraft_doc::MText { + insert: Vec3::new(10.5, 10.1, 0.0), + height: 2.5, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "Note".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: None, + }; + let m = cadcraft_doc::MLeader { + leaders: vec![vec![Vec3::ZERO]], + landing: Vec3::new(10.0, 10.0, 0.0), + dogleg: 0.36, + text: Some(text), + style: "Standard".into(), + arrow_size: 0.18, + spline: false, + block: None, + }; + let h = d.add(&Space::Model, common, EntityKind::MLeader(m)).unwrap(); + (d, h) +} + +#[test] +fn a_multileader_gets_its_context_data_at_each_scale() { + let (d, h) = with_mleader(); + let text = save(&d); + let recs = records(&text); + let ent = recs.iter().find(|(k, t)| k == "MULTILEADER" && get(t, 5) == Some(h.hex().as_str())).unwrap(); + assert!(ent.1.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative")); + // The entity is at 1:10, the current scale: overall scale 10 and text 25. + assert_eq!(num(&ent.1, 40), 10.0); + assert_eq!(num(&ent.1, 41), 25.0); + let ctx = contexts_of(&text, &h.hex()); + let got: Vec<(&str, bool, &str)> = ctx.iter().map(|c| (c.scale.as_str(), c.default, c.class.as_str())).collect(); + assert_eq!(got, [("1:1", false, "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS"), ("1:10", true, "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS")]); + for (c, f) in ctx.iter().zip([1.0, 10.0]) { + // AutoCAD's layout: the context groups straight after the scale, no braces of their own. + assert_eq!(c.tags.first().map(|t| t.0), Some(40), "{:?}", c.tags); + assert!(c.tags.iter().all(|(code, v)| !(*code == 300 && v.starts_with("CONTEXT_DATA")) && *code != 301)); + assert_eq!(num(&c.tags, 40), f); + assert!((num(&c.tags, 41) - 2.5 * f).abs() < 1e-9); + assert!((num(&c.tags, 140) - 0.18 * f).abs() < 1e-9); + // The text keeps its place about the landing, at the scale's size. + assert!((num(&c.tags, 12) - (10.0 + 0.5 * f)).abs() < 1e-9 && (num(&c.tags, 22) - (10.0 + 0.1 * f)).abs() < 1e-9); + } + // A multileader has no block per scale (only dimensions do). + assert!(!recs.iter().any(|(k, t)| k == "BLOCK" && get(t, 2).is_some_and(|n| n.starts_with("*D")))); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let (a, b) = (d.entity(h).unwrap(), back.entity(h).unwrap()); + assert_eq!(a.common.anno_scales, b.common.anno_scales); + let (EntityKind::MLeader(x), EntityKind::MLeader(y)) = (&a.kind, &b.kind) else { panic!("multileader") }; + let (tx, ty) = (x.text.as_ref().unwrap(), y.text.as_ref().unwrap()); + assert!((tx.height - ty.height).abs() < 1e-9 && (tx.insert - ty.insert).len() < 1e-9, "{ty:?}"); + assert!((x.arrow_size - y.arrow_size).abs() < 1e-9 && (x.dogleg - y.dogleg).abs() < 1e-9, "{y:?}"); +} + +/// A multileader's scales come back through DWG from CADCraft's own record (the DWG bridge +/// doesn't convert contexts yet, storytold/craft-libs#2005), at its paper size; the DWG holds no +/// multileader contexts. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_multileader_keeps_its_scales_through_dwg() { + cadcraft_io::dwg_worker::allow_in_process(); + let (d, _) = with_mleader(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + let e = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap(); + let got: Vec<&str> = e.common.anno_scales.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(got, ["1:1", "1:10"]); + let EntityKind::MLeader(m) = &e.kind else { panic!("multileader") }; + assert!((m.text.as_ref().unwrap().height - 2.5).abs() < 1e-9, "{m:?}"); + let text = String::from_utf8_lossy(&craft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned(); + assert!(!records(&text).iter().any(|(k, _)| k == "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS"), "no contexts in the DWG"); +} + +/// The fixture with AutoCAD's variable dictionary naming 1:10 as the current annotation scale. +fn with_current_scale() -> String { + dxf(FIXTURE) + .replace("3\nACAD_SCALELIST\n350\n10\n", "3\nACAD_SCALELIST\n350\n10\n3\nAcDbVariableDictionary\n350\n60\n") + .replace( + "0\nENDSEC\n0\nEOF\n", + "0\nDICTIONARY\n5\n60\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nCANNOSCALE\n350\n61\n0\nDICTIONARYVAR\n5\n61\n330\n60\n100\nDictionaryVariables\n280\n0\n1\n1:10\n0\nENDSEC\n0\nEOF\n", + ) +} + +#[test] +fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() { + let mut d = cadcraft_io::read_dxf(with_current_scale().as_bytes()).unwrap(); + assert_eq!(d.header.str("CANNOSCALE", ""), "1:10"); + // Written at the current scale: the 1:10 context is the default one. + let text = save(&d); + let got: Vec<(String, bool)> = contexts_of(&text, "30").into_iter().map(|c| (c.scale, c.default)).collect(); + assert_eq!(got, [("1:2".to_string(), false), ("1:10".to_string(), true)]); + // Changed in CADCraft, AutoCAD's variable says so too. + d.header.set_str("CANNOSCALE", "1:2"); + let recs = records(&save(&d)); + let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap(); + assert_eq!(get(&var.1, 1), Some("1:2")); + assert_eq!(recs.iter().filter(|(k, _)| k == "DICTIONARYVAR").count(), 1); + // Naming no scale of the drawing's, it is the 1:1 the contexts are written at. + d.header.set_str("CANNOSCALE", "1:999"); + let recs = records(&save(&d)); + let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap(); + assert_eq!(get(&var.1, 1), Some("1:1")); +} diff --git a/crates/io/tests/it/attrib_modes.rs b/crates/io/tests/it/attrib_modes.rs index abfabcc51..062d811f3 100644 --- a/crates/io/tests/it/attrib_modes.rs +++ b/crates/io/tests/it/attrib_modes.rs @@ -19,6 +19,8 @@ fn attrib(tag: &str, modes: AttribModes) -> Attrib { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }; Attrib { tag: tag.into(), text, invisible: false, constant: false, prompt: String::new(), props: Default::default(), multiline: None, modes } } diff --git a/crates/io/tests/it/attrib_props.rs b/crates/io/tests/it/attrib_props.rs index 4787dd8c2..7a1eca63e 100644 --- a/crates/io/tests/it/attrib_props.rs +++ b/crates/io/tests/it/attrib_props.rs @@ -20,6 +20,8 @@ fn text(x: f64, value: &str) -> Text { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, } } @@ -167,3 +169,40 @@ fn hostile_attrib_groups_do_not_panic() { assert_eq!((p.layer.as_deref(), p.linetype.as_deref()), (None, None), "empty names are not properties"); let _ = write_dxf(&d); } + +/// The layer and colour of each attribute of each block reference in `d`, in file order. +fn layers_and_colors(d: &Drawing) -> Vec<(Option, Option)> { + let attribs = d.model.iter().filter_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.attribs.clone()) } else { None }); + attribs.flatten().map(|a| (a.props.layer, a.props.color)).collect() +} + +/// #3492: an ATTRIB on layer 0 of a reference on layer A stays on layer 0 when the drawing is read +/// and saved again, as DXF and as DWG; layer 0 means the reference's layer only for a definition. +#[test] +fn attribute_on_layer_zero_stays_on_layer_zero() { + cadcraft_io::dwg_worker::allow_in_process(); + let attrib = |layer: &str, color: &str| format!("0\nATTRIB\n8\n{layer}\n{color}10\n0\n20\n1\n30\n0\n40\n1\n1\nv\n2\nT1\n70\n0\n"); + let insert = |x: u32, attrib: String| format!("0\nINSERT\n8\nA\n66\n1\n2\nBLK\n10\n{x}\n20\n0\n30\n0\n{attrib}0\nSEQEND\n8\nA\n"); + let dxf = format!( + "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n70\n2\n0\nLAYER\n2\nA\n70\n0\n62\n3\n6\nCONTINUOUS\n\ +0\nLAYER\n2\nB\n70\n0\n62\n5\n6\nCONTINUOUS\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\nBLK\n70\n2\n10\n0\n20\n0\n30\n0\n3\nBLK\n\ +0\nLINE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n0\n31\n0\n\ +0\nATTDEF\n8\n0\n10\n0\n20\n1\n30\n0\n40\n1\n1\nx\n3\n\n2\nT1\n70\n0\n0\nENDBLK\n8\n0\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n{}{}{}0\nENDSEC\n0\nEOF\n", + insert(0, attrib("0", "")), + insert(10, attrib("B", "")), + insert(20, attrib("0", "62\n1\n")), + ); + let d = cadcraft_io::read(dxf.as_bytes(), "t.dxf").expect("read"); + let read = layers_and_colors(&d); + assert_eq!(read.len(), 3); + let layers: Vec> = read.iter().map(|(l, _)| l.as_deref()).collect(); + assert_eq!(layers, [Some("0"), Some("B"), Some("0")], "as the file says"); + assert_eq!(read[2].1, Some(Color::Index(1))); + for name in ["t.dxf", "t.dwg"] { + let saved = cadcraft_io::write(&d, name).expect("write"); + let back = cadcraft_io::read(&saved, name).expect("reopen"); + assert_eq!(layers_and_colors(&back), read, "{name}: attribute layers or colours changed"); + } +} diff --git a/crates/io/tests/it/block_expansion.rs b/crates/io/tests/it/block_expansion.rs index 7aac5d7db..7fd0a337c 100644 --- a/crates/io/tests/it/block_expansion.rs +++ b/crates/io/tests/it/block_expansion.rs @@ -395,6 +395,9 @@ fn an_empty_followup_viewport_does_not_mark_an_exact_budget_truncated() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; let paper = Space::Paper("Layout1".into()); diff --git a/crates/io/tests/it/dim_block_resave_roundtrip.rs b/crates/io/tests/it/dim_block_resave_roundtrip.rs index a8625db72..0066943e4 100644 --- a/crates/io/tests/it/dim_block_resave_roundtrip.rs +++ b/crates/io/tests/it/dim_block_resave_roundtrip.rs @@ -311,6 +311,8 @@ fn an_unedited_dimension_keeps_a_block_with_any_name() { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), ] { let h = d.new_handle(); diff --git a/crates/io/tests/it/dim_text_below.rs b/crates/io/tests/it/dim_text_below.rs new file mode 100644 index 000000000..1107bdac6 --- /dev/null +++ b/crates/io/tests/it/dim_text_below.rs @@ -0,0 +1,48 @@ +//! #1055: a dimension's `*D` block (what AutoCAD and other readers draw) holds the text after +//! `\X` as a second MTEXT below the dimension line. + +use cadcraft_doc::{Common, DimKind, Dimension, Drawing, EntityKind, Space}; +use cadcraft_geom::Vec3; + +#[test] +fn the_text_below_the_dimension_line_is_a_second_mtext() { + let mut d = Drawing::new_metric(); + let dm = Dimension { + kind: DimKind::Linear { rotation: 0.0 }, + defpt: Vec3::new(50.0, 20.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(100.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: "30 MIN.\\X50 MAX.".into(), + style: "ISO-25".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: None, + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap(); + let dxf = cadcraft_io::write_dxf(&d); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let pairs: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect(); + let blocks = pairs.iter().position(|(c, v)| *c == "2" && *v == "BLOCKS").unwrap(); + let start = blocks + pairs[blocks..].iter().position(|(c, v)| *c == "2" && v.starts_with("*D")).unwrap(); + let end = start + pairs[start..].iter().position(|(c, v)| *c == "0" && *v == "ENDBLK").unwrap(); + let (mut texts, mut kind, mut y) = (Vec::new(), "", 0.0); + for (c, v) in &pairs[start..end] { + match *c { + "0" => kind = v, + "20" if kind == "MTEXT" => y = v.parse().unwrap(), + "1" if kind == "MTEXT" => texts.push((v.to_string(), y)), + _ => {} + } + } + assert_eq!(texts.len(), 2, "{texts:?}"); + assert_eq!((texts[0].0.as_str(), texts[1].0.as_str()), ("30 MIN.", "50 MAX.")); + assert!(texts[0].1 > 20.0 && texts[1].1 < 20.0, "above and below the line at y = 20: {texts:?}"); +} diff --git a/crates/io/tests/it/dwg_roundtrip_losses.rs b/crates/io/tests/it/dwg_roundtrip_losses.rs index 8e9cb3bb0..3337f1e5b 100644 --- a/crates/io/tests/it/dwg_roundtrip_losses.rs +++ b/crates/io/tests/it/dwg_roundtrip_losses.rs @@ -28,6 +28,9 @@ fn viewport(id: u32) -> EntityKind { layer_colors: vec![], clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) } diff --git a/crates/io/tests/it/dxf_versions.rs b/crates/io/tests/it/dxf_versions.rs index 6e4d5a72a..75a4e8bf5 100644 --- a/crates/io/tests/it/dxf_versions.rs +++ b/crates/io/tests/it/dxf_versions.rs @@ -19,6 +19,8 @@ fn text(value: &str) -> EntityKind { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }) } diff --git a/crates/io/tests/it/entity_props_roundtrip.rs b/crates/io/tests/it/entity_props_roundtrip.rs index 27f41a5b2..20f96f85c 100644 --- a/crates/io/tests/it/entity_props_roundtrip.rs +++ b/crates/io/tests/it/entity_props_roundtrip.rs @@ -83,6 +83,8 @@ fn thickness_roundtrips_on_every_entity_that_has_one() { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }; let kinds = vec![ EntityKind::Line(Line { a: p(0.0, 0.0), b: p(10.0, 0.0) }), diff --git a/crates/io/tests/it/followups_626.rs b/crates/io/tests/it/followups_626.rs index 51a11afa8..0ba550789 100644 --- a/crates/io/tests/it/followups_626.rs +++ b/crates/io/tests/it/followups_626.rs @@ -46,6 +46,7 @@ fn mleader_drawing() -> (Drawing, MLeader) { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), style: "Standard".into(), arrow_size: 1.0, @@ -173,6 +174,8 @@ fn code_page_is_kept_before_2007() { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }), ) .unwrap(); diff --git a/crates/io/tests/it/hatch_loop_flags.rs b/crates/io/tests/it/hatch_loop_flags.rs index 71e8e8cf3..0c3ecbb62 100644 --- a/crates/io/tests/it/hatch_loop_flags.rs +++ b/crates/io/tests/it/hatch_loop_flags.rs @@ -58,11 +58,17 @@ fn flags_written(drawing: &Drawing) -> Vec { .collect() } +/// The group 92 of a path read with `flags`, as saved: Polyline set, and Derived cleared because +/// the pixel size it needs is not kept (#3664). +fn saved(flags: i64) -> i64 { + (flags | 2) & !4 +} + #[test] fn boundary_flags_survive_dxf_open_and_save() { for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] { let drawing = read_dxf(logo(flags).as_bytes()).unwrap(); - let expected = flags.map(|flag| flag | 2); + let expected = flags.map(saved); assert_eq!(flags_written(&drawing), expected); let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap(); assert_eq!(flags_written(&back), expected); @@ -92,7 +98,7 @@ fn reclassified_loops_write_current_external_bit() { }); let written = flags_written(&drawing)[1]; assert_eq!(written & 1, 0); - assert_eq!(written & (4 | 16), imported & (4 | 16)); + assert_eq!(written & (4 | 16), imported & 16); assert_ne!(written & 2, 0); let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap(); assert_eq!(flags_written(&back), flags_written(&drawing)); @@ -103,7 +109,7 @@ fn reclassified_loops_write_current_external_bit() { fn undocumented_boundary_bits_are_not_written_back() { let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22]; let drawing = read_dxf(logo(flags).as_bytes()).unwrap(); - let expected = flags.map(|flag| (flag & 31) | 2); + let expected = flags.map(|flag| saved(flag & 31)); assert_eq!(flags_written(&drawing), expected); let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap(); assert_eq!(flags_written(&back), expected); @@ -117,7 +123,7 @@ fn boundary_flags_survive_dwg_open_and_both_save_formats() { let drawing = read_dxf(logo(flags).as_bytes()).unwrap(); let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap(); let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap(); - let expected = flags.map(|flag| flag | 2); + let expected = flags.map(saved); assert_eq!(flags_written(&back), expected); let again = cadcraft_io::write(&back, "logo.dwg").unwrap(); assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected); @@ -143,3 +149,97 @@ fn old_serialized_loops_keep_locally_created_flags() { } assert_eq!(flags_written(&drawing), expected); } + +/// The first of the four LINEs in [`derived_hatches`]. +const LINES: u64 = 0x1A0; + +/// Invented geometry: a 30 by 20 rectangle drawn as four LINEs and two hatches on it. The first +/// is a NET pattern linked to the lines (71 = 1, 97 = 4), with a derived outer path (92 = 7), a +/// derived edge-path island (92 = 20) and its pixel size (47) after the pattern lines. The second +/// is solid and not linked, with one derived edge path (92 = 5) and a pixel size. +fn derived_hatches() -> String { + let corners = [(0.0, 0.0), (30.0, 0.0), (30.0, 20.0), (0.0, 20.0)]; + let island = [(10.0, 5.0), (20.0, 5.0), (20.0, 15.0), (10.0, 15.0)]; + let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"); + for (index, (start, end)) in (0..).zip(corners.iter().zip(corners.iter().cycle().skip(1))) { + text.push_str(&format!( + "0\nLINE\n5\n{:X}\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n{}\n20\n{}\n30\n0\n11\n{}\n21\n{}\n31\n0\n", + LINES + index, + start.0, + start.1, + end.0, + end.1 + )); + } + let head = |handle: &str, pattern: &str, solid: i64, linked: i64, paths: usize| { + format!( + "0\nHATCH\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\n{pattern}\n70\n{solid}\n71\n{linked}\n91\n{paths}\n" + ) + }; + text.push_str(&head("1A4", "NET", 0, 1, 2)); + text.push_str(boundary(&corners, 7).strip_suffix("97\n0\n").unwrap()); + text.push_str("97\n4\n"); + for index in 0..4 { + text.push_str(&format!("330\n{:X}\n", LINES + index)); + } + text.push_str(&boundary(&island, 20)); + text.push_str("75\n0\n76\n1\n52\n0\n41\n2\n77\n0\n78\n2\n"); + text.push_str("53\n0\n43\n0\n44\n0\n45\n0\n46\n2.5\n79\n0\n53\n90\n43\n0\n44\n0\n45\n-2.5\n46\n0\n79\n0\n47\n1.5\n98\n0\n"); + text.push_str(&head("1A5", "SOLID", 1, 0, 1)); + text.push_str(&boundary(&corners, 5)); + text.push_str("75\n0\n76\n1\n47\n1.5\n98\n0\n0\nENDSEC\n0\nEOF\n"); + text +} + +/// The (code, value) pairs of each HATCH record in a DXF text. +fn hatch_records(text: &str) -> Vec> { + let lines: Vec<_> = text.lines().collect(); + let mut records: Vec> = Vec::new(); + let mut hatch = false; + for pair in lines.as_chunks::<2>().0 { + let code: i32 = pair[0].trim().parse().unwrap(); + let value = pair[1].trim().to_string(); + if code == 0 { + hatch = value == "HATCH"; + if hatch { + records.push(Vec::new()); + } + } else if hatch && let Some(record) = records.last_mut() { + record.push((code, value)); + } + } + records +} + +/// The values of `code` in a HATCH record, from its boundary paths (group 91) on. +fn path_values(record: &[(i32, String)], code: i32) -> Vec { + record.iter().skip_while(|(group, _)| *group != 91).filter(|(group, _)| *group == code).map(|(_, value)| value.clone()).collect() +} + +/// A derived path (92 bit 4) needs the hatch's pixel size (47), which is not kept (#3664). The +/// path is saved without the bit and no stand-in size is written; the hatch keeps its other path +/// bits, its pattern and its link to the lines, through a second save too. +#[test] +fn derived_paths_are_saved_without_the_bit_or_a_stand_in_pixel_size() { + let drawing = read_dxf(derived_hatches().as_bytes()).unwrap(); + let first = write_dxf(&drawing); + let again = write_dxf(&read_dxf(first.as_bytes()).unwrap()); + for text in [first, again] { + let hatches = hatch_records(&text); + assert_eq!(hatches.len(), 2); + for hatch in &hatches { + let derived = path_values(hatch, 92).iter().any(|flags| flags.parse::().unwrap() & 4 != 0); + assert!(!derived, "{hatch:?}"); + assert!(!hatch.iter().any(|(code, _)| *code == 47), "{hatch:?}"); + } + assert_eq!(path_values(&hatches[0], 92), [saved(7), saved(20)].map(|flags| flags.to_string())); + assert_eq!(path_values(&hatches[1], 92), [saved(5).to_string()]); + // Still a NET pattern fill with its two lines, and still linked to the lines it was made from. + assert!(hatches[0].contains(&(2, "NET".to_string())) && hatches[0].contains(&(70, "0".to_string())), "{:?}", hatches[0]); + assert_eq!(path_values(&hatches[0], 78), ["2"]); + assert!(hatches[0].contains(&(71, "1".to_string())), "{:?}", hatches[0]); + assert_eq!(path_values(&hatches[0], 97), ["4", "0"]); + let lines: Vec = (0..4).map(|index| format!("{:X}", LINES + index)).collect(); + assert_eq!(path_values(&hatches[0], 330), lines); + } +} diff --git a/crates/io/tests/it/hatch_pattern_def.rs b/crates/io/tests/it/hatch_pattern_def.rs index 98add4dd6..f4dc24eea 100644 --- a/crates/io/tests/it/hatch_pattern_def.rs +++ b/crates/io/tests/it/hatch_pattern_def.rs @@ -1,5 +1,6 @@ -//! HATCH pattern definition lines (groups 78, 53, 43–46, 79, 49) of a pattern the library -//! doesn't define survive a DXF read and save (issue #290). +//! HATCH pattern definition lines (groups 78, 53, 43–46, 79, 49) survive a DXF read and save: a +//! pattern the library doesn't define (issue #290), and a user-defined hatch's own families, which +//! a DWG keeps too. use cadcraft_doc::library::PatternLine; use cadcraft_doc::*; @@ -35,15 +36,22 @@ fn custom_lines() -> Vec { ] } -fn save(h: Hatch) -> String { +fn drawing(h: Hatch) -> Drawing { let mut d = Drawing::new_imperial(); d.add(&Space::Model, Common::default(), EntityKind::Hatch(h)).expect("add"); - write_dxf(&d) + d +} + +fn save(h: Hatch) -> String { + write_dxf(&drawing(h)) +} + +fn first_hatch_of(d: &Drawing) -> Hatch { + d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).expect("hatch") } fn first_hatch(text: &str) -> Hatch { - let d = read_dxf(text.as_bytes()).expect("read"); - d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).expect("hatch") + first_hatch_of(&read_dxf(text.as_bytes()).expect("read")) } /// (group code, value) pairs of a DXF text. @@ -58,6 +66,12 @@ fn pattern_data(p: &[(i32, String)]) -> usize { p.iter().skip(hatch).position(|(c, _)| *c == 78).map(|k| hatch + k).expect("78") } +/// The first value of group `code` in the first HATCH of a DXF text. +fn hatch_group(p: &[(i32, String)], code: i32) -> Option { + let hatch = p.iter().position(|(c, v)| *c == 0 && v == "HATCH")?; + p.iter().skip(hatch).find(|(c, _)| *c == code).map(|(_, v)| v.clone()) +} + fn join(p: &[(i32, String)]) -> String { p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() } @@ -97,6 +111,99 @@ fn custom_pattern_lines_roundtrip_scaled_and_rotated() { assert!(near(&first_hatch(&save(h)).pattern_lines, &custom_lines())); } +#[test] +fn user_defined_hatches_save_their_type_double_flag_and_lines_and_read_back() { + let lines = cadcraft_doc::library::user_defined_lines(true); + let text = save(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 30f64.to_radians(), Vec2::new(1.0, 2.0), lines.clone())); + let p = pairs(&text); + assert_eq!(hatch_group(&p, 2).as_deref(), Some("_USER")); + assert_eq!(hatch_group(&p, 76).as_deref(), Some("0"), "pattern type 0: user-defined"); + assert_eq!(hatch_group(&p, 77).as_deref(), Some("1"), "double hatch area"); + assert_eq!(hatch_group(&p, 78).as_deref(), Some("2"), "the two families are listed"); + // Each family is written as a pattern line is: its angle, base point, offset and dashes. + let at = pattern_data(&p); + let num = |k: usize| p[at + k].1.parse::().expect("number"); + let off = Vec2::new(0.0, 1.0).rotate(30f64.to_radians()) * 2.0; + assert!((num(1) - 30.0).abs() < 1e-9, "53 angle: the family turned by the hatch's angle"); + assert!((num(2) - 1.0).abs() < 1e-9 && (num(3) - 2.0).abs() < 1e-9, "43/44 base point at the hatch origin"); + assert!((num(4) - off.x).abs() < 1e-9 && (num(5) - off.y).abs() < 1e-9, "45/46 offset: the spacing, turned"); + assert_eq!(p[at + 6], (79, "0".into()), "79 dashes"); + // Read back to the same angle, spacing and families, and saved again unchanged. + let h = first_hatch(&text); + assert_eq!(h.pattern, "_USER"); + assert!((h.scale - 2.0).abs() < 1e-12 && (h.angle - 30f64.to_radians()).abs() < 1e-12, "{} {}", h.scale, h.angle); + assert!(near(&h.pattern_lines, &lines), "{:?}", h.pattern_lines); + assert!(near(&first_hatch(&save(h)).pattern_lines, &lines)); + + // One family is not doubled, and a predefined pattern is type 1 with its lines listed. + let single = save(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 0.0, Vec2::ZERO, cadcraft_doc::library::user_defined_lines(false))); + let p = pairs(&single); + assert_eq!(hatch_group(&p, 76).as_deref(), Some("0")); + assert_eq!(hatch_group(&p, 77).as_deref(), Some("0")); + assert_eq!(hatch_group(&p, 78).as_deref(), Some("1"), "the one family is listed"); + assert_eq!(first_hatch(&single).pattern_lines.len(), 1); + let ansi = save(hatch("ANSI31", 1.0, 0.0, Vec2::ZERO, custom_lines())); + let p = pairs(&ansi); + assert_eq!(hatch_group(&p, 76).as_deref(), Some("1")); + assert_eq!(hatch_group(&p, 77).as_deref(), Some("0")); + assert_eq!(hatch_group(&p, 78).as_deref(), Some("2")); +} + +/// A user-defined hatch's families are a pattern definition like any other's, so an imported one +/// based away from its origin and doubled keeps both families' angle, base point, offset and count +/// through a DXF save and a DWG save. Written as 78 = 0 they were lost: a reader with no fallback +/// drew nothing, and this program's fallback moved the base point to the hatch's origin. +#[test] +fn a_user_defined_hatch_keeps_its_line_definitions_through_dxf_and_dwg() { + // Two families based at (1,1): a double hatch whose lines do not start at its origin. + let mut lines = cadcraft_doc::library::user_defined_lines(true); + for l in &mut lines { + l.origin = (1.0, 1.0); + } + let d = drawing(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 30f64.to_radians(), Vec2::ZERO, lines.clone())); + let text = write_dxf(&d); + assert_eq!(hatch_group(&pairs(&text), 78).as_deref(), Some("2"), "the file lists both families"); + let back = first_hatch(&text); + assert_eq!(back.pattern_lines.len(), 2, "{:?}", back.pattern_lines); + assert!(near(&back.pattern_lines, &lines), "{:?}", back.pattern_lines); + // A DWG keeps them too: the DWG bridge converts the same written HATCH. + #[cfg(not(target_arch = "wasm32"))] + { + cadcraft_io::dwg_worker::allow_in_process(); + let dwg = cadcraft_io::write(&d, "user-pattern.dwg").expect("write dwg"); + let h = first_hatch_of(&cadcraft_io::read(&dwg, "user-pattern.dwg").expect("read dwg")); + assert_eq!(h.pattern_lines.len(), 2, "{:?}", h.pattern_lines); + assert!(near(&h.pattern_lines, &lines), "{:?}", h.pattern_lines); + } +} + +/// A user-defined hatch a file lists with 78 = 0 (AutoCAD writes its own so) has no definition +/// lines: the reader makes its families from the double flag (77), and keeps the hatch's angle +/// (52) and spacing (41) to turn and space them. +#[test] +fn a_user_defined_hatch_listing_no_lines_gets_its_families_from_the_double_flag() { + let lines = cadcraft_doc::library::user_defined_lines(false); + let text = save(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 30f64.to_radians(), Vec2::new(1.0, 2.0), lines)); + let p = pairs(&text); + let at = pattern_data(&p); + let end = p.iter().skip(at).position(|(c, _)| *c == 98).map(|k| at + k).expect("98"); + for double in [false, true] { + // The hatch as such a file has it: its double flag, then 78 = 0 and no lines. + let mut q = p.clone(); + q.splice(at..end, [(78, "0".to_string())]); + let flag = q[..at].iter().rposition(|(c, _)| *c == 77).expect("77"); + q[flag].1 = u8::from(double).to_string(); + assert_eq!(hatch_group(&q, 78).as_deref(), Some("0")); + assert_eq!(hatch_group(&q, 53), None, "no definition line is left in the file"); + + let h = first_hatch(&join(&q)); + assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN); + assert!((h.scale - 2.0).abs() < 1e-12 && (h.angle - 30f64.to_radians()).abs() < 1e-12, "{} {}", h.scale, h.angle); + assert_eq!(h.pattern_lines.len(), if double { 2 } else { 1 }, "double = {double}: {:?}", h.pattern_lines); + assert!(near(&h.pattern_lines, &cadcraft_doc::library::user_defined_lines(double)), "double = {double}: {:?}", h.pattern_lines); + } +} + #[test] fn library_named_patterns_keep_the_files_definition() { // The library's AR-CONC only approximates AutoCAD's: the file's own lines are kept and saved. @@ -146,3 +253,17 @@ fn hostile_pattern_definitions_are_capped() { d.add(&Space::Model, Common::default(), EntityKind::Hatch(h)).expect("add"); let _ = cadcraft_render::build(&d, &Space::Model, &cadcraft_render::Options::default()); } + +#[test] +fn a_hatch_too_small_to_scale_saves_the_same_lines_each_time() { + // A spacing at or below 1e-9 is drawn and read at unit scale; the writer uses the same scale, + // so saving again does not shrink the lines. + let lines = cadcraft_doc::library::user_defined_lines(false); + let d = drawing(hatch(cadcraft_doc::library::USER_PATTERN, 1e-9, 0.0, Vec2::ZERO, lines)); + let once = first_hatch(&write_dxf(&d)); + let twice = first_hatch(&write_dxf(&drawing(once.clone()))); + // Compared as a ratio: the values are far below any fixed tolerance. + let spacing = |h: &Hatch| h.pattern_lines.first().map(|l| l.delta.1).unwrap_or(f64::NAN); + let ratio = spacing(&twice) / spacing(&once); + assert!((ratio - 1.0).abs() < 1e-6, "{:?} then {:?}", once.pattern_lines, twice.pattern_lines); +} diff --git a/crates/io/tests/it/layout_flags.rs b/crates/io/tests/it/layout_flags.rs new file mode 100644 index 000000000..5d79f5d52 --- /dev/null +++ b/crates/io/tests/it/layout_flags.rs @@ -0,0 +1,158 @@ +//! Each LAYOUT object's own flags (group 70 after the AcDbLayout marker; DXF Reference, LAYOUT: +//! 1 is the layout's PSLTSCALE and 2 its LIMCHECK, each the value in effect while that layout is +//! current) are saved as the file had them. Saving wrote 1 for every layout, which turned +//! PSLTSCALE on in each paper-space layout whatever the source said. + +use cadcraft_doc::Drawing; +use cadcraft_io::{read, read_dxf, write, write_dxf}; + +/// Each LAYOUT object's name and its own flags (the AcDbLayout groups 1 and 70) in DXF text. +fn layout_flags(text: &str) -> Vec<(String, i64)> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let (mut inside, mut subclass, mut name, mut flags) = (false, "", None, None); + for pair in lines.chunks(2) { + let [code, value] = pair else { break }; + match *code { + "0" => { + if let (true, Some(n), Some(f)) = (inside, name.take(), flags.take()) { + out.push((n, f)); + } + (inside, subclass, name, flags) = (*value == "LAYOUT", "", None, None); + } + "100" if inside => subclass = value, + "1" if inside && subclass == "AcDbLayout" => name = Some(value.to_string()), + "70" if inside && subclass == "AcDbLayout" => flags = value.parse().ok(), + _ => {} + } + } + out +} + +/// `text` with the AcDbLayout group 70 of each layout named in `set` replaced by its value. +fn with_layout_flags(text: &str, set: &[(&str, i64)]) -> String { + let mut lines: Vec = text.lines().map(str::to_string).collect(); + let mut i = 0; + while i + 5 < lines.len() { + let at = |k: usize| lines[i + k].trim(); + if at(0) == "100" + && at(1) == "AcDbLayout" + && at(2) == "1" + && at(4) == "70" + && let Some((_, f)) = set.iter().find(|(n, _)| *n == at(3)) + { + lines[i + 5] = f.to_string(); + } + i += 2; + } + lines.join("\n") +} + +/// The flags each layout of `text` has, sorted by name. +fn sorted(text: &str) -> Vec<(String, i64)> { + let mut v = layout_flags(text); + v.sort(); + v +} + +/// A DXF whose layouts have their own flags: PSLTSCALE off (0), off with LIMCHECK on (2), both on +/// (3), and the Model layout with LIMCHECK on. +fn source() -> String { + let mut d = Drawing::new_imperial(); + d.layouts = vec![cadcraft_doc::Layout::new("A", 1), cadcraft_doc::Layout::new("B", 2), cadcraft_doc::Layout::new("C", 3)].into(); + let text = with_layout_flags(&write_dxf(&d), &[("Model", 2), ("A", 0), ("B", 2), ("C", 3)]); + assert_eq!(sorted(&text), [("A", 0), ("B", 2), ("C", 3), ("Model", 2)].map(|(n, f)| (n.to_string(), f)), "the source as made"); + text +} + +/// The flags each layout of [`source`] has after it is read, saved as `name` and read back, and +/// the flags it was made with. +fn after_save(name: &str) -> (Vec<(String, i64)>, Vec<(String, i64)>) { + let text = source(); + let d = read_dxf(text.as_bytes()).expect("read"); + let back = read(&write(&d, name).expect("save"), name).expect("reopen"); + (sorted(&write_dxf(&back)), sorted(&text)) +} + +#[test] +fn layout_flags_are_saved_as_read() { + let (saved, made) = after_save("sheet.dxf"); + assert_eq!(saved, made); +} + +// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DWG saving fails there. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn layout_flags_survive_a_dwg_save() { + cadcraft_io::dwg_worker::allow_in_process(); + let (saved, made) = after_save("sheet.dwg"); + assert_eq!(saved, made); +} + +#[test] +fn only_the_bits_the_reference_defines_are_written() { + // 4 and above have no meaning in the DXF Reference: a damaged file's other bits are dropped, + // the two defined ones kept. + let text = with_layout_flags(&source(), &[("A", 4 | 2), ("B", -1)]); + let back = sorted(&write_dxf(&read_dxf(text.as_bytes()).expect("read"))); + let flags = |name: &str| back.iter().find(|(n, _)| n == name).map(|&(_, f)| f); + assert_eq!((flags("A"), flags("B")), (Some(2), Some(3)), "{back:?}"); +} + +#[test] +fn a_layout_record_without_its_marker_takes_no_plot_flags_as_its_own() { + // Before the AcDbLayout marker group 70 is the plot layout flags: a LAYOUT record without the + // marker is read with no flags of its own, not with those. + let text = source(); + let lines: Vec<&str> = text.lines().collect(); + let marker = lines.windows(4).position(|w| w[0].trim() == "100" && w[1].trim() == "AcDbLayout" && w[3].trim() == "A").expect("A's marker"); + let cut = [&lines[..marker], &lines[marker + 2..]].concat().join("\n"); + let d = read_dxf(cut.as_bytes()).expect("read"); + let flags: Vec<(&str, Option)> = d.layouts.iter().map(|l| (l.name.as_str(), l.flags)).collect(); + assert_eq!(flags.len(), 3, "{flags:?}"); + for (name, f) in &flags { + let want = match *name { + "B" => Some(2), + "C" => Some(3), + _ => None, + }; + assert_eq!(*f, want, "{flags:?}"); + } +} + +/// The DWG bridge carries a DWG's layout flags into the DXF CADCraft reads: a DWG another program +/// wrote with PSLTSCALE off and LIMCHECK on in its layout converts to a DXF that says so. +// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526). +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn a_dwg_layouts_flags_reach_the_converted_dxf() { + let mut doc = acadrust::CadDocument::new(); + let mut set = 0; + for o in doc.objects.values_mut() { + if let acadrust::objects::ObjectType::Layout(l) = o + && l.name == "Layout1" + { + l.flags = 2; + set += 1; + } + } + assert_eq!(set, 1, "the DWG has a paper-space layout"); + let dwg = acadrust::DwgWriter::write_to_vec(&doc).expect("DWG"); + cadcraft_io::dwg_worker::allow_in_process(); + let d = read(&dwg, "sheet.dwg").expect("read the DWG"); + let flags = layout_flags(&write_dxf(&d)); + assert!(flags.contains(&("Layout1".to_string(), 2)), "{flags:?}"); +} + +#[test] +fn a_layout_without_its_own_flags_takes_psltscale() { + // A layout made in CADCraft has no flags of its own: it gets the drawing's PSLTSCALE, the + // value CADCraft draws every layout with, and LIMCHECK off, as CADCraft has no limits check. + for psltscale in [0, 1] { + let mut d = Drawing::new_imperial(); + d.header.set_i64("PSLTSCALE", psltscale); + let flags = layout_flags(&write_dxf(&d)); + assert!(flags.len() > 1, "Model and the paper-space layouts: {flags:?}"); + assert!(flags.iter().all(|(_, f)| *f == psltscale), "PSLTSCALE {psltscale}: {flags:?}"); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index c45a57658..e3d58fbe8 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -2,8 +2,10 @@ mod acad_interop; #[cfg(not(target_arch = "wasm32"))] mod acis_data_store; mod angle_header; +mod annotative_block_contexts; mod annotative_orientation; mod annotative_roundtrip; +mod annotative_text_contexts; mod assoc_array_roundtrip; mod assoc_dependency_prune; mod attdef_insert_dwg; @@ -16,6 +18,7 @@ mod dash_controls; mod dim_block_resave_roundtrip; mod dim_block_text; mod dim_marks_roundtrip; +mod dim_text_below; mod dim_text_frame; mod dimstyle_vars_roundtrip; mod dimtfill_roundtrip; @@ -44,6 +47,7 @@ mod hatch_pattern_def; mod helix_roundtrip; mod large_radial_dimension; mod layer_states_acad; +mod layout_flags; mod layout_limits_roundtrip; mod layout_paper_units; mod layout_plot_flags; @@ -62,6 +66,7 @@ mod mleader_roundtrip; mod mline_roundtrip; #[cfg(not(target_arch = "wasm32"))] mod model_layout_plot_type; +mod mtext_background_mask; mod mtext_caret_spaces; mod mtext_columns_roundtrip; mod mtext_embedded_object; @@ -73,6 +78,7 @@ mod ole2frame_roundtrip; mod ole_frame; mod paperview_marker; mod passthrough_image_roundtrip; +mod pdf_fill_outline; mod pdf_followups; mod pdf_import; mod pdf_layers; @@ -108,7 +114,9 @@ mod user_lin_pat_roundtrip; mod view_tables_roundtrip; mod view_target; mod viewport_clip_roundtrip; +mod viewport_ucs_roundtrip; #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] mod visualstyle_dwg; +mod vport_circle_sides; mod xclip_roundtrip; mod xref_roundtrip; diff --git a/crates/io/tests/it/mleader_roundtrip.rs b/crates/io/tests/it/mleader_roundtrip.rs index 7a50c20d1..5fa1814f8 100644 --- a/crates/io/tests/it/mleader_roundtrip.rs +++ b/crates/io/tests/it/mleader_roundtrip.rs @@ -32,6 +32,7 @@ fn text_mleader() -> MLeader { line_spacing: 1.25, line_spacing_exact: true, columns: None, + background: None, }), style: "Callout".into(), arrow_size: 0.3, @@ -89,6 +90,8 @@ fn spline_leader_with_block_content_and_attributes() { style: "Standard".into(), halign: HAlign::default(), valign: VAlign::default(), + backwards: false, + upside_down: false, }; blk.entities.push(Entity::new( Handle(0x201), diff --git a/crates/io/tests/it/mtext_background_mask.rs b/crates/io/tests/it/mtext_background_mask.rs new file mode 100644 index 000000000..383ebee74 --- /dev/null +++ b/crates/io/tests/it/mtext_background_mask.rs @@ -0,0 +1,128 @@ +//! MTEXT background mask (DXF groups 90, 63/421, 45) conditional emission and round-trip. + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::{Common, Drawing, EntityKind, MText, MTextBackground, MTextColumnType, MTextColumns, Space}; +use cadcraft_geom::Vec3; +use cadcraft_io::{read_dxf, write_dxf}; + +fn make_mtext(background: Option, columns: Option) -> MText { + MText { + insert: Vec3::new(10.0, 20.0, 0.0), + height: 2.5, + width: 50.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "Hello MTEXT".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns, + background, + } +} + +fn round_trip(t: MText) -> (MText, String) { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + let dxf = write_dxf(&d); + let back = read_dxf(dxf.as_bytes()).unwrap(); + let entity = back + .model + .iter() + .find_map(|e| match &e.kind { + EntityKind::MText(m) => Some(m.clone()), + _ => None, + }) + .expect("MText after round trip"); + (entity, dxf) +} + +/// Extract `(group_code, value)` pairs of the first `MTEXT` entity in `ENTITIES`. +fn mtext_entity_tags(dxf: &str) -> Vec<(i32, String)> { + let mut lines = dxf.lines(); + let mut pairs = Vec::new(); + let mut in_entities = false; + let mut in_mtext = false; + while let (Some(c), Some(v)) = (lines.next(), lines.next()) { + let code: i32 = c.trim().parse().expect("group code"); + let val = v.trim().to_string(); + if code == 0 && val == "SECTION" { + if let (Some(_), Some(sec)) = (lines.next(), lines.next()) { + in_entities = sec.trim() == "ENTITIES"; + } + continue; + } + if !in_entities { + continue; + } + if code == 0 { + if in_mtext { + break; + } + if val == "MTEXT" { + in_mtext = true; + } + continue; + } + if in_mtext { + pairs.push((code, val)); + } + } + pairs +} + +#[test] +fn mtext_background_mask_zero_omits_conditional_tags() { + let bg = MTextBackground { mask: 0, color: Some(Color::True(Rgb(10, 20, 30))), scale: 2.0 }; + let (back, dxf) = round_trip(make_mtext(Some(bg), None)); + assert_eq!(back.background, None); + + let tags = mtext_entity_tags(&dxf); + for forbidden in [90, 63, 421, 45, 441] { + assert!(!tags.iter().any(|(c, _)| *c == forbidden), "mask 0 must not emit group {forbidden}: {tags:?}"); + } +} + +#[test] +fn mtext_background_window_fill_omits_color_tags_and_roundtrips() { + for mask in [2u8, 3u8] { + let bg = MTextBackground { mask, color: Some(Color::Index(1)), scale: 2.25 }; + let (back, dxf) = round_trip(make_mtext(Some(bg), None)); + assert_eq!(back.background, Some(MTextBackground { mask, color: None, scale: 2.25 })); + + let tags = mtext_entity_tags(&dxf); + assert!(tags.iter().any(|(c, v)| *c == 90 && v == &mask.to_string()), "expected group 90={mask}: {tags:?}"); + assert!(tags.iter().any(|(c, v)| *c == 45 && v.parse::().ok() == Some(2.25)), "expected group 45=2.25: {tags:?}"); + for color_code in [63, 421, 441] { + assert!(!tags.iter().any(|(c, _)| *c == color_code), "window background (mask={mask}) must not emit group {color_code}: {tags:?}"); + } + } +} + +#[test] +fn mtext_background_custom_aci_and_truecolor_before_columns_roundtrips() { + let cols = MTextColumns { kind: MTextColumnType::Static, count: 2, gutter: 5.0, height: 20.0, ..Default::default() }; + + let bg_aci = MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 1.75 }; + let (back_aci, dxf_aci) = round_trip(make_mtext(Some(bg_aci.clone()), Some(cols.clone()))); + assert_eq!(back_aci.background, Some(bg_aci)); + let tags_aci = mtext_entity_tags(&dxf_aci); + let col_pos_aci = tags_aci.iter().position(|(c, _)| *c == 75 || *c == 101).expect("column tags"); + let p90 = tags_aci.iter().position(|(c, v)| *c == 90 && v == "1").expect("group 90=1"); + let p63 = tags_aci.iter().position(|(c, v)| *c == 63 && v == "3").expect("group 63=3"); + let p45 = tags_aci.iter().position(|(c, v)| *c == 45 && v.parse::().ok() == Some(1.75)).expect("group 45=1.75"); + assert!(!tags_aci.iter().any(|(c, _)| *c == 421), "ACI color must not emit 421: {tags_aci:?}"); + assert!(p90 < col_pos_aci && p63 < col_pos_aci && p45 < col_pos_aci, "background tags must precede columns"); + + let rgb = Rgb(0x12, 0x34, 0x56); + let bg_rgb = MTextBackground { mask: 1, color: Some(Color::True(rgb)), scale: 2.0 }; + let (back_rgb, dxf_rgb) = round_trip(make_mtext(Some(bg_rgb.clone()), Some(cols))); + assert_eq!(back_rgb.background, Some(bg_rgb)); + let tags_rgb = mtext_entity_tags(&dxf_rgb); + let col_pos_rgb = tags_rgb.iter().position(|(c, _)| *c == 75 || *c == 101).expect("column tags"); + let r90 = tags_rgb.iter().position(|(c, v)| *c == 90 && v == "1").expect("group 90=1"); + let r63 = tags_rgb.iter().position(|(c, _)| *c == 63).expect("group 63"); + let r421 = tags_rgb.iter().position(|(c, v)| *c == 421 && v == &rgb.to_u32().to_string()).expect("group 421"); + let r45 = tags_rgb.iter().position(|(c, v)| *c == 45 && v.parse::().ok() == Some(2.0)).expect("group 45=2.0"); + assert!(r90 < col_pos_rgb && r63 < col_pos_rgb && r421 < col_pos_rgb && r45 < col_pos_rgb, "truecolor background tags must precede columns"); +} diff --git a/crates/io/tests/it/mtext_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs index 31ccf4c30..93e4019e6 100644 --- a/crates/io/tests/it/mtext_caret_spaces.rs +++ b/crates/io/tests/it/mtext_caret_spaces.rs @@ -41,6 +41,7 @@ fn drawing() -> Result<(Drawing, Vec<(Handle, String)>), Box) -> MText line_spacing: 1.0, line_spacing_exact: false, columns, + background: None, } } diff --git a/crates/io/tests/it/mtext_embedded_object.rs b/crates/io/tests/it/mtext_embedded_object.rs index 4bd95cb77..b4e870cbd 100644 --- a/crates/io/tests/it/mtext_embedded_object.rs +++ b/crates/io/tests/it/mtext_embedded_object.rs @@ -22,6 +22,7 @@ fn with_embedded_object(rotation: f64, dir: (f64, f64)) -> String { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); let dxf = write_dxf(&d); diff --git a/crates/io/tests/it/mtext_line_spacing.rs b/crates/io/tests/it/mtext_line_spacing.rs index 8a030cbc7..a3afcb75f 100644 --- a/crates/io/tests/it/mtext_line_spacing.rs +++ b/crates/io/tests/it/mtext_line_spacing.rs @@ -18,6 +18,7 @@ fn line_spacing_style_roundtrips() { line_spacing: 1.5, line_spacing_exact: exact, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t.clone())).unwrap(); let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); @@ -27,3 +28,73 @@ fn line_spacing_style_roundtrips() { assert_eq!(r.line_spacing, 1.5); } } + +#[test] +fn background_mask_roundtrips() { + use cadcraft_color::{Color, Rgb}; + use cadcraft_doc::MTextBackground; + for bg in [ + MTextBackground { mask: 2, color: None, scale: 1.5 }, + MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 2.0 }, + MTextBackground { mask: 1, color: Some(Color::True(Rgb(12, 34, 56))), scale: 1.25 }, + ] { + let mut d = Drawing::new_metric(); + let t = MText { + insert: Vec3::new(1.0, 2.0, 0.0), + height: 2.5, + width: 40.0, + attach: 5, + rotation: 0.0, + style: "Standard".into(), + contents: "MASKED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(bg.clone()), + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let Some(EntityKind::MText(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no mtext") }; + assert_eq!(r.background, Some(bg)); + } +} + +#[test] +fn background_mask_roundtrips_with_legacy_and_embedded_columns() { + use cadcraft_color::Color; + use cadcraft_doc::{MTextBackground, MTextColumnType, MTextColumns}; + use cadcraft_io::{SaveOptions, Version, write_with}; + let bg = MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 1.5 }; + let cols = MTextColumns { + kind: MTextColumnType::Static, + count: 2, + gutter: 2.0, + height: 20.0, + auto_height: false, + heights: Vec::new(), + flow_reversed: false, + }; + for version in [Version::R2013, Version::R2018] { + let mut d = Drawing::new_metric(); + let t = MText { + insert: Vec3::new(1.0, 2.0, 0.0), + height: 2.5, + width: 22.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "COL1\\NCOL2".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: Some(cols.clone()), + background: Some(bg.clone()), + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + let bytes = write_with(&d, "a.dxf", &SaveOptions { version: Some(version), ..Default::default() }).unwrap(); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let Some(EntityKind::MText(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no mtext") }; + assert_eq!(r.background, Some(bg.clone()), "version={version:?}"); + assert!(r.columns.is_some(), "columns lost for version={version:?}"); + } +} diff --git a/crates/io/tests/it/multiline_attributes.rs b/crates/io/tests/it/multiline_attributes.rs index 428dc7db5..6c23e3bcb 100644 --- a/crates/io/tests/it/multiline_attributes.rs +++ b/crates/io/tests/it/multiline_attributes.rs @@ -257,6 +257,8 @@ fn multiline_attributes_are_read_with_their_text() { assert_eq!((ad.tag.as_str(), ad.prompt.as_str()), ("LABEL", "Site")); assert_eq!(ad.text.value, "SITE\nNAME"); assert_eq!(ad.multiline.as_ref().map(|m| m.mtext.contents.as_str()), Some("SITE\\PNAME")); + // The attribute subclass's 71 is its multiline flag (4, 2), not text generation flags. + assert!(!ad.text.upside_down && !ad.text.backwards && !a.text.backwards && !a.text.upside_down); } #[test] @@ -292,6 +294,7 @@ fn multiline_attributes_survive_a_save() { let again = read_dxf(out.as_bytes()).unwrap(); assert_eq!(reference(&again).attribs[0], reference(&d).attribs[0]); assert_eq!(definition(&again), definition(&d)); + assert!(!definition(&again).text.upside_down && !reference(&again).attribs[0].text.backwards); } #[test] diff --git a/crates/io/tests/it/paperview_marker.rs b/crates/io/tests/it/paperview_marker.rs index 283cfc8ac..74231d8c8 100644 --- a/crates/io/tests/it/paperview_marker.rs +++ b/crates/io/tests/it/paperview_marker.rs @@ -18,6 +18,9 @@ fn viewport(id: u32, frozen_layers: Vec, layer_colors: Vec<(String, Colo layer_colors, clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) } diff --git a/crates/io/tests/it/pdf_fill_outline.rs b/crates/io/tests/it/pdf_fill_outline.rs new file mode 100644 index 000000000..ebd15e3bf --- /dev/null +++ b/crates/io/tests/it/pdf_fill_outline.rs @@ -0,0 +1,89 @@ +//! A solid fill is plotted to PDF as the outline of its triangles (#3459): far less path data, +//! the same filled area, islands still empty. + +use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space}; +use cadcraft_geom::{PolyVertex, Vec2}; +use cadcraft_io::plotter; +use serde_json::json; + +/// Vertices of the outer boundary. +const RIM: usize = 400; +/// Radius of the outer boundary. +const R: f64 = 100.0; +/// Half the width of the square island. +const HALF: f64 = 20.0; + +fn ring(points: impl Iterator, outer: bool) -> HatchLoop { + HatchLoop { vertices: points.map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), outer, boundary_flags: None, sources: Vec::new() } +} + +/// A solid hatch: a many-sided outer loop around a square island. +fn drawing() -> Drawing { + let rim = (0..RIM).map(|i| { + let a = std::f64::consts::TAU * i as f64 / RIM as f64; + (R * a.cos(), R * a.sin()) + }); + let island = [(-HALF, -HALF), (HALF, -HALF), (HALF, HALF), (-HALF, HALF)].into_iter(); + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![ring(rim, true), ring(island, false)], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch)).unwrap(); + d +} + +#[test] +fn a_solid_hatch_plots_as_its_outline_with_the_island_empty() { + let bytes = plotter::plot(&drawing(), &Space::Model, &json!({"paper": "A4", "compress": false})).unwrap(); + let doc = crate::pdf_read::read(&bytes); + let drawn = crate::pdf_read::drawn(doc.content()); + let fills = drawn.iter().filter(|o| o.op == "f").count(); + assert_eq!(fills, 1, "one fill for the hatch"); + let path: Vec<&crate::pdf_read::Op> = drawn.iter().filter(|o| matches!(o.op.as_str(), "m" | "l")).collect(); + // The triangles of a fill around an island number at least its boundary vertices; one + // subpath per triangle would give that many `m` and twice as many `l`. + let subpaths = path.iter().filter(|o| o.op == "m").count(); + assert!(subpaths < RIM / 10, "{subpaths} subpaths for {RIM} boundary vertices"); + assert!(path.len() < 2 * RIM, "{} path vertices for {RIM} boundary vertices", path.len()); + + // Fill the path as a viewer does and compare with the shape. + let mut pb = tiny_skia::PathBuilder::new(); + let (mut lo, mut hi) = ((f32::MAX, f32::MAX), (f32::MIN, f32::MIN)); + for o in &path { + let (x, y) = (o.nums[0] as f32, o.nums[1] as f32); + (lo, hi) = ((lo.0.min(x), lo.1.min(y)), (hi.0.max(x), hi.1.max(y))); + if o.op == "m" { + pb.close(); + pb.move_to(x, y); + } else { + pb.line_to(x, y); + } + } + pb.close(); + let size = 400u32; + let k = size as f32 / (hi.0 - lo.0).max(hi.1 - lo.1); + let mut pm = tiny_skia::Pixmap::new(size, size).unwrap(); + let mut paint = tiny_skia::Paint::default(); + paint.set_color_rgba8(0, 0, 0, 255); + let to_px = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, -lo.0 * k, -lo.1 * k); + pm.fill_path(&pb.finish().unwrap(), &paint, tiny_skia::FillRule::Winding, to_px, None); + let alpha = |fx: f64, fy: f64| pm.pixel((fx * f64::from(size)) as u32, (fy * f64::from(size)) as u32).unwrap().alpha(); + assert_eq!(alpha(0.5, 0.5), 0, "the island is empty"); + assert_eq!(alpha(0.5 + 0.3, 0.5), 255, "the ring between island and rim is filled"); + assert_eq!(alpha(0.03, 0.03), 0, "outside the rim is empty"); + // The filled share of the bounding square matches the ring's. + let covered: f64 = pm.pixels().iter().map(|p| f64::from(p.alpha()) / 255.0).sum::() / f64::from(size * size); + let want = (std::f64::consts::PI * R * R - 4.0 * HALF * HALF) / (4.0 * R * R); + assert!((covered - want).abs() < 0.01, "covered {covered}, the ring covers {want}"); +} diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index ce5b74eae..2f7eb3b42 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -435,6 +435,8 @@ fn a_plot_of_a_drawing_imports_back_as_its_geometry() { style: "Standard".into(), halign: HAlign::Left, valign: Default::default(), + backwards: false, + upside_down: false, }), ) .unwrap(); diff --git a/crates/io/tests/it/pdf_layers.rs b/crates/io/tests/it/pdf_layers.rs index b32682f46..3711ccf6b 100644 --- a/crates/io/tests/it/pdf_layers.rs +++ b/crates/io/tests/it/pdf_layers.rs @@ -150,6 +150,9 @@ fn viewport_contents_keep_their_layers() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&paper, Common { layer: "Viewports".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/io/tests/it/proxy_layers.rs b/crates/io/tests/it/proxy_layers.rs index 8ef23cc29..091bc3a87 100644 --- a/crates/io/tests/it/proxy_layers.rs +++ b/crates/io/tests/it/proxy_layers.rs @@ -1,7 +1,8 @@ //! Proxy graphics name layers by their index in the file's LAYER table (#3094). AutoCAD keeps //! layers that only proxy graphics use, but saves the graphics with their old indices after //! PURGE removed a layer before them, which moves the graphics to other layers; CADCraft turns the -//! indices into the written table's on save. +//! indices into the written table's on save. Linetype indices (the LTYPE table without ByBlock +//! and ByLayer) follow it the same way. use cadcraft_doc::{EntityKind, Unknown}; use cadcraft_io::{read_dxf, write_dxf}; @@ -148,3 +149,53 @@ fn a_proxy_copied_from_another_drawing_keeps_its_layers() { let again = read_dxf(write_dxf(&target).as_bytes()).expect("reopen"); assert_eq!(circle_layers(&again), ["0", "B_NOTIZ", "C_EXTRA", "C_EXTRA"]); } + +/// Linetype indices count the LTYPE records other than ByBlock and ByLayer, and follow the +/// written table the same way: removing an unused linetype before the one the graphics draw +/// with keeps them on it after a save. So does a record without a name there, which counts on +/// reading but isn't written. +#[test] +fn removing_a_linetype_before_the_one_the_graphics_use_keeps_it_on_save() { + let mut circle: Vec = [25.0f64, 70.0, 0.0, 15.0, 0.0, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect(); + circle.truncate(56); + let chunks = [chunk(18, &2u32.to_le_bytes()), chunk(2, &circle)]; + let body = chunks.concat(); + let mut g = ((8 + body.len()) as u32).to_le_bytes().to_vec(); + g.extend((chunks.len() as u32).to_le_bytes()); + g.extend(body); + // The table ByBlock, ByLayer, Continuous, `unused` (no name for `None`), HIDDEN. + let file = |unused: Option<&str>| -> String { + let mut tags: Vec<(i32, String)> = Vec::new(); + let mut push = |list: &[(i32, &str)]| tags.extend(list.iter().map(|(c, v)| (*c, v.to_string()))); + push(&[(0, "SECTION"), (2, "CLASSES"), (0, "CLASS"), (1, "SYNLAYERTEST"), (2, "SynLayerTest"), (3, "SyntheticProxyApp")]); + push(&[(90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC"), (0, "SECTION"), (2, "TABLES"), (0, "TABLE"), (2, "LTYPE")]); + for (handle, name) in [("14", Some("ByBlock")), ("15", Some("ByLayer")), ("16", Some("Continuous")), ("17", unused), ("18", Some("HIDDEN"))] { + let dashed = handle == "17" || handle == "18"; + push(&[(0, "LTYPE"), (5, handle)]); + if let Some(name) = name { + push(&[(2, name)]); + } + push(&[(70, "0"), (3, "")]); + push(if dashed { + &[(72, "65"), (73, "2"), (40, "0.375"), (49, "0.25"), (74, "0"), (49, "-0.125"), (74, "0")] + } else { + &[(72, "65"), (73, "0"), (40, "0")] + }); + } + push(&[(0, "ENDTAB"), (0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES"), (0, "ACAD_PROXY_ENTITY"), (5, "21"), (100, "AcDbEntity"), (8, "0")]); + push(&[(100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (95, "0"), (70, "0")]); + tags.push((92, g.len().to_string())); + tags.extend(g.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect()))); + tags.extend([(93, "0".to_string()), (94, "0".to_string()), (0, "ENDSEC".to_string()), (0, "EOF".to_string())]); + tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() + }; + let linetype = |d: &cadcraft_doc::Drawing| proxy(d).graphics[0].common.linetype.clone(); + for unused in [Some("UNUSED"), None] { + let mut d = read_dxf(file(unused).as_bytes()).expect("read"); + assert_eq!(linetype(&d), "HIDDEN", "{unused:?}"); + d.linetypes.retain(|t| t.name != "UNUSED"); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + assert!(again.linetype("UNUSED").is_none()); + assert_eq!(linetype(&again), "HIDDEN", "{unused:?}"); + } +} diff --git a/crates/io/tests/it/roundtrip/cases.rs b/crates/io/tests/it/roundtrip/cases.rs index a6031ec8f..995427ffa 100644 --- a/crates/io/tests/it/roundtrip/cases.rs +++ b/crates/io/tests/it/roundtrip/cases.rs @@ -38,6 +38,8 @@ pub(super) fn text() -> Text { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, } } @@ -227,6 +229,18 @@ pub(super) fn text_obliques() -> Vec { .into() } +pub(super) fn text_generation() -> Vec { + [(true, false), (false, true), (true, true)] + .map(|(backwards, upside_down)| { + entity_case( + &format!("text/backwards={backwards}/upside_down={upside_down}"), + Common::default(), + EntityKind::Text(Text { backwards, upside_down, ..text() }), + ) + }) + .into() +} + pub(super) fn text_styles() -> Vec { ["Standard", "Notes"] .map(|style| entity_case(&format!("text/style={style}"), Common::default(), EntityKind::Text(Text { style: style.into(), ..text() }))) diff --git a/crates/io/tests/it/roundtrip/cases/geometry.rs b/crates/io/tests/it/roundtrip/cases/geometry.rs index e8168c183..0e36bfcaf 100644 --- a/crates/io/tests/it/roundtrip/cases/geometry.rs +++ b/crates/io/tests/it/roundtrip/cases/geometry.rs @@ -133,6 +133,7 @@ pub(crate) fn mtext() -> MText { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } diff --git a/crates/io/tests/it/roundtrip/cases/properties.rs b/crates/io/tests/it/roundtrip/cases/properties.rs index eab95e8ac..c84693a2c 100644 --- a/crates/io/tests/it/roundtrip/cases/properties.rs +++ b/crates/io/tests/it/roundtrip/cases/properties.rs @@ -285,8 +285,10 @@ pub(crate) fn layer_inheritance_overrides() -> Vec { .collect() } -/// Mirrored styles affect baseline placement; their metrics must not overwrite the entity's -/// own height/width/oblique. Font layout constructs consistent inputs, never expected output. +/// Mirrored text affects baseline placement: a TEXT's own flags mirror it (new text takes its +/// style's, so each mirrored style also has text whose flags differ). The style's metrics must +/// not overwrite the entity's own height/width/oblique/flags. Font layout constructs consistent +/// inputs, never expected output. pub(crate) fn alignment_style_interactions() -> Vec { let mut cases = Vec::new(); for (halign, valign) in [ @@ -296,7 +298,7 @@ pub(crate) fn alignment_style_interactions() -> Vec { (HAlign::Aligned, VAlign::Baseline), (HAlign::Fit, VAlign::Baseline), ] { - for flags in 0..4 { + for (flags, text_flags) in (0..4).flat_map(|f| [(f, f), (f, f ^ 3)]) { let style = TextStyle { name: "Notes".into(), height: 7.0, @@ -316,6 +318,8 @@ pub(crate) fn alignment_style_interactions() -> Vec { width_factor: 0.75, oblique: -0.125, rotation: 0.7, + backwards: text_flags & 1 != 0, + upside_down: text_flags & 2 != 0, ..text() }; if !matches!(halign, HAlign::Aligned | HAlign::Fit) { @@ -329,12 +333,16 @@ pub(crate) fn alignment_style_interactions() -> Vec { oblique: t.oblique, h, v, - backwards: style.backwards, - upside_down: style.upside_down, + backwards: t.backwards, + upside_down: t.upside_down, }; t.insert = cadcraft_fonts::baseline_start(&cadcraft_fonts::TextFont::Stroke, &t.value, ¶ms).to3(0.0); } - let mut case = entity_case(&format!("text/alignment-style/{halign:?}/{valign:?}/flags={flags}"), Common::default(), EntityKind::Text(t)); + let mut case = entity_case( + &format!("text/alignment-style/{halign:?}/{valign:?}/flags={flags}/text-flags={text_flags}"), + Common::default(), + EntityKind::Text(t), + ); *case.drawing.text_styles.iter_mut().find(|s| s.name == "Notes").unwrap() = style; cases.push(case); } diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index 70768d3b0..12b1137cf 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -29,6 +29,7 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { let Block { name, annotative, + scale_uniformly, base, entities: contents, description, @@ -39,9 +40,12 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { explodable, units, array, + // Session state (when an xref was read), never in a file. + xref_stamp: _, } = block.as_ref(); equal(name, &back.name, &path, "name"); equal(annotative, &back.annotative, &path, "annotative"); + equal(scale_uniformly, &back.scale_uniformly, &path, "scale_uniformly"); equal(base, &back.base, &path, "base"); equal(description, &back.description, &path, "description"); equal(xref_overlay, &back.xref_overlay, &path, "xref_overlay"); @@ -217,7 +221,7 @@ fn common(expected: &Common, actual: &Common, context: &str) { } fn text(expected: &Text, actual: &Text, context: &str) { - let Text { insert, align_pt, height, value, rotation, width_factor, oblique, style, halign, valign } = expected; + let Text { insert, align_pt, height, value, rotation, width_factor, oblique, style, halign, valign, backwards, upside_down } = expected; equal(insert, &actual.insert, context, "insert"); equal(align_pt, &actual.align_pt, context, "align_pt"); equal(height, &actual.height, context, "height"); @@ -228,10 +232,12 @@ fn text(expected: &Text, actual: &Text, context: &str) { equal(style, &actual.style, context, "style"); equal(halign, &actual.halign, context, "halign"); equal(valign, &actual.valign, context, "valign"); + equal(backwards, &actual.backwards, context, "backwards"); + equal(upside_down, &actual.upside_down, context, "upside_down"); } fn mtext(expected: &MText, actual: &MText, context: &str) { - let MText { insert, height, width, attach, rotation, style, contents, line_spacing, line_spacing_exact, columns } = expected; + let MText { insert, height, width, attach, rotation, style, contents, line_spacing, line_spacing_exact, columns, background } = expected; equal(insert, &actual.insert, context, "mtext.insert"); equal(height, &actual.height, context, "mtext.height"); equal(width, &actual.width, context, "mtext.width"); @@ -242,6 +248,7 @@ fn mtext(expected: &MText, actual: &MText, context: &str) { equal(line_spacing, &actual.line_spacing, context, "mtext.line_spacing"); equal(line_spacing_exact, &actual.line_spacing_exact, context, "mtext.line_spacing_exact"); equal(columns, &actual.columns, context, "mtext.columns"); + equal(background, &actual.background, context, "mtext.background"); } fn attrib(expected: &Attrib, actual: &Attrib, context: &str) { diff --git a/crates/io/tests/it/roundtrip/dwg/entities.rs b/crates/io/tests/it/roundtrip/dwg/entities.rs index 58f97d92f..87f646c65 100644 --- a/crates/io/tests/it/roundtrip/dwg/entities.rs +++ b/crates/io/tests/it/roundtrip/dwg/entities.rs @@ -76,6 +76,10 @@ fn text_values() { check(cases::text_values()); } #[test] +fn text_generation() { + check(cases::text_generation()); +} +#[test] #[ignore = "Confirmed DWG bridge loss: literal Unicode/MIF escape text is decoded again, including R2018"] fn text_literal_escapes() { check(cases::text_literal_escapes()); diff --git a/crates/io/tests/it/roundtrip/dxf/conformance.rs b/crates/io/tests/it/roundtrip/dxf/conformance.rs index 0f8d4a29d..22dd6b1e2 100644 --- a/crates/io/tests/it/roundtrip/dxf/conformance.rs +++ b/crates/io/tests/it/roundtrip/dxf/conformance.rs @@ -40,6 +40,8 @@ pub(super) fn model() -> Drawing { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, }), ) .unwrap(); diff --git a/crates/io/tests/it/roundtrip/dxf/entities.rs b/crates/io/tests/it/roundtrip/dxf/entities.rs index 5816d5017..14161751d 100644 --- a/crates/io/tests/it/roundtrip/dxf/entities.rs +++ b/crates/io/tests/it/roundtrip/dxf/entities.rs @@ -71,6 +71,10 @@ fn text_values() { check(cases::text_values()); } #[test] +fn text_generation() { + check(cases::text_generation()); +} +#[test] fn text_literal_escapes() { check(cases::text_literal_escapes()); } diff --git a/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs index 19e15beaa..0e42f6386 100644 --- a/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs +++ b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs @@ -74,6 +74,7 @@ fn fixtures() -> Vec { line_spacing: 1.75, line_spacing_exact: true, columns: None, + background: None, }), groups: "10\n1.25\n20\n-2.5\n30\n3.75\n40\n2.25\n41\n12.5\n71\n5\n50\n90\n7\nStandard\n1\nfirst\\Psecond\n73\n2\n44\n1.75\n", output: vec![ diff --git a/crates/io/tests/it/table_cellstyle_roundtrip.rs b/crates/io/tests/it/table_cellstyle_roundtrip.rs index a4eda079b..721b34403 100644 --- a/crates/io/tests/it/table_cellstyle_roundtrip.rs +++ b/crates/io/tests/it/table_cellstyle_roundtrip.rs @@ -18,6 +18,7 @@ fn modern_table_cell_values_have_reference_groups() { cells[0][0].text = "Title".into(); cells[0][0].merged = Some((1, cols as u32)); cells[0][1].text = "CoveredText".repeat(30); + cells[0][2].text.clear(); } let table = Table { col_widths: vec![2.0; cols], row_heights: vec![0.5; rows], cells, title: merged, ..Table::default() }; d.add(&Space::Model, Common::default(), EntityKind::Table(table.clone())).unwrap(); @@ -32,16 +33,12 @@ fn modern_table_cell_values_have_reference_groups() { let pairs: Vec<_> = lines.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect(); let start = pairs.iter().position(|p| *p == ("0", "ACAD_TABLE")).unwrap(); let end = start + 1 + pairs[start + 1..].iter().position(|p| p.0 == "0").unwrap(); - let values: Vec<_> = pairs[start..end].iter().filter(|p| p.0 == "302").map(|p| p.1).collect(); - let expected: Vec<_> = table - .cells - .iter() - .enumerate() - .flat_map(|(row, cells)| { - cells.iter().enumerate().map(move |(col, cell)| if merged && row == 0 && col > 0 { "" } else { cell.text.as_str() }) - }) + let values: Vec = pairs[start..end] + .split_inclusive(|p| *p == ("304", "ACVALUE_END")) + .filter(|block| block.contains(&("301", "CELL_VALUE"))) + .map(|block| block.iter().filter(|p| p.0 == "302" || p.0 == "303").map(|p| p.1).collect()) .collect(); - assert_eq!(values, expected); + assert_eq!(values, table.cells.iter().flatten().map(|cell| cell.text.clone()).collect::>()); assert_eq!(pairs[start..end].iter().filter(|p| **p == ("301", "CELL_VALUE")).count(), rows * cols); assert_eq!(pairs[start..end].iter().filter(|p| **p == ("304", "ACVALUE_END")).count(), rows * cols); let value_start = start + pairs[start..end].iter().position(|p| *p == ("301", "CELL_VALUE")).unwrap(); @@ -88,37 +85,19 @@ fn modern_table_cell_values_have_reference_groups() { ); let covered_start = cell_start + 1 + pairs[cell_start + 1..end].iter().position(|pair| *pair == ("171", "1")).unwrap(); let covered_end = covered_start + pairs[covered_start..end].iter().position(|pair| *pair == ("304", "ACVALUE_END")).unwrap(); + let covered = &pairs[covered_start..=covered_end]; + assert!(covered.contains(&("173", "1"))); + assert!(covered.iter().any(|p| p.0 == "303")); + assert_eq!(covered.iter().filter(|p| p.0 == "303" || p.0 == "302").map(|p| p.1).collect::(), table.cells[0][1].text); + let empty_start = covered_end + 1 + pairs[covered_end + 1..end].iter().position(|p| *p == ("171", "1")).unwrap(); + let empty_end = empty_start + pairs[empty_start..end].iter().position(|p| *p == ("304", "ACVALUE_END")).unwrap(); + assert!(pairs[empty_start..=empty_end].contains(&("173", "1"))); assert_eq!( - &pairs[covered_start..=covered_end], - &[ - ("171", "1"), - ("172", "0"), - ("173", "1"), - ("174", "0"), - ("175", "0"), - ("176", "0"), - ("91", "0"), - ("92", "0"), - ("178", "0"), - ("145", "0.0"), - ("301", "CELL_VALUE"), - ("93", "4"), - ("90", "4"), - ("1", ""), - ("94", "0"), - ("300", ""), - ("302", ""), - ("304", "ACVALUE_END") - ] + pairs[empty_start..=empty_end].iter().filter(|p| p.0 == "302" || p.0 == "303").copied().collect::>(), + vec![("302", "")] ); } - let mut expected_cells = table.cells.clone(); - if merged { - for cell in &mut expected_cells[0][1..] { - cell.text.clear(); - } - } - assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells, expected_cells); + assert_eq!(first_table(&cadcraft_io::read(&bytes, "t.dxf").unwrap()).cells, table.cells); } if merged { let bytes = cadcraft_io::write_with(&d, "t.dxf", &SaveOptions { version: Some(Version::R2004), binary: false }).unwrap(); diff --git a/crates/io/tests/it/text_carets_roundtrip.rs b/crates/io/tests/it/text_carets_roundtrip.rs index 0be87d200..7c38e5207 100644 --- a/crates/io/tests/it/text_carets_roundtrip.rs +++ b/crates/io/tests/it/text_carets_roundtrip.rs @@ -17,6 +17,8 @@ fn text(value: &str) -> Text { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, } } diff --git a/crates/io/tests/it/viewport_ucs_roundtrip.rs b/crates/io/tests/it/viewport_ucs_roundtrip.rs new file mode 100644 index 000000000..d2d8db754 --- /dev/null +++ b/crates/io/tests/it/viewport_ucs_roundtrip.rs @@ -0,0 +1,432 @@ +//! A layout viewport's own UCS (UCSVP and groups 110–112, 79, 146, 345, 346) and the groups +//! CADCraft doesn't model (snap, grid, lens, plot style, visual style, lighting…) survive reading, +//! saving as DXF or DWG and copying (#1316). + +use cadcraft_doc::*; +use cadcraft_geom::{Vec2, Vec3}; + +fn viewport() -> EntityKind { + EntityKind::Viewport(Viewport { + center: Vec3::new(50.0, 40.0, 0.0), + width: 80.0, + height: 60.0, + view_center: Vec2::new(10.0, 10.0), + view_height: 50.0, + id: 2, + ..Viewport::default() + }) +} + +/// A drawing with two named UCSs and one layout viewport, saved by CADCraft. +fn base() -> (Drawing, Handle) { + let mut d = Drawing::default(); + d.ucss.push(Ucs { name: "SITE".into(), origin: Vec3::new(100.0, 50.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) }); + d.ucss.push(Ucs { name: "BASE".into(), origin: Vec3::ZERO, x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) }); + let paper = Space::Paper(d.layouts[0].name.clone()); + let h = d.add(&paper, Common::default(), viewport()).unwrap(); + (d, h) +} + +/// The (code, value) pairs of every `kind` record in DXF text. +fn records(text: &str, kind: &str) -> Vec> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec> = Vec::new(); + let mut inside = false; + for pair in lines.chunks(2) { + let [code, value] = pair else { break }; + if *code == "0" { + inside = *value == kind; + if inside { + out.push(Vec::new()); + } + } else if inside && let Some(rec) = out.last_mut() { + rec.push((code.to_string(), value.to_string())); + } + } + out +} + +fn group<'a>(rec: &'a [(String, String)], code: &str) -> Option<&'a str> { + rec.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str()) +} + +/// The handle of the `kind` table record named `name`. +fn record_handle(text: &str, kind: &str, name: &str) -> String { + records(text, kind).into_iter().find(|r| group(r, "2") == Some(name)).and_then(|r| group(&r, "5").map(str::to_string)).unwrap() +} + +/// The viewport record with handle `h`. +fn viewport_record(text: &str, h: Handle) -> Vec<(String, String)> { + records(text, "VIEWPORT").into_iter().find(|r| group(r, "5") == Some(h.hex().as_str())).unwrap() +} + +/// `text` with `groups` put into viewport `h`'s record after its status flags (group 90). +fn inject(text: &str, h: Handle, groups: &[(i32, String)]) -> String { + let lines: Vec<&str> = text.lines().collect(); + let mut out: Vec = Vec::new(); + let (mut in_vp, mut done) = (false, false); + let mut i = 0; + while i + 1 < lines.len() { + let (code, value) = (lines[i].trim(), lines[i + 1].trim()); + if code == "0" { + in_vp = value == "VIEWPORT"; + } + let ours = in_vp && !done; + out.push(lines[i].to_string()); + out.push(lines[i + 1].to_string()); + if ours && code == "5" && value != h.hex() { + in_vp = false; + } + if ours && code == "90" { + for (c, v) in groups { + out.push(c.to_string()); + out.push(v.clone()); + } + done = true; + } + i += 2; + } + assert!(done, "viewport {h:?} not found"); + out.join("\n") + "\n" +} + +const C6: f64 = 0.994_521_895_368_273_3; +const S6: f64 = 0.104_528_463_267_653_47; + +/// The groups another program writes on a viewport with a 6° UCS, after its status flags: +/// UCS, then the ones CADCraft doesn't model, with a visual style handle (`style`), plus the view +/// twist, direction and target that must not be carried raw. +fn foreign_groups(site: &str, base_ucs: &str, style: &str) -> Vec<(i32, String)> { + let mut g: Vec<(i32, String)> = vec![ + (13, "1.0".into()), + (23, "2.0".into()), + (14, "0.5".into()), + (24, "0.5".into()), + (15, "10.0".into()), + (25, "10.0".into()), + (16, "0.0".into()), + (26, "0.0".into()), + (36, "1.0".into()), + (17, "0.0".into()), + (27, "0.0".into()), + (37, "0.0".into()), + (42, "50.0".into()), + (43, "0.0".into()), + (44, "0.0".into()), + (50, "0.0".into()), + (51, "6.0".into()), + (72, "1000".into()), + (1, "monochrome.ctb".into()), + (281, "0".into()), + (71, "1".into()), + (74, "0".into()), + ]; + for (c, v) in [(110, [100.0, 50.0, 0.0]), (111, [C6, S6, 0.0]), (112, [-S6, C6, 0.0])] { + for (k, x) in v.iter().enumerate() { + g.push((c + 10 * k as i32, format!("{x:?}"))); + } + } + g.extend([ + (79, "0".into()), + (146, "2.5".into()), + (345, site.into()), + (346, base_ucs.into()), + (170, "0".into()), + (61, "5".into()), + (348, style.into()), + (292, "1".into()), + (282, "1".into()), + (141, "0.0".into()), + (142, "0.0".into()), + (63, "250".into()), + ]); + g +} + +/// The non-default unmodelled groups, in file order; default-valued settings are canonical absence. +const EXTRA: &[i32] = &[13, 23, 14, 24, 1, 74, 348, 292, 282, 141, 142, 63]; + +fn the_viewport(d: &Drawing) -> (Handle, Viewport) { + d.layouts + .iter() + .flat_map(|l| l.entities.iter()) + .find_map(|e| if let EntityKind::Viewport(v) = &e.kind { (v.id != 1).then(|| (e.handle, v.clone())) } else { None }) + .unwrap() +} + +/// A drawing whose viewport carries another program's UCS and unmodelled groups, its visual +/// style handle pointing at layer 0's record (a record CADCraft writes itself, under a new +/// handle on save). +fn foreign() -> Drawing { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let (site, base_ucs, layer0) = (record_handle(&text, "UCS", "SITE"), record_handle(&text, "UCS", "BASE"), record_handle(&text, "LAYER", "0")); + cadcraft_io::read_dxf(inject(&text, h, &foreign_groups(&site, &base_ucs, &layer0)).as_bytes()).unwrap() +} + +fn expected_ucs() -> ViewportUcs { + ViewportUcs { + origin: Vec3::new(100.0, 50.0, 0.0), + x_axis: Vec3::new(C6, S6, 0.0), + y_axis: Vec3::new(-S6, C6, 0.0), + elevation: 2.5, + ortho: 0, + named: Some("SITE".into()), + base: Some("BASE".into()), + } +} + +fn num(v: &str) -> Option { + v.trim().parse::().ok() +} + +/// The unmodelled groups agree: same codes in the same order, same values (numbers compared as +/// numbers), the visual style pointing at layer 0 in each file. +fn assert_extra(text: &str, rec: &[(String, String)]) { + let codes: Vec = rec.iter().filter_map(|(c, _)| c.parse::().ok()).filter(|c| EXTRA.contains(c)).collect(); + assert_eq!(codes, EXTRA, "{rec:?}"); + for (code, want) in foreign_groups("", "", "").into_iter().filter(|(c, _)| EXTRA.contains(c) && *c != 348) { + let got = group(rec, &code.to_string()).unwrap(); + match (num(got), num(&want)) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-12, "{code}: {got} vs {want}"), + _ => assert_eq!(got, want, "{code}"), + } + } + assert_eq!(group(rec, "348"), Some(record_handle(text, "LAYER", "0").as_str()), "visual style pointer"); +} + +#[test] +fn another_program_s_viewport_ucs_and_settings_are_read() { + let d = foreign(); + let (_, v) = the_viewport(&d); + assert!(v.ucs_per_viewport); + assert_eq!(v.ucs, Some(expected_ucs())); + let codes: Vec = v.extra.iter().map(|t| t.code).collect(); + assert_eq!(codes, EXTRA); +} + +#[test] +fn viewport_ucs_and_settings_survive_a_dxf_save() { + let d = foreign(); + let (h, v) = the_viewport(&d); + let text = cadcraft_io::write_dxf(&d); + let rec = viewport_record(&text, h); + assert_eq!(group(&rec, "71"), Some("1")); + assert_eq!(group(&rec, "345"), Some(record_handle(&text, "UCS", "SITE").as_str())); + assert_eq!(group(&rec, "346"), Some(record_handle(&text, "UCS", "BASE").as_str())); + assert_eq!(num(group(&rec, "146").unwrap()), Some(2.5)); + assert_extra(&text, &rec); + // Written once each, and the view twist, direction and target are not carried raw. + for code in EXTRA.iter().chain(&[71, 110, 345, 346]) { + assert_eq!(rec.iter().filter(|(c, _)| *c == code.to_string()).count(), 1, "group {code} in {rec:?}"); + } + assert!((num(group(&rec, "51").unwrap()).unwrap() - 6.0).abs() < 1e-12); + for code in ["16", "17"] { + assert!(group(&rec, code).is_none(), "{code} in {rec:?}"); + } + // And it reads back the same. + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let (_, w) = the_viewport(&back); + assert_eq!((w.ucs, w.ucs_per_viewport), (v.ucs, v.ucs_per_viewport)); + let again = cadcraft_io::write_dxf(&back); + assert_extra(&again, &viewport_record(&again, h)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn viewport_ucs_and_settings_survive_a_dwg_save() { + cadcraft_io::dwg_worker::allow_in_process(); + let d = foreign(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + let (h, v) = the_viewport(&back); + assert!(v.ucs_per_viewport); + let u = v.ucs.clone().unwrap(); + let want = expected_ucs(); + for (a, b) in [(u.origin, want.origin), (u.x_axis, want.x_axis), (u.y_axis, want.y_axis)] { + assert!((a - b).len() < 1e-12, "{a:?} vs {b:?}"); + } + assert_eq!((u.elevation, u.ortho, u.named.as_deref(), u.base.as_deref()), (2.5, 0, Some("SITE"), Some("BASE"))); + // Every group that isn't a reference comes back with its value, also those the DWG bridge + // drops from the record (plot style sheet, shade plot, lighting: from CADCraft's xdata copy). + // The visual style reference (348) is lost through DWG (docs/file-format-parity.md). + let text = cadcraft_io::write_dxf(&back); + let rec = viewport_record(&text, h); + for (code, want) in foreign_groups("", "", "").into_iter().filter(|(c, _)| EXTRA.contains(c) && *c != 348) { + let got = group(&rec, &code.to_string()).unwrap_or_else(|| panic!("group {code} lost through DWG: {rec:?}")); + match (num(got), num(&want)) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-12, "{code}: {got} vs {want}"), + _ => assert_eq!(got, want, "{code}"), + } + } + // And a second trip through DWG changes nothing more. + let twice = cadcraft_io::read(&cadcraft_io::write(&back, "x.dwg").unwrap(), "x.dwg").unwrap(); + let (_, w) = the_viewport(&twice); + assert_eq!((w.ucs, w.ucs_per_viewport), (v.ucs, v.ucs_per_viewport)); + let mut a: Vec = v.extra.iter().map(|t| t.code).collect(); + let mut b: Vec = w.extra.iter().map(|t| t.code).collect(); + a.sort_unstable(); + b.sort_unstable(); + assert_eq!(a, b); +} + +#[test] +fn a_copied_viewport_keeps_its_ucs_and_settings() { + let mut d = foreign(); + let (h, v) = the_viewport(&d); + let paper = Space::Paper(d.layouts[0].name.clone()); + let copy = d.add(&paper, Common::default(), EntityKind::Viewport(Viewport { id: 3, center: Vec3::new(150.0, 40.0, 0.0), ..v.clone() })).unwrap(); + let text = cadcraft_io::write_dxf(&d); + for vh in [h, copy] { + let rec = viewport_record(&text, vh); + assert_eq!(group(&rec, "345"), Some(record_handle(&text, "UCS", "SITE").as_str()), "{vh:?}"); + assert_extra(&text, &rec); + } +} + +#[test] +fn a_viewport_without_a_ucs_is_written_as_before() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let rec = viewport_record(&text, h); + for code in ["71", "110", "111", "112", "79", "146", "345", "346"] { + assert!(group(&rec, code).is_none(), "{code} in {rec:?}"); + } + let (_, v) = the_viewport(&cadcraft_io::read_dxf(text.as_bytes()).unwrap()); + assert_eq!((v.ucs, v.ucs_per_viewport, v.extra.len()), (None, false, 0)); +} + +#[test] +fn a_deleted_named_ucs_is_not_pointed_at() { + let mut d = foreign(); + d.ucss.retain(|u| u.name != "SITE"); + let (h, _) = the_viewport(&d); + let text = cadcraft_io::write_dxf(&d); + let rec = viewport_record(&text, h); + assert!(group(&rec, "345").is_none(), "{rec:?}"); + assert_eq!(group(&rec, "346"), Some(record_handle(&text, "UCS", "BASE").as_str())); +} + +/// CADCraft's `VPEXTRA` copy of a viewport's unmodelled groups can't smuggle structure into the +/// record: a record start, handles, a subclass, a group brace, an owner or xdata are dropped on +/// read, so a save writes nothing the user didn't draw. +#[test] +fn vpextra_cannot_inject_records_or_handles() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let lines_before = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(); + let mut g: Vec<(i32, String)> = vec![(1001, "CADCRAFT".into()), (1000, "VPEXTRA".into()), (1002, "{".into())]; + for (code, value) in + [("0", "LINE"), ("5", "1F"), ("100", "AcDbLine"), ("102", "{ACAD_REACTORS"), ("105", "2A"), ("330", "1"), ("1001", "X"), ("13", "4.5")] + { + g.push((1000, code.into())); + g.push((1000, value.into())); + } + g.push((1002, "}".into())); + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let (_, v) = the_viewport(&back); + let codes: Vec = v.extra.iter().map(|t| t.code).collect(); + assert!(codes.iter().all(|c| (1..1000).contains(c) && !matches!(c, 5 | 100 | 102 | 105 | 330)), "{codes:?}"); + assert!(v.extra.iter().any(|t| t.code == 13 && t.value.trim() == "4.5"), "a viewport's own group is still kept: {:?}", v.extra); + // Saved and opened again: still one viewport, no LINE it never had, no stray subclass. + let saved = cadcraft_io::write_dxf(&back); + assert!(!saved.lines().any(|l| l.trim() == "AcDbLine"), "no injected subclass"); + let again = cadcraft_io::read_dxf(saved.as_bytes()).unwrap(); + assert_eq!(again.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), lines_before, "no injected LINE"); + assert!(the_viewport(&again).1.extra.iter().all(|t| (1..1000).contains(&t.code))); +} + +/// Structural groups inside the record's own AcDbViewport subclass (a second handle, a group +/// brace) aren't kept either: written back, the record would have two handles. +#[test] +fn a_viewport_records_own_structural_groups_are_not_kept() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let g: Vec<(i32, String)> = vec![(5, "FFFFF1".into()), (105, "FFFFF2".into()), (102, "{ACAD_REACTORS".into()), (13, "4.5".into())]; + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let (_, v) = the_viewport(&back); + let codes: Vec = v.extra.iter().map(|t| t.code).collect(); + assert!(codes.iter().all(|c| !matches!(c, 5 | 102 | 105)), "{codes:?}"); + assert!(v.extra.iter().any(|t| t.code == 13 && t.value.trim() == "4.5"), "a viewport's own group is still kept: {:?}", v.extra); + let saved = cadcraft_io::write_dxf(&back); + assert!(!saved.lines().any(|l| l.trim() == "FFFFF1" || l.trim() == "FFFFF2"), "no second handle"); +} + +/// A viewport whose only UCS group is its base UCS handle (346) keeps that base UCS. +#[test] +fn a_base_ucs_handle_alone_is_kept() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + assert!(the_viewport(&d).1.ucs.is_none() && group(&viewport_record(&text, h), "110").is_none(), "no UCS groups of its own"); + let handle = record_handle(&text, "UCS", "BASE"); + let back = cadcraft_io::read_dxf(inject(&text, h, &[(346, handle)]).as_bytes()).unwrap(); + let u = the_viewport(&back).1.ucs.expect("a UCS from 346 alone"); + assert_eq!(u.base.as_deref(), Some("BASE")); + let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&back).as_bytes()).unwrap(); + assert_eq!(the_viewport(&again).1.ucs.and_then(|u| u.base).as_deref(), Some("BASE"), "kept through a save"); +} + +#[test] +fn hostile_viewport_ucs_groups_do_not_panic() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let mut g: Vec<(i32, String)> = vec![ + (71, "7".into()), + (110, "nan".into()), + (120, "inf".into()), + (111, "1e400".into()), + (79, "99".into()), + (146, "-inf".into()), + (345, "ZZZZ".into()), + ]; + // Far more unmodelled groups than any viewport has. + g.extend((0..5000).map(|i| (13, i.to_string()))); + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let (_, v) = the_viewport(&back); + assert_eq!(v.ucs, None, "unreadable axes give no UCS"); + assert!(!v.ucs_per_viewport, "71 is 1 or 0"); + assert!(v.extra.len() <= 512, "{}", v.extra.len()); + let _ = cadcraft_io::write_dxf(&back); + // A finite UCS with a nonsense orthographic type, elevation and named UCS. + let g: Vec<(i32, String)> = vec![(110, "1.0".into()), (79, "99".into()), (146, "nan".into()), (345, "ZZZZ".into()), (346, "".into())]; + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let u = the_viewport(&back).1.ucs.unwrap(); + assert_eq!((u.ortho, u.elevation, u.named, u.base), (0, 0.0, None, None)); + assert_eq!((u.x_axis, u.y_axis), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0))); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_default_viewport_reads_back_without_ucs_or_extras() { + cadcraft_io::dwg_worker::allow_in_process(); + for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] { + let (d, _) = base(); + let bytes = cadcraft_io::write_with(&d, "viewport.dwg", &cadcraft_io::SaveOptions { version: Some(version), binary: false }).unwrap(); + let back = cadcraft_io::read(&bytes, "viewport.dwg").unwrap(); + let (_, viewport) = the_viewport(&back); + assert!(viewport.ucs.is_none(), "{version}: {:?}", viewport.ucs); + assert!(!viewport.ucs_per_viewport, "{version}"); + assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_viewport_with_non_default_snap_keeps_it() { + cadcraft_io::dwg_worker::allow_in_process(); + for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] { + let (mut d, h) = base(); + d.modify_entity(h, |e| { + let EntityKind::Viewport(v) = &mut e.kind else { return }; + v.extra = vec![RawTag { code: 14, value: "2.0".into() }, RawTag { code: 24, value: "2.0".into() }]; + }) + .unwrap(); + let bytes = cadcraft_io::write_with(&d, "viewport.dwg", &cadcraft_io::SaveOptions { version: Some(version), binary: false }).unwrap(); + let back = cadcraft_io::read(&bytes, "viewport.dwg").unwrap(); + let (_, viewport) = the_viewport(&back); + for code in [14, 24] { + assert_eq!(viewport.extra.iter().find(|t| t.code == code).and_then(|t| num(&t.value)), Some(2.0), "{version}"); + } + assert_eq!(viewport.extra.len(), 2, "only the non-default snap spacing remains: {version}: {:?}", viewport.extra); + } +} diff --git a/crates/io/tests/it/vport_circle_sides.rs b/crates/io/tests/it/vport_circle_sides.rs new file mode 100644 index 000000000..9376eeb80 --- /dev/null +++ b/crates/io/tests/it/vport_circle_sides.rs @@ -0,0 +1,119 @@ +//! Group 72 of the `*Active` VPORT records ("Circle sides" in the DXF Reference, VPORT) survives +//! opening and saving as DXF and as DWG. A drawing that stores none, or one that is not a 16-bit +//! integer (the type of groups 60-79, DXF Reference, Group Code Value Types), is written without +//! it, as before. + +use cadcraft_doc::{Drawing, HVal}; +use cadcraft_io::{read_dxf, write_dxf}; + +/// Where the value is kept with the drawing. +const KEY: &str = "CADCRAFT_VPORT_CIRCLE_SIDES"; + +/// The group 72 of each `*ACTIVE` VPORT record in DXF text, in order (`None`: the record has no +/// 72, or one that is not a number). +fn active_circle_sides(text: &str) -> Vec> { + circle_sides_of(text, "*ACTIVE") +} + +/// The group 72 of each VPORT record named `name` (any case) in DXF text, in order. +fn circle_sides_of(text: &str, name: &str) -> Vec> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let mut record: Option> = None; + let mut finish = |r: Option>| { + if let Some(r) = r.filter(|r| r.iter().any(|(c, v)| *c == "2" && v.eq_ignore_ascii_case(name))) { + out.push(r.iter().find(|(c, _)| *c == "72").and_then(|(_, v)| v.parse().ok())); + } + }; + for pair in lines.chunks(2) { + let [code, value] = pair else { break }; + if *code == "0" { + finish(record.take()); + record = (*value == "VPORT").then(Vec::new); + } else if let Some(r) = record.as_mut() { + r.push((*code, *value)); + } + } + finish(record); + out +} + +/// A DXF whose VPORT table holds `records`, each `(name, group 72)` a usable tile, tiles side by +/// side in pairs. +fn vport_dxf(records: &[(&str, Option<&str>)]) -> String { + let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "TABLES".into()), (0, "TABLE".into()), (2, "VPORT".into())]; + for (i, (name, sides)) in records.iter().enumerate() { + let x0 = if i % 2 == 0 { "0" } else { "0.5" }; + let x1 = if i % 2 == 0 { "0.5" } else { "1" }; + for (c, v) in [(0, "VPORT"), (2, name), (70, "0"), (10, x0), (20, "0"), (11, x1), (21, "1"), (12, "3"), (22, "4"), (40, "9"), (41, "1.5")] { + tags.push((c, v.to_string())); + } + if let Some(v) = sides { + tags.push((72, v.to_string())); + } + } + tags.extend([(0, "ENDTAB".into()), (0, "ENDSEC".into()), (0, "EOF".into())]); + tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +/// The value the first `*ACTIVE` record holds is written back on every `*ACTIVE` record, and again +/// after a second save; it was read and dropped, so the file came back without it. +#[test] +fn circle_sides_of_the_active_vport_are_written_back() { + for sides in ["2500", "1", "0", "-7", "32767", "-32768"] { + let d = read_dxf(vport_dxf(&[("*ACTIVE", Some(sides)), ("*ACTIVE", Some(sides))]).as_bytes()).expect("read"); + let want: i64 = sides.parse().expect("a number"); + let text = write_dxf(&d); + let written = active_circle_sides(&text); + assert_eq!(written.len(), 2, "both tiles are written: {written:?}"); + assert!(written.iter().all(|v| *v == Some(want)), "{sides}: {written:?}"); + let again = write_dxf(&read_dxf(text.as_bytes()).expect("reopen")); + assert!(active_circle_sides(&again).iter().all(|v| *v == Some(want)), "{sides}: second save"); + } + // Only the first `*ACTIVE` record's value is kept: a later one neither replaces it nor stands + // in for a first record that has none. + for (first, second, want) in [(Some("1"), Some("2"), Some(1)), (None, Some("2"), None)] { + let text = write_dxf(&read_dxf(vport_dxf(&[("*Active", first), ("*ACTIVE", second)]).as_bytes()).expect("read")); + assert_eq!(active_circle_sides(&text), [want, want], "{first:?}, {second:?}"); + } + // An untiled drawing: its lone `*ACTIVE` record. A saved configuration that has none does + // not get the shown one's. + let d = read_dxf(vport_dxf(&[("*ACTIVE", Some("2500")), ("Saved", None), ("Saved", None)]).as_bytes()).expect("read"); + let text = write_dxf(&d); + assert_eq!(active_circle_sides(&text), [Some(2500)]); + assert_eq!(circle_sides_of(&text, "Saved"), [None, None]); +} + +/// A drawing with no value, or one that is not a 16-bit integer (from a file or set on the +/// drawing), is written with no group 72, never the bad value. +#[test] +fn missing_or_unusable_circle_sides_are_not_written() { + let none = |text: &str| { + let written = active_circle_sides(text); + !written.is_empty() && written.iter().all(Option::is_none) + }; + let new = write_dxf(&Drawing::new_metric()); + assert!(none(&new), "a new drawing: {:?}", active_circle_sides(&new)); + for sides in [None, Some("32768"), Some("-32769"), Some("99999999999")] { + let text = write_dxf(&read_dxf(vport_dxf(&[("*ACTIVE", sides)]).as_bytes()).expect("read")); + assert!(none(&text), "{sides:?}: {:?}", active_circle_sides(&text)); + } + for bad in [HVal::Int(32_768), HVal::Int(i64::MIN), HVal::Real(f64::NAN), HVal::Real(1e300), HVal::Str("many".into())] { + let mut d = Drawing::new_metric(); + d.header.set(KEY, bad.clone()); + let text = write_dxf(&d); + assert!(none(&text), "{bad:?}: {:?}", active_circle_sides(&text)); + } +} + +/// Saved as DWG and reopened, the drawing keeps the value: the DWG is written from the same VPORT +/// records, and a DWG is read through the DXF its decoder gives, by the same reader. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn circle_sides_survive_a_dwg_round_trip() { + cadcraft_io::dwg_worker::allow_in_process(); + let d = read_dxf(vport_dxf(&[("*ACTIVE", Some("2500"))]).as_bytes()).expect("read"); + let dwg = cadcraft_io::write(&d, "x.dwg").expect("write DWG"); + let back = cadcraft_io::read(&dwg, "x.dwg").expect("read DWG"); + assert_eq!(active_circle_sides(&write_dxf(&back)), [Some(2500)]); +} diff --git a/crates/io/tests/it/xclip_roundtrip.rs b/crates/io/tests/it/xclip_roundtrip.rs index 407b02cda..abdcd25f7 100644 --- a/crates/io/tests/it/xclip_roundtrip.rs +++ b/crates/io/tests/it/xclip_roundtrip.rs @@ -172,3 +172,277 @@ fn hostile_spatial_filters_do_not_panic() { let _ = read(bad.as_bytes(), "a.dxf"); } } + +/// Verifies that a `SPATIAL_FILTER` with a non-identity boundary transform matrix is preserved +/// across DXF and DWG round-trips (R2004, R2010, R2018), while a sheared filter stays foreign. +#[test] +fn spatial_filter_with_non_identity_boundary_transform_round_trips() { + let mut d = Drawing::new_metric(); + let mut block = Block::new("P"); + block.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(100.0, 100.0, 0.0) }))); + d.blocks.insert("P".into(), Arc::new(block)); + let clip = ClipBoundary::new(vec![Vec2::new(20.0, 20.0), Vec2::new(80.0, 80.0)]); + d.add( + &Space::Model, + Common::default(), + EntityKind::Insert(Insert { block: "P".into(), insert: Vec3::new(150.0, 0.0, 0.0), clip: Some(clip), ..Insert::default() }), + ) + .unwrap(); + let text = String::from_utf8(save(&d, "a.dxf", Version::R2018)).unwrap(); + + let mut lines: Vec = text.lines().map(|l| l.trim().to_string()).collect(); + let at = lines.windows(2).position(|w| w[0] == "0" && w[1] == "SPATIAL_FILTER").unwrap(); + let end = (at + 2..lines.len()).step_by(2).find(|i| lines[*i] == "0").unwrap(); + + let mut g40_indices = Vec::new(); + for i in (at..end).step_by(2) { + if lines[i] == "40" { + g40_indices.push(i + 1); + } + } + assert_eq!(g40_indices.len(), 24); + // Group 40 stores two 3x4 matrices row by row: + // Matrix 1 (elements 0..11): inverse insert transform + // Matrix 2 (elements 12..23): boundary transform + // Index 15 = Matrix 2 row 0, col 3 (Tx translation) + // Index 19 = Matrix 2 row 1, col 3 (Ty translation) + lines[g40_indices[15]] = "10.0".to_string(); + lines[g40_indices[19]] = "5.0".to_string(); + + let mutated = lines.join("\r\n") + "\r\n"; + let loaded = read(mutated.as_bytes(), "a.dxf").unwrap(); + let loaded_clips = clips(&loaded); + let ins_clip = loaded_clips[0].as_ref().expect("clip must be preserved"); + assert!(ins_clip.points[0].near(Vec2::new(10.0, 15.0), 1e-9)); + assert!(ins_clip.points[1].near(Vec2::new(70.0, 75.0), 1e-9)); + + for v in [Version::R2004, Version::R2010, Version::R2018] { + let dxf_back = read(&save(&loaded, "resaved.dxf", v), "resaved.dxf").unwrap(); + same(&clips(&dxf_back), &clips(&loaded)); + + let dwg_back = read(&save(&loaded, "resaved.dwg", v), "resaved.dwg").unwrap(); + same(&clips(&dwg_back), &clips(&loaded)); + } + + // Index 13 = Matrix 2 row 0, col 1 (shear term c). A sheared filter cannot be represented + // losslessly as a planar 2D clip and must remain in `foreign.objects` untouched. + lines[g40_indices[13]] = "0.5".to_string(); + let sheared_dxf = lines.join("\r\n") + "\r\n"; + let sheared_loaded = read(sheared_dxf.as_bytes(), "a.dxf").unwrap(); + assert!(clips(&sheared_loaded)[0].is_none(), "sheared filter must not be converted into a lossy clip"); + assert!( + sheared_loaded.foreign.objects.iter().any(|o| o.kind.eq_ignore_ascii_case("SPATIAL_FILTER")), + "sheared SPATIAL_FILTER must be preserved in foreign objects" + ); +} + +/// Verifies that rotated `INSERT` references with uniform, non-uniform, and mirrored scales +/// and normal or inverted 2-point block-space `ClipBoundary` rectangles round-trip losslessly +/// across DXF and DWG (`R2004`, `R2010`, `R2018`) without producing sheared `boundary_xf` matrices. +#[test] +fn inverted_rotated_2point_clip_round_trips() { + let mut d = Drawing::new_metric(); + let mut block = Block::new("Plan"); + block.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::new(-10.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))); + d.blocks.insert(block.name.clone(), Arc::new(block)); + + for scale in [Vec3::new(2.0, 2.0, 1.0), Vec3::new(2.0, 3.0, 1.0), Vec3::new(-2.0, 3.0, 1.0)] { + for inverted in [false, true] { + let clip = ClipBoundary { inverted, ..ClipBoundary::new(vec![Vec2::new(-2.0, -1.0), Vec2::new(2.0, 1.0)]) }; + let ins = + Insert { block: "Plan".into(), insert: Vec3::new(10.0, 20.0, 0.0), scale, rotation: 0.3, clip: Some(clip), ..Insert::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + } + } + + for v in [Version::R2004, Version::R2010, Version::R2018] { + let dxf_back = read(&save(&d, "inv_rot.dxf", v), "inv_rot.dxf").unwrap(); + same(&clips(&dxf_back), &clips(&d)); + + let dwg_back = read(&save(&d, "inv_rot.dwg", v), "inv_rot.dwg").unwrap(); + same(&clips(&dwg_back), &clips(&d)); + } +} + +/// Extracts `(group_70_count, vertices)` from every `SPATIAL_FILTER` in raw DXF text. +fn raw_spatial_filters(dxf_text: &str) -> Vec<(i32, Vec)> { + let lines: Vec<&str> = dxf_text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let mut i = 0; + while i + 1 < lines.len() { + if lines[i] == "0" && lines[i + 1] == "SPATIAL_FILTER" { + let mut count = None; + let mut verts = Vec::new(); + let mut pending_x: Option = None; + i += 2; + while i + 1 < lines.len() && lines[i] != "0" { + match lines[i] { + "70" => count = lines[i + 1].parse::().ok(), + "10" => pending_x = lines[i + 1].parse::().ok(), + "20" => { + if let (Some(x), Ok(y)) = (pending_x.take(), lines[i + 1].parse::()) { + verts.push(Vec2::new(x, y)); + } + } + _ => {} + } + i += 2; + } + out.push((count.unwrap_or(-1), verts)); + } else { + i += 2; + } + } + out +} + +/// Extracts `(ACAD_INVERTEDCLIP_ROUNDTRIP, ACAD_INVERTEDCLIP_ROUNDTRIP_COMPARE)` vertex pairs +/// from every `XRECORD` carrying inverted-clip data in raw DXF text. +fn raw_inverted_xrecords(dxf_text: &str) -> Vec<(Vec, Vec)> { + let lines: Vec<&str> = dxf_text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let mut i = 0; + while i + 1 < lines.len() { + if lines[i] == "0" && lines[i + 1] == "XRECORD" { + let mut section = ""; + let mut rt = Vec::new(); + let mut cmp = Vec::new(); + let mut pending_x: Option = None; + i += 2; + while i + 1 < lines.len() && lines[i] != "0" { + match lines[i] { + "102" => section = lines[i + 1], + "10" => pending_x = lines[i + 1].parse::().ok(), + "20" => { + if let (Some(x), Ok(y)) = (pending_x.take(), lines[i + 1].parse::()) { + match section { + "ACAD_INVERTEDCLIP_ROUNDTRIP" => rt.push(Vec2::new(x, y)), + "ACAD_INVERTEDCLIP_ROUNDTRIP_COMPARE" => cmp.push(Vec2::new(x, y)), + _ => {} + } + } + } + _ => {} + } + i += 2; + } + if !rt.is_empty() || !cmp.is_empty() { + out.push((rt, cmp)); + } + } else { + i += 2; + } + } + out +} + +fn assert_canonical_raw_two_point_clips(dxf_text: &str, expected_filters: usize, expected_inverted: usize) { + let filters = raw_spatial_filters(dxf_text); + assert_eq!(filters.len(), expected_filters); + for (count, verts) in &filters { + assert_eq!(*count, 2, "expected 2-point rectangular SPATIAL_FILTER"); + assert_eq!(verts.len(), 2); + assert!(verts[0].x < verts[1].x && verts[0].y < verts[1].y, "SPATIAL_FILTER corners must be ordered lower-left then upper-right: {verts:?}"); + } + + let xrecords = raw_inverted_xrecords(dxf_text); + assert_eq!(xrecords.len(), expected_inverted); + for (rt, cmp) in &xrecords { + assert_eq!((rt.len(), cmp.len()), (2, 2)); + assert!(rt[0].x < rt[1].x && rt[0].y < rt[1].y, "ROUNDTRIP corners must be lower-left..upper-right: {rt:?}"); + assert!(cmp[0].x < cmp[1].x && cmp[0].y < cmp[1].y, "COMPARE corners must be lower-left..upper-right: {cmp:?}"); + assert!(filters.iter().any(|(_, fv)| fv[0].near(rt[0], 1e-6) && fv[1].near(rt[1], 1e-6))); + assert!(rt[0].near(cmp[0], 1e-6) && rt[1].near(cmp[1], 1e-6)); + } +} + +/// Verifies that mirrored rectangular clips (both ordinary and inverted, unrotated and rotated) +/// write canonical `(lower-left, upper-right)` vertices in raw DXF/DWG `SPATIAL_FILTER` and +/// `ACAD_XREC_ROUNDTRIP` records, and preserve the exact clipped visible region after round-trip. +#[test] +fn mirrored_rectangular_clip_writes_canonical_corners_and_preserves_visible_region() { + let mut base = Drawing::new_metric(); + let mut block = Block::new("Plan"); + // Crossing lines inside the asymmetric clip [-1, 3] x [0.5, 2.5], plus an outside-only line. + block.entities.push(Entity::new(base.new_handle(), EntityKind::Line(Line { a: Vec3::new(-10.0, 1.5, 0.0), b: Vec3::new(10.0, 1.5, 0.0) }))); + block.entities.push(Entity::new(base.new_handle(), EntityKind::Line(Line { a: Vec3::new(1.0, -10.0, 0.0), b: Vec3::new(1.0, 10.0, 0.0) }))); + block.entities.push(Entity::new(base.new_handle(), EntityKind::Line(Line { a: Vec3::new(-8.0, -8.0, 0.0), b: Vec3::new(-5.0, -5.0, 0.0) }))); + base.blocks.insert(block.name.clone(), Arc::new(block)); + + // Ordinary unrotated mirrored insert: verify exact clipped visible bounds after DXF & DWG round-trip. + let mut ordinary = base.clone(); + let asym_clip = ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]); + ordinary + .add( + &Space::Model, + Common::default(), + EntityKind::Insert(Insert { + block: "Plan".into(), + insert: Vec3::new(10.0, 20.0, 0.0), + scale: Vec3::new(-2.0, 3.0, 1.0), + rotation: 0.0, + clip: Some(asym_clip.clone()), + ..Insert::default() + }), + ) + .unwrap(); + + let expected_bounds = cadcraft_render::build(&ordinary, &Space::Model, &cadcraft_render::Options::default()).bounds; + assert!((expected_bounds.min.x - 4.0).abs() < 1e-6 && (expected_bounds.max.x - 12.0).abs() < 1e-6); + assert!((expected_bounds.min.y - 21.5).abs() < 1e-6 && (expected_bounds.max.y - 27.5).abs() < 1e-6); + + // Combined ordinary + inverted mirrored inserts across scales and rotations. + let mut combined = base; + let mut filter_count = 0; + let mut inverted_count = 0; + for (idx, (scale, rotation)) in + [(Vec3::new(-2.0, 3.0, 1.0), 0.0), (Vec3::new(2.0, -3.0, 1.0), 0.0), (Vec3::new(-2.0, -3.0, 1.0), 0.0), (Vec3::new(-2.0, 3.0, 1.0), 0.3)] + .into_iter() + .enumerate() + { + for inverted in [false, true] { + let clip = ClipBoundary { inverted, ..asym_clip.clone() }; + let ins = Insert { + block: "Plan".into(), + insert: Vec3::new(10.0 + (idx as f64) * 50.0, 20.0, 0.0), + scale, + rotation, + clip: Some(clip), + ..Insert::default() + }; + combined.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + filter_count += 1; + if inverted { + inverted_count += 1; + } + } + } + + for v in [Version::R2004, Version::R2010, Version::R2018] { + // 1. Ordinary mirrored clip: raw DXF/DWG order + visible rendered region. + let ord_dxf = save(&ordinary, "ord_mirror.dxf", v); + assert_canonical_raw_two_point_clips(&String::from_utf8(ord_dxf.clone()).unwrap(), 1, 0); + let ord_dxf_back = read(&ord_dxf, "ord_mirror.dxf").unwrap(); + let dxf_bounds = cadcraft_render::build(&ord_dxf_back, &Space::Model, &cadcraft_render::Options::default()).bounds; + assert!(dxf_bounds.min.near(expected_bounds.min, 1e-4) && dxf_bounds.max.near(expected_bounds.max, 1e-4)); + + let ord_dwg = save(&ordinary, "ord_mirror.dwg", v); + let ord_dwg_dxf = craft_dwg::dwg_to_dxf(&ord_dwg).unwrap(); + assert_canonical_raw_two_point_clips(&String::from_utf8(ord_dwg_dxf).unwrap(), 1, 0); + let ord_dwg_back = read(&ord_dwg, "ord_mirror.dwg").unwrap(); + let dwg_bounds = cadcraft_render::build(&ord_dwg_back, &Space::Model, &cadcraft_render::Options::default()).bounds; + assert!(dwg_bounds.min.near(expected_bounds.min, 1e-4) && dwg_bounds.max.near(expected_bounds.max, 1e-4)); + + // 2. Combined ordinary + inverted mirrored clips across scales and rotations. + let comb_dxf = save(&combined, "comb_mirror.dxf", v); + assert_canonical_raw_two_point_clips(&String::from_utf8(comb_dxf.clone()).unwrap(), filter_count, inverted_count); + let comb_dxf_back = read(&comb_dxf, "comb_mirror.dxf").unwrap(); + same(&clips(&comb_dxf_back), &clips(&combined)); + + let comb_dwg = save(&combined, "comb_mirror.dwg", v); + let comb_dwg_dxf = craft_dwg::dwg_to_dxf(&comb_dwg).unwrap(); + assert_canonical_raw_two_point_clips(&String::from_utf8(comb_dwg_dxf).unwrap(), filter_count, inverted_count); + let comb_dwg_back = read(&comb_dwg, "comb_mirror.dwg").unwrap(); + same(&clips(&comb_dwg_back), &clips(&combined)); + } +} diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index 434d222f3..33b51b5c6 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -72,6 +72,8 @@ fn text(d: &mut Drawing, space: &Space, style: &str, at: (f64, f64), value: &str style: style.into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; d.add(space, Common::default(), EntityKind::Text(t)).unwrap(); } @@ -231,6 +233,9 @@ fn text_seen_through_a_viewport_and_on_layers() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); @@ -275,6 +280,8 @@ fn hostile_text_never_panics() { style: "Real".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); } diff --git a/crates/io/tests/wipeout_frame.rs b/crates/io/tests/wipeout_frame.rs index 5c2c201c9..7e9afa808 100644 --- a/crates/io/tests/wipeout_frame.rs +++ b/crates/io/tests/wipeout_frame.rs @@ -19,3 +19,134 @@ fn wipeoutvariables_sets_the_frame_flag() { assert_eq!(frame(None), 1, "no object: the default shows frames"); assert_eq!(frame(Some(7)), 1, "an out-of-range flag is ignored"); } + +/// A drawing with `frame` set (or untouched for `None`), saved as `name` and read back. +fn saved(frame: Option, name: &str) -> cadcraft_doc::Drawing { + cadcraft_io::dwg_worker::allow_in_process(); + let mut d = cadcraft_doc::Drawing::new_metric(); + if let Some(f) = frame { + d.header.set_i64("WIPEOUTFRAME", f); + } + let bytes = cadcraft_io::write(&d, name).unwrap(); + cadcraft_io::read(&bytes, name).unwrap() +} + +/// How many records of the written DXF have `value` in group `code`. +fn count(dxf: &str, code: &str, value: &str) -> usize { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + lines.chunks(2).filter(|pair| **pair == [code, value]).count() +} + +/// The object is of a class a reader does not know by itself, so the file declares it; a drawing +/// that never set the frame gets neither the object nor the class. +#[test] +fn the_written_object_has_its_class_and_one_dictionary_entry() { + let mut d = cadcraft_doc::Drawing::new_metric(); + let plain = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap(); + d.header.set_i64("WIPEOUTFRAME", 0); + let set = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap(); + for (code, value) in [("0", "WIPEOUTVARIABLES"), ("1", "WIPEOUTVARIABLES"), ("3", "ACAD_WIPEOUT_VARS")] { + assert_eq!(count(&set, code, value), 1, "set: group {code} {value}"); + assert_eq!(count(&plain, code, value), 0, "not set: group {code} {value}"); + } + // A file that already has the object is not given a second one when it is saved again. + let again = String::from_utf8(cadcraft_io::write(&cadcraft_io::read(set.as_bytes(), "a.dxf").unwrap(), "a.dxf").unwrap()).unwrap(); + assert_eq!(count(&again, "0", "WIPEOUTVARIABLES"), 1, "saved twice"); +} + +#[test] +fn wipeout_frame_setting_survives_a_save_in_dxf_and_dwg() { + // The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works. + let mut names = vec!["a.dxf"]; + if cfg!(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))) { + names.push("a.dwg"); + } + for name in names { + for frame in [0, 1] { + let back = saved(Some(frame), name); + assert_eq!(back.header.i64("WIPEOUTFRAME", 1), frame, "{name}: frame {frame}"); + } + // "Shown but not plotted" has no documented place in the object: the frames stay shown. + assert_ne!(saved(Some(2), name).header.i64("WIPEOUTFRAME", 1), 0, "{name}: frame 2 keeps the frames shown"); + let untouched = saved(None, name); + assert_eq!(untouched.header.i64("WIPEOUTFRAME", 1), 1, "{name}: default"); + } +} + +/// Group 70 of the WIPEOUTVARIABLES object in a written DXF. +fn written_flag(dxf: &str) -> Option { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let mut pairs = lines.chunks(2).skip_while(|pair| **pair != ["0", "WIPEOUTVARIABLES"]).skip(1); + pairs.by_ref().take_while(|pair| pair.first() != Some(&"0")).find(|pair| pair.first() == Some(&"70")).and_then(|pair| pair.get(1)?.parse().ok()) +} + +/// The DXF Reference gives the object's group 70 two values, 0 (no frame) and 1 (display frame), +/// so no setting writes another one. +#[test] +fn the_written_flag_is_one_the_format_documents() { + for frame in [0, 1, 2] { + let mut d = cadcraft_doc::Drawing::new_metric(); + d.header.set_i64("WIPEOUTFRAME", frame); + let dxf = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap(); + let flag = written_flag(&dxf); + assert!(matches!(flag, Some(0 | 1)), "frame {frame} writes {flag:?}"); + assert_eq!(flag == Some(0), frame == 0, "frame {frame}: only hidden frames write 0"); + } +} + +/// A file whose named object dictionary lists a WIPEOUTVARIABLES object with `flag` in group 70. +fn file_with(flag: i64) -> String { + format!( + " 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nSECTION\n 2\nOBJECTS\n\ + 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_WIPEOUT_VARS\n350\nA1\n\ + 0\nWIPEOUTVARIABLES\n 5\nA1\n102\n{{ACAD_REACTORS\n330\nC\n102\n}}\n330\nC\n100\nAcDbWipeoutVariables\n 70\n{flag}\n\ + 0\nENDSEC\n 0\nEOF\n" + ) +} + +/// A file's own WIPEOUTVARIABLES object is replaced by the drawing's setting when the setting +/// changed: the saved file has one object, and it no longer hides the frames. +#[test] +fn a_changed_setting_replaces_the_objects_of_the_file() { + for shown in [1, 2] { + let mut d = cadcraft_io::read_dxf(file_with(0).as_bytes()).unwrap(); + assert_eq!(d.header.i64("WIPEOUTFRAME", 1), 0, "as the file says"); + d.header.set_i64("WIPEOUTFRAME", shown); + let saved = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap(); + assert_eq!(count(&saved, "0", "WIPEOUTVARIABLES"), 1, "set to {shown}: one object"); + assert_eq!(count(&saved, "3", "ACAD_WIPEOUT_VARS"), 1, "set to {shown}: one dictionary entry"); + assert_ne!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.i64("WIPEOUTFRAME", 0), 0, "set to {shown}: the frames are shown"); + } +} + +/// A file's own object is written back as read while the setting is what the file said: what +/// another application hung on it (here an extension dictionary with one record) is still there. +#[test] +fn an_unchanged_setting_keeps_the_objects_of_the_file_as_read() { + for flag in [0, 1, 2] { + let extra = "102\n{ACAD_XDICTIONARY\n360\nB1\n102\n}\n102\n{ACAD_REACTORS"; + let file = file_with(flag).replacen("102\n{ACAD_REACTORS", extra, 1).replacen( + "0\nENDSEC\n 0\nEOF\n", + "0\nDICTIONARY\n 5\nB1\n330\nA1\n100\nAcDbDictionary\n281\n1\n 3\nSOME_APP_DATA\n360\nB2\n\ + 0\nXRECORD\n 5\nB2\n330\nB1\n100\nAcDbXrecord\n280\n1\n 1\nkept\n 0\nENDSEC\n 0\nEOF\n", + 1, + ); + assert_eq!(count(&file, "3", "SOME_APP_DATA"), 1, "the file has the record"); + let d = cadcraft_io::read_dxf(file.as_bytes()).unwrap(); + let saved = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap(); + assert_eq!(count(&saved, "0", "WIPEOUTVARIABLES"), 1, "flag {flag}: one object"); + assert_eq!(written_flag(&saved), Some(flag), "flag {flag}: as the file said"); + assert_eq!(count(&saved, "3", "SOME_APP_DATA"), 1, "flag {flag}: its extension dictionary is kept"); + } +} + +/// A file that came with flag 2 in its object keeps it through a save, as every object CADCraft +/// does not write itself is kept: opening and saving a drawing does not change its setting. +#[test] +fn a_file_that_holds_flag_2_keeps_it() { + let d = cadcraft_io::read_dxf(file_with(2).as_bytes()).unwrap(); + let saved = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap(); + assert_eq!(count(&saved, "0", "WIPEOUTVARIABLES"), 1, "one object"); + assert_eq!(written_flag(&saved), Some(2), "the file's own flag"); + assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.i64("WIPEOUTFRAME", 1), d.header.i64("WIPEOUTFRAME", 1)); +} diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 5f9417a54..bce3bc36c 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -462,14 +462,16 @@ impl Headless { s.execute(&id, ¶ms).map_err(|e| e.to_string()) } "cmdline.input" => { - let before = s.log.len(); + let before = s.log_mark(); let r = s.cmdline(&str_p("text").unwrap_or_default()); + // No frames here: a LISP routine the line started or answered runs on now. + s.lisp_run_until_input(); // Like the app: a refused line is echoed to the history (and `output`), and also // reported in `error`. if let Err(e) = &r { s.echo(e.to_string()); } - let out: Vec = s.log.iter().skip(before).cloned().collect(); + let out: Vec = s.log_since(before).to_vec(); let mut st = state(s); if let Some(o) = st.as_object_mut() { o.insert("output".into(), json!(out)); @@ -480,25 +482,28 @@ impl Headless { Ok(st) } "cmdline.script" => { - let before = s.log.len(); + let before = s.log_mark(); s.script(&str_p("text").unwrap_or_default()).map_err(|e| e.to_string())?; - let out: Vec = s.log.iter().skip(before).cloned().collect(); + let out: Vec = s.log_since(before).to_vec(); Ok(json!({"output": out, "state": state(s)})) } "cmdline.key" => { - let before = s.log.len(); + let before = s.log_mark(); let r = if str_p("key").is_some_and(|k| k.eq_ignore_ascii_case("escape") || k.eq_ignore_ascii_case("esc")) { s.cancel(); Ok(()) } else { - s.input(cadcraft_engine::Input::Enter) + let r = s.input(cadcraft_engine::Input::Enter); + // Enter can repeat a LISP command or answer a routine's prompt. + s.lisp_run_until_input(); + r }; // Like the app: a refused Enter is echoed to the history (and `output`), and also // reported in `error`; the call itself succeeds. if let Err(e) = &r { s.echo(e.to_string()); } - let out: Vec = s.log.iter().skip(before).cloned().collect(); + let out: Vec = s.log_since(before).to_vec(); let mut st = state(s); if let Some(o) = st.as_object_mut() { o.insert("output".into(), json!(out)); diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c4873fa8b..8baf4299a 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -78,6 +78,28 @@ fn agent_draws_a_plate_with_holes() { assert!(img["data"].as_str().unwrap().len() > 100); } +/// #3635: headless, nothing gives a LISP routine frames: a long one in a script or typed at the +/// command line runs to its end before the call returns, and the next LISP line runs. +#[test] +fn headless_lisp_routines_run_to_their_end() { + let mut s = Server::new(Box::new(Headless::default())); + let long = "(progn (repeat 1000000 (setq x 1)) (princ \"done\"))"; + let lines = |r: &Value| r["output"].as_array().cloned().unwrap_or_default(); + let r = tool(&mut s, "script", json!({"text": format!("{long}\n(setq y (+ x 1))\n")})); + assert!(lines(&r).contains(&json!("done")) && r.get("error").is_none(), "{r}"); + let r = tool(&mut s, "command_line", json!({"text": long})); + assert!(lines(&r).contains(&json!("done")) && r.get("error").is_none(), "{r}"); + let r = tool(&mut s, "command_line", json!({"text": "!y"})); + assert!(lines(&r).contains(&json!("2")), "{r}"); + // Enter repeats a LISP command; the control method runs it on as a typed line does. + let mut h = Headless::default(); + let mut call = |method: &str, params: Value| crate::Backend::call(&mut h, method, params).unwrap(); + call("cmdline.input", json!({"text": format!("(defun c:spin () {long})")})); + assert!(lines(&call("cmdline.input", json!({"text": "spin"}))).contains(&json!("done"))); + let r = call("cmdline.key", json!({"key": "enter"})); + assert!(lines(&r).contains(&json!("done")) && r.get("error").is_none(), "{r}"); +} + /// Guards that bad input is reported, not fatal: a refused command and a screenshot without a /// UI are `isError` results, and malformed JSON is a parse error (-32700). #[test] @@ -499,3 +521,43 @@ fn a_read_root_alone_still_draws_but_writes_nothing() { let written: Vec<_> = std::fs::read_dir(&outside).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect(); assert!(written.is_empty(), "nothing is written outside the roots: {written:?}"); } + +/// #3643: headless, each command-line request reports the lines it printed, also when the command +/// history is trimmed from the front meanwhile. +#[test] +fn headless_output_survives_the_history_trim() { + // Echo lines until the next one trims the history: grow it to its first trim, then back up to + // the length it had just before it. + fn fill(h: &mut Headless) { + let mut top = 0; + loop { + let len = h.session.log.len(); + h.session.echo("filler"); + if h.session.log.len() < len { + break; + } + top = h.session.log.len(); + } + while h.session.log.len() < top { + h.session.echo("filler"); + } + } + // The `y` lines a request reports; it reports nothing from before it. + fn ys(h: &mut Headless, method: &str, params: Value) -> usize { + let r = crate::Backend::call(h, method, params).unwrap(); + let out = r["output"].as_array().cloned().unwrap_or_default(); + assert!(!out.contains(&json!("filler")), "{method}: {r}"); + out.iter().filter(|l| *l == "y").count() + } + let mut h = Headless::default(); + let lines = "(repeat 20 (princ \"y\") (terpri))"; + fill(&mut h); + assert_eq!(ys(&mut h, "cmdline.script", json!({"text": format!("{lines}\n")})), 20); + fill(&mut h); + assert_eq!(ys(&mut h, "cmdline.input", json!({"text": lines})), 20); + // Enter repeats a LISP command that prints them. + ys(&mut h, "cmdline.input", json!({"text": format!("(defun c:ys () {lines} (princ))")})); + ys(&mut h, "cmdline.input", json!({"text": "ys"})); + fill(&mut h); + assert_eq!(ys(&mut h, "cmdline.key", json!({"key": "enter"})), 20); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index b71c79d4f..de6def4f2 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -18,10 +18,11 @@ pub fn tool_definitions(has_ui: bool) -> Value { "inputSchema": {"type": "object", "properties": {"filter": {"type": "string"}}}}), json!({"name": "inspect_drawing", "description": "Summary of the active drawing: entity counts, extents, layers, styles, blocks, layouts, selection, undo history and (optionally) entities with handles and geometry.", "inputSchema": {"type": "object", "properties": {"entities": {"type": "boolean"}, "limit": {"type": "integer"}}}}), - json!({"name": "query_entities", "description": "Entities filtered by type (Line, Circle, Polyline…), layer, current selection (selected:true; active space only) and/or a window [[x0,y0],[x1,y1]] (objects whose geometry is inside or crosses it; crossing:false = entirely inside). Returns count (all matches), returned (this page) and entities; page with offset and limit (default 500).", + json!({"name": "query_entities", "description": "Entities filtered by type (Line, Circle, Polyline…), layer, current selection (selected:true; active space only) and/or a window [[x0,y0],[x1,y1]] (objects whose geometry is inside or crosses it; crossing:false = entirely inside). xdata:true adds each entity's extended data {APP: [[code, value], …]}; an application name (or a list of names) keeps only the entities carrying that application's data and shows it. Returns count (all matches), returned (this page) and entities; page with offset and limit (default 500).", "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}, "layer": {"type": "string"}, "selected": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, - "crossing": {"type": "boolean"}, "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), + "crossing": {"type": "boolean"}, "xdata": {"type": ["boolean", "string", "array"], "items": {"type": "string"}}, + "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image content block (content[0].type is \"image\", not text): fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape. `background`: \"dark\" (the canvas; the default without a plot style), \"white\" (the default with one, as a plot prints on paper), \"paper\" or \"#rrggbb\"; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. \"monochrome.ctb\" (every colour black, as most plots) or \"grayscale.ctb\", which make light colours readable on white; \"none\" (or \"\") draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown background or plot style is refused.", "inputSchema": {"type": "object", "properties": {"width": {"type": "integer", "minimum": 16}, "height": {"type": "integer", "minimum": 16}, "fit": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index 5804bfe74..731a32598 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -34,6 +34,7 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> { depth: ctx.depth + 1, top: ctx.top, frozen: ctx.frozen, + selecting: ctx.selecting, vp_colors: ctx.vp_colors, // The reference's own linetype scale (group 48) multiplies that of the objects inside, // as LTSCALE does for the drawing (tests/block_ltscale.rs). @@ -112,7 +113,10 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: b.list.expanded = part.list.expanded; b.list.truncated |= part.list.truncated; b.list.undashed = b.list.undashed.saturating_add(part.list.undashed); - append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }); + let limits = b.limits(); + if !append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }, limits) { + b.spend(); + } xclip_frame(b, ctx, region, rgb); } if stop { @@ -126,7 +130,11 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: let mut part = attr_clip.as_ref().map(|_| b.part()); attributes(part.as_mut().unwrap_or(&mut *b), ctx, e, ins, rgb, own); if let (Some(part), Some((region, inverted))) = (part, &attr_clip) { - append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }); + b.list.truncated |= part.list.truncated; + let limits = b.limits(); + if !append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }, limits) { + b.spend(); + } } } @@ -209,24 +217,30 @@ fn attributes(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert let sh = if multiline.is_none() { Some(place_text_entity(ctx.d, &a.text, &a.text.value).0) } else { None }; // Properties of the attribute's definition (as AutoCAD copies them to the attribute // on insertion), except those set on the attribute itself: ByBlock = the reference's, - // layer 0 = the reference's layer. + // layer 0 from the definition = the reference's layer. let def = defs.get(&a.tag.to_ascii_lowercase()).copied(); - let (ink, lw, shown, t) = match (def, a.props.is_empty()) { - (None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference), + let (ink, lw, shown, t, attr_ctx, attr_layer) = match (def, a.props.is_empty()) { + (None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference, sub_ctx(ctx, e, Mat3::IDENTITY), e.common.layer.clone()), (def, _) => { let c = a.props.over(&def.map(|d| d.common.clone()).unwrap_or_else(by_block)); - let (ink, lw, _, _, shown, layer_t, fade) = resolve_common(&sub_ctx(ctx, e, Mat3::IDENTITY), &c, b.plotting); + let mut sub = sub_ctx(ctx, e, Mat3::IDENTITY); + // An attribute set on layer 0 itself is on layer 0 where its reference is, + // not on the reference's layer. + if a.props.layer.is_some() { + sub.block_layer.clone_from(&ctx.block_layer); + } + let (ink, lw, _, _, shown, layer_t, fade) = resolve_common(&sub, &c, b.plotting); // ByBlock takes the reference's own transparency, not its locked-layer fade. let t = if b.opts.transparency { transparency(c.transparency, layer_t, own) } else { 0 }; let t = if b.opts.on_screen { t.max(fade) } else { t }; - (ink, lw, shown, t) + (ink, lw, shown, t, sub, c.layer) } }; if shown { b.transparency = t; let lw = if b.opts.lineweights { lw } else { 0.0 }; match (&multiline, &sh) { - (Some(m), _) => mtext(b, ctx, m, ink, lw), + (Some(m), _) => mtext(b, &attr_ctx, &attr_layer, m, ink, lw), (None, Some(sh)) => b.shaped(ctx, ink, lw, sh), (None, None) => {} } diff --git a/crates/render/src/clip.rs b/crates/render/src/clip.rs index a95455d3d..2834e229d 100644 --- a/crates/render/src/clip.rs +++ b/crates/render/src/clip.rs @@ -53,53 +53,107 @@ pub fn clip_infinite(base: Vec2, dir: Vec2, ray: bool, r: &Bounds2) -> Option<(V Some((base + dir * t0, base + dir * t1)) } +/// Most a clip may produce: points in all, and pieces (each one primitive). Clipping can cut one +/// primitive into many pieces with more points than it had; a clip within a cap stops at it and +/// says so, so it never builds more than the list it goes into has room for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Cap { + pub points: usize, + pub pieces: usize, +} + +impl Cap { + /// No cap. + pub const NONE: Cap = Cap { points: usize::MAX, pieces: usize::MAX }; +} + +/// The pieces of a clipped polyline, built up to a [`Cap`]. +struct Pieces { + out: Vec>, + cur: Vec, + /// The points in `out` and `cur`. + points: usize, + cap: Cap, + /// Whether the cap stopped the pieces. + cut: bool, +} + +impl Pieces { + fn new(cap: Cap) -> Pieces { + Pieces { out: Vec::new(), cur: Vec::new(), points: 0, cap, cut: false } + } + /// End the current piece: kept when it has two points or more. (A piece is started only when + /// the cap has room for it, and has fewer points only once the cap refused one, and then + /// nothing more is added.) + fn end(&mut self) { + let cur = std::mem::take(&mut self.cur); + if cur.len() >= 2 { + self.out.push(cur); + } + } + /// Add `p` to the current piece, unless the cap has no room for it (the pieces are then cut). + fn point(&mut self, p: Vec2) { + if self.points >= self.cap.points { + self.cut = true; + } else { + self.points += 1; + self.cur.push(p); + } + } + /// Add the segment `p`→`q`: to the current piece when it starts where that one ends, else as + /// a new piece. With no piece left in the cap, the pieces are cut there: the new piece is not + /// started, so its points are not copied only to be dropped. + fn segment(&mut self, p: Vec2, q: Vec2) { + if !self.cur.last().is_some_and(|l| l.near(p, 1e-12)) { + self.end(); + if self.out.len() >= self.cap.pieces { + self.cut = true; + return; + } + self.point(p); + } + self.point(q); + } + /// The pieces, and whether they are all there (the cap did not stop them). Cut pieces are a + /// prefix: the last one may end early. + fn finish(mut self) -> (Vec>, bool) { + self.end(); + (self.out, !self.cut) + } +} + /// Clip a polyline to `r`; returns the visible pieces (each with at least two points). pub fn clip_polyline(pts: &[Vec2], r: &Bounds2) -> Vec> { - let mut out: Vec> = Vec::new(); + clip_polyline_within(pts, r, Cap::NONE).0 +} + +/// [`clip_polyline`] within `cap`; false with the pieces when the cap stopped them. +pub fn clip_polyline_within(pts: &[Vec2], r: &Bounds2, cap: Cap) -> (Vec>, bool) { if r.is_empty() { - return out; + return (Vec::new(), true); } // Fast path: everything inside. - if pts.iter().all(|p| r.contains(*p)) { - if pts.len() >= 2 { - out.push(pts.to_vec()); - } - return out; + if pts.len() <= cap.points && cap.pieces > 0 && pts.iter().all(|p| r.contains(*p)) { + return (if pts.len() >= 2 { vec![pts.to_vec()] } else { Vec::new() }, true); } - let mut cur: Vec = Vec::new(); + let mut out = Pieces::new(cap); for w in pts.windows(2) { + if out.cut { + break; + } let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; match clip_segment(*a, *b, r) { Some((p, q)) => { - let joined = cur.last().is_some_and(|l| l.near(p, 1e-12)); - if !joined { - if cur.len() >= 2 { - out.push(std::mem::take(&mut cur)); - } - cur.clear(); - cur.push(p); - } - cur.push(q); + out.segment(p, q); // Leaving the rectangle ends the piece. if !q.near(*b, 1e-12) { - if cur.len() >= 2 { - out.push(std::mem::take(&mut cur)); - } - cur.clear(); + out.end(); } } - None => { - if cur.len() >= 2 { - out.push(std::mem::take(&mut cur)); - } - cur.clear(); - } + None => out.end(), } } - if cur.len() >= 2 { - out.push(cur); - } - out + out.finish() } /// Clip a convex polygon to `r` (Sutherland–Hodgman). @@ -149,22 +203,38 @@ pub fn clip_polygon(poly: &[Vec2], r: &Bounds2) -> Vec { /// Clip a triangle list (three vertices per triangle) to `r`, re-triangulating as fans. pub fn clip_triangles(tris: &[Vec2], r: &Bounds2) -> Vec { + clip_triangles_within(tris, r, usize::MAX).0 +} + +/// [`clip_triangles`] up to `max` points; false with the triangles that fit when it stopped there. +pub fn clip_triangles_within(tris: &[Vec2], r: &Bounds2, max: usize) -> (Vec, bool) { let mut out = Vec::new(); for t in tris.as_chunks::<3>().0 { - if t.iter().all(|p| r.contains(*p)) { - out.extend_from_slice(t); - continue; - } - let poly = clip_polygon(t, r); - if let Some(first) = poly.first().copied() { - for w in poly.get(1..).unwrap_or(&[]).windows(2) { - if let (Some(b), Some(c)) = (w.first(), w.get(1)) { - out.extend_from_slice(&[first, *b, *c]); - } - } + let fits = if t.iter().all(|p| r.contains(*p)) { push_triangle(&mut out, *t, max) } else { push_fan(&mut out, &clip_polygon(t, r), max) }; + if !fits { + return (out, false); } } - out + (out, true) +} + +/// Append triangle `t` to `out` when that keeps it within `max` points. +fn push_triangle(out: &mut Vec, t: [Vec2; 3], max: usize) -> bool { + if out.len().saturating_add(3) > max { + return false; + } + out.extend_from_slice(&t); + true +} + +/// Append the convex polygon `poly` to `out` as a fan of triangles, while they fit within `max` +/// points; false at the first that doesn't. +fn push_fan(out: &mut Vec, poly: &[Vec2], max: usize) -> bool { + let Some(first) = poly.first().copied() else { return true }; + poly.get(1..).unwrap_or(&[]).windows(2).all(|w| match (w.first(), w.get(1)) { + (Some(b), Some(c)) => push_triangle(out, [first, *b, *c], max), + _ => true, + }) } /// Most vertices a clip boundary keeps (denser outlines are thinned; hostile files). @@ -256,6 +326,8 @@ pub struct PolyClip { band_h: f64, /// The region as triangles (for clipping fills), with each triangle's bounds. tris: Vec<([Vec2; 3], Bounds2)>, + /// Whether `tris` cover the whole region: false when they stopped at the fill cap (#3636). + tris_whole: bool, } impl PolyClip { @@ -266,7 +338,7 @@ impl PolyClip { let band_h = bounds.height() / BANDS as f64; let mut bands: Vec> = vec![Vec::new(); BANDS]; let n = poly.len(); - let mut clip = PolyClip { poly: Vec::new(), bounds, bands: Vec::new(), band_h, tris: Vec::new() }; + let mut clip = PolyClip { poly: Vec::new(), bounds, bands: Vec::new(), band_h, tris: Vec::new(), tris_whole: true }; for i in 0..n { let (Some(a), Some(b)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; let (lo, hi) = (clip.band(a.y.min(b.y)), clip.band(a.y.max(b.y))); @@ -274,7 +346,8 @@ impl PolyClip { band.push(i as u32); } } - let tris = crate::fill::triangulate_evenodd(std::slice::from_ref(&poly)); + let (tris, whole) = crate::fill::triangulate_evenodd_whole(std::slice::from_ref(&poly)); + clip.tris_whole = whole; clip.tris = tris .as_chunks::<3>() .0 @@ -293,6 +366,21 @@ impl PolyClip { pub fn bounds(&self) -> Bounds2 { self.bounds } + /// Whether [`PolyClip::clip_triangles`] may leave out part of fill `tris` (three corners each) + /// that lies inside the region: the region's own triangles stopped at the fill cap (a hostile + /// outline, #3636), and one of `tris` is not wholly inside, so it is cut against triangles + /// that may stop short of it. Its parts past them are then left out: a fill cut to such a + /// region is drawn too little, never past the outline. It errs towards true: a triangle within + /// the region's bounds but outside its outline is cut against the triangles too, and counts. + pub fn may_leave_out(&self, tris: &[Vec2]) -> bool { + !self.tris_whole + && tris.as_chunks::<3>().0.iter().any(|&[a, b, c]| { + // As clip_triangles: one it can't keep whole is cut against the triangles. + let inside = + || [a, b, c].iter().all(|p| self.contains(*p)) && [(a, b), (b, c), (c, a)].iter().all(|(p, q)| self.crossings(*p, *q).is_empty()); + Bounds2::from_points([a, b, c]).intersects(&self.bounds) && !inside() + }) + } fn band(&self, y: f64) -> usize { let k = (y - self.bounds.min.y) / self.band_h; if k.is_finite() && k > 0.0 { (k as usize).min(BANDS - 1) } else { 0 } @@ -355,34 +443,34 @@ impl PolyClip { } /// Clip a polyline; returns the visible pieces (each with at least two points). pub fn clip_polyline(&self, pts: &[Vec2]) -> Vec> { - let mut out: Vec> = Vec::new(); - let mut cur: Vec = Vec::new(); + self.clip_polyline_within(pts, Cap::NONE).0 + } + /// [`PolyClip::clip_polyline`] within `cap`; false with the pieces when the cap stopped them. + /// A segment can cross the outline at each of its edges, so the pieces can have far more + /// points than the polyline. + pub fn clip_polyline_within(&self, pts: &[Vec2], cap: Cap) -> (Vec>, bool) { + self.cut_polyline(pts, cap, PolyClip::clip_segment) + } + /// The pieces of polyline `pts` that `segment` keeps of each of its segments, joined where + /// they meet, within `cap`. + fn cut_polyline(&self, pts: &[Vec2], cap: Cap, segment: fn(&PolyClip, Vec2, Vec2, &mut Vec<(Vec2, Vec2)>)) -> (Vec>, bool) { + let mut out = Pieces::new(cap); let mut pieces = Vec::new(); for w in pts.windows(2) { + if out.cut { + break; + } let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; pieces.clear(); - self.clip_segment(*a, *b, &mut pieces); + segment(self, *a, *b, &mut pieces); if pieces.is_empty() { - if cur.len() >= 2 { - out.push(std::mem::take(&mut cur)); - } - cur.clear(); + out.end(); } for (p, q) in pieces.drain(..) { - if !cur.last().is_some_and(|l| l.near(p, 1e-12)) { - if cur.len() >= 2 { - out.push(std::mem::take(&mut cur)); - } - cur.clear(); - cur.push(p); - } - cur.push(q); + out.segment(p, q); } } - if cur.len() >= 2 { - out.push(cur); - } - out + out.finish() } /// Clip an infinite line (or a ray when `ray`) to the region. pub fn clip_infinite(&self, base: Vec2, dir: Vec2, ray: bool) -> Vec> { @@ -393,6 +481,11 @@ impl PolyClip { } /// Clip a triangle list (three vertices per triangle) to the region, re-triangulating as fans. pub fn clip_triangles(&self, tris: &[Vec2]) -> Vec { + self.clip_triangles_within(tris, usize::MAX).0 + } + /// [`PolyClip::clip_triangles`] up to `max` points; false with the triangles that fit when it + /// stopped there (or past 6,000,000 points, for hostile files). + pub fn clip_triangles_within(&self, tris: &[Vec2], max: usize) -> (Vec, bool) { let mut out = Vec::new(); for t in tris.as_chunks::<3>().0 { let tb = Bounds2::from_points(t.iter().copied()); @@ -401,27 +494,21 @@ impl PolyClip { } // Wholly inside: no outline edge crosses it. if t.iter().all(|p| self.contains(*p)) && (0..3).all(|i| self.crossings(t[i], t[(i + 1) % 3]).is_empty()) { - out.extend_from_slice(t); + if !push_triangle(&mut out, *t, max) { + return (out, false); + } continue; } for (c, cb) in &self.tris { if !cb.intersects(&tb) { continue; } - let poly = clip_convex(t, c); - if let Some(first) = poly.first().copied() { - for w in poly.get(1..).unwrap_or(&[]).windows(2) { - if let (Some(b), Some(c)) = (w.first(), w.get(1)) { - out.extend_from_slice(&[first, *b, *c]); - } - } - } - if out.len() > 6_000_000 { - return out; + if !push_fan(&mut out, &clip_convex(t, c), max) || out.len() > 6_000_000 { + return (out, false); } } } - out + (out, true) } /// Clip a segment the other way round (an inverted XCLIP): the pieces outside the region. @@ -444,34 +531,12 @@ impl PolyClip { } /// Clip a polyline to outside the region (an inverted XCLIP); the visible pieces. pub fn clip_polyline_outside(&self, pts: &[Vec2]) -> Vec> { - let mut out: Vec> = Vec::new(); - let mut cur: Vec = Vec::new(); - let mut pieces = Vec::new(); - for w in pts.windows(2) { - let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; - pieces.clear(); - self.clip_segment_outside(*a, *b, &mut pieces); - if pieces.is_empty() { - if cur.len() >= 2 { - out.push(std::mem::take(&mut cur)); - } - cur.clear(); - } - for (p, q) in pieces.drain(..) { - if !cur.last().is_some_and(|l| l.near(p, 1e-12)) { - if cur.len() >= 2 { - out.push(std::mem::take(&mut cur)); - } - cur.clear(); - cur.push(p); - } - cur.push(q); - } - } - if cur.len() >= 2 { - out.push(cur); - } - out + self.clip_polyline_outside_within(pts, Cap::NONE).0 + } + /// [`PolyClip::clip_polyline_outside`] within `cap`; false with the pieces when the cap + /// stopped them. + pub fn clip_polyline_outside_within(&self, pts: &[Vec2], cap: Cap) -> (Vec>, bool) { + self.cut_polyline(pts, cap, PolyClip::clip_segment_outside) } /// Clip an infinite line (or a ray) to outside the region: the line cut where it crosses. pub fn clip_infinite_outside(&self, base: Vec2, dir: Vec2, ray: bool) -> Vec> { @@ -488,14 +553,19 @@ impl PolyClip { /// Fill triangles outside the region (an inverted XCLIP). A triangle wholly inside goes; one /// the outline crosses stays whole (fills are not cut against the outside). pub fn clip_triangles_outside(&self, tris: &[Vec2]) -> Vec { + self.clip_triangles_outside_within(tris, usize::MAX).0 + } + /// [`PolyClip::clip_triangles_outside`] up to `max` points; false with the triangles that fit + /// when it stopped there. + pub fn clip_triangles_outside_within(&self, tris: &[Vec2], max: usize) -> (Vec, bool) { let mut out = Vec::new(); for t in tris.as_chunks::<3>().0 { let inside = t.iter().all(|p| self.contains(*p)) && (0..3).all(|i| self.crossings(t[i], t[(i + 1) % 3]).is_empty()); - if !inside { - out.extend_from_slice(t); + if !inside && !push_triangle(&mut out, *t, max) { + return (out, false); } } - out + (out, true) } } @@ -603,6 +673,114 @@ mod tests { assert!(c.clip_polyline(&[Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0)]).is_empty()); } + /// A region whose triangles stop at the fill cap (#3636): a fill cut against them may lose + /// what lies past them, and says so; one wholly inside, or away from the region, is not cut + /// against them and says nothing. Nothing is drawn past the outline. + #[test] + fn a_region_past_the_fill_cap_says_which_fills_it_may_cut_short() { + let square = |x: f64, y: f64, s: f64| { + let (a, b, c, d) = (Vec2::new(x, y), Vec2::new(x + s, y), Vec2::new(x + s, y + s), Vec2::new(x, y + s)); + vec![a, b, c, a, c, d] + }; + let star = PolyClip::new(&crate::fill::tests::star(251)).unwrap(); + // The star's middle cell is inside it (each edge passes 6.26 from the centre). + let middle = square(-2.0, -2.0, 4.0); + assert!(!star.may_leave_out(&middle) && star.clip_triangles(&middle) == middle); + // Across the outline near the top, above where the region's triangles stop. + let top = square(-20.0, 900.0, 40.0); + assert!(star.may_leave_out(&top) && star.clip_triangles(&top).is_empty()); + // Corners inside it but edges across its outline: cut against the triangles too. + let far = (100..1000).map(|k| Vec2::new(0.0, -f64::from(k))).find(|q| star.contains(*q)).unwrap(); + assert!(star.may_leave_out(&[Vec2::new(-1.0, -1.0), Vec2::new(1.0, -1.0), far])); + assert!(!star.may_leave_out(&square(2000.0, 0.0, 1.0))); + // A region filled whole leaves nothing out. + let whole = PolyClip::new(&crate::fill::tests::star(121)).unwrap(); + assert!(!whole.may_leave_out(&top) && !whole.clip_triangles(&top).is_empty()); + } + + #[test] + fn clips_stop_at_their_cap_and_say_so() { + // A zigzag across the rectangle's top edge: a piece for each dip below it. + let zig: Vec = (0..41).map(|i| Vec2::new(0.25 * f64::from(i), if i % 2 == 0 { 9.0 } else { 11.0 })).collect(); + let all = clip_polyline(&zig, &r()); + let n: usize = all.iter().map(Vec::len).sum(); + assert!(all.len() > 10 && n > all.len() * 2, "{} pieces, {n} points", all.len()); + assert_eq!(clip_polyline_within(&zig, &r(), Cap { points: n, pieces: all.len() }), (all.clone(), true)); + // Cut by points: a prefix of the pieces, the last of which may end early. + let (cut, whole) = clip_polyline_within(&zig, &r(), Cap { points: n - 2, pieces: usize::MAX }); + assert!(!whole && cut.iter().map(Vec::len).sum::() <= n - 2); + let last = cut.len() - 1; + assert!(cut[..last] == all[..last] && all[last].starts_with(&cut[last]), "{cut:?}"); + // Cut by pieces. + assert_eq!(clip_polyline_within(&zig, &r(), Cap { points: usize::MAX, pieces: 3 }), (all[..3].to_vec(), false)); + // Wholly inside but past the cap: not copied whole. + let inside = [Vec2::new(1.0, 1.0), Vec2::new(2.0, 1.0), Vec2::new(3.0, 1.0), Vec2::new(4.0, 1.0)]; + assert_eq!(clip_polyline_within(&inside, &r(), Cap { points: 3, pieces: 1 }), (vec![inside[..3].to_vec()], false)); + + // A comb of 1,000 teeth: a line across it is cut into 1,000 pieces, so the pieces of a + // polyline can have about 1,000 times its points. + let teeth = 1000; + let mut comb = vec![Vec2::new(0.0, 0.0), Vec2::new(2.0 * f64::from(teeth) - 1.0, 0.0)]; + for k in (0..teeth).rev() { + let x = 2.0 * f64::from(k); + comb.extend([Vec2::new(x + 1.0, 10.0), Vec2::new(x, 10.0)]); + if k > 0 { + comb.extend([Vec2::new(x, 1.0), Vec2::new(x - 1.0, 1.0)]); + } + } + let c = PolyClip::new(&comb).unwrap(); + let line = [Vec2::new(-1.0, 5.0), Vec2::new(2.0 * f64::from(teeth), 5.0)]; + assert_eq!(c.clip_polyline(&line).len(), 1000); + let (cut, whole) = c.clip_polyline_within(&line, Cap { points: 101, pieces: usize::MAX }); + assert!(!whole && cut.len() == 50 && cut.iter().all(|p| p.len() == 2), "{}", cut.len()); + assert_eq!(c.clip_polyline_within(&line, Cap { points: usize::MAX, pieces: 10 }).0.len(), 10); + // Outside it: the gaps between the teeth and both ends. + assert_eq!(c.clip_polyline_outside(&line).len(), 1001); + let (cut, whole) = c.clip_polyline_outside_within(&line, Cap { points: usize::MAX, pieces: 10 }); + assert!(!whole && cut.len() == 10); + + // Triangles over the rectangle's corner: each becomes a fan of three. + let corner = [Vec2::new(-0.5, -0.5), Vec2::new(1.5, 0.5), Vec2::new(0.5, 1.5)]; + let tris: Vec = corner.iter().copied().cycle().take(300).collect(); + let all = clip_triangles(&tris, &r()); + assert_eq!(all.len(), 900); + assert_eq!(clip_triangles_within(&tris, &r(), 900), (all.clone(), true)); + assert_eq!(clip_triangles_within(&tris, &r(), 100), (all[..99].to_vec(), false)); + let c = notched(); + let all = c.clip_triangles(&tris); + let (cut, whole) = c.clip_triangles_within(&tris, 30); + assert!(!whole && cut.len() == 30 && all.len() > 30 && all.starts_with(&cut), "{} of {}", cut.len(), all.len()); + assert_eq!(c.clip_triangles_within(&tris, all.len()), (all, true)); + // Triangles wholly inside are kept whole, up to the cap too. + let inside: Vec = [Vec2::new(1.0, 1.0), Vec2::new(2.0, 1.0), Vec2::new(1.0, 2.0)].iter().copied().cycle().take(30).collect(); + assert_eq!(c.clip_triangles_within(&inside, 10), (inside[..9].to_vec(), false)); + assert_eq!(c.clip_triangles_within(&inside, 30), (inside.clone(), true)); + // Outside the notched square, triangles away from it are kept whole. + let away: Vec = [Vec2::new(20.0, 20.0), Vec2::new(21.0, 20.0), Vec2::new(20.0, 21.0)].iter().copied().cycle().take(30).collect(); + assert_eq!(c.clip_triangles_outside_within(&away, 10), (away[..9].to_vec(), false)); + assert_eq!(c.clip_triangles_outside_within(&away, 30), (away.clone(), true)); + } + + #[test] + fn a_piece_the_cap_has_no_room_for_is_not_built() { + // One piece fits the cap; the next one stops the pieces before any of its points are + // copied. + let mut pieces = Pieces::new(Cap { points: 1_000, pieces: 1 }); + pieces.segment(Vec2::new(1.0, 1.0), Vec2::new(10.0, 1.0)); + pieces.end(); + pieces.segment(Vec2::new(10.0, 2.0), Vec2::new(1.0, 2.0)); + assert!(pieces.cut && pieces.cur.is_empty() && pieces.points == 2, "{} points", pieces.points); + // Through the rectangle: out past its right edge, back in, and on inside for 1,000 points. + let back: Vec = [Vec2::new(1.0, 1.0), Vec2::new(11.0, 1.0), Vec2::new(11.0, 2.0), Vec2::new(1.0, 2.0)] + .into_iter() + .chain((0..1000).map(|i| Vec2::new(1.0 + f64::from(i % 2), 3.0 + f64::from(i) * 0.005))) + .collect(); + let first = vec![Vec2::new(1.0, 1.0), Vec2::new(10.0, 1.0)]; + assert_eq!(clip_polyline_within(&back, &r(), Cap { points: usize::MAX, pieces: 1 }), (vec![first.clone()], false)); + // A piece that fits exactly, with nothing visible after it, is whole. + assert_eq!(clip_polyline_within(&back[..3], &r(), Cap { points: 2, pieces: 1 }), (vec![first], true)); + } + #[test] fn triangles() { let t = clip_triangles(&[Vec2::new(-5.0, 0.0), Vec2::new(5.0, 0.0), Vec2::new(5.0, 10.0)], &r()); diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index a141881e9..38ecd7f8b 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -61,9 +61,18 @@ pub struct DimGeometry { pub value: String, /// The text as MTEXT contents (stacked fractions and tolerances). pub mtext: String, + /// The part of the text after `\X`, drawn below the dimension line (DXF Reference: `\X` + /// starts the text below it), as plain text, and where its centre is (#1055). + pub below: Option<(String, Vec2)>, /// Indices into `lines` of the second extension line (DIMLTEX2); the other extension /// lines take DIMLTEX1. pub ext2_lines: Vec, + /// DIMTMOVE 1's leader to text moved off the dimension line (its two ends), which is drawn as + /// a dimension line but isn't the one the text measures. + pub text_leader: Option<(Vec2, Vec2)>, + /// A linear dimension's whole dimension line (its two feet), drawn or not: with DIMSD1 and + /// DIMSD2 both on nothing of it is drawn, yet the text above and below `\X` still sits by it. + pub dim_axis: Option<(Vec2, Vec2)>, } impl DimGeometry { @@ -72,8 +81,12 @@ impl DimGeometry { /// so other programs plot nothing for it, while every font draws `%%c` (#1645). A `%` /// that would run into a code is written `%%%`. pub fn mtext_contents(&self) -> String { - let mut out = String::with_capacity(self.value.len() + 2); - let mut chars = self.value.chars().peekable(); + Self::mtext_code(&self.value) + } + /// [`Self::mtext_contents`] for any piece of a dimension's text (the part below the line too). + pub fn mtext_code(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 2); + let mut chars = text.chars().peekable(); while let Some(c) = chars.next() { match c { '⌀' => out.push_str("%%c"), @@ -266,7 +279,19 @@ impl<'a> DimConfig<'a> { } } + /// Text with `\X`: as wide as its wider part, as high as the part above the line (the part + /// below goes on the other side of it). fn measure(&self, text: &str) -> (f64, f64) { + match split_below(text) { + (above, Some(below)) => { + let ((wa, ha), (wb, _)) = (self.measure_one(above), self.measure_one(below)); + (wa.max(wb), ha) + } + (above, None) => self.measure_one(above), + } + } + + fn measure_one(&self, text: &str) -> (f64, f64) { if text.is_empty() { return (0.0, 0.0); } @@ -355,6 +380,70 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font g.text_mark(ends); } } + // `\X`: the text before it goes above the dimension line, the text after it below. + if let (above, Some(below)) = split_below(&g.mtext) { + let (above, below) = (above.to_string(), below.to_string()); + let n = Vec2::from_angle(text_angle).perp(); + let ((_, ha), (_, hb)) = (config.measure_one(&above), config.measure_one(&below)); + // The dimension line under the text: the line through its longest piece (arrowheads and + // ticks are short; the line may be broken round centred text), not DIMTMOVE 1's leader. + let leader = g.text_leader; + let on_leader = |a: Vec2, b: Vec2| { + leader.is_some_and(|(l0, l1)| { + let eps = 1e-9 * (1.0 + l0.dist(l1)); + let near = |q: Vec2| on_line(q, l0, l1).dist(q) <= eps; + near(a) && near(b) + }) + }; + // The marks drawn with the text (DIMINSPECT's frame, the arc length symbol) aren't it either. + let foot = g + .lines + .iter() + .zip(&g.line_roles) + .enumerate() + .filter(|(i, (_, r))| **r == LineRole::Dim && !g.text_marks.contains(i)) + .flat_map(|(_, (l, _))| l.windows(2)) + .filter_map(|w| match w { + [a, b] if !on_leader(*a, *b) => Some((*a, *b)), + _ => None, + }) + .max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))) + // With both halves suppressed (DIMSD1, DIMSD2) the line isn't drawn but is still there. + .or(g.dim_axis); + if let Some((a, b)) = foot { + let f = on_line(text_mid, a, b); + // DIMJUST 3 and 4 turn the text along an extension line, beside it: it doesn't sit + // on the dimension line, so it stays where it is and the part below goes under it, + // in its own frame. + let across = (b - a).normalized().perp().dot(n).abs() < 0.5; + let below_mid = if across && st.text_just >= 3 && !d.user_text_pos { + text_mid - n * (ha / 2.0 + gap + hb / 2.0) + } else { + let off = (text_mid - f).dot(n); + // Text centred on the line moves above it; text already off it stays where it is. + let side = if off < 0.0 { -1.0 } else { 1.0 }; + if off.abs() < ha / 2.0 + gap * 0.5 && !d.user_text_pos { + text_mid = f + n * (side * (gap + ha / 2.0)); + } + // As far from the line as the text above is when it sits at its place (whatever + // clearance placed it, #2004), on the other side; text moved away (DIMTEDIT, + // DIMTMOVE) leaves the part below at the usual clearance under the line. A taller + // or shorter part below moves by half the difference. + let above_off = (text_mid - f).dot(n).abs(); + let clearance = if above_off <= gap + ha { above_off } else { gap + ha / 2.0 }; + f - n * (side * (clearance + (hb - ha) / 2.0)) + }; + let l = cadcraft_fonts::layout_mtext_with(&below, ¶ms(below_mid, text_angle)); + for p in l.pieces { + let base = g.text_glyphs.len(); + g.text_runs.extend(p.shaped.text.into_iter().map(|t| cadcraft_fonts::TextGlyph { outline: t.outline + base, ..t })); + g.text.extend(p.shaped.strokes); + g.text_glyphs.extend(p.shaped.glyphs); + } + g.below = Some((decode_value(&cadcraft_fonts::plain_mtext(&below)), below_mid)); + } + g.mtext = above; + } // DIMTFILL: a background behind the text, the text box plus DIMGAP on every side. if st.text_fill != 0 && !g.mtext.is_empty() { let (w, h) = measure(&g.mtext); @@ -395,6 +484,26 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font mod linear; mod variants; + +/// The foot of `p` on the line through `a` and `b`. +fn on_line(p: Vec2, a: Vec2, b: Vec2) -> Vec2 { + let ab = b - a; + let len2 = ab.dot(ab); + if len2 <= 0.0 || !len2.is_finite() { + return a; + } + a + ab * ((p - a).dot(ab) / len2) +} + +/// Dimension text split at `\X` (text below the dimension line): the part above and, when there +/// is one, the part below. +fn split_below(text: &str) -> (&str, Option<&str>) { + match text.split_once("\\X") { + Some((above, below)) => (above, Some(below)), + None => (text, None), + } +} + /// `%%` codes in the plain value become their characters (`%%c` → ⌀, `%%p` → ±, `%%d` → °). fn decode_value(s: &str) -> String { cadcraft_fonts::decode_controls(s).into_iter().map(|(c, _, _)| c).collect() diff --git a/crates/render/src/dim/linear.rs b/crates/render/src/dim/linear.rs index 3dc740186..168538886 100644 --- a/crates/render/src/dim/linear.rs +++ b/crates/render/src/dim/linear.rs @@ -212,6 +212,7 @@ fn draw_linear_lines(config: &DimConfig<'_>, g: &mut DimGeometry, state: &Linear let dle = if state.tick_like { st.dim_line_extend * config.scale } else { 0.0 }; let lo = if st.suppress_dim1 { state.measurement / 2.0 } else { f64::NEG_INFINITY }; let hi = if st.suppress_dim2 { state.measurement / 2.0 } else { f64::INFINITY }; + g.dim_axis = Some((state.f1, state.f2)); let seg = |geometry: &mut DimGeometry, a: Vec2, b: Vec2| { let (ta, tb) = ((a - state.f1).dot(u), (b - state.f1).dot(u)); let (t0, t1) = (ta.min(tb).max(lo), ta.max(tb).min(hi)); @@ -266,7 +267,9 @@ fn draw_linear_lines(config: &DimConfig<'_>, g: &mut DimGeometry, state: &Linear let offset = (state.text_mid - base).dot(n).abs(); if offset > state.text_height / 2.0 + config.gap + 1e-9 { let side = if (base - state.text_mid).dot(state.text_axis) >= 0.0 { state.text_axis } else { -state.text_axis }; - g.dim(vec![base, state.text_mid + side * (state.text_width / 2.0 + config.gap)]); + let end = state.text_mid + side * (state.text_width / 2.0 + config.gap); + g.text_leader = Some((base, end)); + g.dim(vec![base, end]); } } if let Some(jog) = d.marks.jog_line { diff --git a/crates/render/src/dim/tests.rs b/crates/render/src/dim/tests.rs index 29fd622cb..ddc1e95b9 100644 --- a/crates/render/src/dim/tests.rs +++ b/crates/render/src/dim/tests.rs @@ -50,6 +50,98 @@ fn vertical_measures_dy() { assert!((g.measurement - 3.0).abs() < 1e-12, "{}", g.measurement); } +/// #1055: `\X` in the text puts what follows below the dimension line, on the other side of +/// it from the rest, at the same distance; the measured value is the part above. +#[test] +fn text_after_backslash_x_goes_below_the_line() { + for (d, on) in [ + (lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0), Vec2::new(5.0, 3.0)), + (lin((0.0, 0.0), (0.0, 10.0), (4.0, 5.0), std::f64::consts::FRAC_PI_2), Vec2::new(4.0, 5.0)), + ] { + let mut d = d; + d.text = "30 MIN.\\X50 MAX.".into(); + for tad in [0, 1] { + let st = st_with(|s| s.text_above = tad); + let g = dimension_geometry(&d, &st, 1.0); + assert_eq!(g.value, "30 MIN.", "tad {tad}"); + let (below, at) = g.below.clone().expect("a part below the line"); + assert_eq!(below, "50 MAX."); + let n = Vec2::from_angle(g.text_angle).perp(); + let (above_side, below_side) = ((g.text_pos - on).dot(n), (at - on).dot(n)); + assert!(above_side > 0.0 && below_side < 0.0, "opposite sides of the line (tad {tad}): {above_side} {below_side}"); + assert!((above_side + below_side).abs() < 1e-9, "same distance: {above_side} {below_side}"); + } + } + // Text moved far off the line with DIMTMOVE 1's leader: the part below still goes just under + // the dimension line, not along the leader nor as far below as the text is above. + let mut moved = lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0); + moved.text = "30 MIN.\\X50 MAX.".into(); + moved.user_text_pos = true; + moved.text_mid = Vec3::new(5.0, 30.0, 0.0); + let g = dimension_geometry(&moved, &st_with(|s| s.text_move = 1), 1.0); + assert!(g.text_leader.is_some(), "a leader to the moved text"); + let (_, at) = g.below.clone().expect("a part below the line"); + assert!(at.y < 3.0 && at.y > 2.5 && (at.x - 5.0).abs() < 1e-6, "{at:?}"); + // Without `\X` nothing goes below. + assert!(dimension_geometry(&lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0), &DimStyle::default(), 1.0).below.is_none()); +} + +/// `\X` with both halves of the dimension line suppressed (DIMSD1, DIMSD2): nothing of the line +/// is drawn, but both parts of the text still sit by it, one on each side, apart. +#[test] +fn text_after_backslash_x_survives_a_suppressed_dimension_line() { + let mut d = lin((0.0, 0.0), (10.0, 5.0), (-3.0 / 5f64.sqrt(), 6.0 / 5f64.sqrt()), 0.0); + d.kind = DimKind::Aligned; + d.text = "30 MIN.\\X50 MAX.".into(); + let on = Vec2::new(-3.0 / 5f64.sqrt(), 6.0 / 5f64.sqrt()); + let ln = Vec2::new(10.0, 5.0).normalized().perp(); + for tad in [0, 1] { + let st = st_with(|s| { + s.suppress_dim1 = true; + s.suppress_dim2 = true; + s.text_inside_horizontal = false; + s.text_above = tad; + }); + let g = dimension_geometry(&d, &st, 1.0); + assert_eq!(g.lines_of(LineRole::Dim).count(), 0, "no dimension line drawn (tad {tad})"); + assert_eq!(g.value, "30 MIN."); + let (below, at) = g.below.clone().expect("a part below the line"); + assert_eq!(below, "50 MAX."); + let (above_side, below_side) = ((g.text_pos - on).dot(ln), (at - on).dot(ln)); + assert!(above_side * below_side < 0.0, "opposite sides of the line (tad {tad}): {above_side} {below_side}"); + assert!((above_side - below_side).abs() >= g.text_height - 1e-9, "apart (tad {tad}): {above_side} {below_side}"); + assert!((at - on).dot(ln.perp()).abs() - (g.text_pos - on).dot(ln.perp()).abs() < 1e-9, "under the text (tad {tad})"); + } +} + +/// `\X` with DIMJUST 3 and 4: the text runs along an extension line, beside it, and stays +/// there; the part below goes under it in its own frame, not onto the dimension line. +#[test] +fn text_after_backslash_x_stays_by_the_extension_line() { + let mut d = lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0); + d.text = "30 MIN.\\X50 MAX.".into(); + for just in [3, 4] { + for tad in [1, 2] { + let st = st_with(|s| { + s.text_just = just; + s.text_above = tad; + }); + let g = dimension_geometry(&d, &st, 1.0); + assert!((g.text_angle - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "along the extension line"); + let beside = if just == 3 { g.text_pos.x < 0.0 } else { g.text_pos.x > 10.0 }; + assert!( + beside && g.text_pos.y > 3.0 + g.text_height, + "beside the extension line, off the dimension line (just {just}, tad {tad}): {:?}", + g.text_pos + ); + let (_, at) = g.below.clone().expect("a part below the text"); + let (x, n) = (Vec2::from_angle(g.text_angle), Vec2::from_angle(g.text_angle).perp()); + assert!((at - g.text_pos).dot(x).abs() < 1e-9, "stacked (just {just}, tad {tad}): {at:?}"); + assert!((g.text_pos - at).dot(n) >= g.text_height - 1e-9, "under it, apart (just {just}, tad {tad}): {at:?} {:?}", g.text_pos); + } + } +} + #[test] fn override_text() { let mut d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0); @@ -560,6 +652,58 @@ fn radial_and_angular_text() { assert_eq!(g.value, "1.57r"); } +#[test] +fn radial_dimpost_replaces_only_automatic_radius_and_diameter_prefixes() { + let linear = lin((0.0, 0.0), (5.0, 0.0), (0.0, 4.0), 0.0); + let radius = Dimension { kind: DimKind::Radius, defpt: Vec3::ZERO, p15: Vec3::new(5.0, 0.0, 0.0), ..linear.clone() }; + let diameter = Dimension { kind: DimKind::Diameter, defpt: Vec3::new(-5.0, 0.0, 0.0), ..radius.clone() }; + let arc = Dimension { + kind: DimKind::ArcLength, + defpt: Vec3::new(4.0, 4.0, 0.0), + p13: Vec3::new(5.0, 0.0, 0.0), + p14: Vec3::new(0.0, 5.0, 0.0), + ..linear.clone() + }; + let arc_style = DimStyle { arc_symbol: 0, post: "ARC <>".into(), ..DimStyle::default() }; + assert!(dimension_geometry(&arc, &arc_style, 1.0).value.starts_with("ARC ⌒")); + + for (post, expected) in [ + ("", ["R5", "%%c10", "5"]), + ("<> REF", ["R5 REF", "%%c10 REF", "5 REF"]), + (" REF", ["R5 REF", "%%c10 REF", "5 REF"]), + ("PAIR <>", ["PAIR 5", "PAIR 10", "PAIR 5"]), + ("PAIR R<>", ["PAIR R5", "PAIR R10", "PAIR R5"]), + ("%%c<>", ["%%c5", "%%c10", "%%c5"]), + ] { + let st = DimStyle { decimals: 0, post: post.into(), ..DimStyle::default() }; + for (d, want) in [&radius, &diameter, &linear].into_iter().zip(expected) { + assert_eq!(dimension_geometry(d, &st, 1.0).mtext_contents(), want, "{:?}, DIMPOST {post:?}", d.kind); + } + } +} + +#[test] +fn radial_dimpost_keeps_jogged_radius_tolerances_and_alternate_units() { + let mut d = lin((0.0, 0.0), (0.0, 0.0), (0.0, 0.0), 0.0); + d.kind = DimKind::Radius; + d.p15 = Vec3::new(5.0, 0.0, 0.0); + d.marks.jogged = Some(cadcraft_doc::JoggedRadius { center: Vec3::new(0.0, -4.0, 0.0), jog: Vec3::new(2.5, -2.0, 0.0) }); + let st = DimStyle { + post: "PAIR <> REF".into(), + decimals: 1, + tolerance: true, + tol_plus: 0.1, + tol_minus: 0.1, + tol_decimals: 1, + alt: true, + alt_factor: 2.0, + alt_decimals: 1, + alt_post: "ALT <>".into(), + ..DimStyle::default() + }; + assert_eq!(dimension_geometry(&d, &st, 1.0).value, "PAIR 5.0 REF±0.1 REF [ALT 10.0]"); +} + #[test] fn hostile_styles_do_not_panic() { let d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0); diff --git a/crates/render/src/dim/text.rs b/crates/render/src/dim/text.rs index b362eb706..c1ab63350 100644 --- a/crates/render/src/dim/text.rs +++ b/crates/render/src/dim/text.rs @@ -1,4 +1,4 @@ -use super::{DimStyle, Dimension, NumFormat, TextFont, format_decimal, format_linear}; +use super::{DimKind, DimStyle, Dimension, NumFormat, TextFont, format_decimal, format_linear}; /// Format a linear measurement per the style (plain text). pub fn format_linear_value(v: f64, st: &DimStyle) -> String { @@ -17,6 +17,11 @@ pub(super) fn linear_text(meas: f64, d: &Dimension, st: &DimStyle, prefix: &str) let lo = format_linear(v - st.tol_minus, &nf).1; format!("{{\\H{};\\S{up}^{lo};}}", tol_height_code(st)) } else { + // An authored DIMPOST prefix replaces the default radius or diameter symbol. + let prefix = match d.kind { + DimKind::Radius | DimKind::Diameter if st.post.find("<>").is_some_and(|marker| marker > 0) => "", + _ => prefix, + }; format!("{prefix}{}", format_linear(v, &nf).1) }; let mut s = post(&st.post, &main); diff --git a/crates/render/src/display.rs b/crates/render/src/display.rs index 7aae0d882..cff8ff864 100644 --- a/crates/render/src/display.rs +++ b/crates/render/src/display.rs @@ -107,9 +107,11 @@ pub struct DisplayList { pub sheet: Option, /// Block contents expanded while building (see [`MAX_BLOCK_EXPANSION`]). pub expanded: usize, - /// The block-expansion budget or the point budget ([`crate::MAX_DISPLAY_POINTS`]) was spent: - /// block contents or objects past it are not in the list; or a dashed run was drawn - /// continuous past a dash limit ([`DisplayList::undashed`]). The screen, + /// The block-expansion budget, the point budget ([`crate::MAX_DISPLAY_POINTS`]) or the + /// primitive budget ([`crate::MAX_DISPLAY_PRIMS`]) was spent: block contents or objects past it + /// are not in the list; or a dashed run was drawn continuous past a dash limit + /// ([`DisplayList::undashed`]); or plot style ends, joins or fill patterns were left out past + /// the point budget ([`pen::apply`]). The screen, /// plots and exports draw what is here; the control channel and the MCP render report this, /// so an output that leaves contents out is never silent (#1070). pub truncated: bool, diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 9bb8a92b0..1575f66aa 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -22,8 +22,9 @@ pub(crate) fn entity(b: &mut Builder, ctx: &Ctx, e: &Entity) { if ctx.d.is_hidden_object(e.handle) || b.opts.cancelled() { return; } - // Once the build holds all the points it may, nothing more is drawn (or computed). - if b.points_spent() { + // Once the build holds all the points or primitives it may, nothing more is drawn (or + // computed). + if b.spent() { b.list.truncated = true; return; } @@ -59,6 +60,15 @@ fn shown_transparency(b: &mut Builder, ctx: &Ctx, e: &Entity, layer_transparency own } +/// While a reference is edited in place (REFEDIT), everything outside the working set is faded by +/// XFADECTL percent on screen: how much `e` fades (0 when it doesn't). +fn refedit_fade(b: &Builder, ctx: &Ctx, e: &Entity) -> u8 { + match b.fade { + Some(f) if !b.plotting && !f.working.contains(&if ctx.depth == 0 { e.handle } else { ctx.top }) => f.percent, + _ => 0, + } +} + fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { // A top-level annotative object draws at the view's annotation scale: a viewport's scale for // model space seen through it, else the drawing's (CANNOSCALE in model space, 1:1 on paper). @@ -82,6 +92,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if !visible { return; } + let fade = fade.max(refedit_fade(b, ctx, e)); let own = shown_transparency(b, ctx, e, layer_transparency, fade); // A plot style's linetype replaces the object's. let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { @@ -157,9 +168,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { return; } if e.common.matches_layout_orientation() && t.rotation != 0.0 { - mtext(b, ctx, &cadcraft_doc::MText { rotation: 0.0, ..t.clone() }, rgb, lw); + mtext(b, ctx, &e.common.layer, &cadcraft_doc::MText { rotation: 0.0, ..t.clone() }, rgb, lw); } else { - mtext(b, ctx, t, rgb, lw); + mtext(b, ctx, &e.common.layer, t, rgb, lw); } } EntityKind::Insert(ins) => insert(b, ctx, e, ins, rgb, own), @@ -275,7 +286,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { Prim::Point(p) => b.point(ctx, rgb, p), Prim::Infinite { base, dir, ray } => b.infinite(ctx, rgb, base, dir, ray), Prim::Fill(pts) => { - let tris = fill::triangulate_evenodd(&[pts]); + let tris = b.region_tris(&[pts]); b.tris(ctx, rgb, &tris); } } @@ -297,7 +308,9 @@ fn draw_mleader(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &cadcraft_doc::MLeade let land = m.landing.xy(); let dir = if t.insert.x >= land.x { 1.0 } else { -1.0 }; b.polyline(ctx, rgb, lw, &[land, land + Vec2::new(m.dogleg * dir, 0.0)]); - mtext(b, ctx, t, rgb, lw); + if b.opts.text { + mtext(b, ctx, &e.common.layer, t, rgb, lw); + } } if let Some(ins) = &m.block { if m.dogleg > 0.0 && !m.leaders.is_empty() { @@ -342,7 +355,8 @@ fn draw_wipeout(b: &mut Builder, ctx: &Ctx, w: &cadcraft_doc::Wipeout, rgb: Ink, // 0 = none, 1 = shown and plotted, 2 = shown but not plotted. if b.opts.fill { let n = b.list.prims.len(); - b.tris(ctx, rgb, &fill::triangulate_evenodd(std::slice::from_ref(&w.boundary))); + let tris = b.region_tris(std::slice::from_ref(&w.boundary)); + b.tris(ctx, rgb, &tris); if let Some(p) = b.list.prims.get_mut(n) { p.kind = Kind::Mask; } diff --git a/crates/render/src/fill.rs b/crates/render/src/fill.rs index 2ac7c286f..d6958d04f 100644 --- a/crates/render/src/fill.rs +++ b/crates/render/src/fill.rs @@ -9,8 +9,29 @@ use crate::pen::MITER_LIMIT; /// horizontal slabs at every vertex y and emitting trapezoids. Two edges that cross inside a slab /// (a bowtie, two loops crossing each other) swap order there, so such a slab is cut again at the /// crossing and each part is paired on its own. Robust for any input; output size is -/// O(slabs × crossings), capped for hostile inputs. +/// O(slabs × crossings), capped for hostile inputs: past `MAX_FILL_EDGES` edges nothing is +/// filled, and once the triangles pass `MAX_FILL_POINTS` points the slabs above are left out. +/// `triangulate_evenodd_whole` says when that happened. pub fn triangulate_evenodd(loops: &[Vec]) -> Vec { + triangulate_evenodd_within(loops, MAX_FILL_POINTS).0 +} + +/// [`triangulate_evenodd`], and whether its triangles cover the whole region (false when a cap +/// left part of it out). A display list drawn from triangles that don't is marked truncated, so a +/// fill left part-done is never silent (#3636). +pub(crate) fn triangulate_evenodd_whole(loops: &[Vec]) -> (Vec, bool) { + triangulate_evenodd_within(loops, MAX_FILL_POINTS) +} + +/// Most edges a region may have to be filled at all (hostile inputs). +const MAX_FILL_EDGES: usize = 200_000; + +/// Points past which a region's triangles stop (hostile inputs): the slab that passes it is the +/// last one filled. +const MAX_FILL_POINTS: usize = 6_000_000; + +/// [`triangulate_evenodd_whole`] with the triangles stopping once they pass `max` points. +fn triangulate_evenodd_within(loops: &[Vec], max: usize) -> (Vec, bool) { let mut edges: Vec<(Vec2, Vec2)> = Vec::new(); for l in loops { let n = l.len(); @@ -24,8 +45,11 @@ pub fn triangulate_evenodd(loops: &[Vec]) -> Vec { } } } - if edges.is_empty() || edges.len() > 200_000 { - return Vec::new(); + if edges.is_empty() { + return (Vec::new(), true); + } + if edges.len() > MAX_FILL_EDGES { + return (Vec::new(), false); } let mut ys: Vec = edges.iter().flat_map(|(a, b)| [a.y, b.y]).collect(); ys.sort_by(f64::total_cmp); @@ -79,18 +103,21 @@ pub fn triangulate_evenodd(loops: &[Vec]) -> Vec { continue; } } + // Past the cap the slabs from this one up are left out. It is checked before a slab + // that adds triangles rather than after the one that passed it, so the triangles are + // the same and a region whose last slab passes it is whole. + if xs.len() >= 2 && out.len() > max { + return (out, false); + } for pair in xs.chunks(2) { if let [l, r] = pair { let (a, b, c, d) = (Vec2::new(l.1, ya), Vec2::new(r.1, ya), Vec2::new(r.2, yb), Vec2::new(l.2, yb)); out.extend_from_slice(&[a, b, c, a, c, d]); } } - if out.len() > 6_000_000 { - return out; - } } } - out + (out, true) } /// How many extra slab boundaries crossings may add over one region. @@ -419,6 +446,45 @@ pub(crate) mod tests { assert!((area(&tris) - 20.0).abs() < 1e-9, "{}", area(&tris)); } + /// The star polygon {n/((n-1)/2)} for an odd `n`: `n` points on a circle of radius 1000, each + /// joined to the one almost opposite, so its edges cross each other many times (#3636). + pub(crate) fn star(n: usize) -> Vec { + let step = (n - 1) / 2; + (0..n).map(|i| Vec2::polar(Vec2::ZERO, 1000.0, std::f64::consts::TAU * ((i * step) % n) as f64 / n as f64 + 0.1234567)).collect() + } + + /// Past its cap a fill stops after the slab that passed it, and says so: its triangles are then + /// the start of the whole fill. A fill whose last slab passes the cap leaves nothing out, even + /// under a sliver too thin to make a slab of its own (#3636). + #[test] + fn filling_stops_past_its_cap_and_says_so() { + let loops = [star(21)]; + let (all, whole) = triangulate_evenodd_within(&loops, usize::MAX); + assert!(whole && all.len() > 1000, "{}", all.len()); + assert_eq!(triangulate_evenodd_whole(&loops), (all.clone(), true)); + assert_eq!(triangulate_evenodd(&loops), all); + let (cut, whole) = triangulate_evenodd_within(&loops, all.len() / 2); + assert!(!whole && cut.len() > all.len() / 2 && cut.len() < all.len() && all.starts_with(&cut), "{} of {}", cut.len(), all.len()); + assert_eq!(triangulate_evenodd_within(&loops, all.len() - 1), (all, true)); + let square = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)]; + let sliver = vec![Vec2::new(0.0, 5.0), Vec2::new(1.0, 5.0 + 1e-13), Vec2::new(2.0, 5.0)]; + let (tris, whole) = triangulate_evenodd_within(&[square, sliver], 5); + assert!(whole && tris.len() == 6, "{tris:?}"); + } + + /// A region with more edges than [`MAX_FILL_EDGES`] is not filled at all, and says so. + #[test] + fn a_region_with_too_many_edges_is_left_empty_and_says_so() { + let ring = |n: usize| -> Vec { + (0..n).map(|i| Vec2::polar(Vec2::ZERO, 1000.0, std::f64::consts::TAU * i as f64 / n as f64 + 0.1234567)).collect() + }; + let (tris, whole) = triangulate_evenodd_whole(&[ring(MAX_FILL_EDGES)]); + assert!(whole && !tris.is_empty()); + assert_eq!(triangulate_evenodd_whole(&[ring(MAX_FILL_EDGES + 1)]), (Vec::new(), false)); + // No edges at all is an empty region, not a cut one. + assert_eq!(triangulate_evenodd_whole(&[vec![Vec2::ZERO, Vec2::X]]), (Vec::new(), true)); + } + #[test] fn degenerate_input() { assert!(triangulate_evenodd(&[vec![Vec2::ZERO, Vec2::X]]).is_empty()); diff --git a/crates/render/src/hatch.rs b/crates/render/src/hatch.rs index b96180a23..20e0aa812 100644 --- a/crates/render/src/hatch.rs +++ b/crates/render/src/hatch.rs @@ -8,9 +8,9 @@ //! line (as linetypes already are), and nothing is generated outside the view. Plots, exports and //! picks pass `min_dash = 0` and `view = None` and get every line. -use super::{Builder, Ctx, Ink, fill, ink, max_scale}; +use super::{Builder, Ctx, Ink, ink, max_scale}; use cadcraft_color::{Color, Rgb}; -use cadcraft_doc::library::{PatternLine, pattern_for}; +use cadcraft_doc::library::{PatternLine, effective_hatch_pattern_scale, pattern_for}; use cadcraft_doc::{Drawing, Entity, Gradient, Hatch}; use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -33,7 +33,7 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, h: &Hatch, rgb: Ink, let dense = b.opts.fill && reads_solid(ctx.d, h, px); if h.solid || h.pattern.eq_ignore_ascii_case("SOLID") || h.gradient.is_some() || dense { if b.opts.fill { - let tris = fill::triangulate_evenodd(&loops); + let tris = b.region_tris(&loops); match &h.gradient { Some(g) => gradient(b, ctx, g, layer_color, &tris), None => b.tris(ctx, rgb, &tris), @@ -44,7 +44,8 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, h: &Hatch, rgb: Ink, if let Some(bg) = h.background && b.opts.fill { - b.tris(ctx, ink(bg, layer_color, ctx.block_color), &fill::triangulate_evenodd(&loops)); + let tris = b.region_tris(&loops); + b.tris(ctx, ink(bg, layer_color, ctx.block_color), &tris); } // The area being looked at, in the hatch's units. let view = b.opts.view.and_then(|v| { @@ -81,43 +82,97 @@ fn same_polygon(a: &[Vec2], b: &[Vec2]) -> bool { /// Remove degenerate and duplicate boundary loops within a shared comparison budget. /// Retain remaining loops without further comparisons once the budget is exhausted. +#[cfg(test)] fn dedup_polygons(loops: &mut Vec>) { + let roled: Vec<(usize, bool, Vec)> = loops.drain(..).enumerate().map(|(i, l)| (i, true, l)).collect(); + *loops = dedup_roles(roled).into_iter().map(|(_, _, l)| l).collect(); +} + +/// [`dedup_polygons`] with each loop's role (outer, or island) and index: a loop the same as one +/// kept in the same role is a duplicate and goes (a file can repeat a loop); one the same as a +/// kept loop in the other role cancels it, both going, as they do under the odd-parity fill (one +/// pick's outer loop that is another's island: a pick inside a circle and one around it fill the +/// circle too). +fn dedup_roles(loops: Vec<(usize, bool, Vec)>) -> Vec<(usize, bool, Vec)> { // `same_polygon` is O(n²) in a polygon's vertex count (every cyclic alignment, both windings), - // and each loop is compared against every unique one kept so far, so adversarial boundary - // geometry could force quadratic-on-quadratic work. Charge every vertex comparison against a - // shared budget; once it is spent, stop deduplicating and keep the remaining loops as-is - // (CWE-407). + // and each loop is compared with the loops kept so far, so adversarial boundary geometry could + // force quadratic-on-quadratic work. Only loops that could match are looked at (same role, or + // the other one, and the same vertex count, found by key), every vertex comparison is charged + // against a shared budget, and once it is spent no more loops are looked at: the rest are kept + // as they are (CWE-407). let mut budget: u64 = MAX_DEDUP_COMPARISONS; - let mut unique: Vec> = Vec::with_capacity(loops.len()); - for l in loops.drain(..) { + // First a repeat within its role goes: the first of each boundary per role is kept. + let mut unique: Vec<(usize, bool, Vec)> = Vec::with_capacity(loops.len()); + let mut by_shape: std::collections::HashMap<(bool, usize), Vec> = std::collections::HashMap::new(); + for (i, outer, l) in loops { if l.len() < 3 { continue; } - let mut dup = false; - for u in &unique { - if u.len() != l.len() { - continue; - } - // Each `same_polygon` call costs about 2·len² comparisons; stop if that would overrun. - let cost = 2u64.saturating_mul((u.len() as u64).saturating_mul(l.len() as u64)); - match budget.checked_sub(cost) { - Some(left) => budget = left, - None => { - // Out of budget: keep `l` without further comparison. - budget = 0; - break; - } + let key = (outer, l.len()); + let mut repeat = false; + for &k in by_shape.get(&key).map_or(&[][..], Vec::as_slice) { + let Some((_, _, u)) = unique.get(k) else { continue }; + if !charge(&mut budget, u.len(), l.len()) { + break; } if same_polygon(u, &l) { - dup = true; + repeat = true; break; } } - if !dup { - unique.push(l); + if !repeat { + by_shape.entry(key).or_default().push(unique.len()); + unique.push((i, outer, l)); + } + } + // Then an outer loop and an island that are the same boundary cancel, whatever their order. + let mut slots: Vec)>> = Vec::with_capacity(unique.len()); + let mut open: std::collections::HashMap<(bool, usize), Vec> = std::collections::HashMap::new(); + for (i, outer, l) in unique { + let twin_key = (!outer, l.len()); + let mut twin = None; + for (at, &k) in open.get(&twin_key).map_or(&[][..], Vec::as_slice).iter().enumerate() { + let Some(Some((_, _, u))) = slots.get(k) else { continue }; + if !charge(&mut budget, u.len(), l.len()) { + break; + } + if same_polygon(u, &l) { + twin = Some((at, k)); + break; + } + } + match twin { + Some((at, k)) => { + if let Some(slot) = slots.get_mut(k) { + *slot = None; + } + if let Some(ks) = open.get_mut(&twin_key) { + ks.remove(at); + } + } + None => { + open.entry((outer, l.len())).or_default().push(slots.len()); + slots.push(Some((i, outer, l))); + } + } + } + slots.into_iter().flatten().collect() +} + +/// Charge a `same_polygon` call between loops of `a` and `b` vertices (about 2·a·b comparisons) +/// against `budget`: false, with the budget spent, when it would overrun. +fn charge(budget: &mut u64, a: usize, b: usize) -> bool { + let cost = 2u64.saturating_mul((a as u64).saturating_mul(b as u64)); + match budget.checked_sub(cost) { + Some(left) if *budget > 0 => { + *budget = left; + true + } + _ => { + *budget = 0; + false } } - *loops = unique; } /// Vertex comparisons `dedup_polygons` may perform before it stops deduplicating. @@ -128,32 +183,45 @@ const MAX_DEDUP_COMPARISONS: u64 = 50_000_000; /// within islands alternate), 1 outer keeps the outermost loops and their first islands, 2 /// ignore keeps only the outermost loops. Nesting depth = how many other loops enclose a loop. pub fn fill_loops(h: &Hatch, tol: f64) -> Vec> { + fill_loop_indices(h, tol).into_iter().map(|(_, l)| l).collect() +} + +/// [`fill_loops`] with the index in `h.loops` of each loop kept (AREA measures those exactly). +pub fn fill_loop_indices(h: &Hatch, tol: f64) -> Vec<(usize, Vec)> { // One point budget for all the loops: many short arcs across loops must not add up unbounded. let mut budget = cadcraft_geom::MAX_TESSELLATED_POINTS; - // Source loops that are the same boundary up to start vertex and winding are tessellated once, so a - // duplicate cannot be sampled coarser than its twin by the shared budget and then escape `dedup_polygons`. - let mut seen = std::collections::HashSet::new(); - let mut loops: Vec> = h + // Source loops that are the same boundary up to start vertex and winding are tessellated once and + // share that tessellation, so a duplicate cannot be sampled coarser than its twin by the shared + // budget and then escape `dedup_roles`. Each keeps its own role: a repeat in the same role still + // collapses there, and an outer loop still cancels against the same boundary as an island. + let mut tessellated: std::collections::HashMap, Vec> = std::collections::HashMap::new(); + let roled: Vec<(usize, bool, Vec)> = h .loops .iter() - .filter(|l| seen.insert(canonical_key(&l.vertices))) - .map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate_within(tol, &mut budget)) + .enumerate() + .map(|(i, l)| { + let pts = tessellated + .entry(canonical_key(&l.vertices)) + .or_insert_with(|| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate_within(tol, &mut budget)) + .clone(); + (i, l.outer, pts) + }) .collect(); - dedup_polygons(&mut loops); + let loops: Vec<(usize, Vec)> = dedup_roles(roled).into_iter().map(|(i, _, l)| (i, l)).collect(); let max_depth = match h.style { 1 => 1, 2 => 0, _ => return loops, }; - let verts: usize = loops.iter().map(Vec::len).sum(); + let verts: usize = loops.iter().map(|(_, l)| l.len()).sum(); if loops.len().saturating_mul(verts) > MAX_ISLAND_WORK { return loops; } let depth = |i: usize, l: &[Vec2]| { let Some(p) = probe(l) else { return 0 }; - loops.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count() + loops.iter().enumerate().filter(|(j, (_, o))| *j != i && point_in_polygon(o, p)).count() }; - loops.iter().enumerate().filter(|(i, l)| depth(*i, l) <= max_depth).map(|(_, l)| l.clone()).collect() + loops.iter().enumerate().filter(|(i, (_, l))| depth(*i, l) <= max_depth).map(|(_, x)| x.clone()).collect() } /// Start index of the least rotation of `s` (two-pointer scan, O(n)). @@ -202,7 +270,7 @@ fn canonical_key(v: &[PolyVertex]) -> Vec<[u64; 3]> { /// A point of a loop to test its nesting with: the middle of its first non-degenerate edge /// (vertices may touch an enclosing loop; edge midpoints rarely do). -fn probe(l: &[Vec2]) -> Option { +pub fn probe(l: &[Vec2]) -> Option { let n = l.len(); (0..n).find_map(|i| { let (a, b) = (*l.get(i)?, *l.get((i + 1) % n)?); @@ -372,11 +440,6 @@ fn lines_of(d: &Drawing, h: &Hatch) -> Vec { } } -/// The hatch's pattern scale (1 when unusable). -fn scale_of(h: &Hatch) -> f64 { - if h.scale.is_finite() && h.scale > 1e-9 { h.scale } else { 1.0 } -} - /// True when, at `px` hatch units per pixel, the pattern covers its area on screen, so drawing /// it line by line would fill (nearly) every pixel anyway. Each line, dash or dot is drawn at /// least a pixel wide, so that is the case when @@ -390,7 +453,7 @@ pub fn reads_solid(d: &Drawing, h: &Hatch, px: f64) -> bool { if !(px.is_finite() && px > 0.0) { return false; } - let scale = scale_of(h); + let scale = effective_hatch_pattern_scale(h.scale); let mut coverage = 0.0; for f in lines_of(d, h) { let spacing = (f.delta.1 * scale).abs(); @@ -452,7 +515,7 @@ fn pattern_lines_within( work_limit: u64, ) -> Vec> { let lines = lines_of(d, h); - let scale = scale_of(h); + let scale = effective_hatch_pattern_scale(h.scale); let px = if px.is_finite() && px > 0.0 { px } else { 0.0 }; let mut out = Vec::new(); // Shared work budget across all families and spans, counting dash-processing steps even when @@ -704,12 +767,75 @@ mod tests { }; let loops = fill_loops(&hatch, 1e-4); assert_eq!(loops.len(), 1, "fill_loops must deduplicate duplicate loops"); - let tris = fill::triangulate_evenodd(&loops); + let tris = crate::fill::triangulate_evenodd(&loops); let area: f64 = tris.chunks(3).map(|t| ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs()).sum(); assert!((area - 100.0).abs() < 1e-6, "triangulated area must be 100.0, not zero"); } } +#[cfg(test)] +mod role_dedup_tests { + use super::*; + use cadcraft_doc::{Hatch, HatchLoop}; + use cadcraft_geom::PolyVertex; + + fn square(x0: f64, x1: f64, outer: bool) -> HatchLoop { + HatchLoop { + vertices: [(x0, x0), (x1, x0), (x1, x1), (x0, x1)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), + outer, + boundary_flags: None, + sources: vec![], + } + } + + /// The same boundary as outer and island loops: repeats within a role collapse first, then an + /// outer loop and an island cancel, so the fill doesn't depend on the loops' order. + #[test] + fn coincident_loops_give_the_same_fill_in_any_order() { + let hatch = |loops: Vec| Hatch { + origin: Vec2::ZERO, + pattern: "SOLID".into(), + solid: true, + loops, + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + background: None, + pattern_lines: vec![], + }; + let inner = |o: bool| square(40.0, 60.0, o); + for order in [vec![true, false, true], vec![true, true, false], vec![false, true, true]] { + let mut loops = vec![square(0.0, 100.0, true)]; + loops.extend(order.iter().map(|&o| inner(o))); + let kept = fill_loops(&hatch(loops), 1e-4); + assert_eq!(kept.len(), 1, "{order:?}: only the enclosing square is left"); + } + } +} + +#[cfg(test)] +mod role_dedup_scale_tests { + use super::*; + + /// Many distinct loops (as an adversarial file may hold) are sorted out quickly: only loops + /// that could match are looked at, and once the budget is spent none are. + #[test] + fn many_distinct_loops_are_handled_quickly() { + let tri = |k: usize| { + let x = k as f64; + vec![Vec2::new(x, 0.0), Vec2::new(x + 0.5, 0.0), Vec2::new(x, 0.5)] + }; + let loops: Vec<(usize, bool, Vec)> = (0..40_000).map(|k| (k, k % 2 == 0, tri(k))).collect(); + let start = std::time::Instant::now(); + let kept = dedup_roles(loops); + assert_eq!(kept.len(), 40_000); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); + } +} + #[cfg(test)] mod dedup_budget_tests { use super::*; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 97bee349d..0da2991de 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -33,7 +33,7 @@ use pen::Pen; pub use dim::{ArrowGeom, Arrowhead, DimGeometry, DimText, LineRole, arrowhead, dimension_geometry, dimension_geometry_with, format_linear_value}; pub use fill::triangulate_evenodd; -pub use hatch::{fill_loops as hatch_fill_loops, pattern_swatch}; +pub use hatch::{fill_loop_indices as hatch_fill_loop_indices, fill_loops as hatch_fill_loops, pattern_swatch, probe as hatch_loop_probe}; pub use paper::{PAPER_SIZES, PaperSize, Sheet, paper_size, sheet}; pub use tolerance::{gdt_points, tolerance_in}; @@ -92,6 +92,11 @@ struct Ctx<'a> { top: Handle, /// Layers frozen in the viewport being drawn. frozen: &'a [String], + /// Built as loose entities ([`build_entities_in_viewport`]: for a selection, a highlight or a + /// preview) and not to draw a viewport: a point on the layer Defpoints that is a part of a + /// block is then kept whatever layers are given as frozen + /// ([`cadcraft_doc::point_on_defpoints`]). + selecting: bool, /// Per-viewport layer colour overrides of the viewport being drawn. vp_colors: &'a [(String, Color)], /// Extra linetype scale for model space seen through a viewport: 1 / viewport scale when @@ -134,6 +139,10 @@ struct Builder<'a> { points: &'a std::sync::atomic::AtomicUsize, /// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests). max_points: usize, + /// Primitives the whole build has charged so far, shared like `points`. + prims: &'a std::sync::atomic::AtomicUsize, + /// The most primitives the build may hold: [`MAX_DISPLAY_PRIMS`] (less in tests). + max_prims: usize, /// Dash pattern elements the whole build has laid out so far, shared like `points`. dashes: &'a std::sync::atomic::AtomicUsize, /// The most dash pattern elements the build may lay out: [`MAX_DASH_ELEMENTS`] (less in tests). @@ -141,6 +150,24 @@ struct Builder<'a> { /// The loops of the drawing's block graph, worked out once for the whole build when a search /// near a dimension's block does not settle whether it leads back (see [`loops`]). loops: &'a std::sync::OnceLock, + /// While a reference is edited in place: what is drawn faded ([`Fade::of`]). + fade: Option<&'a Fade>, +} + +/// While a reference is edited in place (REFEDIT), everything outside the working set is drawn +/// faded by XFADECTL percent on screen. Built once per display list: a lookup per object drawn +/// would scan the working set each time. +struct Fade { + working: std::collections::HashSet, + percent: u8, +} + +impl Fade { + fn of(d: &Drawing) -> Option { + let r = d.refedit.as_ref()?; + let percent = u8::try_from(d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50); + Some(Fade { working: r.items.iter().map(|i| i.copy).collect(), percent }) + } } /// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy @@ -159,6 +186,27 @@ pub const MAX_BLOCK_EXPANSION: usize = 2_000_000; /// for a plot) is expected to hold a few tens of millions. pub const MAX_DISPLAY_POINTS: usize = 64_000_000; +/// Upper bound on the primitives one display list holds. Each primitive is charged at least one +/// point, so on a 64-bit target [`MAX_DISPLAY_POINTS`] bounds them already and this is the same +/// number. A 32-bit target (the web build) has 2 GiB per allocation and 4 GiB in all: at 40 bytes +/// a primitive, a list of more than 2^25 one-point primitives (a dotted linetype) needed more than +/// 2 GiB when its primitive vector grew, and the build panicked with "capacity overflow" (#1603). +/// There a list holds at most 2^24 primitives (640 MiB of them), below that limit to leave room +/// for the canvas's vertex data and for the next list, built while this one is still shown. Past +/// the limit nothing more is drawn and [`DisplayList::truncated`] is set. +pub const MAX_DISPLAY_PRIMS: usize = if usize::BITS >= 64 { MAX_DISPLAY_POINTS } else { 1 << 24 }; + +// A vector holding the most primitives (or points) a list may hold can still double without +// passing `isize::MAX` bytes, the most one allocation can take; the wasm build checks this for +// 32-bit memory. +const _: () = assert!(MAX_DISPLAY_PRIMS <= isize::MAX as usize / 2 / std::mem::size_of::()); +const _: () = assert!(MAX_DISPLAY_POINTS <= isize::MAX as usize / 2 / std::mem::size_of::()); +const _: () = assert!(MAX_DISPLAY_PRIMS <= isize::MAX as usize / 2 / std::mem::size_of::()); +// Plotted text and images hold at most one entry per primitive and grow one push at a time, so by +// doubling from a power of two: the most they reach is the power of two at or above the limit. +const _: () = assert!(MAX_DISPLAY_PRIMS.next_power_of_two() <= isize::MAX as usize / std::mem::size_of::()); +const _: () = assert!(MAX_DISPLAY_PRIMS.next_power_of_two() <= isize::MAX as usize / std::mem::size_of::()); + /// Upper bound on the dash pattern elements one dashed run (a line, an arc, a polyline segment or /// a PLINEGEN polyline) is laid out over: a longer pattern repeated more often is drawn /// continuous, and [`DisplayList::undashed`] counts it. A plot keeps the dashes of a run of any @@ -299,6 +347,13 @@ impl<'a> Builder<'a> { len, }); } + /// The triangles of the even-odd region bounded by `loops` ([`fill::triangulate_evenodd`]), + /// marking the list truncated when a cap left part of the region out of them (#3636). + fn region_tris(&mut self, loops: &[Vec]) -> Vec { + let (tris, whole) = fill::triangulate_evenodd_whole(loops); + self.list.truncated |= !whole; + tris + } /// Shaped text: strokes as polylines; TrueType glyphs filled (TEXTFILL) or outlined. fn shaped(&mut self, ctx: &Ctx, color: Ink, lw: f32, sh: &cadcraft_fonts::Shaped) { for s in &sh.strokes { @@ -406,9 +461,12 @@ impl<'a> Builder<'a> { transparency: self.transparency, points: self.points, max_points: self.max_points, + prims: self.prims, + max_prims: self.max_prims, dashes: self.dashes, max_dashes: self.max_dashes, loops: self.loops, + fade: self.fade, } } /// Whether block `to` leads back to block `from` in `d`, the drawing being built (see @@ -417,10 +475,11 @@ impl<'a> Builder<'a> { loops::leads_back(d, self.loops, from, to) } /// Take one unit of the block-expansion budget; false once it is spent, or once the build - /// holds all the points it may ([`MAX_DISPLAY_POINTS`]), so block copies stop being visited. + /// holds all the points ([`MAX_DISPLAY_POINTS`]) or primitives ([`MAX_DISPLAY_PRIMS`]) it may, + /// so block copies stop being visited. fn expand(&mut self) -> bool { self.list.expanded = self.list.expanded.saturating_add(1); - let ok = !self.points_spent() + let ok = !self.spent() && match self.shared_budget { Some(spent) => spent.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < MAX_BLOCK_EXPANSION, None => self.list.expanded <= MAX_BLOCK_EXPANSION, @@ -430,22 +489,63 @@ impl<'a> Builder<'a> { } ok } - /// Whether the build holds all the points it may: nothing more is drawn. - fn points_spent(&self) -> bool { - self.points.load(std::sync::atomic::Ordering::Relaxed) >= self.max_points + /// Whether the build holds all the points or all the primitives it may: nothing more is drawn. + fn spent(&self) -> bool { + use std::sync::atomic::Ordering::Relaxed; + self.points.load(Relaxed) >= self.max_points || (self.counts_prims() && self.prims.load(Relaxed) >= self.max_prims) } - /// Charge `n` points to the build's [`MAX_DISPLAY_POINTS`] budget before they are pushed; - /// false (and the list marked truncated) when they don't fit, and nothing is pushed. Once the - /// budget is spent nothing more is added to the count, so it stays within the limit plus one - /// primitive per thread building in parallel. + /// Whether the primitive budget can bind. Every primitive is charged at least one point, so a + /// primitive limit at or above the point limit (64-bit targets) never does and isn't counted. + fn counts_prims(&self) -> bool { + self.max_prims < self.max_points + } + /// Spend the build: nothing more is drawn, as when a budget runs out. For a list without room + /// for what is appended to it (see [`Limits`]), so the objects left are not worked out only to + /// be refused. + fn spend(&mut self) { + self.points.fetch_max(self.max_points, std::sync::atomic::Ordering::Relaxed); + self.list.truncated = true; + } + /// Charge one primitive of `n` points to the build's budgets ([`MAX_DISPLAY_POINTS`] and + /// [`MAX_DISPLAY_PRIMS`]) before it is pushed; false (and the list marked truncated) when it + /// doesn't fit, and nothing is pushed. Once a budget is spent nothing more is added to the + /// counts, so they stay within their limits plus one primitive per thread building in parallel. + /// The list itself must have room too: clipped copies appended to it are not in the counts. A + /// list without room spends the build. fn charge(&mut self, n: usize) -> bool { use std::sync::atomic::Ordering::Relaxed; - let ok = !self.points_spent() && self.points.fetch_add(n, Relaxed).saturating_add(n) <= self.max_points; + if !self.spent() && !self.limits().room(&mut self.list, n) { + self.spend(); + } + let ok = !self.spent() + && self.points.fetch_add(n, Relaxed).saturating_add(n) <= self.max_points + && (!self.counts_prims() || self.prims.fetch_add(1, Relaxed) < self.max_prims); if !ok { self.list.truncated = true; } ok } + /// What one list of this build may hold, for the clipped copies appended to it. + fn limits(&self) -> Limits { + Limits { points: self.max_points, prims: self.max_prims } + } + /// Join the parts of a list built on all cores to this builder's list, in drawing order and + /// within its limits ([`Limits`]): the clipped copies a part holds are in no count, so the + /// parts can hold more together than one list may. At the first part that doesn't fit the build + /// is spent and the parts left are not joined. + #[cfg(not(target_arch = "wasm32"))] + fn join(&mut self, parts: Vec) { + let points = |l: &DisplayList| l.verts.len().saturating_add(l.tris.len()); + for part in parts { + if self.list.prims.len().saturating_add(part.prims.len()) > self.max_prims + || points(&self.list).saturating_add(points(&part)) > self.max_points + { + self.spend(); + return; + } + display::append(&mut self.list, part); + } + } } /// The build's dash budget ([`MAX_DASH_ELEMENTS`]), charged as [`Builder::charge`] charges @@ -481,7 +581,10 @@ fn image_clip(i: &cadcraft_doc::Image, place: impl Fn(Vec2) -> Vec2) -> Option rgb, c => ink(c, Color::Index(7), ctx.block_color), }; - b.tris(ctx, c, &fill::triangulate_evenodd(&g.fill)); + let tris = b.region_tris(&g.fill); + b.tris(ctx, c, &tris); } let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12); // One look per element: colour, lineweight, linetype and its scale. diff --git a/crates/render/src/paper.rs b/crates/render/src/paper.rs index be0cd67c7..dbbd0471d 100644 --- a/crates/render/src/paper.rs +++ b/crates/render/src/paper.rs @@ -31,7 +31,11 @@ const fn inch(name: &'static str, aliases: &'static [&'static str], w: f64, h: f PaperSize { name, aliases, width_mm: w * 25.4, height_mm: h * 25.4, imperial: true } } -/// Common ISO (A0–A6, B0–B5) and ANSI/ARCH sheet sizes (ISO 216, ANSI/ASME Y14.1). +/// Common ISO (A0–A6, B0–B6), JIS (B4–B6), Japanese stationery and ANSI/ARCH sheet sizes +/// (ISO 216, JIS P 0138, ANSI/ASME Y14.1). +/// +/// The bare names `B4`/`B5`/`B6` are the ISO sizes (250×353, 176×250 and 125×176 mm); the JIS +/// sheets (257×364, 182×257 and 128×182 mm) need explicit names (`JIS B4`, `B4 (JIS)`…). pub const PAPER_SIZES: &[PaperSize] = &[ iso("ISO A0 (841.00 x 1189.00 MM)", &["A0", "ISO A0"], 841.0, 1189.0), iso("ISO A1 (594.00 x 841.00 MM)", &["A1", "ISO A1"], 594.0, 841.0), @@ -44,8 +48,22 @@ pub const PAPER_SIZES: &[PaperSize] = &[ iso("ISO B1 (707.00 x 1000.00 MM)", &["B1", "ISO B1"], 707.0, 1000.0), iso("ISO B2 (500.00 x 707.00 MM)", &["B2", "ISO B2"], 500.0, 707.0), iso("ISO B3 (353.00 x 500.00 MM)", &["B3", "ISO B3"], 353.0, 500.0), - iso("ISO B4 (250.00 x 353.00 MM)", &["B4", "ISO B4"], 250.0, 353.0), - iso("ISO B5 (176.00 x 250.00 MM)", &["B5", "ISO B5"], 176.0, 250.0), + iso("ISO B4 (250.00 x 353.00 MM)", &["B4", "ISO B4", "B4 (ISO)"], 250.0, 353.0), + iso("ISO B5 (176.00 x 250.00 MM)", &["B5", "ISO B5", "B5 (ISO)"], 176.0, 250.0), + iso("ISO B6 (125.00 x 176.00 MM)", &["B6", "ISO B6", "B6 (ISO)"], 125.0, 176.0), + // JIS B4–B6 (JIS P 0138): the sheets Japanese drafting and Excel call B4/B5/B6, a few + // millimetres larger than the ISO ones. Explicit names only, so the bare names stay ISO. + iso("JIS B4 (257.00 x 364.00 MM)", &["B4 (JIS)", "JIS B4"], 257.0, 364.0), + iso("JIS B5 (182.00 x 257.00 MM)", &["B5 (JIS)", "JIS B5"], 182.0, 257.0), + iso("JIS B6 (128.00 x 182.00 MM)", &["B6 (JIS)", "JIS B6"], 128.0, 182.0), + // Japanese stationery: postcards, the long (chou) and square (kaku) envelopes and 四六判, the + // 127×188 mm book/paper trade size. No bare `Postcard`: postcard sizes differ by country, so + // the name (and はがき) say which one is meant. + iso("Japanese Postcard (100.00 x 148.00 MM)", &["Japanese Postcard", "はがき"], 100.0, 148.0), + iso("Japanese Double Postcard (148.00 x 200.00 MM)", &["Japanese Double Postcard", "往復はがき"], 148.0, 200.0), + iso("Japanese Envelope #3 (120.00 x 235.00 MM)", &["Japanese Envelope #3", "Envelope #3", "長形3号"], 120.0, 235.0), + iso("Japanese Envelope Kaku #2 (240.00 x 332.00 MM)", &["Japanese Envelope Kaku #2", "Kaku #2", "角形2号"], 240.0, 332.0), + iso("Japanese Shirokuban (127.00 x 188.00 MM)", &["Shirokuban", "Yotsuro", "四六判"], 127.0, 188.0), inch("ANSI A (8.50 x 11.00 Inches)", &["ANSI A", "Letter", "A-size"], 8.5, 11.0), inch("Legal (8.50 x 14.00 Inches)", &["Legal"], 8.5, 14.0), inch("ANSI B (11.00 x 17.00 Inches)", &["ANSI B", "Tabloid", "Ledger", "B-size"], 11.0, 17.0), @@ -68,9 +86,22 @@ impl PaperSize { } } -/// Look up a paper size by canonical name or alias (case- and space-insensitive). +/// Look up a paper size by canonical name or alias (case-insensitive; spaces, underscores, hyphens +/// and parentheses are ignored, so `B5 (JIS)`, `b5-jis` and `b5jis` are one name). pub fn paper_size(name: &str) -> Option<&'static PaperSize> { - let norm = |s: &str| s.chars().filter(|c| !c.is_whitespace() && *c != '_' && *c != '-').collect::().to_ascii_lowercase(); + // Full-width forms are what a Japanese keyboard or IME produces (`B5 (JIS)`), so fold them + // to ASCII before the rest of the normalisation: U+FF01..U+FF5E are ASCII + 0xFEE0. + let norm = |s: &str| { + s.chars() + .map(|c| match c { + '\u{FF01}'..='\u{FF5E}' => char::from_u32(c as u32 - 0xFEE0).unwrap_or(c), + '\u{3000}' => ' ', + _ => c, + }) + .filter(|c| !c.is_whitespace() && !matches!(c, '_' | '-' | '(' | ')')) + .collect::() + .to_ascii_lowercase() + }; let n = norm(name); if n.is_empty() { return None; @@ -200,6 +231,73 @@ pub fn sheet(d: &Drawing, layout: &str) -> Option { mod tests { use super::*; + #[test] + fn jis_and_japanese_paper_sizes() { + // The bare names B4/B5/B6 are the ISO sizes, as they were before the JIS sheets arrived. + for (name, w, h) in [ + ("B4", 250.0, 353.0), + ("b4", 250.0, 353.0), + ("ISO B4", 250.0, 353.0), + ("B4 (ISO)", 250.0, 353.0), + ("B5", 176.0, 250.0), + ("b5-iso", 176.0, 250.0), + ("B6", 125.0, 176.0), + ("B6 (ISO)", 125.0, 176.0), + ] { + let p = paper_size(name).unwrap_or_else(|| panic!("{name}")); + assert_eq!((p.width_mm, p.height_mm), (w, h), "{name}"); + assert!(!p.imperial, "{name} is a metric sheet"); + } + assert_eq!(paper_size("B4").map(|p| p.name), Some("ISO B4 (250.00 x 353.00 MM)")); + assert_eq!(paper_size("B6").map(|p| p.name), Some("ISO B6 (125.00 x 176.00 MM)")); + // The JIS sizes (JIS P 0138) are reachable by their explicit names only. + for (name, w, h) in [ + ("B4 (JIS)", 257.0, 364.0), + ("b4-jis", 257.0, 364.0), + ("JIS B4", 257.0, 364.0), + ("B5 (JIS)", 182.0, 257.0), + ("b5 (jis)", 182.0, 257.0), + ("JIS B5", 182.0, 257.0), + ("B6 (JIS)", 128.0, 182.0), + ("b6jis", 128.0, 182.0), + ("JIS B6", 128.0, 182.0), + ] { + let p = paper_size(name).unwrap_or_else(|| panic!("{name}")); + assert_eq!((p.width_mm, p.height_mm), (w, h), "{name}"); + assert!(!p.imperial, "{name} is a metric sheet"); + } + assert_eq!(paper_size("JIS B5").map(|p| p.name), Some("JIS B5 (182.00 x 257.00 MM)")); + // A page setup stores the canonical name; the ISO and JIS names both keep resolving, so a + // drawing keeps the sheet it stored. + for name in ["ISO B4 (250.00 x 353.00 MM)", "JIS B4 (257.00 x 364.00 MM)"] { + assert_eq!(paper_size(name).map(|p| p.name), Some(name), "{name}"); + } + // Japanese postcards, envelopes and 四六判. + for (name, w, h) in [ + ("Japanese Postcard", 100.0, 148.0), + ("はがき", 100.0, 148.0), + ("Japanese Double Postcard", 148.0, 200.0), + ("往復はがき", 148.0, 200.0), + ("Japanese Envelope #3", 120.0, 235.0), + ("長形3号", 120.0, 235.0), + ("Japanese Envelope Kaku #2", 240.0, 332.0), + ("kaku #2", 240.0, 332.0), + ("角形2号", 240.0, 332.0), + ("Shirokuban", 127.0, 188.0), + ("四六判", 127.0, 188.0), + ] { + let p = paper_size(name).unwrap_or_else(|| panic!("{name}")); + assert_eq!((p.width_mm, p.height_mm), (w, h), "{name}"); + } + // The bare postcard aliases are ambiguous and gone. + assert!(paper_size("Postcard").is_none()); + assert!(paper_size("Double Postcard").is_none()); + // A6 was already an ISO sheet. + assert_eq!(paper_size("A6").map(|p| (p.width_mm, p.height_mm)), Some((105.0, 148.0))); + // Unknown names still fail. + assert!(paper_size("Z9").is_none()); + } + #[test] fn metric_length_unit_reads_the_length_unit() { // Metric units, whatever MEASUREMENT says. @@ -346,3 +444,22 @@ pub fn saved_plot(page: &PageSetup) -> SavedPlot { let scale = Some(page.scale).filter(|s| !page.scale_to_fit && s.is_finite() && *s > 0.0 && (*s - 1.0).abs() > 1e-9); SavedPlot { window, fit, scale, center: page.center } } + +#[cfg(test)] +mod wide_name_tests { + use super::*; + + /// A name typed on a Japanese keyboard arrives in full-width forms (`B5 (JIS)`); it must + /// resolve to the same sheet as `B5 (JIS)`. + #[test] + fn full_width_names_resolve_like_their_ascii_forms() { + for (wide, ascii) in [("B5 (JIS)", "B5 (JIS)"), ("A4", "A4"), ("B4", "B4")] { + let w = paper_size(wide).unwrap_or_else(|| panic!("{wide}")); + let a = paper_size(ascii).unwrap_or_else(|| panic!("{ascii}")); + assert_eq!(w.name, a.name, "{wide} vs {ascii}"); + } + // The Japanese spellings still work, and the ideographic space is a separator. + assert_eq!(paper_size("はがき").map(|p| p.name), paper_size("Japanese Postcard").map(|p| p.name)); + assert_eq!(paper_size(" B5 ").map(|p| p.name), Some(paper_size("B5").unwrap().name)); + } +} diff --git a/crates/render/src/pen.rs b/crates/render/src/pen.rs index f3b83af1b..c33fff3c9 100644 --- a/crates/render/src/pen.rs +++ b/crates/render/src/pen.rs @@ -13,11 +13,14 @@ //! The patterns are CADCraft's own definitions, measured in millimetres on paper and anchored to //! the paper origin. Layouts apply them while building (paper units are known); a model-space //! plot applies them once its plot scale is known. +//! +//! This geometry is made after the build, outside its budgets, so the list stops at the build's +//! point limit, [`MAX_DISPLAY_POINTS`] (see [`apply`]). use cadcraft_doc::{EndStyle, FillStyle, JoinStyle}; use cadcraft_geom::Vec2; -use crate::{DisplayList, Kind}; +use crate::{DisplayList, Kind, MAX_DISPLAY_POINTS}; /// End, join and fill style a primitive prints with (all "use object" when no plot style table /// is applied). @@ -68,7 +71,19 @@ const ROUND_STEPS: usize = 12; /// millimetres on paper. Lines with end or join styles become filled outlines and patterned /// fills become the pattern's pieces. Each primitive stays one primitive (same order, handle and /// colour) and the pens are used up, so applying twice changes nothing. +/// +/// The build's budgets don't count this geometry, and a 2-point line with round ends becomes 78 +/// triangle corners, so the list holds at most [`MAX_DISPLAY_POINTS`] points: from the first +/// primitive whose geometry doesn't fit, the primitives left keep their plain line or solid fill +/// and the list is marked truncated. Without the limit a wide-line plot style on a list near the +/// budget made more points than the web build can allocate (#1603). pub fn apply(list: &mut DisplayList, mm_per_unit: f64) { + apply_within(list, mm_per_unit, MAX_DISPLAY_POINTS); +} + +/// [`apply`] with the list holding at most `max_points` points (polyline vertices and triangle +/// corners): the build's own limit, less in tests. +pub(crate) fn apply_within(list: &mut DisplayList, mm_per_unit: f64, max_points: usize) { let pens = std::mem::take(&mut list.pens); if !(mm_per_unit.is_finite() && mm_per_unit > 0.0) { return; @@ -76,15 +91,23 @@ pub fn apply(list: &mut DisplayList, mm_per_unit: f64) { let mut budget = MAX_PATTERN_CELLS; for (i, pen) in pens.iter().enumerate() { let Some(p) = list.prims.get(i).copied() else { break }; + let room = max_points.saturating_sub(list.verts.len().saturating_add(list.tris.len())); let out = match p.kind { Kind::Polyline if pen.shapes_lines() && p.lw > WIDE_MM => { let hw = f64::from(p.lw) / 2.0 / mm_per_unit; - Some(stroke(list.points(&p), hw, pen.end, pen.join)) + stroke_within(list.points(&p), hw, pen.end, pen.join, room) } - Kind::Tris if pen.patterned() => pattern(list.points(&p), pen.fill, PATTERN_MM / mm_per_unit, &mut budget), - _ => None, + Kind::Tris if pen.patterned() => { + let Some(out) = pattern_within(list.points(&p), pen.fill, PATTERN_MM / mm_per_unit, &mut budget, room) else { continue }; + out + } + _ => continue, }; - let Some(tris) = out else { continue }; + if out.full { + list.truncated = true; + break; + } + let tris = out.pts; let (Ok(start), Ok(len)) = (u32::try_from(list.tris.len()), u32::try_from(tris.len())) else { continue }; if start.checked_add(len).is_none() { continue; @@ -98,22 +121,38 @@ pub fn apply(list: &mut DisplayList, mm_per_unit: f64) { } } +/// Triangle corners being made, at most `max` of them: a triangle past it is left out and `full` +/// set, and the caller keeps the primitive as it was. +struct Out { + pts: Vec, + max: usize, + full: bool, +} + +impl Out { + fn within(max: usize) -> Out { + Out { pts: Vec::new(), max, full: false } + } +} + /// Push triangle `a b c` counter-clockwise (so overlapping pieces fill as a union under the /// non-zero rule); degenerate ones are dropped. -fn tri(out: &mut Vec, a: Vec2, b: Vec2, c: Vec2) { +fn tri(out: &mut Out, a: Vec2, b: Vec2, c: Vec2) { let area = (b - a).cross(c - a); if !area.is_finite() || area.abs() <= 1e-300 { return; } - if area > 0.0 { - out.extend_from_slice(&[a, b, c]); + if out.pts.len().saturating_add(3) > out.max { + out.full = true; + } else if area > 0.0 { + out.pts.extend_from_slice(&[a, b, c]); } else { - out.extend_from_slice(&[a, c, b]); + out.pts.extend_from_slice(&[a, c, b]); } } /// Fan of the arc around `c` from `from` to `to` (radius `r`), turning the short way. -fn round_fan(out: &mut Vec, c: Vec2, r: f64, from: Vec2, to: Vec2) { +fn round_fan(out: &mut Out, c: Vec2, r: f64, from: Vec2, to: Vec2) { let a0 = from.y.atan2(from.x); let mut sweep = to.y.atan2(to.x) - a0; while sweep > std::f64::consts::PI { @@ -135,7 +174,12 @@ fn round_fan(out: &mut Vec, c: Vec2, r: f64, from: Vec2, to: Vec2) { /// corners ("use object" = round). A polyline whose last point is its first is closed: joins all /// round, no ends. pub fn stroke(pts: &[Vec2], hw: f64, end: EndStyle, join: JoinStyle) -> Vec { - let mut out = Vec::new(); + stroke_within(pts, hw, end, join, usize::MAX).pts +} + +/// [`stroke`], making at most `max` triangle corners (see [`Out`]). +fn stroke_within(pts: &[Vec2], hw: f64, end: EndStyle, join: JoinStyle, max: usize) -> Out { + let mut out = Out::within(max); if !(hw.is_finite() && hw > 0.0) { return out; } @@ -180,7 +224,7 @@ pub fn stroke(pts: &[Vec2], hw: f64, end: EndStyle, join: JoinStyle) -> Vec, p: Vec2, out_dir: Vec2, hw: f64, end: EndStyle) { +fn cap(out: &mut Out, p: Vec2, out_dir: Vec2, hw: f64, end: EndStyle) { let n = out_dir.perp() * hw; match end { EndStyle::Butt => {} @@ -195,7 +239,7 @@ fn cap(out: &mut Vec, p: Vec2, out_dir: Vec2, hw: f64, end: EndStyle) { } /// The corner at `c` between a segment arriving in direction `d0` and one leaving in `d1`. -fn corner(out: &mut Vec, c: Vec2, d0: Vec2, d1: Vec2, hw: f64, join: JoinStyle) { +fn corner(out: &mut Out, c: Vec2, d0: Vec2, d1: Vec2, hw: f64, join: JoinStyle) { let turn = d0.cross(d1); if turn.abs() <= 1e-12 && d0.dot(d1) > 0.0 { return; // straight on @@ -284,11 +328,17 @@ fn band_range(t: &[Vec2; 3], axis: Vec2, pitch: f64) -> Option<(f64, f64)> { /// The pieces of the triangles `tris` covered by `fill`'s pattern at repeat distance `pitch`, or /// `None` (draw solid) when the pattern would take more than the remaining `budget` of cells. pub fn pattern(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize) -> Option> { + pattern_within(tris, fill, pitch, budget, usize::MAX).map(|out| out.pts) +} + +/// [`pattern`], making at most `max` triangle corners (see [`Out`]). Once a triangle doesn't fit, +/// it stops with `full` set, before a later triangle can run out of cells and return `None`. +fn pattern_within(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize, max: usize) -> Option { if !(pitch.is_finite() && pitch > 0.0) { return None; } let families = grids(fill, pitch); - let mut out = Vec::new(); + let mut out = Out::within(max); for t in tris.as_chunks::<3>().0 { if t.iter().any(|p| !p.is_finite()) { continue; @@ -296,6 +346,11 @@ pub fn pattern(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize) - let [a, b, c] = *t; let base: Vec = if (b - a).cross(c - a) >= 0.0 { vec![a, b, c] } else { vec![a, c, b] }; for g in &families { + // Past the point limit: say so now. Running out of cells later would keep the fill + // solid without marking the list, and applying would go on. + if out.full { + return Some(out); + } let (i0, i1) = band_range(t, g.a, g.pitch)?; let (j0, j1) = match g.b { Some(axis) => band_range(t, axis, g.pitch)?, @@ -333,7 +388,7 @@ pub fn pattern(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize) - } /// Triangle fan of a convex polygon. -fn fan(out: &mut Vec, poly: &[Vec2]) { +fn fan(out: &mut Out, poly: &[Vec2]) { let Some(first) = poly.first().copied() else { return }; for w in poly.get(1..).unwrap_or(&[]).windows(2) { if let [b, c] = w { @@ -372,4 +427,96 @@ mod tests { assert!(pattern(&big, FillStyle::Checkerboard, f64::NAN, &mut budget).is_none()); assert!(stroke(&[Vec2::new(f64::NAN, 0.0)], 1.0, EndStyle::Round, JoinStyle::Round).is_empty()); } + + /// Three 10-unit lines and a filled triangle 0.5 mm wide at 1 mm per unit, printed with `pens`. + fn styled(pens: [Pen; 4]) -> DisplayList { + let prim = |kind, start, len| crate::DPrim { + handle: cadcraft_doc::Handle(1), + color: cadcraft_color::Rgb(255, 0, 0), + aci7: false, + lw: 0.5, + transparency: 0, + kind, + start, + len, + }; + DisplayList { + verts: (0..3).flat_map(|k| [Vec2::new(0.0, 5.0 * f64::from(k)), Vec2::new(10.0, 5.0 * f64::from(k))]).collect(), + tris: vec![Vec2::new(0.0, 20.0), Vec2::new(10.0, 20.0), Vec2::new(0.0, 30.0)], + prims: vec![prim(Kind::Polyline, 0, 2), prim(Kind::Polyline, 2, 2), prim(Kind::Polyline, 4, 2), prim(Kind::Tris, 0, 3)], + pens: pens.to_vec(), + ..Default::default() + } + } + + #[test] + fn styled_geometry_stops_at_the_lists_point_limit_and_says_so() { + // Made after the build, outside its budgets: a 2-point line with round ends becomes 78 + // triangle corners, so a list near the point budget passed it (#1603). + let points = |l: &DisplayList| l.verts.len() + l.tris.len(); + let round = Pen { end: EndStyle::Round, ..Pen::default() }; + let butt = Pen { end: EndStyle::Butt, ..Pen::default() }; + let built = styled([round, round, butt, Pen::default()]); + let mut all = built.clone(); + apply_within(&mut all, 1.0, usize::MAX); + assert!(all.prims.iter().all(|p| p.kind == Kind::Tris) && all.prims[..3] != built.prims[..3] && !all.truncated); + let first = all.points(&all.prims[0]).len(); + let last = all.points(&all.prims[2]).len(); + assert!(last < first, "the butt-ended line is the smaller outline"); + // Room for the first round-ended outline, and then none, or enough for the butt-ended third + // line's outline only: the second doesn't fit, so it and every primitive after it, the + // third included, keep their plain line. + for extra in [0, last] { + let max = points(&built) + first + extra; + let mut cut = built.clone(); + apply_within(&mut cut, 1.0, max); + assert!(cut.truncated && points(&cut) <= max, "{extra}: {} points", points(&cut)); + assert_eq!(cut.prims[0], all.prims[0], "{extra}: the outline that fits is drawn"); + assert_eq!(cut.prims[1..], built.prims[1..], "{extra}"); + assert!(cut.pens.is_empty(), "{extra}: the pens are used up"); + } + // A fill pattern without room stays a solid fill. + let checker = Pen { fill: FillStyle::Checkerboard, ..Pen::default() }; + let built = styled([Pen::default(), Pen::default(), Pen::default(), checker]); + let mut all = built.clone(); + apply_within(&mut all, 1.0, usize::MAX); + assert!(points(&all) > points(&built) + 3 && all.prims[3] != built.prims[3] && !all.truncated); + let mut cut = built.clone(); + apply_within(&mut cut, 1.0, points(&built) + 3); + assert!(cut.truncated && cut.prims == built.prims && points(&cut) == points(&built)); + } + + #[test] + fn a_fill_past_the_point_limit_says_so_though_a_later_triangle_runs_out_of_cells() { + // A fill whose pattern passes the point limit on one triangle is refused for that: the + // list is marked and applying stops, even when a later triangle would take more pattern + // cells than are left. So the butt-ended line after it keeps its plain line, though its + // outline would fit. + let points = |l: &DisplayList| l.verts.len() + l.tris.len(); + let butt = Pen { end: EndStyle::Butt, ..Pen::default() }; + let checker = Pen { fill: FillStyle::Checkerboard, ..Pen::default() }; + let mut lines = styled([Pen::default(), Pen::default(), butt, Pen::default()]); + apply_within(&mut lines, 1.0, usize::MAX); + let outline = lines.points(&lines.prims[2]).len(); + // The fill moved before the third line, with a second triangle far too large to pattern. + let mut built = styled([Pen::default(), Pen::default(), checker, butt]); + built.prims.swap(2, 3); + built.tris.extend([Vec2::new(0.0, 0.0), Vec2::new(1e9, 0.0), Vec2::new(0.0, 1e9)]); + built.prims[2].len = 6; + let mut cells = MAX_PATTERN_CELLS; + assert!(pattern(&built.tris[..3], FillStyle::Checkerboard, PATTERN_MM, &mut cells).is_some_and(|p| p.len() > outline)); + assert!(pattern(&built.tris[3..], FillStyle::Checkerboard, PATTERN_MM, &mut cells).is_none()); + let max = points(&built) + outline; + let mut cut = built.clone(); + apply_within(&mut cut, 1.0, max); + assert!(cut.truncated, "the fill past the limit marks the list"); + assert_eq!(cut.prims, built.prims, "the fill stays solid and the line after it plain"); + assert!(points(&cut) == points(&built) && cut.pens.is_empty()); + // The cells running out first keeps the fill solid without marking the list, as before, + // and the line after it is drawn with its ends. + let mut first = built.clone(); + first.tris.rotate_left(3); + apply_within(&mut first, 1.0, max); + assert!(!first.truncated && first.prims[2] == built.prims[2] && first.prims[3].kind == Kind::Tris); + } } diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 08e07053a..a1334a049 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -1,11 +1,9 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::display::append; use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT}; use super::draw::entity; use super::viewports::{MAX_VIEWPORTS, viewport}; use super::{ - Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, - pen, plotstyle, point, + Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Fade, Handle, Lineweight, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, + Mat3, Space, Vec2, paper, pen, plotstyle, point, }; /// Build options. @@ -98,6 +96,7 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St depth: 0, top, frozen, + selecting: false, vp_colors, lt_factor: 1.0, block_pstyle: None, @@ -107,16 +106,26 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St } fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> DisplayList { - build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS) + build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS) } -/// [`build_space`] holding at most `max_points` points and laying out at most `max_dashes` dash -/// pattern elements. -pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plotting: bool, max_points: usize, max_dashes: usize) -> DisplayList { +/// [`build_space`] holding at most `max_points` points and `max_prims` primitives, and laying out +/// at most `max_dashes` dash pattern elements. +pub(crate) fn build_space_within( + d: &Drawing, + space: &Space, + opts: &Options, + plotting: bool, + max_points: usize, + max_prims: usize, + max_dashes: usize, +) -> DisplayList { let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t)); - let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); + let (points, prims, dashes) = + (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); let loops = std::sync::OnceLock::new(); + let fade = Fade::of(d); let mut b = Builder { list: DisplayList::default(), opts, @@ -127,9 +136,12 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo transparency: 0, points: &points, max_points, + prims: &prims, + max_prims, dashes: &dashes, max_dashes, loops: &loops, + fade: fade.as_ref(), }; if let Space::Paper(name) = space { b.list.sheet = paper::sheet(d, name); @@ -158,7 +170,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo } // A layout is drawn in paper units, so its pens become geometry now. if let Some(sheet) = b.list.sheet { - pen::apply(&mut b.list, sheet.unit_mm); + pen::apply_within(&mut b.list, sheet.unit_mm, b.max_points); } b.list } @@ -177,8 +189,8 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor use rayon::prelude::*; let ents: Vec<&std::sync::Arc> = store.iter().collect(); let budget = std::sync::atomic::AtomicUsize::new(0); - let (opts, plotting, points, max_points, dashes, max_dashes, loops) = - (b.opts, b.plotting, b.points, b.max_points, b.dashes, b.max_dashes, b.loops); + let (opts, plotting, points, max_points, prims, max_prims, dashes, max_dashes, loops, fade) = + (b.opts, b.plotting, b.points, b.max_points, b.prims, b.max_prims, b.dashes, b.max_dashes, b.loops, b.fade); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { @@ -192,9 +204,12 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor transparency: 0, points, max_points, + prims, + max_prims, dashes, max_dashes, loops, + fade, }; for e in chunk { entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); @@ -202,13 +217,11 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor part.list }) .collect(); - // One allocation per array for the joined list. - b.list.prims.reserve(parts.iter().map(|p| p.prims.len()).sum()); - b.list.verts.reserve(parts.iter().map(|p| p.verts.len()).sum()); - b.list.tris.reserve(parts.iter().map(|p| p.tris.len()).sum()); - for part in parts { - append(&mut b.list, part); - } + // One allocation per array for the joined list, within what it may hold. + b.list.prims.reserve(parts.iter().map(|p| p.prims.len()).sum::().min(b.max_prims)); + b.list.verts.reserve(parts.iter().map(|p| p.verts.len()).sum::().min(b.max_points)); + b.list.tris.reserve(parts.iter().map(|p| p.tris.len()).sum::().min(b.max_points)); + b.join(parts); } /// The plot style table a build draws with: the one in `opts`, else (on screen) the layout's @@ -238,6 +251,17 @@ pub(crate) fn with_point_view(d: &Drawing, space: &Space, opts: &Options) -> Opt /// Build the display list for a set of loose entities (previews, rubber bands). pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: I, opts: &Options) -> DisplayList { + build_entities_in_viewport(d, ents, opts, &[]) +} + +/// [`build_entities`] as a selection through a layout viewport that freezes the layers in +/// `frozen` sees them: what is on one of those layers is left out, as the viewport does not draw +/// it, the parts of a block reference too. Only a point on the layer Defpoints that is a part of +/// a block is kept, as the definition points of a dimension are in its block: a selection counts +/// it whatever the viewport freezes ([`cadcraft_doc::point_on_defpoints`]). Picking through the +/// viewport tests objects against this, so a part the viewport does not draw is not hit, and the +/// highlight of an object seen through the viewport is built from it. +pub fn build_entities_in_viewport<'a, I: IntoIterator>(d: &Drawing, ents: I, opts: &Options, frozen: &[String]) -> DisplayList { let ents: Vec<&Entity> = ents.into_iter().collect(); // Only previews holding points need the model extents for relative point sizes. let with_view; @@ -247,8 +271,10 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: } else { opts }; - let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); + let (points, prims, dashes) = + (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); let loops = std::sync::OnceLock::new(); + let fade = Fade::of(d); let mut b = Builder { list: DisplayList::default(), opts, @@ -259,12 +285,15 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: transparency: 0, points: &points, max_points: MAX_DISPLAY_POINTS, + prims: &prims, + max_prims: MAX_DISPLAY_PRIMS, dashes: &dashes, max_dashes: MAX_DASH_ELEMENTS, loops: &loops, + fade: fade.as_ref(), }; for e in ents { - entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); + entity(&mut b, &Ctx { selecting: true, ..top_ctx(d, Mat3::IDENTITY, e.handle, frozen, &[]) }, e); } b.list } diff --git a/crates/render/src/props.rs b/crates/render/src/props.rs index 651dc2bc5..00eb795d1 100644 --- a/crates/render/src/props.rs +++ b/crates/render/src/props.rs @@ -6,17 +6,25 @@ use super::{Color, Ctx, Drawing, Entity, Ink, Lineweight, ink}; type Resolved = (Ink, f32, Option, f64, bool, u8, u8); pub(crate) fn resolve(ctx: &Ctx, e: &Entity, plotting: bool) -> Resolved { - resolve_common(ctx, &e.common, plotting) + // A selection through a viewport counts a point on Defpoints inside a block whatever the + // viewport freezes. + let kept = ctx.selecting && ctx.depth > 0 && cadcraft_doc::point_on_defpoints(e); + resolve_in(ctx, &e.common, plotting, if kept { &[] } else { ctx.frozen }) } /// [`resolve`] for an object's properties `c`. pub(crate) fn resolve_common(ctx: &Ctx, c: &cadcraft_doc::Common, plotting: bool) -> Resolved { + resolve_in(ctx, c, plotting, ctx.frozen) +} + +/// [`resolve_common`] with `frozen` as the layers the viewport leaves out. +fn resolve_in(ctx: &Ctx, c: &cadcraft_doc::Common, plotting: bool, frozen: &[String]) -> Resolved { let d = ctx.d; // Layer "0" inside a block takes the insert's layer. let layer_name = if c.layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { c.layer.as_str() }; let layer = d.layer(layer_name); let visible = - c.visible && layer.is_none_or(|l| l.visible() && (!plotting || l.plot)) && !ctx.frozen.iter().any(|f| f.eq_ignore_ascii_case(layer_name)); + c.visible && layer.is_none_or(|l| l.visible() && (!plotting || l.plot)) && !frozen.iter().any(|f| f.eq_ignore_ascii_case(layer_name)); let layer_color = ctx.layer_color(layer_name).unwrap_or(Color::Index(7)); let rgb = ink(c.color, layer_color, ctx.block_color); let lw = match c.lineweight { diff --git a/crates/render/src/table.rs b/crates/render/src/table.rs index 146918d04..c45c85d6d 100644 --- a/crates/render/src/table.rs +++ b/crates/render/src/table.rs @@ -38,6 +38,8 @@ pub struct TableText { /// MTEXT attachment (1 top left … 9 bottom right). pub attach: u8, pub height: f64, + /// Available horizontal text wrap width inside the cell (0 disables wrapping). + pub wrap_width: f64, pub color: Color, pub style: String, pub text: String, @@ -94,7 +96,7 @@ fn coverage(t: &Table) -> Result>, Vec>> { /// The table style a table uses (Standard defaults when missing). pub fn table_style_of(d: &Drawing, t: &Table) -> TableStyle { - d.table_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&t.style)).cloned().unwrap_or_default() + d.table_styles.by_name(&t.style).cloned().unwrap_or_default() } /// The scale of a table relative to its style: SCALE changes the table's text height, and every @@ -363,12 +365,17 @@ fn layout(d: &Drawing, t: &Table) -> TableGeom { 1 => (y0 + y1) / 2.0, _ => y1 - cs.margin_v, }; + // Why: wrap cell text inside the cell's horizontal bounds (excluding margins) so long lines + // do not spill into adjacent columns; clamp non-finite or narrow spans to 0 (no wrap). + let inner_w = x1 - x0 - 2.0 * cs.margin_h; + let wrap_width = if inner_w.is_finite() && inner_w > 0.0 { inner_w } else { 0.0 }; g.texts.push(TableText { row: a.row, col: a.col, at: p(x, y), attach, height: cell.text_height.filter(|h| h.is_finite() && *h > 0.0).map_or(cs.text_height, |h| h * k), + wrap_width, color: cs.text_color, style: cs.text_style.clone(), text: cell.text.clone(), @@ -385,6 +392,28 @@ fn style_ink(c: Color, table: Ink) -> Ink { } } +/// Resolve the [`cadcraft_fonts::MTextParams`] the renderer uses for a table cell's text style, +/// alignment point, text height, attachment, and horizontal wrap width. +pub fn table_text_mtext_params(d: &Drawing, style: &str, at: Vec2, height: f64, attach: u8, wrap_width: f64) -> cadcraft_fonts::MTextParams { + let ts = crate::text_style(d, style); + let font = crate::style_font(&ts); + cadcraft_fonts::MTextParams { + attach, + width: wrap_width, + font, + width_factor: ts.width_factor, + oblique: ts.oblique, + ..cadcraft_fonts::MTextParams::new(at, height) + } +} + +/// Lay out a [`TableText`] with the exact resolved text style, font, width factor, and oblique +/// angle used when drawing the table. +pub fn layout_table_text(d: &Drawing, tx: &TableText) -> cadcraft_fonts::MTextLayout { + let mp = table_text_mtext_params(d, &tx.style, tx.at, tx.height, tx.attach, tx.wrap_width); + cadcraft_fonts::layout_mtext_with(&tx.text, &mp) +} + /// Draw a table into the display list. pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) { let g = table_geometry(ctx.d, t); @@ -406,18 +435,9 @@ pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) { return; } for tx in &g.texts { - let ts = crate::text_style(ctx.d, &tx.style); - let font = crate::style_font(&ts); // Cell content is MTEXT (`\P`, `{\Q15;…}`, `\F…;`): laid out as such, at the cell's // alignment point (its numbering is MTEXT's attachment). - let mp = cadcraft_fonts::MTextParams { - attach: tx.attach, - font, - width_factor: ts.width_factor, - oblique: ts.oblique, - ..cadcraft_fonts::MTextParams::new(tx.at, tx.height) - }; - let layout = cadcraft_fonts::layout_mtext_with(&tx.text, &mp); + let layout = layout_table_text(ctx.d, tx); for piece in &layout.pieces { b.shaped(ctx, style_ink(tx.color, rgb), lw, &piece.shaped); } @@ -458,4 +478,77 @@ mod budget_tests { let part = part_table(&t, &rows, Vec2::ZERO); assert_eq!(part.cells[0][0].merged, Some((99, 1))); } + + #[test] + fn cell_text_wraps_within_column_and_merged_bounds() { + let mut d = Drawing::default(); + let long_text = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu"; + let t = Table { + col_widths: vec![30.0, 20.0], + row_heights: vec![40.0, 40.0], + text_height: 2.5, + cells: vec![ + vec![TableCell { text: long_text.into(), ..Default::default() }, TableCell { text: "B".into(), ..Default::default() }], + vec![TableCell { text: long_text.into(), merged: Some((1, 2)), ..Default::default() }, TableCell::default()], + ], + ..Default::default() + }; + let g = table_geometry(&d, &t); + assert!(g.texts[0].wrap_width > 0.0 && g.texts[0].wrap_width < 30.0); + // Merged cell spans both columns (50.0 total), so its wrap width exceeds a single column. + assert!(g.texts[2].wrap_width > g.texts[0].wrap_width); + + // Render via `crate::build` and verify all stroke vertices of cell (0,0) stay inside column 0 [0, 30]. + d.model.push(cadcraft_doc::Entity::new( + cadcraft_doc::Handle(1), + cadcraft_doc::EntityKind::Table(Table { + col_widths: vec![30.0, 20.0], + row_heights: vec![40.0], + text_height: 2.5, + cells: vec![vec![TableCell { text: long_text.into(), ..Default::default() }, TableCell::default()]], + ..Default::default() + }), + )); + let list = crate::build(&d, &cadcraft_doc::Space::Model, &crate::Options::default()); + assert!(!list.verts.is_empty()); + for p in &list.verts { + assert!(p.x >= -1e-6 && p.x <= 50.0 + 1e-6, "vertex outside table: {p:?}"); + } + // Verify layout_mtext_with at tx.wrap_width wraps into multiple lines and stays inside column 0 [0, 30]. + let mp = cadcraft_fonts::MTextParams { + attach: g.texts[0].attach, + width: g.texts[0].wrap_width, + ..cadcraft_fonts::MTextParams::new(g.texts[0].at, g.texts[0].height) + }; + let laid = cadcraft_fonts::layout_mtext_with(&g.texts[0].text, &mp); + assert!(laid.lines.len() > 1); + for s in &laid.strokes { + for p in s { + assert!(p.x >= -1e-6 && p.x <= 30.0 + 1e-6, "glyph spilled past column 0: {p:?}"); + } + } + } + + #[test] + fn narrow_or_non_finite_columns_and_escapes_do_not_panic() { + let mut d = Drawing::default(); + let t = Table { + col_widths: vec![0.1, f64::NAN, 40.0], + row_heights: vec![10.0], + cells: vec![vec![ + TableCell { text: "Narrow".into(), ..Default::default() }, + TableCell { text: "NaN".into(), ..Default::default() }, + TableCell { text: "Line1\\PLine2\\\\{brace}".into(), ..Default::default() }, + ]], + ..Default::default() + }; + let g = table_geometry(&d, &t); + assert_eq!(g.texts[0].wrap_width, 0.0); + assert_eq!(g.texts[1].wrap_width, 0.0); + assert!(g.texts[2].wrap_width > 0.0); + + d.model.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), cadcraft_doc::EntityKind::Table(t))); + let list = crate::build(&d, &cadcraft_doc::Space::Model, &crate::Options::default()); + assert!(!list.verts.is_empty()); + } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index b5cbbea06..423268990 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -39,6 +39,129 @@ fn linetype_dashes_line() { assert!(l.prims.len() > 10); } +/// Loose entities built as a layout viewport draws them leave out what is on a layer frozen in +/// it, the part of a block reference on that layer too, whatever the case of the layer's name. +/// With no such layer the list is the one [`build_entities`] gives. +#[test] +fn loose_entities_built_for_a_viewport_leave_out_its_frozen_layers() { + let line = |handle: u64, y: f64, layer: &str| { + let kind = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }); + let mut e = cadcraft_doc::Entity::new(Handle(handle), kind); + e.common.layer = layer.into(); + e + }; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let mut b = cadcraft_doc::Block::new("B"); + for part in [line(1, 0.0, "0"), line(2, 5.0, "Hidden")] { + b.entities.push(part); + } + d.blocks.insert("B".into(), std::sync::Arc::new(b)); + let reference = cadcraft_doc::Insert { block: "B".into(), ..Default::default() }; + let ents = [cadcraft_doc::Entity::new(Handle(3), EntityKind::Insert(reference)), line(4, 5.0, "Hidden"), line(5, 8.0, "0")]; + let ys = |l: &DisplayList| -> Vec { l.prims.iter().map(|p| l.points(p)[0].y).collect() }; + let opts = Options::default(); + let frozen = ["HIDDEN".to_string()]; + assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &frozen)), [0.0, 8.0]); + assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &[])), [0.0, 5.0, 5.0, 8.0]); + assert_eq!(ys(&build_entities(&d, &ents, &opts)), [0.0, 5.0, 5.0, 8.0]); +} + +/// A drawing with the layers Defpoints and "Hidden" and the block P: a line along y = 0 on layer +/// 0, a point at y = 5 and a line along y = 6 on Defpoints, and a line along y = 7 on "Hidden". +/// The block N holds a dimension that draws P ([`dimension_of_p`]). +fn drawing_with_p() -> Drawing { + let line = |handle: u64, y: f64, layer: &str| { + let kind = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }); + let mut e = cadcraft_doc::Entity::new(Handle(handle), kind); + e.common.layer = layer.into(); + e + }; + let mut point = cadcraft_doc::Entity::new(Handle(2), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 })); + point.common.layer = "Defpoints".into(); + let mut d = Drawing::new_metric(); + d.ensure_layer("Defpoints"); + d.ensure_layer("Hidden"); + let mut p = cadcraft_doc::Block::new("P"); + for part in [line(1, 0.0, "0"), point, line(3, 6.0, "Defpoints"), line(4, 7.0, "Hidden")] { + p.entities.push(part); + } + d.blocks.insert("P".into(), std::sync::Arc::new(p)); + let mut n = cadcraft_doc::Block::new("N"); + n.entities.push(cadcraft_doc::Entity::new(Handle(1), dimension_of_p())); + d.blocks.insert("N".into(), std::sync::Arc::new(n)); + d +} + +/// A dimension that draws the block P of [`drawing_with_p`]. +fn dimension_of_p() -> EntityKind { + EntityKind::Dimension(cadcraft_doc::Dimension { + kind: cadcraft_doc::DimKind::Aligned, + defpt: Vec3::new(5.0, 1.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("P".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }) +} + +/// Built for a selection through a viewport that freezes the layer Defpoints, a point on that +/// layer that is a part of a block is kept: in the block a dimension draws, where its definition +/// points are, in that of a dimension inside a block and in that of a plain reference. The line +/// on Defpoints in the same block is left out, in a dimension too, like the line on the other +/// frozen layer. A point on Defpoints that is not a part of a block is left out with its layer, +/// like every object on a layer the viewport freezes: the rule is about the parts of blocks. +#[test] +fn entities_built_for_a_viewport_keep_the_points_on_defpoints_in_a_block() { + let d = drawing_with_p(); + let reference = |handle: u64, block: &str| { + cadcraft_doc::Entity::new(Handle(handle), EntityKind::Insert(cadcraft_doc::Insert { block: block.into(), ..Default::default() })) + }; + let mut loose = cadcraft_doc::Entity::new(Handle(7), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 9.0, 0.0), angle: 0.0 })); + loose.common.layer = "Defpoints".into(); + let ents = [cadcraft_doc::Entity::new(Handle(4), dimension_of_p()), reference(5, "N"), reference(6, "P"), loose]; + let ys = |l: &DisplayList| -> Vec { l.prims.iter().map(|p| l.points(p)[0].y).collect() }; + let opts = Options::default(); + let frozen = ["defpoints".to_string(), "Hidden".to_string()]; + assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &frozen)), [0.0, 5.0, 0.0, 5.0, 0.0, 5.0]); + assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &[])), [0.0, 5.0, 6.0, 7.0, 0.0, 5.0, 6.0, 7.0, 0.0, 5.0, 6.0, 7.0, 9.0]); +} + +/// A layout viewport that freezes the layer Defpoints does not draw the points on it, a part of a +/// dimension's block or of a reference's: only a selection through the viewport counts them +/// ([`build_entities_in_viewport`]). A viewport that draws the layer draws them. +#[test] +fn a_viewport_that_freezes_defpoints_does_not_draw_the_points_on_it() { + let drawn = |frozen: &[&str]| -> Vec { + let mut d = drawing_with_p(); + d.add(&Space::Model, Common::default(), dimension_of_p()).unwrap(); + let held = cadcraft_doc::Insert { block: "N".into(), insert: Vec3::new(0.0, 10.0, 0.0), ..Default::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(held)).unwrap(); + let plain = cadcraft_doc::Insert { block: "P".into(), insert: Vec3::new(0.0, 20.0, 0.0), ..Default::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(plain)).unwrap(); + // The viewport shows model space at 1:1 around (5, 15), so paper and model coordinates + // are the same. + let mut v = vp(Vec2::new(5.0, 15.0), 60.0, 60.0, Vec2::new(5.0, 15.0), 60.0, 2); + v.frozen_layers = frozen.iter().map(|layer| layer.to_string()).collect(); + let paper = Space::Paper("Layout1".into()); + d.add(&paper, Common::default(), EntityKind::Viewport(v)).unwrap(); + viewport_points(&build(&d, &paper, &Options::default())).iter().map(|p| p[0].y).collect() + }; + assert_eq!(drawn(&["defpoints"]), [0.0, 7.0, 10.0, 17.0, 20.0, 27.0]); + assert_eq!(drawn(&[]), [0.0, 5.0, 6.0, 7.0, 10.0, 15.0, 16.0, 17.0, 20.0, 25.0, 26.0, 27.0]); +} + #[test] fn frozen_layer_hidden() { let mut d = sample(); @@ -63,6 +186,8 @@ fn text_produces_strokes() { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), ) .unwrap(); @@ -70,6 +195,188 @@ fn text_produces_strokes() { assert!(l.prims.len() >= 3); } +/// What is drawn of one TEXT whose two points are `span` apart, and the drawing's extents. +fn drawn_and_extents( + halign: cadcraft_doc::HAlign, + value: &str, + height: f64, + width_factor: f64, + span: f64, +) -> (cadcraft_geom::Bounds2, cadcraft_geom::Bounds2) { + drawn_and_extents_at(halign, Default::default(), value, height, width_factor, span, (false, false)) +} + +/// The same for a vertical justification and the text's generation flags (backwards, upside down). +fn drawn_and_extents_at( + halign: cadcraft_doc::HAlign, + valign: cadcraft_doc::VAlign, + value: &str, + height: f64, + width_factor: f64, + span: f64, + (backwards, upside_down): (bool, bool), +) -> (cadcraft_geom::Bounds2, cadcraft_geom::Bounds2) { + let mut d = Drawing::new_imperial(); + let text = cadcraft_doc::Text { + insert: Vec3::ZERO, + align_pt: Some(Vec3::new(span, 0.0, 0.0)), + height, + value: value.into(), + rotation: 0.0, + width_factor, + oblique: 0.0, + style: "Standard".into(), + halign, + valign, + backwards, + upside_down, + }; + d.add(&Space::Model, Common::default(), EntityKind::Text(text)).unwrap(); + let l = build(&d, &Space::Model, &Options::default()); + let drawn = cadcraft_geom::Bounds2::from_points(l.prims.iter().flat_map(|p| l.points(p).iter().copied())); + assert!(!drawn.is_empty(), "{value:?} over {span}: the text is drawn"); + (drawn, d.extents(&Space::Model)) +} + +/// Fit text whose two points are so close that the fitted width factor is too small to shape +/// is drawn unstretched, far wider than the span between its points: the drawing's extents hold +/// what is drawn, as they do for the same text fitted over a span it can be stretched to. +#[test] +fn fit_text_extents_hold_the_drawn_text_when_the_span_is_too_short_to_fit() { + for span in [1e-7, 10.0] { + let (drawn, extents) = drawn_and_extents(cadcraft_doc::HAlign::Fit, "AB", 1.0, 1.0, span); + let slack = 1e-6; + assert!( + drawn.min.x >= extents.min.x - slack + && drawn.max.x <= extents.max.x + slack + && drawn.min.y >= extents.min.y - slack + && drawn.max.y <= extents.max.y + slack, + "span {span}: drawn {drawn:?} outside extents {extents:?}" + ); + } + // The short span is the case the fitted factor falls back in: the text is wider than its span. + assert!(drawn_and_extents(cadcraft_doc::HAlign::Fit, "AB", 1.0, 1.0, 1e-7).0.width() > 1e-7 * 1000.0); +} + +/// Backwards and upside-down text over two points is mirrored about its first point, along the +/// line through both. The drawing's extents are mirrored the same way: they are the plain text's +/// extents reflected, as what is drawn is the plain text reflected. +#[test] +fn mirrored_aligned_and_fit_text_extents_follow_the_drawn_text() { + use cadcraft_doc::HAlign::{Aligned, Fit}; + use cadcraft_geom::{Bounds2, Vec2}; + let near = |a: Bounds2, b: Bounds2| a.min.dist(b.min) < 1e-9 && a.max.dist(b.max) < 1e-9; + for halign in [Aligned, Fit] { + // The first point is the origin and the second is at +x. + let (plain_drawn, plain_extents) = drawn_and_extents(halign, "AB", 1.0, 1.0, 10.0); + assert!(plain_drawn.min.x > -1e-9 && plain_drawn.max.y > 0.5, "{halign:?}: drawn {plain_drawn:?}"); + for flags in [(true, false), (false, true), (true, true)] { + let (mx, my) = (if flags.0 { -1.0 } else { 1.0 }, if flags.1 { -1.0 } else { 1.0 }); + let reflect = |b: Bounds2| Bounds2::from_points([b.min, b.max].map(|p| Vec2::new(p.x * mx, p.y * my))); + let (drawn, extents) = drawn_and_extents_at(halign, Default::default(), "AB", 1.0, 1.0, 10.0, flags); + assert!(near(drawn, reflect(plain_drawn)), "{halign:?} {flags:?}: drawn {drawn:?}, plain {plain_drawn:?}"); + assert!(near(extents, reflect(plain_extents)), "{halign:?} {flags:?}: extents {extents:?}, plain {plain_extents:?}"); + } + } +} + +/// The extents estimate a line's width where the fonts measure it, so near the fonts' cutoffs +/// the two could decide differently. The extents then take the larger outcome, and stay near +/// what is drawn in each of these cases. +#[test] +fn aligned_and_fit_text_extents_stay_near_the_drawn_text_at_the_cutoffs() { + use cadcraft_doc::HAlign::{Aligned, Fit}; + // Wide letters over a span just where the fitted factor reaches the cutoff: the estimate says + // the text is stretched, the fonts draw it unstretched, a million times wider than its span. + let (drawn, extents) = drawn_and_extents(Fit, "AAAAAAAAA", 1.0, 1.0, 8.12e-6); + assert!(drawn.width() > 1.0, "drawn unstretched: {drawn:?}"); + assert!(extents.width() > drawn.width() * 0.9, "drawn {drawn:?}, extents {extents:?}"); + // A narrow letter shrunk into a short span by Aligned stays about as tall as it was. + let (drawn, extents) = drawn_and_extents(Aligned, "I", 1.0, 1.0, 1.0 / 3.0); + assert!(extents.max.y >= drawn.max.y - 1e-6, "drawn {drawn:?}, extents {extents:?}"); + // A line of next to no width is left as it is: the extents do not reach for the second point. + for halign in [Aligned, Fit] { + let (drawn, extents) = drawn_and_extents(halign, "I", 1e-8, 1e-5, 10.0); + assert!(drawn.width() < 1e-3 && drawn.height() < 1e-3, "{halign:?}: drawn as it is: {drawn:?}"); + assert!(extents.width() < 1e-3 && extents.height() < 1e-3, "{halign:?}: extents {extents:?}"); + } +} + +/// Aligned text is as tall as its span makes it, and narrow letters over a long span are drawn far +/// taller than their own height: the extents hold them, without growing out of proportion for +/// wide letters. +#[test] +fn aligned_text_extents_hold_narrow_letters_stretched_over_a_long_span() { + // The last two are control codes: toggles that draw nothing around "AB", and two symbols. + for value in ["I", "IIII", "W", "WWWW", "AB", "%%uAB%%u", "%%c%%d"] { + let (drawn, extents) = drawn_and_extents(cadcraft_doc::HAlign::Aligned, value, 1.0, 1.0, 20.0); + assert!(drawn.height() > 1.0, "{value:?}: stretched taller than its own height: {drawn:?}"); + assert!(extents.max.y >= drawn.max.y - 1e-6, "{value:?}: drawn {drawn:?} above extents {extents:?}"); + assert!(extents.height() < drawn.height() * 5.0, "{value:?}: drawn {drawn:?}, extents {extents:?}"); + } +} + +/// The fitted height also sets how far a vertical justification moves Aligned text, and the box +/// does not know that height exactly: it holds the text from its lowest possible bottom to its +/// highest possible top, whichever way it is justified. +#[test] +fn aligned_text_extents_hold_the_text_at_every_vertical_justification() { + use cadcraft_doc::VAlign::{Baseline, Bottom, Middle, Top}; + for valign in [Baseline, Bottom, Middle, Top] { + for value in ["I", "W", "WWWW"] { + // Plain, and mirrored each way about the point the text is placed by. + for flags in [(false, false), (true, false), (false, true), (true, true)] { + let (drawn, extents) = drawn_and_extents_at(cadcraft_doc::HAlign::Aligned, valign, value, 1.0, 1.0, 20.0, flags); + assert!( + extents.min.y <= drawn.min.y + 1e-6 && extents.max.y >= drawn.max.y - 1e-6, + "{valign:?} {value:?} {flags:?}: drawn {drawn:?} outside extents {extents:?}" + ); + } + } + } +} + +/// Text of next to no width is left as it is by the fonts, neither stretched nor scaled, and its +/// extents stay its own size: they follow the fonts' own cutoff. +#[test] +fn unfitted_text_of_next_to_no_width_keeps_extents_of_its_own_size() { + for halign in [cadcraft_doc::HAlign::Aligned, cadcraft_doc::HAlign::Fit] { + let (drawn, extents) = drawn_and_extents(halign, "I", 1e-7, 1e-5, 10.0); + assert!(drawn.width() < 1e-3 && drawn.height() < 1e-3, "{halign:?}: drawn as it is: {drawn:?}"); + assert!(extents.width() < 1e-3 && extents.height() < 1e-3, "{halign:?}: extents {extents:?}"); + } +} + +/// A value of nothing but underline and overline toggles draws nothing and has no extents: not +/// those of one character, which Aligned text would stretch over its span. +#[test] +fn text_that_draws_nothing_has_no_extents() { + use cadcraft_doc::HAlign::{Aligned, Fit, Left}; + for halign in [Left, Aligned, Fit] { + for value in ["%%u%%u", "%%o", ""] { + let mut d = Drawing::new_imperial(); + let text = cadcraft_doc::Text { + insert: Vec3::ZERO, + align_pt: Some(Vec3::new(20.0, 0.0, 0.0)), + height: 1.0, + value: value.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign, + valign: Default::default(), + backwards: false, + upside_down: false, + }; + d.add(&Space::Model, Common::default(), EntityKind::Text(text)).unwrap(); + assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty(), "{halign:?} {value:?}: nothing is drawn"); + let extents = d.extents(&Space::Model); + assert!(extents.is_empty(), "{halign:?} {value:?}: extents {extents:?}"); + } + } +} + #[test] fn hatch_pattern_and_solid() { let mut d = Drawing::new_imperial(); @@ -142,6 +449,9 @@ fn vp(center: Vec2, w: f64, h: f64, view_center: Vec2, view_height: f64, id: u32 layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, } } @@ -271,6 +581,8 @@ fn text_doc(style_font: &str, value: &str) -> Drawing { style: "TT".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }), ) .unwrap(); @@ -395,13 +707,25 @@ fn backwards_and_upside_down_mirror_text() { let mut d = text_doc("CADCraft Stroke", "ABC"); let normal = build(&d, &Space::Model, &Options::default()).bounds; assert!(normal.min.x >= -1e-9 && normal.min.y >= -1e-9); + // The text's own flags (DXF 71) mirror it, as AutoCAD's do; its style's are what new text + // starts with and don't change it. + let set = |d: &mut Drawing, backwards: bool, upside_down: bool| { + let h = d.model.iter().next().map(|e| e.handle).unwrap(); + d.modify_entity(h, |e| { + if let EntityKind::Text(t) = &mut e.kind { + t.backwards = backwards; + t.upside_down = upside_down; + } + }) + .unwrap(); + }; d.text_styles.iter_mut().for_each(|s| s.backwards = true); + let styled = build(&d, &Space::Model, &Options::default()).bounds; + assert!((styled.min.x - normal.min.x).abs() < 1e-9, "the style's flag doesn't mirror existing text"); + set(&mut d, true, false); let back = build(&d, &Space::Model, &Options::default()).bounds; assert!(back.max.x <= 1e-9 && (back.width() - normal.width()).abs() < 1e-9, "mirrored to the left"); - d.text_styles.iter_mut().for_each(|s| { - s.backwards = false; - s.upside_down = true; - }); + set(&mut d, false, true); let up = build(&d, &Space::Model, &Options::default()).bounds; assert!(up.max.y <= 1e-9 && up.min.y < -0.9, "mirrored below the baseline"); } @@ -425,6 +749,7 @@ fn truetype_mtext_and_dimension_text() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), ) .unwrap(); @@ -863,6 +1188,8 @@ fn attrib(tag: &str) -> cadcraft_doc::Attrib { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }, invisible: false, constant: false, @@ -1020,6 +1347,62 @@ fn attributes_follow_the_reference_layer_and_have_no_definition() { } } +#[test] +fn attribute_set_on_layer_zero_does_not_take_the_reference_layer() { + // #3492: a layer-0 definition in a reference on a 40 % layer. An attribute that takes layer 0 + // from its definition is drawn on the reference's layer, like the line; one set on layer 0 + // itself is drawn on the opaque layer 0. + let drawn = |layer: Option<&str>| { + let mut d = Drawing::new_imperial(); + let mut blk = cadcraft_doc::Block::new("B"); + let (c, k) = line_common(Common::default()); + blk.entities.push(block_entity(1, c, k)); + blk.entities.push(block_entity(2, Common::default(), EntityKind::AttDef(attrib("TAG")))); + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") }; + let props = cadcraft_doc::AttribProps { layer: layer.map(Into::into), ..Default::default() }; + ins.attribs.push(cadcraft_doc::Attrib { props, ..attrib("TAG") }); + d.add(&Space::Model, Common { layer: "Glass".into(), ..Default::default() }, EntityKind::Insert(ins)).unwrap(); + d.layer_mut("Glass").unwrap().transparency = 40; + line_and_text(&d) + }; + let (inherited_line, inherited) = drawn(None); + let (line, own) = drawn(Some("0")); + assert_eq!(line, inherited_line, "the block's contents still take the reference's layer"); + assert!(inherited.iter().all(|t| *t == line), "{inherited:?}"); + assert!(own.iter().all(|t| *t < line), "{own:?}"); +} + +#[test] +fn attribute_on_layer_zero_of_a_nested_reference_follows_the_outer_reference() { + // A reference on the opaque layer A, with an attribute set on layer 0, sits inside block + // Outer beside a layer-0 line; Outer is placed on a 40 % layer. In Outer the attribute is + // layer-0 content like that line, so both take the outer reference's layer: not layer 0 + // itself, and not layer A, which only the inner block's own line takes. + let mut d = Drawing::new_imperial(); + d.layers.push(cadcraft_doc::Layer { name: "A".into(), ..Default::default() }); + let mut inner = cadcraft_doc::Block::new("B"); + let (c, k) = line_common(Common::default()); + inner.entities.push(block_entity(1, c, k)); + inner.entities.push(block_entity(2, Common::default(), EntityKind::AttDef(attrib("TAG")))); + d.blocks.insert("B".into(), std::sync::Arc::new(inner)); + let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") }; + let props = cadcraft_doc::AttribProps { layer: Some("0".into()), ..Default::default() }; + ins.attribs.push(cadcraft_doc::Attrib { props, ..attrib("TAG") }); + let mut outer = cadcraft_doc::Block::new("Outer"); + let (c, k) = line_common(Common::default()); + outer.entities.push(block_entity(3, c, k)); + outer.entities.push(block_entity(4, Common { layer: "A".into(), ..Default::default() }, EntityKind::Insert(ins))); + d.blocks.insert("Outer".into(), std::sync::Arc::new(outer)); + d.add(&Space::Model, Common { layer: "Glass".into(), ..Default::default() }, insert_of("Outer")).unwrap(); + d.layer_mut("Glass").unwrap().transparency = 40; + let l = build(&d, &Space::Model, &with_transparency()); + let [outer_line, inner_line, text @ ..] = l.prims.as_slice() else { panic!("two lines and the attribute") }; + assert!(!text.is_empty(), "the attribute is drawn"); + assert!(inner_line.transparency < outer_line.transparency, "the inner block's line is on layer A"); + assert!(text.iter().all(|p| p.transparency == outer_line.transparency), "the attribute follows the outer reference's layer"); +} + #[test] fn mtext_exact_spacing_ignores_taller_lines() { // #711: a doubled middle line pushes the next baseline down with At least, not with Exactly. @@ -1034,6 +1417,7 @@ fn mtext_exact_spacing_ignores_taller_lines() { line_spacing, line_spacing_exact, columns: None, + background: None, }; let d = Drawing::new_imperial(); let height = |contents: &str, ls: f64, exact: bool| layout_mtext_entity(&d, &mtext(contents, ls, exact)).bounds.height(); @@ -1523,7 +1907,270 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() { assert_eq!(loops_of(&h).len(), 2); } -// ---------- point budget (#1922) ---------- +#[test] +fn mtext_background_mask_emits_mask_before_text() { + let mut d = Drawing::new_metric(); + d.add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.25, + style: "Standard".into(), + contents: "ANCHOR".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 2, color: None, scale: 1.5 }), + }), + ) + .unwrap(); + let list = build(&d, &Space::Model, &Options::default()); + let mask_idx = list.prims.iter().position(|p| p.kind == Kind::Mask).expect("background mask"); + assert_eq!(mask_idx, 0, "mask must precede text primitives"); + + let mut d2 = Drawing::new_metric(); + d2.add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "COLORED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 1.5 }), + }), + ) + .unwrap(); + let list2 = build(&d2, &Space::Model, &Options::default()); + assert!(list2.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(0, 255, 0)), "green background fill"); + assert!(!list2.prims.iter().any(|p| p.kind == Kind::Mask)); + // Border offset factor 1.5 with height 2.0 expands each side by (1.5 - 1.0) * 2.0 = 1.0. + let mut d2_plain = Drawing::new_metric(); + d2_plain + .add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "COLORED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: None, + }), + ) + .unwrap(); + let plain_list = build(&d2_plain, &Space::Model, &Options::default()); + assert!((list2.bounds.width() - plain_list.bounds.width() - 2.0).abs() < 1e-6, "expected +2.0 width margin"); + assert!((list2.bounds.height() - plain_list.bounds.height() - 2.0).abs() < 1e-6, "expected +2.0 height margin"); +} + +#[test] +fn mtext_background_mask_stays_paper_mask_under_monochrome_ctb() { + let mut d = Drawing::new_metric(); + d.add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::new(5.0, 5.0, 0.0), + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.5, + style: "Standard".into(), + contents: "MASKED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 3, color: None, scale: 1.5 }), + }), + ) + .unwrap(); + let opts = Options { + plot_style_table: Some(std::sync::Arc::new(cadcraft_doc::PlotStyleTable::builtin("monochrome.ctb").unwrap())), + ..Default::default() + }; + let list = build_plot(&d, &Space::Model, &opts); + let mask_idx = list.prims.iter().position(|p| p.kind == Kind::Mask).expect("Kind::Mask must remain"); + let text_idx = list.prims.iter().position(|p| p.kind != Kind::Mask).expect("text prims"); + assert!(mask_idx < text_idx, "Kind::Mask must precede text under monochrome.ctb"); +} + +#[test] +fn mtext_background_mask_resolves_bylayer_byblock_and_nonfinite_rotation() { + let mut d = Drawing::new_metric(); + d.layers.push(cadcraft_doc::Layer { name: "RED_LAYER".into(), color: Color::Index(1), ..Default::default() }); + d.add( + &Space::Model, + Common { layer: "RED_LAYER".into(), ..Default::default() }, + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: f64::NAN, + style: "Standard".into(), + contents: "BYLAYER".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::ByLayer), scale: 1.5 }), + }), + ) + .unwrap(); + let mut blk = cadcraft_doc::Block::new("BG_BLK"); + blk.entities.push(block_entity( + 8001, + Common { layer: "0".into(), ..Default::default() }, + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::new(0.0, 20.0, 0.0), + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "BYBLOCK".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::ByBlock), scale: 1.5 }), + }), + )); + d.blocks.insert("BG_BLK".into(), std::sync::Arc::new(blk)); + let mut ins = insert_of("BG_BLK"); + if let EntityKind::Insert(ref mut i) = ins { + i.insert = Vec3::new(0.0, 20.0, 0.0); + } + d.add(&Space::Model, Common { color: Color::Index(5), ..Default::default() }, ins).unwrap(); + + let list = build(&d, &Space::Model, &Options::default()); + assert!(list.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(255, 0, 0)), "ByLayer red background fill"); + assert!(list.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(0, 0, 255)), "ByBlock blue background fill"); + assert!(list.tris.iter().all(|v| v.x.is_finite() && v.y.is_finite()), "non-finite rotation must yield finite background tris"); + + // Multiline ATTRIB without ATTDEF and with empty props inherits INSERT block_color for ByBlock background mask. + let mut d_attr = Drawing::new_metric(); + d_attr.blocks.insert("EMPTY_BLK".into(), std::sync::Arc::new(cadcraft_doc::Block::new("EMPTY_BLK"))); + let mut ins_attr = insert_of("EMPTY_BLK"); + if let EntityKind::Insert(ref mut i) = ins_attr { + i.attribs.push(cadcraft_doc::Attrib { + tag: "TAG".into(), + text: cadcraft_doc::Text { + insert: Vec3::ZERO, + align_pt: None, + height: 2.0, + value: "ATTR".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + backwards: false, + upside_down: false, + }, + multiline: Some(cadcraft_doc::MultilineAttrib { + mtext: cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "ATTR".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::ByBlock), scale: 1.5 }), + }, + read_as: "ATTR".into(), + }), + invisible: false, + constant: false, + prompt: String::new(), + props: cadcraft_doc::AttribProps::default(), + modes: cadcraft_doc::AttribModes::default(), + }); + } + d_attr.add(&Space::Model, Common { color: Color::Index(3), ..Default::default() }, ins_attr).unwrap(); + let attr_list = build(&d_attr, &Space::Model, &Options::default()); + assert!(attr_list.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(0, 255, 0)), "Attrib ByBlock green background fill"); + + // MLeader with opts.text == false must not emit MText background mask triangles. + let mut d_ml = Drawing::new_metric(); + d_ml.add( + &Space::Model, + Common::default(), + EntityKind::MLeader(cadcraft_doc::MLeader { + leaders: Vec::new(), + landing: Vec3::ZERO, + dogleg: 1.0, + style: "Standard".into(), + arrow_size: 1.0, + spline: false, + text: Some(cadcraft_doc::MText { + insert: Vec3::new(2.0, 0.0, 0.0), + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "ML".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 3, color: None, scale: 1.5 }), + }), + block: None, + }), + ) + .unwrap(); + let ml_no_text = build(&d_ml, &Space::Model, &Options { text: false, ..Default::default() }); + assert!(!ml_no_text.prims.iter().any(|p| p.kind == Kind::Mask), "MLeader background mask must not draw when opts.text is false"); + + // Unbreakable word overflowing narrow reference width expands background quad beyond reference width. + let mut d_ovf = Drawing::new_metric(); + d_ovf + .add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 1.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "WWWWWW".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 3, color: None, scale: 1.5 }), + }), + ) + .unwrap(); + let ovf_list = build(&d_ovf, &Space::Model, &Options::default()); + let min_x = ovf_list.tris.iter().map(|v| v.x).fold(f64::INFINITY, f64::min); + let max_x = ovf_list.tris.iter().map(|v| v.x).fold(f64::NEG_INFINITY, f64::max); + assert!(max_x - min_x > 8.0, "overflowing word background quad width ({}) must cover actual glyph strokes", max_x - min_x); +} + +// ---------- point and primitive budgets (#1922, #1603) ---------- fn circle() -> EntityKind { EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::ZERO, radius: 100.0 }) @@ -1551,7 +2198,15 @@ fn block_copies_stop_at_the_point_budget_and_say_so() { let d = arrayed_circles(); let full = build(&d, &Space::Model, &Options::default()); assert!(!full.truncated && points(&full) > 100_000, "{}", points(&full)); - let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, crate::MAX_DASH_ELEMENTS); + let l = crate::pipeline::build_space_within( + &d, + &Space::Model, + &Options::default(), + false, + 10_000, + crate::MAX_DISPLAY_PRIMS, + crate::MAX_DASH_ELEMENTS, + ); assert!(l.truncated); assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l)); assert!(l.prims.iter().all(|p| p.start as usize + p.len as usize <= l.verts.len())); @@ -1564,11 +2219,336 @@ fn objects_built_on_all_cores_stop_at_the_point_budget_and_say_so() { for _ in 0..600 { d.add(&Space::Model, Common::default(), circle()).unwrap(); } - let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, crate::MAX_DASH_ELEMENTS); + let l = crate::pipeline::build_space_within( + &d, + &Space::Model, + &Options::default(), + false, + 10_000, + crate::MAX_DISPLAY_PRIMS, + crate::MAX_DASH_ELEMENTS, + ); assert!(l.truncated); assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l)); } +fn point_at(x: f64) -> EntityKind { + EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(x, 0.0, 0.0), angle: 0.0 }) +} + +/// A block of one point referenced as 1,000 copies in place: every copy is one primitive of one +/// point, so the point budget holds far more of them than a 32-bit target's primitive vector +/// (#1603). +fn arrayed_points() -> Drawing { + let mut d = Drawing::new_imperial(); + let mut blk = cadcraft_doc::Block::new("B"); + blk.entities.push(block_entity(1, Common::default(), point_at(0.0))); + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") }; + ins.cols = 1000; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + d +} + +#[test] +fn one_point_primitives_stop_at_the_primitive_budget_and_say_so() { + let d = arrayed_points(); + let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); + assert!(!full.truncated && full.prims.len() >= 1000, "{}", full.prims.len()); + let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 100, MAX_DASH_ELEMENTS); + assert!(l.truncated); + assert!(!l.prims.is_empty() && l.prims.len() <= 100, "{}", l.prims.len()); + // And the copies past it are not visited. + assert!(l.expanded < full.expanded / 2, "{} of {}", l.expanded, full.expanded); +} + +#[test] +fn primitives_built_on_all_cores_stop_at_the_primitive_budget_and_say_so() { + // Enough references of a one-point block for the parallel build: the parts share one + // primitive count, and stop visiting their blocks once it is spent. + let mut d = Drawing::new_imperial(); + let mut blk = cadcraft_doc::Block::new("B"); + blk.entities.push(block_entity(1, Common::default(), point_at(0.0))); + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + for i in 0..600 { + let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") }; + ins.insert = Vec3::new(f64::from(i), 0.0, 0.0); + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + } + let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); + assert_eq!(full.prims.len(), 600); + let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 100, MAX_DASH_ELEMENTS); + assert!(l.truncated); + assert!(!l.prims.is_empty() && l.prims.len() <= 100, "{}", l.prims.len()); + assert!(l.expanded < full.expanded / 2, "{} of {}", l.expanded, full.expanded); + // A limit no one part reaches (parts of 256 objects): only the shared count stops the parts + // at the limit together. Counted per part, each would build its whole chunk, and the join + // would keep the first part alone. + let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 300, MAX_DASH_ELEMENTS); + assert!(l.truncated); + assert_eq!(l.prims.len(), 300); +} + +/// A polyline of 200 points zigzagging across y = 1 between x = 1.5 and 8.5: a clip whose edge +/// is y = 1 cuts it into about 100 pieces of three points each. +fn zigzag() -> EntityKind { + let vertices = (0..200).map(|i| PolyVertex::new(Vec2::new(1.5 + 7.0 * f64::from(i) / 199.0, if i % 2 == 0 { 0.0 } else { 2.0 }))).collect(); + EntityKind::LwPolyline(cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false }) +} + +#[test] +fn pieces_cut_by_a_clip_stop_at_the_list_limits_and_say_so() { + // Seen through a viewport whose model window starts at y = 1, the zigzag and then a point + // inside the window. Each drawing ends with a point the budgets alone would still take after + // the pieces: a full list stops the build. + let mut through_viewport = Drawing::new_imperial(); + through_viewport.add(&Space::Model, Common::default(), zigzag()).unwrap(); + through_viewport + .add(&Space::Model, Common::default(), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 })) + .unwrap(); + let paper = Space::Paper("Layout1".into()); + through_viewport.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap(); + through_viewport.add(&paper, Common::default(), point_at(5.0)).unwrap(); + // In a block reference clipped (XCLIP) to a rectangle from y = 1 up, without its frame. + let mut xclipped = Drawing::new_imperial(); + xclipped.header.set_i64("XCLIPFRAME", 0); + let mut blk = cadcraft_doc::Block::new("Z"); + blk.entities.push(block_entity(1, Common::default(), zigzag())); + blk.entities.push(block_entity(2, Common::default(), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 }))); + xclipped.blocks.insert("Z".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = insert_of("Z") else { panic!("an insert") }; + ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(0.0, 1.0), Vec2::new(10.0, 10.0)])); + xclipped.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + xclipped.add(&Space::Model, Common::default(), point_at(5.0)).unwrap(); + for (d, space) in [(&through_viewport, &paper), (&xclipped, &Space::Model)] { + let build = |max_points, max_prims| { + crate::pipeline::build_space_within(d, space, &Options::default(), false, max_points, max_prims, MAX_DASH_ELEMENTS) + }; + // The one polyline the build charges becomes many pieces with more points. + let full = build(MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS); + assert!(!full.truncated && full.prims.len() > 50 && points(&full) > 250, "{space:?}: {} prims, {} points", full.prims.len(), points(&full)); + let l = build(10_000, 20); + assert!(l.truncated && !l.prims.is_empty() && l.prims.len() <= 20, "{space:?}: {}", l.prims.len()); + // The pieces stop at the first that doesn't fit: neither point comes after them. + let l = build(220, MAX_DISPLAY_PRIMS); + assert!(l.truncated && points(&l) > 0 && points(&l) <= 220, "{space:?}: {}", points(&l)); + assert!(full.prims.iter().any(|p| p.kind == Kind::Point) && l.prims.iter().all(|p| p.kind != Kind::Point), "{space:?}"); + // Pieces that fill the list exactly leave no room for the last point. + for l in [build(MAX_DISPLAY_POINTS, full.prims.len() - 1), build(points(&full) - 1, MAX_DISPLAY_PRIMS)] { + assert!(l.truncated && l.prims.len() == full.prims.len() - 1, "{space:?}: {} of {}", l.prims.len(), full.prims.len()); + } + } +} + +/// The zigzag drawn 0.2 wide: one primitive of triangles, seen through a viewport whose model +/// window starts at y = 1, and a point after it on the layout. +fn wide_zigzag_through_viewport() -> Drawing { + let mut d = Drawing::new_imperial(); + let EntityKind::LwPolyline(mut wide) = zigzag() else { panic!("a polyline") }; + wide.const_width = 0.2; + d.add(&Space::Model, Common::default(), EntityKind::LwPolyline(wide)).unwrap(); + let paper = Space::Paper("Layout1".into()); + d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap(); + d.add(&paper, Common::default(), point_at(5.0)).unwrap(); + d +} + +#[test] +fn fills_cut_by_a_clip_stop_at_the_list_limits_and_say_so() { + // Each triangle the window's edge crosses becomes a fan with more points. With room for part + // of the clipped fill, the triangles that fit are drawn up to the limit, the rest is not built, + // and the list says it was left out; the point after the viewport is not drawn either. + let d = wide_zigzag_through_viewport(); + let paper = Space::Paper("Layout1".into()); + let build = + |max_points| crate::pipeline::build_space_within(&d, &paper, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); + let full = build(MAX_DISPLAY_POINTS); + let fills = full.prims.iter().filter(|p| p.kind == Kind::Tris).count(); + // The build charges the fill's points before it is clipped: fewer than the clip makes. + let charged = + crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); + assert!( + !full.truncated && fills == 1 && full.tris.len() > charged.tris.len() + 100, + "{fills} fills, {} of {}", + full.tris.len(), + charged.tris.len() + ); + // Limits the charge passes and the clipped fill does not fit. + for limit in [points(&full) - (full.tris.len() - charged.tris.len()) / 2, full.verts.len() + charged.tris.len()] { + let l = build(limit); + assert!(l.truncated && !l.tris.is_empty() && full.tris.starts_with(&l.tris), "{limit}: {}", l.tris.len()); + // Whole triangles, up to the limit. + assert!(l.tris.len() % 3 == 0 && points(&l) <= limit && points(&l) + 3 > limit, "{limit}: {}", points(&l)); + assert!(l.prims.iter().all(|p| p.kind != Kind::Point), "{limit}"); + } + // Clipped into a list of its own (as a preview's clipped copy is, with no build to stop), the + // cut fill marks that list truncated too. + let mut list = DisplayList::default(); + let window = crate::viewports::Clip::Rect(Bounds2::new(Vec2::new(1.0, 1.0), Vec2::new(9.0, 9.0))); + let fits = crate::viewports::append_clipped(&mut list, &charged, &window, crate::viewports::Limits { points: 300, prims: 10 }); + assert!(!fits && list.truncated && list.tris.len() == 300, "{}", list.tris.len()); +} + +#[test] +fn a_clipped_preview_keeps_what_its_list_left_out() { + // A point, then a zigzag the point budget leaves out: the list says so, and so does its copy + // clipped to a viewport's outline (the preview of a command inside a clipped viewport). + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), point_at(5.0)).unwrap(); + d.add(&Space::Model, Common::default(), zigzag()).unwrap(); + let mut l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 100, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); + assert!(l.truncated && l.prims.len() == 1, "{} prims", l.prims.len()); + (l.undashed, l.expanded) = (2, 3); + let square = [Vec2::new(-100.0, -100.0), Vec2::new(100.0, -100.0), Vec2::new(100.0, 100.0), Vec2::new(-100.0, 100.0)]; + let c = crate::clip_list(&l, &crate::clip::PolyClip::new(&square).unwrap()); + assert_eq!(c.prims.len(), 1); + assert!(c.truncated); + assert_eq!((c.undashed, c.expanded), (2, 3)); +} + +#[test] +fn layout_plot_style_outlines_stop_at_the_list_limits_and_say_so() { + // A plot style's line ends turn each wide line into a filled outline after the build, outside + // its budgets (#1603). Drawn on a layout or inside one of its viewports, the outlines stop at + // the build's point limit: every line is still drawn, those past it as plain lines. + let round = cadcraft_doc::PlotStyleTable::color_dependent("round.ctb", "", |i| { + (i == 1).then(|| cadcraft_doc::PlotStyle { lineweight: Some(100), end: cadcraft_doc::EndStyle::Round, ..Default::default() }) + }); + let opts = Options { plot_style_table: Some(std::sync::Arc::new(round)), lineweights: true, ..Default::default() }; + let paper = Space::Paper("Layout1".into()); + for space in [paper.clone(), Space::Model] { + let mut d = Drawing::new_metric(); + for k in 0..20 { + let y = 10.0 + 4.0 * f64::from(k); + let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(10.0, y, 0.0), b: Vec3::new(90.0, y, 0.0) }); + d.add(&space, Common { color: Color::Index(1), ..Default::default() }, line).unwrap(); + } + if space == Space::Model { + d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(50.0, 50.0), 100.0, 100.0, Vec2::new(50.0, 50.0), 100.0, 2))).unwrap(); + } + let build = |max_points| crate::pipeline::build_space_within(&d, &paper, &opts, false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); + let full = build(MAX_DISPLAY_POINTS); + let outlines = full.prims.iter().filter(|p| p.kind == Kind::Tris).count(); + assert!(!full.truncated && outlines == 20, "{space:?}: {outlines} outlines"); + let limit = points(&full) / 2; + let l = build(limit); + let plain = l.prims.iter().filter(|p| p.kind == Kind::Polyline).count(); + assert!(l.truncated && points(&l) <= limit, "{space:?}: {} of {limit}", points(&l)); + assert!(l.prims.len() == full.prims.len() && plain > 0 && plain < 20, "{space:?}: {plain} plain of {}", l.prims.len()); + } +} + +#[test] +fn viewport_outlines_stop_at_the_room_the_layout_has_left() { + // Viewport contents get their plot style outlines before they are clipped into the layout's + // list, which already holds the objects drawn before the viewport. Outlines made within the + // build's whole limit could fit the contents' own list but not the layout's: the append then + // stopped part-way and spent the build, so the last line in the viewport and the layout + // objects after it were left out, though their plain lines fit. Within the room the layout's + // list has left, every object is drawn and only outlines are left out. + let round = cadcraft_doc::PlotStyleTable::color_dependent("round.ctb", "", |i| { + (i == 1).then(|| cadcraft_doc::PlotStyle { lineweight: Some(100), end: cadcraft_doc::EndStyle::Round, ..Default::default() }) + }); + let opts = Options { plot_style_table: Some(std::sync::Arc::new(round)), lineweights: true, ..Default::default() }; + let paper = Space::Paper("Layout1".into()); + let line = |y: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(10.0, y, 0.0), b: Vec3::new(90.0, y, 0.0) }); + let plain = || Common { color: Color::Index(2), ..Default::default() }; + let mut d = Drawing::new_metric(); + // Before the viewport: 40 plain lines and 10 solids on the layout. + for k in 0..40 { + d.add(&paper, plain(), line(150.0 + f64::from(k))).unwrap(); + } + for k in 0..10 { + let x = 120.0 + 5.0 * f64::from(k); + let corners = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 4.0, 0.0, 0.0), Vec3::new(x, 4.0, 0.0), Vec3::new(x + 4.0, 4.0, 0.0)]; + d.add(&paper, plain(), EntityKind::Solid(cadcraft_doc::Solid { corners })).unwrap(); + } + // 20 round-ended lines seen through the viewport, and 5 plain lines on the layout after it. + for k in 0..20 { + d.add(&Space::Model, Common { color: Color::Index(1), ..Default::default() }, line(10.0 + 4.0 * f64::from(k))).unwrap(); + } + d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(50.0, 50.0), 100.0, 100.0, Vec2::new(50.0, 50.0), 100.0, 2))).unwrap(); + let after = [200.0, 201.0, 202.0, 203.0, 204.0]; + for y in after { + d.add(&paper, plain(), line(y)).unwrap(); + } + let build = |max_points| crate::pipeline::build_space_within(&d, &paper, &opts, false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); + let plain_lines = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Polyline).count(); + let full = build(MAX_DISPLAY_POINTS); + assert!(!full.truncated && full.prims.iter().filter(|p| p.kind == Kind::Tris).count() == 30); + // Room for every object but the last outline. The contents' own list (their plain lines' + // vertices and every outline) fits that limit; after the objects before the viewport it + // doesn't. + let tail: usize = full.prims.iter().rev().take(after.len()).map(|p| full.points(p).len()).sum(); + let limit = points(&full) - tail - 1; + let l = build(limit); + assert!(l.truncated && points(&l) <= limit, "{} of {limit}", points(&l)); + assert_eq!(l.prims.len(), full.prims.len(), "every object is drawn"); + assert!(plain_lines(&l) > plain_lines(&full), "some lines in the viewport keep their plain line"); +} + +/// A block reference clipped (XCLIP, frame off) to a large rectangle, of block "Z" holding `kind`. +fn xclipped_ref(d: &mut Drawing, kind: EntityKind, at: Vec3) -> EntityKind { + if d.block("Z").is_none() { + let mut blk = cadcraft_doc::Block::new("Z"); + blk.entities.push(block_entity(1, Common::default(), kind)); + d.blocks.insert("Z".into(), std::sync::Arc::new(blk)); + } + let EntityKind::Insert(mut ins) = insert_of("Z") else { panic!("an insert") }; + ins.insert = at; + ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(-100.0, 1.0), Vec2::new(100.0, 100.0)])); + EntityKind::Insert(ins) +} + +#[test] +fn attributes_cut_by_a_clip_say_what_the_budget_left_out() { + // The last object of the drawing: a clipped reference whose attribute text runs out of points. + let mut d = Drawing::new_imperial(); + d.header.set_i64("XCLIPFRAME", 0); + let kind = xclipped_ref(&mut d, line_common(Common::default()).1, Vec3::ZERO); + let EntityKind::Insert(mut ins) = kind else { panic!("an insert") }; + let mut a = attrib("TAG"); + a.text.insert = Vec3::new(1.0, 2.0, 0.0); + a.text.value = "ABCDEFGHIJKLMNOP".into(); + ins.attribs.push(a); + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + let build = |max_points| { + crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS) + }; + let full = build(MAX_DISPLAY_POINTS); + assert!(!full.truncated && points(&full) > 20, "{}", points(&full)); + let l = build(points(&full) - 1); + assert!(l.truncated && points(&l) < points(&full), "{} of {}", points(&l), points(&full)); +} + +#[test] +fn parts_built_on_all_cores_are_joined_within_the_list_limits() { + // Two clipped zigzags in different parts of the parallel build: each part fits the list's + // limits and the build's counts, which hold the zigzags and not their pieces; together they + // don't fit. + let mut d = Drawing::new_imperial(); + d.header.set_i64("XCLIPFRAME", 0); + for i in 0..600 { + let kind = if i == 0 || i == 300 { xclipped_ref(&mut d, zigzag(), Vec3::ZERO) } else { point_at(f64::from(i)) }; + d.add(&Space::Model, Common::default(), kind).unwrap(); + } + let build = |max_points, max_prims| { + crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, max_points, max_prims, MAX_DASH_ELEMENTS) + }; + let full = build(MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS); + assert!(!full.truncated && full.prims.len() > 700 && points(&full) > 1000, "{} prims, {} points", full.prims.len(), points(&full)); + let max = full.prims.len() - 50; + let l = build(MAX_DISPLAY_POINTS, max); + assert!(l.truncated && l.prims.len() <= max, "{} of {max}", l.prims.len()); + let max = points(&full) - 50; + let l = build(max, MAX_DISPLAY_PRIMS); + assert!(l.truncated && points(&l) <= max, "{} of {max}", points(&l)); + // Exactly as much as the parts hold is joined whole. + for l in [build(MAX_DISPLAY_POINTS, full.prims.len()), build(points(&full), MAX_DISPLAY_PRIMS)] { + assert!(!l.truncated && l.prims.len() == full.prims.len(), "{} of {}", l.prims.len(), full.prims.len()); + } +} + // ---------- dash budget (#1069, #1923) ---------- /// A drawing of lines on DASHED (0.5, -0.25), one per entry of `periods` and that many periods @@ -1619,11 +2599,12 @@ fn a_run_past_its_dash_limit_is_drawn_continuous_and_says_so() { #[test] fn dashed_runs_past_the_build_dash_budget_are_drawn_continuous_and_counted() { let d = dashed_lines(&[1000.0; 40]); - let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS); + let full = + crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS); assert!(!full.truncated && full.undashed == 0); let each = prims_per_entity(&full); assert!(each.len() == 40 && each.iter().all(|n| *n > 1000), "{each:?}"); - let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, 40_000); + let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 40_000); let dashed = 40 - l.undashed; assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed); assert!(dashed * 2004 <= 40_000, "{dashed} lines dashed"); @@ -1638,7 +2619,7 @@ fn dashed_runs_past_the_build_dash_budget_are_drawn_continuous_and_counted() { fn dashed_runs_built_on_all_cores_share_the_dash_budget() { // 600 lines of 100 periods (204 elements each): enough for the parallel build. let d = dashed_lines(&[100.0; 600]); - let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, 20_000); + let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 20_000); let dashed = 600 - l.undashed; assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed); assert!(dashed * 204 <= 20_000, "{dashed} lines dashed"); @@ -1662,10 +2643,56 @@ fn runs_seen_through_a_viewport_are_counted_and_spend_the_layout_dash_budget() { let l = build_plot(&d, &paper, &Options::default()); assert!(l.prims.iter().any(|p| p.handle == VIEWPORT_CONTENT), "the lines show in the viewport"); assert!(l.truncated && l.undashed == 1, "{}", l.undashed); - let l = crate::pipeline::build_space_within(&d, &paper, &Options::default(), true, MAX_DISPLAY_POINTS, 100); + let l = crate::pipeline::build_space_within(&d, &paper, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 100); assert_eq!(l.undashed, 2); } +/// Viewports after a spent layout build draw nothing, and the list says what they leave out: also +/// when the build was spent by a list filled exactly, before anything was left out. A list that +/// left out only dashes still draws them. +#[test] +fn viewports_after_a_spent_layout_build_say_what_they_leave_out() { + // A point seen through a rectangular viewport and then through a clipped one (which has no + // border), on a layout with a dashed line and the clip outline first: nothing on the layout + // after the viewports marks the list. + let paper = Space::Paper("Layout1".into()); + let layout = |second_on: bool| { + let mut d = dashed_lines(&[]); + let point = EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 }); + d.add(&Space::Model, Common::default(), point).unwrap(); + let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 12.0, 0.0), b: Vec3::new(750.0, 12.0, 0.0) }); + d.add(&paper, Common { linetype: "DASHED".into(), ..Default::default() }, line).unwrap(); + let vertices = [(20.0, 0.0), (30.0, 0.0), (30.0, 10.0), (20.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec(); + let square = cadcraft_doc::LwPolyline { vertices, closed: true, const_width: 0.0, elevation: 0.0, plinegen: false }; + let outline = d.add(&paper, Common::default(), EntityKind::LwPolyline(square)).unwrap(); + d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 5.0), 10.0, 10.0, Vec2::new(5.0, 5.0), 10.0, 2))).unwrap(); + let mut clipped = vp(Vec2::new(25.0, 5.0), 10.0, 10.0, Vec2::new(5.0, 5.0), 10.0, 3); + clipped.clip = Some(outline); + clipped.on = second_on; + d.add(&paper, Common::default(), EntityKind::Viewport(clipped)).unwrap(); + d + }; + let build = |d: &Drawing, max_points, max_dashes| { + crate::pipeline::build_space_within(d, &paper, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, max_dashes) + }; + let shown = |l: &DisplayList| l.prims.iter().filter(|p| p.handle == VIEWPORT_CONTENT).count(); + let (both, first) = (layout(true), layout(false)); + let full = build(&both, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS); + assert!(!full.truncated && shown(&full) == 2, "{}", shown(&full)); + // The layout up to the first viewport's point fills the list exactly: whole when the second + // viewport is off, and its point said to be left out when it is on. + let exact = points(&build(&first, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS)); + let l = build(&first, exact, MAX_DASH_ELEMENTS); + assert!(!l.truncated && shown(&l) == 1, "{}", shown(&l)); + let l = build(&both, exact, MAX_DASH_ELEMENTS); + assert!(l.truncated && shown(&l) == 1, "{}", shown(&l)); + let l = build(&both, exact - 1, MAX_DASH_ELEMENTS); + assert!(l.truncated && shown(&l) == 0, "{}", shown(&l)); + // The dashed line past the dash budget: drawn continuous, and both viewports drawn. + let l = build(&both, MAX_DISPLAY_POINTS, 100); + assert!(l.truncated && l.undashed == 1 && shown(&l) == 2, "{} {}", l.undashed, shown(&l)); +} + /// A block reference cut by an XCLIP boundary is drawn apart and then joined: a run in it drawn /// continuous is still counted. #[test] @@ -1696,8 +2723,104 @@ fn linetype_text_is_left_off_a_run_past_the_dash_budget() { let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(95.0, y, 0.0) }); d.add(&Space::Model, Common { linetype: "GAS".into(), ..Default::default() }, line).unwrap(); } - let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, 400); + let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 400); let each = prims_per_entity(&l); assert!(matches!(each.as_slice(), [first, 1] if *first > 101), "{each:?}"); assert_eq!(l.undashed, 1); } + +// ---------- fills past the even-odd fill cap (#3636) ---------- + +fn star(n: usize) -> Vec { + crate::fill::tests::star(n) +} + +/// A solid HATCH bounded by the star of `n` points. +fn star_hatch(n: usize) -> Hatch { + let vertices = star(n).into_iter().map(PolyVertex::new).collect(); + let loops = vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }]; + Hatch { solid: true, pattern: "SOLID".into(), loops, ..pattern_hatch("SOLID", 1.0, (0.0, 0.0, 1.0, 1.0)) } +} + +fn drawing_of(kind: EntityKind) -> Drawing { + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), kind).unwrap(); + d +} + +fn built(d: &Drawing) -> DisplayList { + build(d, &Space::Model, &Options::default()) +} + +/// A solid fill whose triangles pass the fill cap is drawn up to it, and the list says the rest is +/// left out: the 251-point star is filled only below its middle. The 121-point star is filled +/// whole and leaves nothing out (#3636). +#[test] +fn a_solid_fill_past_the_fill_cap_marks_the_list_truncated() { + let whole = built(&drawing_with(star_hatch(121))); + assert!(!whole.truncated && whole.tris.len() > 2_000_000, "{}", whole.tris.len()); + let cut = built(&drawing_with(star_hatch(251))); + let top = cut.tris.iter().map(|p| p.y).fold(f64::MIN, f64::max); + assert!(cut.truncated && cut.tris.len() > 6_000_000 && top < 100.0, "{} points up to y = {top}", cut.tris.len()); +} + +/// A hatch's background past the fill cap marks the list too; its pattern lines are drawn. +#[test] +fn hatch_backgrounds_past_the_fill_cap_mark_the_list_truncated() { + let hatch = |n| Hatch { solid: false, pattern: "ANSI31".into(), scale: 2000.0, background: Some(Color::Index(5)), ..star_hatch(n) }; + let whole = built(&drawing_with(hatch(21))); + assert!(!whole.truncated && whole.prims.iter().any(|p| p.kind == Kind::Tris)); + let cut = built(&drawing_with(hatch(251))); + assert!(cut.truncated && cut.prims.iter().any(|p| p.kind == Kind::Polyline)); +} + +/// A multiline's fill past the fill cap marks the list. +#[test] +fn multiline_fills_past_the_fill_cap_mark_the_list_truncated() { + let def = cadcraft_doc::MLineStyle { fill: Some(Color::Index(3)), ..Default::default() }; + let mline = |n| EntityKind::MLine(cadcraft_doc::MLine::new(&def, &star(n), true, cadcraft_doc::MLineJust::Zero, 1.0)); + let whole = built(&drawing_of(mline(21))); + assert!(!whole.truncated && whole.prims.iter().any(|p| p.kind == Kind::Tris)); + assert!(built(&drawing_of(mline(251))).truncated); +} + +/// A wipeout's mask past the fill cap marks the list: it hides less than its outline. +#[test] +fn wipeouts_past_the_fill_cap_mark_the_list_truncated() { + let wipeout = |n| EntityKind::Wipeout(cadcraft_doc::Wipeout { boundary: star(n) }); + assert!(!built(&drawing_of(wipeout(21))).truncated); + let cut = built(&drawing_of(wipeout(251))); + assert!(cut.truncated && cut.prims.iter().any(|p| p.kind == Kind::Mask)); +} + +/// A block of one solid square, `(x0, y0, x1, y1)`, drawn through an XCLIP boundary shaped as the +/// star of `n` points. +fn clipped_square(n: usize, (x0, y0, x1, y1): (f64, f64, f64, f64)) -> Drawing { + let mut d = Drawing::new_imperial(); + let mut blk = cadcraft_doc::Block::new("B"); + let corners = [(x0, y0), (x1, y0), (x0, y1), (x1, y1)].map(|(x, y)| Vec3::new(x, y, 0.0)); + blk.entities.push(block_entity(1, Common::default(), EntityKind::Solid(cadcraft_doc::Solid { corners }))); + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") }; + ins.clip = Some(cadcraft_doc::ClipBoundary::new(star(n))); + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + d +} + +fn fill_area(l: &DisplayList) -> f64 { + l.tris.as_chunks::<3>().0.iter().map(|t| cadcraft_geom::shoelace(t).abs()).sum() +} + +/// A clip region is cut into triangles to cut fills to it, and those triangles have the fill cap +/// too (#3636). Where they stop short, a fill the outline crosses is left out rather than drawn +/// past the outline, and the list says so: the 251-point star's triangles stop near its middle, +/// so a square across its outline near the top is not drawn. The 121-point star cuts it to the +/// part inside. +#[test] +fn fills_cut_to_a_clip_region_past_the_fill_cap_are_left_out_and_mark_the_list() { + let near_top = (-20.0, 900.0, 20.0, 940.0); + let whole = built(&clipped_square(121, near_top)); + assert!(!whole.truncated && fill_area(&whole) > 0.0 && fill_area(&whole) < 1600.0, "{}", fill_area(&whole)); + let cut = built(&clipped_square(251, near_top)); + assert!(cut.truncated && fill_area(&cut) == 0.0, "{}", fill_area(&cut)); +} diff --git a/crates/render/src/text_entity.rs b/crates/render/src/text_entity.rs index 417c1682d..3178737fd 100644 --- a/crates/render/src/text_entity.rs +++ b/crates/render/src/text_entity.rs @@ -37,8 +37,8 @@ fn text_params(d: &Drawing, t: &cadcraft_doc::Text) -> (cadcraft_fonts::TextFont oblique: t.oblique, h, v, - backwards: ts.backwards, - upside_down: ts.upside_down, + backwards: t.backwards, + upside_down: t.upside_down, }; (font, p) } @@ -81,13 +81,57 @@ fn mtext_color(c: Option, rgb: Ink) -> Ink { } } -pub(crate) fn mtext(b: &mut Builder, ctx: &Ctx, t: &cadcraft_doc::MText, rgb: Ink, lw: f32) { +pub(crate) fn mtext(b: &mut Builder, ctx: &Ctx, layer: &str, t: &cadcraft_doc::MText, rgb: Ink, lw: f32) { let l = layout_mtext_entity(ctx.d, t); + let layer_name = if layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { layer }; + let layer_color = ctx.layer_color(layer_name).unwrap_or(Color::Index(7)); + if b.opts.fill + && let Some(bg) = &t.background + && (bg.mask & 0x03) != 0 + && let Some([p0, p1, p2, p3]) = mtext_bg_quad(ctx.d, t, &l, bg.scale) + { + let n = b.list.prims.len(); + let use_mask = (bg.mask & 2) != 0 || bg.color.is_none(); + let fill_ink = match bg.color { + Some(c) if !use_mask => ink(c, layer_color, ctx.block_color), + _ => Ink { rgb: Rgb(255, 255, 255), aci7: false, aci: 0 }, + }; + b.tris(ctx, fill_ink, &[p0, p1, p2, p0, p2, p3]); + if use_mask && let Some(p) = b.list.prims.get_mut(n) { + p.kind = super::Kind::Mask; + } + } for p in &l.pieces { b.shaped(ctx, mtext_color(p.color, rgb), lw, &p.shaped); } } +fn mtext_bg_quad(d: &Drawing, t: &cadcraft_doc::MText, l: &cadcraft_fonts::MTextLayout, scale: f64) -> Option<[cadcraft_geom::Vec2; 4]> { + let rot = if t.rotation.is_finite() { t.rotation } else { 0.0 }; + let u_owned; + let u = if rot == 0.0 { + l + } else { + u_owned = layout_mtext_entity(d, &cadcraft_doc::MText { rotation: 0.0, background: None, ..t.clone() }); + &u_owned + }; + let mut bounds = u.bounds; + for q in u.strokes.iter().flatten() { + if q.is_finite() { + bounds.add(*q); + } + } + if !(bounds.width().is_finite() && bounds.height().is_finite()) || bounds.width() <= 0.0 || bounds.height() <= 0.0 { + return None; + } + let gap = (scale - 1.0).clamp(0.0, 4.0) * t.height.max(0.0); + let (lo, hi) = (bounds.min - cadcraft_geom::Vec2::new(gap, gap), bounds.max + cadcraft_geom::Vec2::new(gap, gap)); + let at = t.insert.xy(); + let (x, y) = (cadcraft_geom::Vec2::from_angle(rot), cadcraft_geom::Vec2::from_angle(rot).perp()); + let turn = |p: cadcraft_geom::Vec2| at + x * (p.x - at.x) + y * (p.y - at.y); + Some([turn(lo), turn(cadcraft_geom::Vec2::new(hi.x, lo.y)), turn(hi), turn(cadcraft_geom::Vec2::new(lo.x, hi.y))]) +} + /// A TEXT's justification as the fonts' alignment (used where text is placed outside a build). pub fn text_align(h: cadcraft_doc::HAlign, v: cadcraft_doc::VAlign) -> (cadcraft_fonts::Align, cadcraft_fonts::VAlign) { align(h, v) diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index e6c0bf79d..15f0872ae 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -1,13 +1,11 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::display::append; use super::display::{DImage, DPrim, DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT}; use super::draw::entity; #[cfg(not(target_arch = "wasm32"))] use super::pipeline::PARALLEL_CHUNK; use super::pipeline::{Options, style_table, top_ctx, with_point_view}; use super::{ - Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, - clip, paper, pen, plotstyle, + Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Fade, Handle, MAX_BLOCK_EXPANSION, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, + Mat3, Pen, Space, Vec2, clip, paper, pen, plotstyle, }; /// Upper bound on viewports drawn per layout (hostile files). @@ -70,8 +68,10 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds } let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t)); - let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); + let (points, prims, dashes) = + (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); let loops = std::sync::OnceLock::new(); + let fade = Fade::of(d); let mut b = Builder { list: DisplayList::default(), opts, @@ -82,9 +82,12 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds transparency: 0, points: &points, max_points: MAX_DISPLAY_POINTS, + prims: &prims, + max_prims: MAX_DISPLAY_PRIMS, dashes: &dashes, max_dashes: MAX_DASH_ELEMENTS, loops: &loops, + fade: fade.as_ref(), }; contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle)); b.list @@ -96,6 +99,12 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou if b.list.expanded >= MAX_BLOCK_EXPANSION || !vp.on { return; } + // A spent build draws nothing more: once its list says so, the model is not scanned (and its + // objects' bounds worked out) for nothing. A build spent by a list filled exactly has left + // nothing out yet: the scan still marks the list for the contents it can't draw. + if b.spent() && b.list.truncated { + return; + } let center = vp.center.xy(); let ok = |v: f64| v.is_finite() && v > 0.0; if !(ok(vp.width) && ok(vp.height) && ok(vp.view_height) && center.is_finite() && vp.view_center.is_finite()) { @@ -139,9 +148,12 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou transparency: 0, points: b.points, max_points: b.max_points, + prims: b.prims, + max_prims: b.max_prims, dashes: b.dashes, max_dashes: b.max_dashes, loops: b.loops, + fade: b.fade, }; #[cfg(not(target_arch = "wasm32"))] let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK; @@ -153,7 +165,8 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou // As `build_parallel`: chunks built side by side, joined in drawing order. use rayon::prelude::*; let ents: Vec<&std::sync::Arc> = d.model.iter().collect(); - let (opts, points, max_points, dashes, max_dashes, loops) = (b.opts, b.points, b.max_points, b.dashes, b.max_dashes, b.loops); + let (opts, points, max_points, prims, max_prims, dashes, max_dashes, loops, fade) = + (b.opts, b.points, b.max_points, b.prims, b.max_prims, b.dashes, b.max_dashes, b.loops, b.fade); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { @@ -167,9 +180,12 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou transparency: 0, points, max_points, + prims, + max_prims, dashes, max_dashes, loops, + fade, }; let c = ctx(); for me in chunk.iter().filter(|me| seen(me)) { @@ -178,9 +194,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou part.list }) .collect(); - for part in parts { - append(&mut sub.list, part); - } + sub.join(parts); } } else { let c = ctx(); @@ -199,12 +213,19 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou b.list.texts.push(PlotText { prim: PlotText::NONE, ..t }); } } - // The contents are in paper units now: draw their pens before clipping. - pen::apply(&mut sub.list, unit_mm); + // The contents are in paper units now: draw their pens before clipping, within the room the + // layout's list has left rather than the build's whole limit. Outlines that fit the contents' + // own list but not the layout's would stop the append part-way and spend the build, leaving + // out contents and layout objects whose plain lines fit. + let limits = b.limits(); + let room = limits.points.saturating_sub(b.list.verts.len().saturating_add(b.list.tris.len())); + pen::apply_within(&mut sub.list, unit_mm, room); b.list.expanded = b.list.expanded.saturating_add(sub.list.expanded); b.list.truncated |= sub.list.truncated; b.list.undashed = b.list.undashed.saturating_add(sub.list.undashed); - append_clipped(&mut b.list, &sub.list, clip); + if !append_clipped(&mut b.list, &sub.list, clip, limits) { + b.spend(); + } } /// The clip region of a clipped viewport: the outline of its clip boundary entity, when that @@ -217,13 +238,54 @@ pub fn viewport_clip(d: &Drawing, handle: Handle, vp: &cadcraft_doc::Viewport) - } /// `list` clipped to `clip` (a clipped viewport's outline in the list's own units), for a list -/// drawn inside a clipped viewport apart from its contents. +/// drawn inside a clipped viewport apart from its contents. It says what `list` left out +/// (`truncated`, `undashed`) and counts its block copies, as viewport contents do. pub fn clip_list(list: &DisplayList, clip: &clip::PolyClip) -> DisplayList { - let mut out = DisplayList::default(); - append_clipped(&mut out, list, &Clip::Poly(clip)); + let mut out = DisplayList { truncated: list.truncated, undashed: list.undashed, expanded: list.expanded, ..DisplayList::default() }; + append_clipped(&mut out, list, &Clip::Poly(clip), Limits::BUILD); out } +/// What one display list may hold. Clipping can cut one primitive into many pieces, each with +/// points of its own where it crosses the clip, and the build's budgets count the primitive, not +/// its pieces: the pieces appended to a list stop at these limits, which mark it truncated, and +/// what the build draws into a list afterwards checks them too. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Limits { + pub points: usize, + pub prims: usize, +} + +impl Limits { + /// A build's own limits: [`MAX_DISPLAY_POINTS`] and [`MAX_DISPLAY_PRIMS`]. + const BUILD: Limits = Limits { points: MAX_DISPLAY_POINTS, prims: MAX_DISPLAY_PRIMS }; + + /// Whether `list` has room for one more primitive of `n` points; when it has none, the list + /// is marked truncated. + pub(crate) fn room(self, list: &mut DisplayList, n: usize) -> bool { + let ok = list.prims.len() < self.prims && list.verts.len().saturating_add(list.tris.len()).saturating_add(n) <= self.points; + if !ok { + list.truncated = true; + } + ok + } + + /// The room `list` has left: what a clip appending to it may produce. + fn left(self, list: &DisplayList) -> clip::Cap { + let pieces = self.prims.saturating_sub(list.prims.len()); + let points = if pieces == 0 { 0 } else { self.points.saturating_sub(list.verts.len().saturating_add(list.tris.len())) }; + clip::Cap { points, pieces } + } +} + +/// `whole`, marking `list` truncated when it is false (a clip stopped at the room `list` had). +fn whole(list: &mut DisplayList, whole: bool) -> bool { + if !whole { + list.truncated = true; + } + whole +} + /// What viewport contents are clipped to. pub(crate) enum Clip<'a> { /// The viewport rectangle (the fast path). @@ -234,21 +296,21 @@ pub(crate) enum Clip<'a> { Outside(&'a clip::PolyClip), } -/// Append `src` to `dst`, clipped to `clip`. -pub(crate) fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { - for p in &src.prims { - clip_prim(dst, src, p, clip); - } +/// Append `src` to `dst`, clipped to `clip`, within `limits`; false once a piece did not fit +/// (`dst` is then marked truncated and nothing after that piece is appended). +pub(crate) fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip, limits: Limits) -> bool { + src.prims.iter().all(|p| clip_prim(dst, src, p, clip, limits)) } -/// Append `src` to `dst` clipped to `clip`, keeping each primitive's plot style pen and, for a -/// glyph that the clip leaves whole, its plotted text (an XCLIP-clipped block reference). -pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { +/// Append `src` to `dst` clipped to `clip` within `limits`, keeping each primitive's plot style +/// pen and, for a glyph that the clip leaves whole, its plotted text (an XCLIP-clipped block +/// reference); false once a piece did not fit, as [`append_clipped`]. +pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip: &Clip, limits: Limits) -> bool { let texts: std::collections::HashMap = src.texts.iter().filter(|t| t.prim != PlotText::NONE && t.prim != PlotText::CLIPPED).map(|t| (t.prim as usize, t)).collect(); for (i, p) in src.prims.iter().enumerate() { let first = dst.prims.len(); - clip_prim(dst, src, p, clip); + let fits = clip_prim(dst, src, p, clip, limits); // Each piece keeps its source's layer (block contents not on layer 0 keep theirs). if let Some(layer) = src.prim_layers.get(i).copied() { for k in first..dst.prims.len() { @@ -270,122 +332,118 @@ pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip { dst.texts.push(PlotText { prim, ..(**t).clone() }); } + if !fits { + return false; + } } + true } -/// Append primitive `p` of `src` to `dst`, clipped to `clip`. -fn clip_prim(dst: &mut DisplayList, src: &DisplayList, p: &DPrim, clip: &Clip) { - { - let pts = src.points(p); - match (p.kind, clip) { - (Kind::Polyline, Clip::Rect(rect)) => { - for piece in clip::clip_polyline(pts, rect) { - push_raw(dst, p, Kind::Polyline, &piece); - } +/// Append primitive `p` of `src` to `dst`, clipped to `clip`, within `limits`; false when a piece +/// did not fit (the pieces after it are not appended). +/// +/// Lines and fills are clipped within the room `dst` has left, since a clip can make far more +/// points than `p` has: the pieces, or the triangles, that fit are appended and the rest is left +/// out, without building it first. +fn clip_prim(dst: &mut DisplayList, src: &DisplayList, p: &DPrim, clip: &Clip, limits: Limits) -> bool { + let pts = src.points(p); + let cap = limits.left(dst); + let pieces = |dst: &mut DisplayList, (cut, all): (Vec>, bool)| { + cut.iter().all(|piece| push_raw(dst, p, Kind::Polyline, piece, limits)) && whole(dst, all) + }; + let fill = |dst: &mut DisplayList, (cut, all): (Vec, bool)| push_raw(dst, p, p.kind, &cut, limits) && whole(dst, all); + match (p.kind, clip) { + (Kind::Polyline, Clip::Rect(rect)) => pieces(dst, clip::clip_polyline_within(pts, rect, cap)), + (Kind::Polyline, Clip::Poly(c)) => pieces(dst, c.clip_polyline_within(pts, cap)), + (Kind::Polyline, Clip::Outside(c)) => pieces(dst, c.clip_polyline_outside_within(pts, cap)), + (Kind::Tris | Kind::Mask, Clip::Rect(rect)) => fill(dst, clip::clip_triangles_within(pts, rect, cap.points)), + (Kind::Tris | Kind::Mask, Clip::Poly(c)) => { + // Cut against region triangles that stop short: drawn as far as they reach (#3636). + dst.truncated |= c.may_leave_out(pts); + fill(dst, c.clip_triangles_within(pts, cap.points)) + } + (Kind::Tris | Kind::Mask, Clip::Outside(c)) => fill(dst, c.clip_triangles_outside_within(pts, cap.points)), + (Kind::Point, _) => { + let inside = |q: Vec2| match clip { + Clip::Rect(rect) => rect.contains(q), + Clip::Poly(c) => c.contains(q), + Clip::Outside(c) => !c.contains(q), + }; + match pts.first() { + Some(q) if inside(*q) => push_raw(dst, p, Kind::Point, &[*q], limits), + _ => true, } - (Kind::Polyline, Clip::Poly(c)) => { - for piece in c.clip_polyline(pts) { - push_raw(dst, p, Kind::Polyline, &piece); - } - } - (Kind::Polyline, Clip::Outside(c)) => { - for piece in c.clip_polyline_outside(pts) { - push_raw(dst, p, Kind::Polyline, &piece); - } - } - (Kind::Tris | Kind::Mask, Clip::Rect(rect)) => { - let t = clip::clip_triangles(pts, rect); - push_raw(dst, p, p.kind, &t); - } - (Kind::Tris | Kind::Mask, Clip::Poly(c)) => { - let t = c.clip_triangles(pts); - push_raw(dst, p, p.kind, &t); - } - (Kind::Tris | Kind::Mask, Clip::Outside(c)) => { - let t = c.clip_triangles_outside(pts); - push_raw(dst, p, p.kind, &t); - } - (Kind::Point, _) => { - let inside = |q: Vec2| match clip { - Clip::Rect(rect) => rect.contains(q), - Clip::Poly(c) => c.contains(q), - Clip::Outside(c) => !c.contains(q), - }; - if let Some(q) = pts.first() - && inside(*q) - { - push_raw(dst, p, Kind::Point, &[*q]); - } - } - (Kind::Image { index }, _) => { - if let Some(img) = src.images.get(index as usize) { - push_clipped_image(dst, p, img, pts, clip); - } - } - (Kind::Infinite { ray }, Clip::Rect(rect)) => { - if let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) - && let Some((a, c)) = clip::clip_infinite(*base, *dir, ray, rect) - { - push_raw(dst, p, Kind::Polyline, &[a, c]); - } - } - (Kind::Infinite { ray }, Clip::Poly(c)) => { - if let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) { - for piece in c.clip_infinite(*base, *dir, ray) { - push_raw(dst, p, Kind::Polyline, &piece); - } - } - } - (Kind::Infinite { ray }, Clip::Outside(c)) => { - if let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) { - for piece in c.clip_infinite_outside(*base, *dir, ray) { - push_raw(dst, p, Kind::Polyline, &piece); - } - } + } + (Kind::Image { index }, _) => match src.images.get(index as usize) { + Some(img) => push_clipped_image(dst, p, img, pts, clip, limits), + None => true, + }, + (Kind::Infinite { ray }, _) => { + let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) else { return true }; + match clip { + Clip::Rect(rect) => match clip::clip_infinite(*base, *dir, ray, rect) { + Some((a, c)) => push_raw(dst, p, Kind::Polyline, &[a, c], limits), + None => true, + }, + // A line or ray has two points: its pieces are at most one per outline edge. + Clip::Poly(c) => pieces(dst, (c.clip_infinite(*base, *dir, ray), true)), + Clip::Outside(c) => pieces(dst, (c.clip_infinite_outside(*base, *dir, ray), true)), } } } } /// Append image `img` (primitive `p`, corners `corners`) to `dst`, to be cut to `clip` when it -/// is drawn: the picture is not cut here, the outline is added to those it carries. -fn push_clipped_image(dst: &mut DisplayList, p: &DPrim, img: &DImage, corners: &[Vec2], clip: &Clip) { +/// is drawn: the picture is not cut here, the outline is added to those it carries. False when +/// it did not fit. +fn push_clipped_image(dst: &mut DisplayList, p: &DPrim, img: &DImage, corners: &[Vec2], clip: &Clip, limits: Limits) -> bool { let (outline, area) = match clip { Clip::Rect(rect) => (vec![rect.min, Vec2::new(rect.max.x, rect.min.y), rect.max, Vec2::new(rect.min.x, rect.max.y)], *rect), Clip::Poly(c) => (c.polygon().to_vec(), c.bounds()), // An image can only be cut to the inside of an outline: under an inverted XCLIP it is // drawn whole, which shows too much rather than losing any of it. Clip::Outside(_) => { - let Ok(index) = u32::try_from(dst.images.len()) else { return }; + let Ok(index) = u32::try_from(dst.images.len()) else { return true }; + if !limits.room(dst, corners.len()) { + return false; + } dst.images.push(img.clone()); - push_raw(dst, p, Kind::Image { index }, corners); - return; + return push_raw(dst, p, Kind::Image { index }, corners, limits); } }; let own = Bounds2::from_points(corners.iter().copied()); if !own.intersects(&area) { - return; + return true; } - let Ok(index) = u32::try_from(dst.images.len()) else { return }; + if !limits.room(dst, corners.len()) { + return false; + } + let Ok(index) = u32::try_from(dst.images.len()) else { return true }; let mut img = img.clone(); img.clips.push(outline); dst.images.push(img); // The list's bounds take only the part inside the clip, as for the other primitives. let before = dst.bounds; - push_raw(dst, p, Kind::Image { index }, corners); + let fits = push_raw(dst, p, Kind::Image { index }, corners, limits); dst.bounds = before; dst.bounds.add(own.min.max(area.min)); dst.bounds.add(own.max.min(area.max)); + fits } -fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2]) { +/// Append one piece; false when `dst` has no room for it ([`Limits::room`]). A piece too short +/// to draw is left out and counts as appended. +fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2], limits: Limits) -> bool { let min = match kind { Kind::Polyline => 2, Kind::Tris | Kind::Mask => 3, _ => 1, }; if pts.len() < min { - return; + return true; + } + if !limits.room(dst, pts.len()) { + return false; } let tris = matches!(kind, Kind::Tris | Kind::Mask); let start = if tris { dst.tris.len() } else { dst.verts.len() } as u32; @@ -407,4 +465,5 @@ fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2]) { start, len: pts.len() as u32, }); + true } diff --git a/crates/render/tests/it/annotative_orientation.rs b/crates/render/tests/it/annotative_orientation.rs index ee28b0624..77ab5e0cb 100644 --- a/crates/render/tests/it/annotative_orientation.rs +++ b/crates/render/tests/it/annotative_orientation.rs @@ -35,6 +35,8 @@ fn bounds(rotation: f64, match_orientation: Option<&str>) -> Bounds2 { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; d.add(&Space::Model, common, EntityKind::Text(text)).unwrap(); let l = build(&d, &Space::Model, &Options::default()); diff --git a/crates/render/tests/it/annotative_viewport.rs b/crates/render/tests/it/annotative_viewport.rs index 1e93b1a6b..1f1c675a8 100644 --- a/crates/render/tests/it/annotative_viewport.rs +++ b/crates/render/tests/it/annotative_viewport.rs @@ -35,6 +35,8 @@ fn drawing(scale: f64, all_visible: bool) -> Drawing { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; d.add(&Space::Model, anno, EntityKind::Text(text)).unwrap(); d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(viewport(50.0, scale))).unwrap(); diff --git a/crates/render/tests/it/dim_text_fill.rs b/crates/render/tests/it/dim_text_fill.rs index 46028a576..e13b44e2a 100644 --- a/crates/render/tests/it/dim_text_fill.rs +++ b/crates/render/tests/it/dim_text_fill.rs @@ -149,6 +149,7 @@ fn a_dimension_read_with_its_block_keeps_the_block_and_gets_the_background() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; blk.entities.push(Entity::new(Handle(2), EntityKind::MText(text))); d.blocks.insert("*D1".into(), std::sync::Arc::new(blk)); @@ -181,6 +182,7 @@ fn every_text_of_a_block_gets_a_background() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; blk.entities.push(Entity::new(Handle(i as u64 + 1), EntityKind::MText(text))); } @@ -211,6 +213,7 @@ fn a_block_that_holds_its_background_gets_no_second_one() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; blk.entities.push(Entity::new(Handle(2), EntityKind::MText(text))); d.blocks.insert("*D1".into(), std::sync::Arc::new(blk)); @@ -241,6 +244,8 @@ fn a_block_with_turned_text_gets_a_turned_background() { style: "Standard".into(), halign: Default::default(), valign: Default::default(), + backwards: false, + upside_down: false, }; blk.entities.push(Entity::new(Handle(1), EntityKind::Text(text))); d.blocks.insert("*D1".into(), std::sync::Arc::new(blk)); diff --git a/crates/render/tests/it/plot_line_styles.rs b/crates/render/tests/it/plot_line_styles.rs index b0abc6702..5a803cfdd 100644 --- a/crates/render/tests/it/plot_line_styles.rs +++ b/crates/render/tests/it/plot_line_styles.rs @@ -167,6 +167,9 @@ fn viewport_contents_get_their_pens() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; let space = Space::Paper("Layout1".into()); diff --git a/crates/render/tests/it/psltscale.rs b/crates/render/tests/it/psltscale.rs index ed0f17ea5..baaf89cf7 100644 --- a/crates/render/tests/it/psltscale.rs +++ b/crates/render/tests/it/psltscale.rs @@ -25,6 +25,9 @@ fn drawing(psltscale: i64) -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/tests/it/render_props.rs b/crates/render/tests/it/render_props.rs index b0361c21f..29660b10e 100644 --- a/crates/render/tests/it/render_props.rs +++ b/crates/render/tests/it/render_props.rs @@ -63,6 +63,9 @@ fn dimensions_take_the_viewport_layer_colour() { layer_colors: vec![("a".into(), Color::Index(3))], clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); @@ -111,6 +114,8 @@ fn text(x: f64, value: &str) -> Text { style: "Standard".into(), halign: HAlign::Left, valign: VAlign::Baseline, + backwards: false, + upside_down: false, } } diff --git a/crates/render/tests/it/viewport_frozen_layer.rs b/crates/render/tests/it/viewport_frozen_layer.rs index 876b33574..30879e4f4 100644 --- a/crates/render/tests/it/viewport_frozen_layer.rs +++ b/crates/render/tests/it/viewport_frozen_layer.rs @@ -21,6 +21,9 @@ fn drawing() -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common { layer: "VPORTS".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/tests/raster_image.rs b/crates/render/tests/raster_image.rs index 2572fcf72..a76fccb27 100644 --- a/crates/render/tests/raster_image.rs +++ b/crates/render/tests/raster_image.rs @@ -258,6 +258,9 @@ fn a_layout_viewport_cuts_the_image_to_its_outline() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index d5dfe75db..27a78e61f 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -39,6 +39,8 @@ web-time = { workspace = true } craft-update = { workspace = true } [dev-dependencies] +# `Updater::ready_for_tests`. +craft-update = { workspace = true, features = ["screen-testing"] } # The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in # production too; the tests exercise the same installed chain as the app. egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 3116b01db..95e3a15ae 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -1,4 +1,4 @@ -//! Bake the contributor credits into the binary as static Rust tables. Nothing is read at run time. +//! Bake the contributor credits and validate the shared Chinese overlay at build time. //! //! - contributors/contributors.json: commit stats per GitHub username, with a mark for whose people.toml //! entry is verified. @@ -11,7 +11,11 @@ use std::fmt::Write as _; use serde_json::Value; +const SHARED_ZH: &str = "src/i18n/zh_shared.tsv"; +const SHARED_ZH_KEY: &str = "Construction Geometry"; + fn main() { + verify_shared_zh(); let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contributors"); let json = read(&dir.join("contributors.json"), "the About window shows no contributors", |t| { serde_json::from_str::(t).map_err(|e| e.to_string()) @@ -25,6 +29,52 @@ fn main() { } } +// Local/offline builds use the checked-in projection. Hosted and release builds with +// craft-i18n.rev also check it against their canonical craft-i18n checkout. +fn verify_shared_zh() { + println!("cargo::rerun-if-env-changed=CRAFT_I18N_DIR"); + println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED"); + println!("cargo::rerun-if-changed={SHARED_ZH}"); + let result = projected_row(include_str!("src/i18n/zh_shared.tsv")).and_then(verify_checkout); + if let Err(e) = result { + println!("cargo::error=shared Simplified Chinese catalog: {e}"); + } +} + +fn projected_row(projection: &str) -> Result<&str, String> { + let mut rows = projection.lines().filter(|line| !line.is_empty() && !line.starts_with('#')); + let Some(row) = rows.next() else { + return Err(format!("missing projected key {SHARED_ZH_KEY:?}")); + }; + let valid = row + .strip_prefix('\t') + .and_then(|rest| rest.split_once('\t')) + .is_some_and(|(key, value)| key == SHARED_ZH_KEY && !value.trim().is_empty() && !value.contains(['\t', '\\', '\r'])); + if rows.next().is_some() || !valid { + return Err(format!("expected exactly one ordinary literal row for {SHARED_ZH_KEY:?}")); + } + Ok(row) +} + +fn verify_checkout(projected: &str) -> Result<(), String> { + let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v.trim() == "1"); + let Some(dir) = std::env::var_os("CRAFT_I18N_DIR").filter(|dir| !dir.is_empty()) else { + return if required { Err("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR is unset".to_string()) } else { Ok(()) }; + }; + let dir = std::path::PathBuf::from(dir); + if !dir.is_absolute() { + return Err("CRAFT_I18N_DIR must be an absolute path".to_string()); + } + let catalog = dir.join("locales/zh-hans/cadcraft.tsv"); + println!("cargo::rerun-if-changed={}", catalog.display()); + let source = std::fs::read_to_string(&catalog).map_err(|e| format!("reading {}: {e}", catalog.display()))?; + let mut rows = source.lines().filter(|row| row.strip_prefix('\t').is_some_and(|rest| rest.split('\t').next() == Some(SHARED_ZH_KEY))); + if rows.next() != Some(projected) || rows.next().is_some() { + return Err(format!("projected key {SHARED_ZH_KEY:?} is missing, duplicated or differs from the checked-out source")); + } + Ok(()) +} + fn read(path: &std::path::Path, fallback: &str, parse: impl Fn(&str) -> Result) -> Option { println!("cargo::rerun-if-changed={}", path.display()); let r = std::fs::read_to_string(path).map_err(|e| e.to_string()).and_then(|t| parse(&t)); diff --git a/crates/ui-egui/src/attedit.rs b/crates/ui-egui/src/attedit.rs new file mode 100644 index 000000000..6735d45da --- /dev/null +++ b/crates/ui-egui/src/attedit.rs @@ -0,0 +1,324 @@ +//! The Attribute Editor dialog: ATTEDIT / EATTEDIT typed or started +//! from a menu while one block reference with attributes is selected. It lists each attribute's +//! tag, prompt and value; Apply and OK run `attedit {handle, at}` with the values changed (one +//! undo step each). With nothing suitable selected ATTEDIT asks at the command line instead, and +//! JSON calls never open the dialog. + +use cadcraft_engine::doc::{Drawing, EntityKind, Handle}; +use egui::{RichText, vec2}; +use serde_json::{Map, Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// One attribute row: what the drawing had when the dialog opened, and what is typed now. +#[derive(Clone, Debug)] +pub struct Row { + pub tag: String, + pub prompt: String, + pub value: String, + pub editable: bool, + pub invisible: bool, + pub multiline: bool, + /// The whole attribute the row was loaded from (see `cadcraft_engine::AttributeRow`): a row + /// index is only the attribute's place in the reference, and a reorder of the block's + /// definitions moves a different attribute — the same tag, value and insertion point is not + /// enough to tell them apart. + pub record: cadcraft_engine::doc::Attrib, + pub typed: String, +} + +impl Row { + /// Whether `a` is still the attribute this row was loaded from: the whole stored attribute must + /// be equal, so a property the dialog doesn't show (text height, rotation, justification, + /// style, the attribute's own overrides) tells a reordered one apart too. + fn is(&self, a: &cadcraft_engine::AttributeRow) -> bool { + self.record == a.record + } +} + +/// The dialog's state while it is open. +#[derive(Default)] +pub struct State { + /// The block reference edited. + pub handle: Option, + /// The drawing it is in (`DocState::uid`): handles repeat across drawings, and the dialog + /// doesn't stop another drawing's tab from being chosen. + pub doc: Option, + /// Its block's name (the dynamic block's for a dynamic block reference). + pub block: String, + pub rows: Vec, + /// The row that is current: shown in bold, and its value box takes the focus when the + /// dialog opens (the attribute double-clicked). + pub current: Option, + /// The current row's value box still has to take the focus. + pub focus: bool, + /// Why the last Apply failed. + pub error: Option, +} + +/// The block reference the dialog edits: the selection as the active viewport shows it when that +/// is exactly one block reference with an attribute that can be changed. +fn selected_reference(app: &CadApp) -> Option { + let selection = app.session.selection(); + let [h] = selection.as_slice() else { return None }; + let st = app.session.state().ok()?; + matches!(st.doc.entity(*h).map(|e| &e.kind), Some(EntityKind::Insert(_))).then_some(*h)?; + cadcraft_engine::attributes(&st.doc, *h).iter().any(|a| a.editable).then_some(*h) +} + +/// The name shown for block reference `h`: its dynamic block's, not its anonymous copy's. +fn block_name(d: &Drawing, h: Handle) -> String { + if let Some(r) = cadcraft_engine::doc::dynblock::reference(d, h) { + return r.definition; + } + match d.entity(h).map(|e| &e.kind) { + Some(EntityKind::Insert(i)) => i.block.clone(), + _ => String::new(), + } +} + +/// Load the rows of block reference `h`. +fn load(app: &mut CadApp, h: Handle) { + let Ok(st) = app.session.state() else { return }; + let rows = cadcraft_engine::attributes(&st.doc, h) + .into_iter() + .map(|a| Row { + typed: a.value.clone(), + tag: a.tag, + prompt: a.prompt, + value: a.value, + editable: a.editable, + invisible: a.invisible, + multiline: a.multiline, + record: a.record, + }) + .collect(); + let current = app.attedit.current; + app.attedit = State { handle: Some(h), doc: Some(st.uid), block: block_name(&st.doc, h), rows, current, focus: false, error: None }; +} + +/// Open the dialog on block reference `h` of the active drawing, with attribute `current` (an +/// index into its attributes, in `cadcraft_engine::attributes` order) current; without one, or +/// when that attribute can't be changed, the first one that can. False, and nothing opens, when +/// `h` is not a block reference with an attribute that can be changed. +pub fn open(app: &mut CadApp, h: Handle, current: Option) -> bool { + let Ok(st) = app.session.state() else { return false }; + if !matches!(st.doc.entity(h).map(|e| &e.kind), Some(EntityKind::Insert(_))) { + return false; + } + let attribs = cadcraft_engine::attributes(&st.doc, h); + let Some(first) = attribs.iter().position(|a| a.editable) else { return false }; + let current = current.filter(|i| attribs.get(*i).is_some_and(|a| a.editable)).unwrap_or(first); + app.attedit.current = Some(current); + load(app, h); + app.attedit.focus = true; + app.ui.dialog = Some("attedit".into()); + true +} + +/// The block reference the dialog edits, while the drawing it was opened for is the active one +/// and still has it. +fn edited(app: &CadApp) -> Option { + let h = app.attedit.handle?; + let st = app.session.state().ok()?; + (Some(st.uid) == app.attedit.doc && st.doc.entity(h).is_some()).then_some(h) +} + +/// ATTEDIT / EATTEDIT opens the dialog when one editable reference is selected. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if !matches!(id, "attedit" | "ate" | "eattedit") || !params.is_null() { + return None; + } + let h = selected_reference(app)?; + if app.session.prompting() { + app.session.cancel(); + } + if app.session.prompting() { + app.session.echo(crate::tl!("ATTEDIT: another command is still active.")); + return Some(Err("another command is still active".into())); + } + app.session.echo(format!("Command: {}", id.to_ascii_uppercase())); + open(app, h, None).then_some(Ok(Value::Null)) +} + +/// The values typed that differ from the drawing's, as `attedit`'s `at` (by row, so attributes +/// sharing a tag stay apart). +fn changed(rows: &[Row]) -> Map { + rows.iter().enumerate().filter(|(_, r)| r.editable && r.typed != r.value).map(|(i, r)| (i.to_string(), Value::String(r.typed.clone()))).collect() +} + +/// True while the reference's attributes are still the ones the dialog listed: every stored +/// property of every row's attribute, its place included (two attributes can share a tag and a +/// value, and a reorder of the block's definitions swaps those). +fn rows_unchanged(app: &CadApp, h: Handle) -> bool { + let Ok(st) = app.session.state() else { return false }; + let now = cadcraft_engine::attributes(&st.doc, h); + now.len() == app.attedit.rows.len() && now.iter().zip(&app.attedit.rows).all(|(a, r)| r.is(a)) +} + +/// Apply: run `attedit` with the changed values; true when it went through (or nothing changed). +pub fn apply(app: &mut CadApp) -> bool { + let Some(h) = edited(app) else { return false }; + let values = changed(&app.attedit.rows); + if values.is_empty() { + return true; + } + if !rows_unchanged(app, h) { + // Another command reordered, renamed or edited the attributes while the dialog was open: + // a row index would address a different attribute now. Show what the drawing has, and say + // in the dialog and on the command line why nothing was written. + load(app, h); + let msg = crate::tl!("The attributes changed while this dialog was open. Review them and apply again.").to_string(); + app.session.echo(msg.clone()); + app.attedit.error = Some(msg); + return false; + } + match app.run("attedit", json!({ "handle": h.hex(), "at": values })) { + Ok(_) => { + load(app, h); + true + } + Err(e) => { + app.attedit.error = Some(e); + false + } + } +} + +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + // The reference went away (undo, erase from the command line) or another drawing is active: + // nothing to edit. + if edited(app).is_none() { + *open = false; + return; + } + let t = Tokens::get(); + let mut choice: Option<&str> = None; + let st = &mut app.attedit; + egui::Window::new(crate::tl!("Attribute Editor")) + .id(egui::Id::unique("Attribute Editor")) + .open(open) + .collapsible(false) + .resizable(true) + .default_width(460.0) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(crate::tl!("Block:")).color(t.text_dim)); + ui.label(&st.block); + }); + ui.add_space(6.0); + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { + egui::Grid::new("attedit-rows").num_columns(3).striped(true).spacing(vec2(12.0, 4.0)).show(ui, |ui| { + ui.label(RichText::new(crate::tl!("Tag")).color(t.text_dim)); + ui.label(RichText::new(crate::tl!("Prompt")).color(t.text_dim)); + ui.label(RichText::new(crate::tl!("Value")).color(t.text_dim)); + ui.end_row(); + for (i, r) in st.rows.iter_mut().enumerate() { + let current = st.current == Some(i); + let tag = if r.invisible { format!("{} ({})", r.tag, crate::i18n::t("invisible")) } else { r.tag.clone() }; + let tag_label = ui.label(if current { RichText::new(tag).strong() } else { RichText::new(tag) }); + ui.label(&r.prompt); + let edit = if r.multiline || r.value.contains(['\n', '\r']) { + egui::TextEdit::multiline(&mut r.typed).desired_rows(2) + } else { + egui::TextEdit::singleline(&mut r.typed) + }; + let resp = ui.add_enabled(r.editable, edit.desired_width(220.0)).labelled_by(tag_label.id); + if resp.has_focus() { + st.current = Some(i); + } + if current && st.focus { + resp.request_focus(); + resp.scroll_to_me(Some(egui::Align::Center)); + st.focus = false; + } + if !r.editable { + let _ = resp.on_disabled_hover_text(crate::tl!("Constant")); + } + ui.end_row(); + } + }); + }); + if let Some(e) = &st.error { + ui.add_space(4.0); + ui.colored_label(t.warn, e); + } + ui.add_space(8.0); + ui.horizontal(|ui| { + let dirty = !changed(&st.rows).is_empty(); + if ui.button(crate::tl!("OK")).clicked() { + choice = Some("ok"); + } + if ui.button(crate::tl!("Cancel")).clicked() { + choice = Some("cancel"); + } + if ui.add_enabled(dirty, egui::Button::new(crate::tl!("Apply"))).clicked() { + choice = Some("apply"); + } + }); + }); + match choice { + Some("ok") => { + if apply(app) { + *open = false; + } + } + Some("apply") => { + apply(app); + } + Some(_) => *open = false, + None => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_geom::Vec3; + + fn row(tag: &str, value: &str, typed: &str, editable: bool) -> Row { + Row { + tag: tag.into(), + prompt: String::new(), + value: value.into(), + editable, + invisible: false, + multiline: false, + record: cadcraft_engine::doc::Attrib { + tag: tag.into(), + text: cadcraft_engine::doc::Text { + insert: Vec3::ZERO, + align_pt: None, + height: 1.0, + value: value.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: cadcraft_engine::doc::HAlign::Left, + valign: cadcraft_engine::doc::VAlign::Baseline, + backwards: false, + upside_down: false, + }, + invisible: false, + constant: !editable, + prompt: String::new(), + props: cadcraft_engine::doc::AttribProps::default(), + multiline: None, + modes: cadcraft_engine::doc::AttribModes::default(), + }, + typed: typed.into(), + } + } + + #[test] + fn only_changed_editable_values_are_sent() { + let rows = [row("A", "1", "1", true), row("B", "2", "3", true), row("C", "x", "y", false)]; + let v = changed(&rows); + assert_eq!(v.len(), 1); + assert_eq!(v.get("1"), Some(&json!("3"))); + } +} diff --git a/crates/ui-egui/src/autosave.rs b/crates/ui-egui/src/autosave.rs index de05d9447..24d717de1 100644 --- a/crates/ui-egui/src/autosave.rs +++ b/crates/ui-egui/src/autosave.rs @@ -96,12 +96,19 @@ impl CadApp { } } - /// Every frame: autosave what is due, and wake up when the next one is. + /// Every frame: autosave what is due and keep the drawing locks, and wake up when the next + /// autosave or lock heartbeat is. pub fn autosave_tick(&mut self, _ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] if let Some(wait) = self.autosave.as_mut().and_then(|s| s.tick(&self.session)) { _ctx.request_repaint_after(wait); } + // A drawing someone else has open (its lock, `cadcraft_engine::drawlock`): say so. + #[cfg(not(target_arch = "wasm32"))] + for note in self.autosave.as_mut().map(|s| s.take_lock_notes()).unwrap_or_default() { + self.session.echo(note.clone()); + self.set_status(note); + } #[cfg(not(target_arch = "wasm32"))] { // A write that fails while the app is idle must still reach the notice. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b8bc67428..0a654d64b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -12,6 +12,7 @@ use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, pos2, vec2}; use crate::CadApp; use crate::theme::Tokens; +mod area_fill; mod cursor; mod cycle; mod draw; @@ -24,6 +25,7 @@ mod press; mod viewport; mod widgets; +use area_fill::{AreaPreviewCache, area_preview_fill}; use cursor::{draw_crosshair, draw_snap_marker, draw_tracking, effective_point, override_cursor}; use cycle::{CycleList, cycle_badge, cycle_click, cycle_list, over_canvas_menu, shift_space_cycle}; pub(crate) use draw::{Look, draw_highlight, draw_list}; @@ -31,7 +33,7 @@ use draw::{dashed_polygon, dashed_rect, draw_drag_gpu, draw_highlight_gpu, draw_ use dyn_boxes::dynamic_input; pub(crate) use dyn_boxes::length_units; use grid::draw_grid; -use grips::{click_grip, grip_at, grip_menu, grip_options, grip_rect}; +use grips::{click_grip, draw_selection_grips, grip_at, grip_menu, grip_options}; use list::{OnlyList, PrimIndex, ensure_list, rebuilt_preview}; #[cfg(test)] use list::{preview_options, prims_of}; @@ -102,6 +104,8 @@ fn same_content(a: &ListKey, b: &ListKey) -> bool { #[derive(Default)] pub struct CanvasState { pub list: Option, + /// AREA's fixed selected-edge validation, reused across cursor movements. + area_preview_cache: AreaPreviewCache, /// The font set the list was drawn with ([`cadcraft_fonts::ttf::generation`] and /// [`cadcraft_fonts::shx::generation`]): a new font folder redraws the text. font_generation: u64, @@ -236,6 +240,20 @@ impl CanvasState { self.job.is_some() } + /// Snapshot of the cached GPU mesh keys and vertex origins across the drawing, active + /// layout viewport, and selection highlight layers. + #[doc(hidden)] + pub fn gpu_mesh_state(&self) -> GpuMeshState { + GpuMeshState { + drawing_key: self.mesh_key, + drawing_origin: self.mesh_origin, + viewport_key: self.vp.mesh_key, + viewport_origin: self.vp.mesh_origin, + highlight_key: self.hl_key, + highlight_origin: self.hl_origin, + } + } + /// Put a finished background build in place, with its GPU vertex data when it has some. fn install(&mut self, key: ListKey, window: Option, built: rebuild::Built) { self.list_gen = self.list_gen.wrapping_add(1); @@ -255,6 +273,19 @@ impl CanvasState { } } +/// Snapshot of the cached GPU mesh keys and vertex origins across the drawing, active layout +/// viewport, and selection highlight layers. +#[doc(hidden)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpuMeshState { + pub drawing_key: Option, + pub drawing_origin: Vec2, + pub viewport_key: Option, + pub viewport_origin: Vec2, + pub highlight_key: Option, + pub highlight_origin: Vec2, +} + /// Tab cycling through the candidate snaps under the cursor: where it started and which /// candidate shows. Moving the cursor out of the aperture ends it. #[derive(Clone, Copy, Debug)] @@ -287,7 +318,11 @@ fn navigate_canvas(app: &mut CadApp, ui: &mut egui::Ui, nav: &Navigation<'_>) -> let p = nav.pointer; let inside = p.hover_pos.is_some_and(|at| nav.rect.contains(at) && ui.ctx().layer_id_at(at) == Some(ui.layer_id()) && nav.response.hovered()); let on_menu = p.hover_pos.is_some_and(|at| over_canvas_menu(app, at)); + if p.mods.shift != app.session.shift_down || p.mods.ctrl != app.session.ctrl_down { + ui.ctx().request_repaint(); + } app.session.ctrl_down = p.mods.ctrl; + app.session.shift_down = p.mods.shift; ui.input(|i| { for event in &i.raw.events { if let egui::Event::MouseWheel { unit, .. } = event { @@ -1255,6 +1290,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) { app.canvas.draw_ms = crate::now_ms() - t0; compare::paint(app, ui.ctx(), painter, &xf_paper, rect); blockedit::paint(app, ui.ctx(), painter, &xf_paper, rect); + refedit::paint(app, ui.ctx(), rect); // Constraint bars and dynamic dimensional constraints (model space, or inside a viewport). if sheet.is_none() || active_vp.is_some() { let clip = match &active_vp { @@ -1270,50 +1306,13 @@ fn paint_canvas(frame: CanvasPaint<'_>) { } else { crate::parametric::dismiss_inline(app, ui.ctx()); } - // Grips on selected objects (when idle or editing grips). - let grip_edit = app.session.running.as_ref().is_some_and(|r| r.id == "grip"); - if (!grip_edit && (app.canvas.grip_editing || app.session.prompting())) || sel.is_empty() { - app.canvas.hot_grips.clear(); - } - if !grip_edit { - app.canvas.dyn_hot = None; - } - app.canvas.grip_editing = grip_edit; - if (!app.session.prompting() || grip_edit) - && app.session.shows_grips(sel.len()) - && let Ok(st) = app.session.state() - { - let gs = app.session.settings.gripsize as f32; - for h in sel.iter().take(200) { - if let Some(e) = st.doc.entity(*h) - && st.shows(e) - { - let grips = e.kind.grips(); - let count = grips.len(); - for (gi, g) in grips.into_iter().enumerate() { - let sp = xf.to_screen(g); - if rect.contains(sp) { - let r = grip_rect(&e.kind, count, gi, sp, gs); - let hot = app.canvas.hot_grips.contains(&(*h, gi)); - let warm = !hot && hover_pos.is_some_and(|hp| r.expand(2.0).contains(hp)); - painter.rect_filled( - r, - 0.0, - if hot { - t.grip_hot - } else if warm { - Color32::from_rgb(0xff, 0x7f, 0x9f) - } else { - t.grip - }, - ); - painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80)), egui::StrokeKind::Middle); - } - } - } - } - crate::dyngrips::draw(app, painter, &xf, rect, hover_pos); + draw_selection_grips(app, painter, &xf, rect, hover_pos, t); + // Do not retain AREA validation across separate commands. The exact + // coordinates in the cache key also cover Undo and changed selections. + if app.session.active_command_id() != Some("area") { + app.canvas.area_preview_cache.clear(); } + // Rubber band preview of the active command. // `xf` is the space being edited: paper space, or model space inside the active viewport. // While the Array window is open the pointer is over it, so fall back to the last canvas @@ -1337,6 +1336,10 @@ fn paint_canvas(frame: CanvasPaint<'_>) { if !ents.is_empty() && let Ok(st) = app.session.state() { + // Paint translucent AREA fill below the unchanged rubber-band outline. + if let Some(mesh) = area_preview_fill(app.session.active_command_id(), &ents, &xf, &mut app.canvas.area_preview_cache) { + painter.add(Shape::mesh(mesh)); + } let list = rebuilt_preview(&st.doc, ents.iter(), scale); draw_list(painter, &xf, &list, bg, false); } @@ -1395,3 +1398,5 @@ mod compare; /// Background rebuilds of the display list for a new view. mod images; mod rebuild; +/// The Edit Reference bar while a reference is edited in place (REFEDIT). +mod refedit; diff --git a/crates/ui-egui/src/canvas/area_fill.rs b/crates/ui-egui/src/canvas/area_fill.rs new file mode 100644 index 000000000..0932a3d1d --- /dev/null +++ b/crates/ui-egui/src/canvas/area_fill.rs @@ -0,0 +1,417 @@ +//! Temporary AREA command fill. Never changes saved geometry, the reported area, or snap behavior. + +use super::Xf; +use cadcraft_geom::Vec2; +use egui::Color32; + +/// True if two nonadjacent edges cross or touch, or their arithmetic overflows. +/// Shared by the full boundary check and the moving-cursor checks. +fn edges_conflict(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool { + let ab = b - a; + let cd = d - c; + let ac = c - a; + let ad = d - a; + let ca = a - c; + let cb = b - c; + let (o1, o2, o3, o4) = (ab.cross(ac), ab.cross(ad), cd.cross(ca), cd.cross(cb)); + if ![o1, o2, o3, o4].iter().all(|v| v.is_finite()) { + return true; + } + let opposite = |a: f64, b: f64| (a > 0.0 && b < 0.0) || (a < 0.0 && b > 0.0); + let on_segment = |a: Vec2, b: Vec2, p: Vec2| p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x) && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y); + (opposite(o1, o2) && opposite(o3, o4)) + || (o1 == 0.0 && on_segment(a, b, c)) + || (o2 == 0.0 && on_segment(a, b, d)) + || (o3 == 0.0 && on_segment(c, d, a)) + || (o4 == 0.0 && on_segment(c, d, b)) +} + +/// Selected edges do not change as the cursor moves. Check those edges once +/// per selected-point sequence, including nonadjacent overlaps and touches. +fn selected_open_chain_is_simple(selected: &[Vec2]) -> bool { + if !(2..=255).contains(&selected.len()) || selected.iter().any(|p| !p.is_finite()) { + return false; + } + for i in 0..selected.len() - 1 { + let (a, b) = (selected[i], selected[i + 1]); + if a == b { + return false; + } + for j in i + 2..selected.len() - 1 { + if edges_conflict(a, b, selected[j], selected[j + 1]) { + return false; + } + } + } + true +} + +/// Only the last-to-cursor and cursor-to-first edges move during rubber-banding. +/// Compare each with nonadjacent selected edges: O(n) work per cursor frame. +fn cursor_edges_are_simple(selected: &[Vec2], cursor: Vec2) -> bool { + let first = selected[0]; + let last = selected[selected.len() - 1]; + if !cursor.is_finite() || cursor == first || cursor == last { + return false; + } + for i in 0..selected.len() - 1 { + let (a, b) = (selected[i], selected[i + 1]); + // The final selected edge touches last-to-cursor and is adjacent. + if i + 1 < selected.len() - 1 && edges_conflict(a, b, last, cursor) { + return false; + } + // The first selected edge touches cursor-to-first and is adjacent. + if i > 0 && edges_conflict(a, b, cursor, first) { + return false; + } + } + true +} + +/// Cached independently of the viewport transform. Exact selected coordinates, +/// not just their count, are the key: Undo, command restarts, or changed geometry +/// with an unchanged count must not accidentally reuse stale validation. +#[derive(Default)] +pub(super) struct AreaPreviewCache { + selected: Vec, + open_valid: bool, + closed_valid: bool, + #[cfg(test)] + validation_rebuilds: usize, +} + +impl AreaPreviewCache { + pub(super) fn clear(&mut self) { + self.selected.clear(); + self.open_valid = false; + self.closed_valid = false; + } + + fn boundary_is_simple(&mut self, boundary: &[Vec2]) -> bool { + let Some((cursor, selected)) = boundary.split_last() else { + return false; + }; + if self.selected.as_slice() != selected { + self.selected = selected.to_vec(); + self.open_valid = selected_open_chain_is_simple(selected); + // When the cursor revisits any selected point, the selected points + // alone form the boundary; cache that closing-edge validation too. + self.closed_valid = area_preview_boundary_is_simple(selected); + #[cfg(test)] + { + self.validation_rebuilds += 1; + } + } + if selected.contains(cursor) { self.closed_valid } else { self.open_valid && cursor_edges_are_simple(selected, *cursor) } + } +} + +/// Check whether a closed AREA boundary is a simple polygon safe to fill. +/// Nonadjacent edges may neither cross nor touch: AREA uses shoelace area while the +/// even-odd triangulator shades individual lobes of self-intersecting outlines. +/// Fail closed on degenerate edges or non-finite intermediate calculations. This +/// runs only for previews of up to 256 vertices; the drawing and AREA result stay unchanged. +fn area_preview_boundary_is_simple(boundary: &[Vec2]) -> bool { + let n = boundary.len(); + if !(3..=256).contains(&n) || boundary.iter().any(|p| !p.is_finite()) { + return false; + } + for (i, &a) in boundary.iter().enumerate() { + let Some(&b) = boundary.get((i + 1) % n) else { + return false; + }; + if a == b { + return false; + } + // Edges sharing a corner are adjacent; only nonadjacent intersections + // make the preview ambiguous. Include endpoint touches and collinear overlap. + for (j, &c) in boundary.iter().enumerate().skip(i + 2) { + if i == 0 && j == n - 1 { + continue; + } + let Some(&d) = boundary.get((j + 1) % n) else { + return false; + }; + if edges_conflict(a, b, c, d) { + return false; + } + } + } + true +} + +/// Screen-only AREA rubber-band shading. This is not a HATCH and never enters the drawing. +pub(super) fn area_preview_fill(command: Option<&str>, ents: &[cadcraft_doc::Entity], xf: &Xf, cache: &mut AreaPreviewCache) -> Option { + if command != Some("area") { + cache.clear(); + return None; + } + let cadcraft_doc::EntityKind::LwPolyline(poly) = &ents.first()?.kind else { + return None; + }; + // This runs on pointer movement; keep triangulation and mesh allocation bounded. + if !poly.closed || poly.vertices.len() < 3 || poly.vertices.len() > 256 { + return None; + } + let mut boundary: Vec = poly.vertices.iter().map(|v| v.p).collect(); + // Evaluate the immutable selected chain once per selection change. Check + // only the two cursor edges every frame; reject invalid shapes as before. + if !cache.boundary_is_simple(&boundary) { + return None; + } + // AREA adds the cursor as a temporary last vertex. When it revisits a + // selected point, shade the unchanged selected polygon instead. + if boundary.split_last().is_some_and(|(cursor, selected)| selected.contains(cursor)) { + boundary.pop(); + } + // Use the existing even-odd renderer for simple concave polygons (not a triangle fan). + let triangles = cadcraft_render::triangulate_evenodd(&[boundary]); + if triangles.len() > 24_000 || triangles.iter().any(|p| !p.is_finite()) { + return None; + } + let mut mesh = egui::Mesh::default(); + let fill = Color32::from_rgba_unmultiplied(48, 195, 112, 76); // ~30% opacity + for triangle in triangles.as_chunks::<3>().0 { + let start = mesh.vertices.len() as u32; + for point in triangle { + mesh.colored_vertex(xf.to_screen(*point), fill); + } + mesh.add_triangle(start, start + 1, start + 2); + } + (!mesh.indices.is_empty()).then_some(mesh) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + use cadcraft_engine::Input; + use egui::{Rect, pos2}; + + fn preview_fill(command: Option<&str>, ents: &[cadcraft_doc::Entity], xf: &Xf) -> Option { + area_preview_fill(command, ents, xf, &mut AreaPreviewCache::default()) + } + + /// A regular AREA rectangle shades only the transient mesh, not the saved drawing. + #[test] + fn area_preview_fills_rectangle_without_changing_drawing() { + let mut s = cadcraft_engine::Session::new(); + let initial = s.doc().unwrap().model.len(); + s.start("area").unwrap(); + for p in [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0)] { + s.input(Input::Point(p)).unwrap(); + } + let ents = s.preview(Vec2::new(0.0, 10.0)); + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(5.0, 5.0), scale: 10.0, twist: 0.0 }; + let mesh = preview_fill(s.active_command_id(), &ents, &xf).unwrap(); + assert!(!mesh.indices.is_empty()); + assert!(mesh.vertices.iter().all(|v| v.color.a() == 76)); + assert_eq!(s.doc().unwrap().model.len(), initial); + assert!(preview_fill(Some("line"), &ents, &xf).is_none()); + s.input(Input::Enter).unwrap(); + assert_eq!(s.active_command_id(), None); + assert_eq!(s.doc().unwrap().model.len(), initial); + } + + /// A simple concave boundary shades its notch correctly without filling its bounding box. + #[test] + fn area_preview_concave_polygon_respects_notch() { + let mut s = cadcraft_engine::Session::new(); + s.start("area").unwrap(); + for p in [Vec2::new(0.0, 0.0), Vec2::new(6.0, 0.0), Vec2::new(6.0, 2.0), Vec2::new(2.0, 2.0), Vec2::new(2.0, 6.0)] { + s.input(Input::Point(p)).unwrap(); + } + let ents = s.preview(Vec2::new(0.0, 6.0)); + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(3.0, 3.0), scale: 10.0, twist: 0.0 }; + let mesh = preview_fill(s.active_command_id(), &ents, &xf).unwrap(); + let drawn_area: f32 = mesh + .indices + .as_chunks::<3>() + .0 + .iter() + .map(|tri| { + let a = mesh.vertices[tri[0] as usize].pos; + let b = mesh.vertices[tri[1] as usize].pos; + let c = mesh.vertices[tri[2] as usize].pos; + ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)).abs() / 2.0 + }) + .sum(); + // L-shaped polygon = (6 x 2) + (2 x 4) = 20 square drawing units. + assert!((drawn_area / 100.0 - 20.0).abs() < 0.01); + s.cancel(); + assert_eq!(s.active_command_id(), None); + } + + /// Collinear AREA points create no triangles, even though the outline remains. + #[test] + fn area_preview_collinear_points_have_no_fill() { + let mut s = cadcraft_engine::Session::new(); + s.start("area").unwrap(); + s.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap(); + s.input(Input::Point(Vec2::new(2.0, 0.0))).unwrap(); + let ents = s.preview(Vec2::new(4.0, 0.0)); + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(2.0, 0.0), scale: 10.0, twist: 0.0 }; + assert!(preview_fill(s.active_command_id(), &ents, &xf).is_none()); + s.cancel(); + } + + /// A stationary cursor repeats only the temporary preview vertex; the valid triangle stays shaded. + #[test] + fn area_preview_keeps_fill_when_cursor_equals_last_selected_point() { + let mut s = cadcraft_engine::Session::new(); + let initial = s.doc().unwrap().model.len(); + s.start("area").unwrap(); + for p in [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 3.0)] { + s.input(Input::Point(p)).unwrap(); + } + let cursor = Vec2::new(0.0, 3.0); + let ents = s.preview(cursor); + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(2.0, 1.5), scale: 10.0, twist: 0.0 }; + let mesh = preview_fill(s.active_command_id(), &ents, &xf).unwrap(); + assert!(!mesh.indices.is_empty()); + assert_eq!(s.doc().unwrap().model.len(), initial); + s.cancel(); + assert_eq!(s.active_command_id(), None); + } + + /// Revisit the first or an interior selected point without hiding a valid AREA fill. + #[test] + fn area_preview_keeps_fill_when_cursor_returns_to_earlier_selected_points() { + let mut s = cadcraft_engine::Session::new(); + let initial = s.doc().unwrap().model.len(); + s.start("area").unwrap(); + for p in [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 3.0), Vec2::new(0.0, 3.0)] { + s.input(Input::Point(p)).unwrap(); + } + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(2.0, 1.5), scale: 10.0, twist: 0.0 }; + for cursor in [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 3.0)] { + let ents = s.preview(cursor); + let mesh = preview_fill(s.active_command_id(), &ents, &xf).unwrap(); + assert!(!mesh.indices.is_empty(), "valid selected boundary should remain shaded at {cursor:?}"); + } + assert_eq!(s.doc().unwrap().model.len(), initial); + s.cancel(); + } + + /// A repeated earlier *selected* point remains invalid even if the temporary cursor repeats it. + #[test] + fn area_preview_rejects_real_duplicate_earlier_selected_point() { + let mut s = cadcraft_engine::Session::new(); + s.start("area").unwrap(); + for p in [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 3.0), Vec2::new(0.0, 3.0), Vec2::new(4.0, 0.0)] { + s.input(Input::Point(p)).unwrap(); + } + let ents = s.preview(Vec2::new(4.0, 0.0)); + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(2.0, 1.5), scale: 10.0, twist: 0.0 }; + assert!(!ents.is_empty(), "preview outline still exists"); + assert!(preview_fill(s.active_command_id(), &ents, &xf).is_none()); + s.cancel(); + } + + /// Real duplicate clicks remain invalid even when the cursor repeats the final selected point. + #[test] + fn area_preview_still_rejects_duplicate_selected_points() { + let mut s = cadcraft_engine::Session::new(); + s.start("area").unwrap(); + for p in [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 3.0), Vec2::new(0.0, 3.0)] { + s.input(Input::Point(p)).unwrap(); + } + let ents = s.preview(Vec2::new(0.0, 3.0)); + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(2.0, 1.5), scale: 10.0, twist: 0.0 }; + assert!(!ents.is_empty(), "the outline remains available"); + assert!(preview_fill(s.active_command_id(), &ents, &xf).is_none()); + s.cancel(); + } + + /// A self-crossing bowtie has zero signed shoelace area; its two visual lobes must not be shaded. + #[test] + fn area_preview_bowtie_does_not_show_misleading_fill() { + let mut s = cadcraft_engine::Session::new(); + let initial = s.doc().unwrap().model.len(); + s.start("area").unwrap(); + for p in [Vec2::new(0.0, 0.0), Vec2::new(2.0, 2.0), Vec2::new(2.0, 0.0)] { + s.input(Input::Point(p)).unwrap(); + } + let ents = s.preview(Vec2::new(0.0, 2.0)); + let xf = Xf { rect: Rect::from_min_max(pos2(0.0, 0.0), pos2(300.0, 300.0)), center: Vec2::new(1.0, 1.0), scale: 10.0, twist: 0.0 }; + assert!(!ents.is_empty(), "the outline is still available"); + assert!(preview_fill(s.active_command_id(), &ents, &xf).is_none()); + assert_eq!(s.doc().unwrap().model.len(), initial); + s.cancel(); + assert_eq!(s.active_command_id(), None); + } + + /// Touching nonadjacent edges, duplicate points and invalid coordinates are not safe to shade. + #[test] + fn area_preview_rejects_touching_and_degenerate_boundaries() { + let v = |x, y| Vec2::new(x, y); + assert!(!area_preview_boundary_is_simple(&[v(0.0, 0.0), v(4.0, 0.0), v(4.0, 4.0), v(2.0, 2.0), v(0.0, 4.0), v(2.0, 2.0)])); + assert!(!area_preview_boundary_is_simple(&[v(0.0, 0.0), v(4.0, 0.0), v(4.0, 0.0), v(0.0, 4.0)])); + assert!(!area_preview_boundary_is_simple(&[v(0.0, 0.0), v(f64::NAN, 2.0), v(0.0, 4.0)])); + assert!(area_preview_boundary_is_simple(&[v(0.0, 0.0), v(6.0, 0.0), v(6.0, 2.0), v(2.0, 2.0), v(2.0, 6.0), v(0.0, 6.0)])); + } + + /// Moving the cursor never repeats the expensive selected-edge validation. + #[test] + fn area_cache_reuses_selected_validation_while_cursor_moves() { + let v = |x, y| Vec2::new(x, y); + let mut cache = AreaPreviewCache::default(); + let selected = [v(0.0, 0.0), v(4.0, 0.0), v(4.0, 4.0)]; + for cursor in [v(0.0, 4.0), v(1.0, 3.0), v(2.0, 2.0), v(2.0, -1.0), v(0.0, 0.0)] { + let mut boundary = selected.to_vec(); + boundary.push(cursor); + let mut expected = boundary.clone(); + if selected.contains(&cursor) { + expected.pop(); + } + assert_eq!(cache.boundary_is_simple(&boundary), area_preview_boundary_is_simple(&expected)); + } + assert_eq!(cache.validation_rebuilds, 1); + } + + /// Same vertex count does not imply the same geometry. + #[test] + fn area_cache_invalidates_on_changed_selected_points_and_clear() { + let v = |x, y| Vec2::new(x, y); + let mut cache = AreaPreviewCache::default(); + let rectangle = [v(0.0, 0.0), v(4.0, 0.0), v(4.0, 4.0), v(0.0, 4.0), v(0.0, 0.0)]; + assert!(cache.boundary_is_simple(&rectangle)); + assert_eq!(cache.validation_rebuilds, 1); + let bowtie = [v(0.0, 0.0), v(4.0, 4.0), v(4.0, 0.0), v(0.0, 4.0), v(0.0, 0.0)]; + assert!(!cache.boundary_is_simple(&bowtie)); + assert_eq!(cache.validation_rebuilds, 2); + cache.clear(); + assert!(cache.boundary_is_simple(&rectangle)); + assert_eq!(cache.validation_rebuilds, 3); + } + + /// Cache results must match the full validator for convex, concave, + /// crossing, collinear and duplicate-selected boundaries. + #[test] + fn area_cache_matches_complete_validator_for_varied_boundaries() { + let v = |x, y| Vec2::new(x, y); + let mut cache = AreaPreviewCache::default(); + let cases = [ + vec![v(0.0, 0.0), v(4.0, 0.0), v(4.0, 3.0), v(0.0, 3.0)], + vec![v(0.0, 0.0), v(6.0, 0.0), v(6.0, 2.0), v(2.0, 2.0), v(2.0, 6.0)], + vec![v(0.0, 0.0), v(4.0, 4.0), v(4.0, 0.0), v(0.0, 4.0)], + vec![v(0.0, 0.0), v(2.0, 0.0), v(4.0, 0.0)], + vec![v(0.0, 0.0), v(4.0, 0.0), v(4.0, 3.0), v(4.0, 0.0)], + ]; + for selected in cases { + for cursor in [v(0.0, 0.0), v(2.0, 2.0), v(0.0, 6.0), v(2.0, -1.0), v(4.0, 3.0)] { + let mut boundary = selected.clone(); + boundary.push(cursor); + let mut expected = boundary.clone(); + if selected.contains(&cursor) { + expected.pop(); + } + assert_eq!( + cache.boundary_is_simple(&boundary), + area_preview_boundary_is_simple(&expected), + "selected={selected:?}, cursor={cursor:?}" + ); + } + } + } +} diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index d499eff32..88c791823 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -169,13 +169,16 @@ pub(super) fn draw_highlight_gpu( stencil: crate::gpu::Stencil, ) { let (hl_key, hl_slot, hl_origin, hl_infinite) = hl; - let origin = crate::gpu::choose_origin(&list.bounds, xf.center, f64::from(xf.rect.height()) / xf.scale.max(1e-300)); - let key = { + let hl_hash = |o: Vec2| { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - (list_gen, sel, origin.x.to_bits(), origin.y.to_bits(), color.to_array(), look.width.to_bits(), look.dashed).hash(&mut h); + (list_gen, sel, o.x.to_bits(), o.y.to_bits(), color.to_array(), look.width.to_bits(), look.dashed).hash(&mut h); h.finish() }; + let view_height = f64::from(xf.rect.height()) / xf.scale.max(1e-300); + let reuse = *hl_key == Some(hl_hash(*hl_origin)) && crate::gpu::origin_usable(*hl_origin, &list.bounds, xf.center, view_height); + let origin = if reuse { *hl_origin } else { crate::gpu::choose_origin(&list.bounds, xf.center, view_height) }; + let key = hl_hash(origin); if *hl_key != Some(key) { let prims = prims(); let mesh = crate::gpu::build_highlight_mesh(list, &prims, origin, color.to_array(), look.width, look.dashed); @@ -279,7 +282,10 @@ pub(super) fn list_mesh_key(key: &ListKey, list_gen: u64, origin: Vec2, bg: Rgb, /// the infinite lines, which are clipped to the view on the CPU every frame. pub(super) fn draw_list_gpu(c: &mut CanvasState, p: &egui::Painter, xf: &Xf, bg: Rgb, lwdisplay: bool) { let Some(list) = &c.list else { return }; - let origin = crate::gpu::choose_origin(&list.bounds, xf.center, f64::from(xf.rect.height()) / xf.scale.max(1e-300)); + let view_height = f64::from(xf.rect.height()) / xf.scale.max(1e-300); + let reuse = c.mesh_key == Some(list_mesh_key(&c.key, c.list_gen, c.mesh_origin, bg, lwdisplay)) + && crate::gpu::origin_usable(c.mesh_origin, &list.bounds, xf.center, view_height); + let origin = if reuse { c.mesh_origin } else { crate::gpu::choose_origin(&list.bounds, xf.center, view_height) }; let key = list_mesh_key(&c.key, c.list_gen, origin, bg, lwdisplay); if c.mesh_key != Some(key) { let t0 = crate::now_ms(); diff --git a/crates/ui-egui/src/canvas/grips.rs b/crates/ui-egui/src/canvas/grips.rs index e9394c929..f1fdfb5e2 100644 --- a/crates/ui-egui/src/canvas/grips.rs +++ b/crates/ui-egui/src/canvas/grips.rs @@ -1,4 +1,93 @@ +use egui::{Color32, Stroke}; + use super::{CadApp, Handle, Input, Pos2, Rect, Xf, vec2}; +use crate::theme::Tokens; + +/// Grips on selected objects (when idle or editing grips), including GROUPDISPLAYMODE boxes. +pub(super) fn draw_selection_grips(app: &mut CadApp, painter: &egui::Painter, xf: &Xf, rect: Rect, hover_pos: Option, t: Tokens) { + let sel = app.session.selection(); + let grip_edit = app.session.running.as_ref().is_some_and(|r| r.id == "grip"); + if (!grip_edit && (app.canvas.grip_editing || app.session.prompting())) || sel.is_empty() { + app.canvas.hot_grips.clear(); + } + if !grip_edit { + app.canvas.dyn_hot = None; + } + app.canvas.grip_editing = grip_edit; + if !(!app.session.prompting() || grip_edit) || !app.session.shows_grips(sel.len()) { + return; + } + let Ok(st) = app.session.state() else { return }; + let gs = app.session.settings.gripsize as f32; + let gdm = app.session.settings.groupdisplaymode; + let mut grouped_members = std::collections::HashSet::new(); + if gdm > 0 && app.session.settings.pickstyle & 1 != 0 { + for g in &st.doc.groups { + if g.selectable && !g.members.is_empty() && g.members.iter().all(|h| sel.contains(h)) { + let mut b = cadcraft_geom::Bounds2::EMPTY; + for h in &g.members { + if let Some(e) = st.doc.entity(*h) { + grouped_members.insert(*h); + let eb = cadcraft_engine::doc::entity_bounds(&st.doc, e, 0); + b = b.union(&eb); + } + } + if !b.is_empty() { + let min_sp = xf.to_screen(b.min); + let max_sp = xf.to_screen(b.max); + let box_rect = Rect::from_two_pos(min_sp, max_sp).expand(4.0); + if rect.intersects(box_rect) { + painter.rect_stroke( + box_rect, + 0.0, + Stroke::new(1.0, Color32::from_rgba_unmultiplied(0x80, 0x90, 0xb0, 0xb0)), + egui::StrokeKind::Middle, + ); + let center_sp = xf.to_screen(b.center()); + if rect.contains(center_sp) { + let cr = Rect::from_center_size(center_sp, egui::vec2(gs * 2.0, gs * 2.0)); + let warm = hover_pos.is_some_and(|hp| cr.expand(2.0).contains(hp)); + painter.rect_filled(cr, 0.0, if warm { Color32::from_rgb(0xff, 0x7f, 0x9f) } else { t.grip }); + painter.rect_stroke(cr, 0.0, Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80)), egui::StrokeKind::Middle); + } + } + } + } + } + } + for h in sel.iter().take(200) { + if gdm == 1 && grouped_members.contains(h) { + continue; + } + if let Some(e) = st.doc.entity(*h) + && st.shows(e) + { + let grips = e.kind.grips(); + let count = grips.len(); + for (gi, g) in grips.into_iter().enumerate() { + let sp = xf.to_screen(g); + if rect.contains(sp) { + let r = grip_rect(&e.kind, count, gi, sp, gs); + let hot = app.canvas.hot_grips.contains(&(*h, gi)); + let warm = !hot && hover_pos.is_some_and(|hp| r.expand(2.0).contains(hp)); + painter.rect_filled( + r, + 0.0, + if hot { + t.grip_hot + } else if warm { + Color32::from_rgb(0xff, 0x7f, 0x9f) + } else { + t.grip + }, + ); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80)), egui::StrokeKind::Middle); + } + } + } + } + crate::dyngrips::draw(app, painter, xf, rect, hover_pos); +} /// A click on grip `g` (idle): Shift+click makes it hot or cold again; a plain click starts /// editing it, with the other hot grips when it is one of them. diff --git a/crates/ui-egui/src/canvas/refedit.rs b/crates/ui-egui/src/canvas/refedit.rs new file mode 100644 index 000000000..de9250205 --- /dev/null +++ b/crates/ui-egui/src/canvas/refedit.rs @@ -0,0 +1,72 @@ +//! Editing a reference in place (REFEDIT) on the canvas: a bar over the drawing with the +//! reference's name (and, for an xref, the file it writes to), the working set's size, Add to / +//! Remove from Working Set, and Save Changes / Discard Changes (REFCLOSE). The rest of the +//! drawing is drawn faded by the renderer (XFADECTL) and locked by the engine. + +use egui::{Rect, RichText, Stroke, vec2}; +use serde_json::json; + +use crate::CadApp; +use crate::theme::Tokens; + +fn id() -> egui::Id { + egui::Id::unique("cadcraft-refedit-bar") +} + +/// The edit shown: (block, xref file, working-set size). +fn editing(app: &CadApp) -> Option<(String, Option, usize)> { + let r = app.session.state().ok()?.doc.refedit.clone()?; + Some((r.block, r.xref.map(|x| x.file), r.items.len())) +} + +/// What a bar button asks for. +enum Act { + Start(&'static str), + Run(&'static str, serde_json::Value), +} + +/// The bar (over the drawing, at its top). +pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, rect: Rect) { + let Some((name, file, count)) = editing(app) else { return }; + let t = Tokens::get(); + let sel: Vec = app.session.selection().iter().map(|h| h.hex()).collect(); + let mut act = None; + egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( + ctx, + |ui| { + egui::Frame::new().fill(t.cmd_bg).stroke(Stroke::new(1.0, t.accent)).corner_radius(4.0).inner_margin(6.0).show(ui, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(crate::tl!("Edit Reference")).color(t.accent).strong()); + let shown = ui.label(RichText::new(&name).color(t.text)); + if let Some(f) = &file { + shown.on_hover_text(crate::tf!("Saving writes {file}", file = f)); + } + ui.label(RichText::new(crate::tf!("{n} in the working set", n = count)).color(t.text_dim)); + ui.separator(); + if ui.button(crate::tl!("Add to Working Set")).clicked() { + act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "add": sel })) }); + } + if ui.button(crate::tl!("Remove from Working Set")).clicked() { + act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "remove": sel })) }); + } + ui.separator(); + if ui.button(RichText::new(crate::tl!("Save Changes")).color(t.accent)).clicked() { + act = Some(Act::Run("refclose", json!({ "option": "save" }))); + } + if ui.button(crate::tl!("Discard Changes")).clicked() { + act = Some(Act::Run("refclose", json!({ "option": "discard" }))); + } + }); + }); + }, + ); + match act { + Some(Act::Start(id)) => app.start(id), + Some(Act::Run(id, p)) => { + if let Err(e) = app.run(id, p) { + app.set_status(e); + } + } + None => {} + } +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 69a955709..89b87d703 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -200,6 +200,11 @@ fn a_wheel_notch_zooms_whole_in_its_own_frame() { /// The text painted by one frame of the app at `pointer`. pub(crate) fn painted_text(app: &mut CadApp, ctx: &egui::Context, pointer: Pos2) -> String { + painted_text_with(app, ctx, pointer, egui::Modifiers::NONE) +} + +/// The text painted by one frame at `pointer`, with `modifiers` held (as egui reports them). +fn painted_text_with(app: &mut CadApp, ctx: &egui::Context, pointer: Pos2, modifiers: egui::Modifiers) -> String { fn collect(shape: &Shape, text: &mut String) { match shape { Shape::Text(s) => { @@ -212,7 +217,7 @@ pub(crate) fn painted_text(app: &mut CadApp, ctx: &egui::Context, pointer: Pos2) } let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), - events: vec![egui::Event::PointerMoved(pointer)], + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::PointerMoved(pointer)], ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { @@ -447,6 +452,37 @@ fn the_viewport_highlight_leaves_out_objects_the_viewport_does_not_draw() { assert_eq!(outlined(&app, &mut highlight, both), both); } +/// The highlight of a block reference inside the active viewport shows the parts that viewport +/// draws: not its part on a layer frozen there, which the other viewport's highlight shows. +#[test] +fn the_viewport_highlight_of_a_reference_leaves_out_the_parts_the_viewport_does_not_draw() { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + for y in [0, 30] { + app.run("line", serde_json::json!({ "points": [[0, y], [100, y]] })).unwrap(); + } + let lines = app.session.doc().unwrap().model.handles(); + let (a, b) = viewports_freezing_hidden(&mut app); + // Inside a viewport the block's reference is made in model space, where the lines are. + app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap(); + app.session.execute("properties.set", &serde_json::json!({ "handles": [lines[1].hex()], "layer": "Hidden" })).unwrap(); + let parts: Vec = lines.iter().map(|h| h.hex()).collect(); + let made = app.session.execute("block", &serde_json::json!({ "name": "B", "base": [0, 0], "handles": parts })).unwrap(); + let reference = Handle::parse_hex(made["insert"].as_str().unwrap()).unwrap(); + assert_eq!(app.session.doc().unwrap().model.handles(), [reference], "the reference must be the one object in model space"); + /// The heights at which `highlight` draws something for the reference. + fn heights(app: &CadApp, highlight: &mut VpHighlight, reference: Handle) -> Vec { + highlight.update(app.session.state().unwrap(), &[reference], 10.0); + let mut ys: Vec = highlight.list.prims.iter().map(|p| highlight.list.points(p)[0].y).collect(); + ys.sort_by(f64::total_cmp); + ys + } + let mut highlight = VpHighlight::default(); + app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap(); + assert_eq!(heights(&app, &mut highlight, reference), [0.0, 30.0], "this viewport draws both parts"); + app.session.execute("mspace", &serde_json::json!({ "handle": a })).unwrap(); + assert_eq!(heights(&app, &mut highlight, reference), [0.0], "a part the viewport does not draw was highlighted"); +} + /// Selection cycling's badge beside a resting pointer follows the layers frozen in the active /// viewport: over two overlapping lines it shows while the viewport draws both, goes when the /// layer of one of them is frozen there, and comes back when the layer is thawed. @@ -537,3 +573,72 @@ fn a_fence_point_taken_back_with_undo_updates_the_highlight_at_once() { painted_text(&mut app, &ctx, below); assert!(app.canvas.hover_part.list.as_ref().is_none_or(|l| l.prims.is_empty()), "nothing is crossed"); } +/// #1118: at TRIM's Crossing stage the prompt does not change with Shift, so holding Shift flips +/// the cached highlight to the opposite edit and back only through the `session.shift_down` cache bit. +/// The cursor stays fixed; only `shift_down` changes across the frames below. +#[test] +fn trim_shift_flips_the_cached_crossing_highlight_with_a_steady_prompt() { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + for points in [[[4, -5], [4, 5]], [[10, -5], [10, 5]], [[0, 0], [8, 0]]] { + app.run("line", serde_json::json!({ "points": points })).unwrap(); + } + app.session.zoom_extents().unwrap(); + let ctx = egui::Context::default(); + crate::framework::install_headless(&ctx); + painted_text(&mut app, &ctx, pos2(700.0, 450.0)); + app.session.cmdline("trim").unwrap(); + app.session.input(Input::Keyword("Crossing".into())).unwrap(); + app.session.input(Input::Point(Vec2::new(4.5, -1.0))).unwrap(); + let cursor = app.canvas.xf.unwrap().to_screen(Vec2::new(6.0, 1.0)); + painted_text(&mut app, &ctx, cursor); + let prompt = app.session.prompt_text(); + assert_eq!(prompt, "TRIM Specify opposite corner:", "the Crossing prompt is steady under Shift"); + let part = app.canvas.hover_part.list.as_ref().expect("a part of the line is highlighted"); + assert!((part.bounds.min.x - 4.0).abs() < 1e-6 && (part.bounds.max.x - 8.0).abs() < 1e-6, "the piece a click removes: {:?}", part.bounds); + let (hover, cursor, scale) = (app.canvas.hover, app.canvas.cursor, app.canvas.xf.unwrap().scale); + let computed = app.canvas.hover_part.list_gen; + app.session.shift_down = true; + app.canvas.hover_part.update(&app.session, hover, cursor, scale); + assert_eq!(app.session.prompt_text(), prompt, "the prompt is unchanged by Shift at Crossing"); + assert_ne!(app.canvas.hover_part.list_gen, computed, "shift recomputes the highlight at a resting cursor"); + let part = app.canvas.hover_part.list.as_ref().expect("the opposite part is highlighted"); + assert!((part.bounds.min.x - 8.0).abs() < 1e-6 && (part.bounds.max.x - 10.0).abs() < 1e-6, "the stretch a shift-click adds: {:?}", part.bounds); + let flipped = app.canvas.hover_part.list_gen; + app.session.shift_down = false; + app.canvas.hover_part.update(&app.session, hover, cursor, scale); + assert_eq!(app.session.prompt_text(), prompt, "releasing Shift keeps the Crossing prompt"); + assert_ne!(app.canvas.hover_part.list_gen, flipped, "releasing shift recomputes it again"); + let part = app.canvas.hover_part.list.as_ref().expect("the original part is highlighted"); + assert!((part.bounds.min.x - 4.0).abs() < 1e-6 && (part.bounds.max.x - 8.0).abs() < 1e-6, "back to the trim piece: {:?}", part.bounds); +} +/// #1118: pressing and releasing Shift through the UI (an `egui::Event::ModifiersChanged` +/// in the frame's events) flips the TRIM rollover preview to the opposite edit and back, at a resting +/// cursor: `canvas.rs` reads `p.mods.shift` into `session.shift_down`. +#[test] +fn shift_modifier_at_rest_flips_the_rollover_preview_through_the_canvas() { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + for points in [[[4, -5], [4, 5]], [[10, -5], [10, 5]], [[0, 0], [8, 0]]] { + app.run("line", serde_json::json!({ "points": points })).unwrap(); + } + app.session.zoom_extents().unwrap(); + let ctx = egui::Context::default(); + crate::framework::install_headless(&ctx); + painted_text(&mut app, &ctx, pos2(700.0, 450.0)); + app.session.cmdline("trim").unwrap(); + let cursor = app.canvas.xf.unwrap().to_screen(Vec2::new(6.0, 0.0)); + + painted_text_with(&mut app, &ctx, cursor, egui::Modifiers::NONE); + assert!(!app.session.shift_down, "no modifier held: shift is up"); + let part = app.canvas.hover_part.list.as_ref().expect("a part of the line is highlighted"); + assert!((part.bounds.min.x - 4.0).abs() < 1e-6 && (part.bounds.max.x - 8.0).abs() < 1e-6, "the piece a click removes: {:?}", part.bounds); + + painted_text_with(&mut app, &ctx, cursor, egui::Modifiers::SHIFT); + assert!(app.session.shift_down, "shift held through the canvas reaches the session"); + let part = app.canvas.hover_part.list.as_ref().expect("the opposite part is highlighted"); + assert!((part.bounds.min.x - 8.0).abs() < 1e-6 && (part.bounds.max.x - 10.0).abs() < 1e-6, "the stretch a shift-click adds: {:?}", part.bounds); + + painted_text_with(&mut app, &ctx, cursor, egui::Modifiers::NONE); + assert!(!app.session.shift_down, "shift released: shift is up again"); + let part = app.canvas.hover_part.list.as_ref().expect("the original part is highlighted"); + assert!((part.bounds.min.x - 4.0).abs() < 1e-6 && (part.bounds.max.x - 8.0).abs() < 1e-6, "back to the trim piece: {:?}", part.bounds); +} diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index b855bfd4f..84ce1ed8d 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -45,9 +45,9 @@ pub(super) struct VpContent { motion: Option<(f64, Vec2)>, /// Bumped on each rebuild. pub(super) builds: u64, - mesh_key: Option, + pub(super) mesh_key: Option, mesh_slot: crate::gpu::MeshSlot, - mesh_origin: Vec2, + pub(super) mesh_origin: Vec2, /// A clipped viewport's outline on the GPU (see [`draw_vp_mask`]). mask_key: Option, mask_slot: crate::gpu::MeshSlot, @@ -175,13 +175,16 @@ pub(super) fn draw_vp_content(c: &mut VpContent, gpu: bool, p: &egui::Painter, f draw_vp_mask(c, p, outline, xf_paper); stencil = crate::gpu::Stencil::Inside; } - let origin = crate::gpu::choose_origin(&c.list.bounds, xf.center, f64::from(xf.rect.height()) / xf.scale.max(1e-300)); - let key = { + let mesh_hash = |o: Vec2| { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - (c.builds, origin.x.to_bits(), origin.y.to_bits(), bg.0, bg.1, bg.2, lwdisplay).hash(&mut h); + (c.builds, o.x.to_bits(), o.y.to_bits(), bg.0, bg.1, bg.2, lwdisplay).hash(&mut h); h.finish() }; + let view_height = f64::from(xf.rect.height()) / xf.scale.max(1e-300); + let reuse = c.mesh_key == Some(mesh_hash(c.mesh_origin)) && crate::gpu::origin_usable(c.mesh_origin, &c.list.bounds, xf.center, view_height); + let origin = if reuse { c.mesh_origin } else { crate::gpu::choose_origin(&c.list.bounds, xf.center, view_height) }; + let key = mesh_hash(origin); if c.mesh_key != Some(key) { let mesh = crate::gpu::build_mesh(&c.list, origin, bg, lwdisplay); if let Ok(mut slot) = c.mesh_slot.lock() { @@ -274,7 +277,10 @@ pub(super) fn viewport_highlight_tolerance(scale: f64) -> f64 { /// the hover are kept apart, so moving the cursor over objects doesn't tessellate the selection /// again; each is rebuilt only when the drawing, the objects, the zoom band or the layers frozen /// in the viewport change. An object on one of those layers is not drawn in the viewport, so it -/// is not highlighted there either. +/// is not highlighted there either, and neither are the parts of a block reference on them. The +/// highlight is built as a selection through the viewport sees the objects, so a point on the +/// layer Defpoints in a block stays in it, as the definition points of a dimension are +/// ([`cadcraft_render::build_entities_in_viewport`]). #[derive(Default)] pub(super) struct VpHighlight { key: Option, @@ -286,18 +292,19 @@ pub(super) struct VpHighlight { impl VpHighlight { pub(super) fn update(&mut self, st: &cadcraft_engine::DocState, handles: &[Handle], scale: f64) { let tolerance = viewport_highlight_tolerance(scale); + // Entering another viewport changes what is drawn without changing the drawing. + let frozen = st.viewport_frozen(); let key = { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - // Entering another viewport changes what is drawn without changing the drawing. - let frozen = st.viewport_frozen(); (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), handles, frozen, super::list::font_generation()) .hash(&mut h); h.finish() }; if self.key != Some(key) { let ents = handles.iter().filter_map(|h| st.doc.model.get(*h)).filter(|e| !st.hidden_in_viewport(e)).map(|e| e.as_ref()); - self.list = cadcraft_render::build_entities(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() }); + self.list = + cadcraft_render::build_entities_in_viewport(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() }, frozen); self.key = Some(key); self.list_gen = self.list_gen.wrapping_add(1); } @@ -333,7 +340,19 @@ impl HoverPart { // Every answer the running command is given counts, not only those that change the // prompt: a fence point taken back with Undo leaves the same prompt but a shorter fence. let answers = (session.commands_started, session.inputs); - (hover, c.x.to_bits(), c.y.to_bits(), scale.to_bits(), doc, answers, session.prompt_text(), super::list::font_generation()).hash(&mut hs); + ( + hover, + c.x.to_bits(), + c.y.to_bits(), + scale.to_bits(), + doc, + answers, + session.shift_down, + session.ctrl_down, + session.prompt_text(), + super::list::font_generation(), + ) + .hash(&mut hs); hs.finish() }; if self.key == Some(key) { diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 501307993..97dd5e3db 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -61,7 +61,7 @@ pub fn dyn_frame(app: &CadApp) -> Option { } let p = app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts)?; let ucs = app.session.input_ucs(); - Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, ucs }) + Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian || p.xy, absolute: st.dynpi_absolute, ucs }) } /// Whether Tab on the command line has something to act on: a running command or LISP prompt, typed @@ -379,9 +379,10 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { options_still_fit(app); for ev in events { app.cmd.forget_stale_first(dyn_frame(app).is_some()); + let space_is_text = app.session.space_is_text(&app.cmd.buffer); // The options menu takes the arrows, Enter and Escape; typing closes it. if app.cmd.options.is_some() { - let space = matches!(&ev, egui::Event::Text(t) if t == " ") && !text_prompt; + let space = matches!(&ev, egui::Event::Text(t) if t == " ") && !space_is_text; match &ev { _ if space => { if let Some(k) = app.cmd.options.as_ref().and_then(|m| m.current()).map(str::to_owned) { @@ -412,7 +413,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { } match ev { egui::Event::Text(t) => { - if t == " " && !text_prompt { + if t == " " && !space_is_text { submit(app); } else { app.cmd.preedit.clear(); @@ -1356,3 +1357,85 @@ mod dyn_tab_tests { assert!(!app.cmd.first_active()); } } + +#[cfg(test)] +mod lisp_space_tests { + use super::*; + use cadcraft_doc::EntityKind; + use cadcraft_geom::Vec2; + + fn run_frame(app: &mut CadApp, ctx: &egui::Context, events: Vec) { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + } + + #[test] + fn space_types_inside_an_open_lisp_expression_and_submits_once_closed() { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + app.session.settings.dynmode = true; + let ctx = egui::Context::default(); + crate::framework::install_headless(&ctx); + run_frame(&mut app, &ctx, Vec::new()); + + let send = |app: &mut CadApp, text: &str| { + let mut events = Vec::new(); + for c in text.chars() { + if c == ' ' { + events.push(egui::Event::Key { + key: egui::Key::Space, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + } + events.push(egui::Event::Text(c.to_string())); + } + run_frame(app, &ctx, events); + }; + + // Nested forms, an escaped quote, a `)` inside a string and a `;| ... |;` block comment + // stay open across spaces; once the outer `)` closes the form, Space evaluates it. + send(&mut app, "(defun c:greet () (princ \"hi \\\" ) there\") ;| ) |; (princ))"); + assert_eq!(app.cmd.buffer, "(defun c:greet () (princ \"hi \\\" ) there\") ;| ) |; (princ))"); + send(&mut app, " "); + assert!(app.cmd.buffer.is_empty()); + send(&mut app, "greet "); + assert_eq!(app.session.log.last().map(String::as_str), Some("hi \" ) there")); + + // At point and number prompts (including with the Dynamic Input options menu open), + // spaces stay inside `(...)` and Space after `)` answers the prompt. + send(&mut app, "(setq r 5) "); + send(&mut app, "circle "); + run_frame( + &mut app, + &ctx, + vec![egui::Event::Key { key: egui::Key::ArrowDown, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(app.cmd.options.is_some()); + send(&mut app, "(list 3 4) (* 2 r) "); + assert!(app.session.running.is_none()); + let circle = app.session.doc().unwrap().model.iter().find_map(|e| match &e.kind { + EntityKind::Circle(c) => Some((c.center.xy(), c.radius)), + _ => None, + }); + assert_eq!(circle, Some((Vec2::new(3.0, 4.0), 10.0))); + + // A `)` inside a `;` line comment does not close the form, so Space keeps typing text. + send(&mut app, "(+ 1 ; ) "); + assert_eq!(app.cmd.buffer, "(+ 1 ; ) "); + escape(&mut app); + + // A free-text prompt still keeps spaces after a closing parenthesis as text. + send(&mut app, "-text 0,0 2.5 0 (3+4) 5"); + assert_eq!(app.cmd.buffer, "(3+4) 5"); + } +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 4237a7c9a..d0a09d3ee 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -153,7 +153,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) => vec![("textedit", None)], EntityKind::Insert(_) => { let mut v = vec![("bedit", None), ("refedit", None)]; - if ents.iter().any(|e| matches!(&e.kind, EntityKind::Insert(i) if !i.attribs.is_empty())) { + if ents.iter().any(|e| matches!(&e.kind, EntityKind::Insert(i) if i.attribs.iter().any(|a| !a.constant))) { v.push(("attedit", Some("Edit Attributes..."))); } v diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index f86a8e1e0..5b2ce53d4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -333,9 +333,9 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) - } "cmdline.input" => { let text = s("text").unwrap_or(""); - let before = app.session.log.len(); + let before = app.session.log_mark(); let error = app.cmdline(text); - let out: Vec = app.session.log.iter().skip(before).cloned().collect(); + let out: Vec = app.session.log_since(before).to_vec(); let mut st = cmdline_state(app); if let Some(o) = st.as_object_mut() { o.insert("output".into(), json!(out)); @@ -346,16 +346,16 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) - ok(st) } "cmdline.script" => { - let before = app.session.log.len(); + let before = app.session.log_mark(); let r = app.session.script(s("text").unwrap_or("")).map_err(|e| e.to_string()); - let out: Vec = app.session.log.iter().skip(before).cloned().collect(); + let out: Vec = app.session.log_since(before).to_vec(); match r { Ok(()) => ok(json!({"output": out, "state": cmdline_state(app)})), Err(e) => err(e), } } "cmdline.key" => { - let before = app.session.log.len(); + let before = app.session.log_mark(); let error = match s("key").unwrap_or("enter").to_ascii_lowercase().as_str() { "escape" | "esc" => { app.paste.cancel(); @@ -368,7 +368,7 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) - if let Some(e) = &error { app.session.echo(e.clone()); } - let out: Vec = app.session.log.iter().skip(before).cloned().collect(); + let out: Vec = app.session.log_since(before).to_vec(); let mut st = cmdline_state(app); if let Some(o) = st.as_object_mut() { o.insert("output".into(), json!(out)); @@ -975,6 +975,48 @@ mod tests { assert_eq!(render_reply(b"abc", 7, 5, None, true)["truncated"], true); } + /// #3643: the command-line methods report the lines a request printed, also when the command + /// history is trimmed from the front meanwhile. + #[test] + fn cmdline_output_survives_the_history_trim() { + // Echo lines until the next one trims the history: grow it to its first trim, then back + // up to the length it had just before it. + fn fill(app: &mut CadApp) { + let mut top = 0; + loop { + let len = app.session.log.len(); + app.session.echo("filler"); + if app.session.log.len() < len { + break; + } + top = app.session.log.len(); + } + while app.session.log.len() < top { + app.session.echo("filler"); + } + } + // The `y` lines a request reports; it reports nothing from before it. + fn ys(app: &mut CadApp, method: &str, params: Value) -> usize { + let (req, _rx) = ControlRequest::new(method, params); + let Outcome::Done(r) = handle(app, &egui::Context::default(), &req) else { panic!("{method} took a screenshot") }; + let out = r["result"]["output"].as_array().cloned().unwrap_or_default(); + assert!(!out.contains(&json!("filler")), "{method}: {r}"); + out.iter().filter(|l| *l == "y").count() + } + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + app.session.new_drawing(false); + let lines = "(repeat 20 (princ \"y\") (terpri))"; + fill(&mut app); + assert_eq!(ys(&mut app, "cmdline.script", json!({"text": format!("{lines}\n")})), 20); + fill(&mut app); + assert_eq!(ys(&mut app, "cmdline.input", json!({"text": lines})), 20); + // Enter repeats a LISP command that prints them. + ys(&mut app, "cmdline.input", json!({"text": format!("(defun c:ys () {lines} (princ))")})); + ys(&mut app, "cmdline.input", json!({"text": "ys"})); + fill(&mut app); + assert_eq!(ys(&mut app, "cmdline.key", json!({"key": "enter"})), 20); + } + /// The reply to a `ui.render` request in an app showing one line along y = 0: colour 7, or /// red on a red layer. fn render_line(red: bool, params: Value) -> Value { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 789f7763d..bc770780d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -32,6 +32,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "preview" => crate::exchange::dialog(app, ctx, &mut open), "pdfimport" => crate::exchange::pdf_dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), + "attedit" => crate::attedit::dialog(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "wblock" => crate::wblock::dialog(app, ctx, &mut open), @@ -279,33 +280,34 @@ fn units(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { .unwrap_or([2, 4, 0, 0, 1]) }); let (mut apply, mut cancel) = (false, false); - egui::Window::new("Drawing Units").open(open).resizable(false).collapsible(false).show(ctx, |ui| { + let title = crate::tl!("Drawing Units"); + egui::Window::new(title).id(egui::Id::unique("Drawing Units")).open(open).resizable(false).collapsible(false).show(ctx, |ui| { let [lu, lp, au, ap, ins] = &mut v; - let types = |t: &[(i64, &str)]| t.iter().map(|(k, l)| (*k, l.to_string())).collect::>(); + let types = |t: &[(i64, &str)]| t.iter().map(|(k, l)| (*k, crate::i18n::t(l).to_string())).collect::>(); egui::Grid::new("units_grid").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { - ui.strong("Length"); + ui.strong(crate::tl!("Length")); ui.end_row(); - ui.label("Type"); + ui.label(crate::tl!("Type")); pick(ui, "units_lunits", lu, &types(&LENGTH_TYPES)); ui.end_row(); - ui.label("Precision"); + ui.label(crate::tl!("Precision")); pick(ui, "units_luprec", lp, &length_precisions(*lu)); ui.end_row(); - ui.strong("Angle"); + ui.strong(crate::tl!("Angle")); ui.end_row(); - ui.label("Type"); + ui.label(crate::tl!("Type")); pick(ui, "units_aunits", au, &types(&ANGLE_TYPES)); ui.end_row(); - ui.label("Precision"); + ui.label(crate::tl!("Precision")); pick(ui, "units_auprec", ap, &(0..=8).map(|p| (p, format_angle(45f64.to_radians(), *au, p))).collect::>()); ui.end_row(); - ui.strong("Insertion scale"); + ui.strong(crate::tl!("Insertion scale")); ui.end_row(); - ui.label("Units to scale inserted content"); - let names = INSERTION_UNITS.iter().enumerate().map(|(k, l)| (k as i64, l.to_string())).collect::>(); + ui.label(crate::tl!("Units to scale inserted content")); + let names = INSERTION_UNITS.iter().enumerate().map(|(k, l)| (k as i64, crate::i18n::t(l).to_string())).collect::>(); pick(ui, "units_insunits", ins, &names); ui.end_row(); - ui.strong("Sample output"); + ui.strong(crate::tl!("Sample output")); ui.end_row(); ui.label(""); ui.label(format!("{},{},{}", format_distance(1.5, *lu, *lp), format_distance(2.0039, *lu, *lp), format_distance(0.0, *lu, *lp))); @@ -316,8 +318,8 @@ fn units(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }); ui.separator(); ui.horizontal(|ui| { - apply = ui.button("OK").clicked(); - cancel = ui.button("Cancel").clicked(); + apply = ui.button(crate::tl!("OK")).clicked(); + cancel = ui.button(crate::tl!("Cancel")).clicked(); }); }); if apply { diff --git a/crates/ui-egui/src/dyninput.rs b/crates/ui-egui/src/dyninput.rs index ed8225fff..3a7c7e37e 100644 --- a/crates/ui-egui/src/dyninput.rs +++ b/crates/ui-egui/src/dyninput.rs @@ -2,7 +2,8 @@ //! //! The command-line text is the single source of truth; the boxes are a view of it: //! - `40` is typing in the first box (X, or the distance for second and next points, which -//! default to polar as in AutoCAD; DYNPIFORMAT = 1 makes them Cartesian). +//! default to polar as in AutoCAD; DYNPIFORMAT = 1 makes them Cartesian). RECTANG's other +//! corner is always X and Y (`Prompt::xy`), so `40` Tab `30` is a 40 by 30 rectangle. //! - `40,` locks X = 40 and moves to Y; `40<` locks the distance and moves to the angle. A locked //! value holds the cursor. //! - Tab types the separator for the format on show, so `40` Tab `90` reads `40<90`; Tab after the @@ -47,7 +48,8 @@ impl Format { pub struct Frame { /// The prompt's base point (the last point), if it has one. pub base: Option, - /// DYNPIFORMAT = 1: second and next points start Cartesian instead of polar. + /// DYNPIFORMAT = 1, or a prompt that asks for X and Y: second and next points start Cartesian + /// instead of polar. pub cartesian: bool, /// DYNPICOORDS = 1: second and next points are absolute instead of relative. pub absolute: bool, diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index 22323768a..ac864d7de 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -52,7 +52,10 @@ pub fn route(app: &mut CadApp, id: &str) -> Result { .pick_then(Pick::Save(format!("{stem}.pdf")), |app, path| app.run("publish", json!({ "path": path }))) .unwrap_or_else(|| no_picker(app, "PUBLISH", "publish {}")), _ => app - .pick_then(Pick::Save(format!("{stem}.svg")), |app, path| app.run("export", json!({ "path": path }))) + .pick_then(Pick::Save(format!("{stem}.svg")), |app, path| { + let params = version_params(&app.ui, &path); + app.run("export", params) + }) .unwrap_or_else(|| no_picker(app, "EXPORT", r#"export {"format": "svg"}"#)), } } @@ -153,6 +156,17 @@ pub fn pdf_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } } +/// SAVEAS or EXPORT parameters for a path picked in the Save or Export dialog: a DXF or DWG file is +/// written in the version chosen under File ▸ Default Save Format (#3213), whatever version the +/// drawing was read in; other formats have no version. +pub(crate) fn version_params(ui: &crate::UiState, path: &str) -> Value { + let drawing_file = matches!(cadcraft_doc::Format::from_path(path), Some(cadcraft_doc::Format::Dxf | cadcraft_doc::Format::Dwg)); + match crate::SaveVersion::parse(&ui.save_version) { + Some(v) if drawing_file => json!({ "path": path, "version": v.year() }), + _ => json!({ "path": path }), + } +} + fn no_picker(app: &mut CadApp, name: &str, example: &str) -> Result { let msg = format!("{name}: there is no file dialog here; run it with parameters, e.g. {example}"); app.session.echo(msg.clone()); @@ -350,6 +364,17 @@ mod tests { (CadApp::new(Session::new(), services), asked, answer) } + #[test] + fn export_writes_drawing_files_in_the_default_save_version() { + // #3213: File ▸ Default Save Format ▸ 2000 makes Export write an R2000 DXF or DWG. + let ui = crate::UiState { save_version: "2000".into(), ..crate::UiState::default() }; + assert_eq!(super::version_params(&ui, "/tmp/plan.dxf"), json!({ "path": "/tmp/plan.dxf", "version": "2000" })); + assert_eq!(super::version_params(&ui, "/tmp/plan.DWG"), json!({ "path": "/tmp/plan.DWG", "version": "2000" })); + // Images and PDF have no version. + assert_eq!(super::version_params(&ui, "/tmp/plan.svg"), json!({ "path": "/tmp/plan.svg" })); + assert_eq!(super::version_params(&ui, "/tmp/plan.pdf"), json!({ "path": "/tmp/plan.pdf" })); + } + fn status(app: &CadApp) -> &str { app.status.as_ref().map(|(s, _)| s.as_str()).unwrap_or_default() } diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 095c2d192..ee30889b8 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -180,11 +180,27 @@ fn premultiplied(c: Rgb, a: u8) -> [u8; 4] { } /// Convert a display list into vertex data relative to `origin`, colours resolved against `bg`. +/// +/// Each array is counted first and allocated once at its final size. Grown by doubling, the quads +/// (wide-line segments and point markers) of a list near its budget passed 1 GiB, and their next +/// size was more than one allocation can take on a 32-bit target (the web build), which panics +/// with "capacity overflow" (#1603). For a list within the display budget (`MAX_DISPLAY_POINTS`, +/// 64M points) no array here passes 1.8 GB. pub fn build_mesh(list: &DisplayList, origin: Vec2, bg: Rgb, lwdisplay: bool) -> MeshData { + let (mut lines, mut quads) = (0usize, 0usize); + for prim in &list.prims { + let n = list.points(prim).len(); + match prim.kind { + Kind::Polyline if wide_width(prim.lw, lwdisplay).is_some() => quads = quads.saturating_add(n.saturating_sub(1)), + Kind::Polyline => lines = lines.saturating_add(n.saturating_sub(1).saturating_mul(2)), + Kind::Point => quads = quads.saturating_add(n.min(1)), + _ => {} + } + } let mut m = MeshData { - lines: Vec::with_capacity(list.segment_count().saturating_mul(2 * VERTEX_SIZE)), + lines: Vec::with_capacity(lines.saturating_mul(VERTEX_SIZE)), tris: Vec::with_capacity(list.tris.len().saturating_mul(VERTEX_SIZE)), - quads: Vec::new(), + quads: Vec::with_capacity(quads.saturating_mul(INSTANCE_SIZE)), breaks: Vec::new(), uploaded: None, }; @@ -243,9 +259,38 @@ pub fn build_mesh(list: &DisplayList, origin: Vec2, bg: Rgb, lwdisplay: bool) -> /// the CPU path: lines `width` points wide, and fills filled, or with `dashed` (SELECTIONEFFECT 0; /// the callback's `dash` dashes the lines) outlined. A wipeout is always outlined, since filling it /// would hide the drawing; infinite lines are left to the CPU (they are clipped per frame). +/// +/// Each array is counted first and allocated once at its final size, as in [`build_mesh`]: grown +/// by doubling, the quads of a selection of more than about 38 million segments passed 1 GiB, and +/// their next size was more than one allocation can take on the web build (#1603). Fill outlines +/// are worked out once, while counting, and kept until they are drawn. pub fn build_highlight_mesh(list: &DisplayList, prims: &[usize], origin: Vec2, color: [u8; 4], width: f32, dashed: bool) -> MeshData { - let mut m = MeshData::default(); - for prim in prims.iter().filter_map(|&i| list.prims.get(i)) { + let selected = || prims.iter().filter_map(|&i| list.prims.get(i)); + // As many as the loop below draws, kind by kind. + let (mut tris, mut quads) = (0usize, 0usize); + let mut outlines = Vec::new(); + for prim in selected() { + let n = list.points(prim).len(); + match prim.kind { + Kind::Polyline => quads = quads.saturating_add(n.saturating_sub(1)), + Kind::Point => quads = quads.saturating_add(n.min(1)), + Kind::Tris if !dashed => tris = tris.saturating_add(n / 3 * 3), + Kind::Tris | Kind::Mask => { + let lines = list.fill_outlines(prim); + quads = lines.iter().fold(quads, |q, line| q.saturating_add(line.len().saturating_sub(1))); + outlines.push(lines); + } + Kind::Infinite { .. } => {} + Kind::Image { .. } => quads = quads.saturating_add(n), + } + } + let mut m = MeshData { + tris: Vec::with_capacity(tris.saturating_mul(VERTEX_SIZE)), + quads: Vec::with_capacity(quads.saturating_mul(INSTANCE_SIZE)), + ..MeshData::default() + }; + let mut outlines = outlines.into_iter(); + for prim in selected() { let pts = list.points(prim); match prim.kind { Kind::Polyline => { @@ -272,7 +317,7 @@ pub fn build_highlight_mesh(list: &DisplayList, prims: &[usize], origin: Vec2, c } } Kind::Tris | Kind::Mask => { - for line in list.fill_outlines(prim) { + for line in outlines.next().unwrap_or_default() { let mut run = 0.0; for s in line.windows(2) { if let [a, b] = s { @@ -295,9 +340,13 @@ pub fn build_highlight_mesh(list: &DisplayList, prims: &[usize], origin: Vec2, c m } +/// Maximum drift of a cached vertex origin from `view_center` (in multiples of `view_height`) +/// before re-centering to preserve `f32` GPU vertex precision. +const MAX_ORIGIN_DRIFT_FACTOR: f64 = 512.0; + /// The vertex origin for a display list seen at `view_center` / `view_height`: the list's centre /// normally; at deep zoom (the view much smaller than the drawing) a point near the view, snapped -/// to a coarse grid so panning re-uploads only every few dozen screens. +/// to a coarse power-of-two grid so consecutive zoom steps and panning re-upload rarely. pub fn choose_origin(bounds: &Bounds2, view_center: Vec2, view_height: f64) -> Vec2 { let size = bounds.width().max(bounds.height()); if bounds.is_empty() @@ -307,8 +356,34 @@ pub fn choose_origin(bounds: &Bounds2, view_center: Vec2, view_height: f64) -> V { return if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; } - let step = view_height * 64.0; - Vec2::new((view_center.x / step).round() * step, (view_center.y / step).round() * step) + let raw = view_height * 64.0; + if !raw.is_finite() || raw <= 0.0 { + return bounds.center(); + } + let exp = raw.log2().floor().clamp(-1000.0, 1000.0) as i32; + let step = 2.0_f64.powi(exp); + if !step.is_finite() || step <= 0.0 { + return bounds.center(); + } + let o = Vec2::new((view_center.x / step).round() * step, (view_center.y / step).round() * step); + if o.is_finite() { o } else { bounds.center() } +} + +/// Whether an already uploaded mesh's `origin` is still close enough to `view_center` for `f32` +/// vertex precision at `view_height`, avoiding needless GPU mesh rebuilds while zooming or panning. +pub fn origin_usable(origin: Vec2, bounds: &Bounds2, view_center: Vec2, view_height: f64) -> bool { + if !origin.is_finite() { + return false; + } + if bounds.is_empty() || !view_center.is_finite() || view_height.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { + return true; + } + let size = bounds.width().max(bounds.height()); + if view_height * 2000.0 >= size && origin == bounds.center() { + return true; + } + let d = (view_center.x - origin.x).abs().max((view_center.y - origin.y).abs()); + d.is_finite() && d <= view_height * MAX_ORIGIN_DRIFT_FACTOR } /// Pending upload shared between the canvas (producer) and the paint callback (consumer). @@ -382,6 +457,7 @@ struct Layer { uniform: wgpu::Buffer, bind_group: wgpu::BindGroup, key: Option, + uploads: u64, lines: Vec, tris: Vec, quads: Vec, @@ -535,7 +611,7 @@ impl Resources { layout: &bgl, entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }], }); - Layer { uniform, bind_group, key: None, lines: Vec::new(), tris: Vec::new(), quads: Vec::new(), breaks: Vec::new() } + Layer { uniform, bind_group, key: None, uploads: 0, lines: Vec::new(), tris: Vec::new(), quads: Vec::new(), breaks: Vec::new() } }; // A render pass with a stencil buffer needs every pipeline to name its format; only the // clipped-viewport pipelines read or write it. @@ -697,6 +773,12 @@ pub fn install(rs: &egui_wgpu::RenderState, faults: &Arc, stencil: Op target } +/// Number of GPU mesh uploads completed on `layer` since [`install`]. +#[doc(hidden)] +pub fn layer_uploads(rs: &egui_wgpu::RenderState, layer: usize) -> u64 { + rs.renderer.read().callback_resources.get::().and_then(|r| r.layers.get(layer)).map_or(0, |l| l.uploads) +} + impl egui_wgpu::CallbackTrait for CanvasCallback { fn prepare( &self, @@ -720,6 +802,7 @@ impl egui_wgpu::CallbackTrait for CanvasCallback { } res.breaks = m.breaks; res.key = Some(self.key); + res.uploads = res.uploads.saturating_add(1); } } let ppp = screen.pixels_per_point; @@ -942,6 +1025,45 @@ mod tests { assert_eq!(wide_width(0.7, false), None); } + #[test] + fn vertex_data_is_allocated_once_at_its_final_size() { + // Grown by doubling, the quads of a list near its budget needed more than a 32-bit target + // can allocate (#1603). A wide copy of the polyline and five more point markers: with + // lineweights shown the wide one becomes quads, otherwise lines. + let mut l = list(); + let mut prims = l.prims.clone(); + prims.extend(l.prims.iter().take(1).map(|p| DPrim { lw: 0.7, ..*p })); + prims.extend(l.prims.iter().filter(|p| p.kind == Kind::Point).cycle().take(5).copied()); + l.prims = prims; + for lwdisplay in [false, true] { + let m = build_mesh(&l, Vec2::ZERO, Rgb(0, 0, 0), lwdisplay); + assert!(m.line_vertices() > 0 && m.tri_vertices() > 0 && m.quad_instances() >= 6, "{lwdisplay}"); + assert_eq!([m.lines.capacity(), m.tris.capacity(), m.quads.capacity()], [m.lines.len(), m.tris.len(), m.quads.len()], "{lwdisplay}"); + } + } + + #[test] + fn highlight_vertex_data_is_allocated_once_at_its_final_size() { + // As in `build_mesh`: grown by doubling, the quads of a selection of about 38 million + // segments needed more than a 32-bit target can allocate (#1603). Every kind the highlight + // draws, a wipeout and an image frame among them, with the polyline selected twice. + let mut l = list(); + let corners = u32::try_from(l.verts.len()).unwrap_or(u32::MAX); + l.verts.extend([Vec2::new(10.0, 10.0), Vec2::new(12.0, 10.0), Vec2::new(12.0, 11.0), Vec2::new(10.0, 11.0)]); + let more: Vec = (l.prims.iter().filter(|p| p.kind == Kind::Tris).map(|p| DPrim { kind: Kind::Mask, ..*p })) + .chain(l.prims.iter().take(1).map(|p| DPrim { kind: Kind::Image { index: 0 }, start: corners, len: 4, ..*p })) + .collect(); + l.prims.extend(more); + let mut sel: Vec = (0..l.prims.len()).collect(); + sel.push(0); + for dashed in [false, true] { + let m = build_highlight_mesh(&l, &sel, Vec2::ZERO, [1, 2, 3, 255], 1.5, dashed); + // Two polylines of two segments, the point, the wipeout's three edges and the frame's four. + assert!(m.quad_instances() >= 12 && (m.tri_vertices() > 0) != dashed, "{dashed}"); + assert_eq!([m.tris.capacity(), m.quads.capacity()], [m.tris.len(), m.quads.len()], "{dashed}"); + } + } + #[test] #[allow(clippy::unwrap_used)] fn shader_is_valid_for_webgpu_and_webgl2() { @@ -970,6 +1092,45 @@ mod tests { assert_eq!(choose_origin(&b, Vec2::new(f64::NAN, 0.0), 1.0), b.center()); } + #[test] + fn choose_origin_is_stable_across_small_zoom_steps() { + let b = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(1e6, 1e6)); + let center = Vec2::new(123_456.7, 654_321.2); + let base = choose_origin(&b, center, 1.0); + for h in [1.1, 1.25, 1.5, 1.9] { + assert_eq!(choose_origin(&b, center, h), base, "view_height {h} changed origin within 2x band"); + } + // Panning far away or zooming across much larger/smaller scales still tracks the camera. + let panned = choose_origin(&b, Vec2::new(900_000.0, 900_000.0), 1.0); + assert_ne!(panned, base); + assert!((panned.x - 900_000.0).abs() <= 32.0); + let zoomed_out = choose_origin(&b, center, 64.0); + assert!((zoomed_out.x - center.x).abs() <= 2048.0); + let zoomed_in = choose_origin(&b, Vec2::new(123_456.789, 654_321.123), 1e-3); + assert!((zoomed_in.x - 123_456.789).abs() <= 0.1); + // Degenerate view heights and extreme scales fall back cleanly without panicking or NaN. + assert_eq!(choose_origin(&b, center, 0.0), b.center()); + assert_eq!(choose_origin(&b, center, -1.0), b.center()); + assert_eq!(choose_origin(&b, center, f64::NAN), b.center()); + assert!(choose_origin(&b, center, 1e-300).is_finite()); + assert_eq!(choose_origin(&b, center, 1e300), b.center()); + } + + #[test] + fn origin_usable_keeps_origin_within_precision_budget() { + let b = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(1e6, 1e6)); + let center = Vec2::new(123_456.7, 654_321.2); + let o = choose_origin(&b, center, 1.0); + // Small pans and zooming out or moderately in keep the uploaded origin valid. + assert!(origin_usable(o, &b, center + Vec2::new(100.0, -200.0), 1.0)); + assert!(origin_usable(o, &b, center, 10.0)); + assert!(origin_usable(o, &b, o + Vec2::new(256.0, -256.0), 0.5)); + // Exceeding 512 * view_height or non-finite origins force a recenter. + assert!(!origin_usable(o, &b, o + Vec2::new(513.0, 0.0), 1.0)); + assert!(!origin_usable(o, &b, o + Vec2::new(60.0, 0.0), 0.1)); + assert!(!origin_usable(Vec2::new(f64::NAN, 0.0), &b, center, 1.0)); + } + #[test] fn wipeout_masks_start_a_draw_order_group() { let mut l = list(); diff --git a/crates/ui-egui/src/grip_dyn.rs b/crates/ui-egui/src/grip_dyn.rs index 0b5473853..13a788738 100644 --- a/crates/ui-egui/src/grip_dyn.rs +++ b/crates/ui-egui/src/grip_dyn.rs @@ -342,6 +342,46 @@ mod tests { } } + /// RECTANG's other corner asks for X and Y whatever DYNPIFORMAT says, as the reference + /// application does, so `40` Tab `30` Enter is a 40 by 30 rectangle, not 40 at 30 degrees. + #[test] + fn rectangle_corner_asks_for_x_and_y_in_either_format() { + for cartesian in [false, true] { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + app.session.settings.dynpi_cartesian = cartesian; + let ctx = egui::Context::default(); + crate::framework::install_headless(&ctx); + crate::canvas::tests::painted_text(&mut app, &ctx, pos2(700.0, 450.0)); + let at = app.canvas.xf.unwrap().to_screen(Vec2::new(10.0, 20.0)) + vec2(130.0, -70.0); + app.session.cmdline("rectang").unwrap(); + app.session.input(Input::Point(Vec2::new(10.0, 20.0))).unwrap(); + crate::canvas::tests::painted_text(&mut app, &ctx, at); + crate::canvas::tests::painted_text(&mut app, &ctx, at); + let frame = crate::cmdline::dyn_frame(&app).unwrap(); + assert_eq!(frame.default_format(), crate::dyninput::Format::Cartesian, "DYNPIFORMAT {cartesian}"); + + run_frame(&mut app, &ctx, vec![Event::Text("40".into())]); + run_frame(&mut app, &ctx, key(egui::Key::Tab)); + run_frame(&mut app, &ctx, vec![Event::Text("30".into())]); + run_frame(&mut app, &ctx, key(egui::Key::Enter)); + assert!(app.session.running.is_none(), "DYNPIFORMAT {cartesian}"); + let bounds = app.session.doc().unwrap().model.iter().find_map(|e| match &e.kind { + EntityKind::LwPolyline(pl) => { + let xs = pl.vertices.iter().map(|v| v.p.x); + let ys = pl.vertices.iter().map(|v| v.p.y); + Some(( + xs.clone().fold(f64::MAX, f64::min), + ys.clone().fold(f64::MAX, f64::min), + xs.fold(f64::MIN, f64::max), + ys.fold(f64::MIN, f64::max), + )) + } + _ => None, + }); + assert_eq!(bounds, Some((10.0, 20.0, 50.0, 50.0)), "DYNPIFORMAT {cartesian}"); + } + } + /// The grip's length fields read the drawing's length units (LUNITS/LUPREC) (#841). #[test] fn length_fields_follow_the_drawing_units() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index c08357995..c3ffc4631 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -352,8 +352,24 @@ fn parse(source: &str) -> (Catalog<'_>, Vec) { (entries, errors) } +fn merge_ordinary_zh<'a>(catalog: &mut Catalog<'a>, supplemental: &'a str) { + for ((context, key), value) in parse(supplemental).0 { + if context.is_empty() { + catalog.entry((context, key)).or_insert(value); + } + } +} + fn catalog(language: &str) -> Option<&'static Catalog<'static>> { - LANGUAGES.iter().find(|l| l.code == language && !l.source.is_empty()).map(|l| l.catalog.get_or_init(|| parse(l.source).0)) + LANGUAGES.iter().find(|l| l.code == language && !l.source.is_empty()).map(|l| { + l.catalog.get_or_init(|| { + let mut entries = parse(l.source).0; + if l.code == "zh" { + merge_ordinary_zh(&mut entries, include_str!("i18n/zh_shared.tsv")); + } + entries + }) + }) } pub fn tr<'a>(language: &str, source: &'a str) -> &'a str { diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9b6a44102..e3726eaf4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -74,6 +74,7 @@ Area Plocha Arrange Panel Uspořádat panel Array Pole + Arrow size Velikost šipky Attach Připojit Attribute Atribut Attribute Definition Definice atributu @@ -105,6 +106,7 @@ Box Kvádr Break Přerušit Break At Point Přerušit v bodě + Break-line Symbol Značka přerušení čáry Bring Above Objects Přenést nad objekty Bring Annotations to Front Přenést popisy dopředu Bring to Front Přenést dopředu @@ -136,6 +138,10 @@ Clear Vymazat Clip Oříznout hranicí Clip Viewport Oříznout výřez + Clip Xref Oříznout externí referenci + Xref Clip Frame Rámeček oříznutí externí reference + Xref Externí reference + Multiple Insert Vícenásobné vložení Clipboard Schránka Close Zavřít Close All Zavřít vše @@ -144,6 +150,7 @@ Close Comparison Zavřít porovnání Export Comparison Exportovat porovnání Coincident Totožnost + Collapse Palettes Sbalit palety Collapse Tool Sets Sbalit sady nástrojů Collinear Kolinearita Color Barva @@ -171,6 +178,7 @@ Contributors Přispěvatelé Control Vertices Řídicí vrcholy Convert Převést + Convert Text to Mtext Převést text na víceřádkový text Copy Kopírovat Copy Full File Path Kopírovat úplnou cestu k souboru Copy History Kopírovat historii @@ -193,7 +201,10 @@ Cylinder Válec DWG DWG DWG Reference... Reference DWG... + Raster Image Reference... Reference rastrového obrázku... + Raster Images Rastrové obrázky DXF DXF + DView Dynamický pohled Dark Tmavé Data Extraction... Extrahovat data... Default Výchozí @@ -221,6 +232,7 @@ Description Popis Deselect All Zrušit celý výběr Diameter Průměr + Dim scale overall Celkové měřítko kót Dim style Kótovací styl Dimension Break Přerušení kóty Dimension Edit Upravit kótu @@ -320,11 +332,14 @@ Equal Shodnost Erase Vymazat objekty Evaluate Vyhodnotit + Evaluate LISP Vyhodnotit LISP Exclude from new selection set Vyloučit z nové výběrové množiny Explode Rozložit + Explode Attributes to Text Rozložit atributy na text Export Exportovat Export Table Exportovat tabulku Export to PDF... Exportovat do PDF... + Express Tools Doplňkové nástroje Expression Výraz Extend Prodloužit Extension Prodloužení @@ -404,6 +419,10 @@ How to apply: Způsob použití: ID Point Souřadnice bodu Import Importovat + Align Multileaders Srovnat multiodkazy + Collect Shromáždit + Collect Multileaders Shromáždit multiodkazy + Edit Multileader Upravit multiodkaz In Přiblížit pohled In-window Menu Bar Nabídka v okně Include in new selection set Zahrnout do nové výběrové množiny @@ -495,6 +514,10 @@ List Text Styles Vypsat styly textu Load all Načíst vše Load... Načíst... + Load Application... Načíst aplikaci... + Enter name of LISP file to load Zadejte název souboru LISP k načtení + Enter geometric characteristic Zadejte geometrickou charakteristiku + Enter block names to extract Zadejte názvy bloků pro extrakci dat Loaded linetypes Načtené typy čar Lock Zamknout Lock Layer Zamknout hladinu @@ -525,6 +548,7 @@ Models Modely Modify Upravit Move Posunout + Move/Copy/Rotate Posunout/Kopírovat/Otočit Multileader Multiodkaz Multileader Style... Styl multiodkazu... Multileader style Styl multiodkazů @@ -589,6 +613,8 @@ Open sample drawing Otevřít ukázku výkresu Open Xref Otevřít externí referenci Open... Otevřít... + Open Recent Otevřít nedávné + Clear Recent Files Vymazat seznam nedávných souborů Operator: Operátor: Orbit Orbit Ordinate Souřadnicová @@ -677,6 +703,7 @@ Position X Poloha X Position Y Poloha Y Position Z Poloha Z + Precision Přesnost Previous Předchozí Previous Change Předchozí změna Previous Layer Předchozí hladina @@ -850,6 +877,8 @@ Show All Zobrazit vše Show All Constraint Bars Zobrazit všechny lišty vazeb Show All Dynamic Dimensions Zobrazit všechny dynamické kóty + Show and hide the tools of this category Zobrazit nebo skrýt nástroje této kategorie + Show in Tool Sets Zobrazit v sadách nástrojů Show command prompting near the crosshairs Zobrazovat výzvy příkazů u nitkového kříže Show Layer List Zobrazit seznam hladin Show/Hide Lineweight Zobrazit/Skrýt tloušťku čáry @@ -936,21 +965,32 @@ Command line history Historie příkazového řádku Copy as JSON Kopírovat jako JSON Crosshair size Velikost nitkového kříže + Crossing selection color: Barva výběru křížícím oknem: Display Zobrazení + Exclude: Vyloučit: Grip size Velikost uzlů + Grips Uzly + Groups Skupiny + Hatches Šrafy Hold Shift to add to the selection Podržením klávesy Shift přidáte objekty k výběru + Indicate selection area Zobrazovat oblast výběru Interface language Jazyk uživatelského rozhraní Interface theme Motiv uživatelského rozhraní Keep the system cursor visible over the drawing area Ponechat systémový kurzor viditelný nad kreslicí plochou Largest array Největší pole Layout paper Papír rozvržení Model background Pozadí modelu + Multiline text Víceřádkový text + Object grouping Výběr skupin objektů + Object selection limit for display of grips Limit vybraných objektů pro zobrazení uzlů Object snap aperture Dosah uchopení objektu Object snap marker size Velikost značky uchopení objektu + Objects on locked layers Objekty na zamčených hladinách Open and Save Otevírání a ukládání Options Možnosti Options... Možnosti... Pickbox size Velikost výběrového terčíku + Preview Náhled Profiles Profily Reset keeps the interface language. Obnovení výchozího nastavení zachová jazyk rozhraní. Reset to Defaults Obnovit výchozí nastavení @@ -958,11 +998,25 @@ Screen magnifiers, screen readers and recorders follow the system cursor. Lupy, čtečky obrazovky a záznamové nástroje sledují systémový kurzor. Select objects first, then choose a command Nejprve vybrat objekty, potom zvolit příkaz Selection Výběr + Selection Area Effect Efekt oblasti výběru + Selection Preview Filter Filtr náhledu výběru + Selection area opacity: Krytí oblasti výběru: + Selection effect color Barva efektu výběru + Selection modes Režimy výběru + Selection preview Náhled výběru Settings... Nastavení... Show Quick Properties for selected objects Zobrazovat rychlé vlastnosti vybraných objektů + Show grips Zobrazovat uzly Snap, grid, polar tracking and Dynamic Input: Uchopení, rastr, polární trasování a dynamické zadávání: + Tables Tabulky The aperture is how near the cursor must come to a point for an object snap to find it. Dosah určuje, jak blízko se kurzor musí přiblížit k bodu, aby jej uchopení objektu nalezlo. User Preferences Uživatelské předvolby + Visual Effect Settings Nastavení vizuálních efektů + Visual Effect Settings... Nastavení vizuálních efektů... + When a command is active Při aktivním příkazu + When no command is active Bez aktivního příkazu + Window selection color: Barva výběru oknem: + Xrefs Externí reference objects objektů Specify inside diameter of donut Určete vnitřní průměr prstence Specify leader arrowhead location Určete polohu šipky odkazu @@ -1183,6 +1237,7 @@ Show System Cursor Zobrazit systémový kurzor Animation Effects Efekty animace Animation effects Efekty animace + Interface scale Měřítko uživatelského rozhraní Import... Importovat... Export... Exportovat... Batch Publish... Dávkově publikovat... @@ -1208,23 +1263,187 @@ Multiline... Multičára... Multiline Style... Styl multičáry... Solid Editing Úpravy těles + 3D Mouse... 3D myš... + 3D Mouse 3D myš + Calibrate 3D Mouse Kalibrovat 3D myš + 3D Mouse Navigation Ovládání pohledu 3D myší + 3D mouse input is unavailable on this platform Vstup z 3D myši není na této platformě dostupný + No supported 3D mouse found Nebyla nalezena žádná podporovaná 3D myš + Release the 3D mouse to calibrate its resting position Uvolněte 3D myš pro kalibraci její klidové polohy + 3D mouse connected 3D myš je připojena + 3D mouse busy, possibly 3DxWare or missing device permissions 3D myš je obsazena, příčinou může být 3DxWare nebo chybějící oprávnění k zařízení + 3D mouse disconnected 3D myš je odpojena + 3D mouse input could not be started Příjem vstupu z 3D myši se nepodařilo spustit + Enable 3D mouse navigation Zapnout ovládání pohledu 3D myší + Pan sensitivity Citlivost posunu pohledu + Zoom sensitivity Citlivost změny přiblížení + Reverse zoom direction Obrátit směr změny přiblížení + Calibrate Kalibrovat + Move sideways to pan; push/pull or twist to zoom. Pohybem do stran posunete pohled; zatlačením, přitažením nebo otočením změníte přiblížení. + Left device button: zoom extents. Right device button: calibrate. Levým tlačítkem zařízení přiblížíte na rozsah. Pravým tlačítkem spustíte kalibraci. X X Y Y B B CADCraft CADCraft More toolbar commands Další příkazy panelu nástrojů + Default save version Výchozí verze formátu pro ukládání + Automatic save every Interval automatického ukládání + min min + Automatic save file location Umístění souborů automatického ukládání + Backup copy Záložní kopie + Create backup copy with each save Při každém uložení vytvořit záložní kopii + Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. Výkresy, které ještě nemají soubor, se ukládají ve výchozí verzi formátu. Hodnota 0 minut vypíná automatické ukládání. + Time-sensitive right-click: a quick click is Enter, holding opens the menu Rozlišovat délku stisku pravého tlačítka: krátké kliknutí odpovídá klávese Enter, podržení otevře místní nabídku + Turned off, a right-click while a command runs always opens the shortcut menu. Při vypnuté volbě kliknutí pravým tlačítkem během příkazu vždy otevře místní nabídku. + Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. Při vypnuté volbě se kliknutí pravým tlačítkem během příkazu řídí nastavením Režim příkazu v Přizpůsobení pravého tlačítka. menu View Zobrazení menu Draw Kreslení menu Dimension Kótování menu Modify Modifikace Hatch Pattern Vzor šrafy Search for pattern Hledat vzor + Run Script... Spustit skript... Not a number or distance: {text} Není číslo ani vzdálenost: {text} + Dynamic Block Data Data dynamického bloku + Custom Vlastní + Dynamic Block Reference Reference dynamického bloku + Set Dynamic Property Nastavit dynamickou vlastnost + Dynamic Block Grips Uzly dynamického bloku + Drag Dynamic Grip Přetáhnout dynamický uzel + Save Block Uložit blok + Save Block As Uložit blok jako + Close Block Editor Zavřít editor bloků + Unsaved changes Neuložené změny + Edit Block Definition Upravit definici bloku + Block to create or edit Blok k vytvoření nebo úpravě + Open in Block Editor Otevřít v editoru bloků + This drawing Tento výkres + contains authoring elements. Open in Block Editor? obsahuje prvky pro tvorbu dynamického bloku. Chcete jej otevřít v editoru bloků? + New block Nový blok + Italic Kurzíva + Underline Podtržení + Overline Nadtržení + Justify Do bloku + Text color Barva textu + Click the ruler to add a tab stop, right-click to remove one Kliknutím na pravítko přidáte zarážku tabulátoru, kliknutím pravým tlačítkem ji odeberete + Select using two clicks only Vybírat pouze dvěma kliknutími + Define each corner of the selection window with a separate click. Každý roh výběrového okna určete samostatným kliknutím. + Type an alias name. Zadejte název aliasu. + Choose the command the alias starts. Zvolte příkaz, který alias spouští. + {command} is an unknown command. {command} je neznámý příkaz. + {alias} is already defined; select it and use Edit. Alias {alias} je již definován; vyberte jej a použijte tlačítko „Upravit…“. + More than {n} aliases. Byl překročen limit {n} aliasů. + Alias file: {file} Soubor aliasů: {file} + No alias file loaded. REINIT replaces these aliases with a file's. Není načten žádný soubor aliasů. Příkaz REINIT nahradí tyto aliasy aliasy ze souboru. + Aliases are saved in your CADCraft profile and survive restarts. Aliasy se ukládají do vašeho profilu CADCraftu a zůstanou zachovány i po restartu. + Alias Alias + Command Příkaz + overrides built-in nahrazuje vestavěný alias + built-in vestavěný + Add… Přidat… + Edit… Upravit… + Import… Importovat… + Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. Import: dialog pro výběr souboru tu není k dispozici; spusťte ALIASEDIT s obsahem souboru v parametru text. + Run ALIASEDIT with the file's contents using its text parameter. Spusťte ALIASEDIT s obsahem souboru v parametru text. + Importing a file replaces your {n} aliases, and any changes not applied yet. Import souboru nahradí vaše aliasy (počet: {n}) i všechny dosud nepoužité změny. + Import and replace Importovat a nahradit + Keep my aliases Ponechat moje aliasy + {n} more warnings; see the command line. Další varování: {n}; podrobnosti najdete na příkazovém řádku. + Alias files (PGP) Soubory aliasů (PGP) + Save alias Uložit alias + Discard Zahodit úpravy + Customize Přizpůsobit + Edit Command Aliases (PGP)... Upravit aliasy příkazů (PGP)... Query Texts Dotaz na texty Analyze Shapes Analyzovat tvary + Hatch Pick Výběr pro šrafy + Hatch and Gradient Šrafy a přechod + Color 1 Barva 1 + Color 2 Barva 2 + Shape Tvar + Curved Zakřivený + Spherical Kulový + Hemispherical Polokulový + Inverted Obrácený + Centered Vystředěný + Hatch origin Počátek šraf + Use current origin Použít aktuální počátek + Specified origin Zadaný počátek + Click to set new origin Zadat nový počátek kliknutím + Default to boundary extents Použít rozsah hranic + Bottom left Vlevo dole + Bottom right Vpravo dole + Top left Vlevo nahoře + Top right Vpravo nahoře + Boundaries Hranice + Add: Pick points Přidat: vybrat body + Add: Select objects Přidat: vybrat objekty + Boundaries picked: {n} Počet vybraných hranic: {n} + Select boundaries to remove Vyberte hranice k odebrání + Island Ostrov + Associative Asociativní + Create separate hatches Vytvářet samostatné šrafy + Island detection Detekce ostrovů + Outer Vnější + Ignore Ignorovat + Origin: {x}, {y} Počátek: {x}, {y} + Sheet Books to PDF... Exportovat sady listů do PDF... + Analyze Usage Analýza využití + AutoLISP (LSP) AutoLISP (LSP) + SVG drawings (SVG, SVGZ) Výkresy SVG (SVG, SVGZ) + Imperial (inches) Imperiální (palce) + Implied Loops Odvozené smyčky + Metric (millimetres) Metrické (milimetry) + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). Příkaz Nový i první výkres po spuštění používají tyto jednotky, pokud není nastavena výchozí šablona (QNEWTEMPLATE). + Units of new drawings Jednotky nových výkresů Check for Updates… Zkontrolovat aktualizace… CADCraft is up to date. CADCraft je aktuální. Could not check for updates. Aktualizace se nepodařilo zkontrolovat. + Font Písmo + Change Změnit + Change Properties Změnit vlastnosti + Units Jednotky + Save Layout as Template Uložit rozvržení jako šablonu + Save changes to block "{name}"? Uložit změny do bloku „{name}“? + Find All Najít vše + Find what: Najít co: + Match case Rozlišovat velikost písmen + Replace Nahradit + Replace All Nahradit vše + Replace with: Nahradit čím: + Replacement text Nahrazující text + Results Výsledky + Searches the current space. Prohledává aktuální prostor. + Text to find Hledaný text + Whole words Celá slova + Nothing found Nic nenalezeno + Ctrl+Enter to apply Ctrl+Enter potvrdí + Edit Text Upravit text + The drawing changed. Close the window and open it again. Výkres se změnil. Zavřete okno a otevřete jej znovu. + Keyboard Shortcuts... Klávesové zkratky... + Keyboard Shortcuts Klávesové zkratky + Replaces the shortcut of {commands} Nahradí zkratku pro: {commands} + Needs Ctrl, Alt or a function key Vyžaduje Ctrl, Alt nebo funkční klávesu + Press the keys Stiskněte klávesy + Back to CADCraft's shortcut Vrátit zkratku CADCraftu + A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Vámi zadaná zkratka má přednost před zkratkou CADCraftu. Změny se projeví okamžitě a uloží se pro příště. + Right-Click Customization... Přizpůsobení pravého tlačítka... + Right-Click Customization Přizpůsobení pravého tlačítka + Turn on time-sensitive right-click Zapnout rozlišování délky stisku pravého tlačítka + Longer click duration: Doba delšího kliknutí: + milliseconds milisekund + While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Během příkazu krátké kliknutí odpovídá klávese Enter a delší kliknutí otevře místní nabídku. + Default Mode Výchozí režim + No objects selected and no command running: Není vybrán žádný objekt a neběží žádný příkaz: + Edit Mode Režim úprav + Objects selected and no command running: Jsou vybrány objekty a neběží žádný příkaz: + Repeat last command Opakovat poslední příkaz + Shortcut Menu Místní nabídka + Command Mode Režim příkazu + While a command runs: Během příkazu: + ENTER ENTER + Shortcut Menu: always enabled Místní nabídka: vždy zapnutá + Shortcut Menu: enabled when command options are present Místní nabídka: zapnutá, když má příkaz možnosti Add a drawing file as a block library Přidat výkresový soubor jako knihovnu bloků Add a folder of drawings or a drawing file to use its blocks. Přidejte složku s výkresy nebo výkresový soubor, abyste mohli používat jeho bloky. Block Libraries Knihovny bloků @@ -1241,7 +1460,7 @@ menu Modify Modifikace Libraries Knihovny Medium Icons Střední ikony No block matches the filter. Filtru neodpovídá žádný blok. - This block is already in the drawing, so its definition is used. Tento blok už v kresbě je, proto se použije jeho definice. + This block is already in the drawing, so its definition is used. Tento blok už ve výkresu je, proto se použije jeho definice. Open Library... Otevřít knihovnu... Read the library again Načíst knihovnu znovu Reading the library... Načítání knihovny... @@ -1252,21 +1471,211 @@ menu Modify Modifikace This drawing has no blocks. Tento výkres neobsahuje žádné bloky. This library has no drawings or blocks. Tato knihovna neobsahuje žádné výkresy ani bloky. Only the first {n} are shown. Zobrazuje se pouze prvních {n}. - Find All Find All - Find what: Find what: - Match case Match case - Replace Replace - Replace All Replace All - Replace with: Replace with: - Replacement text Replacement text - Results Results - Searches the current space. Searches the current space. - Text to find Text to find - Whole words Whole words - Nothing found Nothing found - Ctrl+Enter to apply Ctrl+Enter to apply - Edit Text Edit Text - The drawing changed. Close the window and open it again. Výkres se změnil. Zavřete okno a otevřete jej znovu. # ArtCraft feature naming Additional Tools Další nástroje + +# Dimension styles and dimension properties +