mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-16 10:49:50 -06:00
Compare commits
74
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
259d892a33 | ||
|
|
2ccf5874b0 | ||
|
|
ed0fbce27c | ||
|
|
e1b86d5743 | ||
|
|
cb36b573c3 | ||
|
|
32dfdef71c | ||
|
|
29e17181bf | ||
|
|
b21747b30b | ||
|
|
b3d11070e4 | ||
|
|
155fd45d61 | ||
|
|
0bc69feed0 | ||
|
|
13f4d09b6d | ||
|
|
27256f0ba5 | ||
|
|
386750bd56 | ||
|
|
eec225a218 | ||
|
|
7013ce459c | ||
|
|
7b525189c0 | ||
|
|
13de76e5b2 | ||
|
|
afe77dc0d4 | ||
|
|
e5091e052e | ||
|
|
d267d6580e | ||
|
|
2974d74bdc | ||
|
|
0e3f62f50d | ||
|
|
007a24ef94 | ||
|
|
f9c0c96e63 | ||
|
|
1069c8217a | ||
|
|
6dfc0ef6a2 | ||
|
|
11e90d34fb | ||
|
|
0dae816499 | ||
|
|
a009f7d022 | ||
|
|
e7a51dcc3d | ||
|
|
c985814fcb | ||
|
|
a853649ffa | ||
|
|
ed6377fc46 | ||
|
|
7cb07b2f3b | ||
|
|
923f4174a6 | ||
|
|
9789562ac7 | ||
|
|
a20a46f7c3 | ||
|
|
682034d737 | ||
|
|
db70717001 | ||
|
|
173cdf6e8a | ||
|
|
5b170664aa | ||
|
|
305f452283 | ||
|
|
78bcdce794 | ||
|
|
fd11b47915 | ||
|
|
91b14c83cf | ||
|
|
ca6c100342 | ||
|
|
072ec4500a | ||
|
|
8a4e275466 | ||
|
|
58a13b5a64 | ||
|
|
a5a5550165 | ||
|
|
281f86d602 | ||
|
|
caaa0e37f7 | ||
|
|
c07b6a2ff7 | ||
|
|
7064a685a8 | ||
|
|
e43c39c55e | ||
|
|
deff6cb092 | ||
|
|
67514021ae | ||
|
|
6749299b95 | ||
|
|
4072f84290 | ||
|
|
f877213876 | ||
|
|
06203e4958 | ||
|
|
8e69890223 | ||
|
|
fbb083803b | ||
|
|
54dfb2ee00 | ||
|
|
fa7a97728b | ||
|
|
2a9fc8f241 | ||
|
|
ddfa833bc2 | ||
|
|
bf581c2376 | ||
|
|
fefb973754 | ||
|
|
ff2163ddfe | ||
|
|
64f707968f | ||
|
|
2ac6d98dac | ||
|
|
a84de56183 |
@@ -23,43 +23,5 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
|
||||
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main
|
||||
|
||||
@@ -28,51 +28,9 @@ jobs:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
release:
|
||||
needs: [git-sources, credits]
|
||||
needs: credits
|
||||
permissions:
|
||||
# The reusable release workflow tags and uploads the draft release.
|
||||
contents: write
|
||||
|
||||
@@ -114,3 +114,7 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
## Shared libraries
|
||||
|
||||
Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers.
|
||||
|
||||
+3
-1
@@ -23,6 +23,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `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`. |
|
||||
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
|
||||
@@ -62,6 +63,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | @dmatviichuk | Original Ukrainian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/pl.tsv` | @neronek22 (Echo Rozumu & Gadajło; AI-assisted) | Original Polish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/de.tsv` | the CADCraft contributors | Original German translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/es.tsv` | @PedroGuille | Original Spanish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/pt_br.tsv` | @WladmirJunior | Original Brazilian Portuguese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
@@ -76,6 +78,6 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `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/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending |
|
||||
| `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 chosen with a native speaker, full proofreading pending |
|
||||
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
|
||||
|
||||
Generated
+412
-25
@@ -156,6 +156,21 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
@@ -284,6 +299,9 @@ name = "arrayvec"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "as-raw-xcb-connection"
|
||||
@@ -513,6 +531,12 @@ version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -568,6 +592,16 @@ dependencies = [
|
||||
"piper",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "6.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -614,7 +648,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-io",
|
||||
@@ -645,7 +679,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-cli"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-io",
|
||||
@@ -661,14 +695,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-color"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-constraints"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-doc",
|
||||
"cadcraft-geom",
|
||||
@@ -678,7 +712,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-doc"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-geom",
|
||||
@@ -687,17 +721,9 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-dwg"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-engine"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-constraints",
|
||||
@@ -708,6 +734,7 @@ dependencies = [
|
||||
"cadcraft-render",
|
||||
"craft-docpath",
|
||||
"craft-dxf",
|
||||
"craft-mime",
|
||||
"libc",
|
||||
"log",
|
||||
"rstar",
|
||||
@@ -718,10 +745,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-fonts"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-geom",
|
||||
"craft-dxf",
|
||||
"craft-font-catalog",
|
||||
"craft-shx",
|
||||
"encoding_rs",
|
||||
"harfrust 0.14.0",
|
||||
"icu_segmenter",
|
||||
@@ -731,41 +760,45 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-geom"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-io"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"cadcraft-color",
|
||||
"cadcraft-doc",
|
||||
"cadcraft-dwg",
|
||||
"cadcraft-fonts",
|
||||
"cadcraft-geom",
|
||||
"cadcraft-render",
|
||||
"craft-dwg",
|
||||
"craft-dxf",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-pdf",
|
||||
"craft-svg",
|
||||
"image",
|
||||
"miniz_oxide 0.9.1",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"tiny-skia",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-mcp"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"clap",
|
||||
"craft-jsonrpc",
|
||||
"craft-mcp",
|
||||
"getrandom 0.4.3",
|
||||
"libc",
|
||||
"log",
|
||||
@@ -775,12 +808,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-render"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-doc",
|
||||
"cadcraft-fonts",
|
||||
"cadcraft-geom",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"lyon_tessellation",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
@@ -789,15 +823,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-ui-egui"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-doc",
|
||||
"cadcraft-engine",
|
||||
"cadcraft-fonts",
|
||||
"cadcraft-geom",
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"chrono",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
@@ -816,7 +852,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-web"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-fonts",
|
||||
@@ -1138,21 +1174,52 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf#7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=006e4df225fca57e95ead0fb1f91920900798a99#006e4df225fca57e95ead0fb1f91920900798a99"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
dependencies = [
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
|
||||
"encoding_rs",
|
||||
"kurbo",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c07e38090879ffa994f893df9956c6d5b96c049c#c07e38090879ffa994f893df9956c6d5b96c049c"
|
||||
dependencies = [
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -1181,6 +1248,123 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jsonrpc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mcp"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
dependencies = [
|
||||
"craft-jsonrpc",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -1191,6 +1375,45 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-shx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2f2d1d84e3a36b3f93e81507aeff3f0da97a7162#2f2d1d84e3a36b3f93e81507aeff3f0da97a7162"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
"kurbo",
|
||||
"quick-xml 0.41.0",
|
||||
"roxmltree",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -1270,6 +1493,16 @@ dependencies = [
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.3"
|
||||
@@ -1759,6 +1992,22 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.74.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
"half",
|
||||
"lebe",
|
||||
"miniz_oxide 0.8.9",
|
||||
"multiversion",
|
||||
"rayon-core",
|
||||
"smallvec",
|
||||
"zune-inflate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2263,6 +2512,9 @@ name = "hayro-jpeg2000"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
@@ -2565,9 +2817,12 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"byteorder-lite",
|
||||
"color_quant",
|
||||
"gif",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
@@ -2707,6 +2962,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -2790,6 +3051,7 @@ dependencies = [
|
||||
"arrayvec",
|
||||
"euclid",
|
||||
"polycool",
|
||||
"serde",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2799,6 +3061,12 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
|
||||
[[package]]
|
||||
name = "lebe"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -2839,6 +3107,19 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo",
|
||||
"polycool",
|
||||
"rustc-hash 2.1.3",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
@@ -2991,6 +3272,28 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
|
||||
dependencies = [
|
||||
"multiversion-macros",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion-macros"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -3859,6 +4162,15 @@ version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qoi"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "2.0.1"
|
||||
@@ -3969,6 +4281,17 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.44.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.45.1"
|
||||
@@ -4076,6 +4399,15 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rstar"
|
||||
version = "0.13.0"
|
||||
@@ -4433,6 +4765,16 @@ dependencies = [
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.47.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.44.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.48.0"
|
||||
@@ -4656,6 +4998,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-features"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -5073,6 +5421,27 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.18.0"
|
||||
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.18.0"
|
||||
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-geom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.2.0"
|
||||
@@ -5995,7 +6364,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"serde_json",
|
||||
@@ -6248,6 +6617,15 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-inflate"
|
||||
version = "0.2.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
|
||||
dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpeg"
|
||||
version = "0.5.15"
|
||||
@@ -6257,6 +6635,15 @@ dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpegxl"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
|
||||
dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant"
|
||||
version = "5.15.1"
|
||||
|
||||
+12
-3
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
# default-members
|
||||
|
||||
[workspace.package]
|
||||
version = "0.20.1"
|
||||
version = "0.21.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -14,8 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
# internal
|
||||
cadcraft-geom = { path = "crates/geom" }
|
||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" }
|
||||
cadcraft-dwg = { path = "crates/dwg" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
|
||||
cadcraft-color = { path = "crates/color" }
|
||||
cadcraft-doc = { path = "crates/doc" }
|
||||
cadcraft-constraints = { path = "crates/constraints" }
|
||||
@@ -25,11 +28,17 @@ cadcraft-io = { path = "crates/io" }
|
||||
cadcraft-engine = { path = "crates/engine" }
|
||||
cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false }
|
||||
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "c07e38090879ffa994f893df9956c6d5b96c049c", default-features = false }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
|
||||
@@ -11,7 +11,7 @@ Third-party material
|
||||
|
||||
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
|
||||
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the
|
||||
Mozilla Public License 2.0 and is used unmodified as a separate library (crates/dwg). Its source
|
||||
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
|
||||
is available from crates.io and the repository above.
|
||||
|
||||
|
||||
@@ -48,3 +48,127 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
JPEG encoding dependency: jpeg-encoder 0.6.1
|
||||
|
||||
Source: https://crates.io/crates/jpeg-encoder/0.6.1
|
||||
Declared license: (MIT OR Apache-2.0) AND IJG.
|
||||
This software is based in part on the work of the Independent JPEG Group.
|
||||
|
||||
The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0
|
||||
alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root
|
||||
(https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1).
|
||||
The dependency is used unmodified; no encoder implementation is vendored here.
|
||||
|
||||
LICENSE-MIT
|
||||
|
||||
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
Original src/fdct.rs opening notice
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg to rust
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1991-1996, Thomas G. Lane.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2015, 2020, D. R. Commander.
|
||||
*
|
||||
* Conditions of distribution and use:
|
||||
* In plain English:
|
||||
*
|
||||
* 1. We don't promise that this software works. (But if you find any bugs,
|
||||
* please let us know!)
|
||||
* 2. You can use this software for whatever you want. You don't have to pay us.
|
||||
* 3. You may not pretend that you wrote this software. If you use it in a
|
||||
* program, you must acknowledge somewhere in your documentation that
|
||||
* you've used the IJG code.
|
||||
*
|
||||
* In legalese:
|
||||
*
|
||||
* The authors make NO WARRANTY or representation, either express or implied,
|
||||
* with respect to this software, its quality, accuracy, merchantability, or
|
||||
* fitness for a particular purpose. This software is provided "AS IS", and you,
|
||||
* its user, assume the entire risk as to its quality and accuracy.
|
||||
*
|
||||
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
|
||||
* All Rights Reserved except as specified below.
|
||||
*
|
||||
* Permission is hereby granted to use, copy, modify, and distribute this
|
||||
* software (or portions thereof) for any purpose, without fee, subject to these
|
||||
* conditions:
|
||||
* (1) If any part of the source code for this software is distributed, then this
|
||||
* README file must be included, with this copyright and no-warranty notice
|
||||
* unaltered; and any additions, deletions, or changes to the original files
|
||||
* must be clearly indicated in accompanying documentation.
|
||||
* (2) If only executable code is distributed, then the accompanying
|
||||
* documentation must state that "this software is based in part on the work of
|
||||
* the Independent JPEG Group".
|
||||
* (3) Permission for use of this software is granted only if the user accepts
|
||||
* full responsibility for any undesirable consequences; the authors accept
|
||||
* NO LIABILITY for damages of any kind.
|
||||
*
|
||||
* These conditions apply to any software derived from or based on the IJG code,
|
||||
* not just to the unmodified library. If you use our work, you ought to
|
||||
* acknowledge us.
|
||||
*
|
||||
* Permission is NOT granted for the use of any IJG author's name or company name
|
||||
* in advertising or publicity relating to this software or products derived from
|
||||
* it. This software may be referred to only as "the Independent JPEG Group's
|
||||
* software".
|
||||
*
|
||||
* We specifically permit and encourage the use of this software as the basis of
|
||||
* commercial products, provided that all warranty or liability claims are
|
||||
* assumed by the product vendor.
|
||||
*
|
||||
* This file contains a slower but more accurate integer implementation of the
|
||||
* forward DCT (Discrete Cosine Transform).
|
||||
*
|
||||
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
|
||||
* on each column. Direct algorithms are also available, but they are
|
||||
* much more complex and seem not to be any faster when reduced to code.
|
||||
*
|
||||
* This implementation is based on an algorithm described in
|
||||
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
|
||||
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
|
||||
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
|
||||
* The primary algorithm described there uses 11 multiplies and 29 adds.
|
||||
* We use their alternate method with 12 multiplies and 32 adds.
|
||||
* The advantage of this method is that no data path contains more than one
|
||||
* multiplication; this allows a very simple and accurate implementation in
|
||||
* scaled fixed-point arithmetic, with a minimal number of shifts.
|
||||
*/
|
||||
|
||||
Original src/avx2/fdct.rs opening notice
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg / jfdctint-avx2.asm to rust
|
||||
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
|
||||
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
|
||||
*
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
|
||||
@@ -118,3 +118,6 @@ sync_github_name = true
|
||||
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.V1dalTheAbidal]
|
||||
sync_github_name = true
|
||||
|
||||
+40
-24
@@ -1,5 +1,5 @@
|
||||
//! CAD colours: the 256-entry colour index (ACI), 24-bit true colour, and the logical
|
||||
//! ByLayer / ByBlock values. The index palette is generated from its well-known structure
|
||||
//! `ByLayer` / `ByBlock` values. The index palette is generated from its well-known structure
|
||||
//! (24 hues × 5 values × 2 saturations, plus primaries and greys), not copied from any file.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
@@ -11,12 +11,15 @@ use serde::{Deserialize, Serialize};
|
||||
pub struct Rgb(pub u8, pub u8, pub u8);
|
||||
|
||||
impl Rgb {
|
||||
#[must_use]
|
||||
pub fn to_u32(self) -> u32 {
|
||||
(u32::from(self.0) << 16) | (u32::from(self.1) << 8) | u32::from(self.2)
|
||||
}
|
||||
#[must_use]
|
||||
pub fn from_u32(v: u32) -> Rgb {
|
||||
Rgb(((v >> 16) & 0xff) as u8, ((v >> 8) & 0xff) as u8, (v & 0xff) as u8)
|
||||
}
|
||||
#[must_use]
|
||||
pub fn hex(self) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
|
||||
}
|
||||
@@ -29,6 +32,7 @@ impl Rgb {
|
||||
u32::from_str_radix(s, 16).ok().map(Rgb::from_u32)
|
||||
}
|
||||
/// Relative luminance (0..1) for contrast decisions.
|
||||
#[must_use]
|
||||
pub fn luma(self) -> f64 {
|
||||
(0.2126 * f64::from(self.0) + 0.7152 * f64::from(self.1) + 0.0722 * f64::from(self.2)) / 255.0
|
||||
}
|
||||
@@ -48,7 +52,8 @@ pub enum Color {
|
||||
|
||||
impl Color {
|
||||
pub const WHITE: Color = Color::Index(7);
|
||||
/// DXF group 62 value: 0 = ByBlock, 256 = ByLayer.
|
||||
/// DXF group 62 value: 0 = `ByBlock`, 256 = `ByLayer`.
|
||||
#[must_use]
|
||||
pub fn to_aci(self) -> i16 {
|
||||
match self {
|
||||
Color::ByLayer => 256,
|
||||
@@ -57,14 +62,16 @@ impl Color {
|
||||
Color::True(rgb) => i16::from(nearest_aci(rgb)),
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
pub fn from_aci(v: i16) -> Color {
|
||||
match v {
|
||||
0 => Color::ByBlock,
|
||||
1..=255 => Color::Index(v as u8),
|
||||
1..=255 => u8::try_from(v).map_or(Color::ByLayer, Color::Index),
|
||||
_ => Color::ByLayer,
|
||||
}
|
||||
}
|
||||
/// Resolve to RGB given the layer and block colours.
|
||||
#[must_use]
|
||||
pub fn resolve(self, layer: Color, block: Color) -> Rgb {
|
||||
match self {
|
||||
Color::ByLayer => match layer {
|
||||
@@ -79,7 +86,8 @@ impl Color {
|
||||
Color::True(c) => c,
|
||||
}
|
||||
}
|
||||
/// Short display name like AutoCAD's Properties palette ("ByLayer", "Red", "Color 34", "255,128,0").
|
||||
/// Short display name like `AutoCAD`'s Properties palette ("`ByLayer`", "Red", "Color 34", "255,128,0").
|
||||
#[must_use]
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
Color::ByLayer => "ByLayer".into(),
|
||||
@@ -102,7 +110,7 @@ impl Color {
|
||||
let t = s.trim().to_ascii_lowercase();
|
||||
let named = ["", "red", "yellow", "green", "cyan", "blue", "magenta", "white"];
|
||||
if let Some(i) = named.iter().position(|n| !n.is_empty() && *n == t) {
|
||||
return Some(Color::Index(i as u8));
|
||||
return u8::try_from(i).ok().map(Color::Index);
|
||||
}
|
||||
match t.as_str() {
|
||||
"bylayer" => return Some(Color::ByLayer),
|
||||
@@ -117,7 +125,7 @@ impl Color {
|
||||
return match i {
|
||||
0 => Some(Color::ByBlock),
|
||||
256 => Some(Color::ByLayer),
|
||||
1..=255 => Some(Color::Index(i as u8)),
|
||||
1..=255 => u8::try_from(i).ok().map(Color::Index),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
@@ -145,11 +153,16 @@ pub fn aci_rgb(i: u8) -> Rgb {
|
||||
PALETTE.get(usize::from(i)).copied().unwrap_or(Rgb(255, 255, 255))
|
||||
}
|
||||
|
||||
/// The palette as a 256-entry table (entry 0 = ByBlock placeholder = black).
|
||||
/// The palette as a 256-entry table (entry 0 = `ByBlock` placeholder = black).
|
||||
pub static PALETTE: std::sync::LazyLock<[Rgb; 256]> = std::sync::LazyLock::new(build_palette);
|
||||
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "Palette channels are finite and clamped to the u8 range before conversion."
|
||||
)]
|
||||
fn build_palette() -> [Rgb; 256] {
|
||||
let mut p = [Rgb(0, 0, 0); 256];
|
||||
let mut palette = [Rgb(0, 0, 0); 256];
|
||||
let base = [
|
||||
Rgb(0, 0, 0),
|
||||
Rgb(255, 0, 0),
|
||||
@@ -162,34 +175,35 @@ fn build_palette() -> [Rgb; 256] {
|
||||
Rgb(128, 128, 128),
|
||||
Rgb(192, 192, 192),
|
||||
];
|
||||
for (slot, c) in p.iter_mut().zip(base) {
|
||||
*slot = c;
|
||||
for (slot, colour) in palette.iter_mut().zip(base) {
|
||||
*slot = colour;
|
||||
}
|
||||
let values = [255.0, 204.0, 153.0, 127.0, 76.0];
|
||||
for i in 10..250usize {
|
||||
let hue = (i - 10) / 10; // 0..24, 15° each
|
||||
let sub = i % 10;
|
||||
let v: f64 = values.get(sub / 2).copied().unwrap_or(255.0);
|
||||
for index in 10..250usize {
|
||||
let hue = (index - 10) / 10; // 0..24, 15° each
|
||||
let sub = index % 10;
|
||||
let value: f64 = values.get(sub / 2).copied().unwrap_or(255.0);
|
||||
let half = sub % 2 == 1;
|
||||
let (r, g, b) = hue_fractions(hue);
|
||||
let ch = |f: f64| -> u8 {
|
||||
let f = if half { 0.5 + 0.5 * f } else { f };
|
||||
(v * f).floor().clamp(0.0, 255.0) as u8
|
||||
let (red, green, blue) = hue_fractions(hue);
|
||||
let channel = |fraction: f64| -> u8 {
|
||||
let fraction = if half { 0.5 + 0.5 * fraction } else { fraction };
|
||||
(value * fraction).floor().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
if let Some(slot) = p.get_mut(i) {
|
||||
*slot = Rgb(ch(r), ch(g), ch(b));
|
||||
if let Some(slot) = palette.get_mut(index) {
|
||||
*slot = Rgb(channel(red), channel(green), channel(blue));
|
||||
}
|
||||
}
|
||||
let greys = [51u8, 91, 132, 173, 214, 255];
|
||||
for (k, g) in greys.iter().enumerate() {
|
||||
if let Some(slot) = p.get_mut(250 + k) {
|
||||
*slot = Rgb(*g, *g, *g);
|
||||
for (offset, shade) in greys.iter().enumerate() {
|
||||
if let Some(slot) = palette.get_mut(250 + offset) {
|
||||
*slot = Rgb(*shade, *shade, *shade);
|
||||
}
|
||||
}
|
||||
p
|
||||
palette
|
||||
}
|
||||
|
||||
/// Channel fractions for hue step 0..24 (red → yellow → green → cyan → blue → magenta → red).
|
||||
#[expect(clippy::cast_precision_loss, reason = "Only the four hue offsets 0..=3 are converted; they are exact in f64.")]
|
||||
fn hue_fractions(h: usize) -> (f64, f64, f64) {
|
||||
let seg = h / 4;
|
||||
let t = (h % 4) as f64 / 4.0;
|
||||
@@ -204,6 +218,7 @@ fn hue_fractions(h: usize) -> (f64, f64, f64) {
|
||||
}
|
||||
|
||||
/// The closest index colour to an RGB value (1..=255).
|
||||
#[must_use]
|
||||
pub fn nearest_aci(c: Rgb) -> u8 {
|
||||
let mut best = (u32::MAX, 7u8);
|
||||
for i in 1..=255u8 {
|
||||
@@ -220,6 +235,7 @@ pub fn nearest_aci(c: Rgb) -> u8 {
|
||||
/// Display colour of `c` on `background`. Colour 7 (`aci7`) flips to contrast with the
|
||||
/// background, white on dark and black on light (paper), as CAD programs draw it; every other
|
||||
/// colour, including a true-colour or index white or black, keeps its RGB.
|
||||
#[must_use]
|
||||
pub fn display_rgb(c: Rgb, aci7: bool, background: Rgb) -> Rgb {
|
||||
if !aci7 {
|
||||
c
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
[package]
|
||||
name = "cadcraft-dwg"
|
||||
description = "CADCraft DWG bridge: converts DWG to and from DXF bytes using the acadrust crate (MPL-2.0, used unmodified)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
log = { workspace = true }
|
||||
|
||||
# The same targets as build.rs's `no_dwg_bridge` leave acadrust out: wasm32, and FreeBSD aarch64,
|
||||
# where acadrust 0.6.6 passes a `*const c_char` (u8 there) to its own `*const i8` sysctlbyname.
|
||||
# 0.6.7 and 0.6.8 fix that but read some damaged DWGs as empty with no note (tests.rs, #800).
|
||||
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dependencies]
|
||||
# MPL-2.0: used as an unmodified dependency only (see plan/adr/0001 and NOTICE).
|
||||
acadrust = "0.6.6"
|
||||
@@ -1,12 +0,0 @@
|
||||
//! Sets `no_dwg_bridge` on the targets built without acadrust (see Cargo.toml): the DWG functions
|
||||
//! there return an error that says to use DXF.
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo::rustc-check-cfg=cfg(no_dwg_bridge)");
|
||||
let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
|
||||
let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
|
||||
if arch == "wasm32" || (os == "freebsd" && arch == "aarch64") {
|
||||
println!("cargo::rustc-cfg=no_dwg_bridge");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,632 +0,0 @@
|
||||
//! Another application's entities and their classes through the DWG bridge: on reading a DWG,
|
||||
//! registered entities acadrust has no model for become proxy entities of their class; on writing
|
||||
//! one, the DWG gets the source DXF's classes in their places, so every proxy names its own class.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use acadrust::CadDocument;
|
||||
use acadrust::classes::{DxfClass, ProxyFlags};
|
||||
use acadrust::entities::{EntityType, ExtendedEntityData, ProxyEntityData};
|
||||
use acadrust::objects::{ObjectType, ProxyPayload};
|
||||
|
||||
fn class_number(index: usize) -> Result<i16, String> {
|
||||
index.checked_add(500).and_then(|n| i16::try_from(n).ok()).ok_or_else(|| "DXF: too many application classes".into())
|
||||
}
|
||||
|
||||
/// After a DWG read: each registered entity of another application's class that acadrust keeps
|
||||
/// only as its record and opaque data (no decoded properties) becomes a proxy entity of that class
|
||||
/// (DXF Reference, ACAD_PROXY_ENTITY), with its graphics, data bits, R2007+ strings and object
|
||||
/// references, so the DXF keeps it; and every proxy's class number becomes 500 plus its class's
|
||||
/// place in the classes, as a DXF numbers it. A record that can't be converted (its class is
|
||||
/// missing or not unique) is left out and named in the notes; one with decoded properties stays as
|
||||
/// read, also named, as its opaque data has no DXF form beside them.
|
||||
pub(super) fn prepare(doc: &mut CadDocument) -> Vec<String> {
|
||||
let classes: Vec<_> = doc.classes.iter().cloned().collect();
|
||||
let mut numbers = HashMap::new();
|
||||
let mut identities = HashMap::new();
|
||||
for (index, class) in classes.iter().enumerate() {
|
||||
let number = class_number(index).ok();
|
||||
numbers.entry(i32::from(class.class_number)).and_modify(|v| *v = None).or_insert(number.map(i32::from));
|
||||
let identity = (class.dxf_name.as_str(), class.cpp_class_name.as_str(), class.is_an_entity);
|
||||
identities.entry(identity).and_modify(|v| *v = None).or_insert(number);
|
||||
}
|
||||
let identity = |dxf: &str, cpp: &str, entity: bool| {
|
||||
identities
|
||||
.get(&(dxf, cpp, entity))
|
||||
.copied()
|
||||
.flatten()
|
||||
.map(i32::from)
|
||||
.ok_or_else(|| format!("missing or ambiguous application CLASS for {dxf:.80} ({cpp:.80})"))
|
||||
};
|
||||
let Some(dwg_version) = super::native::proxy_dwg_version(doc.dwg_source_version.unwrap_or(doc.version)) else { return Vec::new() };
|
||||
let maintenance = i32::from(doc.maintenance_version);
|
||||
let remap = |id: i32| numbers.get(&id).copied().flatten().ok_or_else(|| format!("proxy names missing or ambiguous application class {id}"));
|
||||
// Only mutate proxies: entities_mut invalidates the decoder's verbatim records for every entity.
|
||||
let handles: Vec<_> = doc
|
||||
.entities()
|
||||
.filter_map(|e| match e {
|
||||
EntityType::Extended(e) => match &e.data {
|
||||
ExtendedEntityData::Proxy(_) => Some(e.common.handle),
|
||||
ExtendedEntityData::RegisteredClass(data) if data.properties.is_empty() || data.payload.bit_count > 0 => Some(e.common.handle),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut notes = Vec::new();
|
||||
let mut entity_count = 0usize;
|
||||
let mut object_count = 0usize;
|
||||
let mut semantic = 0usize;
|
||||
for handle in handles {
|
||||
// Ok(None): not an application record; Ok(Some(None)): kept as read, with its properties.
|
||||
let converted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<Option<Option<ExtendedEntityData>>, String> {
|
||||
let Some(EntityType::Extended(entity)) = doc.get_entity(handle) else { return Ok(None) };
|
||||
let data = match &entity.data {
|
||||
ExtendedEntityData::Proxy(data) => {
|
||||
let mut proxy = data.clone();
|
||||
proxy.class_id = remap(proxy.class_id)?;
|
||||
ExtendedEntityData::Proxy(proxy)
|
||||
}
|
||||
ExtendedEntityData::RegisteredClass(data) => {
|
||||
if !data.properties.is_empty() {
|
||||
return Ok(Some(None));
|
||||
}
|
||||
let class_id = identity(&data.dxf_name, &data.cpp_class_name, true)?;
|
||||
let text_payload = entity.common.raw_record.as_deref().map(registered_text).transpose()?.unwrap_or_default();
|
||||
ExtendedEntityData::Proxy(ProxyEntityData {
|
||||
proxy_id: 498,
|
||||
class_id,
|
||||
dxf_subclass: String::new(),
|
||||
version: (maintenance << 16) | dwg_version,
|
||||
dwg_version,
|
||||
maintenance_version: maintenance,
|
||||
from_dxf: false,
|
||||
graphics: ProxyPayload::from_bytes(entity.common.graphic_data.as_deref().unwrap_or_default()),
|
||||
payload: data.payload.clone(),
|
||||
text_payload,
|
||||
object_ids: data.object_ids.clone(),
|
||||
})
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
Ok(Some(Some(data)))
|
||||
}))
|
||||
.unwrap_or_else(|_| Err("application record conversion failed".into()));
|
||||
match converted {
|
||||
Ok(Some(Some(data))) => {
|
||||
if let Some(EntityType::Extended(entity)) = doc.get_entity_mut(handle) {
|
||||
entity.data = data;
|
||||
}
|
||||
}
|
||||
Ok(Some(None)) => semantic = semantic.saturating_add(1),
|
||||
Ok(None) => {}
|
||||
Err(why) => {
|
||||
doc.remove_entity(handle);
|
||||
entity_count = entity_count.saturating_add(1);
|
||||
skipped_note(&mut notes, "entity", handle, &why);
|
||||
}
|
||||
}
|
||||
}
|
||||
doc.objects.retain(|handle, object| {
|
||||
if let ObjectType::ProxyObject(proxy) = object {
|
||||
match remap(proxy.class_id) {
|
||||
Ok(id) => proxy.class_id = id,
|
||||
Err(why) => {
|
||||
object_count = object_count.saturating_add(1);
|
||||
skipped_note(&mut notes, "object", *handle, &why);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
if entity_count > 0 || object_count > 0 {
|
||||
notes.insert(0, format!("DWG: partial read; application proxy records left out (entities: {entity_count}, objects: {object_count})"));
|
||||
}
|
||||
if semantic > 0 {
|
||||
notes.push(format!(
|
||||
"DWG: {semantic} registered entities with decoded properties keep them, without their other data; saving over the original file would lose it"
|
||||
));
|
||||
}
|
||||
notes
|
||||
}
|
||||
|
||||
fn skipped_note(notes: &mut Vec<String>, kind: &str, handle: acadrust::types::Handle, why: &str) {
|
||||
if notes.len() < 6 {
|
||||
let why: String = why.chars().take(256).collect();
|
||||
notes.push(format!("DWG: proxy {kind} {handle} left out: {why}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoder's registered-class representation omits the separate R2007+ string stream.
|
||||
fn registered_text(raw: &acadrust::entities::RawRecord) -> Result<ProxyPayload, String> {
|
||||
use acadrust::io::dwg::DwgVersion;
|
||||
use acadrust::io::dwg::dwg_stream_readers::object_reader::DwgObjectReader;
|
||||
use acadrust::io::dwg::dwg_stream_writers::bit_writer::DwgBitWriter;
|
||||
use acadrust::types::DxfVersion;
|
||||
|
||||
if raw.version < DxfVersion::AC1021 {
|
||||
return Ok(ProxyPayload::default());
|
||||
}
|
||||
let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| format!("DWG proxy text: {e}"))?;
|
||||
let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "DWG proxy text: negative handle stream size")?;
|
||||
let total_bits = raw.data.len().checked_mul(8).ok_or("DWG proxy text: record too large")?;
|
||||
if handle_bits > total_bits {
|
||||
return Err("DWG proxy text: handle stream exceeds record".into());
|
||||
}
|
||||
// Frame the verbatim record for the dependency's checked object reader.
|
||||
let mut frame = DwgBitWriter::new(version, raw.version);
|
||||
frame.write_modular_short(raw.data.len());
|
||||
if raw.version >= DxfVersion::AC1024 {
|
||||
frame.write_modular_char(handle_bits);
|
||||
}
|
||||
frame.write_bytes(&raw.data);
|
||||
let reader = DwgObjectReader::new(frame.into_bytes(), raw.version, HashMap::new()).map_err(|e| format!("DWG proxy text: {e}"))?;
|
||||
let (kind, mut streams) = reader.read_record_at(0).map_err(|e| format!("DWG proxy text: {e}"))?;
|
||||
reader.read_common_entity_data(&mut streams, kind);
|
||||
if kind == 498 {
|
||||
// An existing registered-class envelope is a proxy and carries its class name first.
|
||||
streams.read_variable_text();
|
||||
} else if kind < 500 {
|
||||
return Err("DWG proxy text: registered entity has no application class".into());
|
||||
}
|
||||
streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?;
|
||||
let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "DWG proxy text: negative string stream size")?;
|
||||
if bits > total_bits {
|
||||
return Err("DWG proxy text: string stream exceeds record".into());
|
||||
}
|
||||
let count = u32::try_from(bits).map_err(|_| "DWG proxy text: string stream too large")?;
|
||||
let mut bytes = vec![0; bits.div_ceil(8)];
|
||||
for (index, byte) in bytes.iter_mut().enumerate() {
|
||||
for bit in 0..8.min(bits.saturating_sub(index * 8)) {
|
||||
if streams.read_text_bit() {
|
||||
*byte |= 0x80 >> bit;
|
||||
}
|
||||
}
|
||||
}
|
||||
streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?;
|
||||
Ok(ProxyPayload::from_bits(&bytes, count))
|
||||
}
|
||||
|
||||
/// ASCII DXF pairs decoded with the bridge's public code-page and escape codecs. A malformed
|
||||
/// pair yields `None`, so both class scans fall back rather than guessing its identity.
|
||||
pub(super) fn text_pairs(dxf: &[u8]) -> Option<impl Iterator<Item = Option<(i32, String)>> + '_> {
|
||||
use acadrust::io::dxf::code_page::{decode_legacy_escapes, encoding_from_code_page};
|
||||
|
||||
if dxf.starts_with(b"AutoCAD Binary DXF") {
|
||||
return None;
|
||||
}
|
||||
let version =
|
||||
super::native::header_value(dxf, b"$ACADVER").and_then(|(_, v)| std::str::from_utf8(v).ok()).map(acadrust::DxfVersion::from_version_string);
|
||||
let unicode = version.is_some_and(|v| v >= acadrust::DxfVersion::AC1021);
|
||||
let encoding = if version.is_some_and(|v| v < acadrust::DxfVersion::AC1021) {
|
||||
super::native::header_value(dxf, b"$DWGCODEPAGE").and_then(|(_, page)| std::str::from_utf8(page).ok()).and_then(encoding_from_code_page)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut lines = dxf.split(|b| *b == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line));
|
||||
Some(std::iter::from_fn(move || {
|
||||
let code = lines.next()?;
|
||||
let Some(value) = lines.next() else { return (!code.trim_ascii().is_empty()).then_some(None) };
|
||||
let pair = || {
|
||||
let code = std::str::from_utf8(code).ok()?.trim().parse().ok()?;
|
||||
let text = if let Some(encoding) = encoding {
|
||||
encoding.decode(value).0.into_owned()
|
||||
} else if unicode {
|
||||
String::from_utf8_lossy(value).into_owned()
|
||||
} else {
|
||||
// The decoder uses UTF-8 with Latin-1 fallback when no encoding was declared.
|
||||
std::str::from_utf8(value).map_or_else(|_| value.iter().map(|&b| char::from(b)).collect(), str::to_string)
|
||||
};
|
||||
let text = decode_legacy_escapes(&text);
|
||||
// DXF's escaped control characters are decoded after CIF/MIF, as in the bridge.
|
||||
let text = text.replace("^J", "\n").replace("^M", "\r").replace("^I", "\t").replace("^ ", "^");
|
||||
Some((code, text))
|
||||
};
|
||||
Some(pair())
|
||||
}))
|
||||
}
|
||||
|
||||
/// The CLASS records of an ASCII DXF, in CLASSES order and numbered by place from 500 (DXF
|
||||
/// Reference, CLASSES; a proxy's group 91 is that number). `None` for a binary DXF (CADCraft's own
|
||||
/// bridge DXF is ASCII), and for one with a record that can't be written back as it is: no names,
|
||||
/// flags or instance count out of range, more classes than the numbers allow. Then
|
||||
/// `proxy_classes` matches the classes by name instead.
|
||||
pub(super) fn source_classes(dxf: &[u8]) -> Option<Vec<DxfClass>> {
|
||||
let pairs = text_pairs(dxf)?;
|
||||
let mut records: Vec<Vec<(i32, String)>> = Vec::new();
|
||||
let (mut section, mut in_classes) = (false, false);
|
||||
for pair in pairs {
|
||||
let (code, value) = pair?;
|
||||
match (code, value.as_str()) {
|
||||
(0, "ENDSEC") if in_classes => break,
|
||||
(0, "SECTION") => section = true,
|
||||
(2, name) if section => {
|
||||
in_classes = name == "CLASSES";
|
||||
section = false;
|
||||
}
|
||||
(0, kind) if in_classes => {
|
||||
if kind != "CLASS" {
|
||||
return None;
|
||||
}
|
||||
records.push(Vec::new());
|
||||
}
|
||||
(code, value) if in_classes => records.last_mut()?.push((code, value.to_string())),
|
||||
_ => section = false,
|
||||
}
|
||||
}
|
||||
records.iter().enumerate().map(|(index, groups)| source_class(groups, class_number(index).ok()?)).collect()
|
||||
}
|
||||
|
||||
/// One CLASS record's groups as the class `number`, or `None` when it can't be written back.
|
||||
fn source_class(groups: &[(i32, String)], number: i16) -> Option<DxfClass> {
|
||||
let text = |code| groups.iter().find(|(c, _)| *c == code).map(|(_, v)| v.clone()).unwrap_or_default();
|
||||
let integer = |code| groups.iter().find(|(c, _)| *c == code).map_or(Some(0), |(_, v)| v.trim().parse::<i64>().ok());
|
||||
let mut class = DxfClass::new(text(1), text(2));
|
||||
if class.dxf_name.is_empty() || class.cpp_class_name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
class.application_name = text(3);
|
||||
class.proxy_flags = ProxyFlags(u16::try_from(integer(90)?).ok()?);
|
||||
class.instance_count = i32::try_from(integer(91)?).ok()?;
|
||||
class.was_zombie = integer(280)? != 0;
|
||||
class.is_an_entity = integer(281)? != 0;
|
||||
class.item_class_id = if class.is_an_entity { 498 } else { 499 };
|
||||
class.class_number = number;
|
||||
Some(class)
|
||||
}
|
||||
|
||||
/// Give a DWG of 2013 or later the source DXF's classes (`classes`, from [`source_classes`]) in
|
||||
/// their places, with their metadata and duplicate names, so each proxy's DXF class number names
|
||||
/// its own class; the decoder's default classes the source lacks follow them. A proxy whose number
|
||||
/// names no source class is left out, as `proxy_classes` leaves it out. Returns how many proxy objects and
|
||||
/// entities were left out; nothing changes when the drawing has no proxies. `None`, with nothing
|
||||
/// changed, when the classes would be more than the class numbers allow.
|
||||
pub(super) fn restore_classes(doc: &mut CadDocument, classes: Vec<DxfClass>) -> Option<(usize, usize)> {
|
||||
let fits = |number: i32| number.checked_sub(500).and_then(|n| usize::try_from(n).ok()).is_some_and(|i| i < classes.len());
|
||||
let mut any = false;
|
||||
let mut entities = Vec::new();
|
||||
for entity in doc.entities() {
|
||||
if let EntityType::Extended(e) = entity
|
||||
&& let ExtendedEntityData::Proxy(p) = &e.data
|
||||
{
|
||||
any = true;
|
||||
if !fits(p.class_id) {
|
||||
entities.push(e.common.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut objects = Vec::new();
|
||||
for (handle, object) in &doc.objects {
|
||||
if let ObjectType::ProxyObject(p) = object {
|
||||
any = true;
|
||||
if !fits(p.class_id) {
|
||||
objects.push(*handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return Some((0, 0));
|
||||
}
|
||||
let mut names: HashSet<_> = classes.iter().map(|c| c.dxf_name.to_uppercase()).collect();
|
||||
let defaults: Vec<_> = doc.classes.iter().filter(|c| names.insert(c.dxf_name.to_uppercase())).cloned().collect();
|
||||
if let Some(last) = classes.len().checked_add(defaults.len())?.checked_sub(1) {
|
||||
class_number(last).ok()?;
|
||||
}
|
||||
for handle in &entities {
|
||||
doc.remove_entity(*handle);
|
||||
}
|
||||
for handle in &objects {
|
||||
doc.objects.remove(handle);
|
||||
}
|
||||
doc.classes.clear();
|
||||
for (index, mut class) in classes.into_iter().chain(defaults).enumerate() {
|
||||
class.class_number = class_number(index).ok()?;
|
||||
doc.classes.push_preserving(class);
|
||||
}
|
||||
Some((objects.len(), entities.len()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use acadrust::entities::{EntityCommon, ExtendedEntity, RegisteredClassEntityData};
|
||||
use acadrust::types::DxfVersion;
|
||||
|
||||
fn proxy_doc() -> CadDocument {
|
||||
let mut doc = CadDocument::new();
|
||||
doc.version = DxfVersion::AC1032;
|
||||
doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity {
|
||||
common: EntityCommon::default(),
|
||||
data: ExtendedEntityData::Proxy(ProxyEntityData {
|
||||
proxy_id: 498,
|
||||
class_id: 501,
|
||||
dxf_subclass: String::new(),
|
||||
version: 33,
|
||||
dwg_version: 33,
|
||||
maintenance_version: 0,
|
||||
from_dxf: false,
|
||||
graphics: ProxyPayload::default(),
|
||||
payload: ProxyPayload::from_bits(&[0x80], 1),
|
||||
text_payload: ProxyPayload::default(),
|
||||
object_ids: vec![],
|
||||
}),
|
||||
})))
|
||||
.unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
/// An ASCII DXF of `groups`, `(code, value)` per pair of lines.
|
||||
fn dxf(groups: &[(i32, &str)]) -> Vec<u8> {
|
||||
groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_classes_keep_duplicates_and_metadata_before_defaults() {
|
||||
let bytes = dxf(&[
|
||||
(0, "SECTION"),
|
||||
(2, "HEADER"),
|
||||
(9, "$DIMSTYLE"),
|
||||
(2, "CLASSES"),
|
||||
(0, "ENDSEC"),
|
||||
(0, "SECTION"),
|
||||
(2, "CLASSES"),
|
||||
(0, "CLASS"),
|
||||
(1, "Объект"),
|
||||
(2, "First"),
|
||||
(3, "Первый"),
|
||||
(90, "1025"),
|
||||
(91, "7"),
|
||||
(280, "1"),
|
||||
(281, "1"),
|
||||
(0, "CLASS"),
|
||||
(1, "Объект"),
|
||||
(2, "Second"),
|
||||
(3, "Второй"),
|
||||
(90, "128"),
|
||||
(281, "1"),
|
||||
(0, "ENDSEC"),
|
||||
(0, "EOF"),
|
||||
]);
|
||||
let classes = source_classes(&bytes).unwrap();
|
||||
assert_eq!(classes.len(), 2);
|
||||
assert_eq!(classes[0].application_name, "Первый");
|
||||
assert_eq!(classes[0].proxy_flags.0, 1025);
|
||||
assert_eq!(classes[0].instance_count, 7);
|
||||
assert!(classes[0].was_zombie);
|
||||
assert_eq!((classes[0].class_number, classes[1].class_number), (500, 501));
|
||||
assert_eq!(classes[1].cpp_class_name, "Second");
|
||||
let mut doc = proxy_doc();
|
||||
assert_eq!(restore_classes(&mut doc, classes.clone()), Some((0, 0)));
|
||||
assert_eq!(doc.classes.iter().take(2).cloned().collect::<Vec<_>>(), classes);
|
||||
// A binary DXF, and a CLASS record that can't be written back as it is, give no classes.
|
||||
assert!(source_classes(b"AutoCAD Binary DXF\r\n\x1a\0").is_none());
|
||||
for (code, value) in [(1, ""), (2, ""), (90, "65536"), (91, "9223372036854775807"), (281, "x")] {
|
||||
let mut class = vec![(1, "A"), (2, "A")];
|
||||
class.retain(|(c, _)| *c != code);
|
||||
class.push((code, value));
|
||||
let mut groups = vec![(0, "SECTION"), (2, "CLASSES"), (0, "CLASS")];
|
||||
groups.extend(class);
|
||||
groups.extend([(0, "ENDSEC"), (0, "EOF")]);
|
||||
assert!(source_classes(&dxf(&groups)).is_none(), "{code} {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_classes_decode_escapes_once_and_respect_legacy_code_pages() {
|
||||
let body = "0\nCLASS\n1\n\\U+041E\\U+0431\\U+044A\\U+0435\\U+043A\\U+0442\n2\nClass\n3\nCaf\\U+00E9\\U+D83D\\U+DE42\\U+005CU+0041\n281\n1\n0\nENDSEC\n0\nEOF\n";
|
||||
let text = format!("0\nSECTION\n2\nCLASSES\n{body}");
|
||||
let classes = source_classes(text.as_bytes()).unwrap();
|
||||
assert_eq!(classes[0].dxf_name, "Объект");
|
||||
assert_eq!(classes[0].application_name, "Café🙂\\U+0041");
|
||||
|
||||
let prefix =
|
||||
b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DWGCODEPAGE\n3\nANSI_1251\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n";
|
||||
let encoded = [prefix.as_slice(), b"\xCF\xF0\xE8\xEC\xE5\xF0", b"\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n"].concat();
|
||||
assert_eq!(source_classes(&encoded).unwrap()[0].dxf_name, "Пример");
|
||||
// R2007+ text is UTF-8 even with a legacy code-page declaration.
|
||||
let modern = String::from_utf8_lossy(prefix).replace("AC1015", "AC1032") + "Пример\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n";
|
||||
assert_eq!(source_classes(modern.as_bytes()).unwrap()[0].dxf_name, "Пример");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxies_of_missing_classes_are_left_out() {
|
||||
for id in [-1, 499, 501, i32::MAX] {
|
||||
let mut doc = proxy_doc();
|
||||
if let Some(EntityType::Extended(e)) = doc.entities_mut().next()
|
||||
&& let ExtendedEntityData::Proxy(p) = &mut e.data
|
||||
{
|
||||
p.class_id = id;
|
||||
}
|
||||
let mut class = DxfClass::new_entity("ENTITY", "Entity");
|
||||
class.class_number = 500;
|
||||
assert_eq!(restore_classes(&mut doc, vec![class]), Some((0, 1)), "{id}");
|
||||
assert_eq!(doc.entities().count(), 0);
|
||||
}
|
||||
// Class 501 is there: the proxy keeps it, in its place.
|
||||
let mut doc = proxy_doc();
|
||||
assert_eq!(restore_classes(&mut doc, vec![DxfClass::new("A", "A"), DxfClass::new_entity("B", "B")]), Some((0, 0)));
|
||||
assert_eq!(doc.entities().count(), 1);
|
||||
assert_eq!(doc.classes.iter().nth(1).map(|c| (c.dxf_name.clone(), c.class_number)), Some(("B".to_string(), 501)));
|
||||
// Without proxies the classes stay the decoder's.
|
||||
let mut doc = CadDocument::new();
|
||||
let before: Vec<_> = doc.classes.iter().cloned().collect();
|
||||
assert_eq!(restore_classes(&mut doc, vec![DxfClass::new("A", "A")]), Some((0, 0)));
|
||||
assert_eq!(doc.classes.iter().cloned().collect::<Vec<_>>(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrepresentable_proxies_keep_other_geometry_and_bounded_diagnostics() {
|
||||
use acadrust::entities::{Line, RawRecord};
|
||||
use acadrust::objects::ProxyObject;
|
||||
use acadrust::types::{Handle, Vector3};
|
||||
for count in [1, 10] {
|
||||
let mut doc = proxy_doc();
|
||||
if let Some(EntityType::Extended(e)) = doc.entities_mut().next()
|
||||
&& let ExtendedEntityData::Proxy(p) = &mut e.data
|
||||
{
|
||||
p.class_id = i32::MAX;
|
||||
}
|
||||
let template = doc.entities().next().unwrap().clone();
|
||||
for _ in 1..count {
|
||||
let mut entity = template.clone();
|
||||
entity.common_mut().handle = Handle::NULL;
|
||||
doc.add_entity(entity).unwrap();
|
||||
}
|
||||
let object = Handle::new(u64::MAX - 1);
|
||||
assert!(!doc.objects.contains_key(&object));
|
||||
doc.objects.insert(object, ObjectType::ProxyObject(ProxyObject { handle: object, class_id: i32::MAX, ..Default::default() }));
|
||||
let line = doc.add_entity(EntityType::Line(Line::from_points(Vector3::new(2.0, 3.0, 0.0), Vector3::new(12.0, 13.0, 0.0)))).unwrap();
|
||||
let raw = RawRecord { data: vec![0xAA, 0x55], handle_bits: 0, version: DxfVersion::AC1032 };
|
||||
doc.get_entity_mut(line).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone()));
|
||||
let notes = prepare(&mut doc);
|
||||
assert_eq!(notes.len(), (count + 1).min(6) + 1);
|
||||
assert!(notes.iter().all(|n| n.starts_with("DWG:")));
|
||||
assert!(notes[0].contains(&format!("entities: {count}, objects: 1")));
|
||||
assert_eq!(doc.entities().count(), 1);
|
||||
assert!(!doc.objects.contains_key(&object));
|
||||
let Some(EntityType::Line(actual)) = doc.get_entity(line) else { panic!("readable line") };
|
||||
assert_eq!(actual.start, Vector3::new(2.0, 3.0, 0.0));
|
||||
assert_eq!(actual.end, Vector3::new(12.0, 13.0, 0.0));
|
||||
assert_eq!(doc.get_entity(line).unwrap().common().raw_record.as_deref(), Some(&raw));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn opaque_registered_class_ambiguity_is_not_guessed() {
|
||||
let mut doc = CadDocument::new();
|
||||
doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom"));
|
||||
doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom"));
|
||||
doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity {
|
||||
common: EntityCommon::default(),
|
||||
data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData {
|
||||
dxf_name: "CUSTOM".into(),
|
||||
cpp_class_name: "Custom".into(),
|
||||
properties: vec![],
|
||||
payload: ProxyPayload::from_bits(&[0x80], 1),
|
||||
object_ids: vec![],
|
||||
}),
|
||||
})))
|
||||
.unwrap();
|
||||
assert!(prepare(&mut doc).iter().any(|n| n.contains("ambiguous")));
|
||||
assert_eq!(doc.entities().count(), 0);
|
||||
assert!(class_number(usize::MAX).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn semantic_records_keep_verbatim_data_and_mixed_payloads_are_reported() {
|
||||
use acadrust::entities::RawRecord;
|
||||
use acadrust::objects::{SemanticProperty, SemanticPropertyValue};
|
||||
for payload in [ProxyPayload::default(), ProxyPayload::from_bits(&[0x80], 1)] {
|
||||
let mut doc = CadDocument::new();
|
||||
let raw = RawRecord { data: vec![0xAA], handle_bits: 0, version: DxfVersion::AC1032 };
|
||||
let handle = doc
|
||||
.add_entity(EntityType::Extended(Box::new(ExtendedEntity {
|
||||
common: EntityCommon::default(),
|
||||
data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData {
|
||||
dxf_name: "SEMANTIC".into(),
|
||||
cpp_class_name: "Semantic".into(),
|
||||
properties: vec![SemanticProperty {
|
||||
subclass: "Semantic".into(),
|
||||
code: 1,
|
||||
value: SemanticPropertyValue::Text("value".into()),
|
||||
}],
|
||||
payload: payload.clone(),
|
||||
object_ids: vec![],
|
||||
}),
|
||||
})))
|
||||
.unwrap();
|
||||
doc.get_entity_mut(handle).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone()));
|
||||
assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw));
|
||||
if payload.bit_count == 0 {
|
||||
assert!(prepare(&mut doc).is_empty());
|
||||
assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw));
|
||||
} else {
|
||||
// Kept as read, and named: its opaque data has no DXF form beside the properties.
|
||||
assert!(prepare(&mut doc).iter().any(|n| n.contains("decoded properties")));
|
||||
assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod string_stream_tests {
|
||||
use super::*;
|
||||
use acadrust::entities::{EntityCommon, ExtendedEntity, RawRecord, RegisteredClassEntityData};
|
||||
use acadrust::types::DxfVersion;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[test]
|
||||
fn registered_transport_recovers_separate_non_byte_aligned_strings() {
|
||||
for version in [DxfVersion::AC1027, DxfVersion::AC1032] {
|
||||
let mut source = CadDocument::new();
|
||||
source.version = version;
|
||||
source.classes.add_or_update(DxfClass::new_entity("CUSTOM_TEXT", "CustomText"));
|
||||
let class_id = i32::from(source.classes.get_by_name("CUSTOM_TEXT").unwrap().class_number);
|
||||
let text = ProxyPayload::from_bits(&[0xA5, 0xC7, 0xE0], 19);
|
||||
let payload = ProxyPayload::from_bits(&[0x80], 1);
|
||||
source
|
||||
.add_entity(EntityType::Extended(Box::new(ExtendedEntity {
|
||||
common: EntityCommon::default(),
|
||||
data: ExtendedEntityData::Proxy(ProxyEntityData {
|
||||
proxy_id: 498,
|
||||
class_id,
|
||||
dxf_subclass: "CustomText".into(),
|
||||
version: 33,
|
||||
dwg_version: 33,
|
||||
maintenance_version: 0,
|
||||
from_dxf: false,
|
||||
graphics: ProxyPayload::default(),
|
||||
payload: payload.clone(),
|
||||
text_payload: text.clone(),
|
||||
object_ids: vec![],
|
||||
}),
|
||||
})))
|
||||
.unwrap();
|
||||
let bytes = acadrust::DwgWriter::write_to_vec(&source).unwrap();
|
||||
let mut decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap();
|
||||
let entity = decoded.entities().next().unwrap();
|
||||
let handle = entity.common().handle;
|
||||
let raw = entity.common().raw_record.clone().unwrap();
|
||||
assert_eq!(registered_text(&raw).unwrap().data(), text.data());
|
||||
assert_eq!(registered_text(&raw).unwrap().bit_count, 19);
|
||||
let EntityType::Extended(entity) = decoded.get_entity_mut(handle).unwrap() else { panic!() };
|
||||
entity.data = ExtendedEntityData::RegisteredClass(RegisteredClassEntityData {
|
||||
dxf_name: "CUSTOM_TEXT".into(),
|
||||
cpp_class_name: "CustomText".into(),
|
||||
properties: vec![],
|
||||
payload: payload.clone(),
|
||||
object_ids: vec![],
|
||||
});
|
||||
entity.common.raw_record = Some(raw);
|
||||
assert!(prepare(&mut decoded).is_empty());
|
||||
for _ in 0..2 {
|
||||
let mut dxf = Vec::new();
|
||||
acadrust::DxfWriter::new(&decoded).write_to_writer(&mut dxf).unwrap();
|
||||
let bytes = crate::dxf_to_dwg_as(&dxf, "AC1032").unwrap();
|
||||
decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap();
|
||||
let p = decoded
|
||||
.entities()
|
||||
.find_map(|e| match e {
|
||||
EntityType::Extended(e) => match &e.data {
|
||||
ExtendedEntityData::Proxy(p) => Some(p),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(p.payload.bit_count, 1);
|
||||
assert_eq!(p.payload.data(), payload.data());
|
||||
assert_eq!(p.text_payload.bit_count, 19);
|
||||
assert_eq!(p.text_payload.data(), text.data());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_string_stream_boundaries_return_errors() {
|
||||
for handle_bits in [-1, 1000] {
|
||||
let raw = RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 };
|
||||
assert!(registered_text(&raw).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
//! The DWG reader and writer in a child process.
|
||||
//!
|
||||
//! An allocation failure or stack overflow in the third-party code ends the process it runs in, and
|
||||
//! `catch_unwind` can't stop that. So the app runs them in a copy of itself: [`use_own_worker`] says
|
||||
//! how to start one, and [`serve_if_asked`], first thing in `main`, turns the copy into a worker
|
||||
//! that reads one request from standard input and writes one reply to standard output. A file that
|
||||
//! kills the worker then costs that one open or save, and every other open drawing stays safe.
|
||||
//!
|
||||
//! Without a worker (libraries, tests, a build that can't start one) [`decode`] and [`encode_as`]
|
||||
//! run in the calling process, as they always did. There's no memory limit on the worker yet: that
|
||||
//! takes per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate.
|
||||
//!
|
||||
//! A reply comes from a process that just handled a possibly hostile file, so it is parsed as
|
||||
//! untrusted input.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc::{RecvTimeoutError, channel};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::Limits;
|
||||
|
||||
/// The argument that makes the app a worker.
|
||||
pub const WORKER_ARG: &str = "--dwg-worker";
|
||||
/// Bumped when the messages change: an app updated while running may start a newer copy.
|
||||
const PROTOCOL: u8 = 2;
|
||||
const DECODE: u8 = 1;
|
||||
const ENCODE: u8 = 2;
|
||||
const CRASH: u8 = 0xff;
|
||||
/// How long one file may take before the worker is stopped. It can't be interrupted otherwise.
|
||||
const TIMEOUT: Duration = Duration::from_secs(30 * 60);
|
||||
/// Most bytes accepted for what a reply carries besides the drawing.
|
||||
const MAX_NOTES_BYTES: u64 = 64 << 20;
|
||||
/// Most bytes accepted as a written DWG.
|
||||
const MAX_DWG_REPLY: u64 = 2 << 30;
|
||||
/// Most bytes one request holds: the largest input, whichever the direction, and its header.
|
||||
const MAX_REQUEST: u64 = (2 << 30) + 256;
|
||||
|
||||
struct Worker {
|
||||
program: PathBuf,
|
||||
args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static WORKER: Mutex<Option<Worker>> = Mutex::new(None);
|
||||
|
||||
/// Start `program args` as the worker from now on. `program` must call [`serve_if_asked`].
|
||||
pub fn use_worker(program: PathBuf, args: Vec<OsString>) {
|
||||
if let Ok(mut w) = WORKER.lock() {
|
||||
*w = Some(Worker { program, args });
|
||||
}
|
||||
}
|
||||
|
||||
/// Use a copy of this program as the worker, started with [`WORKER_ARG`]. If its path can't be
|
||||
/// found, the reader and writer stay in this process.
|
||||
pub fn use_own_worker() {
|
||||
match std::env::current_exe() {
|
||||
Ok(program) => use_worker(program, vec![WORKER_ARG.into()]),
|
||||
Err(e) => log::warn!("DWG worker: can't find this program: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one request and return the exit code if this process was started as a worker.
|
||||
pub fn serve_if_asked() -> Option<i32> {
|
||||
(std::env::args_os().nth(1)? == WORKER_ARG).then(|| serve(std::io::stdin().lock(), std::io::stdout().lock()))
|
||||
}
|
||||
|
||||
/// [`super::dwg_to_dxf_noted`] in the worker, when there is one.
|
||||
pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec<u8>, Vec<String>), String> {
|
||||
// Before starting a process, and so the same limit holds with or without one.
|
||||
if bytes.len() > limits.max_dwg_bytes {
|
||||
return super::dwg_to_dxf_noted(bytes, limits);
|
||||
}
|
||||
let reply_limit = (limits.max_dxf_bytes as u64).saturating_add(MAX_NOTES_BYTES);
|
||||
match call(&request(DECODE, limits, ""), bytes, reply_limit, "reading this file") {
|
||||
Some(reply) => reply?,
|
||||
None => super::dwg_to_dxf_noted(bytes, limits),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`super::dxf_to_dwg_as`] in the worker, when there is one.
|
||||
pub fn encode_as(dxf: &[u8], version: &str) -> Result<Vec<u8>, String> {
|
||||
encode_noted(dxf, version).map(|(dwg, _)| dwg)
|
||||
}
|
||||
|
||||
/// [`super::dxf_to_dwg_noted`] in the worker, when there is one. What the writer left out comes
|
||||
/// back as notes of `TYPE<tab>count`.
|
||||
pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec<u8>, super::Unwritten), String> {
|
||||
encode_kept_noted(dxf, version, None)
|
||||
}
|
||||
|
||||
/// [`encode_noted`] for a DXF whose carried-over groups were read from a file of version `kept`
|
||||
/// ([`super::dxf_to_dwg_kept_noted`]); `None` is [`encode_noted`].
|
||||
pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec<u8>, super::Unwritten), String> {
|
||||
if u8::try_from(version.len()).is_err() {
|
||||
return Err(super::unsupported(version));
|
||||
}
|
||||
// A kept version too long to send is no version CADCraft knows: it changes nothing.
|
||||
let kept = kept.filter(|k| u8::try_from(k.len()).is_ok());
|
||||
let mut header = request(ENCODE, Limits::DEFAULT, version);
|
||||
push_str(&mut header, kept.unwrap_or(""));
|
||||
match call(&header, dxf, MAX_DWG_REPLY, "writing this file") {
|
||||
Some(reply) => reply?.map(|(dwg, notes)| (dwg, unwritten_from(¬es))),
|
||||
None => encode_here(dxf, version, kept),
|
||||
}
|
||||
}
|
||||
|
||||
/// The conversion in this process.
|
||||
fn encode_here(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec<u8>, super::Unwritten), String> {
|
||||
match kept {
|
||||
Some(kept) => super::dxf_to_dwg_kept_noted(dxf, version, kept),
|
||||
None => super::dxf_to_dwg_noted(dxf, version),
|
||||
}
|
||||
}
|
||||
|
||||
fn unwritten_from(notes: &[String]) -> super::Unwritten {
|
||||
notes.iter().filter_map(|n| n.split_once('\t')).filter_map(|(kind, n)| Some((kind.to_string(), n.parse::<usize>().ok()?))).fold(
|
||||
super::Unwritten::new(),
|
||||
|mut m, (kind, n)| {
|
||||
*m.entry(kind).or_insert(0) = n;
|
||||
m
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Make the worker abort, as the third-party code can: what the tests prove isolation with.
|
||||
#[doc(hidden)]
|
||||
pub fn crash_worker_for_test() -> Result<(), String> {
|
||||
call(&request(CRASH, Limits::DEFAULT, ""), &[], 1024, "testing").ok_or("no worker")??.map(|_| ())
|
||||
}
|
||||
|
||||
fn request(op: u8, limits: Limits, version: &str) -> Vec<u8> {
|
||||
let mut r = vec![PROTOCOL, op];
|
||||
r.extend((limits.max_dwg_bytes as u64).to_le_bytes());
|
||||
r.extend((limits.max_dxf_bytes as u64).to_le_bytes());
|
||||
push_str(&mut r, version);
|
||||
r
|
||||
}
|
||||
|
||||
/// `text` with a one-byte length before it; callers keep it under 256 bytes.
|
||||
fn push_str(r: &mut Vec<u8>, text: &str) {
|
||||
r.push(u8::try_from(text.len()).unwrap_or(0));
|
||||
r.extend(text.as_bytes());
|
||||
}
|
||||
|
||||
type Reply = Result<(Vec<u8>, Vec<String>), String>;
|
||||
|
||||
/// Run one request in a worker. `None`: none could be started, so the caller does the work.
|
||||
/// `Err`: the worker went wrong, and `doing` says at what, for the user.
|
||||
fn call(header: &[u8], payload: &[u8], reply_limit: u64, doing: &str) -> Option<Result<Reply, String>> {
|
||||
let mut command = {
|
||||
let worker = WORKER.lock().ok()?;
|
||||
let worker = worker.as_ref()?;
|
||||
let mut c = Command::new(&worker.program);
|
||||
c.args(&worker.args);
|
||||
c
|
||||
};
|
||||
command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
let mut child = match command.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!("DWG worker: can't start it: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let (Some(mut to_child), Some(from_child)) = (child.stdin.take(), child.stdout.take()) else {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
};
|
||||
let received = std::thread::scope(|scope| {
|
||||
// Written beside the read: a worker that replies before it has read everything, or dies,
|
||||
// must block neither side. A failed write shows up as the reply going wrong.
|
||||
scope.spawn(move || {
|
||||
let _ = to_child.write_all(header).and_then(|()| to_child.write_all(payload));
|
||||
});
|
||||
let (tx, rx) = channel();
|
||||
scope.spawn(move || {
|
||||
let mut reply = Vec::new();
|
||||
let read = from_child.take(reply_limit).read_to_end(&mut reply);
|
||||
let _ = tx.send(read.map(|_| reply));
|
||||
});
|
||||
let received = rx.recv_timeout(TIMEOUT);
|
||||
if matches!(received, Err(RecvTimeoutError::Timeout)) {
|
||||
let _ = child.kill();
|
||||
}
|
||||
received
|
||||
});
|
||||
let status = child.wait();
|
||||
let stopped = || format!("the DWG worker stopped while {doing}; nothing else is affected");
|
||||
Some(match (received, status) {
|
||||
(Err(RecvTimeoutError::Timeout), _) => Err(format!("{doing} took too long, so the DWG worker was stopped; nothing else is affected")),
|
||||
(Ok(Ok(reply)), Ok(status)) if status.success() => parse_reply(reply).ok_or_else(stopped),
|
||||
_ => Err(stopped()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Take `n` bytes off the front of `b`.
|
||||
fn take<'a>(b: &mut &'a [u8], n: usize) -> Option<&'a [u8]> {
|
||||
let (head, tail) = b.split_at_checked(n)?;
|
||||
*b = tail;
|
||||
Some(head)
|
||||
}
|
||||
|
||||
fn take_u32(b: &mut &[u8]) -> Option<usize> {
|
||||
let bytes: [u8; 4] = take(b, 4)?.try_into().ok()?;
|
||||
usize::try_from(u32::from_le_bytes(bytes)).ok()
|
||||
}
|
||||
|
||||
fn take_u64(b: &mut &[u8]) -> Option<u64> {
|
||||
Some(u64::from_le_bytes(take(b, 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// A reply: 0, the note count, each note with its length, then the bytes with their length; or 1
|
||||
/// and a message. `None` when it isn't one, whole. Takes the reply, because the bytes can be most
|
||||
/// of the memory the app may use: they are kept, not copied.
|
||||
fn parse_reply(mut reply: Vec<u8>) -> Option<Reply> {
|
||||
let total = reply.len();
|
||||
let mut b = &reply[..];
|
||||
match *take(&mut b, 1)?.first()? {
|
||||
0 => {
|
||||
let count = take_u32(&mut b)?;
|
||||
let mut notes = Vec::new();
|
||||
for _ in 0..count {
|
||||
let n = take_u32(&mut b)?;
|
||||
notes.push(String::from_utf8_lossy(take(&mut b, n)?).into_owned());
|
||||
}
|
||||
let n = usize::try_from(take_u64(&mut b)?).ok()?;
|
||||
if b.len() != n {
|
||||
return None;
|
||||
}
|
||||
reply.drain(..total - n);
|
||||
Some(Ok((reply, notes)))
|
||||
}
|
||||
1 => Some(Err(String::from_utf8_lossy(b).into_owned())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_reply(out: &mut impl Write, reply: Reply) -> std::io::Result<()> {
|
||||
match reply {
|
||||
Ok((bytes, notes)) => {
|
||||
out.write_all(&[0])?;
|
||||
out.write_all(&u32::try_from(notes.len()).unwrap_or(0).to_le_bytes())?;
|
||||
for note in ¬es {
|
||||
out.write_all(&u32::try_from(note.len()).unwrap_or(0).to_le_bytes())?;
|
||||
if u32::try_from(note.len()).is_ok() {
|
||||
out.write_all(note.as_bytes())?;
|
||||
}
|
||||
}
|
||||
out.write_all(&(bytes.len() as u64).to_le_bytes())?;
|
||||
out.write_all(&bytes)?;
|
||||
}
|
||||
Err(e) => {
|
||||
out.write_all(&[1])?;
|
||||
out.write_all(e.as_bytes())?;
|
||||
}
|
||||
}
|
||||
out.flush()
|
||||
}
|
||||
|
||||
/// What a request asks for, or why it can't be served.
|
||||
fn handle(mut b: &[u8]) -> Reply {
|
||||
let bad = || "the DWG worker got a request it can't read (a different CADCraft version?)".to_string();
|
||||
if take(&mut b, 1).and_then(<[u8]>::first) != Some(&PROTOCOL) {
|
||||
return Err(bad());
|
||||
}
|
||||
let op = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?;
|
||||
let max_dwg_bytes = take_u64(&mut b).and_then(|n| usize::try_from(n).ok()).ok_or_else(bad)?;
|
||||
let max_dxf_bytes = take_u64(&mut b).and_then(|n| usize::try_from(n).ok()).ok_or_else(bad)?;
|
||||
let version_len = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?;
|
||||
let version = take(&mut b, usize::from(version_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?;
|
||||
match op {
|
||||
DECODE => super::dwg_to_dxf_noted(b, Limits { max_dwg_bytes, max_dxf_bytes }),
|
||||
ENCODE => {
|
||||
// The version the DXF's carried-over groups were read from; empty for none.
|
||||
let kept_len = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?;
|
||||
let kept = take(&mut b, usize::from(kept_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?;
|
||||
encode_here(b, version, (!kept.is_empty()).then_some(kept))
|
||||
.map(|(dwg, left_out)| (dwg, left_out.iter().map(|(kind, n)| format!("{kind}\t{n}")).collect()))
|
||||
}
|
||||
CRASH => std::process::abort(),
|
||||
_ => Err(bad()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve the one request on `input`. The exit code is 0 unless the reply couldn't be sent.
|
||||
fn serve(input: impl Read, mut output: impl Write) -> i32 {
|
||||
let mut request = Vec::new();
|
||||
let reply = match input.take(MAX_REQUEST).read_to_end(&mut request) {
|
||||
Ok(_) => handle(&request),
|
||||
Err(e) => Err(format!("the DWG worker could not read its request: {e}")),
|
||||
};
|
||||
i32::from(write_reply(&mut output, reply).is_err())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn wire(reply: Reply) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
write_reply(&mut out, reply).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_writer_left_out_survives_the_reply() {
|
||||
let notes = vec!["ACME_WIDGET\t2".to_string(), "not a count".to_string(), "X\tmany".to_string()];
|
||||
assert_eq!(unwritten_from(¬es), [("ACME_WIDGET".to_string(), 2)].into_iter().collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replies_round_trip() {
|
||||
let ok: Reply = Ok((b"bytes".to_vec(), vec!["one".into(), "two é".into()]));
|
||||
assert_eq!(parse_reply(wire(ok.clone())), Some(ok));
|
||||
let failed: Reply = Err("DWG: no".into());
|
||||
assert_eq!(parse_reply(wire(failed.clone())), Some(failed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_cut_short_or_made_up_is_refused() {
|
||||
let whole = wire(Ok((b"bytes".to_vec(), vec!["note".into()])));
|
||||
for n in 0..whole.len() {
|
||||
assert_eq!(parse_reply(whole[..n].to_vec()), None, "cut at {n}");
|
||||
}
|
||||
assert_eq!(parse_reply(vec![7, 0, 0]), None);
|
||||
// A note count far beyond what follows ends at the first missing note.
|
||||
assert_eq!(parse_reply(vec![0, 0xff, 0xff, 0xff, 0xff]), None);
|
||||
assert_eq!(parse_reply(vec![0, 1, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_it_cannot_read_is_an_error_not_a_crash() {
|
||||
for request in [
|
||||
&[][..],
|
||||
&[PROTOCOL + 1, DECODE],
|
||||
&[PROTOCOL],
|
||||
&[PROTOCOL, DECODE, 1, 2, 3],
|
||||
&[PROTOCOL, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
] {
|
||||
assert!(handle(request).is_err(), "{request:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An encode request carries the kept version after the target one; a request without it is
|
||||
/// one it can't read, and one with it reaches the converter.
|
||||
#[test]
|
||||
fn an_encode_request_carries_the_kept_version() {
|
||||
let bad = "the DWG worker got a request it can't read (a different CADCraft version?)";
|
||||
let short = self::request(ENCODE, Limits::DEFAULT, "AC1032");
|
||||
assert_eq!(handle(&short).unwrap_err(), bad);
|
||||
for kept in ["", "AC1032"] {
|
||||
let mut request = self::request(ENCODE, Limits::DEFAULT, "AC1032");
|
||||
push_str(&mut request, kept);
|
||||
request.extend(b"not a drawing");
|
||||
let err = handle(&request).unwrap_err();
|
||||
assert_ne!(err, bad, "kept {kept:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serving_reports_a_decode_failure_as_a_reply() {
|
||||
let mut request = self::request(DECODE, Limits::DEFAULT, "");
|
||||
request.extend(b"AC1032 not really a drawing");
|
||||
let mut out = Vec::new();
|
||||
assert_eq!(serve(&request[..], &mut out), 0);
|
||||
assert!(matches!(parse_reply(out.clone()), Some(Err(_))), "{out:?}");
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ workspace = true
|
||||
cadcraft-geom = { workspace = true }
|
||||
cadcraft-color = { workspace = true }
|
||||
cadcraft-doc = { workspace = true }
|
||||
craft-mime = { workspace = true }
|
||||
craft-dxf = { workspace = true }
|
||||
cadcraft-constraints = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St
|
||||
|
||||
pub(super) fn blockreplace_spec() -> CommandSpec {
|
||||
CommandSpec::new("blockreplace", "Replace Block...", run_blockreplace)
|
||||
.menu(&["Tools", "Express Tools", "Replace Block..."])
|
||||
.menu(&["Tools", "Additional Tools", "Replace Block..."])
|
||||
.alias(&["-blockreplace"])
|
||||
.params("{block (the block whose references are replaced), with (the replacement block), purge?: bool (default false: remove the replaced block's definition when nothing references it any more)} → {block, with, replaced, purged}")
|
||||
.interactive(|_| Ok(Box::new(BlockreplaceM::default())))
|
||||
@@ -184,8 +184,10 @@ impl Interactive for BlockreplaceM {
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.stage {
|
||||
Stage::Old => Prompt::new("Enter the name of the block to replace", Accept::TEXT).kw(&["?", "Select"]),
|
||||
Stage::New => Prompt::new(format!("Enter the name of the replacement block for {}", self.old), Accept::TEXT).kw(&["?", "Select"]),
|
||||
Stage::Old => Prompt::new("Enter the name of the block to replace", Accept::TEXT).kw(&["?", "Select"]).takes_block(),
|
||||
Stage::New => {
|
||||
Prompt::new(format!("Enter the name of the replacement block for {}", self.old), Accept::TEXT).kw(&["?", "Select"]).takes_block()
|
||||
}
|
||||
Stage::Select => Prompt::new("Select a block reference", Accept::SELECT),
|
||||
Stage::Purge => Prompt::new(format!("Purge the unreferenced block definition {}?", self.old), KW).kw(&["Yes", "No"]).default("Yes"),
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::{Result, Session};
|
||||
|
||||
pub(super) fn burst_spec() -> CommandSpec {
|
||||
CommandSpec::new("burst", "Explode Attributes to Text", run_burst)
|
||||
.menu(&["Tools", "Express Tools", "Explode Attributes to Text"])
|
||||
.menu(&["Tools", "Additional Tools", "Explode Attributes to Text"])
|
||||
.params("{handles?} (block references; other objects are left alone) → {handles}")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("burst", "BURST"))))
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("breakline", "Break-line Symbol", run_breakline)
|
||||
.menu(&["Tools", "Express Tools", "Break-line Symbol"])
|
||||
.menu(&["Tools", "Additional Tools", "Break-line Symbol"])
|
||||
.params(
|
||||
"{p1, p2, at?: [x,y] (symbol location; default the midpoint), size? (default 1, times DIMSCALE), \
|
||||
extension? (past both points; default 0), block? (a block with two points on Defpoints; default the built-in symbol)} → {handle}",
|
||||
|
||||
@@ -557,9 +557,15 @@ fn run_clear(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
fn run_selectall(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let space = s.space();
|
||||
let d = s.doc()?;
|
||||
let frozen = s.viewport_frozen();
|
||||
let hs: Vec<Handle> = d
|
||||
.space(&space)
|
||||
.map(|st| st.iter().filter(|e| d.is_visible(e) && d.layer(&e.common.layer).is_none_or(|l| !l.locked)).map(|e| e.handle).collect())
|
||||
.map(|st| {
|
||||
st.iter()
|
||||
.filter(|e| crate::select::selectable(d, e, frozen) && d.layer(&e.common.layer).is_none_or(|l| !l.locked))
|
||||
.map(|e| e.handle)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let n = hs.len();
|
||||
s.set_selection(hs);
|
||||
@@ -580,16 +586,19 @@ fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let add = bool_or(p, "add", false);
|
||||
let picked: Vec<Handle> = if let Some(w) = points_param(p, "window") {
|
||||
let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return Err(bad("select", "window needs 2 corners")) };
|
||||
crate::select::select_window(s.doc()?, &space, Bounds2::new(*a, *b), bool_or(p, "crossing", false))
|
||||
crate::select::select_window_in(s.doc()?, &space, s.viewport_frozen(), Bounds2::new(*a, *b), bool_or(p, "crossing", false))
|
||||
} else if let Some(at) = point_param(p, "at") {
|
||||
let ap = f64_or(p, "aperture", s.pixel_size() * s.settings.pickbox * 1.5);
|
||||
crate::select::pick(s.doc()?, &space, at, ap).into_iter().collect()
|
||||
crate::select::pick_in(s.doc()?, &space, s.viewport_frozen(), at, ap).into_iter().collect()
|
||||
} else if let Some(f) = points_param(p, "fence") {
|
||||
crate::select::select_fence(s.doc()?, &space, &f)
|
||||
} else {
|
||||
crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &f)
|
||||
} else if ["handles", "handle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
targets(s, p)?
|
||||
} else {
|
||||
// Nothing to select with: the selection stays, also what the active viewport does not draw.
|
||||
s.stored_selection()
|
||||
};
|
||||
let mut sel = if add { s.selection() } else { Vec::new() };
|
||||
let mut sel = if add { s.stored_selection() } else { Vec::new() };
|
||||
sel.extend(picked);
|
||||
s.set_selection(sel);
|
||||
let sel = s.selection();
|
||||
|
||||
@@ -363,7 +363,7 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
|
||||
cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b);
|
||||
}
|
||||
let png = pm.encode_png().map_err(|_| bad("preview", "rendering the preview failed"))?;
|
||||
let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?;
|
||||
let layout = space.tab_name();
|
||||
Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape }))
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::{Accept, Input, Prompt, Result, Session, Step};
|
||||
|
||||
/// The rules the Command Aliases dialog checks before it sends an alias to ALIASEDIT.
|
||||
pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases};
|
||||
pub(crate) use pgp::{specs as alias_specs, user_alias};
|
||||
pub(crate) use pgp::{greek_alias, specs as alias_specs, user_alias};
|
||||
pub use template::{qnew_template, set_qnew_template};
|
||||
|
||||
/// Largest drawing accepted from a local path, matching the per-file xref limit. A path naming an
|
||||
@@ -1020,46 +1020,14 @@ fn run_saveas_reporting(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
save_reporting(s, p, run_saveas, asked)
|
||||
}
|
||||
|
||||
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
/// Encode bytes with the standard padded Base64 alphabet.
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
|
||||
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
|
||||
for i in 0..4 {
|
||||
if i <= chunk.len() {
|
||||
out.push(char::from(B64[((n >> (18 - 6 * i)) & 63) as usize]));
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
craft_mime::base64::STANDARD.encode(data)
|
||||
}
|
||||
|
||||
/// Decode the legacy file/control Base64 form, retaining its permissive alphabet and padding.
|
||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(s.len() * 3 / 4);
|
||||
let mut buf = 0u32;
|
||||
let mut bits = 0;
|
||||
for c in s.bytes() {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' | b'-' => 62,
|
||||
b'/' | b'_' => 63,
|
||||
b'=' | b'\n' | b'\r' | b' ' => continue,
|
||||
_ => return None,
|
||||
};
|
||||
buf = (buf << 6) | u32::from(v);
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(((buf >> bits) & 0xff) as u8);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
craft_mime::base64_compat::decode(s).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -59,6 +59,12 @@ pub(crate) fn user_alias(name: &str) -> Option<String> {
|
||||
store().map.get(name).cloned()
|
||||
}
|
||||
|
||||
/// The user alias that is the Greek word `word` in another case or accent.
|
||||
pub(crate) fn greek_alias(word: &str) -> Option<String> {
|
||||
let same = crate::keyboard::same_greek_word_as(word)?;
|
||||
store().map.keys().find(|alias| same(alias)).cloned()
|
||||
}
|
||||
|
||||
/// The user aliases and the file REINIT reads, as the host's user profile keeps them:
|
||||
/// `{"aliases": {alias: command}, "file": path or null}`. Not drawing data.
|
||||
pub fn alias_profile() -> Value {
|
||||
|
||||
@@ -43,7 +43,8 @@ pub(crate) struct GripEdit {
|
||||
hot: Vec<(Handle, usize)>,
|
||||
/// Typed `GRIP`: still collecting grips ("Select grips").
|
||||
picking: bool,
|
||||
/// What MOVE/ROTATE/SCALE/MIRROR transform: the hot grips' objects and the selection.
|
||||
/// What MOVE/ROTATE/SCALE/MIRROR transform: the hot grips' objects and the objects of the
|
||||
/// selection that the view being edited shows.
|
||||
targets: Vec<Handle>,
|
||||
base: Vec2,
|
||||
mode: GripMode,
|
||||
@@ -69,6 +70,13 @@ fn positive(v: Option<f64>) -> Result<f64> {
|
||||
v.filter(|f| f.is_finite() && *f > 1e-12).ok_or_else(|| other("Requires a positive number."))
|
||||
}
|
||||
|
||||
/// Whether the view being edited shows `h`. A hidden object (HIDEOBJECTS, an off or frozen layer,
|
||||
/// a layer frozen in the active MSPACE viewport) takes no part in a grip edit, even when Undo or
|
||||
/// a selection command put it back into the selection.
|
||||
fn shown(s: &Session, h: Handle) -> bool {
|
||||
s.state().is_ok_and(|st| st.doc.entity(h).is_some_and(|e| st.shows(e)))
|
||||
}
|
||||
|
||||
impl GripEdit {
|
||||
fn new(s: &Session, hot: Vec<(Handle, usize)>) -> Result<Self> {
|
||||
let mut g = GripEdit {
|
||||
@@ -87,16 +95,22 @@ impl GripEdit {
|
||||
Ok(g)
|
||||
}
|
||||
|
||||
/// Make grip `index` of `h` hot (the first one becomes the base point).
|
||||
/// Make grip `index` of `h` hot (the first one becomes the base point). The grip of an object
|
||||
/// the view being edited does not show is left out, and so are the hidden objects of the
|
||||
/// selection.
|
||||
fn add_hot(&mut self, s: &Session, (h, i): (Handle, usize)) -> Result<()> {
|
||||
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
|
||||
return Ok(());
|
||||
}
|
||||
let p = s.grips_of(h)?.get(i).copied().ok_or_else(|| other("no such grip"))?;
|
||||
// After the lookup: a missing object or grip stays the error it was.
|
||||
if !shown(s, h) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.hot.is_empty() {
|
||||
self.base = p;
|
||||
self.targets.push(h);
|
||||
self.targets.extend(s.selection().into_iter().filter(|x| *x != h));
|
||||
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
|
||||
} else if !self.targets.contains(&h) {
|
||||
self.targets.push(h);
|
||||
}
|
||||
@@ -107,13 +121,13 @@ impl GripEdit {
|
||||
/// The grips of the selected objects at `p` (typed `GRIP`): all objects with a grip there.
|
||||
fn grips_at(s: &Session, p: Vec2) -> Vec<(Handle, usize)> {
|
||||
let tol = (s.pixel_size() * (s.settings.gripsize + 3.0)).max(1e-9 * (1.0 + p.len()));
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let Ok(st) = s.state() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for h in s.selection().into_iter().take(MAX_HOT) {
|
||||
if super::curves::is_locked(s, h) {
|
||||
continue;
|
||||
}
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
|
||||
let gs = e.kind.grips();
|
||||
// The nearest grip of this object within the tolerance.
|
||||
let best = gs
|
||||
@@ -470,7 +484,9 @@ impl Interactive for GripEdit {
|
||||
impl Session {
|
||||
/// Make grips hot and start editing them (the UI's click on a grip; Shift+click collects
|
||||
/// several first). `hot` lists (object, grip index); the first is the base grip. The grip
|
||||
/// modes and their options then run at the command line like any prompt.
|
||||
/// modes and their options then run at the command line like any prompt. Grips of objects the
|
||||
/// view being edited does not show are left out (the first grip left is the base grip), and it
|
||||
/// is an error when none is left.
|
||||
pub fn start_grip_edit(&mut self, hot: &[(Handle, usize)]) -> Result<()> {
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
@@ -479,6 +495,9 @@ impl Session {
|
||||
return Err(other("no grip"));
|
||||
}
|
||||
let g = GripEdit::new(self, hot.to_vec())?;
|
||||
if g.hot.is_empty() {
|
||||
return Err(other("no grip"));
|
||||
}
|
||||
let label = g.label();
|
||||
let machine = crate::guard::Guarded::wrap(Box::new(g));
|
||||
let st = self.state()?;
|
||||
|
||||
@@ -28,7 +28,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
const MEMBER_PICKS: &[&str] = &["groupedit", "-group"];
|
||||
|
||||
/// `hs` plus the other members of the selectable groups they belong to (in the space being
|
||||
/// edited, visible), when PICKSTYLE has group selection on. Order: `hs` first.
|
||||
/// edited, visible, and inside an MSPACE viewport not on a layer frozen in it), when PICKSTYLE
|
||||
/// has group selection on. Order: `hs` first.
|
||||
pub(crate) fn expand(s: &Session, hs: Vec<Handle>) -> Vec<Handle> {
|
||||
if s.settings.pickstyle & 1 == 0 || hs.is_empty() || s.running.as_ref().is_some_and(|r| MEMBER_PICKS.contains(&r.id.as_str())) {
|
||||
return hs;
|
||||
@@ -39,6 +40,7 @@ pub(crate) fn expand(s: &Session, hs: Vec<Handle>) -> Vec<Handle> {
|
||||
}
|
||||
let space = s.space();
|
||||
let Some(store) = d.space(&space) else { return hs };
|
||||
let frozen = s.viewport_frozen();
|
||||
// Member → its selectable groups, built once (window selections may hold many objects).
|
||||
let mut of: HashMap<Handle, Vec<usize>> = HashMap::new();
|
||||
for (i, g) in d.groups.iter().enumerate().filter(|(_, g)| g.selectable) {
|
||||
@@ -56,7 +58,7 @@ pub(crate) fn expand(s: &Session, hs: Vec<Handle>) -> Vec<Handle> {
|
||||
}
|
||||
let Some(g) = d.groups.get(*gi) else { continue };
|
||||
for m in &g.members {
|
||||
if store.get(*m).is_some_and(|e| d.is_visible(e)) && seen.insert(*m) {
|
||||
if store.get(*m).is_some_and(|e| crate::select::selectable(d, e, frozen)) && seen.insert(*m) {
|
||||
out.push(*m);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,6 +533,19 @@ fn run_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "message": format!("{n} Region(s) created.") }))
|
||||
}
|
||||
|
||||
/// Whether the upper-case `name` is a pattern: a standard one or a loaded one.
|
||||
fn pattern_exists(name: &str) -> bool {
|
||||
cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some()
|
||||
}
|
||||
|
||||
/// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded
|
||||
/// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ).
|
||||
pub(crate) fn pattern_named(name: &str) -> Option<String> {
|
||||
let name = name.trim();
|
||||
let up = name.to_ascii_uppercase();
|
||||
if pattern_exists(&up) { Some(up) } else { patfile::user_pattern_name(name) }
|
||||
}
|
||||
|
||||
/// The origin sub-prompt's keywords (a point sets a new origin).
|
||||
const ORIGIN_KW: [&str; 6] = ["Bottom left", "bottom Right", "Top left", "top riGht", "Center", "Use current"];
|
||||
|
||||
@@ -597,7 +610,7 @@ impl HatchM {
|
||||
Some(n) => n,
|
||||
None => t.trim().to_ascii_uppercase(),
|
||||
};
|
||||
if cadcraft_doc::library::pattern(&up).is_some() || patfile::user_pattern(&up).is_some() {
|
||||
if pattern_exists(&up) {
|
||||
self.settings.pattern = up.clone();
|
||||
s.doc_mut()?.header.set_str("HPNAME", &up);
|
||||
} else {
|
||||
|
||||
@@ -28,6 +28,13 @@ pub(crate) fn user_pattern(name: &str) -> Option<UserPattern> {
|
||||
store().iter().find(|p| p.name.eq_ignore_ascii_case(name)).cloned()
|
||||
}
|
||||
|
||||
/// The name of the user pattern that is the Greek word `name` in another case or accent
|
||||
/// ([`user_pattern`] folds ASCII only).
|
||||
pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
|
||||
let same = crate::keyboard::same_greek_word_as(name)?;
|
||||
store().iter().find(|p| same(&p.name)).map(|p| p.name.clone())
|
||||
}
|
||||
|
||||
/// The line families a new hatch of pattern `name` carries: a user pattern's, else none (the
|
||||
/// library's patterns are drawn and saved from the library).
|
||||
pub(crate) fn lines_for(name: &str) -> Vec<PatternLine> {
|
||||
|
||||
@@ -591,7 +591,7 @@ fn run_inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"dimStyles": d.dim_styles.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
|
||||
"blocks": d.blocks.keys().filter(|k| !k.starts_with('*')).cloned().collect::<Vec<_>>(),
|
||||
"layouts": d.layouts.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
|
||||
"selection": st.selection.iter().map(|h| h.hex()).collect::<Vec<_>>(),
|
||||
"selection": st.shown_selection().iter().map(|h| h.hex()).collect::<Vec<_>>(),
|
||||
"undo": st.undo.iter().rev().take(20).map(|u| u.label.clone()).collect::<Vec<_>>(),
|
||||
"view": { "center": [st.view().center.x, st.view().center.y], "height": st.view().height },
|
||||
// Records of the file the drawing came from that the reader could not place.
|
||||
|
||||
@@ -21,14 +21,17 @@ impl StretchArea {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add to `hs` the visible multilines in `space` with a control vertex inside `area`. A crossing
|
||||
/// selection tests the drawn element lines, which sit away from the control vertices by the
|
||||
/// multiline's scale, so a small area around a vertex alone would miss them.
|
||||
fn add_mline_vertex_hits(d: &cadcraft_doc::Drawing, space: &cadcraft_doc::Space, area: &StretchArea, hs: &mut Vec<Handle>) {
|
||||
let Some(store) = d.space(space) else { return };
|
||||
/// Add to `hs` the multilines in the edit space that a selection can take there (visible, and
|
||||
/// inside an MSPACE viewport not on a layer frozen in it) with a control vertex inside `area`. A
|
||||
/// crossing selection tests the drawn element lines, which sit away from the control vertices by
|
||||
/// the multiline's scale, so a small area around a vertex alone would miss them.
|
||||
fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let Some(store) = d.space(&s.space()) else { return };
|
||||
let frozen = s.viewport_frozen();
|
||||
for e in store.iter() {
|
||||
if let EntityKind::MLine(m) = &e.kind
|
||||
&& d.is_visible(e)
|
||||
&& crate::select::selectable(d, e, frozen)
|
||||
&& !hs.contains(&e.handle)
|
||||
&& m.vertices.iter().any(|v| area.contains(v.p.xy()))
|
||||
{
|
||||
@@ -94,19 +97,19 @@ pub(super) fn run_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// A fence marks no area: the objects it crosses move whole.
|
||||
if let Some(fence) = listed("fence", 2)? {
|
||||
let hs = crate::select::select_fence(s.doc()?, &space, &fence);
|
||||
let hs = crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &fence);
|
||||
let moved = transform_entities(s, &hs, &Mat3::translate(d), false)?;
|
||||
return Ok(json!({ "stretched": moved.len() }));
|
||||
}
|
||||
let (mut hs, area) = if let Some(poly) = listed("polygon", 3)? {
|
||||
(crate::select::select_polygon(s.doc()?, &space, &poly, true), StretchArea::Polygon(poly))
|
||||
(crate::select::select_polygon_in(s.doc()?, &space, s.viewport_frozen(), &poly, true), StretchArea::Polygon(poly))
|
||||
} else {
|
||||
let w = points_param(p, "window").ok_or_else(|| bad("stretch", "`window` [[x,y],[x,y]], `polygon` or `fence` is required"))?;
|
||||
let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return Err(bad("stretch", "window needs 2 corners")) };
|
||||
let bx = cadcraft_geom::Bounds2::new(*a, *b);
|
||||
(crate::select::select_window(s.doc()?, &space, bx, true), StretchArea::Box(bx))
|
||||
(crate::select::select_window_in(s.doc()?, &space, s.viewport_frozen(), bx, true), StretchArea::Box(bx))
|
||||
};
|
||||
add_mline_vertex_hits(s.doc()?, &space, &area, &mut hs);
|
||||
add_mline_vertex_hits(s, &area, &mut hs);
|
||||
hs.retain(|h| !crate::cmd::curves::is_locked(s, *h));
|
||||
let doc = s.doc_mut()?;
|
||||
let areas = [area];
|
||||
@@ -173,7 +176,7 @@ impl StretchM {
|
||||
/// of two) the mode is dropped.
|
||||
fn finish_mode(&mut self, s: &mut Session, m: SelectMode) -> Result<()> {
|
||||
let space = s.space();
|
||||
let Some(mut hs) = m.select(s.doc()?, &space) else { return Ok(()) };
|
||||
let Some(mut hs) = m.select_in(s.doc()?, &space, s.viewport_frozen()) else { return Ok(()) };
|
||||
let crossing = match (m.kind, m.pts.first().zip(m.pts.get(1))) {
|
||||
(SelectKind::Crossing | SelectKind::CPolygon, _) => true,
|
||||
(SelectKind::Box, Some((a, b))) => b.x < a.x,
|
||||
@@ -189,7 +192,7 @@ impl StretchM {
|
||||
};
|
||||
let whole = area.is_none();
|
||||
if let (Some(a), true, false) = (&area, crossing, self.removing) {
|
||||
add_mline_vertex_hits(s.doc()?, &space, a, &mut hs);
|
||||
add_mline_vertex_hits(s, a, &mut hs);
|
||||
}
|
||||
if let (Some(a), false) = (area, self.removing) {
|
||||
self.windows.push(a);
|
||||
@@ -228,10 +231,10 @@ impl StretchM {
|
||||
Some(c) => {
|
||||
let bx = cadcraft_geom::Bounds2::new(c, p);
|
||||
let space = s.space();
|
||||
let mut hs = crate::select::select_window(s.doc()?, &space, bx, p.x < c.x);
|
||||
let mut hs = crate::select::select_window_in(s.doc()?, &space, s.viewport_frozen(), bx, p.x < c.x);
|
||||
if !self.removing {
|
||||
if p.x < c.x {
|
||||
add_mline_vertex_hits(s.doc()?, &space, &StretchArea::Box(bx), &mut hs);
|
||||
add_mline_vertex_hits(s, &StretchArea::Box(bx), &mut hs);
|
||||
}
|
||||
self.windows.push(StretchArea::Box(bx));
|
||||
}
|
||||
@@ -240,7 +243,7 @@ impl StretchM {
|
||||
None => {
|
||||
let aperture = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
match crate::select::pick(s.doc()?, &space, p, aperture) {
|
||||
match crate::select::pick_in(s.doc()?, &space, s.viewport_frozen(), p, aperture) {
|
||||
Some(h) => self.add(s, vec![h], true),
|
||||
None => self.corner = Some(p),
|
||||
}
|
||||
@@ -251,6 +254,7 @@ impl StretchM {
|
||||
self.corner = None;
|
||||
let d = s.doc()?;
|
||||
let store = d.space(&s.space());
|
||||
let frozen = s.viewport_frozen();
|
||||
let word = t.trim().to_ascii_lowercase();
|
||||
// `_C`, `_L`: the English name, as scripts write it.
|
||||
let word = word.strip_prefix('_').unwrap_or(&word).to_string();
|
||||
@@ -267,9 +271,14 @@ impl StretchM {
|
||||
self.removing = false;
|
||||
None
|
||||
}
|
||||
"all" => Some(store.map(|st| st.iter().filter(|e| d.is_visible(e)).map(|e| e.handle).collect()).unwrap_or_default()),
|
||||
"l" | "last" => Some(store.and_then(|st| st.last()).map(|e| vec![e.handle]).unwrap_or_default()),
|
||||
"p" | "previous" => Some(s.state()?.previous_selection.clone()),
|
||||
"all" => Some(
|
||||
store.map(|st| st.iter().filter(|e| crate::select::selectable(d, e, frozen)).map(|e| e.handle).collect()).unwrap_or_default(),
|
||||
),
|
||||
"l" | "last" => Some(store.and_then(|st| crate::select::last_in(st, frozen)).map(|h| vec![h]).unwrap_or_default()),
|
||||
"p" | "previous" => {
|
||||
let st = s.state()?;
|
||||
Some(st.drawn_in_viewport(&st.previous_selection))
|
||||
}
|
||||
_ => {
|
||||
s.echo("*Invalid selection*");
|
||||
None
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params("{handle (block reference), pick?: [x,y] (nearest nested object; default all), delta? | from,to}")
|
||||
.interactive(|_| Ok(Box::new(NcopyM::default()))),
|
||||
CommandSpec::new("mocoro", "Move/Copy/Rotate", mocoro::run_mocoro)
|
||||
.menu(&["Tools", "Express Tools", "Move/Copy/Rotate"])
|
||||
.menu(&["Tools", "Additional Tools", "Move/Copy/Rotate"])
|
||||
.params("{handles?, base: [x,y], ops: [{move: [x,y]} | {copy: [x,y]} | {rotate: degrees} | {scale: factor} | {base: [x,y]}]} → {handles (copies)}")
|
||||
.interactive(|_| Ok(Box::new(mocoro::MocoroM::default()))),
|
||||
CommandSpec::new("chspace", "Change Space", run_chspace)
|
||||
|
||||
@@ -280,7 +280,7 @@ fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = match mode.as_str() {
|
||||
"exclude" => excluded,
|
||||
"append" => {
|
||||
let mut cur = s.selection();
|
||||
let mut cur = s.stored_selection();
|
||||
for h in matched {
|
||||
if !cur.contains(&h) {
|
||||
cur.push(h);
|
||||
|
||||
@@ -99,14 +99,21 @@ pub(crate) fn similar(e: &Entity, r: &Entity, mode: u32) -> bool {
|
||||
&& (mode & NAME == 0 || same_text(object_name(e), object_name(r)))
|
||||
}
|
||||
|
||||
/// The visible objects of the current space like any of `refs`.
|
||||
/// The objects of the current space like any of `refs` that a selection can take there: visible,
|
||||
/// and inside an MSPACE viewport not on a layer frozen in it.
|
||||
fn similar_objects(s: &Session, d: &Drawing, refs: &[Handle], mode: u32) -> Vec<Handle> {
|
||||
let refs: Vec<&Entity> = refs.iter().filter_map(|h| d.entity(*h).map(|e| e.as_ref())).collect();
|
||||
if refs.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(store) = d.space(&s.space()) else { return Vec::new() };
|
||||
store.iter().take(MAX_SCAN).filter(|e| d.is_visible(e) && refs.iter().any(|r| similar(e, r, mode))).map(|e| e.handle).collect()
|
||||
let frozen = s.viewport_frozen();
|
||||
store
|
||||
.iter()
|
||||
.take(MAX_SCAN)
|
||||
.filter(|e| crate::select::selectable(d, e, frozen) && refs.iter().any(|r| similar(e, r, mode)))
|
||||
.map(|e| e.handle)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mode_param(s: &Session, p: &Value) -> Result<u32> {
|
||||
|
||||
@@ -59,7 +59,7 @@ fn fence(s: &mut Session, pts: &[Vec2], extending: bool, edges: Edges, quick: bo
|
||||
let fb = Bounds2::from_points(pts.iter().copied());
|
||||
let tol = crate::select::window_tol(&fb);
|
||||
let mut work: Vec<(Handle, Vec<Vec2>)> = Vec::new();
|
||||
for h in crate::select::select_fence(d, &space, pts) {
|
||||
for h in crate::select::select_fence_in(d, &space, s.viewport_frozen(), pts) {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let polys = crate::select::hit_polylines(d, e, tol);
|
||||
let mut xs: Vec<Vec2> = Vec::new();
|
||||
@@ -96,7 +96,7 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu
|
||||
];
|
||||
let inside = |p: Vec2| bx.expand(tol).contains(p);
|
||||
let mut work: Vec<(Handle, Vec<Vec2>)> = Vec::new();
|
||||
for h in crate::select::select_window(d, &space, bx, true) {
|
||||
for h in crate::select::select_window_in(d, &space, s.viewport_frozen(), bx, true) {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let mut best: Option<Vec2> = None;
|
||||
for pl in crate::select::hit_polylines(d, e, tol) {
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("txt2mtxt", "Convert Text to Mtext", run_txt2mtxt)
|
||||
.menu(&["Tools", "Express Tools", "Convert Text to Mtext"])
|
||||
.menu(&["Tools", "Additional Tools", "Convert Text to Mtext"])
|
||||
.params(
|
||||
"{handles? (default the selection; TEXT, and MTEXT when combining), combine? (default true: one MTEXT; false: one per TEXT), \
|
||||
sort?: \"topdown\" (default) | \"selection\", wrap? (default false: one line per text)} → {handles}",
|
||||
|
||||
@@ -8,6 +8,12 @@ pub struct Snapshot {
|
||||
pub selection: Vec<Handle>,
|
||||
}
|
||||
|
||||
/// [`DocState::drawn_in_viewport`] looks its handles up one by one while there is fewer than one
|
||||
/// of them for every `LOOKUP_COST` objects of model space, and passes over model space once
|
||||
/// otherwise. Timed on drawings of 40,000 and of 200,000 lines, the two cost the same at about
|
||||
/// one handle for every 47 and for every 18 objects.
|
||||
const LOOKUP_COST: usize = 32;
|
||||
|
||||
/// One open drawing.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DocState {
|
||||
@@ -119,13 +125,65 @@ impl DocState {
|
||||
}
|
||||
/// The active MSPACE viewport, if it still exists in the current layout.
|
||||
pub fn active_viewport(&self) -> Option<(Handle, cadcraft_doc::Viewport)> {
|
||||
self.active_viewport_ref().map(|(h, v)| (h, v.clone()))
|
||||
}
|
||||
/// [`DocState::active_viewport`] without copying the viewport.
|
||||
fn active_viewport_ref(&self) -> Option<(Handle, &cadcraft_doc::Viewport)> {
|
||||
let h = self.mspace?;
|
||||
let e = self.doc.space(&self.space)?.get(h)?;
|
||||
match &e.kind {
|
||||
cadcraft_doc::EntityKind::Viewport(v) if v.height > 1e-12 && v.view_height > 1e-12 => Some((h, v.clone())),
|
||||
cadcraft_doc::EntityKind::Viewport(v) if v.height > 1e-12 && v.view_height > 1e-12 => Some((h, v)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The layers frozen in the active MSPACE viewport (VPLAYER, "VP Freeze"): that viewport does
|
||||
/// not draw their objects, so picks, selections and grips made through it leave them out.
|
||||
/// Empty in paper space and on the Model tab.
|
||||
pub fn viewport_frozen(&self) -> &[String] {
|
||||
match self.active_viewport_ref() {
|
||||
Some((_, v)) => &v.frozen_layers,
|
||||
None => &[],
|
||||
}
|
||||
}
|
||||
/// Whether `e` is a model-space object the active MSPACE viewport does not draw: it is on a
|
||||
/// layer frozen in that viewport ([`DocState::viewport_frozen`]). Objects on the sheet are not
|
||||
/// drawn through the viewport, so its frozen layers do not hide them.
|
||||
pub fn hidden_in_viewport(&self, e: &cadcraft_doc::Entity) -> bool {
|
||||
crate::select::on_frozen_layer(self.viewport_frozen(), e) && self.doc.model.contains(e.handle)
|
||||
}
|
||||
/// Whether the view being edited shows `e`: the drawing shows it ([`Drawing::is_visible`]),
|
||||
/// and the active MSPACE viewport, if there is one, draws it
|
||||
/// ([`DocState::hidden_in_viewport`]).
|
||||
pub fn shows(&self, e: &cadcraft_doc::Entity) -> bool {
|
||||
self.doc.is_visible(e) && !self.hidden_in_viewport(e)
|
||||
}
|
||||
/// `handles` without the objects the active MSPACE viewport does not draw
|
||||
/// ([`DocState::hidden_in_viewport`]): a set of objects made earlier (the selection, the
|
||||
/// Previous set) as that viewport takes it. All of them anywhere else.
|
||||
pub(crate) fn drawn_in_viewport(&self, handles: &[Handle]) -> Vec<Handle> {
|
||||
let frozen = self.viewport_frozen();
|
||||
if frozen.is_empty() || handles.is_empty() {
|
||||
return handles.to_vec();
|
||||
}
|
||||
let model = &self.doc.model;
|
||||
let hidden = |e: &Arc<cadcraft_doc::Entity>| crate::select::on_frozen_layer(frozen, e);
|
||||
// The UI asks for the selection several times a frame. A few handles are looked up one
|
||||
// by one; beyond that, one pass over model space costs less than the lookups.
|
||||
if handles.len().saturating_mul(LOOKUP_COST) < model.len() {
|
||||
return handles.iter().copied().filter(|h| !model.get(*h).is_some_and(hidden)).collect();
|
||||
}
|
||||
let mut gone: Vec<Handle> = model.iter().filter(|e| hidden(e)).map(|e| e.handle).collect();
|
||||
gone.sort_unstable();
|
||||
handles.iter().copied().filter(|h| gone.binary_search(h).is_err()).collect()
|
||||
}
|
||||
/// The selection as the view being edited has it: [`DocState::selection`] without the objects
|
||||
/// the active MSPACE viewport does not draw. Those stay in [`DocState::selection`] until the
|
||||
/// selection is replaced or cleared, and count as selected again once that viewport draws
|
||||
/// them; until then nothing that starts from the selection (a command, a grip, a palette)
|
||||
/// edits them through that viewport.
|
||||
pub fn shown_selection(&self) -> Vec<Handle> {
|
||||
self.drawn_in_viewport(&self.selection)
|
||||
}
|
||||
pub fn paper_view(&self) -> View {
|
||||
self.views.iter().find(|(s, _)| *s == self.space).map(|(_, v)| *v).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Words typed on a Greek keyboard layout.
|
||||
//!
|
||||
//! With the Greek layout active, the keys that type LINE produce ΛΙΝΕ. Command names, aliases and
|
||||
//! prompt keywords are Latin, so a Greek speaker would have to switch layouts for every command.
|
||||
//! [`latin_keys`] reads a word as the Latin keys that produced it (the layout puts each Greek
|
||||
//! letter on the key of the Latin letter it sounds like): the command line then accepts ΛΙΝΕ and
|
||||
//! ΣΤΡΕΤΨΗ as LINE and STRETCH. Accents (the layout's dead key) are ignored.
|
||||
|
||||
/// The Latin key a Greek letter is typed on (lower case, accents removed).
|
||||
fn key_of(c: char) -> Option<char> {
|
||||
Some(match c {
|
||||
'α' | 'ά' => 'a',
|
||||
'β' => 'b',
|
||||
'γ' => 'g',
|
||||
'δ' => 'd',
|
||||
'ε' | 'έ' => 'e',
|
||||
'ζ' => 'z',
|
||||
'η' | 'ή' => 'h',
|
||||
'θ' => 'u',
|
||||
'ι' | 'ί' | 'ϊ' | 'ΐ' => 'i',
|
||||
'κ' => 'k',
|
||||
'λ' => 'l',
|
||||
'μ' => 'm',
|
||||
'ν' => 'n',
|
||||
'ξ' => 'j',
|
||||
'ο' | 'ό' => 'o',
|
||||
'π' => 'p',
|
||||
'ρ' => 'r',
|
||||
'σ' => 's',
|
||||
// The W key types the final sigma.
|
||||
'ς' => 'w',
|
||||
'τ' => 't',
|
||||
'υ' | 'ύ' | 'ϋ' | 'ΰ' => 'y',
|
||||
'φ' => 'f',
|
||||
'χ' => 'x',
|
||||
'ψ' => 'c',
|
||||
'ω' | 'ώ' => 'v',
|
||||
// The Q key types the semicolon, which Greek text writes as ";" or U+037E.
|
||||
';' | '\u{37e}' => 'q',
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `c` is a Greek letter (the basic and accented ranges the layout types).
|
||||
fn is_greek_letter(c: char) -> bool {
|
||||
matches!(c, '\u{386}'..='\u{3ce}') && c != '\u{387}'
|
||||
}
|
||||
|
||||
/// `word` read as the Latin keys of a Greek-layout keyboard, lower case: `Some` only when the word
|
||||
/// has a Greek letter and every character is a Greek letter the layout types, the semicolon on
|
||||
/// the Q key, or ASCII (itself, in lower case). A combining tonos or dialytika, the accent of
|
||||
/// decomposed text, is ignored like the accent of a precomposed letter, but only straight after
|
||||
/// the Greek letter it accents and once each: anywhere else the word is not Greek-layout typing.
|
||||
pub fn latin_keys(word: &str) -> Option<String> {
|
||||
let mut greek = false;
|
||||
// What the previous Greek letter already carries (tonos, dialytika); `None` when the previous
|
||||
// character is not a Greek letter, which leaves a combining mark nothing to accent.
|
||||
let mut marks: Option<(bool, bool)> = None;
|
||||
let mut out = String::with_capacity(word.len());
|
||||
for c in word.chars() {
|
||||
if matches!(c, '\u{301}' | '\u{308}') {
|
||||
let (tonos, dialytika) = marks.as_mut()?;
|
||||
if std::mem::replace(if c == '\u{301}' { tonos } else { dialytika }, true) {
|
||||
return None;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if c.is_ascii() {
|
||||
// The Q key types the ASCII semicolon in the Greek layout; every other ASCII character is itself.
|
||||
out.push(if c == ';' { 'q' } else { c.to_ascii_lowercase() });
|
||||
marks = None;
|
||||
continue;
|
||||
}
|
||||
let lower = c.to_lowercase().next().unwrap_or(c);
|
||||
out.push(key_of(lower)?);
|
||||
let letter = is_greek_letter(lower);
|
||||
greek |= letter;
|
||||
marks = letter.then_some((false, false));
|
||||
}
|
||||
greek.then_some(out)
|
||||
}
|
||||
|
||||
/// `word` with its case, accents and final sigma folded away, when it is Greek-layout typing: every
|
||||
/// spelling of one Greek word gives the same string. It is the word's keys, with the final sigma
|
||||
/// read as the letter sigma instead of the W key.
|
||||
pub fn greek_fold(word: &str) -> Option<String> {
|
||||
latin_keys(&word.replace('ς', "σ"))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are one Greek word, whatever their case, accents or final sigma.
|
||||
pub fn same_greek_word(a: &str, b: &str) -> bool {
|
||||
same_greek_word_as(b).is_some_and(|same| same(a))
|
||||
}
|
||||
|
||||
/// A test for "is the Greek word `word`, whatever the case, accents or final sigma", or `None`
|
||||
/// when `word` is not Greek-layout typing. `word` is folded here, once: looking a typed word up
|
||||
/// among many names costs its length once, not once for every name.
|
||||
pub fn same_greek_word_as(word: &str) -> Option<impl Fn(&str) -> bool> {
|
||||
let fold = greek_fold(word)?;
|
||||
Some(move |name: &str| greek_fold(name).as_deref() == Some(fold.as_str()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{latin_keys, same_greek_word};
|
||||
|
||||
/// One Greek word compares equal in any case, accent or final sigma; another word, or a Latin
|
||||
/// one, does not.
|
||||
#[test]
|
||||
fn one_greek_word_is_the_same_in_any_case_accent_or_final_sigma() {
|
||||
for (a, b) in [("ΣΟΛΙΔ", "σολιδ"), ("ΣΟΛΙΔ", "σολίδ"), ("ΛΑΣ", "λας"), ("ΛΑΣ", "λασ"), ("ΛΙ\u{301}ΝΕ", "λινε")]
|
||||
{
|
||||
assert!(same_greek_word(a, b), "{a} {b}");
|
||||
}
|
||||
for (a, b) in [("ΣΟΛΙΔ", "ΣΟΛΙ"), ("ΣΟΛΙΔ", "solid"), ("solid", "SOLID")] {
|
||||
assert!(!same_greek_word(a, b), "{a} {b}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A character the layout does not type is never taken for the Greek letter Unicode upper-cases
|
||||
/// it to: the micro sign is not μ, the long s and the sharp s are not σ, an alpha with an iota
|
||||
/// subscript is not αι, the theta symbol is not θ.
|
||||
#[test]
|
||||
fn a_character_the_layout_does_not_type_is_no_spelling_of_a_greek_letter() {
|
||||
let pairs = [("\u{b5}", "μ"), ("Λ\u{17f}", "ΛΣ"), ("Λ\u{df}", "ΛΣΣ"), ("\u{1fb3}", "αι"), ("\u{3d1}", "θ")];
|
||||
let same: Vec<_> = pairs.iter().filter(|(a, b)| same_greek_word(a, b) || same_greek_word(b, a)).collect();
|
||||
assert!(same.is_empty(), "{same:?}");
|
||||
}
|
||||
|
||||
/// Greek-layout typing reads as its Latin keys: plain, accented and decomposed letters, the Q
|
||||
/// and W keys, ASCII prefixes.
|
||||
#[test]
|
||||
fn greek_layout_commands_read_as_their_latin_keys() {
|
||||
assert_eq!(latin_keys("ΛΙΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("λινε").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΣΤΡΕΤΨΗ").as_deref(), Some("stretch"));
|
||||
assert_eq!(latin_keys("ΜΙΡΡΟΡ").as_deref(), Some("mirror"));
|
||||
assert_eq!(latin_keys("ΘΝΔΟ").as_deref(), Some("undo"));
|
||||
// The Q key types ";", the W key the final sigma.
|
||||
assert_eq!(latin_keys(";ΣΑΩΕ").as_deref(), Some("qsave"));
|
||||
assert_eq!(latin_keys("ςΒΛΟΨΚ").as_deref(), Some("wblock"));
|
||||
// Accented letters (the layout's dead key) read as the plain letter.
|
||||
assert_eq!(latin_keys("ΛΊΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΆΡΡΑΥ").as_deref(), Some("array"));
|
||||
// The same accents written as a combining mark after the letter (decomposed text).
|
||||
assert_eq!(latin_keys("ΛΙ\u{301}ΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΛΙΝΕ\u{301}").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΛΙ\u{308}ΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΛΙ\u{308}\u{301}ΝΕ").as_deref(), Some("line"), "dialytika and tonos on one letter");
|
||||
// Prefixes and digits are kept.
|
||||
assert_eq!(latin_keys("-ΛΑΥΕΡ").as_deref(), Some("-layer"));
|
||||
assert_eq!(latin_keys("_ΛΙΝΕ").as_deref(), Some("_line"));
|
||||
}
|
||||
|
||||
/// A word with no Greek letter, or with a character the layout does not type, is not read.
|
||||
#[test]
|
||||
fn words_that_are_not_greek_layout_typing_are_left_alone() {
|
||||
assert_eq!(latin_keys("line"), None, "no Greek letter");
|
||||
assert_eq!(latin_keys(""), None);
|
||||
assert_eq!(latin_keys(";"), None, "a semicolon alone is not a word");
|
||||
assert_eq!(latin_keys("ΛΙΝΕ Ж"), None, "a letter the layout does not type");
|
||||
assert_eq!(latin_keys("ΛΙΝΕ 日本"), None);
|
||||
assert_eq!(latin_keys("\u{387}"), None, "the ano teleia is punctuation, not a letter");
|
||||
}
|
||||
|
||||
/// A combining tonos or dialytika counts only straight after a Greek letter, and once each.
|
||||
#[test]
|
||||
fn a_combining_mark_must_follow_the_greek_letter_it_accents() {
|
||||
assert_eq!(latin_keys("\u{301}ΛΙΝΕ"), None, "no letter before the mark");
|
||||
assert_eq!(latin_keys("\u{308}ΛΙΝΕ"), None);
|
||||
assert_eq!(latin_keys("ΛΙΝΕ-\u{301}"), None, "after punctuation");
|
||||
assert_eq!(latin_keys("a\u{301}ΛΙΝΕ"), None, "after a Latin letter");
|
||||
assert_eq!(latin_keys("Λ\u{301}\u{301}ΙΝΕ"), None, "a second tonos on one letter");
|
||||
assert_eq!(latin_keys("Λ\u{308}\u{308}ΙΝΕ"), None, "a second dialytika on one letter");
|
||||
}
|
||||
|
||||
/// A 100 000-letter word and odd code points are read or refused; nothing panics.
|
||||
#[test]
|
||||
fn hostile_text_never_panics() {
|
||||
let long = "Ω".repeat(100_000);
|
||||
assert_eq!(latin_keys(&long).map(|s| s.len()), Some(100_000));
|
||||
for s in ["\u{0}", "\u{301}", "ΛΙΝΕ\u{301}", "\u{10ffff}", "ς\u{3c2}\u{3a3}"] {
|
||||
let _ = latin_keys(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ mod finite;
|
||||
pub mod grip_dims;
|
||||
pub mod grips;
|
||||
mod guard;
|
||||
pub mod keyboard;
|
||||
pub mod lisp;
|
||||
pub mod mtext_edit;
|
||||
pub mod pointmod;
|
||||
@@ -236,11 +237,25 @@ impl Session {
|
||||
pub fn space(&self) -> Space {
|
||||
self.state().map(DocState::edit_space).unwrap_or_default()
|
||||
}
|
||||
/// The layers frozen in the active MSPACE viewport ([`DocState::viewport_frozen`]): what a
|
||||
/// pick or a selection in [`Session::space`] leaves out. Empty with no drawing open.
|
||||
pub fn viewport_frozen(&self) -> &[String] {
|
||||
self.state().map(DocState::viewport_frozen).unwrap_or_default()
|
||||
}
|
||||
/// The tab being displayed: Model or a layout, regardless of MSPACE.
|
||||
pub fn layout_space(&self) -> Space {
|
||||
self.state().map(|s| s.space.clone()).unwrap_or_default()
|
||||
}
|
||||
/// The selected objects as the view being edited has them ([`DocState::shown_selection`]):
|
||||
/// inside an MSPACE viewport, without the objects on layers frozen in that viewport. Commands,
|
||||
/// grips and palettes start from this; [`DocState::selection`] holds every selected object.
|
||||
pub fn selection(&self) -> Vec<Handle> {
|
||||
self.state().map(DocState::shown_selection).unwrap_or_default()
|
||||
}
|
||||
/// Every selected object ([`DocState::selection`]), also the ones the active MSPACE viewport
|
||||
/// does not draw, which [`Session::selection`] leaves out. Adding to the selection or removing
|
||||
/// from it starts from this, so that it keeps them.
|
||||
pub(crate) fn stored_selection(&self) -> Vec<Handle> {
|
||||
self.state().map(|s| s.selection.clone()).unwrap_or_default()
|
||||
}
|
||||
pub fn set_selection(&mut self, sel: Vec<Handle>) {
|
||||
|
||||
@@ -126,9 +126,11 @@ fn write_text_file(path: &str, text: &str, append: bool) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_text_file(_path: &str, _text: &str, _append: bool) {}
|
||||
|
||||
/// A file or a folder: routines test whether a module is installed with `(findfile "module/.")`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_exists(path: &str) -> bool {
|
||||
std::path::Path::new(path).is_file()
|
||||
let p = std::path::Path::new(path);
|
||||
p.is_file() || p.is_dir()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -651,15 +651,19 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Some("X") => all(s, true),
|
||||
Some("L") => {
|
||||
let order = handles_in_order(ctx);
|
||||
order.last().copied().into_iter().collect()
|
||||
// Inside an MSPACE viewport, the objects that viewport does not draw are passed over.
|
||||
let st = ctx.s.state().ok();
|
||||
let drawn = |h: &Handle| st.is_none_or(|st| st.doc.entity(*h).is_none_or(|e| !st.hidden_in_viewport(e)));
|
||||
order.iter().rev().copied().find(drawn).into_iter().collect()
|
||||
}
|
||||
Some("P") => ctx.s.state().map(|st| st.previous_selection.clone()).unwrap_or_default(),
|
||||
Some("P") => ctx.s.state().map(|st| st.drawn_in_viewport(&st.previous_selection)).unwrap_or_default(),
|
||||
Some("I") => ctx.s.selection(),
|
||||
Some("W") | Some("C") => {
|
||||
let (p1, p2) = (point(0)?, point(1)?);
|
||||
let s = &*ctx.s;
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
crate::select::select_window(d, &space, cadcraft_geom::Bounds2::from_points([p1, p2]), mode.as_deref() == Some("C"))
|
||||
let bx = cadcraft_geom::Bounds2::from_points([p1, p2]);
|
||||
crate::select::select_window_in(d, &space, s.viewport_frozen(), bx, mode.as_deref() == Some("C"))
|
||||
}
|
||||
Some("F") | Some("WP") | Some("CP") => {
|
||||
let poly: Vec<Vec2> =
|
||||
@@ -667,8 +671,8 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let s = &*ctx.s;
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
match mode.as_deref() {
|
||||
Some("F") => crate::select::select_fence(d, &space, &poly),
|
||||
m => crate::select::select_polygon(d, &space, &poly, m == Some("CP")),
|
||||
Some("F") => crate::select::select_fence_in(d, &space, s.viewport_frozen(), &poly),
|
||||
m => crate::select::select_polygon_in(d, &space, s.viewport_frozen(), &poly, m == Some("CP")),
|
||||
}
|
||||
}
|
||||
Some(":S") | Some("A") | None => {
|
||||
@@ -684,7 +688,7 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let s = &*ctx.s;
|
||||
let ap = s.settings.pickbox.max(1.0) * s.pixel_size();
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
crate::select::pick(d, &space, p, ap).into_iter().collect()
|
||||
crate::select::pick_in(d, &space, s.viewport_frozen(), p, ap).into_iter().collect()
|
||||
}
|
||||
}
|
||||
Some(m) => return Err(LispError::new(format!("bad argument value: ssget mode {m}"))),
|
||||
|
||||
@@ -141,7 +141,7 @@ impl GetRequest {
|
||||
let ap = s.settings.pickbox.max(1.0) * s.pixel_size();
|
||||
let space = s.state().map(|st| st.edit_space()).map_err(|e| Again::Msg(e.to_string()))?;
|
||||
let d = s.doc().map_err(|e| Again::Msg(e.to_string()))?;
|
||||
match crate::select::pick(d, &space, Vec2::new(p[0], p[1]), ap) {
|
||||
match crate::select::pick_in(d, &space, s.viewport_frozen(), Vec2::new(p[0], p[1]), ap) {
|
||||
Some(h) => Ok(Value::list(vec![Value::Ename(h), Value::point(&p)])),
|
||||
None => Err("Missed, try again.".into()),
|
||||
}
|
||||
|
||||
@@ -102,6 +102,10 @@ pub struct Prompt {
|
||||
/// the routine writes, so it cannot be read for the word "Select" (#1598).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub picks_one: bool,
|
||||
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
|
||||
/// block's name is that block, not a keyword read from its Latin keys.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub takes_block: bool,
|
||||
}
|
||||
|
||||
/// Parse `@distance<angle` (relative polar), returning `(distance, angle in radians)`.
|
||||
@@ -136,6 +140,11 @@ impl Prompt {
|
||||
self.picker = Some(p);
|
||||
self
|
||||
}
|
||||
/// Takes a block's name besides its keywords (the `takes_block` field).
|
||||
pub fn takes_block(mut self) -> Self {
|
||||
self.takes_block = true;
|
||||
self
|
||||
}
|
||||
pub fn kw(mut self, k: &[&str]) -> Self {
|
||||
self.keywords = k.iter().map(ToString::to_string).collect();
|
||||
self
|
||||
@@ -215,6 +224,24 @@ impl Prompt {
|
||||
return None;
|
||||
}
|
||||
let tl = t.to_ascii_lowercase();
|
||||
// A keyword typed with the Greek keyboard layout active (ΘΝΔΟ for Undo) is its Latin keys, unless
|
||||
// the prompt offers that spelling itself (a Greek keyword in a LISP program's list): its word
|
||||
// or a prefix of it as typed (ΘΝ for ΘΝΔΟ, not UN for Undo) is read before the Latin keys.
|
||||
if let Some(latin) = crate::keyboard::latin_keys(t) {
|
||||
// Greek letters have case, accents and a final sigma, which the ASCII-only folding above does not see.
|
||||
let typed = crate::keyboard::greek_fold(t).unwrap_or_else(|| latin.clone());
|
||||
let greek = || self.keywords.iter().filter_map(|k| crate::keyboard::greek_fold(k).map(|fold| (k, fold)));
|
||||
return greek()
|
||||
.find(|(_, k)| *k == typed)
|
||||
.or_else(|| greek().find(|(_, k)| k.starts_with(&typed)))
|
||||
.map(|(k, _)| k.clone())
|
||||
.or_else(|| self.match_latin_keyword(&latin));
|
||||
}
|
||||
self.match_latin_keyword(&tl)
|
||||
}
|
||||
|
||||
/// [`Prompt::match_keyword`] for text already read as Latin letters, in lower case.
|
||||
fn match_latin_keyword(&self, tl: &str) -> Option<String> {
|
||||
let keys = self.keywords.iter().map(|k| {
|
||||
let shortcut: String = k.chars().filter(|c| c.is_ascii_uppercase() || c.is_ascii_digit()).collect::<String>().to_ascii_lowercase();
|
||||
let shortcut =
|
||||
@@ -227,8 +254,8 @@ impl Prompt {
|
||||
// CHPROP: "Ambiguous response, please clarify..."), `LTS` is ltScale.
|
||||
let past_capitals = |k: &str| k.char_indices().rfind(|(_, c)| c.is_ascii_uppercase() || c.is_ascii_digit()).map_or(1, |(i, _)| i + 1);
|
||||
keys.clone()
|
||||
.find(|(_, kl, sc)| tl == *kl || tl == *sc)
|
||||
.or_else(|| keys.clone().find(|(k, kl, _)| tl.len() >= past_capitals(k) && kl.starts_with(&tl)))
|
||||
.find(|(_, kl, sc)| tl == kl.as_str() || tl == sc.as_str())
|
||||
.or_else(|| keys.clone().find(|(k, kl, _)| tl.len() >= past_capitals(k) && kl.starts_with(tl)))
|
||||
.map(|(k, _, _)| k.clone())
|
||||
}
|
||||
}
|
||||
@@ -394,6 +421,29 @@ mod tests {
|
||||
assert_eq!(parse_point("1,2,3,4", last), None);
|
||||
}
|
||||
|
||||
/// A keyword the prompt offers in Greek is matched as spelled (any case, accent or final sigma,
|
||||
/// or a prefix) before the Latin reading of the same keys; without one, the keys answer the
|
||||
/// Latin keyword.
|
||||
#[test]
|
||||
fn a_greek_keyword_is_matched_as_spelled_before_its_latin_reading() {
|
||||
// ΘΝΔΟ is the keys U-N-D-O, so it answers Undo, unless the prompt offers the Greek word itself
|
||||
// (a LISP program's keyword list).
|
||||
let both = Prompt::new("", Accept::TEXT).kw(&["Undo", "ΘΝΔΟ"]);
|
||||
assert_eq!(both.match_keyword("ΘΝΔΟ").as_deref(), Some("ΘΝΔΟ"));
|
||||
assert_eq!(both.match_keyword("θνδο").as_deref(), Some("ΘΝΔΟ"), "Greek case is folded like Latin case");
|
||||
assert_eq!(both.match_keyword("Undo").as_deref(), Some("Undo"));
|
||||
// A prefix of the Greek word as typed (ΘΝ) is that keyword, not the Latin prefix UN of Undo.
|
||||
assert_eq!(both.match_keyword("ΘΝ").as_deref(), Some("ΘΝΔΟ"));
|
||||
assert_eq!(both.match_keyword("θν").as_deref(), Some("ΘΝΔΟ"), "in either case");
|
||||
assert_eq!(both.match_keyword("θνδό").as_deref(), Some("ΘΝΔΟ"), "with an accent");
|
||||
let sigma = Prompt::new("", Accept::TEXT).kw(&["Last", "ΛΑΣΤ"]);
|
||||
assert_eq!(sigma.match_keyword("λας").as_deref(), Some("ΛΑΣΤ"), "a final sigma folds too");
|
||||
let latin = Prompt::new("", Accept::TEXT).kw(&["Undo"]);
|
||||
assert_eq!(latin.match_keyword("ΘΝ").as_deref(), Some("Undo"));
|
||||
assert_eq!(latin.match_keyword("ΘΝΔΟ").as_deref(), Some("Undo"));
|
||||
assert_eq!(latin.match_keyword("Θ").as_deref(), Some("Undo"), "a Greek-layout shortcut still works");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords() {
|
||||
let p = Prompt::new("Specify next point", Accept::POINT).kw(&["Undo", "Close"]);
|
||||
|
||||
+101
-21
@@ -152,8 +152,28 @@ fn in_box(pts: impl Iterator<Item = Vec2>, angle: f64, p: Vec2) -> bool {
|
||||
!b.is_empty() && b.contains(turn(p))
|
||||
}
|
||||
|
||||
fn selectable(d: &Drawing, e: &Entity) -> bool {
|
||||
d.is_visible(e)
|
||||
/// Whether `e` is on one of the layers in `frozen`: the layers frozen in a layout viewport, which
|
||||
/// does not draw their objects. The names are compared as the renderer compares them.
|
||||
pub(crate) fn on_frozen_layer(frozen: &[String], e: &Entity) -> bool {
|
||||
frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer))
|
||||
}
|
||||
|
||||
/// The last object of `store`, in draw order, that is not on one of the layers in `frozen`, the
|
||||
/// layers frozen in the layout viewport the selection is made through: what the Last option
|
||||
/// takes there. With no such layers it is the last object, whether the drawing shows it or not.
|
||||
pub(crate) fn last_in(store: &cadcraft_doc::EntityStore, frozen: &[String]) -> Option<Handle> {
|
||||
if frozen.is_empty() {
|
||||
return store.last().map(|e| e.handle);
|
||||
}
|
||||
store.iter().filter(|e| !on_frozen_layer(frozen, e)).last().map(|e| e.handle)
|
||||
}
|
||||
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
|
||||
/// on one of the layers in `frozen`, the layers frozen in the layout viewport the selection is
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else). A viewport shows
|
||||
/// model space, so `frozen` goes with a selection in model space only.
|
||||
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e)
|
||||
}
|
||||
|
||||
/// Entities to test, in the order to test them, each with its bounds when already known.
|
||||
@@ -196,15 +216,28 @@ pub(crate) fn candidates<'a>(
|
||||
/// the nearest, as AutoCAD 2024 picks (two objects under the pickbox: the one drawn later is
|
||||
/// picked, and DRAWORDER changes which).
|
||||
pub fn pick(d: &Drawing, space: &Space, p: Vec2, aperture: f64) -> Option<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
pick_with(d, space, &ix, p, aperture)
|
||||
pick_in(d, space, &[], p, aperture)
|
||||
}
|
||||
|
||||
pub(crate) fn pick_with(d: &Drawing, space: &Space, ix: &Option<std::sync::Arc<SpatialIndex>>, p: Vec2, aperture: f64) -> Option<Handle> {
|
||||
/// [`pick`] through a layout viewport: the objects on the layers in `frozen`, the layers frozen
|
||||
/// in that viewport, are not drawn there and are not picked.
|
||||
pub fn pick_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, aperture: f64) -> Option<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
pick_with(d, space, &ix, frozen, p, aperture)
|
||||
}
|
||||
|
||||
pub(crate) fn pick_with(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<SpatialIndex>>,
|
||||
frozen: &[String],
|
||||
p: Vec2,
|
||||
aperture: f64,
|
||||
) -> Option<Handle> {
|
||||
let probe = Bounds2::new(p, p).expand(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) {
|
||||
if !selectable(d, e, frozen) {
|
||||
continue;
|
||||
}
|
||||
let infinite = is_infinite(e);
|
||||
@@ -221,11 +254,16 @@ pub(crate) fn pick_with(d: &Drawing, space: &Space, ix: &Option<std::sync::Arc<S
|
||||
/// Every entity within `aperture` of `p`, topmost first (so the first is what [`pick`] chooses):
|
||||
/// the objects selection cycling lists.
|
||||
pub fn pick_all(d: &Drawing, space: &Space, p: Vec2, aperture: f64) -> Vec<Handle> {
|
||||
pick_all_in(d, space, &[], p, aperture)
|
||||
}
|
||||
|
||||
/// [`pick_all`] through a layout viewport that freezes the layers in `frozen` ([`pick_in`]).
|
||||
pub fn pick_all_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, aperture: f64) -> Vec<Handle> {
|
||||
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() };
|
||||
cands
|
||||
.filter(|(e, known)| selectable(d, e) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe)))
|
||||
.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)
|
||||
.map(|(e, _)| e.handle)
|
||||
.collect()
|
||||
@@ -253,14 +291,27 @@ fn seg_hits_box(a: Vec2, b: Vec2, bx: &Bounds2) -> bool {
|
||||
|
||||
/// Window selection (entirely inside) or crossing selection (inside or touching).
|
||||
pub fn select_window(d: &Drawing, space: &Space, bx: Bounds2, crossing: bool) -> Vec<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
select_window_with(d, space, &ix, bx, crossing)
|
||||
select_window_in(d, space, &[], bx, crossing)
|
||||
}
|
||||
|
||||
pub(crate) fn select_window_with(d: &Drawing, space: &Space, ix: &Option<std::sync::Arc<SpatialIndex>>, bx: Bounds2, crossing: bool) -> Vec<Handle> {
|
||||
/// [`select_window`] through a layout viewport: the objects on the layers in `frozen`, the layers
|
||||
/// frozen in that viewport, are not drawn there and are not selected.
|
||||
pub fn select_window_in(d: &Drawing, space: &Space, frozen: &[String], bx: Bounds2, crossing: bool) -> Vec<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
select_window_with(d, space, &ix, frozen, bx, crossing)
|
||||
}
|
||||
|
||||
pub(crate) fn select_window_with(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<SpatialIndex>>,
|
||||
frozen: &[String],
|
||||
bx: Bounds2,
|
||||
crossing: bool,
|
||||
) -> Vec<Handle> {
|
||||
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) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
|
||||
cands.filter(|(e, known)| selectable(d, e, frozen) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
|
||||
}
|
||||
|
||||
/// The tessellation tolerance window and crossing tests use for a box.
|
||||
@@ -306,11 +357,23 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bo
|
||||
|
||||
/// Fence selection: entities crossed by the fence polyline.
|
||||
pub fn select_fence(d: &Drawing, space: &Space, fence: &[Vec2]) -> Vec<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
select_fence_with(d, space, &ix, fence)
|
||||
select_fence_in(d, space, &[], fence)
|
||||
}
|
||||
|
||||
pub(crate) fn select_fence_with(d: &Drawing, space: &Space, ix: &Option<std::sync::Arc<SpatialIndex>>, fence: &[Vec2]) -> Vec<Handle> {
|
||||
/// [`select_fence`] through a layout viewport that freezes the layers in `frozen`
|
||||
/// ([`select_window_in`]).
|
||||
pub fn select_fence_in(d: &Drawing, space: &Space, frozen: &[String], fence: &[Vec2]) -> Vec<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
select_fence_with(d, space, &ix, frozen, fence)
|
||||
}
|
||||
|
||||
pub(crate) fn select_fence_with(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<SpatialIndex>>,
|
||||
frozen: &[String],
|
||||
fence: &[Vec2],
|
||||
) -> Vec<Handle> {
|
||||
let fb = Bounds2::from_points(fence.iter().copied());
|
||||
let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0;
|
||||
let probe = fb.expand(tol);
|
||||
@@ -318,7 +381,7 @@ pub(crate) fn select_fence_with(d: &Drawing, space: &Space, ix: &Option<std::syn
|
||||
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) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) {
|
||||
if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) {
|
||||
continue;
|
||||
}
|
||||
let polys = hit_polylines(d, e, tol);
|
||||
@@ -339,6 +402,12 @@ pub(crate) fn select_fence_with(d: &Drawing, space: &Space, ix: &Option<std::syn
|
||||
/// Window polygon selection (entities entirely inside `poly`) or crossing polygon selection
|
||||
/// (inside or crossing its edges). The polygon closes back to its first point.
|
||||
pub fn select_polygon(d: &Drawing, space: &Space, poly: &[Vec2], crossing: bool) -> Vec<Handle> {
|
||||
select_polygon_in(d, space, &[], poly, crossing)
|
||||
}
|
||||
|
||||
/// [`select_polygon`] through a layout viewport that freezes the layers in `frozen`
|
||||
/// ([`select_window_in`]).
|
||||
pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[Vec2], crossing: bool) -> Vec<Handle> {
|
||||
let (Some(first), true) = (poly.first(), poly.len() >= 3) else { return Vec::new() };
|
||||
let ix = spatial::index(d, space);
|
||||
let pb = Bounds2::from_points(poly.iter().copied());
|
||||
@@ -349,7 +418,7 @@ pub fn select_polygon(d: &Drawing, space: &Space, poly: &[Vec2], crossing: bool)
|
||||
let mut out = Vec::new();
|
||||
for (e, known) in cands {
|
||||
let infinite = is_infinite(e);
|
||||
if !selectable(d, e) || (infinite && !crossing) {
|
||||
if !selectable(d, e, frozen) || (infinite && !crossing) {
|
||||
continue;
|
||||
}
|
||||
let eb = bounds_of(d, e, known);
|
||||
@@ -378,9 +447,15 @@ pub fn select_polygon(d: &Drawing, space: &Space, poly: &[Vec2], crossing: bool)
|
||||
/// The visible objects in `space` of the group called `name` (any case), or `None` when the
|
||||
/// drawing has no such group.
|
||||
pub fn select_group(d: &Drawing, space: &Space, name: &str) -> Option<Vec<Handle>> {
|
||||
select_group_in(d, space, &[], name)
|
||||
}
|
||||
|
||||
/// [`select_group`] through a layout viewport that freezes the layers in `frozen`: the group's
|
||||
/// objects on those layers are left out.
|
||||
pub fn select_group_in(d: &Drawing, space: &Space, frozen: &[String], name: &str) -> Option<Vec<Handle>> {
|
||||
let g = d.groups.iter().find(|g| g.name.eq_ignore_ascii_case(name.trim()))?;
|
||||
let store = d.space(space)?;
|
||||
Some(g.members.iter().copied().filter(|h| store.get(*h).is_some_and(|e| d.is_visible(e))).collect())
|
||||
Some(g.members.iter().copied().filter(|h| store.get(*h).is_some_and(|e| selectable(d, e, frozen))).collect())
|
||||
}
|
||||
|
||||
/// A selection mode typed at "Select objects", collecting its points before it selects.
|
||||
@@ -454,14 +529,19 @@ impl SelectMode {
|
||||
}
|
||||
/// The objects the mode selects, or `None` while it has too few points.
|
||||
pub fn select(&self, d: &Drawing, space: &Space) -> Option<Vec<Handle>> {
|
||||
self.select_in(d, space, &[])
|
||||
}
|
||||
/// [`SelectMode::select`] through a layout viewport: the objects on the layers in `frozen`,
|
||||
/// the layers frozen in that viewport, are not drawn there and are not selected.
|
||||
pub fn select_in(&self, d: &Drawing, space: &Space, frozen: &[String]) -> Option<Vec<Handle>> {
|
||||
match (self.kind, self.pts.as_slice()) {
|
||||
(SelectKind::Window | SelectKind::Crossing, [a, b, ..]) => {
|
||||
Some(select_window(d, space, Bounds2::new(*a, *b), self.kind == SelectKind::Crossing))
|
||||
Some(select_window_in(d, space, frozen, Bounds2::new(*a, *b), self.kind == SelectKind::Crossing))
|
||||
}
|
||||
(SelectKind::Box, [a, b, ..]) => Some(select_window(d, space, Bounds2::new(*a, *b), b.x < a.x)),
|
||||
(SelectKind::Fence, pts) if pts.len() >= 2 => Some(select_fence(d, space, pts)),
|
||||
(SelectKind::Box, [a, b, ..]) => Some(select_window_in(d, space, frozen, Bounds2::new(*a, *b), b.x < a.x)),
|
||||
(SelectKind::Fence, pts) if pts.len() >= 2 => Some(select_fence_in(d, space, frozen, pts)),
|
||||
(SelectKind::WPolygon | SelectKind::CPolygon, pts) if pts.len() >= 3 => {
|
||||
Some(select_polygon(d, space, pts, self.kind == SelectKind::CPolygon))
|
||||
Some(select_polygon_in(d, space, frozen, pts, self.kind == SelectKind::CPolygon))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -116,9 +116,26 @@ impl Session {
|
||||
};
|
||||
}
|
||||
// At "Select objects" prompts the selection modes (Previous, Last, ALL) win over a command
|
||||
// keyword sharing the letter (HATCH's "picK internal point" against `P`).
|
||||
let selection_mode = prompt.accept.select
|
||||
&& matches!(tt.strip_prefix('_').unwrap_or(tt).to_ascii_lowercase().as_str(), "all" | "l" | "last" | "p" | "previous");
|
||||
// keyword sharing the letter (HATCH's "picK internal point" against `P`). A word typed with
|
||||
// the Greek keyboard layout active is read by its keys there too: Λ is Last at COUNT's prompt,
|
||||
// not List.
|
||||
let selection_mode = prompt.accept.select && {
|
||||
let word = tt.strip_prefix('_').unwrap_or(tt);
|
||||
let keys = crate::keyboard::latin_keys(word).unwrap_or_else(|| word.to_ascii_lowercase());
|
||||
matches!(keys.as_str(), "all" | "l" | "last" | "p" | "previous")
|
||||
};
|
||||
// A Greek word that is an existing name at a prompt that takes one is that name, in any case:
|
||||
// ΣΟΛΙΔ is also the keys of Solid.
|
||||
let existing = if matches!(prompt.picker, Some(crate::Picker::HatchPattern(_))) {
|
||||
crate::keyboard::greek_fold(tt).and_then(|_| cmd::hatch::pattern_named(tt))
|
||||
} else if prompt.takes_block {
|
||||
self.greek_block_name(tt)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = existing {
|
||||
return self.input(Input::Text(name));
|
||||
}
|
||||
// A leading underscore asks for a keyword by its English name, whatever the interface
|
||||
// language (`_M`, `_Yes`): scripts and LISP routines write them that way. (Snap
|
||||
// overrides such as `_cen` were taken above.)
|
||||
|
||||
@@ -8,6 +8,39 @@ use super::{
|
||||
impl Session {
|
||||
// ---------------- interactive commands ----------------
|
||||
|
||||
/// Whether `name`, as typed, is a command, an alias or a LISP command: the lookups
|
||||
/// [`Session::start`] dispatches by, so only ASCII is lower-cased and a Greek alias stays as stored.
|
||||
fn names_a_command(&self, name: &str) -> bool {
|
||||
let lower = name.trim_start_matches(['_', '.', '-']).to_ascii_lowercase();
|
||||
let dashed = name.trim_start_matches(['_', '.']);
|
||||
find_command(&cmd::resolve_alias(dashed)).is_some()
|
||||
|| find_command(&cmd::resolve_alias(&lower)).is_some()
|
||||
|| self.lisp_command(&lower).is_some()
|
||||
}
|
||||
|
||||
/// The alias or LISP command that is the Greek word `name` in another case or accent (λινε for
|
||||
/// c:ΛΙΝΕ): those lookups fold ASCII only.
|
||||
fn greek_command_name(&self, name: &str) -> Option<String> {
|
||||
let bare = name.trim_start_matches(['_', '.', '-']);
|
||||
let same = crate::keyboard::same_greek_word_as(bare)?;
|
||||
let lisp = || self.lisp_commands().into_iter().find(|c| same(c) && self.lisp_command(c).is_some());
|
||||
cmd::file::greek_alias(bare).or_else(lisp)
|
||||
}
|
||||
|
||||
/// Whether the Greek word `name` is a command of its own, which [`Session::start`] runs instead
|
||||
/// of the Latin name its keys type.
|
||||
pub fn greek_word_is_a_command(&self, name: &str) -> bool {
|
||||
self.names_a_command(name) || self.greek_command_name(name).is_some()
|
||||
}
|
||||
|
||||
/// The existing block that is the Greek word `word`: as spelled, else in another case or accent
|
||||
/// (μ for Μ).
|
||||
pub(super) fn greek_block_name(&self, word: &str) -> Option<String> {
|
||||
let same = crate::keyboard::same_greek_word_as(word)?;
|
||||
let blocks = &self.doc().ok()?.blocks;
|
||||
blocks.keys().find(|k| *k == word).or_else(|| blocks.keys().find(|k| same(k))).cloned()
|
||||
}
|
||||
|
||||
/// Start a command by name or alias as if typed at the command line.
|
||||
pub fn start(&mut self, name: &str) -> Result<()> {
|
||||
self.last_polar = None;
|
||||
@@ -17,6 +50,12 @@ impl Session {
|
||||
Some(n) => (true, n),
|
||||
None => (false, name),
|
||||
};
|
||||
// A name typed with the Greek keyboard layout active (ΛΙΝΕ for LINE) is the Latin name's keys,
|
||||
// unless it is a command, alias or LISP function of its own, in any case or accent.
|
||||
let typed = name;
|
||||
let latin =
|
||||
crate::keyboard::latin_keys(name).filter(|_| !self.names_a_command(name)).map(|latin| self.greek_command_name(name).unwrap_or(latin));
|
||||
let name = latin.as_deref().unwrap_or(name);
|
||||
let lower = name.trim_start_matches(['_', '.', '-']).to_ascii_lowercase();
|
||||
// A command-line form with an id of its own (-ATTEDIT) is not the command it prefixes.
|
||||
let dashed = cmd::resolve_alias(&name.trim_start_matches(['_', '.']).to_ascii_lowercase());
|
||||
@@ -37,7 +76,7 @@ impl Session {
|
||||
self.start(if transparent { "'setvar" } else { "setvar" })?;
|
||||
return self.input(Input::Text(var));
|
||||
}
|
||||
return Err(EngineError::UnknownCommand(name.to_string()));
|
||||
return Err(EngineError::UnknownCommand(typed.to_string()));
|
||||
};
|
||||
if transparent && spec.transparent && self.running.is_some() {
|
||||
// Transparent commands (zoom, pan…) run without cancelling the active one.
|
||||
@@ -175,17 +214,33 @@ impl Session {
|
||||
Input::Text(t) => Input::Text(t.trim().strip_prefix('_').map(str::to_string).unwrap_or(t)),
|
||||
other => other,
|
||||
};
|
||||
if let Input::Text(t) | Input::Keyword(t) = &input
|
||||
&& let Some(m) = select::SelectMode::from_keyword(t)
|
||||
// A selection word typed with the Greek keyboard layout active (ΑΛΛ for ALL) is looked up as its
|
||||
// Latin keys. Only the lookup is: text that is no selection word (a block name at BEDIT's prompt,
|
||||
// which also takes a selection) reaches the command as typed. The name of an existing block at
|
||||
// a prompt that takes a name reaches it as stored, in whatever case it was typed: a block
|
||||
// called Μ is that block there, not Multiple.
|
||||
let block = match &input {
|
||||
Input::Text(t) if prompt.accept.text => self.greek_block_name(t.trim()),
|
||||
_ => None,
|
||||
};
|
||||
let is_block = block.is_some();
|
||||
let input = block.map_or(input, Input::Text);
|
||||
let word = match &input {
|
||||
Input::Text(t) => Some(crate::keyboard::latin_keys(t.trim()).filter(|_| !is_block).unwrap_or_else(|| t.clone())),
|
||||
Input::Keyword(k) => Some(k.clone()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(w) = &word
|
||||
&& let Some(m) = select::SelectMode::from_keyword(w)
|
||||
{
|
||||
self.pending_window = None;
|
||||
self.select_mode = Some(m);
|
||||
return Ok(None);
|
||||
}
|
||||
if let Input::Text(t) | Input::Keyword(t) = &input
|
||||
&& !prompt.keywords.iter().any(|k| k.eq_ignore_ascii_case(t.trim()))
|
||||
if let Some(w) = &word
|
||||
&& !prompt.keywords.iter().any(|k| k.eq_ignore_ascii_case(w.trim()))
|
||||
{
|
||||
match t.trim().to_ascii_lowercase().as_str() {
|
||||
match w.trim().to_ascii_lowercase().as_str() {
|
||||
"si" | "single" => {
|
||||
self.select_single = true;
|
||||
return Ok(None);
|
||||
@@ -202,10 +257,10 @@ impl Session {
|
||||
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
|
||||
if let Some(pw) = self.pending_window.take() {
|
||||
let crossing = self.window_is_crossing(pw.corner, p);
|
||||
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
|
||||
let hs = select::select_window_in(self.doc()?, &space, self.viewport_frozen(), Bounds2::new(pw.corner, p), crossing);
|
||||
return Ok(Some(Input::Pick(cmd::groups::expand(self, hs))));
|
||||
}
|
||||
match select::pick(self.doc()?, &space, p, ap) {
|
||||
match select::pick_in(self.doc()?, &space, self.viewport_frozen(), p, ap) {
|
||||
Some(h) => Ok(Some(Input::Pick(cmd::groups::expand(self, vec![h])))),
|
||||
None => {
|
||||
self.pending_window = Some(PendingWindow { corner: p, during_command: true });
|
||||
@@ -213,14 +268,18 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
Input::Text(ref t) | Input::Keyword(ref t) => {
|
||||
let tl = t.trim().to_ascii_lowercase();
|
||||
Input::Text(_) | Input::Keyword(_) => {
|
||||
let tl = word.as_deref().unwrap_or_default().trim().to_ascii_lowercase();
|
||||
let d = self.doc()?;
|
||||
let store = d.space(&space);
|
||||
let frozen = self.viewport_frozen();
|
||||
let picked = match tl.as_str() {
|
||||
"all" => store.map(|s| s.iter().filter(|e| d.is_visible(e)).map(|e| e.handle).collect()),
|
||||
"l" | "last" => store.and_then(|s| s.last()).map(|e| vec![e.handle]),
|
||||
"p" | "previous" => Some(self.state()?.previous_selection.clone()),
|
||||
"all" => store.map(|s| s.iter().filter(|e| select::selectable(d, e, frozen)).map(|e| e.handle).collect()),
|
||||
"l" | "last" => store.and_then(|s| select::last_in(s, frozen)).map(|h| vec![h]),
|
||||
"p" | "previous" => {
|
||||
let st = self.state()?;
|
||||
Some(st.drawn_in_viewport(&st.previous_selection))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match picked {
|
||||
@@ -241,8 +300,9 @@ impl Session {
|
||||
fn select_mode_input(&mut self, input: Input) -> Result<Option<Input>> {
|
||||
let Some(mut mode) = self.select_mode.take() else { return Ok(Some(input)) };
|
||||
if mode.kind == select::SelectKind::Group {
|
||||
let space = self.space();
|
||||
return match input {
|
||||
Input::Text(name) | Input::Keyword(name) => match select::select_group(self.doc()?, &self.space(), &name) {
|
||||
Input::Text(name) | Input::Keyword(name) => match select::select_group_in(self.doc()?, &space, self.viewport_frozen(), &name) {
|
||||
Some(hs) => Ok(Some(Input::Pick(hs))),
|
||||
None => {
|
||||
self.echo(format!("No group named \"{}\".", name.trim()));
|
||||
@@ -262,14 +322,14 @@ impl Session {
|
||||
match input {
|
||||
Input::Point(p) => {
|
||||
if mode.push(p) {
|
||||
return Ok(mode.select(self.doc()?, &self.space()).map(Input::Pick));
|
||||
return Ok(mode.select_in(self.doc()?, &self.space(), self.viewport_frozen()).map(Input::Pick));
|
||||
}
|
||||
}
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
mode.pts.pop();
|
||||
}
|
||||
// Enter ends a fence or polygon; with too few points the mode is dropped.
|
||||
Input::Enter => return Ok(mode.select(self.doc()?, &self.space()).map(Input::Pick)),
|
||||
Input::Enter => return Ok(mode.select_in(self.doc()?, &self.space(), self.viewport_frozen()).map(Input::Pick)),
|
||||
Input::Cancel | Input::Pick(_) => return Ok(Some(input)),
|
||||
_ => self.echo("Invalid point."),
|
||||
}
|
||||
|
||||
@@ -32,9 +32,9 @@ impl Session {
|
||||
let pickadd = self.settings.pickadd;
|
||||
if let Some(pw) = self.pending_window.take() {
|
||||
let crossing = self.window_is_crossing(pw.corner, p);
|
||||
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
|
||||
let hs = select::select_window_in(self.doc()?, &space, self.viewport_frozen(), Bounds2::new(pw.corner, p), crossing);
|
||||
let hs = cmd::groups::expand(self, hs);
|
||||
let mut sel = if pickadd || shift { self.selection() } else { Vec::new() };
|
||||
let mut sel = if pickadd || shift { self.stored_selection() } else { Vec::new() };
|
||||
if shift && pickadd {
|
||||
sel.retain(|h| !hs.contains(h));
|
||||
} else {
|
||||
@@ -44,7 +44,7 @@ impl Session {
|
||||
return Ok(());
|
||||
}
|
||||
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
|
||||
match select::pick(self.doc()?, &space, p, ap) {
|
||||
match select::pick_in(self.doc()?, &space, self.viewport_frozen(), p, ap) {
|
||||
Some(h) => self.idle_pick(h, shift),
|
||||
None => self.pending_window = Some(PendingWindow { corner: p, during_command: false }),
|
||||
}
|
||||
@@ -56,7 +56,7 @@ impl Session {
|
||||
let pickadd = self.settings.pickadd;
|
||||
// With group selection the object's selectable groups come (or go) with it.
|
||||
let hs = cmd::groups::expand(self, vec![h]);
|
||||
let mut sel = if pickadd || shift { self.selection() } else { Vec::new() };
|
||||
let mut sel = if pickadd || shift { self.stored_selection() } else { Vec::new() };
|
||||
let had = sel.contains(&h);
|
||||
if shift && (pickadd || had) {
|
||||
sel.retain(|x| !hs.contains(x));
|
||||
@@ -93,7 +93,7 @@ impl Session {
|
||||
return Vec::new();
|
||||
}
|
||||
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
|
||||
self.doc().map(|d| select::pick_all(d, &self.space(), p, ap)).unwrap_or_default()
|
||||
self.doc().map(|d| select::pick_all_in(d, &self.space(), self.viewport_frozen(), p, ap)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether selection cycling marks `p` with its badge (SELECTIONCYCLING 1 or 2): overlapping
|
||||
@@ -155,7 +155,8 @@ impl Session {
|
||||
|
||||
/// The object a prompt picking one object finds at `p` in `space`: the one named for that
|
||||
/// point ([`Session::input_object`]), which is none when it lies in another space, else the
|
||||
/// object under `p` within `aperture`.
|
||||
/// object under `p` within `aperture`. Inside an MSPACE viewport a pick in model space finds
|
||||
/// what that viewport draws: not the objects on the layers frozen in it.
|
||||
pub fn pick_object(&self, space: &Space, p: Vec2, aperture: f64) -> Result<Option<Handle>> {
|
||||
let d = self.doc()?;
|
||||
if let Some((h, q)) = self.pick_hint
|
||||
@@ -163,7 +164,9 @@ impl Session {
|
||||
{
|
||||
return Ok((d.space_of(h).as_ref() == Some(space)).then_some(h));
|
||||
}
|
||||
Ok(select::pick(d, space, p, aperture))
|
||||
// The viewport shows model space only: its frozen layers hide nothing on the sheet.
|
||||
let frozen = if *space == Space::Model { self.viewport_frozen() } else { &[] };
|
||||
Ok(select::pick_in(d, space, frozen, p, aperture))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -424,8 +424,8 @@ mod tests {
|
||||
for k in 0..400 {
|
||||
let p = Vec2::new(r.r(-5.0, 105.0), r.r(-5.0, 105.0));
|
||||
let ap = [0.05, 0.3, 1.5][k % 3];
|
||||
let a = select::pick_with(&d, &Space::Model, &ix, p, ap);
|
||||
let b = select::pick_with(&d, &Space::Model, &None, p, ap);
|
||||
let a = select::pick_with(&d, &Space::Model, &ix, &[], p, ap);
|
||||
let b = select::pick_with(&d, &Space::Model, &None, &[], p, ap);
|
||||
assert_eq!(a, b, "seed {seed} p {p:?} ap {ap}");
|
||||
hits += usize::from(a.is_some());
|
||||
}
|
||||
@@ -444,12 +444,15 @@ mod tests {
|
||||
let b = a + Vec2::new(r.r(-40.0, 40.0), r.r(-40.0, 40.0));
|
||||
let bx = Bounds2::new(a, b);
|
||||
for crossing in [false, true] {
|
||||
let x = select::select_window_with(&d, &Space::Model, &ix, bx, crossing);
|
||||
let y = select::select_window_with(&d, &Space::Model, &None, bx, crossing);
|
||||
let x = select::select_window_with(&d, &Space::Model, &ix, &[], bx, crossing);
|
||||
let y = select::select_window_with(&d, &Space::Model, &None, &[], bx, crossing);
|
||||
assert_eq!(x, y, "seed {seed} box {bx:?} crossing {crossing}");
|
||||
}
|
||||
let fence: Vec<Vec2> = (0..(2 + k % 3)).map(|_| Vec2::new(r.r(0.0, 100.0), r.r(0.0, 100.0))).collect();
|
||||
assert_eq!(select::select_fence_with(&d, &Space::Model, &ix, &fence), select::select_fence_with(&d, &Space::Model, &None, &fence));
|
||||
assert_eq!(
|
||||
select::select_fence_with(&d, &Space::Model, &ix, &[], &fence),
|
||||
select::select_fence_with(&d, &Space::Model, &None, &[], &fence)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -484,10 +487,13 @@ mod tests {
|
||||
for (p, ap) in
|
||||
[(Vec2::new(f64::NAN, 1.0), 1.0), (Vec2::new(1.0, 1.0), f64::NAN), (Vec2::new(f64::INFINITY, 0.0), 1.0), (Vec2::new(50.0, 50.0), 1e300)]
|
||||
{
|
||||
assert_eq!(select::pick_with(&d, &Space::Model, &ix, p, ap), select::pick_with(&d, &Space::Model, &None, p, ap));
|
||||
assert_eq!(select::pick_with(&d, &Space::Model, &ix, &[], p, ap), select::pick_with(&d, &Space::Model, &None, &[], p, ap));
|
||||
}
|
||||
let bx = Bounds2 { min: Vec2::new(f64::NEG_INFINITY, 0.0), max: Vec2::new(f64::INFINITY, 50.0) };
|
||||
assert_eq!(select::select_window_with(&d, &Space::Model, &ix, bx, true), select::select_window_with(&d, &Space::Model, &None, bx, true));
|
||||
assert_eq!(
|
||||
select::select_window_with(&d, &Space::Model, &ix, &[], bx, true),
|
||||
select::select_window_with(&d, &Space::Model, &None, &[], bx, true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1551,3 +1551,13 @@ fn setvar_rejects_non_finite_text_for_real_variables() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_tools_keeps_compatible_command_ids() {
|
||||
assert_eq!(crate::cmd::resolve_alias("-blockreplace"), "blockreplace");
|
||||
for id in ["blockreplace", "burst", "breakline", "mocoro", "txt2mtxt"] {
|
||||
let command = crate::cmd::find_command(id).expect("existing command id");
|
||||
assert!(command.menu.contains(&"Additional Tools"), "{id}: {:?}", command.menu);
|
||||
assert!(!command.menu.contains(&"Express Tools"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
//! File and automation inputs retain CADCraft's accepted Base64 forms.
|
||||
use cadcraft_engine::cmd::file::{base64_decode, base64_encode};
|
||||
|
||||
#[test]
|
||||
fn legacy_inputs_and_standard_outputs_survive_the_shared_cutover() {
|
||||
for bytes in [&b""[..], b"f", b"fo", b"foo", b"foobar", &[0, 255, 127]] {
|
||||
assert_eq!(base64_decode(&base64_encode(bytes)).as_deref(), Some(bytes));
|
||||
}
|
||||
assert_eq!(base64_decode("+_8=").as_deref(), Some(&[251, 255][..]));
|
||||
assert_eq!(base64_decode("Z=m 9\nv\r").as_deref(), Some(&b"foo"[..]));
|
||||
assert_eq!(base64_decode("A").as_deref(), Some(&b""[..]));
|
||||
assert!(base64_decode("Zm9v\t").is_none());
|
||||
assert!(base64_decode("Zm9v!").is_none());
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! A word typed with the Greek keyboard layout that is an alias of its own (ALIASEDIT) is that
|
||||
//! alias, not the Latin name its keys type. The aliases are process-wide, so this file keeps to
|
||||
//! one test at a time.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::json;
|
||||
|
||||
/// The alias store is process-wide: each test holds this while it changes the aliases.
|
||||
static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// A Greek word the user made an alias runs the alias's command, not the command its keys type.
|
||||
#[test]
|
||||
fn a_greek_alias_starts_its_command_not_the_latin_keys_command() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
// ΛΙΝΕ types LINE, but the user made it an alias of CIRCLE: aliases are stored as typed (only
|
||||
// ASCII is lower-cased), and the alias wins.
|
||||
s.execute("aliasedit", &json!({ "set": { "ΛΙΝΕ": "circle" } })).unwrap();
|
||||
let ran = s.script(
|
||||
"ΛΙΝΕ 0,0 5
|
||||
",
|
||||
);
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
ran.unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
let lines = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
assert_eq!((circles, lines), (1, 0), "the alias drew the circle, LINE was not started");
|
||||
}
|
||||
|
||||
/// The alias is found when it is typed in lower case or with an accent too.
|
||||
#[test]
|
||||
fn a_greek_alias_starts_its_command_in_any_case_or_accent() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
s.execute("aliasedit", &json!({ "set": { "ΛΙΝΕ": "circle" } })).unwrap();
|
||||
let ran: Vec<_> = ["λινε", "λίνε"].iter().map(|typed| s.script(&format!("{typed} 0,0 5\n"))).collect();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
assert!(ran.iter().all(Result::is_ok), "{ran:?}");
|
||||
let doc = s.doc().unwrap();
|
||||
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
let lines = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
assert_eq!((circles, lines), (2, 0), "the alias drew both circles, LINE was not started");
|
||||
}
|
||||
|
||||
/// 5 000 Greek aliases and a pasted word of a million letters that is none of them: looking it up
|
||||
/// costs the word's length once, not once for every alias.
|
||||
#[test]
|
||||
fn a_long_greek_word_is_folded_once_however_many_greek_aliases_there_are() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
let set: serde_json::Map<String, serde_json::Value> = (0..5_000).map(|i| (format!("ΞΞ{i}"), json!("line"))).collect();
|
||||
s.execute("aliasedit", &json!({ "set": set })).unwrap();
|
||||
let word = "Ω".repeat(1_000_000);
|
||||
let t = std::time::Instant::now();
|
||||
let started = s.start(&word);
|
||||
let took = t.elapsed();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
assert!(started.is_err(), "no command has those keys");
|
||||
assert!(took.as_secs() < 5, "{took:?}");
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! A command or keyword typed with the Greek keyboard layout active (ΛΙΝΕ for LINE, ΘΝΔΟ for
|
||||
//! Undo) works as its Latin name: the layout types each Greek letter on the Latin key it sounds
|
||||
//! like.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::json;
|
||||
|
||||
/// How many lines the drawing's model space holds.
|
||||
fn lines(s: &Session) -> usize {
|
||||
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
|
||||
}
|
||||
|
||||
/// ΛΙΝΕ draws a line like LINE, in lower case and with accents too; `;ΣΑΩΕ` starts QSAVE; a
|
||||
/// Greek word that is no command's keys is reported as typed.
|
||||
#[test]
|
||||
fn greek_layout_commands_start_like_the_latin_ones() {
|
||||
let mut s = Session::new();
|
||||
s.script("ΛΙΝΕ 0,0 10,0\n\n").unwrap();
|
||||
assert_eq!(lines(&s), 1, "{}", s.prompt_text());
|
||||
// Accents the layout's dead key adds are ignored; lower case works too.
|
||||
s.script("λίνε 0,5 10,5\n\n").unwrap();
|
||||
assert_eq!(lines(&s), 2);
|
||||
// The Q key types a semicolon: QSAVE is ";ΣΑΩΕ", which only starts the command (no file needed
|
||||
// here: it reports, it never fails as an unknown command).
|
||||
let err = s.start(";ΣΑΩΕ").map(|_| String::new()).unwrap_or_else(|e| e.to_string());
|
||||
assert!(!err.contains("unknown command"), "{err}");
|
||||
// A Greek word that is no command's keys is reported as typed, not as the Latin letters read from it.
|
||||
let err = s.start("ΧΥΖ").unwrap_err().to_string();
|
||||
assert!(err.contains("ΧΥΖ") && !err.contains("xyz"), "{err}");
|
||||
}
|
||||
|
||||
/// A LISP command with a Greek name runs as itself, not as the command its keys type.
|
||||
#[test]
|
||||
fn a_greek_lisp_command_runs_as_itself_not_as_the_latin_keys_command() {
|
||||
let mut s = Session::new();
|
||||
// ΛΙΝΕ types LINE, but the routine defines a command of that Greek name: it is the command typed.
|
||||
s.cmdline("(defun c:ΛΙΝΕ () (command \"_.CIRCLE\" '(0 0) 5) (princ))").unwrap();
|
||||
s.cmdline("ΛΙΝΕ").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let doc = s.doc().unwrap();
|
||||
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!((circles, lines(&s)), (1, 0), "the routine drew the circle, LINE was not started");
|
||||
}
|
||||
|
||||
/// ΑΛΛ at "Select objects" selects everything, as ALL does.
|
||||
#[test]
|
||||
fn greek_layout_selection_words_select_like_the_latin_ones() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [20, 0], "radius": 5 })).unwrap();
|
||||
// ΑΛΛ is the keys A-L-L: ALL at the "Select objects" prompt.
|
||||
s.script(
|
||||
"ERASE ΑΛΛ
|
||||
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(s.doc().unwrap().model.is_empty(), "ΑΛΛ selected nothing");
|
||||
}
|
||||
|
||||
/// Ν and Υ answer MIRROR's "Erase source objects?" as N and Y do.
|
||||
#[test]
|
||||
fn greek_layout_keywords_match_prompt_options() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
|
||||
s.script("ΜΙΡΡΟΡ ALL\n\n0,0 10,0\n").unwrap();
|
||||
// ... the last prompt asks whether to delete the sources: N (Greek layout: Ν) keeps them. Text
|
||||
// the prompt does not know keeps them too, so what Ν is read as is checked itself.
|
||||
let no = s.current_prompt().and_then(|p| p.match_keyword("Ν"));
|
||||
assert_eq!(no.as_deref(), Some("No"), "{}", s.prompt_text());
|
||||
s.script("Ν\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!(circles, 2, "the circle and its mirror image");
|
||||
|
||||
// Υ (the Y key) answers Yes, which erases the source: unmatched Greek text would count as No, so
|
||||
// only a recognised keyword gives this result.
|
||||
let mut yes = Session::new();
|
||||
yes.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
|
||||
yes.script(
|
||||
"ΜΙΡΡΟΡ ALL
|
||||
|
||||
0,0 10,0
|
||||
Υ
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(yes.running.is_none(), "{}", yes.prompt_text());
|
||||
let circles = yes.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!(circles, 1, "Υ answered Yes and the source was erased");
|
||||
}
|
||||
|
||||
/// A Greek block name typed at BEDIT's "block name or select" opens that block: it is not read
|
||||
/// as a selection word.
|
||||
#[test]
|
||||
fn a_greek_block_name_typed_at_a_name_or_select_prompt_reaches_the_command_as_typed() {
|
||||
let mut s = Session::new();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
s.execute("block", &json!({ "name": "ΠΟΡΤΑ", "base": [0, 0], "handles": [l] })).unwrap();
|
||||
// BEDIT asks for a block name or a selected reference. ΠΟΡΤΑ is also the keys P-O-R-T-A, which a
|
||||
// selection word would be read from, but no selection word is meant here: the name is typed as it is.
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline("ΠΟΡΤΑ").unwrap();
|
||||
let open = s.state().unwrap().block_editor().map(str::to_string);
|
||||
assert_eq!(open.as_deref(), Some("ΠΟΡΤΑ"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
/// Μ is the M key, Multiple at a selection prompt; once a block has that name, typing it at
|
||||
/// BEDIT opens the block.
|
||||
#[test]
|
||||
fn a_block_named_like_a_greek_selection_word_opens_at_a_name_or_select_prompt() {
|
||||
// The Greek capital Mu (U+039C) is the M key: Multiple at a selection prompt.
|
||||
let mu = "\u{39c}";
|
||||
let mut s = Session::new();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
// With no block of that name it stays the selection word, which BEDIT's prompt waits through.
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline(mu).unwrap();
|
||||
assert!(s.running.is_some(), "Multiple keeps the prompt: {}", s.prompt_text());
|
||||
assert!(s.state().unwrap().block_editor().is_none());
|
||||
s.cancel();
|
||||
// Once a block has that name, typing it opens that block.
|
||||
s.execute("block", &json!({ "name": mu, "base": [0, 0], "handles": [l] })).unwrap();
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline(mu).unwrap();
|
||||
let open = s.state().unwrap().block_editor().map(str::to_string);
|
||||
assert_eq!(open.as_deref(), Some(mu), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
/// ΣΟΛΙΔ is the keys of Solid at HATCH's pattern prompt; once a loaded pattern has that name,
|
||||
/// typing it in any case or accent chooses that pattern.
|
||||
#[test]
|
||||
fn a_loaded_pattern_named_like_the_greek_keys_of_solid_is_that_pattern_at_the_pattern_prompt() {
|
||||
// ΣΟΛΙΔ is the keys S-O-L-I-D: Solid at HATCH's pattern prompt, which takes no scale or angle.
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
|
||||
s.start("hatch").unwrap();
|
||||
s.input(cadcraft_engine::Input::Keyword("Pattern".into())).unwrap();
|
||||
s.cmdline("ΣΟΛΙΔ").unwrap();
|
||||
assert!(!s.prompt_text().contains("scale"), "Solid: {}", s.prompt_text());
|
||||
s.cancel();
|
||||
// A pattern file that defines a pattern of that name: typing the name chooses that pattern, which asks its scale.
|
||||
s.execute("hatch.patterns", &json!({ "text": "*ΣΟΛΙΔ, test\n0,0,0,0,1\n" })).unwrap();
|
||||
let asked = ["ΣΟΛΙΔ", "σολιδ", "σολίδ"].map(|typed| {
|
||||
s.start("hatch").unwrap();
|
||||
s.input(cadcraft_engine::Input::Keyword("Pattern".into())).unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let asked = s.prompt_text();
|
||||
s.cancel();
|
||||
asked
|
||||
});
|
||||
s.execute("hatch.patterns", &json!({ "clear": true })).unwrap();
|
||||
assert!(asked.iter().all(|a| a.contains("scale")), "the loaded pattern, in any spelling: {asked:?}");
|
||||
}
|
||||
|
||||
/// A LISP command with a Greek name runs when typed in upper case, lower case or with an accent.
|
||||
#[test]
|
||||
fn a_greek_lisp_command_runs_in_any_case_or_accent() {
|
||||
for typed in ["ΛΙΝΕ", "λινε", "λίνε"] {
|
||||
let mut s = Session::new();
|
||||
s.cmdline("(defun c:ΛΙΝΕ () (command \"_.CIRCLE\" '(0 0) 5) (princ))").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!((circles, lines(&s)), (1, 0), "{typed}: {}", s.prompt_text());
|
||||
}
|
||||
}
|
||||
|
||||
/// A block called Μ opens at BEDIT when its name is typed in either case.
|
||||
#[test]
|
||||
fn a_block_opens_in_any_case_or_accent_at_a_prompt_that_also_takes_a_selection() {
|
||||
for typed in ["\u{39c}", "\u{3bc}"] {
|
||||
let mut s = Session::new();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
s.execute("block", &json!({ "name": "\u{39c}", "base": [0, 0], "handles": [l] })).unwrap();
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let open = s.state().unwrap().block_editor().map(str::to_string);
|
||||
assert_eq!(open.as_deref(), Some("\u{39c}"), "{typed}: {}", s.prompt_text());
|
||||
}
|
||||
}
|
||||
|
||||
/// Σ is the S key, Select at BLOCKREPLACE; once a block has that name, typing it in either case
|
||||
/// names the block.
|
||||
#[test]
|
||||
fn a_block_named_like_the_keys_of_select_is_that_block_at_blockreplace() {
|
||||
let mut s = Session::new();
|
||||
// Σ is the S key: the Select option of BLOCKREPLACE, while no block has that name.
|
||||
s.start("BLOCKREPLACE").unwrap();
|
||||
s.cmdline("Σ").unwrap();
|
||||
assert!(s.prompt_text().contains("Select a block reference"), "{}", s.prompt_text());
|
||||
s.cancel();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
s.execute("block", &json!({ "name": "Σ", "base": [0, 0], "handles": [l] })).unwrap();
|
||||
s.execute("insert", &json!({ "name": "Σ", "at": [0, 0] })).unwrap();
|
||||
for typed in ["Σ", "σ"] {
|
||||
s.start("BLOCKREPLACE").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let asked = s.prompt_text();
|
||||
s.cancel();
|
||||
assert!(asked.contains("replacement block for Σ"), "{typed}: {asked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Λ is the L key. At COUNT's "Select object to count or [List/Spaces]" the Latin L is the selection
|
||||
/// word Last, not the List option: the Greek key is read the same way, and so is the whole word.
|
||||
#[test]
|
||||
fn a_greek_selection_word_wins_over_a_keyword_on_the_same_key() {
|
||||
let answer = |typed: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap();
|
||||
s.start("COUNT").unwrap();
|
||||
let from = s.log.len();
|
||||
s.cmdline(typed).unwrap();
|
||||
s.log[from..].join("\n")
|
||||
};
|
||||
let last = answer("L");
|
||||
assert!(last.contains("like the selected one"), "L counts the objects like the last one: {last}");
|
||||
assert_ne!(last, answer("List"));
|
||||
for typed in ["Λ", "λ", "ΛΑΣΤ"] {
|
||||
assert_eq!(answer(typed), last, "{typed}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! A hidden object that is back in the selection takes no part in a grip edit: Undo, `sssetfirst`
|
||||
//! or a control call can restore it there, and the grips it shares with a visible object must not
|
||||
//! drag it along.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
/// Draws a line from `a` to `b` and returns its handle.
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
let r = s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The two ends of the line `h`.
|
||||
fn ends(s: &Session, h: Handle) -> (Vec2, Vec2) {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
|
||||
k => panic!("not a line: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two lines sharing the end (0, 0), the second one hidden, both in the selection.
|
||||
fn shared_corner() -> (Session, Handle, Handle) {
|
||||
let mut s = Session::new();
|
||||
let shown = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
|
||||
let hidden = line(&mut s, [0.0, 0.0], [0.0, 10.0]);
|
||||
s.execute("hideobjects", &json!({ "handles": [hidden.hex()] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(!d.is_visible(d.entity(hidden).unwrap()), "the second line must be hidden");
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
(s, shown, hidden)
|
||||
}
|
||||
|
||||
/// The index of the grip of `h` at `p`.
|
||||
fn grip_at(s: &Session, h: Handle, p: Vec2) -> usize {
|
||||
s.grips_of(h).unwrap().iter().position(|g| g.near(p, 1e-9)).unwrap()
|
||||
}
|
||||
|
||||
/// Stretching the shared corner moves the visible line only; the hidden one stays where it was.
|
||||
#[test]
|
||||
fn a_hidden_selected_line_is_not_stretched_with_a_shared_grip() {
|
||||
let (mut s, shown, hidden) = shared_corner();
|
||||
let i = grip_at(&s, shown, Vec2::new(0.0, 0.0));
|
||||
s.start_grip_edit(&[(shown, i)]).unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (start, end) = ends(&s, shown);
|
||||
assert!(start.near(Vec2::new(3.0, 4.0), 1e-9) && end.near(Vec2::new(10.0, 0.0), 1e-9), "{start:?} {end:?}");
|
||||
let (start, end) = ends(&s, hidden);
|
||||
assert!(start.near(Vec2::new(0.0, 0.0), 1e-9) && end.near(Vec2::new(0.0, 10.0), 1e-9), "the hidden line moved: {start:?} {end:?}");
|
||||
}
|
||||
|
||||
/// The Move mode of a grip edit moves the visible selection only.
|
||||
#[test]
|
||||
fn a_hidden_selected_line_is_not_moved_by_the_move_mode_of_a_grip_edit() {
|
||||
let (mut s, shown, hidden) = shared_corner();
|
||||
let i = grip_at(&s, shown, Vec2::new(10.0, 0.0));
|
||||
s.start_grip_edit(&[(shown, i)]).unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.prompt_text().contains("** MOVE **"), "{}", s.prompt_text());
|
||||
s.cmdline("12,5").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (start, end) = ends(&s, shown);
|
||||
assert!(start.near(Vec2::new(2.0, 5.0), 1e-9) && end.near(Vec2::new(12.0, 5.0), 1e-9), "{start:?} {end:?}");
|
||||
let (start, end) = ends(&s, hidden);
|
||||
assert!(start.near(Vec2::new(0.0, 0.0), 1e-9) && end.near(Vec2::new(0.0, 10.0), 1e-9), "the hidden line moved: {start:?} {end:?}");
|
||||
}
|
||||
|
||||
/// The grip of a hidden object is never made hot, so a grip edit cannot start on it.
|
||||
#[test]
|
||||
fn the_grip_of_a_hidden_object_cannot_be_made_hot() {
|
||||
let (mut s, _, hidden) = shared_corner();
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
let err = s.start_grip_edit(&[(hidden, 0)]).unwrap_err().to_string();
|
||||
assert!(err.contains("no grip"), "{err}");
|
||||
assert!(s.running.is_none());
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "nothing may change");
|
||||
}
|
||||
|
||||
/// A hidden object's grip among the hot grips is left out, wherever it stands in the list: the
|
||||
/// first grip the drawing shows is the base grip, and only the visible line is stretched.
|
||||
#[test]
|
||||
fn a_hidden_grip_among_the_hot_grips_is_left_out() {
|
||||
for hidden_first in [false, true] {
|
||||
let (mut s, shown, hidden) = shared_corner();
|
||||
let mut hot = vec![(shown, grip_at(&s, shown, Vec2::new(0.0, 0.0))), (hidden, grip_at(&s, hidden, Vec2::new(0.0, 10.0)))];
|
||||
if hidden_first {
|
||||
hot.reverse();
|
||||
}
|
||||
s.start_grip_edit(&hot).unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (start, end) = ends(&s, shown);
|
||||
assert!(start.near(Vec2::new(3.0, 4.0), 1e-9) && end.near(Vec2::new(10.0, 0.0), 1e-9), "hidden first: {hidden_first}: {start:?} {end:?}");
|
||||
let (start, end) = ends(&s, hidden);
|
||||
assert!(
|
||||
start.near(Vec2::new(0.0, 0.0), 1e-9) && end.near(Vec2::new(0.0, 10.0), 1e-9),
|
||||
"hidden first: {hidden_first}: the hidden line moved: {start:?} {end:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Only what the drawing does not show is left out: a grip of an object that does not exist is
|
||||
/// still an error, also after a good one.
|
||||
#[test]
|
||||
fn a_missing_object_among_the_hot_grips_is_still_an_error() {
|
||||
let (mut s, shown, _) = shared_corner();
|
||||
let i = grip_at(&s, shown, Vec2::new(0.0, 0.0));
|
||||
let err = s.start_grip_edit(&[(shown, i), (Handle(0xFFFF), 0)]).unwrap_err().to_string();
|
||||
assert!(err.contains("no such object"), "{err}");
|
||||
assert!(s.running.is_none());
|
||||
}
|
||||
|
||||
/// A selected line on a layer that is off is not shown either, and is not stretched with a
|
||||
/// shared grip.
|
||||
#[test]
|
||||
fn a_selected_line_on_a_layer_that_is_off_is_not_stretched_with_a_shared_grip() {
|
||||
let mut s = Session::new();
|
||||
let shown = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
|
||||
s.execute("layer.new", &json!({ "name": "Guides", "current": true })).unwrap();
|
||||
let off = line(&mut s, [0.0, 0.0], [0.0, 10.0]);
|
||||
s.execute("layer.current", &json!({ "name": "0" })).unwrap();
|
||||
s.execute("layer.set", &json!({ "name": "Guides", "on": false })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(!d.is_visible(d.entity(off).unwrap()), "the second line must be on a layer that is off");
|
||||
s.set_selection(vec![shown, off]);
|
||||
let i = grip_at(&s, shown, Vec2::new(0.0, 0.0));
|
||||
s.start_grip_edit(&[(shown, i)]).unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (start, end) = ends(&s, shown);
|
||||
assert!(start.near(Vec2::new(3.0, 4.0), 1e-9) && end.near(Vec2::new(10.0, 0.0), 1e-9), "{start:?} {end:?}");
|
||||
let (start, end) = ends(&s, off);
|
||||
assert!(
|
||||
start.near(Vec2::new(0.0, 0.0), 1e-9) && end.near(Vec2::new(0.0, 10.0), 1e-9),
|
||||
"the line on the layer that is off moved: {start:?} {end:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The typed GRIP command finds no grip where only a hidden object has one, and at the shared
|
||||
/// corner it makes only the visible line's grip hot.
|
||||
#[test]
|
||||
fn the_typed_grip_command_finds_no_grip_of_a_hidden_object() {
|
||||
let (mut s, shown, hidden) = shared_corner();
|
||||
s.cmdline("grip").unwrap();
|
||||
assert!(s.prompt_text().contains("Select grip"), "{}", s.prompt_text());
|
||||
// Only the hidden line has a grip at (0, 10): the command says so and asks again.
|
||||
s.cmdline("0,10").unwrap();
|
||||
assert!(s.log.iter().any(|l| l.contains("No grip of a selected object there")), "{:?}", s.log);
|
||||
s.cmdline("0,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.prompt_text().contains("** STRETCH **"), "{}", s.prompt_text());
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (start, end) = ends(&s, shown);
|
||||
assert!(start.near(Vec2::new(3.0, 4.0), 1e-9) && end.near(Vec2::new(10.0, 0.0), 1e-9), "{start:?} {end:?}");
|
||||
let (start, end) = ends(&s, hidden);
|
||||
assert!(start.near(Vec2::new(0.0, 0.0), 1e-9) && end.near(Vec2::new(0.0, 10.0), 1e-9), "the hidden line moved: {start:?} {end:?}");
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//! LISP `findfile` finds folders as well as files (#2985): routines test whether an optional
|
||||
//! module is installed with `(findfile "module/.")`.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
/// `(findfile name)` as LISP prints it.
|
||||
fn findfile(name: &str) -> String {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("lisp", &json!({ "code": format!("(findfile \"{name}\")") })).unwrap();
|
||||
r["value"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findfile_finds_a_folder_with_and_without_a_trailing_dot() {
|
||||
let dir = TempDir::new("findfile-folder");
|
||||
std::fs::create_dir_all(dir.join("module")).unwrap();
|
||||
// Forward slashes, so the name needs no escaping in the LISP string on Windows.
|
||||
let folder = dir.join("module").to_string_lossy().replace('\\', "/");
|
||||
assert_eq!(findfile(&folder), format!("\"{folder}\""));
|
||||
assert_eq!(findfile(&format!("{folder}/.")), format!("\"{folder}/.\""));
|
||||
// A folder that isn't there is still nil.
|
||||
assert_eq!(findfile(&format!("{folder}-missing")), "nil");
|
||||
assert_eq!(findfile(&format!("{folder}-missing/.")), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findfile_still_finds_a_file() {
|
||||
let dir = TempDir::new("findfile-file");
|
||||
let file = dir.file("routine.lsp", "(princ)").replace('\\', "/");
|
||||
assert_eq!(findfile(&file), format!("\"{file}\""));
|
||||
}
|
||||
@@ -52,6 +52,7 @@ mod extend_polyline_arc_end;
|
||||
mod fillet_chamfer;
|
||||
mod fix_holds_grips;
|
||||
mod followups_626;
|
||||
mod greek_keyboard;
|
||||
mod grip_dim_input;
|
||||
mod grip_options;
|
||||
mod grip_selection;
|
||||
@@ -62,6 +63,7 @@ mod hatch_dialog_helpers;
|
||||
mod hatch_numeric_validation;
|
||||
mod hatch_options;
|
||||
mod helix;
|
||||
mod hidden_grip_targets;
|
||||
mod inquiry_keywords;
|
||||
mod inquiry_variables;
|
||||
mod inquiry_z;
|
||||
@@ -77,6 +79,7 @@ mod layout_prompts;
|
||||
mod leader_command;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod lisp_corpus;
|
||||
mod lisp_findfile;
|
||||
mod lisp_undo_in_routine;
|
||||
mod malformed_handles;
|
||||
mod matchprop;
|
||||
@@ -165,6 +168,7 @@ mod trim_extend_options;
|
||||
mod undo_count;
|
||||
mod undo_layout_tab;
|
||||
mod viewport_clip;
|
||||
mod viewport_frozen_selection;
|
||||
mod vplayer_prompts;
|
||||
mod vports;
|
||||
mod wipeout_grips;
|
||||
|
||||
@@ -0,0 +1,783 @@
|
||||
//! Inside an MSPACE viewport an object on a layer frozen in that viewport (VPLAYER, "VP Freeze")
|
||||
//! is not drawn there, so the selections made through that viewport leave it out: picks, windows,
|
||||
//! the typed selection modes, the commands that select for themselves, and, for an object that is
|
||||
//! already selected, its grips and the commands that start from the selection. In a viewport that
|
||||
//! does not freeze the layer, in paper space and on the Model tab everything is as before.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle, Space};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Draws a line from `a` to `b` on the current layer and returns its handle.
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
let r = s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Puts `h` on the layer "Hidden", which [`viewports`] freezes in its first viewport.
|
||||
fn hide(s: &mut Session, h: Handle) {
|
||||
if s.doc().unwrap().layer("Hidden").is_none() {
|
||||
s.execute("layer.new", &json!({ "name": "Hidden" })).unwrap();
|
||||
}
|
||||
s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": "Hidden" })).unwrap();
|
||||
assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "Hidden");
|
||||
}
|
||||
|
||||
/// Two viewports on Layout1: the first freezes the layer "Hidden", the second freezes nothing.
|
||||
/// The session is left in paper space.
|
||||
fn viewports(s: &mut Session) -> (String, String) {
|
||||
if s.doc().unwrap().layer("Hidden").is_none() {
|
||||
s.execute("layer.new", &json!({ "name": "Hidden" })).unwrap();
|
||||
}
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let r = s.execute("mview", &json!({ "count": 2, "p1": [20, 20], "p2": [220, 120] })).unwrap();
|
||||
let (a, b) = (r["viewports"][0].as_str().unwrap().to_string(), r["viewports"][1].as_str().unwrap().to_string());
|
||||
s.execute("vplayer", &json!({ "handles": [a], "freeze": ["Hidden"] })).unwrap();
|
||||
(a, b)
|
||||
}
|
||||
|
||||
/// Makes `viewport` the active MSPACE viewport.
|
||||
fn enter(s: &mut Session, viewport: &str) {
|
||||
s.execute("mspace", &json!({ "handle": viewport })).unwrap();
|
||||
assert_eq!(s.space(), Space::Model, "inside a viewport the edit space is model space");
|
||||
}
|
||||
|
||||
/// What most tests draw: `shown` on layer 0 and, drawn after it and so on top of it, `hidden` on
|
||||
/// the layer "Hidden", both from (0, 0) to (10, 0); and the two viewports of [`viewports`].
|
||||
struct Sheet {
|
||||
s: Session,
|
||||
shown: Handle,
|
||||
hidden: Handle,
|
||||
/// The viewport that freezes "Hidden".
|
||||
a: String,
|
||||
/// The viewport that freezes nothing.
|
||||
b: String,
|
||||
}
|
||||
|
||||
/// The drawing of [`Sheet`], in paper space.
|
||||
fn sheet() -> Sheet {
|
||||
let mut s = Session::new();
|
||||
let shown = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
|
||||
let hidden = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
|
||||
hide(&mut s, hidden);
|
||||
assert_eq!(s.doc().unwrap().entity(shown).unwrap().common.layer, "0");
|
||||
let (a, b) = viewports(&mut s);
|
||||
Sheet { s, shown, hidden, a, b }
|
||||
}
|
||||
|
||||
/// The two ends of the line `h`.
|
||||
fn ends(s: &Session, h: Handle) -> (Vec2, Vec2) {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
|
||||
k => panic!("not a line: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the line `h` still runs from (0, 0) to (10, 0).
|
||||
fn untouched(s: &Session, h: Handle) -> bool {
|
||||
let (a, b) = ends(s, h);
|
||||
a.near(Vec2::new(0.0, 0.0), 1e-9) && b.near(Vec2::new(10.0, 0.0), 1e-9)
|
||||
}
|
||||
|
||||
/// Whether the drawing still has the object `h`.
|
||||
fn exists(s: &Session, h: Handle) -> bool {
|
||||
s.doc().unwrap().entity(h).is_some()
|
||||
}
|
||||
|
||||
/// Every selected object, in handle order: the stored selection, which also holds the objects
|
||||
/// the active viewport does not draw ([`Session::selection`] leaves those out).
|
||||
fn selected(s: &Session) -> Vec<Handle> {
|
||||
let mut v = s.state().unwrap().selection.clone();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// Whether the line `h` was erased or no longer runs from (0, 0) to (10, 0).
|
||||
fn edited(s: &Session, h: Handle) -> bool {
|
||||
!exists(s, h) || !untouched(s, h)
|
||||
}
|
||||
|
||||
/// The index of the grip of `h` at the origin.
|
||||
fn origin_grip(s: &Session, h: Handle) -> usize {
|
||||
s.grips_of(h).unwrap().iter().position(|g| g.near(Vec2::new(0.0, 0.0), 1e-9)).unwrap()
|
||||
}
|
||||
|
||||
/// `hs` in handle order.
|
||||
fn sorted(mut hs: Vec<Handle>) -> Vec<Handle> {
|
||||
hs.sort();
|
||||
hs
|
||||
}
|
||||
|
||||
/// Runs `text` as a script and ends whatever prompt it leaves open with Enter.
|
||||
fn run(s: &mut Session, text: &str) {
|
||||
s.script(text).unwrap();
|
||||
for _ in 0..4 {
|
||||
if s.running.is_none() {
|
||||
break;
|
||||
}
|
||||
s.cmdline("").unwrap();
|
||||
}
|
||||
assert!(s.running.is_none(), "`{text}` left a prompt open: {}", s.prompt_text());
|
||||
}
|
||||
|
||||
/// The JSON `select` command replaces the selection with what `how` finds.
|
||||
fn select(s: &mut Session, how: Value) -> Vec<Handle> {
|
||||
s.set_selection(Vec::new());
|
||||
s.execute("select", &how).unwrap();
|
||||
selected(s)
|
||||
}
|
||||
|
||||
/// A pick takes the topmost object the viewport draws: the frozen line lies on top of the other
|
||||
/// one, and a pick at the same point finds the line under it. Where the layer is not frozen the
|
||||
/// pick finds the line on top, as it always did.
|
||||
#[test]
|
||||
fn a_pick_finds_the_topmost_object_the_viewport_draws() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
let at = json!({ "at": [5, 0], "aperture": 0.5 });
|
||||
enter(&mut s, &a);
|
||||
assert_eq!(select(&mut s, at.clone()), [shown], "the viewport freezes the layer of the line on top");
|
||||
enter(&mut s, &b);
|
||||
assert_eq!(select(&mut s, at.clone()), [hidden], "this viewport draws both: the one on top is picked");
|
||||
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
|
||||
assert_eq!(select(&mut s, at), [hidden], "the Model tab draws both");
|
||||
}
|
||||
|
||||
/// Window, crossing and fence selection through the viewport leave the frozen line out, and take
|
||||
/// both lines through the viewport that draws both.
|
||||
#[test]
|
||||
fn a_window_a_crossing_and_a_fence_leave_out_what_the_viewport_does_not_draw() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
let ways =
|
||||
[json!({ "window": [[-1, -1], [11, 1]] }), json!({ "window": [[4, -1], [6, 1]], "crossing": true }), json!({ "fence": [[5, -1], [5, 1]] })];
|
||||
for how in &ways {
|
||||
enter(&mut s, &a);
|
||||
assert_eq!(select(&mut s, how.clone()), [shown], "{how}");
|
||||
enter(&mut s, &b);
|
||||
assert_eq!(select(&mut s, how.clone()), sorted(vec![shown, hidden]), "{how}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Clicks with no command running: a click on the two lines selects the one the viewport draws,
|
||||
/// and a window dragged around them takes only that one.
|
||||
#[test]
|
||||
fn idle_clicks_and_windows_select_what_the_viewport_draws() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
s.idle_click(Vec2::new(5.0, 0.0), false).unwrap();
|
||||
assert_eq!(selected(&s), [shown]);
|
||||
s.set_selection(Vec::new());
|
||||
// A click on nothing opens a window; the next click closes it (left to right: a window).
|
||||
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
|
||||
assert!(s.pending_window.is_some(), "the first click must be on nothing");
|
||||
s.idle_click(Vec2::new(11.0, 1.0), false).unwrap();
|
||||
assert_eq!(selected(&s), [shown]);
|
||||
|
||||
enter(&mut s, &b);
|
||||
s.idle_click(Vec2::new(5.0, 0.0), false).unwrap();
|
||||
assert_eq!(selected(&s), [hidden], "this viewport draws both: the one on top is picked");
|
||||
s.set_selection(Vec::new());
|
||||
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
|
||||
s.idle_click(Vec2::new(11.0, 1.0), false).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![shown, hidden]));
|
||||
}
|
||||
|
||||
/// Selection cycling lists the objects under the pick box that the viewport draws.
|
||||
#[test]
|
||||
fn selection_cycling_lists_what_the_viewport_draws() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
assert_eq!(s.pick_candidates(Vec2::new(5.0, 0.0)), [shown]);
|
||||
enter(&mut s, &b);
|
||||
assert_eq!(s.pick_candidates(Vec2::new(5.0, 0.0)), [hidden, shown], "topmost first");
|
||||
}
|
||||
|
||||
/// Every way of answering "Select objects" leaves the frozen line out: ERASE through the
|
||||
/// viewport that freezes its layer erases the other line only, and through the other viewport
|
||||
/// both.
|
||||
#[test]
|
||||
fn the_answers_to_select_objects_leave_out_what_the_viewport_does_not_draw() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
s.execute("group", &json!({ "name": "PAIR", "handles": [shown.hex(), hidden.hex()] })).unwrap();
|
||||
// Group selection off: a pick takes the object alone, so each answer is tested by itself.
|
||||
s.settings.pickstyle = 0;
|
||||
let answers = [
|
||||
"5,0",
|
||||
"-1,-1 11,1",
|
||||
"ALL",
|
||||
"W -1,-1 11,1",
|
||||
"C 6,1 4,-1",
|
||||
"BOX 6,1 4,-1",
|
||||
"F 5,-1 5,1\n",
|
||||
"WP -1,-1 11,-1 11,1 -1,1\n",
|
||||
"CP 4,-1 6,-1 5,1\n",
|
||||
"G PAIR",
|
||||
];
|
||||
for answer in answers {
|
||||
enter(&mut s, &a);
|
||||
run(&mut s, &format!("ERASE {answer}\n"));
|
||||
assert!(!exists(&s, shown), "`{answer}` must erase the line the viewport draws");
|
||||
assert!(exists(&s, hidden), "`{answer}` erased a line the viewport does not draw");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert!(exists(&s, shown) && exists(&s, hidden));
|
||||
|
||||
enter(&mut s, &b);
|
||||
run(&mut s, &format!("ERASE {answer}\n"));
|
||||
// A pick takes one object, the one on top; every other answer takes both.
|
||||
assert_eq!((exists(&s, shown), exists(&s, hidden)), (answer == "5,0", false), "`{answer}` where both are drawn");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert!(exists(&s, shown) && exists(&s, hidden));
|
||||
}
|
||||
}
|
||||
|
||||
/// With group selection on, a pick brings the members of its group that the viewport draws.
|
||||
#[test]
|
||||
fn a_pick_brings_the_group_members_the_viewport_draws() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
s.execute("group", &json!({ "name": "PAIR", "handles": [shown.hex(), hidden.hex()] })).unwrap();
|
||||
s.settings.pickstyle = 1;
|
||||
s.set_selection(Vec::new());
|
||||
s.idle_click(Vec2::new(5.0, 0.0), false).unwrap();
|
||||
assert_eq!(selected(&s), [shown]);
|
||||
enter(&mut s, &b);
|
||||
s.idle_click(Vec2::new(5.0, 0.0), false).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![shown, hidden]));
|
||||
}
|
||||
|
||||
/// Select All and Select Similar take what the viewport draws.
|
||||
#[test]
|
||||
fn select_all_and_select_similar_take_what_the_viewport_draws() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
// Mode 0: any object of the same type is similar, whatever its layer.
|
||||
let similar = json!({ "handles": [shown.hex()], "mode": 0 });
|
||||
enter(&mut s, &a);
|
||||
s.execute("selectall", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), [shown]);
|
||||
s.execute("selectsimilar", &similar).unwrap();
|
||||
assert_eq!(selected(&s), [shown]);
|
||||
enter(&mut s, &b);
|
||||
s.execute("selectall", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![shown, hidden]));
|
||||
s.execute("selectsimilar", &similar).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![shown, hidden]));
|
||||
}
|
||||
|
||||
/// STRETCH selects for itself: its crossing window, polygon and fence, called with JSON or
|
||||
/// typed, and its typed All, Last and Previous, move the line the viewport draws and leave the
|
||||
/// frozen one where it was.
|
||||
#[test]
|
||||
fn stretch_moves_what_the_viewport_draws() {
|
||||
let calls = [
|
||||
json!({ "window": [[9, -1], [11, 1]], "delta": [0, 5] }),
|
||||
json!({ "polygon": [[9, -1], [11, -1], [11, 1], [9, 1]], "delta": [0, 5] }),
|
||||
json!({ "fence": [[5, -1], [5, 1]], "delta": [0, 5] }),
|
||||
];
|
||||
for call in &calls {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
s.execute("stretch", call).unwrap();
|
||||
assert!(!untouched(&s, shown), "{call}: the line the viewport draws must move");
|
||||
assert!(untouched(&s, hidden), "{call}: a line the viewport does not draw moved: {:?}", ends(&s, hidden));
|
||||
enter(&mut s, &b);
|
||||
s.execute("stretch", call).unwrap();
|
||||
assert!(!untouched(&s, hidden), "{call}: where both are drawn both move");
|
||||
}
|
||||
// Typed: a crossing window, named and implied, All, a pick, Last, and Previous (both lines).
|
||||
for objects in ["C 11,1 9,-1", "11,1 9,-1", "ALL", "5,0", "L", "P"] {
|
||||
let typed = format!("STRETCH {objects}\n\n0,0 0,5\n");
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
s.remember_selection(&[shown, hidden]);
|
||||
run(&mut s, &typed);
|
||||
assert!(!untouched(&s, shown), "{typed:?}: the line the viewport draws must move");
|
||||
assert!(untouched(&s, hidden), "{typed:?}: a line the viewport does not draw moved: {:?}", ends(&s, hidden));
|
||||
enter(&mut s, &b);
|
||||
s.remember_selection(&[shown, hidden]);
|
||||
run(&mut s, &typed);
|
||||
assert!(!untouched(&s, hidden), "{typed:?}: where both are drawn the one on top moves");
|
||||
}
|
||||
}
|
||||
|
||||
/// A multiline whose control vertex is inside STRETCH's crossing window is stretched although
|
||||
/// the window misses its drawn lines, but not when the viewport does not draw it.
|
||||
#[test]
|
||||
fn stretch_leaves_a_multiline_the_viewport_does_not_draw() {
|
||||
/// The control vertices of the multiline `h`.
|
||||
fn vertices(s: &Session, h: Handle) -> Vec<Vec2> {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::MLine(m) => m.vertices.iter().map(|v| v.p.xy()).collect(),
|
||||
k => panic!("not a multiline: {k:?}"),
|
||||
}
|
||||
}
|
||||
let mut s = Session::new();
|
||||
// Zero justification at scale 2: the element lines run one unit either side of the vertices.
|
||||
let r = s.execute("mline", &json!({ "points": [[0, 0], [10, 0]], "scale": 2, "justification": "zero" })).unwrap();
|
||||
let mline = Handle::parse_hex(r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap()).unwrap();
|
||||
hide(&mut s, mline);
|
||||
let (a, b) = viewports(&mut s);
|
||||
let call = json!({ "window": [[9.9, -0.1], [10.1, 0.1]], "delta": [0, 5] });
|
||||
enter(&mut s, &a);
|
||||
s.execute("stretch", &call).unwrap();
|
||||
assert!(vertices(&s, mline)[1].near(Vec2::new(10.0, 0.0), 1e-9), "a multiline the viewport does not draw was stretched");
|
||||
enter(&mut s, &b);
|
||||
s.execute("stretch", &call).unwrap();
|
||||
assert!(vertices(&s, mline)[1].near(Vec2::new(10.0, 5.0), 1e-9), "{:?}", vertices(&s, mline));
|
||||
}
|
||||
|
||||
/// TRIM's fence and crossing window trim the line the viewport draws and leave the frozen one.
|
||||
#[test]
|
||||
fn trim_by_fence_and_crossing_leaves_what_the_viewport_does_not_draw() {
|
||||
for call in [json!({ "fence": [[8, -1], [8, 1]] }), json!({ "crossing": [[7.5, -1], [8.5, 1]] })] {
|
||||
let mut s = Session::new();
|
||||
let shown = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
|
||||
let hidden = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
|
||||
// The cutting edge, on a layer every viewport draws.
|
||||
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
|
||||
hide(&mut s, hidden);
|
||||
let (a, b) = viewports(&mut s);
|
||||
enter(&mut s, &a);
|
||||
s.execute("trim", &call).unwrap();
|
||||
assert!(!untouched(&s, shown), "{call}: the line the viewport draws must be trimmed");
|
||||
assert!(untouched(&s, hidden), "{call}: a line the viewport does not draw was trimmed: {:?}", ends(&s, hidden));
|
||||
enter(&mut s, &b);
|
||||
s.execute("trim", &call).unwrap();
|
||||
assert!(!untouched(&s, hidden), "{call}: where both are drawn both are trimmed");
|
||||
}
|
||||
}
|
||||
|
||||
/// A prompt that picks one object (BREAK's "Select object") finds the one the viewport draws.
|
||||
#[test]
|
||||
fn a_prompt_for_one_object_picks_what_the_viewport_draws() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
run(&mut s, "BREAK 4,0 6,0\n");
|
||||
assert!(untouched(&s, hidden), "a line the viewport does not draw was broken: {:?}", ends(&s, hidden));
|
||||
assert!(!untouched(&s, shown), "the line the viewport draws must be broken");
|
||||
enter(&mut s, &b);
|
||||
run(&mut s, "BREAK 4,0 6,0\n");
|
||||
assert!(!untouched(&s, hidden), "where both are drawn the one on top is broken");
|
||||
}
|
||||
|
||||
/// LEADER's Copy option picks the text to copy: at a point where two texts lie, the one the
|
||||
/// viewport draws.
|
||||
#[test]
|
||||
fn leader_copies_the_text_the_viewport_draws() {
|
||||
/// The contents of the multiline texts in model space: LEADER's copies.
|
||||
fn copies(s: &Session) -> Vec<String> {
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::MText(m) = &e.kind { Some(m.contents.clone()) } else { None }).collect()
|
||||
}
|
||||
let mut s = Session::new();
|
||||
for text in ["SHOWN", "HIDDEN"] {
|
||||
s.execute("text", &json!({ "at": [0, 0], "text": text, "height": 2.5 })).unwrap();
|
||||
}
|
||||
// The text drawn last lies on top.
|
||||
let hidden = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
hide(&mut s, hidden);
|
||||
let (a, b) = viewports(&mut s);
|
||||
let leader = "(command \"_.LEADER\" '(20.0 20.0) '(30.0 25.0) \"\" \"\" \"_C\" '(1.0 1.0))";
|
||||
enter(&mut s, &a);
|
||||
s.cmdline(leader).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(copies(&s), ["SHOWN"], "the viewport freezes the layer of the text on top");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert!(copies(&s).is_empty());
|
||||
enter(&mut s, &b);
|
||||
s.cmdline(leader).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(copies(&s), ["HIDDEN"], "this viewport draws both: the one on top is picked");
|
||||
}
|
||||
|
||||
/// AutoLISP selects through the viewport too: `ssget` with a window, a crossing window, a fence,
|
||||
/// a polygon, a crossing polygon or a point leaves the frozen line out, and `entsel` picks the
|
||||
/// line the viewport draws. The sets made earlier (the implied selection, `ssgetfirst`, Previous)
|
||||
/// come without the frozen line, and Last is the last object the viewport draws.
|
||||
#[test]
|
||||
fn lisp_selects_what_the_viewport_draws() {
|
||||
use cadcraft_engine::lisp::value::Value as Lisp;
|
||||
/// The objects of the selection set that `code` returns (none for nil), in handle order.
|
||||
fn set(s: &mut Session, code: &str) -> Vec<Handle> {
|
||||
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:?}"),
|
||||
}
|
||||
}
|
||||
/// The object `entsel` returns for a pick at (5, 0).
|
||||
fn entsel(s: &mut Session) -> Handle {
|
||||
s.cmdline("(setq picked (car (entsel)))").unwrap();
|
||||
s.input(cadcraft_engine::Input::Point(Vec2::new(5.0, 0.0))).unwrap();
|
||||
match s.lisp_var("picked") {
|
||||
Lisp::Ename(h) => h,
|
||||
other => panic!("entsel returned {other:?}: {}", s.prompt_text()),
|
||||
}
|
||||
}
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
let areas = [
|
||||
"(ssget \"W\" '(-1 -1) '(11 1))",
|
||||
"(ssget \"C\" '(4 -1) '(6 1))",
|
||||
"(ssget \"F\" '((5 -1) (5 1)))",
|
||||
"(ssget \"WP\" '((-1 -1) (11 -1) (11 1) (-1 1)))",
|
||||
"(ssget \"CP\" '((4 -1) (6 -1) (5 1)))",
|
||||
];
|
||||
enter(&mut s, &a);
|
||||
for code in areas {
|
||||
assert_eq!(set(&mut s, code), [shown], "{code}");
|
||||
}
|
||||
assert_eq!(set(&mut s, "(ssget '(5 0))"), [shown], "a point picks the object the viewport draws");
|
||||
assert_eq!(entsel(&mut s), shown);
|
||||
enter(&mut s, &b);
|
||||
for code in areas {
|
||||
assert_eq!(set(&mut s, code), sorted(vec![shown, hidden]), "{code}");
|
||||
}
|
||||
assert_eq!(set(&mut s, "(ssget '(5 0))"), [hidden], "this viewport draws both: the one on top is picked");
|
||||
assert_eq!(entsel(&mut s), hidden);
|
||||
|
||||
let earlier = ["(ssget \"I\")", "(ssget)", "(cadr (ssgetfirst))", "(ssget \"P\")"];
|
||||
for (viewport, expected) in [(&a, vec![shown]), (&b, sorted(vec![shown, hidden]))] {
|
||||
enter(&mut s, viewport);
|
||||
for code in earlier {
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
s.remember_selection(&[shown, hidden]);
|
||||
assert_eq!(set(&mut s, code), expected, "{code}");
|
||||
}
|
||||
}
|
||||
// Last: of two lines made after everything else, the later one is on the layer the first
|
||||
// viewport freezes, so through that viewport Last is the earlier one.
|
||||
s.set_selection(Vec::new());
|
||||
enter(&mut s, &b);
|
||||
let drawn = line(&mut s, [0.0, 2.0], [10.0, 2.0]);
|
||||
let last = line(&mut s, [0.0, 3.0], [10.0, 3.0]);
|
||||
hide(&mut s, last);
|
||||
assert_eq!(set(&mut s, "(ssget \"L\")"), [last]);
|
||||
enter(&mut s, &a);
|
||||
assert_eq!(set(&mut s, "(ssget \"L\")"), [drawn], "Last must pass over an object the viewport does not draw");
|
||||
}
|
||||
|
||||
/// The grips of a selected object the viewport does not draw take no part in a grip edit: a
|
||||
/// shared grip stretches only the line that is drawn. Through the other viewport both stretch.
|
||||
#[test]
|
||||
fn a_selected_line_the_viewport_does_not_draw_is_not_stretched_with_a_shared_grip() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, &a);
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
let i = origin_grip(&s, shown);
|
||||
s.start_grip_edit(&[(shown, i)]).unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(ends(&s, shown).0.near(Vec2::new(3.0, 4.0), 1e-9), "{:?}", ends(&s, shown));
|
||||
assert!(untouched(&s, hidden), "a line the viewport does not draw moved: {:?}", ends(&s, hidden));
|
||||
// Its own grip starts no edit there.
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
let j = origin_grip(&s, hidden);
|
||||
assert!(s.start_grip_edit(&[(hidden, j)]).is_err());
|
||||
assert!(s.running.is_none());
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "nothing may change");
|
||||
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
enter(&mut s, &b);
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
s.start_grip_edit(&[(shown, i)]).unwrap();
|
||||
s.cmdline("3,4").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(ends(&s, shown).0.near(Vec2::new(3.0, 4.0), 1e-9), "{:?}", ends(&s, shown));
|
||||
assert!(ends(&s, hidden).0.near(Vec2::new(3.0, 4.0), 1e-9), "where both are drawn both stretch: {:?}", ends(&s, hidden));
|
||||
}
|
||||
|
||||
/// A layer frozen in the viewport while its object is selected: from then on the object's grips
|
||||
/// are not there, and thawing the layer in the viewport brings them back.
|
||||
#[test]
|
||||
fn freezing_a_layer_in_the_viewport_removes_the_grips_of_a_selected_object() {
|
||||
let Sheet { mut s, hidden, b, .. } = sheet();
|
||||
enter(&mut s, &b);
|
||||
s.set_selection(vec![hidden]);
|
||||
// The typed GRIP command finds a grip of the selected line at its start.
|
||||
let grip_there = |s: &mut Session| {
|
||||
s.cmdline("grip").unwrap();
|
||||
s.cmdline("0,0").unwrap();
|
||||
let none = s.log.iter().any(|l| l.contains("No grip of a selected object there"));
|
||||
s.input(cadcraft_engine::Input::Cancel).unwrap();
|
||||
s.log.clear();
|
||||
!none
|
||||
};
|
||||
assert!(grip_there(&mut s), "the viewport draws the line: its grip is there");
|
||||
s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap();
|
||||
s.set_selection(vec![hidden]);
|
||||
assert!(!grip_there(&mut s), "the viewport no longer draws the line");
|
||||
s.execute("vplayer", &json!({ "handles": [b], "thaw": ["Hidden"] })).unwrap();
|
||||
s.set_selection(vec![hidden]);
|
||||
assert!(grip_there(&mut s), "thawed in the viewport: the grip is back");
|
||||
}
|
||||
|
||||
/// What the edited view shows: the frozen layer hides its model-space objects inside that
|
||||
/// viewport only, and never an object on the sheet.
|
||||
#[test]
|
||||
fn only_the_viewport_that_freezes_a_layer_hides_its_model_objects() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
// A line on the sheet, on the layer the first viewport freezes.
|
||||
let on_sheet = line(&mut s, [1.0, 1.0], [2.0, 1.0]);
|
||||
hide(&mut s, on_sheet);
|
||||
assert_eq!(s.doc().unwrap().space_of(on_sheet), Some(Space::Paper("Layout1".into())));
|
||||
let shows = |s: &Session, h: Handle| {
|
||||
let st = s.state().unwrap();
|
||||
st.shows(st.doc.entity(h).unwrap())
|
||||
};
|
||||
assert!(s.viewport_frozen().is_empty(), "paper space: no viewport is active");
|
||||
assert!(shows(&s, hidden) && shows(&s, shown) && shows(&s, on_sheet));
|
||||
enter(&mut s, &a);
|
||||
assert_eq!(s.viewport_frozen(), ["Hidden".to_string()]);
|
||||
assert!(!shows(&s, hidden), "frozen in the active viewport");
|
||||
assert!(shows(&s, shown));
|
||||
assert!(shows(&s, on_sheet), "the viewport draws model space: its frozen layers hide nothing on the sheet");
|
||||
// A prompt that picks one object on the sheet while the viewport is active finds it.
|
||||
let sheet_space = Space::Paper("Layout1".into());
|
||||
assert_eq!(s.pick_object(&sheet_space, Vec2::new(1.5, 1.0), 0.5).unwrap(), Some(on_sheet));
|
||||
assert_eq!(s.pick_object(&Space::Model, Vec2::new(5.0, 0.0), 0.5).unwrap(), Some(shown), "in model space the frozen line is left out");
|
||||
enter(&mut s, &b);
|
||||
assert!(s.viewport_frozen().is_empty());
|
||||
assert!(shows(&s, hidden));
|
||||
// Layer names are not case sensitive: frozen under another spelling, the line is hidden too.
|
||||
s.execute("vplayer", &json!({ "handles": [b], "freeze": ["HIDDEN"] })).unwrap();
|
||||
assert_eq!(s.viewport_frozen(), ["HIDDEN".to_string()]);
|
||||
assert!(!shows(&s, hidden));
|
||||
assert_eq!(select(&mut s, json!({ "at": [5, 0], "aperture": 0.5 })), [shown]);
|
||||
s.execute("vplayer", &json!({ "handles": [b], "thaw": ["hidden"] })).unwrap();
|
||||
assert!(shows(&s, hidden));
|
||||
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
|
||||
assert!(s.viewport_frozen().is_empty(), "the Model tab has no layout viewport");
|
||||
assert!(shows(&s, hidden));
|
||||
}
|
||||
|
||||
/// An object that is selected when its layer is frozen in the active viewport stays selected, but
|
||||
/// nothing that starts from the selection takes it there: a typed command with the selection
|
||||
/// made before it (PICKFIRST), a JSON command that names no objects, and Delete.
|
||||
#[test]
|
||||
fn a_command_leaves_out_a_selected_object_the_viewport_does_not_draw() {
|
||||
/// One way of editing the selection.
|
||||
type Edit = fn(&mut Session);
|
||||
let edits: [(&str, Edit); 5] = [
|
||||
("typed ERASE", |s: &mut Session| run(s, "ERASE\n")),
|
||||
("typed MOVE", |s: &mut Session| run(s, "MOVE 0,0 0,5\n")),
|
||||
("JSON erase", |s: &mut Session| drop(s.execute("erase", &json!({})).unwrap())),
|
||||
("JSON move", |s: &mut Session| drop(s.execute("move", &json!({ "delta": [0, 5] })).unwrap())),
|
||||
("Delete", |s: &mut Session| drop(s.execute("erase.selection", &json!({})).unwrap())),
|
||||
];
|
||||
for (name, edit) in edits {
|
||||
// Where both lines are drawn, both are edited.
|
||||
let Sheet { mut s, shown, hidden, b, .. } = sheet();
|
||||
enter(&mut s, &b);
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
edit(&mut s);
|
||||
assert!(edited(&s, shown) && edited(&s, hidden), "{name}: where both are drawn both are edited");
|
||||
|
||||
// The layer is frozen in the active viewport while both lines are selected.
|
||||
let Sheet { mut s, shown, hidden, b, .. } = sheet();
|
||||
enter(&mut s, &b);
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![shown, hidden]), "{name}: both lines must still be selected");
|
||||
assert_eq!(s.selection(), [shown], "{name}: the selection as the viewport has it");
|
||||
edit(&mut s);
|
||||
assert!(edited(&s, shown), "{name}: the line the viewport draws must be edited");
|
||||
assert!(!edited(&s, hidden), "{name}: a line the viewport does not draw was edited: {:?}", ends(&s, hidden));
|
||||
}
|
||||
|
||||
// With only that line selected there is nothing to start from.
|
||||
let Sheet { mut s, hidden, a, b, .. } = sheet();
|
||||
enter(&mut s, &a);
|
||||
s.set_selection(vec![hidden]);
|
||||
assert!(s.selection().is_empty());
|
||||
assert!(s.execute("erase.selection", &json!({})).is_err(), "Delete must find nothing selected");
|
||||
s.script("ERASE\n").unwrap();
|
||||
assert!(s.running.is_some() && s.prompt_text().contains("Select objects"), "ERASE must ask for objects: {}", s.prompt_text());
|
||||
s.input(cadcraft_engine::Input::Cancel).unwrap();
|
||||
assert!(!edited(&s, hidden));
|
||||
// The line is still selected, and a viewport that draws it has it again.
|
||||
s.set_selection(vec![hidden]);
|
||||
s.execute("vplayer", &json!({ "handles": [a], "thaw": ["Hidden"] })).unwrap();
|
||||
assert_eq!(s.selection(), [hidden], "thawed in the viewport: selected as before");
|
||||
s.execute("vplayer", &json!({ "handles": [a], "freeze": ["Hidden"] })).unwrap();
|
||||
assert!(s.selection().is_empty());
|
||||
enter(&mut s, &b);
|
||||
s.set_selection(vec![hidden]);
|
||||
run(&mut s, "ERASE\n");
|
||||
assert!(!exists(&s, hidden), "where the line is drawn the selection made before ERASE is erased");
|
||||
}
|
||||
|
||||
/// The Previous and Last options of "Select objects" take what the viewport draws: of the set a
|
||||
/// command used before, and the last object that is not frozen there.
|
||||
#[test]
|
||||
fn previous_and_last_leave_out_what_the_viewport_does_not_draw() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
for option in ["P", "L"] {
|
||||
enter(&mut s, &a);
|
||||
s.set_selection(Vec::new());
|
||||
s.remember_selection(&[shown, hidden]);
|
||||
run(&mut s, &format!("ERASE {option}\n"));
|
||||
assert!(!exists(&s, shown), "`{option}` must erase the line the viewport draws");
|
||||
assert!(exists(&s, hidden), "`{option}` erased a line the viewport does not draw");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert!(exists(&s, shown) && exists(&s, hidden));
|
||||
|
||||
enter(&mut s, &b);
|
||||
s.set_selection(Vec::new());
|
||||
s.remember_selection(&[shown, hidden]);
|
||||
run(&mut s, &format!("ERASE {option}\n"));
|
||||
// Previous is both lines; Last is the one made last, the line on the layer "Hidden".
|
||||
assert_eq!((exists(&s, shown), exists(&s, hidden)), (option == "L", false), "`{option}` where both are drawn");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert!(exists(&s, shown) && exists(&s, hidden));
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON grip edits that cover the selection (`grip.stretch` with hot grips, and
|
||||
/// [`Session::grip_edit`]) drag the grips of the other selected objects on the same point, but
|
||||
/// not the grip of a selected line the viewport does not draw.
|
||||
#[test]
|
||||
fn the_grip_edits_that_cover_the_selection_leave_out_what_the_viewport_does_not_draw() {
|
||||
use cadcraft_engine::grips::GripMode;
|
||||
/// Drags grip `i` of the line `h` to (3, 4).
|
||||
type Edit = fn(&mut Session, Handle, usize);
|
||||
let edits: [(&str, Edit); 2] = [
|
||||
("grip.stretch", |s: &mut Session, h: Handle, i: usize| {
|
||||
drop(s.execute("grip.stretch", &json!({ "grips": [[h.hex(), i]], "to": [3, 4] })).unwrap())
|
||||
}),
|
||||
("grip_edit", |s: &mut Session, h: Handle, i: usize| s.grip_edit(h, i, Vec2::new(3.0, 4.0), GripMode::Stretch).unwrap()),
|
||||
];
|
||||
for (name, edit) in edits {
|
||||
for frozen in [true, false] {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
enter(&mut s, if frozen { &a } else { &b });
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
let i = origin_grip(&s, shown);
|
||||
edit(&mut s, shown, i);
|
||||
assert!(ends(&s, shown).0.near(Vec2::new(3.0, 4.0), 1e-9), "{name}: {:?}", ends(&s, shown));
|
||||
assert_eq!(untouched(&s, hidden), frozen, "{name}, layer frozen in the viewport: {frozen}: {:?}", ends(&s, hidden));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the session reports as the selection is the selection as the viewport has it, while
|
||||
/// every selected object stays in the stored selection.
|
||||
#[test]
|
||||
fn the_reported_selection_leaves_out_what_the_viewport_does_not_draw() {
|
||||
/// The handles in `list`, a JSON array of hex strings, in handle order.
|
||||
fn handles(list: &Value) -> Vec<Handle> {
|
||||
sorted(list.as_array().unwrap().iter().map(|h| Handle::parse_hex(h.as_str().unwrap()).unwrap()).collect())
|
||||
}
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
for (viewport, expected) in [(&a, vec![shown]), (&b, sorted(vec![shown, hidden]))] {
|
||||
enter(&mut s, viewport);
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
assert_eq!(selected(&s), sorted(vec![shown, hidden]), "both lines are selected");
|
||||
assert_eq!(sorted(s.selection()), expected);
|
||||
assert_eq!(handles(&s.summary()["selection"]), expected);
|
||||
let inspect = s.execute("drawing.inspect", &json!({})).unwrap();
|
||||
assert_eq!(handles(&inspect["selection"]), expected);
|
||||
}
|
||||
// A selected object on the sheet is never left out, whatever its layer.
|
||||
s.execute("pspace", &json!({})).unwrap();
|
||||
let on_sheet = line(&mut s, [1.0, 1.0], [2.0, 1.0]);
|
||||
hide(&mut s, on_sheet);
|
||||
enter(&mut s, &a);
|
||||
s.set_selection(vec![shown, hidden, on_sheet]);
|
||||
assert_eq!(sorted(s.selection()), sorted(vec![shown, on_sheet]));
|
||||
// Where no viewport is active nothing is left out: in paper space and on the Model tab.
|
||||
s.execute("pspace", &json!({})).unwrap();
|
||||
s.set_selection(vec![shown, hidden, on_sheet]);
|
||||
assert_eq!(sorted(s.selection()), sorted(vec![shown, hidden, on_sheet]), "paper space");
|
||||
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
assert_eq!(sorted(s.selection()), sorted(vec![shown, hidden]), "the Model tab");
|
||||
}
|
||||
|
||||
/// Adding to the selection or removing from it inside the viewport keeps a selected object the
|
||||
/// viewport does not draw: nothing drops it behind the user's back, and it counts again once its
|
||||
/// layer is thawed there.
|
||||
#[test]
|
||||
fn changing_the_selection_keeps_a_selected_object_the_viewport_does_not_draw() {
|
||||
let Sheet { mut s, shown, hidden, b, .. } = sheet();
|
||||
enter(&mut s, &b);
|
||||
// A third line, on layer 0 like `shown`, away from the other two.
|
||||
let other = line(&mut s, [0.0, 5.0], [10.0, 5.0]);
|
||||
// Selects `hidden` where it is drawn, then freezes its layer in the active viewport.
|
||||
let freeze = |s: &mut Session| {
|
||||
s.execute("vplayer", &json!({ "handles": [b], "thaw": ["Hidden"] })).unwrap();
|
||||
s.set_selection(vec![hidden]);
|
||||
s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap();
|
||||
assert_eq!(selected(s), [hidden], "the line must still be selected");
|
||||
assert!(s.selection().is_empty(), "the viewport does not draw it");
|
||||
};
|
||||
|
||||
// A click adds (PICKADD), Shift+click removes.
|
||||
freeze(&mut s);
|
||||
s.idle_click(Vec2::new(5.0, 5.0), false).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![hidden, other]), "a click dropped the selected line the viewport does not draw");
|
||||
assert_eq!(s.selection(), [other]);
|
||||
s.idle_click(Vec2::new(5.0, 5.0), true).unwrap();
|
||||
assert_eq!(selected(&s), [hidden], "Shift+click must remove only the line clicked");
|
||||
|
||||
// A window adds.
|
||||
freeze(&mut s);
|
||||
s.idle_click(Vec2::new(-1.0, 4.0), false).unwrap();
|
||||
assert!(s.pending_window.is_some(), "the first click must be on nothing");
|
||||
s.idle_click(Vec2::new(11.0, 6.0), false).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![hidden, other]), "a window dropped the selected line the viewport does not draw");
|
||||
|
||||
// The JSON `select` with `add`, and QSELECT appending the objects on layer 0.
|
||||
freeze(&mut s);
|
||||
s.execute("select", &json!({ "at": [5, 5], "aperture": 0.5, "add": true })).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![hidden, other]), "`select` with `add`");
|
||||
// Given nothing to select with, `select` leaves the selection as it is.
|
||||
s.execute("select", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![hidden, other]), "`select` with nothing to select with");
|
||||
freeze(&mut s);
|
||||
s.execute("qselect", &json!({ "layer": "0", "mode": "append" })).unwrap();
|
||||
assert_eq!(selected(&s), sorted(vec![shown, hidden, other]), "QSELECT appending");
|
||||
assert_eq!(sorted(s.selection()), sorted(vec![shown, other]));
|
||||
|
||||
// Thawed in the viewport, the line counts as selected again.
|
||||
s.execute("vplayer", &json!({ "handles": [b], "thaw": ["Hidden"] })).unwrap();
|
||||
assert_eq!(sorted(s.selection()), sorted(vec![shown, hidden, other]));
|
||||
}
|
||||
|
||||
/// [`Session::selection`] looks a few selected objects up one by one and, when there are many,
|
||||
/// passes over model space once. Both leave out the same objects and keep the order of the
|
||||
/// selection: in a drawing of some hundreds of lines whose draw order is not the order of their
|
||||
/// handles, a selection of a few lines and the selection of every line.
|
||||
#[test]
|
||||
fn a_small_and_a_large_selection_leave_out_the_same_objects() {
|
||||
let Sheet { mut s, shown, hidden, a, b } = sheet();
|
||||
// A line on the sheet, on the layer the first viewport freezes: no viewport hides it.
|
||||
let on_sheet = line(&mut s, [1.0, 1.0], [2.0, 1.0]);
|
||||
hide(&mut s, on_sheet);
|
||||
assert!(!s.doc().unwrap().model.contains(on_sheet), "the line must be on the sheet");
|
||||
enter(&mut s, &b);
|
||||
let more: Vec<Handle> = (0..400).map(|i| line(&mut s, [f64::from(i), 5.0], [f64::from(i), 6.0])).collect();
|
||||
// Every second one of them goes on the layer the first viewport freezes.
|
||||
let frozen: Vec<String> = more.iter().step_by(2).map(|h| h.hex()).collect();
|
||||
s.execute("properties.set", &json!({ "handles": frozen, "layer": "Hidden" })).unwrap();
|
||||
// The frozen line made last goes to the back: it is now the first object in draw order.
|
||||
s.execute("draworder", &json!({ "handles": [more[398].hex()], "order": "back" })).unwrap();
|
||||
assert_eq!(s.doc().unwrap().model.iter().next().map(|e| e.handle), Some(more[398]));
|
||||
let all: Vec<Handle> = [shown, hidden].into_iter().chain(more.iter().copied()).collect();
|
||||
let drawn: Vec<Handle> = std::iter::once(shown).chain(more.iter().copied().skip(1).step_by(2)).collect();
|
||||
assert_eq!(s.doc().unwrap().model.len(), all.len());
|
||||
|
||||
enter(&mut s, &a);
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
assert_eq!(s.selection(), [shown], "two selected lines of some hundreds");
|
||||
s.set_selection(vec![hidden, on_sheet, more[0], more[1]]);
|
||||
assert_eq!(s.selection(), [on_sheet, more[1]], "a line on the sheet is never left out");
|
||||
s.set_selection(all.clone());
|
||||
assert_eq!(s.selection(), drawn, "every line selected");
|
||||
assert_eq!(s.state().unwrap().selection, all, "every line must still be selected");
|
||||
|
||||
// The viewport that freezes nothing has them all, few or many.
|
||||
enter(&mut s, &b);
|
||||
s.set_selection(vec![shown, hidden]);
|
||||
assert_eq!(s.selection(), [shown, hidden]);
|
||||
s.set_selection(all.clone());
|
||||
assert_eq!(s.selection(), all);
|
||||
}
|
||||
@@ -11,6 +11,8 @@ workspace = true
|
||||
[dependencies]
|
||||
cadcraft-geom = { workspace = true }
|
||||
craft-dxf = { workspace = true }
|
||||
craft-font-catalog = { workspace = true }
|
||||
craft-shx = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
harfrust = { workspace = true }
|
||||
unicode-bidi = { workspace = true }
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! empty, `CRAFT_FONTS` is empty and the build is unchanged. It only reads the local checkout
|
||||
//! (no network). A bad checkout is a warning, or an error with `CRAFT_FONTS_REQUIRED=1`.
|
||||
//!
|
||||
//! On wasm32 it embeds only BIZ UDPGothic Regular, the `Arab` and `Geor` faces and the `Thai`
|
||||
//! On wasm32 it embeds only `BIZ UDPGothic` Regular, the `Arab` and `Geor` faces and the `Thai`
|
||||
//! Regular faces (about 6.1 MB), to keep the web build within hosting limits (Cloudflare Pages:
|
||||
//! 25 MiB per file). The web build has no system fonts, so these are its only fallback for
|
||||
//! Japanese, Arabic-script, Georgian and Thai text.
|
||||
@@ -22,7 +22,7 @@ fn main() {
|
||||
println!("cargo::error=CRAFT_FONTS_DIR={}: {}", one_line(&dir.display().to_string()), one_line(&e));
|
||||
}
|
||||
Err(e) => {
|
||||
println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {}", one_line(&dir.display().to_string()), one_line(&e))
|
||||
println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {}", one_line(&dir.display().to_string()), one_line(&e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn visual_runs(chars: &[char], base: Option<bool>) -> Vec<(Range<usize>, boo
|
||||
runs.into_iter()
|
||||
.filter(|r| !r.is_empty())
|
||||
.map(|r| {
|
||||
let rtl = levels.get(r.start).is_some_and(|l| l.is_rtl());
|
||||
let rtl = levels.get(r.start).is_some_and(Level::is_rtl);
|
||||
(char_at(r.start)..char_at(r.end), rtl)
|
||||
})
|
||||
.collect()
|
||||
|
||||
+50
-49
@@ -79,80 +79,81 @@ pub(crate) fn shape(primary: Option<&Face>, s: &str, height: f64, width_factor:
|
||||
|
||||
/// Lay out decoded directional runs, keeping advances and decoration spans for empty glyphs.
|
||||
fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64, width_factor: f64, oblique: f64, base_rtl: Option<bool>) -> Shaped {
|
||||
let h = if height.is_finite() && height > 0.0 { height } else { 1.0 };
|
||||
let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 };
|
||||
let normalized_height = if height.is_finite() && height > 0.0 { height } else { 1.0 };
|
||||
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 sc = h / stroke::CAP;
|
||||
let cs: Vec<char> = chars.iter().map(|c| c.0).collect();
|
||||
let flags = |i: usize| chars.get(i).map(|c| (c.1, c.2)).unwrap_or((false, false));
|
||||
let mut out = Shaped::default();
|
||||
let stroke_scale = normalized_height / stroke::CAP;
|
||||
let characters: Vec<char> = chars.iter().map(|character| character.0).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;
|
||||
let mut spans: Vec<(f64, f64, bool, bool)> = Vec::new();
|
||||
let mut x = 0.0;
|
||||
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(&cs, base_rtl) {
|
||||
let mut pieces = itemize(&cs, run, primary);
|
||||
for (run, rtl) in bidi::visual_runs(&characters, base_rtl) {
|
||||
let mut pieces = itemize(&characters, run, primary);
|
||||
if rtl {
|
||||
pieces.reverse();
|
||||
}
|
||||
for (src, r) in pieces {
|
||||
for (src, range) in pieces {
|
||||
match &src {
|
||||
Src::Hidden => {}
|
||||
Src::Stroke | Src::Missing => {
|
||||
let idx: Vec<usize> = if rtl { r.rev().collect() } else { r.collect() };
|
||||
for i in idx {
|
||||
let c = cs.get(i).copied().unwrap_or(' ');
|
||||
let c = if rtl { bidi::mirror(c) } else { c };
|
||||
match (&src, stroke::glyph(c)) {
|
||||
(Src::Stroke, Some((_, spec))) => crate::draw_stroke_glyph(&mut out, spec, x, sc, wf, shear),
|
||||
(Src::Missing, _) => crate::missing_glyph_box(&mut out, x, h, sc * wf),
|
||||
let indices: Vec<usize> = if rtl { range.rev().collect() } else { range.collect() };
|
||||
for index in indices {
|
||||
let character = characters.get(index).copied().unwrap_or(' ');
|
||||
let character = if rtl { bidi::mirror(character) } else { character };
|
||||
match (&src, stroke::glyph(character)) {
|
||||
(Src::Stroke, Some((_, spec))) => {
|
||||
crate::draw_stroke_glyph(&mut shaped, spec, pen_x, stroke_scale, scale_x, shear);
|
||||
}
|
||||
(Src::Missing, _) => crate::missing_glyph_box(&mut shaped, pen_x, normalized_height, stroke_scale * scale_x),
|
||||
_ => {}
|
||||
}
|
||||
let adv = crate::char_advance(c) * h * wf;
|
||||
let (u, o) = flags(i);
|
||||
spans.push((x, x + adv, u, o));
|
||||
x += adv;
|
||||
let advance = crate::char_advance(character) * normalized_height * scale_x;
|
||||
let (underline, overline) = flags(index);
|
||||
spans.push((pen_x, pen_x + advance, underline, overline));
|
||||
pen_x += advance;
|
||||
stroke_last = true;
|
||||
}
|
||||
}
|
||||
Src::Face(face) => {
|
||||
let glyphs = shape_run(face, &cs, r.clone(), rtl);
|
||||
let glyphs = shape_run(face, &characters, range.clone(), rtl);
|
||||
// Right-to-left runs stay outlines only: their glyphs come in display order
|
||||
// and include ligatures (lam-alef) that stand for several characters.
|
||||
let shows = if rtl { Vec::new() } else { glyph_chars(face, &cs, &glyphs, r.end) };
|
||||
for (n, g) in glyphs.iter().enumerate() {
|
||||
let outline = ttf::glyph_by_id(face, g.gid);
|
||||
let k = h / outline.cap * wf;
|
||||
let dy = g.dy * h / outline.cap;
|
||||
if let Some(mut contours) = ttf::place_glyph_budgeted(&outline, x + g.dx * k, h, wf, shear, &mut points_left) {
|
||||
for p in contours.iter_mut().flatten() {
|
||||
*p += Vec2::new(dy * shear, dy);
|
||||
let shows = if rtl { Vec::new() } else { glyph_chars(face, &characters, &glyphs, range.end) };
|
||||
for (n, glyph) in glyphs.iter().enumerate() {
|
||||
let outline = ttf::glyph_by_id(face, glyph.gid);
|
||||
let glyph_scale = normalized_height / outline.cap * scale_x;
|
||||
let offset_y = glyph.dy * normalized_height / outline.cap;
|
||||
if let Some(mut contours) =
|
||||
ttf::place_glyph_budgeted(&outline, pen_x + glyph.dx * glyph_scale, normalized_height, scale_x, shear, &mut points_left)
|
||||
{
|
||||
for point in contours.iter_mut().flatten() {
|
||||
*point += Vec2::new(offset_y * shear, offset_y);
|
||||
}
|
||||
let origin = Vec2::new(x + g.dx * k + dy * shear, dy);
|
||||
let text = shows
|
||||
.get(n)
|
||||
.copied()
|
||||
.flatten()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.and_then(|c| ttf::text_glyph_at(&outline, c, origin, h / outline.cap, wf, shear));
|
||||
out.push_glyph(contours, text);
|
||||
let origin = Vec2::new(pen_x + glyph.dx * glyph_scale + offset_y * shear, offset_y);
|
||||
let text = shows.get(n).copied().flatten().filter(|character| !character.is_whitespace()).and_then(|character| {
|
||||
ttf::text_glyph_at(&outline, character, origin, normalized_height / outline.cap, scale_x, shear)
|
||||
});
|
||||
shaped.push_glyph(contours, text);
|
||||
}
|
||||
let adv = g.advance * k;
|
||||
let (u, o) = flags(g.cluster);
|
||||
spans.push((x, x + adv, u, o));
|
||||
x += adv;
|
||||
let advance = glyph.advance * glyph_scale;
|
||||
let (underline, overline) = flags(glyph.cluster);
|
||||
spans.push((pen_x, pen_x + advance, underline, overline));
|
||||
pen_x += advance;
|
||||
stroke_last = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.strokes.extend(crate::decorations(&spans, h));
|
||||
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`.
|
||||
out.width = if stroke_last { (x - stroke::GAP * sc * wf).max(0.0) } else { x };
|
||||
out
|
||||
shaped.width = if stroke_last { (pen_x - stroke::GAP * stroke_scale * scale_x).max(0.0) } else { pen_x };
|
||||
shaped
|
||||
}
|
||||
|
||||
/// Split a logical-order run into pieces by what draws each character. Joiners and combining
|
||||
@@ -333,7 +334,7 @@ mod tests {
|
||||
assert!(shaped.text.is_empty());
|
||||
|
||||
let underlined = shape(Some(&face), "%%u ", 1.0, 1.0, 0.0, None).expect("shapes decorated empty glyph");
|
||||
assert_eq!(underlined.width, shaped.width);
|
||||
assert!((underlined.width - shaped.width).abs() < f64::EPSILON);
|
||||
assert!(underlined.glyphs.is_empty());
|
||||
assert!(underlined.text.is_empty());
|
||||
assert!(!underlined.strokes.is_empty(), "decoration spans survive an empty outline");
|
||||
@@ -350,7 +351,7 @@ mod tests {
|
||||
assert!((crate::line_width(s, 1.0, 1.0) - sh.width).abs() < 1e-9);
|
||||
let digits: Vec<f64> = sh.strokes.iter().filter(|st| !(st.len() == 5 && st.first() == st.last())).flatten().map(|p| p.x).collect();
|
||||
assert!(!digits.is_empty());
|
||||
let (lo, hi) = (digits.iter().cloned().fold(f64::MAX, f64::min), digits.iter().cloned().fold(f64::MIN, f64::max));
|
||||
let (lo, hi) = (digits.iter().copied().fold(f64::MAX, f64::min), digits.iter().copied().fold(f64::MIN, f64::max));
|
||||
assert!(lo > 0.2 * sh.width && hi < 0.8 * sh.width, "digits between the words: {lo}..{hi} of {}", sh.width);
|
||||
}
|
||||
|
||||
@@ -382,7 +383,7 @@ mod tests {
|
||||
|
||||
fn nominal(f: &Face, c: char) -> Option<u32> {
|
||||
use skrifa::MetadataProvider;
|
||||
f.font().and_then(|font| font.charmap().map(c)).map(|g| g.to_u32())
|
||||
f.font().and_then(|font| font.charmap().map(c)).map(skrifa::GlyphId::to_u32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -407,7 +408,7 @@ mod tests {
|
||||
assert!(!sh.strokes.iter().any(|s| s.len() == 5 && s.first() == s.last()), "no missing-glyph boxes");
|
||||
// The ASCII digits are stroke glyphs in the middle of the line.
|
||||
let stroke_x: Vec<f64> = sh.strokes.iter().flatten().map(|p| p.x).collect();
|
||||
let (lo, hi) = (stroke_x.iter().cloned().fold(f64::MAX, f64::min), stroke_x.iter().cloned().fold(f64::MIN, f64::max));
|
||||
let (lo, hi) = (stroke_x.iter().copied().fold(f64::MAX, f64::min), stroke_x.iter().copied().fold(f64::MIN, f64::max));
|
||||
assert!(lo > 0.2 * sh.width && hi < 0.8 * sh.width, "digits between the words: {lo}..{hi} of {}", sh.width);
|
||||
assert!((crate::line_width("قیمت 25 تومان", 1.0, 1.0) - sh.width).abs() < 1e-9);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Fonts from the optional craft-fonts build input (<https://github.com/storytold/craft-fonts>).
|
||||
//!
|
||||
//! Built with `CRAFT_FONTS_DIR=<craft-fonts checkout>`, `build.rs` embeds the fonts listed in its
|
||||
//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular, the Arabic and Georgian faces and
|
||||
//! `fonts/manifest.txt` (web builds: only `BIZ UDPGothic` Regular, the `Arab` and `Geor` faces and
|
||||
//! the Thai Regular faces). Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`])
|
||||
//! lists the embedded fonts with the installed ones, under [`CraftFont::stem`]. A text style
|
||||
//! can name one (`BIZ UDPGothic`), and they are fallbacks for characters a text's font lacks.
|
||||
|
||||
+65
-62
@@ -46,24 +46,24 @@ pub struct Run {
|
||||
/// Replace `%%` control codes: `%%d` degree, `%%p` plus/minus, `%%c` diameter, `%%%` percent,
|
||||
/// `%%nnn` character code, and `\U+XXXX` Unicode escapes. Underline/overline toggles (`%%u`,
|
||||
/// `%%o`) are returned as flags per character.
|
||||
pub fn decode_controls(s: &str) -> Vec<(char, bool, bool)> {
|
||||
let mut out = Vec::with_capacity(s.len());
|
||||
pub fn decode_controls(text: &str) -> Vec<(char, bool, bool)> {
|
||||
let mut out = Vec::with_capacity(text.len());
|
||||
let mut under = false;
|
||||
let mut over = false;
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
let c = chars.get(i).copied().unwrap_or(' ');
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let mut index = 0;
|
||||
while index < chars.len() {
|
||||
let character = chars.get(index).copied().unwrap_or(' ');
|
||||
// `\U+XXXX`: a Unicode character by its code.
|
||||
if c == '\\'
|
||||
&& let Some(u) = unicode_escape(&chars, i)
|
||||
if character == '\\'
|
||||
&& let Some(u) = unicode_escape(&chars, index)
|
||||
{
|
||||
out.push((u, under, over));
|
||||
i += 7;
|
||||
index += 7;
|
||||
continue;
|
||||
}
|
||||
if c == '%' && chars.get(i + 1) == Some(&'%') {
|
||||
let code = chars.get(i + 2).copied().unwrap_or(' ');
|
||||
if character == '%' && chars.get(index + 1) == Some(&'%') {
|
||||
let code = chars.get(index + 2).copied().unwrap_or(' ');
|
||||
match code.to_ascii_lowercase() {
|
||||
'd' => out.push(('°', under, over)),
|
||||
'p' => out.push(('±', under, over)),
|
||||
@@ -71,24 +71,24 @@ pub fn decode_controls(s: &str) -> Vec<(char, bool, bool)> {
|
||||
'%' => out.push(('%', under, over)),
|
||||
'u' => under = !under,
|
||||
'o' => over = !over,
|
||||
d if d.is_ascii_digit() => {
|
||||
let digits: String = chars.iter().skip(i + 2).take(3).take_while(|c| c.is_ascii_digit()).collect();
|
||||
let n: u32 = digits.parse().unwrap_or(32);
|
||||
out.push((char::from_u32(n).unwrap_or('?'), under, over));
|
||||
i += 2 + digits.len();
|
||||
digit if digit.is_ascii_digit() => {
|
||||
let digits: String = chars.iter().skip(index + 2).take(3).take_while(|character| character.is_ascii_digit()).collect();
|
||||
let codepoint: u32 = digits.parse().unwrap_or(32);
|
||||
out.push((char::from_u32(codepoint).unwrap_or('?'), under, over));
|
||||
index += 2 + digits.len();
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
out.push(('%', under, over));
|
||||
i += 1;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
i += 3;
|
||||
index += 3;
|
||||
continue;
|
||||
}
|
||||
out.push((c, under, over));
|
||||
i += 1;
|
||||
out.push((character, under, over));
|
||||
index += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -174,81 +174,84 @@ pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Sh
|
||||
|
||||
/// [`shape_stroke`] in the direction `base_rtl` (`None`: that of the line's first strong
|
||||
/// character).
|
||||
pub fn shape_stroke_dir(s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option<bool>) -> Shaped {
|
||||
let h = if height.is_finite() && height > 0.0 { height } else { 1.0 };
|
||||
let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 };
|
||||
let sc = h / stroke::CAP;
|
||||
pub fn shape_stroke_dir(text: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option<bool>) -> Shaped {
|
||||
let normalized_height = if height.is_finite() && height > 0.0 { height } else { 1.0 };
|
||||
let scale_x = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 };
|
||||
let stroke_scale = normalized_height / stroke::CAP;
|
||||
let shear = oblique.tan().clamp(-10.0, 10.0);
|
||||
let mut out = Shaped::default();
|
||||
let mut x = 0.0;
|
||||
let mut pen_x = 0.0;
|
||||
let mut under_start: Option<f64> = None;
|
||||
let mut over_start: Option<f64> = None;
|
||||
let mut gap = stroke::GAP * sc * wf;
|
||||
let mut gap = stroke::GAP * stroke_scale * scale_x;
|
||||
// Retained fallback-outline points over the line, as the TrueType path caps them: a short string
|
||||
// repeating one detailed glyph would otherwise copy its outline per occurrence.
|
||||
let mut points_left = ttf::MAX_SHAPED_POINTS;
|
||||
// The simple path lays a line out left to right: one asked to run right to left goes through
|
||||
// the bidi path even without right-to-left letters.
|
||||
if (complex::needed(s) || base_rtl == Some(true))
|
||||
&& let Some(sh) = complex::shape(None, s, h, wf, oblique, base_rtl)
|
||||
if (complex::needed(text) || base_rtl == Some(true))
|
||||
&& let Some(sh) = complex::shape(None, text, normalized_height, scale_x, oblique, base_rtl)
|
||||
{
|
||||
return sh;
|
||||
}
|
||||
for (c, under, over) in decode_controls(s) {
|
||||
if bidi::is_format_control(c) {
|
||||
for (character, under, over) in decode_controls(text) {
|
||||
if bidi::is_format_control(character) {
|
||||
continue;
|
||||
}
|
||||
let mut adv = char_advance(c) * h * wf;
|
||||
gap = stroke::GAP * sc * wf;
|
||||
match stroke::glyph(c) {
|
||||
Some((_, spec)) => draw_stroke_glyph(&mut out, spec, x, sc, wf, shear),
|
||||
None if !c.is_whitespace() => match ttf::fallback_glyph(c) {
|
||||
Some(g) => {
|
||||
let (y, scale) = stroke_fallback_metrics(&g, c, h);
|
||||
let contours = match points_left.checked_sub(g.points) {
|
||||
let mut adv = char_advance(character) * normalized_height * scale_x;
|
||||
gap = stroke::GAP * stroke_scale * scale_x;
|
||||
match stroke::glyph(character) {
|
||||
Some((_, spec)) => draw_stroke_glyph(&mut out, spec, pen_x, stroke_scale, scale_x, shear),
|
||||
None if !character.is_whitespace() => match ttf::fallback_glyph(character) {
|
||||
Some(glyph) => {
|
||||
let (origin_y, scale) = stroke_fallback_metrics(&glyph, character, normalized_height);
|
||||
let contours = match points_left.checked_sub(glyph.points) {
|
||||
Some(rest) => {
|
||||
points_left = rest;
|
||||
ttf::place_glyph_at(&g, Vec2::new(x, y), scale, wf, shear)
|
||||
ttf::place_glyph_at(&glyph, Vec2::new(pen_x, origin_y), scale, scale_x, shear)
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
if !contours.is_empty() {
|
||||
out.push_glyph(contours, ttf::text_glyph_at(&g, c, Vec2::new(x + y * shear, y), scale, wf, shear));
|
||||
out.push_glyph(
|
||||
contours,
|
||||
ttf::text_glyph_at(&glyph, character, Vec2::new(pen_x + origin_y * shear, origin_y), scale, scale_x, shear),
|
||||
);
|
||||
}
|
||||
adv = g.advance * scale * wf;
|
||||
adv = glyph.advance * scale * scale_x;
|
||||
gap = 0.0;
|
||||
}
|
||||
None => missing_glyph_box(&mut out, x, h, sc * wf),
|
||||
None => missing_glyph_box(&mut out, pen_x, normalized_height, stroke_scale * scale_x),
|
||||
},
|
||||
None => {}
|
||||
}
|
||||
// Decorations.
|
||||
match (under, under_start) {
|
||||
(true, None) => under_start = Some(x),
|
||||
(true, None) => under_start = Some(pen_x),
|
||||
(false, Some(sx)) => {
|
||||
out.strokes.push(vec![Vec2::new(sx, -h * 0.2), Vec2::new(x, -h * 0.2)]);
|
||||
out.strokes.push(vec![Vec2::new(sx, -normalized_height * 0.2), Vec2::new(pen_x, -normalized_height * 0.2)]);
|
||||
under_start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match (over, over_start) {
|
||||
(true, None) => over_start = Some(x),
|
||||
(true, None) => over_start = Some(pen_x),
|
||||
(false, Some(sx)) => {
|
||||
out.strokes.push(vec![Vec2::new(sx, h * 1.2), Vec2::new(x, h * 1.2)]);
|
||||
out.strokes.push(vec![Vec2::new(sx, normalized_height * 1.2), Vec2::new(pen_x, normalized_height * 1.2)]);
|
||||
over_start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
x += adv;
|
||||
pen_x += adv;
|
||||
}
|
||||
// The stroke font's gap after the last character isn't part of the line; a fallback glyph
|
||||
// has none.
|
||||
let end = (x - gap).max(0.0);
|
||||
let end = (pen_x - gap).max(0.0);
|
||||
if let Some(sx) = under_start {
|
||||
out.strokes.push(vec![Vec2::new(sx, -h * 0.2), Vec2::new(end, -h * 0.2)]);
|
||||
out.strokes.push(vec![Vec2::new(sx, -normalized_height * 0.2), Vec2::new(end, -normalized_height * 0.2)]);
|
||||
}
|
||||
if let Some(sx) = over_start {
|
||||
out.strokes.push(vec![Vec2::new(sx, h * 1.2), Vec2::new(end, h * 1.2)]);
|
||||
out.strokes.push(vec![Vec2::new(sx, normalized_height * 1.2), Vec2::new(end, normalized_height * 1.2)]);
|
||||
}
|
||||
out.width = end;
|
||||
out
|
||||
@@ -360,7 +363,7 @@ impl TextFont {
|
||||
if builtin {
|
||||
return TextFont::Stroke;
|
||||
}
|
||||
ttf::find(alt_main).map(TextFont::Outline).unwrap_or(TextFont::Stroke)
|
||||
ttf::find(alt_main).map_or(TextFont::Stroke, TextFont::Outline)
|
||||
}
|
||||
pub fn is_outline(&self) -> bool {
|
||||
matches!(self, TextFont::Outline(_))
|
||||
@@ -503,7 +506,7 @@ pub fn shape_line_dir(font: &TextFont, s: &str, height: f64, width_factor: f64,
|
||||
shape_stroke_dir(s, height, width_factor, oblique, base_rtl)
|
||||
}
|
||||
|
||||
/// Single-line TEXT (and attributes) runs left to right, as AutoCAD lays it out: neutral
|
||||
/// Single-line TEXT (and attributes) runs left to right, as `AutoCAD` lays it out: neutral
|
||||
/// characters before a right-to-left word ("- " in "- פרוייקט") stay on its left (#2500).
|
||||
const TEXT_BASE_RTL: Option<bool> = Some(false);
|
||||
|
||||
@@ -591,7 +594,7 @@ pub fn baseline_start(font: &TextFont, s: &str, p: &TextParams) -> Vec2 {
|
||||
}
|
||||
|
||||
/// How far below the baseline a bottom-justified text's alignment point lies: a third of the
|
||||
/// height for the stroke font (as AutoCAD places it with SHX fonts), the face's descent for an
|
||||
/// height for the stroke font (as `AutoCAD` places it with SHX fonts), the face's descent for an
|
||||
/// outline font (#2229).
|
||||
fn bottom_depth(font: &TextFont, height: f64) -> f64 {
|
||||
match font {
|
||||
@@ -602,12 +605,12 @@ fn bottom_depth(font: &TextFont, height: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The vertical middle of shaped text's ink (its strokes and outlines), above the baseline;
|
||||
/// `None` when it draws nothing. A Middle (M) text is centred there: AutoCAD centres it on the
|
||||
/// `None` when it draws nothing. A Middle (M) text is centred there: `AutoCAD` centres it on the
|
||||
/// string's own extents, descenders included, not at half the height (#2229).
|
||||
fn ink_middle(sh: &Shaped) -> Option<f64> {
|
||||
let ys = sh.strokes.iter().flatten().chain(sh.glyphs.iter().flatten().flatten()).map(|q| q.y).filter(|y| y.is_finite());
|
||||
let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y)));
|
||||
(lo <= hi).then_some((lo + hi) / 2.0)
|
||||
(lo <= hi).then_some(f64::midpoint(lo, hi))
|
||||
}
|
||||
|
||||
/// The offset of a line's baseline start from its alignment point, for justification `h`/`v`.
|
||||
@@ -714,7 +717,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A TEXT that starts with neutral characters before a Hebrew word ("- פרוייקט") keeps them
|
||||
/// on the left, as AutoCAD draws it; the line's own direction (first strong character) would
|
||||
/// on the left, as `AutoCAD` draws it; the line's own direction (first strong character) would
|
||||
/// put the dash on the right (#2500).
|
||||
#[test]
|
||||
fn text_runs_left_to_right_whatever_its_first_strong_character() {
|
||||
@@ -942,7 +945,7 @@ mod justify_tests {
|
||||
ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y)))
|
||||
}
|
||||
|
||||
/// A Middle (M) text is centred on its own ink, descenders included, as AutoCAD centres it,
|
||||
/// A Middle (M) text is centred on its own ink, descenders included, as `AutoCAD` centres it,
|
||||
/// not at half the height: lowercase and descenders move the baseline (#2229).
|
||||
#[test]
|
||||
fn a_middle_text_is_centred_on_its_ink() {
|
||||
@@ -951,11 +954,11 @@ mod justify_tests {
|
||||
for s in ["ABC 123", "gjpqy", "Tg 1234 ABC", "ace"] {
|
||||
let (sh, start) = placed(&font, s, Align::Middle, VAlign::Baseline);
|
||||
let (lo, hi) = ink_y(&sh);
|
||||
assert!(((lo + hi) / 2.0).abs() < 1e-9, "{s}: ink {lo}..{hi} is centred on the alignment point");
|
||||
assert!((f64::midpoint(lo, hi)).abs() < 1e-9, "{s}: ink {lo}..{hi} is centred on the alignment point");
|
||||
// The insertion point a DWG keeps (group 10) is the baseline start, below the ink's
|
||||
// middle by as much as the unplaced text's ink middle is above its baseline.
|
||||
let (lo0, hi0) = ink_y(&shape_line(&font, s, H, 1.0, 0.0));
|
||||
assert!((start.y + (lo0 + hi0) / 2.0).abs() < 1e-9, "{s}: baseline start {start:?}");
|
||||
assert!((start.y + f64::midpoint(lo0, hi0)).abs() < 1e-9, "{s}: baseline start {start:?}");
|
||||
baselines.push((s, start.y));
|
||||
}
|
||||
// Capitals and digits span the height, so they stay at half of it.
|
||||
@@ -975,7 +978,7 @@ mod justify_tests {
|
||||
assert!((start.y + H / 2.0).abs() < 1e-9, "{start:?}");
|
||||
}
|
||||
|
||||
/// With the stroke font (as with AutoCAD's SHX fonts), a bottom-justified text's baseline is
|
||||
/// With the stroke font (as with `AutoCAD`'s SHX fonts), a bottom-justified text's baseline is
|
||||
/// a third of the height above its alignment point, and Middle Center still uses half.
|
||||
#[test]
|
||||
fn stroke_font_bottom_and_middle_center_are_unchanged() {
|
||||
@@ -989,7 +992,7 @@ mod justify_tests {
|
||||
}
|
||||
|
||||
/// With a TrueType font, a bottom-justified text's alignment point is at the face's descent,
|
||||
/// where its descenders end, as AutoCAD places it (#2229: Arial's is 0.296 of the height).
|
||||
/// where its descenders end, as `AutoCAD` places it (#2229: Arial's is 0.296 of the height).
|
||||
/// Uses the first of these common fonts that is installed (Windows, macOS and Linux each have
|
||||
/// one); skips without any.
|
||||
#[test]
|
||||
@@ -1009,6 +1012,6 @@ mod justify_tests {
|
||||
// And Middle centres the ink, as with the stroke font.
|
||||
let (sh, _) = placed(&font, "Tg 1234 ABC", Align::Middle, VAlign::Baseline);
|
||||
let (lo, hi) = ink_y(&sh);
|
||||
assert!(((lo + hi) / 2.0).abs() < 1e-9, "{name}: {lo}..{hi}");
|
||||
assert!((f64::midpoint(lo, hi)).abs() < 1e-9, "{name}: {lo}..{hi}");
|
||||
}
|
||||
}
|
||||
|
||||
+157
-342
@@ -12,79 +12,30 @@ pub fn plain_mtext(s: &str) -> String {
|
||||
let s = unescape_codes(s);
|
||||
let s = s.as_ref();
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
match c {
|
||||
'\\' => {
|
||||
let code = chars.get(i + 1).copied().unwrap_or(' ');
|
||||
match code {
|
||||
'P' => {
|
||||
out.push('\n');
|
||||
i += 2;
|
||||
}
|
||||
'N' => {
|
||||
out.push('\n');
|
||||
i += 2;
|
||||
}
|
||||
'~' => {
|
||||
out.push(' ');
|
||||
i += 2;
|
||||
}
|
||||
'\\' | '{' | '}' => {
|
||||
out.push(code);
|
||||
i += 2;
|
||||
}
|
||||
'S' => {
|
||||
// \Snum^den; \Snum/den; \Snum#den;
|
||||
let mut j = i + 2;
|
||||
let mut stack = String::new();
|
||||
while let Some(&ch) = chars.get(j) {
|
||||
if ch == ';' {
|
||||
break;
|
||||
}
|
||||
stack.push(match ch {
|
||||
'^' | '#' => '/',
|
||||
c => c,
|
||||
});
|
||||
j += 1;
|
||||
}
|
||||
// "6\S1/2;" reads as "6 1/2".
|
||||
if out.chars().last().is_some_and(|c| c.is_ascii_digit()) && stack.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(stack.trim_end_matches('/'));
|
||||
i = j + 1;
|
||||
}
|
||||
'L' | 'l' | 'O' | 'o' | 'K' | 'k' => i += 2,
|
||||
// `\U+XXXX`: a character by its Unicode code, as the layout reads it.
|
||||
'U' if crate::unicode_escape(&chars, i).is_some() => {
|
||||
if let Some(u) = crate::unicode_escape(&chars, i) {
|
||||
out.push(u);
|
||||
}
|
||||
i += 7;
|
||||
}
|
||||
// Codes with an argument terminated by ';' (\f, \F, \H, \W, \Q, \T, \A, \C, \c, \p).
|
||||
_ if takes_arg(code) => {
|
||||
let mut j = i + 2;
|
||||
while let Some(&ch) = chars.get(j) {
|
||||
if ch == ';' {
|
||||
break;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
// An unknown code has no argument: drop the backslash and the code only.
|
||||
_ => i += 2,
|
||||
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens};
|
||||
for token in Tokens::new(s, StackMode::Plain) {
|
||||
match token {
|
||||
Token::Control('P' | 'N') => out.push('\n'),
|
||||
Token::Control('~') => out.push(' '),
|
||||
Token::Control(c @ ('\\' | '{' | '}')) => out.push(c),
|
||||
Token::Stack(raw) => {
|
||||
let stack: String = raw.chars().map(|c| if matches!(c, '^' | '#') { '/' } else { c }).collect();
|
||||
if out.chars().last().is_some_and(|c| c.is_ascii_digit()) && stack.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(stack.trim_end_matches('/'));
|
||||
}
|
||||
// An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD shows it:
|
||||
// keep the backslash and read the code as text. A trailing lone backslash is dropped.
|
||||
Token::Unknown(c) => {
|
||||
out.push('\\');
|
||||
if c != '\r' {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
'{' | '}' => i += 1,
|
||||
'\r' => i += 1,
|
||||
_ => {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
Token::Char('\r') => {}
|
||||
Token::Char(c) => out.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -225,11 +176,8 @@ const MAX_ATOMS: usize = 200_000;
|
||||
/// Scale of stacked text relative to the surrounding text.
|
||||
const STACK_SCALE: f64 = 0.7;
|
||||
|
||||
/// Codes that take an argument terminated by `;` (besides `\S`, which has its own scan). Any
|
||||
/// other code stands alone, so a missing `;` must not swallow the text after it.
|
||||
pub(crate) fn takes_arg(code: char) -> bool {
|
||||
matches!(code, 'f' | 'F' | 'H' | 'W' | 'Q' | 'T' | 'A' | 'C' | 'c' | 'p')
|
||||
}
|
||||
// Shared DXF escape handling and parameterized-command classification.
|
||||
pub(crate) use craft_dxf::mtext::unescape_codes;
|
||||
|
||||
/// The line-spacing factor to lay out with: AutoCAD's 0.25..=4 range, 1 for a missing or
|
||||
/// non-finite value.
|
||||
@@ -237,90 +185,6 @@ pub(crate) fn sane_line_spacing(v: f64) -> f64 {
|
||||
if v.is_finite() && v > 0.0 { v.clamp(0.25, 4.0) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Four hex digits at `chars[at..at + 4]`.
|
||||
fn hex4(chars: &[char], at: usize) -> Option<u32> {
|
||||
let digits = chars.get(at..at.checked_add(4)?)?;
|
||||
digits.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?))
|
||||
}
|
||||
|
||||
/// Push a decoded character so that the tokenizers read it as text, never as markup.
|
||||
fn push_literal(out: &mut String, c: char) {
|
||||
if matches!(c, '\\' | '{' | '}') {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
|
||||
/// Decode `\U+hhhh` (one UTF-16 unit; a surrogate pair gives one character, a lone surrogate
|
||||
/// U+FFFD) and `\M+nhhhh` (double-byte East Asian characters) to the characters they stand
|
||||
/// for. Malformed escapes are left for the tokenizers, which drop the backslash and the code.
|
||||
/// An escaped backslash (`\\U+0041`) is not an escape.
|
||||
pub(crate) fn unescape_codes(s: &str) -> std::borrow::Cow<'_, str> {
|
||||
if !s.contains("\\U+") && !s.contains("\\M+") {
|
||||
return std::borrow::Cow::Borrowed(s);
|
||||
}
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let (n, plus) = (chars.get(i + 1).copied(), chars.get(i + 2).copied());
|
||||
if n == Some('U') && plus == Some('+') {
|
||||
if let Some(unit) = hex4(&chars, i + 3) {
|
||||
i += 7;
|
||||
let low = |at: usize| {
|
||||
(chars.get(at) == Some(&'\\') && chars.get(at + 1) == Some(&'U') && chars.get(at + 2) == Some(&'+'))
|
||||
.then(|| hex4(&chars, at + 3))
|
||||
.flatten()
|
||||
.filter(|u| (0xDC00..0xE000).contains(u))
|
||||
};
|
||||
let ch = if (0xD800..0xDC00).contains(&unit) {
|
||||
match low(i) {
|
||||
Some(lo) => {
|
||||
i += 7;
|
||||
char::from_u32(0x10000 + ((unit - 0xD800) << 10) + (lo - 0xDC00))
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
} else {
|
||||
char::from_u32(unit)
|
||||
};
|
||||
push_literal(&mut out, ch.unwrap_or('\u{fffd}'));
|
||||
continue;
|
||||
}
|
||||
} else if n == Some('M') && plus == Some('+') && chars.get(i + 3).is_some_and(char::is_ascii_digit) && hex4(&chars, i + 4).is_some() {
|
||||
push_literal(&mut out, craft_dxf::mif_escape_at(&chars, i).unwrap_or('\u{fffd}'));
|
||||
i += 8;
|
||||
continue;
|
||||
}
|
||||
// Any other backslash pair stays as it is (and an escaped backslash stays one).
|
||||
out.push('\\');
|
||||
i += 1;
|
||||
if let Some(&next) = chars.get(i) {
|
||||
out.push(next);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(out)
|
||||
}
|
||||
|
||||
fn arg(chars: &[char], from: usize) -> (String, usize) {
|
||||
let mut j = from;
|
||||
let mut a = String::new();
|
||||
while let Some(&ch) = chars.get(j) {
|
||||
if ch == ';' {
|
||||
return (a, j + 1);
|
||||
}
|
||||
a.push(ch);
|
||||
j += 1;
|
||||
}
|
||||
(a, j)
|
||||
}
|
||||
|
||||
fn num(a: &str) -> Option<f64> {
|
||||
a.trim().parse::<f64>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
@@ -358,7 +222,7 @@ fn font_switch(a: &str) -> Option<TextFont> {
|
||||
|
||||
/// Parse MTEXT contents into words, spaces and paragraph breaks with their formats.
|
||||
fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
|
||||
let chars: Vec<char> = contents.chars().collect();
|
||||
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens, split_stack};
|
||||
let h_min = base.height * 1e-3;
|
||||
let h_max = if (base.height * 1e3).is_finite() { base.height * 1e3 } else { f64::MAX };
|
||||
let mut fmts = vec![base];
|
||||
@@ -380,6 +244,19 @@ fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
|
||||
atoms.push(Atom::Word(std::mem::take(word)));
|
||||
}
|
||||
};
|
||||
// A character read as text: a line feed breaks the paragraph and a space ends the word.
|
||||
let text_char = |atoms: &mut Vec<Atom>, word: &mut Vec<(Seg, usize)>, c: char, f: usize| match c {
|
||||
'\r' => {}
|
||||
'\n' => {
|
||||
end_word(atoms, word);
|
||||
atoms.push(Atom::Para(f));
|
||||
}
|
||||
' ' => {
|
||||
end_word(atoms, word);
|
||||
atoms.push(Atom::Space(f));
|
||||
}
|
||||
c => push_char(word, c, f),
|
||||
};
|
||||
// Derive a new format from the current one.
|
||||
let derive = |fmts: &mut Vec<Fmt>, cur: &mut usize, f: &dyn Fn(&mut Fmt)| {
|
||||
let mut n = fmts.get(*cur).cloned().unwrap_or(Fmt {
|
||||
@@ -398,158 +275,91 @@ fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
|
||||
*cur = fmts.len() - 1;
|
||||
}
|
||||
};
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
for token in Tokens::new(contents, StackMode::Structured) {
|
||||
if atoms.len() > MAX_ATOMS {
|
||||
break;
|
||||
}
|
||||
match c {
|
||||
'\\' => {
|
||||
let code = chars.get(i + 1).copied().unwrap_or(' ');
|
||||
i += 2;
|
||||
match code {
|
||||
'P' | 'N' => {
|
||||
end_word(&mut atoms, &mut word);
|
||||
atoms.push(Atom::Para(cur));
|
||||
}
|
||||
'~' => push_char(&mut word, '\u{a0}', cur),
|
||||
'\\' | '{' | '}' => push_char(&mut word, code, cur),
|
||||
'L' => derive(&mut fmts, &mut cur, &|f| f.under = true),
|
||||
'l' => derive(&mut fmts, &mut cur, &|f| f.under = false),
|
||||
'O' => derive(&mut fmts, &mut cur, &|f| f.over = true),
|
||||
'o' => derive(&mut fmts, &mut cur, &|f| f.over = false),
|
||||
'K' | 'k' => {}
|
||||
// `\U+XXXX`: a character by its Unicode code.
|
||||
'U' if i >= 2 && crate::unicode_escape(&chars, i - 2).is_some() => {
|
||||
if let Some(u) = crate::unicode_escape(&chars, i - 2) {
|
||||
push_char(&mut word, u, cur);
|
||||
}
|
||||
i += 5;
|
||||
}
|
||||
'S' => {
|
||||
let mut j = i;
|
||||
let (mut top, mut bottom, mut sep) = (String::new(), String::new(), None);
|
||||
while let Some(&ch) = chars.get(j) {
|
||||
if ch == ';' {
|
||||
break;
|
||||
}
|
||||
if ch == '\\' {
|
||||
if let Some(&n) = chars.get(j + 1) {
|
||||
if sep.is_none() { top.push(n) } else { bottom.push(n) }
|
||||
}
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
if sep.is_none() && matches!(ch, '/' | '#' | '^') {
|
||||
sep = Some(ch);
|
||||
} else if sep.is_none() {
|
||||
top.push(ch);
|
||||
} else {
|
||||
bottom.push(ch);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
i = j + 1;
|
||||
word.push((Seg::Stack(top, bottom, sep.unwrap_or('/')), cur));
|
||||
}
|
||||
'f' | 'F' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
if let Some(font) = font_switch(&a) {
|
||||
derive(&mut fmts, &mut cur, &|f| f.font = font.clone());
|
||||
}
|
||||
}
|
||||
'H' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
|
||||
Some(r) => (true, num(r)),
|
||||
None => (false, num(&a)),
|
||||
};
|
||||
if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) {
|
||||
// Relative heights compound; keep the result within 1e-3..1e3 times the
|
||||
// MTEXT's own height, never infinite.
|
||||
derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v });
|
||||
}
|
||||
}
|
||||
'W' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
// `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it.
|
||||
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
|
||||
Some(r) => (true, num(r)),
|
||||
None => (false, num(&a)),
|
||||
};
|
||||
if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) {
|
||||
// Relative factors compound; keep the result within the absolute range.
|
||||
derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v });
|
||||
}
|
||||
}
|
||||
'Q' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
if let Some(v) = num(&a).filter(|v| v.abs() < 85.0) {
|
||||
derive(&mut fmts, &mut cur, &|f| f.oblique = v.to_radians());
|
||||
}
|
||||
}
|
||||
'C' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
if let Ok(v) = a.trim().parse::<u16>() {
|
||||
let col = if v == 0 || v >= 256 { None } else { Some(MTextColor::Aci(v)) };
|
||||
derive(&mut fmts, &mut cur, &|f| f.color = col);
|
||||
}
|
||||
}
|
||||
'c' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
if let Ok(v) = a.trim().parse::<u32>() {
|
||||
derive(&mut fmts, &mut cur, &|f| f.color = Some(MTextColor::Rgb(v & 0xFF_FFFF)));
|
||||
}
|
||||
}
|
||||
'A' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
if let Ok(v @ 0..=2) = a.trim().parse::<u8>() {
|
||||
derive(&mut fmts, &mut cur, &|f| f.valign = v);
|
||||
}
|
||||
}
|
||||
_ if takes_arg(code) => {
|
||||
// \T and \p: argument up to ';'.
|
||||
let (_, n) = arg(&chars, i);
|
||||
i = n;
|
||||
}
|
||||
// An unknown code has no argument: only the backslash and the code are dropped.
|
||||
_ => {}
|
||||
match token {
|
||||
Token::Control('P' | 'N') => {
|
||||
end_word(&mut atoms, &mut word);
|
||||
atoms.push(Atom::Para(cur));
|
||||
}
|
||||
Token::Control('~') => push_char(&mut word, '\u{a0}', cur),
|
||||
Token::Control(c @ ('\\' | '{' | '}')) => push_char(&mut word, c, cur),
|
||||
Token::Control('L') => derive(&mut fmts, &mut cur, &|f| f.under = true),
|
||||
Token::Control('l') => derive(&mut fmts, &mut cur, &|f| f.under = false),
|
||||
Token::Control('O') => derive(&mut fmts, &mut cur, &|f| f.over = true),
|
||||
Token::Control('o') => derive(&mut fmts, &mut cur, &|f| f.over = false),
|
||||
Token::Stack(raw) => {
|
||||
let (top, bottom, sep) = split_stack(raw);
|
||||
word.push((Seg::Stack(top, bottom, sep.unwrap_or('/')), cur));
|
||||
}
|
||||
Token::Argument('f' | 'F', a) => {
|
||||
if let Some(font) = font_switch(a) {
|
||||
derive(&mut fmts, &mut cur, &|f| f.font = font.clone());
|
||||
}
|
||||
}
|
||||
'{' => {
|
||||
Token::Argument('H', a) => {
|
||||
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
|
||||
Some(r) => (true, num(r)),
|
||||
None => (false, num(a)),
|
||||
};
|
||||
if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) {
|
||||
// Relative heights compound; keep the result within 1e-3..1e3 times the
|
||||
// MTEXT's own height, never infinite.
|
||||
derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v });
|
||||
}
|
||||
}
|
||||
Token::Argument('W', a) => {
|
||||
// `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it.
|
||||
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
|
||||
Some(r) => (true, num(r)),
|
||||
None => (false, num(a)),
|
||||
};
|
||||
if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) {
|
||||
// Relative factors compound; keep the result within the absolute range.
|
||||
derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v });
|
||||
}
|
||||
}
|
||||
Token::Argument('Q', a) => {
|
||||
if let Some(v) = num(a).filter(|v| v.abs() < 85.0) {
|
||||
derive(&mut fmts, &mut cur, &|f| f.oblique = v.to_radians());
|
||||
}
|
||||
}
|
||||
Token::Argument('C', a) => {
|
||||
if let Ok(v) = a.trim().parse::<u16>() {
|
||||
let col = if v == 0 || v >= 256 { None } else { Some(MTextColor::Aci(v)) };
|
||||
derive(&mut fmts, &mut cur, &|f| f.color = col);
|
||||
}
|
||||
}
|
||||
Token::Argument('c', a) => {
|
||||
if let Ok(v) = a.trim().parse::<u32>() {
|
||||
derive(&mut fmts, &mut cur, &|f| f.color = Some(MTextColor::Rgb(v & 0xFF_FFFF)));
|
||||
}
|
||||
}
|
||||
Token::Argument('A', a) => {
|
||||
if let Ok(v @ 0..=2) = a.trim().parse::<u8>() {
|
||||
derive(&mut fmts, &mut cur, &|f| f.valign = v);
|
||||
}
|
||||
}
|
||||
Token::OpenGroup => {
|
||||
if stack.len() < 256 {
|
||||
stack.push(cur);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
'}' => {
|
||||
Token::CloseGroup => {
|
||||
if let Some(f) = stack.pop() {
|
||||
cur = f;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
'\r' => i += 1,
|
||||
'\n' => {
|
||||
end_word(&mut atoms, &mut word);
|
||||
atoms.push(Atom::Para(cur));
|
||||
i += 1;
|
||||
}
|
||||
' ' => {
|
||||
end_word(&mut atoms, &mut word);
|
||||
atoms.push(Atom::Space(cur));
|
||||
i += 1;
|
||||
}
|
||||
_ => {
|
||||
push_char(&mut word, c, cur);
|
||||
i += 1;
|
||||
// An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD shows it:
|
||||
// keep the backslash and read the code as text (#2952).
|
||||
Token::Unknown(c) => {
|
||||
push_char(&mut word, '\\', cur);
|
||||
text_char(&mut atoms, &mut word, c, cur);
|
||||
}
|
||||
Token::Char(c) => text_char(&mut atoms, &mut word, c, cur),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
end_word(&mut atoms, &mut word);
|
||||
@@ -634,56 +444,56 @@ fn seg_width(seg: &Seg, f: &Fmt) -> f64 {
|
||||
}
|
||||
|
||||
/// Shape a segment with its left end at `x` on the baseline.
|
||||
fn seg_shape(seg: &Seg, f: &Fmt, x: f64) -> Shaped {
|
||||
let h = f.height;
|
||||
fn seg_shape(seg: &Seg, format: &Fmt, origin_x: f64) -> Shaped {
|
||||
let height = format.height;
|
||||
let mut out = Shaped::default();
|
||||
let put = |s: &str, size: f64, at: Vec2| {
|
||||
if s.is_empty() {
|
||||
let put = |text: &str, size: f64, at: Vec2| {
|
||||
if text.is_empty() {
|
||||
return Shaped::default();
|
||||
}
|
||||
let mut sh = shape_line(&f.font, s, size, f.wf, f.oblique);
|
||||
sh.map(|p| p + at);
|
||||
let mut sh = shape_line(&format.font, text, size, format.wf, format.oblique);
|
||||
sh.map(|point| point + at);
|
||||
sh
|
||||
};
|
||||
let w = seg_width(seg, f);
|
||||
let width = seg_width(seg, format);
|
||||
match seg {
|
||||
Seg::Text(t) => out.extend(put(t, h, Vec2::new(x, 0.0))),
|
||||
Seg::Text(text) => out.extend(put(text, height, Vec2::new(origin_x, 0.0))),
|
||||
Seg::Stack(top, bottom, sep) => {
|
||||
let hs = h * STACK_SCALE;
|
||||
let wt = text_width(&f.font, top, hs, f.wf);
|
||||
let wb = text_width(&f.font, bottom, hs, f.wf);
|
||||
let hs = height * STACK_SCALE;
|
||||
let wt = text_width(&format.font, top, hs, format.wf);
|
||||
let wb = text_width(&format.font, bottom, hs, format.wf);
|
||||
match sep {
|
||||
'#' => {
|
||||
out.extend(put(top, hs, Vec2::new(x, h * 0.4)));
|
||||
let sx = x + wt + h * 0.1;
|
||||
out.extend(put(bottom, hs, Vec2::new(sx + h * 0.4, -h * 0.05)));
|
||||
out.strokes.push(vec![Vec2::new(sx, -h * 0.1), Vec2::new(sx + h * 0.3, h * 1.1)]);
|
||||
out.extend(put(top, hs, Vec2::new(origin_x, height * 0.4)));
|
||||
let sx = origin_x + wt + height * 0.1;
|
||||
out.extend(put(bottom, hs, Vec2::new(sx + height * 0.4, -height * 0.05)));
|
||||
out.strokes.push(vec![Vec2::new(sx, -height * 0.1), Vec2::new(sx + height * 0.3, height * 1.1)]);
|
||||
}
|
||||
'^' => {
|
||||
// Tolerances: centred on the line, or the lower value on the baseline (\A0) or
|
||||
// the upper value level with the text (\A2).
|
||||
let (yt, yb) = match f.valign {
|
||||
0 => (hs + h * 0.1, 0.0),
|
||||
2 => (0.0, -hs - h * 0.1),
|
||||
_ => (h * 0.55, h * 0.45 - hs),
|
||||
let (yt, yb) = match format.valign {
|
||||
0 => (hs + height * 0.1, 0.0),
|
||||
2 => (0.0, -hs - height * 0.1),
|
||||
_ => (height * 0.55, height * 0.45 - hs),
|
||||
};
|
||||
out.extend(put(top, hs, Vec2::new(x, yt)));
|
||||
out.extend(put(bottom, hs, Vec2::new(x, yb)));
|
||||
out.extend(put(top, hs, Vec2::new(origin_x, yt)));
|
||||
out.extend(put(bottom, hs, Vec2::new(origin_x, yb)));
|
||||
}
|
||||
_ => {
|
||||
let bar = h * 0.45;
|
||||
out.extend(put(top, hs, Vec2::new(x + (w - wt) / 2.0, bar + h * 0.12)));
|
||||
out.extend(put(bottom, hs, Vec2::new(x + (w - wb) / 2.0, bar - h * 0.12 - hs)));
|
||||
out.strokes.push(vec![Vec2::new(x, bar), Vec2::new(x + w, bar)]);
|
||||
let bar = height * 0.45;
|
||||
out.extend(put(top, hs, Vec2::new(origin_x + (width - wt) / 2.0, bar + height * 0.12)));
|
||||
out.extend(put(bottom, hs, Vec2::new(origin_x + (width - wb) / 2.0, bar - height * 0.12 - hs)));
|
||||
out.strokes.push(vec![Vec2::new(origin_x, bar), Vec2::new(origin_x + width, bar)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if f.under {
|
||||
out.strokes.push(vec![Vec2::new(x, -h * 0.2), Vec2::new(x + w, -h * 0.2)]);
|
||||
if format.under {
|
||||
out.strokes.push(vec![Vec2::new(origin_x, -height * 0.2), Vec2::new(origin_x + width, -height * 0.2)]);
|
||||
}
|
||||
if f.over {
|
||||
out.strokes.push(vec![Vec2::new(x, h * 1.2), Vec2::new(x + w, h * 1.2)]);
|
||||
if format.over {
|
||||
out.strokes.push(vec![Vec2::new(origin_x, height * 1.2), Vec2::new(origin_x + width, height * 1.2)]);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -791,8 +601,7 @@ fn plain_lines(atoms: &[Atom], fmts: &[Fmt], base: &Fmt, width: f64) -> Vec<Line
|
||||
};
|
||||
for segments in pieces {
|
||||
let word_width = word_width(segments);
|
||||
let space_width =
|
||||
pending_space.map(|format| crate::space_width(&fmt(format).font, fmt(format).height, fmt(format).wf)).unwrap_or(0.0);
|
||||
let space_width = pending_space.map_or(0.0, |format| crate::space_width(&fmt(format).font, fmt(format).height, fmt(format).wf));
|
||||
if width > 0.0 && !line.items.is_empty() && line.width + space_width + word_width > width + 1e-9 {
|
||||
finish(&mut lines, &mut line, fmt(last_fmt), paragraph);
|
||||
} else if !line.items.is_empty() || pending_space.is_some() {
|
||||
@@ -958,7 +767,7 @@ mod tests {
|
||||
assert_eq!(plain_mtext("\\H2.5x;Big"), "Big");
|
||||
assert_eq!(plain_mtext("unterminated \\H2"), "unterminated ");
|
||||
assert_eq!(plain_mtext("\\U+0041B \\U+00E8"), "AB è");
|
||||
assert_eq!(plain_mtext("\\U+12"), "+12", "a short escape loses only the backslash and the code");
|
||||
assert_eq!(plain_mtext("\\U+12"), "\\U+12", "a short escape is shown as typed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -980,18 +789,24 @@ mod tests {
|
||||
assert_eq!(plain_mtext("\\\\U+0041"), "\\U+0041");
|
||||
// `\M+n` double-byte characters, decoded like the DXF reader does.
|
||||
assert_eq!(plain_mtext("\\M+5BCFE x;y"), "\u{4ef6} x;y");
|
||||
// Malformed escapes lose only the backslash and the code.
|
||||
assert_eq!(plain_mtext("a\\U+12 b"), "a+12 b");
|
||||
assert_eq!(lay("a\\U+12 b", 0.0).lines, vec!["a+12 b"]);
|
||||
assert_eq!(lay("\\pxql;a\\U+12 b", 0.0).lines, vec!["a+12 b"]);
|
||||
assert_eq!(plain_mtext("a\\M+ b"), "a+ b");
|
||||
// Malformed escapes are shown as typed, backslash included, as AutoCAD 2024 shows them.
|
||||
for s in ["a\\U+12 b", "\\U+12x", "a\\U+12;b", "a\\U+123 b", "a\\U+ b", "a\\U+00G1b", "a\\M+ b"] {
|
||||
assert_eq!(plain_mtext(s), s);
|
||||
assert_eq!(lay(s, 0.0).lines, vec![s]);
|
||||
assert_eq!(lay(&format!("\\pxql;{s}"), 0.0).lines, vec![s]);
|
||||
}
|
||||
// A valid escape takes exactly four digits.
|
||||
assert_eq!(plain_mtext("a\\U+12345b"), "a\u{1234}5b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_code_without_semicolon_keeps_the_text() {
|
||||
assert_eq!(plain_mtext("A\\Zbc d"), "Abc d");
|
||||
assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["Abc d"]);
|
||||
assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["Abc d"]);
|
||||
// An unknown code is shown as typed, as AutoCAD 2024 shows it.
|
||||
assert_eq!(plain_mtext("A\\Zbc d"), "A\\Zbc d");
|
||||
assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["A\\Zbc d"]);
|
||||
assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["A\\Zbc d"]);
|
||||
// The text after it is read as usual: here a paragraph break.
|
||||
assert_eq!(plain_mtext("A\\Z\\Pb"), "A\\Z\nb");
|
||||
// A trailing lone backslash is dropped.
|
||||
assert_eq!(plain_mtext("A\\"), "A");
|
||||
// Codes with an argument still take it up to the `;`, or to the end.
|
||||
@@ -1120,7 +935,7 @@ mod tests {
|
||||
let cols: Vec<Option<MTextColor>> = l.pieces.iter().map(|p| p.color).collect();
|
||||
assert_eq!(cols, vec![None, Some(MTextColor::Aci(1)), None]);
|
||||
let l = lay("\\c16711680;R", 0.0);
|
||||
assert_eq!(l.pieces.first().map(|p| p.color), Some(Some(MTextColor::Rgb(0xFF0000))));
|
||||
assert_eq!(l.pieces.first().map(|p| p.color), Some(Some(MTextColor::Rgb(0x00FF_0000))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1142,8 +957,8 @@ mod tests {
|
||||
let bar = l.strokes.iter().find(|s| s.len() == 2 && (s[0].y - s[1].y).abs() < 1e-12 && (s[0].y + 0.55).abs() < 1e-9);
|
||||
assert!(bar.is_some());
|
||||
let ys: Vec<f64> = l.strokes.iter().flatten().map(|p| p.y).collect();
|
||||
let max = ys.iter().cloned().fold(f64::MIN, f64::max);
|
||||
let min = ys.iter().cloned().fold(f64::MAX, f64::min);
|
||||
let max = ys.iter().copied().fold(f64::MIN, f64::max);
|
||||
let min = ys.iter().copied().fold(f64::MAX, f64::min);
|
||||
assert!(max > 0.0 && min < -1.0, "{min}..{max}");
|
||||
// Narrower than the two digits side by side at full size.
|
||||
assert!(l.bounds.width() < crate::line_width("12", 1.0, 1.0));
|
||||
|
||||
+87
-108
@@ -7,7 +7,7 @@
|
||||
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
|
||||
use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, arg, num, parse, seg_plain, seg_shape, seg_width, split_thai};
|
||||
use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, num, parse, seg_plain, seg_shape, seg_width, split_thai};
|
||||
|
||||
/// Columns an MTEXT's text flows through, each as wide as the MTEXT's width.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -57,7 +57,7 @@ pub enum ParaAlign {
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// `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.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ParaProps {
|
||||
@@ -226,7 +226,7 @@ impl ListStyle {
|
||||
let mut s = Vec::new();
|
||||
while n > 0 && s.len() < 16 {
|
||||
n -= 1;
|
||||
let c = b'a' + (n % 26) as u8;
|
||||
let c = b'a' + u8::try_from(n % 26).unwrap_or(0);
|
||||
s.push(char::from(if upper { c.to_ascii_uppercase() } else { c }));
|
||||
n /= 26;
|
||||
}
|
||||
@@ -265,58 +265,30 @@ pub struct Paragraphs {
|
||||
impl Paragraphs {
|
||||
pub fn scan(contents: &str) -> Paragraphs {
|
||||
let contents = super::unescape_codes(contents);
|
||||
let chars: Vec<char> = contents.chars().collect();
|
||||
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens};
|
||||
let mut out = Paragraphs { states: vec![ParaProps::default()], ..Default::default() };
|
||||
let mut cur = 0usize;
|
||||
let mut i = 0;
|
||||
let brk = |out: &mut Paragraphs, cur: usize, column: bool| {
|
||||
out.para.push(cur);
|
||||
out.column_break.push(column);
|
||||
};
|
||||
while let Some(&c) = chars.get(i) {
|
||||
match c {
|
||||
'\\' => {
|
||||
let code = chars.get(i + 1).copied().unwrap_or(' ');
|
||||
i += 2;
|
||||
match code {
|
||||
'P' => brk(&mut out, cur, false),
|
||||
'N' => brk(&mut out, cur, true),
|
||||
'~' | '\\' | '{' | '}' | 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => {}
|
||||
'S' => {
|
||||
let mut j = i;
|
||||
while let Some(&ch) = chars.get(j) {
|
||||
if ch == ';' {
|
||||
break;
|
||||
}
|
||||
j += if ch == '\\' { 2 } else { 1 };
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
'p' => {
|
||||
let (a, n) = arg(&chars, i);
|
||||
i = n;
|
||||
if out.states.len() < MAX_STATES
|
||||
&& let Some(st) = out.states.get(cur)
|
||||
{
|
||||
let mut st = st.clone();
|
||||
st.apply(&a);
|
||||
out.states.push(st);
|
||||
cur = out.states.len() - 1;
|
||||
}
|
||||
}
|
||||
_ if super::takes_arg(code) => {
|
||||
let (_, n) = arg(&chars, i);
|
||||
i = n;
|
||||
}
|
||||
// An unknown code has no argument: only the backslash and the code go.
|
||||
_ => {}
|
||||
for token in Tokens::new(&contents, StackMode::Structured) {
|
||||
match token {
|
||||
// An unknown code is text, as typed (as the layout reads it), so a line feed after a
|
||||
// lone backslash still breaks the paragraph.
|
||||
Token::Control('P') | Token::Char('\n') | Token::Unknown('\n') => brk(&mut out, cur, false),
|
||||
Token::Control('N') => brk(&mut out, cur, true),
|
||||
Token::Argument('p', a) => {
|
||||
if out.states.len() < MAX_STATES
|
||||
&& let Some(st) = out.states.get(cur)
|
||||
{
|
||||
let mut st = st.clone();
|
||||
st.apply(a);
|
||||
out.states.push(st);
|
||||
cur = out.states.len() - 1;
|
||||
}
|
||||
}
|
||||
'\n' => {
|
||||
brk(&mut out, cur, false);
|
||||
i += 1;
|
||||
}
|
||||
_ => i += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// A `\p` anywhere in a paragraph applies to all of it: the break pushed the state at
|
||||
@@ -544,9 +516,7 @@ impl<'a> LineBuilder<'a> {
|
||||
fn place(&mut self, index: usize, segments: &[(Seg, usize)]) {
|
||||
let word_width = self.word_width(segments);
|
||||
let space_width = if index == 0 {
|
||||
self.pending_space
|
||||
.map(|format| crate::space_width(&self.format(format).font, self.format(format).height, self.format(format).wf))
|
||||
.unwrap_or(0.0)
|
||||
self.pending_space.map_or(0.0, |format| crate::space_width(&self.format(format).font, self.format(format).height, self.format(format).wf))
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
@@ -596,72 +566,80 @@ fn next_tab(x: f64, pp: &ParaProps, h: f64) -> (f64, TabKind) {
|
||||
}
|
||||
|
||||
/// Lay out MTEXT with paragraph formatting and columns. `base` is the entity's own format,
|
||||
/// `h` its text height, `width` the column width (0: no wrapping, no columns).
|
||||
pub(super) fn layout(contents: &str, p: &MTextParams, base: &Fmt) -> MTextLayout {
|
||||
let h = base.height;
|
||||
let width = if p.width.is_finite() && p.width > 0.0 { p.width } else { 0.0 };
|
||||
let rotation = if p.rotation.is_finite() { p.rotation } else { 0.0 };
|
||||
let paras = Paragraphs::scan(contents);
|
||||
/// `height` its text height, `width` the column width (0: no wrapping, no columns).
|
||||
#[expect(
|
||||
clippy::too_many_lines,
|
||||
reason = "Paragraph and column placement is one ordered state machine; splitting it would obscure the transitions between lines and columns."
|
||||
)]
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
reason = "Column indices are at most MAX_COLUMNS and gap counts at most MAX_ATOMS, so every usize converted here is exact in f64."
|
||||
)]
|
||||
pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextLayout {
|
||||
let height = base.height;
|
||||
let width = if params.width.is_finite() && params.width > 0.0 { params.width } else { 0.0 };
|
||||
let rotation = if params.rotation.is_finite() { params.rotation } else { 0.0 };
|
||||
let paragraphs = Paragraphs::scan(contents);
|
||||
let (atoms, fmts) = parse(contents, base.clone());
|
||||
let fmt = |i: usize| fmts.get(i).unwrap_or(base);
|
||||
let lines = LineBuilder::new(¶s, &fmts, base, width, h).build(&atoms);
|
||||
let fmt = |index: usize| fmts.get(index).unwrap_or(base);
|
||||
let lines = LineBuilder::new(¶graphs, &fmts, base, width, height).build(&atoms);
|
||||
|
||||
// Vertical placement: baselines below the top of each line's column.
|
||||
let ls = super::sane_line_spacing(p.line_spacing);
|
||||
let cols = p.columns.as_ref().filter(|_| width > 0.0);
|
||||
let line_spacing = super::sane_line_spacing(params.line_spacing);
|
||||
let cols = params.columns.as_ref().filter(|_| width > 0.0);
|
||||
let max_cols = match cols {
|
||||
Some(c) if c.dynamic => MAX_COLUMNS,
|
||||
Some(c) => c.count.clamp(1, MAX_COLUMNS),
|
||||
Some(spec) if spec.dynamic => MAX_COLUMNS,
|
||||
Some(spec) => spec.count.clamp(1, MAX_COLUMNS),
|
||||
None => 1,
|
||||
};
|
||||
let col_height = |c: usize| -> f64 {
|
||||
let col_height = |column: usize| -> f64 {
|
||||
let Some(spec) = cols else { return 0.0 };
|
||||
let v = if spec.heights.is_empty() { spec.height } else { spec.heights.get(c).or(spec.heights.last()).copied().unwrap_or(0.0) };
|
||||
if v.is_finite() && v > 0.0 { v } else { 0.0 }
|
||||
let value = if spec.heights.is_empty() { spec.height } else { spec.heights.get(column).or(spec.heights.last()).copied().unwrap_or(0.0) };
|
||||
if value.is_finite() && value > 0.0 { value } else { 0.0 }
|
||||
};
|
||||
let mut placed: Vec<(usize, f64)> = Vec::with_capacity(lines.len());
|
||||
let (mut c, mut y, mut first_in_col, mut force) = (0usize, 0.0f64, true, false);
|
||||
let (mut column, mut current_y, mut first_in_col, mut force) = (0usize, 0.0f64, true, false);
|
||||
let mut col_bottom = vec![0.0f64];
|
||||
let mut prev_para: Option<usize> = None;
|
||||
for l in &lines {
|
||||
let lh = if l.max_h > 0.0 { l.max_h } else { h };
|
||||
let new_para = prev_para != Some(l.para);
|
||||
let before = if new_para && prev_para.is_some() { paras.props(l.para).before * h } else { 0.0 };
|
||||
let step_h = if p.line_spacing_exact { h } else { lh };
|
||||
let pitch = |first: bool| if first { lh } else { step_h * 5.0 / 3.0 * ls + before };
|
||||
let hc = col_height(c);
|
||||
if !first_in_col && c + 1 < max_cols && (force || (hc > 0.0 && y + pitch(false) > hc + 1e-9)) {
|
||||
c += 1;
|
||||
for line in &lines {
|
||||
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 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;
|
||||
col_bottom.push(0.0);
|
||||
y = 0.0;
|
||||
current_y = 0.0;
|
||||
first_in_col = true;
|
||||
}
|
||||
force = false;
|
||||
y += pitch(first_in_col);
|
||||
current_y += pitch(first_in_col);
|
||||
first_in_col = false;
|
||||
placed.push((c, -y));
|
||||
if let Some(b) = col_bottom.get_mut(c) {
|
||||
*b = y;
|
||||
placed.push((column, -current_y));
|
||||
if let Some(bottom) = col_bottom.get_mut(column) {
|
||||
*bottom = current_y;
|
||||
}
|
||||
if l.para_end {
|
||||
y += paras.props(l.para).after * h;
|
||||
force = paras.column_break(l.para);
|
||||
if line.para_end {
|
||||
current_y += paragraphs.props(line.para).after * height;
|
||||
force = paragraphs.column_break(line.para);
|
||||
}
|
||||
prev_para = Some(l.para);
|
||||
prev_para = Some(line.para);
|
||||
}
|
||||
let n_cols = match cols {
|
||||
Some(spec) if !spec.dynamic => max_cols,
|
||||
_ => c + 1,
|
||||
_ => column + 1,
|
||||
};
|
||||
let content_h = col_bottom.iter().copied().fold(0.0, f64::max);
|
||||
let block_h = match cols {
|
||||
Some(_) => (0..n_cols).map(col_height).fold(content_h, f64::max),
|
||||
None => content_h,
|
||||
};
|
||||
let col_w = if width > 0.0 { width } else { lines.iter().map(|l| l.width + paras.props(l.para).right).fold(0.0, f64::max) };
|
||||
let gutter = cols.map(|s| s.gutter).filter(|g| g.is_finite() && *g >= 0.0).unwrap_or(0.0);
|
||||
let col_w = if width > 0.0 { width } else { lines.iter().map(|line| line.width + paragraphs.props(line.para).right).fold(0.0, f64::max) };
|
||||
let gutter = cols.map(|spec| spec.gutter).filter(|g| g.is_finite() && *g >= 0.0).unwrap_or(0.0);
|
||||
let total_w = col_w * n_cols as f64 + gutter * n_cols.saturating_sub(1) as f64;
|
||||
let attach = p.attach.clamp(1, 9) - 1;
|
||||
let attach = params.attach.clamp(1, 9) - 1;
|
||||
let (acol, arow) = (attach % 3, attach / 3);
|
||||
let top = match arow {
|
||||
0 => 0.0,
|
||||
@@ -673,41 +651,42 @@ pub(super) fn layout(contents: &str, p: &MTextParams, base: &Fmt) -> MTextLayout
|
||||
1 => -total_w / 2.0,
|
||||
_ => -total_w,
|
||||
};
|
||||
let reversed = cols.is_some_and(|s| s.reversed);
|
||||
let insert = p.insert;
|
||||
let xf = |q: Vec2| insert + q.rotate(rotation);
|
||||
let mut out = MTextLayout { lines: lines.iter().map(|l| l.text.clone()).collect(), ..Default::default() };
|
||||
let reversed = cols.is_some_and(|spec| spec.reversed);
|
||||
let insert = params.insert;
|
||||
let xf = |point: Vec2| insert + point.rotate(rotation);
|
||||
let mut out = MTextLayout { lines: lines.iter().map(|line| line.text.clone()).collect(), ..Default::default() };
|
||||
let mut allowance = super::Allowance::new();
|
||||
for (l, (c, base_y)) in lines.iter().zip(placed) {
|
||||
let pp = paras.props(l.para);
|
||||
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(c) } else { c };
|
||||
for (line, (column, base_y)) in lines.iter().zip(placed) {
|
||||
let pp = paragraphs.props(line.para);
|
||||
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column };
|
||||
let col_x = box_x0 + slot as f64 * (col_w + gutter);
|
||||
let right_edge = col_w - pp.right;
|
||||
let free = right_edge - l.width;
|
||||
let free = right_edge - line.width;
|
||||
let align = match pp.align {
|
||||
ParaAlign::Default => [ParaAlign::Left, ParaAlign::Center, ParaAlign::Right].get(usize::from(acol)).copied().unwrap_or_default(),
|
||||
a => a,
|
||||
alignment => alignment,
|
||||
};
|
||||
let spread = width > 0.0 && l.gaps > 0 && free > 0.0 && (align == ParaAlign::Distributed || (align == ParaAlign::Justify && !l.para_end));
|
||||
let spread =
|
||||
width > 0.0 && line.gaps > 0 && free > 0.0 && (align == ParaAlign::Distributed || (align == ParaAlign::Justify && !line.para_end));
|
||||
let (shift, per_gap) = match align {
|
||||
ParaAlign::Center => (free / 2.0, 0.0),
|
||||
ParaAlign::Right => (free, 0.0),
|
||||
_ if spread => (0.0, free / l.gaps as f64),
|
||||
_ if spread => (0.0, free / line.gaps as f64),
|
||||
_ => (0.0, 0.0),
|
||||
};
|
||||
for it in &l.items {
|
||||
let fm = fmt(it.fmt);
|
||||
for item in &line.items {
|
||||
let fm = fmt(item.fmt);
|
||||
if !allowance.left() {
|
||||
out.truncated = true;
|
||||
continue;
|
||||
}
|
||||
let mut sh = seg_shape(&it.seg, fm, it.x);
|
||||
let mut sh = seg_shape(&item.seg, fm, item.x);
|
||||
if !allowance.charge(&sh) {
|
||||
out.truncated = true;
|
||||
continue;
|
||||
}
|
||||
let off = Vec2::new(col_x + shift + per_gap * it.gap as f64, top + base_y);
|
||||
sh.map(|q| xf(q + off));
|
||||
let off = Vec2::new(col_x + shift + per_gap * item.gap as f64, top + base_y);
|
||||
sh.map(|point| xf(point + off));
|
||||
match out.pieces.last_mut() {
|
||||
Some(pc) if pc.color == fm.color => pc.shaped.extend(sh),
|
||||
_ => out.pieces.push(MTextPiece { color: fm.color, shaped: sh }),
|
||||
@@ -763,17 +742,17 @@ mod tests {
|
||||
#[test]
|
||||
fn props_parse_and_persist() {
|
||||
let p = Paragraphs::scan("\\pxi-3,l3,t3;1.\tone\\P2.\ttwo\\P\\pi0,l0,tz;plain");
|
||||
assert_eq!(p.props(0).first, -3.0);
|
||||
assert_eq!(p.props(0).left, 3.0);
|
||||
assert!((p.props(0).first + 3.0).abs() < f64::EPSILON);
|
||||
assert!((p.props(0).left - 3.0).abs() < f64::EPSILON);
|
||||
assert_eq!(p.props(0).tabs, vec![(3.0, TabKind::Left)]);
|
||||
assert_eq!(p.props(1), p.props(0));
|
||||
assert_eq!(p.props(2).left, 0.0);
|
||||
assert!(p.props(2).left.abs() < f64::EPSILON);
|
||||
assert!(p.props(2).tabs.is_empty());
|
||||
let mut pp = ParaProps::default();
|
||||
pp.apply("t2,c4,r6,d8,qc,b0.5");
|
||||
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_eq!(pp.before, 0.5);
|
||||
assert!((pp.before - 0.5).abs() < f64::EPSILON);
|
||||
let mut back = ParaProps::default();
|
||||
back.apply(pp.code().trim_start_matches("\\p").trim_end_matches(';'));
|
||||
assert_eq!(back, pp);
|
||||
|
||||
@@ -1,313 +0,0 @@
|
||||
//! Shape source (`.shp`) to a compiled SHX file, as COMPILE does.
|
||||
//!
|
||||
//! A source is a list of definitions: a header line `*number,defbytes,NAME` followed by its
|
||||
//! specification bytes (on as many lines as needed, ending with 0). Numbers are decimal, or
|
||||
//! hexadecimal after a leading `0` (`012`, `08cfb`); parentheses only group; `;` starts a
|
||||
//! comment. A big font starts with `*BIGFONT nchars,nranges,first,last,…` and a Unicode font
|
||||
//! with `*UNIFONT,6,name` followed by `above,below,modes,encoding,type,0`. Shape 0 is a text
|
||||
//! font's record (`above,below,modes,0`).
|
||||
//!
|
||||
//! Operands are encoded by what they are: a subshape number takes two bytes in a Unicode font
|
||||
//! (and after `7,0` in a big font), displacements and bulges are two's complement, and an arc's
|
||||
//! direction byte (`-043`) keeps its sign in the high bit. `defbytes` is not checked: the
|
||||
//! program's own length is written.
|
||||
|
||||
use super::ShxError;
|
||||
use super::parse::{BIGFONT, SHAPES_10, UNIFONT};
|
||||
|
||||
/// Largest source compiled.
|
||||
const MAX_SOURCE: usize = 8 << 20;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Kind {
|
||||
Shapes,
|
||||
Big,
|
||||
Uni,
|
||||
}
|
||||
|
||||
struct Shape {
|
||||
number: u16,
|
||||
name: String,
|
||||
program: Vec<u8>,
|
||||
}
|
||||
|
||||
/// A number token: value (sign included).
|
||||
fn number(tok: &str, line: usize) -> Result<i64, ShxError> {
|
||||
let t: String = tok.chars().filter(|c| !matches!(c, '(' | ')') && !c.is_whitespace()).collect();
|
||||
let (neg, digits) = match t.strip_prefix('-') {
|
||||
Some(d) => (true, d),
|
||||
None => (false, t.strip_prefix('+').unwrap_or(&t)),
|
||||
};
|
||||
let err = || ShxError::Source(line, format!("not a number: {tok:?}"));
|
||||
let v = if digits.len() > 1 && digits.starts_with('0') {
|
||||
i64::from_str_radix(digits.get(1..).unwrap_or_default(), 16).map_err(|_| err())?
|
||||
} else {
|
||||
digits.parse::<i64>().map_err(|_| err())?
|
||||
};
|
||||
if v > 0xFFFF {
|
||||
return Err(err());
|
||||
}
|
||||
Ok(if neg { -v } else { v })
|
||||
}
|
||||
|
||||
/// The comma-separated numbers of a line (comment removed, blank fields skipped).
|
||||
fn numbers(text: &str, line: usize) -> Result<Vec<i64>, ShxError> {
|
||||
text.split(',').map(str::trim).filter(|t| !t.is_empty() && *t != "(" && *t != ")").map(|t| number(t, line)).collect()
|
||||
}
|
||||
|
||||
/// The spec-byte encoder: walks the tokens as the reader walks the bytes.
|
||||
struct Enc<'a> {
|
||||
toks: &'a [i64],
|
||||
i: usize,
|
||||
out: Vec<u8>,
|
||||
kind: Kind,
|
||||
line: usize,
|
||||
}
|
||||
|
||||
impl Enc<'_> {
|
||||
fn next(&mut self) -> Result<i64, ShxError> {
|
||||
let v = self.toks.get(self.i).copied().ok_or_else(|| ShxError::Source(self.line, "the shape ends inside a command".into()))?;
|
||||
self.i += 1;
|
||||
Ok(v)
|
||||
}
|
||||
fn byte(&mut self) -> Result<(), ShxError> {
|
||||
let v = self.next()?;
|
||||
let b = u8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a byte")))?;
|
||||
self.out.push(b);
|
||||
Ok(())
|
||||
}
|
||||
/// Two's complement −128..127.
|
||||
fn signed(&mut self) -> Result<i64, ShxError> {
|
||||
let v = self.next()?;
|
||||
let b = i8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not −128..127")))?;
|
||||
self.out.extend(b.to_le_bytes());
|
||||
Ok(v)
|
||||
}
|
||||
/// Sign in the high bit (an arc's direction byte).
|
||||
fn sign_magnitude(&mut self) -> Result<(), ShxError> {
|
||||
let v = self.next()?;
|
||||
let m = u8::try_from(v.unsigned_abs())
|
||||
.ok()
|
||||
.filter(|m| *m < 0x80)
|
||||
.ok_or_else(|| ShxError::Source(self.line, format!("{v} is not an octant byte")))?;
|
||||
self.out.push(if v < 0 { m | 0x80 } else { m });
|
||||
Ok(())
|
||||
}
|
||||
fn word(&mut self) -> Result<(), ShxError> {
|
||||
let v = self.next()?;
|
||||
let w = u16::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a shape number")))?;
|
||||
self.out.extend(w.to_be_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn program(mut self) -> Result<Vec<u8>, ShxError> {
|
||||
while self.i < self.toks.len() {
|
||||
let code = self.next()?;
|
||||
let c = u8::try_from(code).map_err(|_| ShxError::Source(self.line, format!("{code} is not a code")))?;
|
||||
self.out.push(c);
|
||||
match c {
|
||||
0 => break,
|
||||
3 | 4 => self.byte()?,
|
||||
7 => match self.kind {
|
||||
Kind::Uni => self.word()?,
|
||||
Kind::Big => {
|
||||
let first = self.toks.get(self.i).copied().unwrap_or(0);
|
||||
if first == 0 {
|
||||
self.byte()?;
|
||||
self.word()?;
|
||||
for _ in 0..4 {
|
||||
self.byte()?;
|
||||
}
|
||||
} else {
|
||||
self.byte()?;
|
||||
}
|
||||
}
|
||||
Kind::Shapes => self.byte()?,
|
||||
},
|
||||
8 => {
|
||||
self.signed()?;
|
||||
self.signed()?;
|
||||
}
|
||||
9 => loop {
|
||||
let (x, y) = (self.signed()?, self.signed()?);
|
||||
if x == 0 && y == 0 {
|
||||
break;
|
||||
}
|
||||
},
|
||||
10 => {
|
||||
self.byte()?;
|
||||
self.sign_magnitude()?;
|
||||
}
|
||||
11 => {
|
||||
for _ in 0..4 {
|
||||
self.byte()?;
|
||||
}
|
||||
self.sign_magnitude()?;
|
||||
}
|
||||
12 => {
|
||||
for _ in 0..3 {
|
||||
self.signed()?;
|
||||
}
|
||||
}
|
||||
13 => loop {
|
||||
let (x, y) = (self.signed()?, self.signed()?);
|
||||
if x == 0 && y == 0 {
|
||||
break;
|
||||
}
|
||||
self.signed()?;
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if self.out.last() != Some(&0) {
|
||||
self.out.push(0);
|
||||
}
|
||||
Ok(self.out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile shape source into an SHX file (a shape file or text font, a big font, or a Unicode
|
||||
/// font, as its first definition says).
|
||||
pub fn compile(source: &str) -> Result<Vec<u8>, ShxError> {
|
||||
if source.len() > MAX_SOURCE {
|
||||
return Err(ShxError::TooLarge);
|
||||
}
|
||||
let mut kind = Kind::Shapes;
|
||||
let mut ranges: Vec<(u16, u16)> = Vec::new();
|
||||
let mut uni_info: Option<(String, Vec<u8>)> = None;
|
||||
// Definitions: header (number, name, line) and the numbers that follow it.
|
||||
let mut defs: Vec<(i64, String, usize, Vec<i64>)> = Vec::new();
|
||||
let mut uni_header_pending = false;
|
||||
for (no, raw) in source.lines().enumerate() {
|
||||
let line = no + 1;
|
||||
let text = raw.split(';').next().unwrap_or_default().trim();
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(head) = text.strip_prefix('*') {
|
||||
let upper = head.trim_start().to_ascii_uppercase();
|
||||
if let Some(rest) = upper.strip_prefix("BIGFONT") {
|
||||
kind = Kind::Big;
|
||||
let v = numbers(rest, line)?;
|
||||
let n = usize::try_from(v.get(1).copied().unwrap_or(0)).unwrap_or(0);
|
||||
for k in 0..n {
|
||||
let lo = v.get(2 + 2 * k).copied().unwrap_or(0);
|
||||
let hi = v.get(3 + 2 * k).copied().unwrap_or(lo);
|
||||
let to = |x: i64| u16::try_from(x).map_err(|_| ShxError::Source(line, "bad escape range".into()));
|
||||
ranges.push((to(lo)?, to(hi)?));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if upper.starts_with("UNIFONT") {
|
||||
kind = Kind::Uni;
|
||||
let name = head.splitn(3, ',').nth(2).unwrap_or_default().trim().to_string();
|
||||
uni_info = Some((name, Vec::new()));
|
||||
uni_header_pending = true;
|
||||
continue;
|
||||
}
|
||||
uni_header_pending = false;
|
||||
let mut parts = head.splitn(3, ',');
|
||||
let num = number(parts.next().unwrap_or_default().trim(), line)?;
|
||||
let _defbytes = parts.next();
|
||||
let name = parts.next().unwrap_or_default().trim().to_string();
|
||||
defs.push((num, name, line, Vec::new()));
|
||||
continue;
|
||||
}
|
||||
let v = numbers(text, line)?;
|
||||
if uni_header_pending {
|
||||
if let Some((_, info)) = uni_info.as_mut() {
|
||||
for x in v {
|
||||
info.push(u8::try_from(x).map_err(|_| ShxError::Source(line, "bad font record".into()))?);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match defs.last_mut() {
|
||||
Some(d) => d.3.extend(v),
|
||||
None => return Err(ShxError::Source(line, "specification bytes before any *number,defbytes,NAME line".into())),
|
||||
}
|
||||
}
|
||||
let mut shapes: Vec<Shape> = Vec::new();
|
||||
for (num, name, line, toks) in defs {
|
||||
let number = u16::try_from(num).map_err(|_| ShxError::Source(line, format!("shape number {num} out of range")))?;
|
||||
let program = if number == 0 {
|
||||
// The font record: plain bytes.
|
||||
toks.iter().map(|x| u8::try_from(*x).map_err(|_| ShxError::Source(line, "bad font record".into()))).collect::<Result<Vec<u8>, _>>()?
|
||||
} else {
|
||||
Enc { toks: &toks, i: 0, out: Vec::new(), kind, line }.program()?
|
||||
};
|
||||
if shapes.iter().any(|s| s.number == number) {
|
||||
return Err(ShxError::Source(line, format!("shape {number} is defined twice")));
|
||||
}
|
||||
shapes.push(Shape { number, name, program });
|
||||
}
|
||||
if shapes.is_empty() {
|
||||
return Err(ShxError::Empty);
|
||||
}
|
||||
shapes.sort_by_key(|s| s.number);
|
||||
let record = |s: &Shape| -> Result<Vec<u8>, ShxError> {
|
||||
let mut r: Vec<u8> = s.name.bytes().filter(|b| *b != 0).collect();
|
||||
r.push(0);
|
||||
r.extend(&s.program);
|
||||
if r.len() > usize::from(u16::MAX) { Err(ShxError::TooLarge) } else { Ok(r) }
|
||||
};
|
||||
let count = u16::try_from(shapes.len()).map_err(|_| ShxError::TooLarge)?;
|
||||
let len16 = |r: &[u8]| u16::try_from(r.len()).unwrap_or(u16::MAX);
|
||||
let mut out = Vec::new();
|
||||
match kind {
|
||||
Kind::Shapes => {
|
||||
out.extend(SHAPES_10);
|
||||
out.extend(shapes.first().map_or(0, |s| s.number).to_le_bytes());
|
||||
out.extend(shapes.last().map_or(0, |s| s.number).to_le_bytes());
|
||||
out.extend(count.to_le_bytes());
|
||||
let recs: Vec<Vec<u8>> = shapes.iter().map(record).collect::<Result<_, _>>()?;
|
||||
for (s, r) in shapes.iter().zip(&recs) {
|
||||
out.extend(s.number.to_le_bytes());
|
||||
out.extend(len16(r).to_le_bytes());
|
||||
}
|
||||
for r in &recs {
|
||||
out.extend(r);
|
||||
}
|
||||
out.extend(b"EOF");
|
||||
}
|
||||
Kind::Big => {
|
||||
out.extend(BIGFONT);
|
||||
let nranges = u16::try_from(ranges.len()).map_err(|_| ShxError::TooLarge)?;
|
||||
out.extend(count.to_le_bytes());
|
||||
out.extend(count.to_le_bytes());
|
||||
out.extend(nranges.to_le_bytes());
|
||||
for (lo, hi) in &ranges {
|
||||
out.extend(lo.to_le_bytes());
|
||||
out.extend(hi.to_le_bytes());
|
||||
}
|
||||
let recs: Vec<Vec<u8>> = shapes.iter().map(record).collect::<Result<_, _>>()?;
|
||||
let mut off = out.len() + 8 * recs.len();
|
||||
for (s, r) in shapes.iter().zip(&recs) {
|
||||
out.extend(s.number.to_le_bytes());
|
||||
out.extend(len16(r).to_le_bytes());
|
||||
out.extend(u32::try_from(off).map_err(|_| ShxError::TooLarge)?.to_le_bytes());
|
||||
off += r.len();
|
||||
}
|
||||
for r in &recs {
|
||||
out.extend(r);
|
||||
}
|
||||
}
|
||||
Kind::Uni => {
|
||||
out.extend(UNIFONT);
|
||||
let (name, info) = uni_info.unwrap_or_default();
|
||||
out.extend((u32::from(count) + 1).to_le_bytes());
|
||||
let mut rec: Vec<u8> = name.bytes().filter(|b| *b != 0).collect();
|
||||
rec.push(0);
|
||||
rec.extend(&info);
|
||||
out.extend(len16(&rec).to_le_bytes());
|
||||
out.extend(&rec);
|
||||
for s in &shapes {
|
||||
let r = record(s)?;
|
||||
out.extend(s.number.to_le_bytes());
|
||||
out.extend(len16(&r).to_le_bytes());
|
||||
out.extend(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -26,7 +26,6 @@
|
||||
//! above, below, modes, encoding, embedding, 0) and then each shape as (number, length,
|
||||
//! record).
|
||||
|
||||
mod compile;
|
||||
mod parse;
|
||||
mod program;
|
||||
mod table;
|
||||
@@ -39,7 +38,8 @@ use std::sync::{Arc, PoisonError, RwLock};
|
||||
|
||||
use cadcraft_geom::Vec2;
|
||||
|
||||
pub use compile::compile;
|
||||
use craft_shx::Record;
|
||||
pub use craft_shx::{ShxError, ShxKind, compile};
|
||||
pub use table::{
|
||||
FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, installed, register, search_path, set_font_dirs,
|
||||
set_font_map, set_provider, set_search_path,
|
||||
@@ -47,46 +47,6 @@ pub use table::{
|
||||
pub use text::ShxText;
|
||||
pub(crate) use text::{shape, width};
|
||||
|
||||
/// Why a font file can't be read or a shape source can't be compiled.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ShxError {
|
||||
/// Not an SHX file (unknown signature).
|
||||
NotShx,
|
||||
/// The file ends inside its header or index.
|
||||
Truncated,
|
||||
/// The file is larger, or has more of something, than CADCraft reads.
|
||||
TooLarge,
|
||||
/// The file is well-formed but holds no shape.
|
||||
Empty,
|
||||
/// Shape source error: line and message.
|
||||
Source(usize, String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ShxError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ShxError::NotShx => f.write_str("not an SHX shape or font file"),
|
||||
ShxError::Truncated => f.write_str("the SHX file is truncated"),
|
||||
ShxError::TooLarge => f.write_str("the SHX file is too large"),
|
||||
ShxError::Empty => f.write_str("the SHX file has no shapes"),
|
||||
ShxError::Source(line, msg) => write!(f, "line {line}: {msg}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ShxError {}
|
||||
|
||||
/// The kind of SHX file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ShxKind {
|
||||
/// A shape file or a text font with single-byte character codes (`shapes 1.0/1.1`).
|
||||
Shapes,
|
||||
/// A big font: double-byte character codes after an escape (lead) byte.
|
||||
BigFont,
|
||||
/// A Unicode font: shape numbers are Unicode code points.
|
||||
Unifont,
|
||||
}
|
||||
|
||||
/// A shape's program run into polylines, in font units (pen starts at the origin).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ShxGlyph {
|
||||
@@ -96,13 +56,6 @@ pub struct ShxGlyph {
|
||||
pub advance: Vec2,
|
||||
}
|
||||
|
||||
/// One shape record: where its name and program are in [`ShxFont::data`].
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Record {
|
||||
name: (usize, usize),
|
||||
program: (usize, usize),
|
||||
}
|
||||
|
||||
/// Glyphs cached per font, keyed by (shape, vertical).
|
||||
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
|
||||
|
||||
|
||||
+21
-220
@@ -1,225 +1,26 @@
|
||||
//! Reading the compiled SHX containers (layouts in the module documentation). Every count and
|
||||
//! offset comes from the file, so each is checked against its length; records that run past
|
||||
//! the end are dropped and the rest kept.
|
||||
//! Bridge the shared bounded container reader into CADCraft's font and glyph cache.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use super::{ShxError, ShxFont};
|
||||
pub(super) use craft_shx::parse::MAX_FILE_BYTES;
|
||||
#[cfg(test)]
|
||||
pub(super) use craft_shx::parse::{BIGFONT, SHAPES_10, UNIFONT};
|
||||
use std::sync::RwLock;
|
||||
|
||||
use super::{Record, ShxError, ShxFont, ShxKind};
|
||||
|
||||
pub(super) const SHAPES_10: &[u8] = b"AutoCAD-86 shapes 1.0\r\n\x1a";
|
||||
pub(super) const SHAPES_11: &[u8] = b"AutoCAD-86 shapes 1.1\r\n\x1a";
|
||||
pub(super) const BIGFONT: &[u8] = b"AutoCAD-86 bigfont 1.0\r\n\x1a";
|
||||
pub(super) const UNIFONT: &[u8] = b"AutoCAD-86 unifont 1.0\r\n\x1a";
|
||||
|
||||
/// Largest file read (the largest big fonts are a few megabytes).
|
||||
pub(super) const MAX_FILE_BYTES: usize = 32 << 20;
|
||||
/// Most escape ranges in a big font (lead bytes: at most 256).
|
||||
const MAX_RANGES: usize = 256;
|
||||
|
||||
/// A checked little-endian reader.
|
||||
struct Rd<'a> {
|
||||
b: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Rd<'a> {
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], ShxError> {
|
||||
let end = self.pos.checked_add(n).ok_or(ShxError::Truncated)?;
|
||||
let s = self.b.get(self.pos..end).ok_or(ShxError::Truncated)?;
|
||||
self.pos = end;
|
||||
Ok(s)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, ShxError> {
|
||||
match self.take(2)? {
|
||||
[a, b] => Ok(u16::from_le_bytes([*a, *b])),
|
||||
_ => Err(ShxError::Truncated),
|
||||
}
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, ShxError> {
|
||||
match self.take(4)? {
|
||||
[a, b, c, d] => Ok(u32::from_le_bytes([*a, *b, *c, *d])),
|
||||
_ => Err(ShxError::Truncated),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A font being read.
|
||||
struct Font {
|
||||
kind: ShxKind,
|
||||
name: String,
|
||||
header: bool,
|
||||
above: f64,
|
||||
below: f64,
|
||||
dual: bool,
|
||||
encoding: u8,
|
||||
char_width: f64,
|
||||
ranges: Vec<(u16, u16)>,
|
||||
records: HashMap<u16, Record>,
|
||||
}
|
||||
|
||||
impl Font {
|
||||
fn new(kind: ShxKind) -> Font {
|
||||
Font {
|
||||
kind,
|
||||
name: String::new(),
|
||||
header: false,
|
||||
above: 0.0,
|
||||
below: 0.0,
|
||||
dual: false,
|
||||
encoding: 0,
|
||||
char_width: 0.0,
|
||||
ranges: Vec::new(),
|
||||
records: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the record of shape `number` at `start..end` of `data`: a NUL-terminated name, then
|
||||
/// the program. Shape 0 is the font record. A record without a name terminator is dropped;
|
||||
/// the first record of a number wins.
|
||||
fn record(&mut self, data: &[u8], number: u16, start: usize, end: usize) {
|
||||
let Some(bytes) = data.get(start..end) else { return };
|
||||
let Some(nul) = bytes.iter().position(|b| *b == 0) else { return };
|
||||
let name = (start, start + nul);
|
||||
let program = (start + nul + 1, end);
|
||||
if number == 0 {
|
||||
if !self.header {
|
||||
self.font_record(data.get(program.0..program.1).unwrap_or_default(), data.get(name.0..name.1).unwrap_or_default());
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.records.entry(number).or_insert(Record { name, program });
|
||||
}
|
||||
|
||||
/// The font record: above, below, modes (and for a unifont encoding and embedding); an
|
||||
/// extended big font's is character height, 0, modes, character width.
|
||||
fn font_record(&mut self, info: &[u8], name: &[u8]) {
|
||||
self.header = true;
|
||||
self.name = name.iter().take(255).map(|c| char::from(*c)).collect();
|
||||
let byte = |i: usize| info.get(i).copied().unwrap_or(0);
|
||||
self.above = f64::from(byte(0));
|
||||
self.below = f64::from(byte(1));
|
||||
self.dual = byte(2) == 2;
|
||||
if self.kind == ShxKind::Unifont {
|
||||
self.encoding = byte(3);
|
||||
}
|
||||
if self.kind == ShxKind::BigFont && info.len() >= 5 && byte(1) == 0 {
|
||||
// Extended: height, 0, modes, width, 0.
|
||||
self.below = 0.0;
|
||||
self.char_width = f64::from(byte(3));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, data: Vec<u8>) -> Result<ShxFont, ShxError> {
|
||||
if self.records.is_empty() {
|
||||
return Err(ShxError::Empty);
|
||||
}
|
||||
Ok(ShxFont {
|
||||
kind: self.kind,
|
||||
name: self.name,
|
||||
header: self.header,
|
||||
above: self.above,
|
||||
below: self.below,
|
||||
dual: self.dual,
|
||||
encoding: self.encoding,
|
||||
char_width: if self.char_width > 0.0 { self.char_width } else { self.above },
|
||||
ranges: self.ranges,
|
||||
data,
|
||||
records: self.records,
|
||||
cache: RwLock::default(),
|
||||
hebrew: std::sync::OnceLock::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
||||
if bytes.len() > MAX_FILE_BYTES {
|
||||
return Err(ShxError::TooLarge);
|
||||
}
|
||||
if bytes.starts_with(SHAPES_10) || bytes.starts_with(SHAPES_11) {
|
||||
shapes(bytes)
|
||||
} else if bytes.starts_with(BIGFONT) {
|
||||
bigfont(bytes)
|
||||
} else if bytes.starts_with(UNIFONT) {
|
||||
unifont(bytes)
|
||||
} else {
|
||||
Err(ShxError::NotShx)
|
||||
}
|
||||
}
|
||||
|
||||
fn shapes(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
||||
let mut r = Rd { b: bytes, pos: SHAPES_10.len() };
|
||||
let _first = r.u16()?;
|
||||
let _last = r.u16()?;
|
||||
let count = usize::from(r.u16()?);
|
||||
// The whole index must be there before anything is read from it.
|
||||
let index = r.take(count.checked_mul(4).ok_or(ShxError::TooLarge)?)?;
|
||||
let mut f = Font::new(ShxKind::Shapes);
|
||||
let mut pos = r.pos;
|
||||
for [a, b, c, d] in index.as_chunks::<4>().0 {
|
||||
let (number, len) = (u16::from_le_bytes([*a, *b]), usize::from(u16::from_le_bytes([*c, *d])));
|
||||
let Some(end) = pos.checked_add(len).filter(|e| *e <= bytes.len()) else { break };
|
||||
f.record(bytes, number, pos, end);
|
||||
pos = end;
|
||||
}
|
||||
f.finish(bytes.to_vec())
|
||||
}
|
||||
|
||||
fn bigfont(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
||||
let mut r = Rd { b: bytes, pos: BIGFONT.len() };
|
||||
let index_size = usize::from(r.u16()?);
|
||||
let count = usize::from(r.u16()?);
|
||||
let nranges = usize::from(r.u16()?);
|
||||
if nranges > MAX_RANGES {
|
||||
return Err(ShxError::TooLarge);
|
||||
}
|
||||
let mut f = Font::new(ShxKind::BigFont);
|
||||
for _ in 0..nranges {
|
||||
let (lo, hi) = (r.u16()?, r.u16()?);
|
||||
f.ranges.push((lo.min(hi), lo.max(hi)));
|
||||
}
|
||||
// The index has `count` entries of 8 bytes; a file whose count doesn't fit but whose index
|
||||
// size does is read by that.
|
||||
let fits = |n: usize| n.checked_mul(8).and_then(|l| r.pos.checked_add(l)).is_some_and(|e| e <= bytes.len());
|
||||
let n = if fits(count) {
|
||||
count
|
||||
} else if fits(index_size) {
|
||||
index_size
|
||||
} else {
|
||||
return Err(ShxError::Truncated);
|
||||
};
|
||||
let index = r.take(n.checked_mul(8).ok_or(ShxError::TooLarge)?)?;
|
||||
for [a, b, c, d, o0, o1, o2, o3] in index.as_chunks::<8>().0 {
|
||||
let number = u16::from_le_bytes([*a, *b]);
|
||||
let len = usize::from(u16::from_le_bytes([*c, *d]));
|
||||
let Ok(off) = usize::try_from(u32::from_le_bytes([*o0, *o1, *o2, *o3])) else { continue };
|
||||
if len == 0 {
|
||||
continue;
|
||||
}
|
||||
let Some(end) = off.checked_add(len).filter(|e| *e <= bytes.len()) else { continue };
|
||||
f.record(bytes, number, off, end);
|
||||
}
|
||||
f.finish(bytes.to_vec())
|
||||
}
|
||||
|
||||
fn unifont(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
||||
let mut r = Rd { b: bytes, pos: UNIFONT.len() };
|
||||
let count = r.u32()?;
|
||||
let info_len = usize::from(r.u16()?);
|
||||
let info = r.take(info_len)?;
|
||||
let mut f = Font::new(ShxKind::Unifont);
|
||||
let nul = info.iter().position(|b| *b == 0).unwrap_or(info.len());
|
||||
f.font_record(info.get(nul.saturating_add(1)..).unwrap_or_default(), info.get(..nul).unwrap_or_default());
|
||||
// `count` includes the font record; never trusted beyond the data that is there.
|
||||
let mut left = count.saturating_sub(1);
|
||||
while left > 0 {
|
||||
left -= 1;
|
||||
let Ok(number) = r.u16() else { break };
|
||||
let Ok(len) = r.u16().map(usize::from) else { break };
|
||||
let start = r.pos;
|
||||
let Some(end) = start.checked_add(len).filter(|e| *e <= bytes.len()) else { break };
|
||||
r.pos = end;
|
||||
f.record(bytes, number, start, end);
|
||||
}
|
||||
f.finish(bytes.to_vec())
|
||||
let font = craft_shx::parse::parse(bytes)?;
|
||||
Ok(ShxFont {
|
||||
kind: font.kind,
|
||||
name: font.name,
|
||||
header: font.header,
|
||||
above: font.above,
|
||||
below: font.below,
|
||||
dual: font.dual,
|
||||
encoding: font.encoding,
|
||||
char_width: font.char_width,
|
||||
ranges: font.ranges,
|
||||
data: font.data,
|
||||
records: font.records,
|
||||
cache: RwLock::default(),
|
||||
hebrew: std::sync::OnceLock::new(),
|
||||
})
|
||||
}
|
||||
|
||||
+23
-338
@@ -1,344 +1,29 @@
|
||||
//! The shape pen program: vector length/direction bytes and special codes 0–14, run into
|
||||
//! polylines. Bounded everywhere: subshape depth, location stack, steps, points, coordinates.
|
||||
//!
|
||||
//! - A byte with a non-zero high nibble is a vector: length (high nibble) in one of 16
|
||||
//! directions (low nibble, counter-clockwise from east in 22.5° steps; the off-axis ones
|
||||
//! are half-unit or unit steps on the minor axis).
|
||||
//! - 0 end, 1 pen down, 2 pen up, 3/4 divide/multiply vector lengths by the next byte,
|
||||
//! 5/6 push/pop the location, 7 subshape (one byte; two bytes high first in a Unicode font;
|
||||
//! `0`, a two-byte number, base point, width and height in an extended big font),
|
||||
//! 8 one X-Y displacement, 9 displacements up to (0,0), 10 octant arc (radius,
|
||||
//! ±0SC: sign = clockwise, S start octant, C octants, 0 = 8), 11 fractional arc (start
|
||||
//! offset, end offset, high and low radius, ±0SC; offsets in 1/256 of 45° from the octant
|
||||
//! boundaries), 12 bulge arc (dx, dy, bulge: ±127 = semicircle), 13 bulge arcs up to (0,0),
|
||||
//! 14 the next command is for vertical text only (dual-orientation fonts).
|
||||
//! - Displacements and bulges are two's complement bytes; the arc direction byte keeps its
|
||||
//! sign in the high bit.
|
||||
|
||||
use std::f64::consts::{FRAC_PI_4, TAU};
|
||||
|
||||
//! Map the shared SHX pen interpreter's neutral strokes into CAD geometry.
|
||||
use super::{ShxFont, ShxGlyph, ShxKind};
|
||||
use cadcraft_geom::Vec2;
|
||||
|
||||
use super::{ShxFont, ShxGlyph, ShxKind};
|
||||
|
||||
/// Subshape nesting (a cycle ends here).
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// Location stack (the format promises four).
|
||||
const MAX_STACK: usize = 64;
|
||||
/// Bytes run per glyph, subshapes included.
|
||||
const MAX_STEPS: usize = 200_000;
|
||||
/// Points per glyph.
|
||||
const MAX_POINTS: usize = 50_000;
|
||||
/// Coordinates in font units.
|
||||
const MAX_COORD: f64 = 1.0e7;
|
||||
/// Arc segments per full turn.
|
||||
const ARC_STEPS: f64 = 64.0;
|
||||
|
||||
/// Why a program stops early: the glyph is then not drawn.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Broken;
|
||||
|
||||
type Res = Result<(), Broken>;
|
||||
|
||||
struct Pen<'a> {
|
||||
font: &'a ShxFont,
|
||||
vertical: bool,
|
||||
pos: Vec2,
|
||||
down: bool,
|
||||
/// Vector length factor (codes 3 and 4).
|
||||
scale: f64,
|
||||
/// Per-axis factor of an extended big font subshape.
|
||||
axes: Vec2,
|
||||
stack: Vec<Vec2>,
|
||||
strokes: Vec<Vec<Vec2>>,
|
||||
active: Vec<Vec2>,
|
||||
steps: usize,
|
||||
points: usize,
|
||||
}
|
||||
|
||||
pub(super) fn outline(font: &ShxFont, number: u16, vertical: bool) -> Result<ShxGlyph, Broken> {
|
||||
let mut pen = Pen {
|
||||
font,
|
||||
vertical,
|
||||
pos: Vec2::ZERO,
|
||||
down: true,
|
||||
scale: 1.0,
|
||||
axes: Vec2::new(1.0, 1.0),
|
||||
stack: Vec::new(),
|
||||
strokes: Vec::new(),
|
||||
active: Vec::new(),
|
||||
steps: 0,
|
||||
points: 0,
|
||||
};
|
||||
pen.run(number, 0)?;
|
||||
pen.flush();
|
||||
Ok(ShxGlyph { strokes: pen.strokes, advance: pen.pos })
|
||||
}
|
||||
|
||||
/// The 16 vector directions (unit length on the major axis).
|
||||
fn direction(d: u8) -> Vec2 {
|
||||
let (x, y) = match d & 15 {
|
||||
0 => (1.0, 0.0),
|
||||
1 => (1.0, 0.5),
|
||||
2 => (1.0, 1.0),
|
||||
3 => (0.5, 1.0),
|
||||
4 => (0.0, 1.0),
|
||||
5 => (-0.5, 1.0),
|
||||
6 => (-1.0, 1.0),
|
||||
7 => (-1.0, 0.5),
|
||||
8 => (-1.0, 0.0),
|
||||
9 => (-1.0, -0.5),
|
||||
10 => (-1.0, -1.0),
|
||||
11 => (-0.5, -1.0),
|
||||
12 => (0.0, -1.0),
|
||||
13 => (0.5, -1.0),
|
||||
14 => (1.0, -1.0),
|
||||
_ => (1.0, -0.5),
|
||||
};
|
||||
Vec2::new(x, y)
|
||||
}
|
||||
|
||||
/// A two's complement operand byte.
|
||||
fn signed(b: u8) -> f64 {
|
||||
f64::from(i8::from_le_bytes([b]))
|
||||
}
|
||||
|
||||
/// A program being read: its bytes and position.
|
||||
struct Cur<'p> {
|
||||
b: &'p [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Cur<'_> {
|
||||
fn byte(&mut self) -> Result<u8, Broken> {
|
||||
let v = self.b.get(self.pos).copied().ok_or(Broken)?;
|
||||
self.pos += 1;
|
||||
Ok(v)
|
||||
impl craft_shx::program::Font for ShxFont {
|
||||
fn kind(&self) -> ShxKind {
|
||||
self.kind
|
||||
}
|
||||
fn dual(&self) -> bool {
|
||||
self.dual
|
||||
}
|
||||
fn above(&self) -> f64 {
|
||||
self.above
|
||||
}
|
||||
fn char_width(&self) -> f64 {
|
||||
self.char_width
|
||||
}
|
||||
fn program(&self, number: u16) -> Option<&[u8]> {
|
||||
ShxFont::program(self, number)
|
||||
}
|
||||
}
|
||||
|
||||
impl Pen<'_> {
|
||||
fn step(&mut self) -> Res {
|
||||
self.steps += 1;
|
||||
if self.steps > MAX_STEPS { Err(Broken) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn flush(&mut self) {
|
||||
if self.active.len() >= 2 {
|
||||
self.strokes.push(std::mem::take(&mut self.active));
|
||||
} else {
|
||||
self.active.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the pen by `d` font units (already scaled), drawing when the pen is down.
|
||||
fn to(&mut self, target: Vec2) -> Res {
|
||||
if !target.is_finite() || target.x.abs().max(target.y.abs()) > MAX_COORD {
|
||||
return Err(Broken);
|
||||
}
|
||||
if self.down {
|
||||
if self.active.is_empty() {
|
||||
self.active.push(self.pos);
|
||||
self.points += 1;
|
||||
}
|
||||
self.active.push(target);
|
||||
self.points += 1;
|
||||
if self.points > MAX_POINTS {
|
||||
return Err(Broken);
|
||||
}
|
||||
} else {
|
||||
self.flush();
|
||||
}
|
||||
self.pos = target;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A displacement in vector units (times the length factor and the subshape axes).
|
||||
fn by(&mut self, d: Vec2) -> Res {
|
||||
let k = d * self.scale;
|
||||
self.to(self.pos + Vec2::new(k.x * self.axes.x, k.y * self.axes.y))
|
||||
}
|
||||
|
||||
/// An arc of `radius` vector units from the pen, starting at angle `start` on its circle
|
||||
/// and turning `sweep` radians (positive counter-clockwise).
|
||||
fn arc(&mut self, radius: f64, start: f64, sweep: f64) -> Res {
|
||||
let r = radius * self.scale;
|
||||
if !(r.is_finite() && r > 0.0 && sweep.is_finite()) {
|
||||
return Ok(());
|
||||
}
|
||||
let n = if self.down { (sweep.abs() / TAU * ARC_STEPS).ceil().clamp(1.0, ARC_STEPS) as usize } else { 1 };
|
||||
let from = self.pos;
|
||||
let s0 = Vec2::new(start.cos(), start.sin());
|
||||
for i in 1..=n {
|
||||
let a = start + sweep * i as f64 / n as f64;
|
||||
let d = (Vec2::new(a.cos(), a.sin()) - s0) * r;
|
||||
self.to(from + Vec2::new(d.x * self.axes.x, d.y * self.axes.y))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An arc to the displacement `d` with `bulge` (−127..127, ±127 a semicircle).
|
||||
fn bulge(&mut self, d: Vec2, bulge: f64) -> Res {
|
||||
let b = bulge.clamp(-127.0, 127.0) / 127.0;
|
||||
if b == 0.0 || !self.down || d.len2() == 0.0 {
|
||||
return self.by(d);
|
||||
}
|
||||
// Centre from the chord midpoint along its left normal; sweep 4·atan(b).
|
||||
let centre = d * 0.5 + Vec2::new(-d.y, d.x) * ((1.0 - b * b) / (4.0 * b));
|
||||
let rel = -centre;
|
||||
self.arc(rel.len(), rel.y.atan2(rel.x), 4.0 * b.atan())
|
||||
}
|
||||
|
||||
/// The octant byte `±0SC`: (clockwise, start octant, octants with 0 = 8).
|
||||
fn octants(spec: u8) -> (f64, f64, f64) {
|
||||
let sign = if spec & 0x80 != 0 { -1.0 } else { 1.0 };
|
||||
let s = f64::from((spec >> 4) & 7);
|
||||
let c = match spec & 7 {
|
||||
0 => 8.0,
|
||||
c => f64::from(c),
|
||||
};
|
||||
(sign, s, c)
|
||||
}
|
||||
|
||||
/// The vector unit size of an extended big font's subshape cell.
|
||||
fn cell(&self) -> Vec2 {
|
||||
let h = if self.font.above > 0.0 { self.font.above } else { 1.0 };
|
||||
let w = if self.font.char_width > 0.0 { self.font.char_width } else { h };
|
||||
Vec2::new(w, h)
|
||||
}
|
||||
|
||||
fn run(&mut self, number: u16, depth: usize) -> Res {
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err(Broken);
|
||||
}
|
||||
let program = self.font.program(number).ok_or(Broken)?;
|
||||
let mut r = Cur { b: program, pos: 0 };
|
||||
let mut skip = false;
|
||||
while r.pos < r.b.len() {
|
||||
self.step()?;
|
||||
let code = r.byte()?;
|
||||
// Code 14: in a dual-orientation font the next command is for vertical text only.
|
||||
let exec = !skip;
|
||||
skip = false;
|
||||
match code {
|
||||
0 => return Ok(()),
|
||||
1 if exec => self.down = true,
|
||||
2 if exec => {
|
||||
self.down = false;
|
||||
self.flush();
|
||||
}
|
||||
3 | 4 => {
|
||||
let k = f64::from(r.byte()?);
|
||||
if exec && k > 0.0 {
|
||||
let s = if code == 3 { self.scale / k } else { self.scale * k };
|
||||
if !(1e-9..=MAX_COORD).contains(&s) {
|
||||
return Err(Broken);
|
||||
}
|
||||
self.scale = s;
|
||||
}
|
||||
}
|
||||
5 if exec => {
|
||||
if self.stack.len() >= MAX_STACK {
|
||||
return Err(Broken);
|
||||
}
|
||||
self.stack.push(self.pos);
|
||||
}
|
||||
6 if exec => {
|
||||
self.flush();
|
||||
if let Some(p) = self.stack.pop() {
|
||||
self.pos = p;
|
||||
}
|
||||
}
|
||||
7 => self.subshape(&mut r, exec, depth)?,
|
||||
8 | 9 | 12 | 13 => loop {
|
||||
self.step()?;
|
||||
let d = Vec2::new(signed(r.byte()?), signed(r.byte()?));
|
||||
if matches!(code, 9 | 13) && d == Vec2::ZERO {
|
||||
break;
|
||||
}
|
||||
let bulge = if matches!(code, 12 | 13) { signed(r.byte()?) } else { 0.0 };
|
||||
if exec {
|
||||
self.bulge(d, bulge)?;
|
||||
}
|
||||
if matches!(code, 8 | 12) {
|
||||
break;
|
||||
}
|
||||
},
|
||||
10 => {
|
||||
let radius = f64::from(r.byte()?);
|
||||
let (sign, s, c) = Self::octants(r.byte()?);
|
||||
if exec {
|
||||
self.arc(radius, s * FRAC_PI_4, sign * c * FRAC_PI_4)?;
|
||||
}
|
||||
}
|
||||
11 => {
|
||||
let start = f64::from(r.byte()?) / 256.0;
|
||||
let end = match r.byte()? {
|
||||
0 => 1.0,
|
||||
e => f64::from(e) / 256.0,
|
||||
};
|
||||
let radius = f64::from(u16::from_be_bytes([r.byte()?, r.byte()?]));
|
||||
let (sign, s, c) = Self::octants(r.byte()?);
|
||||
if exec {
|
||||
// From `start` past the first octant boundary to `end` past the last
|
||||
// octant's.
|
||||
self.arc(radius, (s + sign * start) * FRAC_PI_4, sign * (c - 1.0 + end - start) * FRAC_PI_4)?;
|
||||
}
|
||||
}
|
||||
14 => skip = self.font.dual && !self.vertical && exec,
|
||||
1..=15 => {}
|
||||
v => {
|
||||
if exec {
|
||||
self.by(direction(v) * f64::from(v >> 4))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Code 7 and its operands.
|
||||
fn subshape(&mut self, r: &mut Cur, exec: bool, depth: usize) -> Res {
|
||||
match self.font.kind {
|
||||
ShxKind::Unifont => {
|
||||
let n = u16::from_be_bytes([r.byte()?, r.byte()?]);
|
||||
if exec {
|
||||
self.run(n, depth + 1)?;
|
||||
}
|
||||
}
|
||||
ShxKind::BigFont => {
|
||||
let first = r.byte()?;
|
||||
if first != 0 {
|
||||
if exec {
|
||||
self.run(u16::from(first), depth + 1)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// Extended: the primitive drawn in the box (x, y, width, height) of the cell.
|
||||
let n = u16::from_be_bytes([r.byte()?, r.byte()?]);
|
||||
let (x, y, w, h) = (f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?));
|
||||
if !exec {
|
||||
return Ok(());
|
||||
}
|
||||
let (pos, axes, down) = (self.pos, self.axes, self.down);
|
||||
let cell = self.cell();
|
||||
self.flush();
|
||||
self.pos = pos + Vec2::new(x * axes.x, y * axes.y) * self.scale;
|
||||
self.axes = Vec2::new(axes.x * w / cell.x, axes.y * h / cell.y);
|
||||
let res = self.run(n, depth + 1);
|
||||
self.flush();
|
||||
self.axes = axes;
|
||||
self.pos = pos;
|
||||
self.down = down;
|
||||
res?;
|
||||
}
|
||||
ShxKind::Shapes => {
|
||||
let n = u16::from(r.byte()?);
|
||||
if exec {
|
||||
self.run(n, depth + 1)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn outline(font: &ShxFont, number: u16, vertical: bool) -> Result<ShxGlyph, craft_shx::program::Broken> {
|
||||
let glyph = craft_shx::program::outline(font, number, vertical)?;
|
||||
Ok(ShxGlyph {
|
||||
strokes: glyph.strokes.into_iter().map(|stroke| stroke.into_iter().map(|p| Vec2::new(p.x, p.y)).collect()).collect(),
|
||||
advance: Vec2::new(glyph.advance.x, glyph.advance.y),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,8 +8,10 @@
|
||||
pub(crate) const CAP: f64 = 6.0;
|
||||
pub(crate) const GAP: f64 = 1.6;
|
||||
|
||||
// List bullet: a small crossed diamond at mid x-height.
|
||||
#[expect(clippy::too_many_lines, reason = "The stroke font is one static glyph table; splitting it would obscure the character-to-outline mapping.")]
|
||||
pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> {
|
||||
let g: (f64, &str) = match c {
|
||||
Some(match c {
|
||||
' ' => (2.4, ""),
|
||||
'A' => (4.0, "0c2i4c 1f3f"),
|
||||
'B' => (4.0, "0c0i3i4h4g3f0f 3f4e4d3c0c"),
|
||||
@@ -25,7 +27,6 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> {
|
||||
'L' => (4.0, "0i0c4c"),
|
||||
'M' => (4.0, "0c0i2f4i4c"),
|
||||
'N' => (4.0, "0c0i4c4i"),
|
||||
'O' => (4.0, "1c0d0h1i3i4h4d3c1c"),
|
||||
'P' => (4.0, "0c0i3i4h4g3f0f"),
|
||||
'Q' => (4.0, "1c0d0h1i3i4h4d3c1c 2e4b"),
|
||||
'R' => (4.0, "0c0i3i4h4g3f0f 2f4c"),
|
||||
@@ -37,7 +38,7 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> {
|
||||
'X' => (4.0, "0i4c 0c4i"),
|
||||
'Y' => (4.0, "0i2f4i 2f2c"),
|
||||
'Z' => (4.0, "0i4i0c4c"),
|
||||
'0' => (4.0, "1c0d0h1i3i4h4d3c1c"),
|
||||
'O' | '0' => (4.0, "1c0d0h1i3i4h4d3c1c"),
|
||||
'1' => (4.0, "1h2i2c 1c3c"),
|
||||
'2' => (4.0, "0h1i3i4h4g0c4c"),
|
||||
'3' => (4.0, "0h1i3i4h4g3f2f 3f4e4d3c1c0d"),
|
||||
@@ -108,7 +109,6 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> {
|
||||
'°' => (2.0, "1i0h1g2h1i"),
|
||||
'±' => (4.0, "2e2i 0g4g 0d4d"),
|
||||
'Ø' | 'ø' | '⌀' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"),
|
||||
// List bullet: a small crossed diamond at mid x-height.
|
||||
'•' => (2.0, "1d0e1f2e1d 0e2e 1d1f"),
|
||||
// Original Latin diacritics, composed from our own letter bodies and marks.
|
||||
'\u{00C0}' => (4.0, concat!("0c2i4c 1f3f", " 1k3j")),
|
||||
@@ -166,8 +166,7 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> {
|
||||
'\u{00FF}' => (4.0, concat!("0g2c 4g1a0a", " 1h1i 3h3i")),
|
||||
'\u{0178}' => (4.0, concat!("0i2f4i 2f2c", " 1j1k 3j3k")),
|
||||
_ => return None,
|
||||
};
|
||||
Some(g)
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode one stroke string into point lists in font units.
|
||||
|
||||
@@ -3,50 +3,14 @@
|
||||
//! never embedded; callers draw their text as outlines instead. Fonts without TrueType outlines
|
||||
//! (CFF-flavoured OpenType) aren't embedded either.
|
||||
|
||||
use skrifa::FontRef;
|
||||
use skrifa::raw::types::Tag;
|
||||
|
||||
use crate::ttf::Face;
|
||||
|
||||
/// Whether a face may be embedded as a subset.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Embedding {
|
||||
/// Installable, editable or preview & print embedding (or no OS/2 table).
|
||||
Allowed,
|
||||
/// `fsType` restricted licence: no embedding.
|
||||
Restricted,
|
||||
/// `fsType` bit 8: the font may only be embedded whole.
|
||||
NoSubsetting,
|
||||
/// `fsType` bit 9: only bitmaps may be embedded.
|
||||
BitmapOnly,
|
||||
/// No TrueType outlines (`glyf` / `loca`), or the font doesn't parse.
|
||||
NotTrueType,
|
||||
}
|
||||
|
||||
fn table<'a>(f: &FontRef<'a>, t: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
f.table_data(Tag::new(t)).map(|d| d.as_bytes())
|
||||
}
|
||||
|
||||
fn u16_at(b: &[u8], i: usize) -> Option<u16> {
|
||||
Some(u16::from_be_bytes([*b.get(i)?, *b.get(i + 1)?]))
|
||||
}
|
||||
pub use craft_font_catalog::SubsetEmbedding as Embedding;
|
||||
|
||||
/// The embedding permission of a face.
|
||||
pub fn embedding(face: &Face) -> Embedding {
|
||||
let Ok(f) = FontRef::from_index(&face.bytes, face.index) else { return Embedding::NotTrueType };
|
||||
if table(&f, b"glyf").is_none() || table(&f, b"loca").is_none() || table(&f, b"head").is_none() {
|
||||
return Embedding::NotTrueType;
|
||||
}
|
||||
let Some(fs_type) = table(&f, b"OS/2").and_then(|o| u16_at(o, 8)) else { return Embedding::Allowed };
|
||||
if fs_type & 0x0200 != 0 {
|
||||
Embedding::BitmapOnly
|
||||
} else if fs_type & 0x000F == 0x0002 {
|
||||
Embedding::Restricted
|
||||
} else if fs_type & 0x0100 != 0 {
|
||||
Embedding::NoSubsetting
|
||||
} else {
|
||||
Embedding::Allowed
|
||||
}
|
||||
craft_font_catalog::subset_embedding(&face.bytes, face.index)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+38
-20
@@ -7,10 +7,10 @@
|
||||
//!
|
||||
//! System fonts are searched in the platform's own directories: `/System/Library/Fonts` and
|
||||
//! friends on macOS, `C:\Windows\Fonts` on Windows, `/system/fonts` and the product/vendor
|
||||
//! partitions on Android and HarmonyOS, and the XDG directories elsewhere. Web builds have no
|
||||
//! partitions on Android and `HarmonyOS`, and the XDG directories elsewhere. Web builds have no
|
||||
//! system fonts.
|
||||
//!
|
||||
//! Two process-wide settings (like AutoCAD's profile variables) control substitution:
|
||||
//! Two process-wide settings (like `AutoCAD`'s profile variables) control substitution:
|
||||
//! - [`font_alt`] (`FONTALT`): the font used for a text style font that can't be found (an SHX
|
||||
//! file we don't read, a missing TTF). Empty = the built-in stroke font.
|
||||
//! - [`fallback_fonts`] (`FONTFALLBACK`): fonts tried first for characters the text's font
|
||||
@@ -97,7 +97,7 @@ impl Face {
|
||||
pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec<Option<u32>> {
|
||||
let Some(f) = self.font() else { return vec![None; chars.len()] };
|
||||
let map = f.charmap();
|
||||
chars.iter().map(|c| map.map(*c).map(|g| g.to_u32())).collect()
|
||||
chars.iter().map(|c| map.map(*c).map(skrifa::GlyphId::to_u32)).collect()
|
||||
}
|
||||
fn names(&self) -> Vec<String> {
|
||||
let Some(f) = self.font() else { return Vec::new() };
|
||||
@@ -838,7 +838,13 @@ fn key(name: &str) -> String {
|
||||
|
||||
/// Names that mean a stroke font: never looked up as TrueType.
|
||||
fn is_stroke_name(k: &str) -> bool {
|
||||
k.is_empty() || k.ends_with(".shx") || k == crate::BUILTIN_FONT.to_ascii_lowercase() || k == "txt" || k == "simplex" || k == "romans"
|
||||
k.is_empty()
|
||||
|| k.ends_with(".shx")
|
||||
|| std::path::Path::new(k).extension().is_some_and(|extension| extension.eq_ignore_ascii_case("shx"))
|
||||
|| k == crate::BUILTIN_FONT.to_ascii_lowercase()
|
||||
|| k == "txt"
|
||||
|| k == "simplex"
|
||||
|| k == "romans"
|
||||
}
|
||||
|
||||
/// A face of an installed (or registered) font by file name or family name. Stroke-font names
|
||||
@@ -1025,26 +1031,31 @@ impl OutlinePen for Pen {
|
||||
self.push(Self::pt(x, y));
|
||||
}
|
||||
/// Flatten a quadratic segment into six samples, charging each retained point to the glyph budget.
|
||||
fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
|
||||
let a = self.cur.last().copied().unwrap_or_default();
|
||||
let c = Self::pt(cx0, cy0);
|
||||
let b = Self::pt(x, y);
|
||||
for i in 1..=6 {
|
||||
let t = f64::from(i) / 6.0;
|
||||
let u = 1.0 - t;
|
||||
self.push(a * (u * u) + c * (2.0 * u * t) + b * (t * t));
|
||||
fn quad_to(&mut self, cx0: f32, cy0: f32, end_x: f32, end_y: f32) {
|
||||
let start = self.cur.last().copied().unwrap_or_default();
|
||||
let control = Self::pt(cx0, cy0);
|
||||
let end = Self::pt(end_x, end_y);
|
||||
for step in 1..=6 {
|
||||
let ratio = f64::from(step) / 6.0;
|
||||
let inverse_ratio = 1.0 - ratio;
|
||||
self.push(start * (inverse_ratio * inverse_ratio) + control * (2.0 * inverse_ratio * ratio) + end * (ratio * ratio));
|
||||
}
|
||||
}
|
||||
/// Flatten a cubic segment into eight samples, charging each retained point to the glyph budget.
|
||||
fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
|
||||
let a = self.cur.last().copied().unwrap_or_default();
|
||||
fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, end_x: f32, end_y: f32) {
|
||||
let start = self.cur.last().copied().unwrap_or_default();
|
||||
let c0 = Self::pt(cx0, cy0);
|
||||
let c1 = Self::pt(cx1, cy1);
|
||||
let b = Self::pt(x, y);
|
||||
for i in 1..=8 {
|
||||
let t = f64::from(i) / 8.0;
|
||||
let u = 1.0 - t;
|
||||
self.push(a * (u * u * u) + c0 * (3.0 * u * u * t) + c1 * (3.0 * u * t * t) + b * (t * t * t));
|
||||
let end = Self::pt(end_x, end_y);
|
||||
for step in 1..=8 {
|
||||
let ratio = f64::from(step) / 8.0;
|
||||
let inverse_ratio = 1.0 - ratio;
|
||||
self.push(
|
||||
start * (inverse_ratio * inverse_ratio * inverse_ratio)
|
||||
+ c0 * (3.0 * inverse_ratio * inverse_ratio * ratio)
|
||||
+ c1 * (3.0 * inverse_ratio * ratio * ratio)
|
||||
+ end * (ratio * ratio * ratio),
|
||||
);
|
||||
}
|
||||
}
|
||||
fn close(&mut self) {
|
||||
@@ -1054,7 +1065,7 @@ impl OutlinePen for Pen {
|
||||
|
||||
/// How far below the baseline a face reaches, as a fraction of the text height (which is the
|
||||
/// face's cap height): its descent over its cap height. A bottom-justified text's alignment
|
||||
/// point is there, as AutoCAD places it (#2229). `None` when the face has no usable descent.
|
||||
/// point is there, as `AutoCAD` places it (#2229). `None` when the face has no usable descent.
|
||||
pub fn descent_ratio(face: &Face) -> Option<f64> {
|
||||
let f = face.font()?;
|
||||
let descent = -f64::from(f.metrics(Size::new(UPEM), LocationRef::default()).descent);
|
||||
@@ -1388,6 +1399,13 @@ mod family_tests {
|
||||
let many: Vec<String> = (0..100).map(|i| format!("gost{i:03}")).collect();
|
||||
assert!(family_candidates(&many, "gosttypea", "gost").len() <= MAX_FAMILY_FILES + MAX_FIRST_WORD_FILES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotfile_shx_names_are_stroke_names() {
|
||||
for name in [".shx", ".shx.ttf", ".SHX", ".SHX.TTF", "sub/.shx", "sub/.SHX"] {
|
||||
assert!(is_stroke_name(&key(name)), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -22,7 +22,7 @@ fn max_x(l: &MTextLayout) -> f64 {
|
||||
|
||||
/// Leftmost x of the geometry of line `n` (0 = first; baselines 5/3 apart below -1).
|
||||
fn line_min_x(l: &MTextLayout, n: usize) -> f64 {
|
||||
let base = -1.0 - n as f64 * 5.0 / 3.0;
|
||||
let base = -1.0 - f64::from(u32::try_from(n).unwrap_or(u32::MAX)) * 5.0 / 3.0;
|
||||
l.strokes.iter().flatten().filter(|p| p.y >= base - 0.4 && p.y <= base + 1.3).map(|p| p.x).fold(f64::MAX, f64::min)
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ fn paragraph_alignment_overrides_the_attachment() {
|
||||
let right = lay("\\pqr;ab", 10.0, None);
|
||||
assert!(max_x(&right) > 9.0 && max_x(&right) <= 10.0 + 1e-9, "{}", max_x(&right));
|
||||
let centre = lay("\\pqc;ab", 10.0, None);
|
||||
let c = (min_x(¢re) + max_x(¢re)) / 2.0;
|
||||
let c = f64::midpoint(min_x(¢re), max_x(¢re));
|
||||
assert!((c - 5.0).abs() < 0.5, "{c}");
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ fn text_flows_through_static_columns() {
|
||||
assert!((l.bounds.width() - 34.0).abs() < 1e-9);
|
||||
assert!((l.bounds.height() - 6.0).abs() < 1e-9);
|
||||
for col in 0..3 {
|
||||
let x0 = col as f64 * 12.0;
|
||||
let x0 = f64::from(col) * 12.0;
|
||||
assert!(xs(&l).iter().any(|x| *x >= x0 && *x <= x0 + 10.0), "column {col} has text");
|
||||
}
|
||||
// The gutters stay empty.
|
||||
|
||||
@@ -65,7 +65,7 @@ impl Bounds2 {
|
||||
// (max - min) can overflow even when both endpoints and their midpoint
|
||||
// are finite. Halve first when the endpoints have opposite signs.
|
||||
let mid = |a: f64, b: f64| {
|
||||
if a.is_sign_negative() != b.is_sign_negative() { a * 0.5 + b * 0.5 } else { a + (b - a) * 0.5 }
|
||||
if a.is_sign_negative() == b.is_sign_negative() { a + (b - a) * 0.5 } else { a * 0.5 + b * 0.5 }
|
||||
};
|
||||
Vec2::new(mid(self.min.x, self.max.x), mid(self.min.y, self.max.y))
|
||||
}
|
||||
@@ -101,17 +101,17 @@ mod tests {
|
||||
let b = Bounds2::new(Vec2::new(1e308, 0.0), Vec2::new(1.6e308, 10.0));
|
||||
assert!(b.center().x.is_finite());
|
||||
assert!((b.center().x / 1e308 - 1.3).abs() < 1e-12);
|
||||
assert_eq!(b.center().y, 5.0);
|
||||
assert_eq!(b.center().y.to_bits(), 5.0_f64.to_bits());
|
||||
assert_eq!(Bounds2::EMPTY.center(), Vec2::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn width_and_height_stay_finite_for_opposite_large_coordinates() {
|
||||
let b = Bounds2::new(Vec2::new(-1e308, -1e308), Vec2::new(1e308, 1e308));
|
||||
assert_eq!(b.width(), f64::MAX);
|
||||
assert_eq!(b.height(), f64::MAX);
|
||||
assert_eq!(b.width().to_bits(), f64::MAX.to_bits());
|
||||
assert_eq!(b.height().to_bits(), f64::MAX.to_bits());
|
||||
let b = Bounds2::new(Vec2::new(1e308, 0.0), Vec2::new(1.6e308, 10.0));
|
||||
assert!((b.width() / 1e308 - 0.6).abs() < 1e-12);
|
||||
assert_eq!(b.height(), 10.0);
|
||||
assert_eq!(b.height().to_bits(), 10.0_f64.to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,13 +113,14 @@ impl Arc {
|
||||
pub fn bounds(&self) -> Bounds2 {
|
||||
let mut b = Bounds2::from_points([self.start_point(), self.end_point()]);
|
||||
for k in 0..4 {
|
||||
let a = k as f64 * PI / 2.0;
|
||||
let a = f64::from(k) * PI / 2.0;
|
||||
if self.contains_angle(a) {
|
||||
b.add(Vec2::polar(self.center, self.radius, a));
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
#[expect(clippy::cast_precision_loss, reason = "arc_segments caps the sample count at 4096, so every sample index is exact as f64.")]
|
||||
pub fn tessellate(&self, tol: f64, out: &mut Vec<Vec2>) {
|
||||
let sweep = self.sweep();
|
||||
let n = arc_segments(self.radius, sweep, tol);
|
||||
@@ -192,6 +193,7 @@ impl Circle {
|
||||
/// up to two outer (belt) tangents and two inner (crossed) tangents. Empty for concentric
|
||||
/// circles or when one circle lies inside the other; tangents that touch both circles at the
|
||||
/// same point (circles touching each other) are left out.
|
||||
#[expect(clippy::many_single_char_names, reason = "Circle-tangent equations use conventional r/v/d/u/c/h/n/p/q notation.")]
|
||||
pub fn common_tangents(&self, other: &Circle) -> Vec<(Vec2, Vec2)> {
|
||||
let (r1, r2) = (self.radius, other.radius);
|
||||
let v = other.center - self.center;
|
||||
@@ -264,6 +266,7 @@ impl Ellipse {
|
||||
let (start, end) = if u.cross(v) >= 0.0 { (self.start - t0, self.end - t0) } else { (t0 - self.end, t0 - self.start) };
|
||||
Ellipse { center, major: u, ratio, start: norm_angle(start), end: norm_angle(end) }
|
||||
}
|
||||
#[expect(clippy::cast_precision_loss, reason = "arc_segments caps the sample count at 4096, so every sample index is exact as f64.")]
|
||||
pub fn tessellate(&self, tol: f64, out: &mut Vec<Vec2>) {
|
||||
let r = self.major.len();
|
||||
let sweep = self.sweep();
|
||||
@@ -381,7 +384,7 @@ impl Segment {
|
||||
let start = out.len();
|
||||
arc.tessellate(tol, out);
|
||||
if !ccw && let Some(s) = out.get_mut(start..) {
|
||||
s.reverse()
|
||||
s.reverse();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -590,6 +593,7 @@ impl Polyline {
|
||||
}
|
||||
/// Area centroid of the closed polyline, exact with bulges: the chord triangles fanned from the
|
||||
/// first vertex plus each bulge's circular segment, weighted by signed area. `None` at zero area.
|
||||
#[expect(clippy::many_single_char_names, reason = "Centroid integration uses conventional a/b/c/d/t area and point notation.")]
|
||||
pub fn centroid(&self) -> Option<Vec2> {
|
||||
let origin = self.vertices.first()?.p;
|
||||
let n = self.vertices.len();
|
||||
|
||||
@@ -69,6 +69,7 @@ impl TanCurve {
|
||||
}
|
||||
|
||||
/// The point at distance `d` along the left normal at `t` (`None` where the curve stops).
|
||||
#[expect(clippy::many_single_char_names, reason = "The offset equation uses conventional t/d/p/n/q geometric notation.")]
|
||||
fn offset(&self, t: f64, d: f64) -> Option<Vec2> {
|
||||
let p = self.point(t);
|
||||
if d == 0.0 {
|
||||
@@ -125,6 +126,11 @@ impl TanCurve {
|
||||
}
|
||||
|
||||
/// A sampled offset curve: runs of consecutive (parameter, point) samples.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Sample counts are capped by MAX_SPLINE_SAMPLES, and c/r/d/i/t/p name the curve, range, offset and sample equations."
|
||||
)]
|
||||
fn sample(c: &TanCurve, r: &Range, d: f64) -> Vec<Vec<(f64, Vec2)>> {
|
||||
let n = c.sample_count();
|
||||
let mut runs: Vec<Vec<(f64, Vec2)>> = vec![Vec::new()];
|
||||
|
||||
@@ -14,6 +14,7 @@ pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec
|
||||
}
|
||||
|
||||
/// Intersection of two finite segments.
|
||||
#[expect(clippy::many_single_char_names, reason = "Segment endpoints and parameters use conventional a/b/p/t/u geometric notation.")]
|
||||
pub fn line_line(a: &Line, b: &Line) -> Option<Vec2> {
|
||||
let (p, t, u) = line_line_infinite(a.a, a.b, b.a, b.b)?;
|
||||
let tol = 1e-9;
|
||||
@@ -21,6 +22,7 @@ pub fn line_line(a: &Line, b: &Line) -> Option<Vec2> {
|
||||
}
|
||||
|
||||
/// Intersections of the infinite line through `l` with a circle. Returns points with line params.
|
||||
#[expect(clippy::many_single_char_names, reason = "The line/circle quadratic uses conventional a/d/f/t mathematical notation.")]
|
||||
pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> {
|
||||
let d = l.b - l.a;
|
||||
let f = l.a - c.center;
|
||||
|
||||
@@ -65,6 +65,11 @@ pub fn rad(d: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// Number of segments needed to approximate an arc of `radius` and `sweep` within `tol`.
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "The segment count is nonnegative and immediately clamped to 1..=4096; float-to-usize saturation handles out-of-range values."
|
||||
)]
|
||||
pub fn arc_segments(radius: f64, sweep: f64, tol: f64) -> usize {
|
||||
let r = radius.abs();
|
||||
if !(r.is_finite() && sweep.is_finite()) || r <= EPS {
|
||||
|
||||
@@ -73,6 +73,7 @@ impl Mat3 {
|
||||
pub fn det(&self) -> f64 {
|
||||
self.a * self.d - self.b * self.c
|
||||
}
|
||||
#[expect(clippy::many_single_char_names, reason = "Matrix coefficients use the same a–f notation as Mat3 and the affine-transform formula.")]
|
||||
pub fn inverse(&self) -> Option<Mat3> {
|
||||
let det = self.det();
|
||||
if det.abs() < 1e-300 || !det.is_finite() {
|
||||
|
||||
+50
-18
@@ -44,8 +44,9 @@ const GAUSS: [(f64, f64); 5] = [
|
||||
(0.906_179_845_938_664, 0.236_926_885_056_189_1),
|
||||
];
|
||||
|
||||
#[expect(clippy::many_single_char_names, reason = "Gauss–Legendre quadrature uses conventional a/b/f/m/h/x/w notation.")]
|
||||
fn gauss(a: f64, b: f64, f: impl Fn(f64) -> f64) -> f64 {
|
||||
let (m, h) = ((a + b) / 2.0, (b - a) / 2.0);
|
||||
let (m, h) = (f64::midpoint(a, b), (b - a) / 2.0);
|
||||
GAUSS.iter().map(|(x, w)| w * f(m + h * x)).sum::<f64>() * h
|
||||
}
|
||||
|
||||
@@ -55,8 +56,12 @@ const MAX_GAUSS_DEPTH: usize = 10;
|
||||
|
||||
/// `gauss` over [a, b], halving until the two halves agree with the whole: a fixed panel count
|
||||
/// is far off on a tight bend, and the arc-length inverse must agree with the measure.
|
||||
#[expect(
|
||||
clippy::many_single_char_names,
|
||||
reason = "Adaptive quadrature keeps the panel endpoints, midpoint and left/right integrals in mathematical notation."
|
||||
)]
|
||||
fn adaptive_gauss(a: f64, b: f64, whole: f64, f: &impl Fn(f64) -> f64, depth: usize) -> f64 {
|
||||
let m = (a + b) / 2.0;
|
||||
let m = f64::midpoint(a, b);
|
||||
let (l, r) = (gauss(a, m, f), gauss(m, b, f));
|
||||
if depth == 0 || !(l + r).is_finite() || (l + r - whole).abs() <= 1e-10 * (l + r).abs() {
|
||||
return l + r;
|
||||
@@ -76,6 +81,7 @@ fn bezier_knots(breaks: &[f64], p: usize) -> Vec<f64> {
|
||||
}
|
||||
|
||||
/// One degree elevation of a homogeneous Bézier piece.
|
||||
#[expect(clippy::cast_precision_loss, reason = "Bézier pieces are bounded by MAX_EDIT_DEGREE, so their control indices are exact as f64.")]
|
||||
fn elevate_bezier(p: &[H]) -> Vec<H> {
|
||||
let n = p.len();
|
||||
let zero = (Vec2::ZERO, 0.0);
|
||||
@@ -166,6 +172,11 @@ impl Spline {
|
||||
}
|
||||
|
||||
/// [`Spline::derivative_unchecked`] before a value past f64's range is read as zero.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "The NURBS derivative keeps its standard equation notation, and MAX_DEGREE makes p exact as f64."
|
||||
)]
|
||||
fn velocity(&self, t: f64) -> Vec2 {
|
||||
let p = self.degree;
|
||||
let Some(n) = self.control.len().checked_sub(1) else { return Vec2::ZERO };
|
||||
@@ -220,6 +231,7 @@ impl Spline {
|
||||
|
||||
/// Insert knot `t` once (Boehm's algorithm, in homogeneous coordinates). The result has no
|
||||
/// fit data and is open.
|
||||
#[expect(clippy::many_single_char_names, reason = "Boehm knot insertion keeps the standard p/n/k/i/h/a equation notation.")]
|
||||
pub fn insert_knot(&self, t: f64) -> Option<Spline> {
|
||||
if !self.is_valid() || !t.is_finite() || self.control.len() >= MAX_EDIT_CONTROL {
|
||||
return None;
|
||||
@@ -321,7 +333,7 @@ impl Spline {
|
||||
let (lo, hi) = self.domain();
|
||||
let mut s = self.clone();
|
||||
s.fit.clear();
|
||||
s.fit_opts = Default::default();
|
||||
s.fit_opts = crate::FitOptions::default();
|
||||
if !s.knots.get(..=p).is_some_and(|k| k.iter().all(|x| (*x - lo).abs() < 1e-12)) {
|
||||
s = s.split_raw(lo)?.1;
|
||||
}
|
||||
@@ -412,6 +424,10 @@ impl Spline {
|
||||
/// point becomes their midpoint). Degrees are matched by elevation, weights rescaled so the
|
||||
/// junction carries one weight, and `other`'s parameters follow on at a similar speed. The
|
||||
/// junction is a knot of multiplicity `degree`, so the curve passes through it exactly.
|
||||
#[expect(
|
||||
clippy::many_single_char_names,
|
||||
reason = "Spline joining keeps the two curves, homogeneous points and knot spans in standard short notation."
|
||||
)]
|
||||
pub fn joined(&self, other: &Spline) -> Option<Spline> {
|
||||
let deg = self.degree.max(other.degree);
|
||||
let a = self.elevated(deg)?;
|
||||
@@ -440,6 +456,7 @@ impl Spline {
|
||||
|
||||
/// A straight line from `a` to `b` as a clamped spline of `degree` (evenly spaced control
|
||||
/// points, parameter = distance).
|
||||
#[expect(clippy::cast_precision_loss, reason = "The degree is clamped by MAX_EDIT_DEGREE (25), so every control index is exact as f64.")]
|
||||
pub fn from_line(a: Vec2, b: Vec2, degree: usize) -> Spline {
|
||||
let p = degree.clamp(1, MAX_EDIT_DEGREE);
|
||||
let control = (0..=p).map(|i| a.lerp(b, i as f64 / p as f64)).collect();
|
||||
@@ -453,6 +470,13 @@ impl Spline {
|
||||
/// The elliptical arc `center + u·cos θ + v·sin θ` for θ from `start` over `sweep` (negative
|
||||
/// runs clockwise) as an exact rational quadratic spline, in pieces of at most a quarter
|
||||
/// turn. Circular arcs are the case `|u| = |v|`, `u ⟂ v`.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Conic decomposition uses one to four pieces and standard parametric notation, so all piece indices are exact as f64."
|
||||
)]
|
||||
pub fn from_conic_arc(center: Vec2, u: Vec2, v: Vec2, start: f64, sweep: f64) -> Option<Spline> {
|
||||
if !(start.is_finite() && sweep.is_finite() && center.is_finite() && u.is_finite() && v.is_finite())
|
||||
|| sweep.abs() < 1e-12
|
||||
@@ -515,7 +539,7 @@ impl Spline {
|
||||
for w in cuts.windows(2) {
|
||||
let (Some(&x0), Some(&x1)) = (w.first(), w.get(1)) else { continue };
|
||||
for i in 0..4 {
|
||||
out.push((x0 + (x1 - x0) * i as f64 / 4.0, x0 + (x1 - x0) * (i + 1) as f64 / 4.0));
|
||||
out.push((x0 + (x1 - x0) * f64::from(i) / 4.0, x0 + (x1 - x0) * f64::from(i + 1) / 4.0));
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -587,7 +611,7 @@ impl Spline {
|
||||
let (near, far) = if len > 0.0 { (x0, x1) } else { (x1, x0) };
|
||||
let (mut s0, mut s1) = (near, far);
|
||||
for _ in 0..60 {
|
||||
let m = (s0 + s1) / 2.0;
|
||||
let m = f64::midpoint(s0, s1);
|
||||
let lm = self.panel_length(near.min(m), near.max(m), Spline::derivative_unchecked);
|
||||
if lm < rest {
|
||||
s0 = m;
|
||||
@@ -595,7 +619,7 @@ impl Spline {
|
||||
s1 = m;
|
||||
}
|
||||
}
|
||||
return (s0 + s1) / 2.0;
|
||||
return f64::midpoint(s0, s1);
|
||||
}
|
||||
acc += l;
|
||||
}
|
||||
@@ -610,6 +634,12 @@ impl Ellipse {
|
||||
}
|
||||
|
||||
/// Arc length from parameter `t0` counter-clockwise over `sweep` (radians, >= 0).
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "The quadrature panel count is clamped to 1..=512, so panel indices are nonnegative and exact as f64."
|
||||
)]
|
||||
pub fn arc_length_from(&self, t0: f64, sweep: f64) -> f64 {
|
||||
if !(t0.is_finite() && sweep.is_finite()) || sweep <= 0.0 {
|
||||
return 0.0;
|
||||
@@ -643,14 +673,14 @@ impl Ellipse {
|
||||
let along = |s: f64| if len >= 0.0 { self.arc_length_from(t0, s) } else { self.arc_length_from(t0 - s, s) };
|
||||
let (mut a, mut b) = (0.0, TAU);
|
||||
for _ in 0..80 {
|
||||
let m = (a + b) / 2.0;
|
||||
let m = f64::midpoint(a, b);
|
||||
if along(m) < target {
|
||||
a = m;
|
||||
} else {
|
||||
b = m;
|
||||
}
|
||||
}
|
||||
let s = (a + b) / 2.0;
|
||||
let s = f64::midpoint(a, b);
|
||||
Some(if len >= 0.0 { t0 + s } else { t0 - s })
|
||||
}
|
||||
}
|
||||
@@ -795,7 +825,7 @@ mod tests {
|
||||
s.weights = vec![1.0, 2.0, 0.5, 1.0, 1.5];
|
||||
let (lo, hi) = s.domain();
|
||||
for i in 1..20 {
|
||||
let t = lo + (hi - lo) * i as f64 / 20.0;
|
||||
let t = lo + (hi - lo) * f64::from(i) / 20.0;
|
||||
let h = 1e-6;
|
||||
let fd = (s.eval(t + h) - s.eval(t - h)) / (2.0 * h);
|
||||
assert!(s.derivative(t).near(fd, 1e-4), "{t}: {:?} vs {fd:?}", s.derivative(t));
|
||||
@@ -825,7 +855,7 @@ mod tests {
|
||||
assert!(!c.is_periodic());
|
||||
let ((plo, phi), (clo, chi)) = (p.domain(), c.domain());
|
||||
for i in 0..=20 {
|
||||
let f = i as f64 / 20.0;
|
||||
let f = f64::from(i) / 20.0;
|
||||
assert!(p.eval(plo + (phi - plo) * f).near(c.eval(clo + (chi - clo) * f), 1e-9));
|
||||
}
|
||||
assert!(c.control.first().unwrap().near(p.eval(plo), 1e-9));
|
||||
@@ -837,7 +867,7 @@ mod tests {
|
||||
let e = s.elevated(5).unwrap();
|
||||
assert_eq!(e.degree, 5);
|
||||
for i in 0..=20 {
|
||||
let t = i as f64 / 20.0;
|
||||
let t = f64::from(i) / 20.0;
|
||||
assert!(e.eval(t).near(s.eval(t), 1e-9), "{t}");
|
||||
}
|
||||
// A rational quarter circle elevated to a cubic stays on the circle.
|
||||
@@ -845,12 +875,13 @@ mod tests {
|
||||
let q3 = q.elevated(3).unwrap();
|
||||
let (lo, hi) = q3.domain();
|
||||
for i in 0..=20 {
|
||||
assert!((q3.eval(lo + (hi - lo) * i as f64 / 20.0).len() - 2.0).abs() < 1e-9);
|
||||
assert!((q3.eval(lo + (hi - lo) * f64::from(i) / 20.0).len() - 2.0).abs() < 1e-9);
|
||||
}
|
||||
assert!(s.elevated(2).is_none() && s.elevated(1000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(clippy::many_single_char_names, reason = "The ellipse equation check keeps conventional center/axis/point notation.")]
|
||||
fn conic_arcs_are_exact() {
|
||||
let e = Ellipse { center: Vec2::new(1.0, 2.0), major: Vec2::new(4.0, 3.0), ratio: 0.5, start: 0.3, end: 5.5 };
|
||||
let s = Spline::from_ellipse(&e).unwrap();
|
||||
@@ -860,7 +891,7 @@ mod tests {
|
||||
let (a, b) = (e.major.len(), e.major.len() * e.ratio);
|
||||
let ux = e.major.normalized();
|
||||
for i in 0..=40 {
|
||||
let p = s.eval(lo + (hi - lo) * i as f64 / 40.0) - e.center;
|
||||
let p = s.eval(lo + (hi - lo) * f64::from(i) / 40.0) - e.center;
|
||||
let (x, y) = (p.dot(ux), p.dot(ux.perp()));
|
||||
assert!(((x / a).powi(2) + (y / b).powi(2) - 1.0).abs() < 1e-9);
|
||||
}
|
||||
@@ -881,8 +912,8 @@ mod tests {
|
||||
assert!(j.eval(lo).near(Vec2::new(-5.0, 0.0), 1e-12) && j.eval(hi).near(Vec2::new(12.0, 2.0), 1e-12));
|
||||
// The line part is straight (parameter = distance), the spline part unchanged.
|
||||
for i in 0..=10 {
|
||||
assert!(j.eval(lo + 0.5 * i as f64).near(Vec2::new(-5.0 + 0.5 * i as f64, 0.0), 1e-12));
|
||||
let f = i as f64 / 10.0;
|
||||
assert!(j.eval(lo + 0.5 * f64::from(i)).near(Vec2::new(-5.0 + 0.5 * f64::from(i), 0.0), 1e-12));
|
||||
let f = f64::from(i) / 10.0;
|
||||
assert!(j.eval(5.0 + (hi - 5.0) * f).near(s.eval(f), 1e-9));
|
||||
}
|
||||
assert!((j.length() - (5.0 + s.length())).abs() < 1e-6);
|
||||
@@ -917,7 +948,7 @@ mod tests {
|
||||
assert!(q.eval(t).near(Vec2::new(0.0, 2.0), 1e-6));
|
||||
let t = q.param_at_length(hi, -std::f64::consts::PI / 2.0);
|
||||
assert!(q.eval(t).near(Vec2::new(-2f64.sqrt(), 2f64.sqrt()), 1e-6));
|
||||
assert_eq!(q.param_at_length(lo, 1e9), hi);
|
||||
assert_eq!(q.param_at_length(lo, 1e9).to_bits(), hi.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -966,12 +997,13 @@ mod tests {
|
||||
nan.knots[nan.degree] = f64::NAN;
|
||||
assert!(!nan.is_valid() && nan.domain().0.is_nan());
|
||||
for s in [reversed, nan] {
|
||||
assert_eq!(s.param_at_length(0.5, 1.0), 0.5);
|
||||
assert_eq!(s.param_at_length(0.5, -1.0), 0.5);
|
||||
assert_eq!(s.param_at_length(0.5, 1.0).to_bits(), 0.5_f64.to_bits());
|
||||
assert_eq!(s.param_at_length(0.5, -1.0).to_bits(), 0.5_f64.to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(clippy::many_single_char_names, reason = "The ellipse arc-length reference uses conventional a/b/h/t notation.")]
|
||||
fn ellipse_arc_length() {
|
||||
let c = Ellipse::full(Vec2::ZERO, Vec2::new(3.0, 0.0), 1.0);
|
||||
assert!((c.length() - TAU * 3.0).abs() < 1e-9);
|
||||
|
||||
@@ -22,13 +22,15 @@ impl Rng {
|
||||
x ^= x << 25;
|
||||
x ^= x >> 27;
|
||||
self.0 = x;
|
||||
x.wrapping_mul(0x2545F4914F6CDD1D)
|
||||
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
/// Uniform in `[-scale, scale]`.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")]
|
||||
fn f64(&mut self, scale: f64) -> f64 {
|
||||
((self.next() >> 11) as f64 / (1u64 << 53) as f64) * 2.0 * scale - scale
|
||||
}
|
||||
/// Uniform in `[lo, hi]`.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")]
|
||||
fn range(&mut self, lo: f64, hi: f64) -> f64 {
|
||||
lo + (hi - lo) * (self.next() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
@@ -96,7 +98,7 @@ fn on_line(p: Vec2, a: Vec2, d: Vec2, rel: f64) -> bool {
|
||||
/// The infinite-line intersection lies on both lines, and swapping the lines gives the same point.
|
||||
#[test]
|
||||
fn line_line_infinite_lies_on_both_and_is_symmetric() {
|
||||
let mut r = Rng::new(0xC0FFEE);
|
||||
let mut r = Rng::new(0xC0_FFEE);
|
||||
let mut checked = 0;
|
||||
for _ in 0..4000 {
|
||||
let (a1, a2, b1, b2) = (r.vec(1000.0), r.vec(1000.0), r.vec(1000.0), r.vec(1000.0));
|
||||
@@ -115,8 +117,9 @@ fn line_line_infinite_lies_on_both_and_is_symmetric() {
|
||||
|
||||
/// The finite-line result agrees with the parameters of the infinite one.
|
||||
#[test]
|
||||
#[expect(clippy::many_single_char_names, reason = "The property uses the same a/b/p/t/u notation as the geometric equations under test.")]
|
||||
fn line_line_matches_infinite_parameters() {
|
||||
let mut r = Rng::new(0xBAD5EED);
|
||||
let mut r = Rng::new(0xBAD_5EED);
|
||||
for _ in 0..4000 {
|
||||
let a = Line::new(r.vec(100.0), r.vec(100.0));
|
||||
let b = Line::new(r.vec(100.0), r.vec(100.0));
|
||||
@@ -220,7 +223,7 @@ fn circle_circle_hits_lie_on_both_and_match_the_closed_form() {
|
||||
/// Degenerate and hostile circles: concentric, contained, negative/NaN radii, extreme centres.
|
||||
#[test]
|
||||
fn circle_circle_degenerate_and_hostile_never_panic() {
|
||||
let mut r = Rng::new(0xD15EA5E);
|
||||
let mut r = Rng::new(0xD15_EA5E);
|
||||
for _ in 0..3000 {
|
||||
let c1 = Circle { center: Vec2::new(r.hostile(), r.hostile()), radius: r.hostile() };
|
||||
let c2 = Circle { center: Vec2::new(r.hostile(), r.hostile()), radius: r.hostile() };
|
||||
@@ -240,7 +243,7 @@ fn circle_circle_degenerate_and_hostile_never_panic() {
|
||||
/// Extending segments only adds hits: the finite result is a subset of the extended one.
|
||||
#[test]
|
||||
fn segment_extension_only_adds_hits() {
|
||||
let mut r = Rng::new(0x5E6C0DE);
|
||||
let mut r = Rng::new(0x5E6_C0DE);
|
||||
for _ in 0..3000 {
|
||||
let s1 = Segment::Line(Line::new(r.vec(100.0), r.vec(100.0)));
|
||||
let s2 = Segment::Line(Line::new(r.vec(100.0), r.vec(100.0)));
|
||||
@@ -259,6 +262,7 @@ fn segment_extension_only_adds_hits() {
|
||||
|
||||
/// The closest point on a line is a fixed point of `closest`, and the offset is perpendicular.
|
||||
#[test]
|
||||
#[expect(clippy::many_single_char_names, reason = "The property uses conventional line/point/parameter notation from the closest-point equations.")]
|
||||
fn line_closest_is_a_fixed_point_and_perpendicular() {
|
||||
let mut r = Rng::new(0xC105E);
|
||||
for _ in 0..4000 {
|
||||
@@ -309,7 +313,7 @@ fn arc_endpoints_and_sampling_are_consistent() {
|
||||
assert!(pt_eq(a.at(0.0), a.start_point(), 1e-9), "at(0) != start_point");
|
||||
assert!(pt_eq(a.at(1.0), a.end_point(), 1e-9), "at(1) != end_point");
|
||||
for k in 0..=10 {
|
||||
let t = k as f64 / 10.0;
|
||||
let t = f64::from(k) / 10.0;
|
||||
let p = a.at(t);
|
||||
assert!(p.x.is_finite() && p.y.is_finite(), "arc sample not finite at t={t}: {p:?}");
|
||||
assert!(on_circle(p, a.center, a.radius, 1e-9), "arc sample at t={t} off the circle: {p:?}");
|
||||
|
||||
@@ -44,6 +44,10 @@ pub struct Island {
|
||||
pub sources: Vec<usize>,
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "Rounded tolerance-bin coordinates intentionally use the defined saturating f64-to-i64 conversion."
|
||||
)]
|
||||
fn key(p: Vec2, origin: Vec2, q: f64) -> (i64, i64) {
|
||||
// The drawing may be georeferenced far from (0, 0). Quantizing absolute
|
||||
// coordinates saturates i64 and aliases distinct vertices into one key.
|
||||
@@ -90,6 +94,12 @@ fn pair_splits(segs: &[(Vec2, Vec2)], bb: &Bounds2) -> Option<Vec<Vec<f64>>> {
|
||||
|
||||
/// `pair_splits` with explicit budgets: `None` once more than `max_visits` candidate pairs were visited
|
||||
/// or more than `max_pairs` distinct pairs were tested.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "At most 60,000 segments and 512 grid cells bound the numeric conversions; cell coordinates are clamped before casting."
|
||||
)]
|
||||
fn pair_splits_limited(segs: &[(Vec2, Vec2)], bb: &Bounds2, max_visits: u64, max_pairs: usize) -> Option<Vec<Vec<f64>>> {
|
||||
let n = segs.len();
|
||||
let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512);
|
||||
@@ -333,6 +343,7 @@ fn points(g: &Graph, ids: &[usize]) -> Option<Vec<Vec2>> {
|
||||
}
|
||||
|
||||
/// 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<Vec<usize>> {
|
||||
// Try hits along a ray to +X from nearest outward, so nested faces resolve to the innermost.
|
||||
let mut hits: Vec<(f64, usize, usize)> = Vec::new();
|
||||
@@ -431,6 +442,11 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option<Vec<Vec2>> {
|
||||
}
|
||||
|
||||
/// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`).
|
||||
#[expect(
|
||||
clippy::float_cmp,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Exact x equality is required for the deterministic lexicographic tie-break; graph equations keep their conventional short names."
|
||||
)]
|
||||
fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option<Vec<Island>> {
|
||||
let comp = components(g);
|
||||
let outer_comp: std::collections::HashSet<usize> = outer.iter().filter_map(|&i| comp.get(i).copied()).collect();
|
||||
@@ -503,6 +519,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option<Vec<Island>> {
|
||||
/// The point of the nearest other curve within `snap` of the end `e` of curve `i`, as (curve,
|
||||
/// segment, parameter, point). `None` when the end touches a curve, or none is near. `Err` when
|
||||
/// the budget of segment checks runs out.
|
||||
#[expect(clippy::many_single_char_names, reason = "Nearest-point search keeps conventional i/j/k/a/b/t/q/d geometry notation.")]
|
||||
fn nearest_curve(polys: &[Vec<Vec2>], i: usize, e: Vec2, snap: f64, tol: f64, budget: &mut usize) -> Result<Option<(usize, usize, f64, Vec2)>, ()> {
|
||||
let mut best: Option<(f64, usize, usize, f64, Vec2)> = None;
|
||||
let mut touching = false;
|
||||
@@ -546,6 +563,7 @@ fn nearest_curve(polys: &[Vec<Vec2>], i: usize, e: Vec2, snap: f64, tol: f64, bu
|
||||
/// curve (which gains a vertex there), so the two meet exactly. A curve that is flattened
|
||||
/// into chords (an ellipse, a spline) lies up to the flattening tolerance off the true curve,
|
||||
/// so a line that ends on the true curve can stop just short of the chords.
|
||||
#[expect(clippy::many_single_char_names, reason = "Endpoint snapping keeps conventional polyline, segment and point notation.")]
|
||||
pub fn snap_ends(polys: &[Vec<Vec2>], snap: f64, tol: f64) -> Vec<Vec<Vec2>> {
|
||||
let mut out: Vec<Vec<Vec2>> = polys.to_vec();
|
||||
if !(snap.is_finite() && snap > tol) {
|
||||
@@ -626,6 +644,7 @@ pub fn boundary_at_gap(polys: &[Vec<Vec2>], p: Vec2, tol: f64, gap: f64) -> Opti
|
||||
/// 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<Vec2>], tol: f64, gap: f64) -> Option<Vec<Vec2>> {
|
||||
let g = build_gap(polys, tol, gap)?;
|
||||
let core = prune(&g);
|
||||
@@ -869,6 +888,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(clippy::cast_precision_loss, reason = "The test generates 17,000 segments, so every grid index is exact as f64.")]
|
||||
fn long_segment_crossing_in_unsampled_cell_is_split() {
|
||||
// A diagonal long enough to skip the grid, and a short segment crossing it in a cell the old coarse sampling missed.
|
||||
let mut polys = vec![vec![Vec2::new(0.0, 0.0), Vec2::new(1000.0, 1000.0)], vec![Vec2::new(11.0, 12.0), Vec2::new(12.0, 11.0)]];
|
||||
@@ -943,7 +963,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn lines_of(poly: &[Vec2]) -> Vec<Vec<Vec2>> {
|
||||
poly.windows(2).map(|w| w.to_vec()).collect()
|
||||
poly.windows(2).map(<[Vec2]>::to_vec).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1096,6 +1116,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(clippy::cast_precision_loss, reason = "The test is capped at MAX_SEGMENTS (60,000), so every generated coordinate is exact as f64.")]
|
||||
fn snap_ends_skips_input_over_the_segment_cap() {
|
||||
let mut polys: Vec<Vec<Vec2>> = (0..=MAX_SEGMENTS)
|
||||
.map(|i| {
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::{Bounds2, Vec2};
|
||||
/// Largest B-spline degree treated as valid. Basis evaluation is O(degree²) per sample and
|
||||
/// tessellation takes O(degree) samples, so an unbounded degree (DXF/HATCH can declare up to
|
||||
/// 100 000) turns a tiny spline into billions of iterations (CWE-407). Real splines are low
|
||||
/// degree (AutoCAD caps at 11); above this a spline evaluates to its control polygon instead.
|
||||
/// degree (`AutoCAD` caps at 11); above this a spline evaluates to its control polygon instead.
|
||||
pub const MAX_DEGREE: usize = 64;
|
||||
|
||||
/// A (possibly rational) B-spline curve, DXF SPLINE style.
|
||||
@@ -87,6 +87,7 @@ impl Spline {
|
||||
|
||||
/// `eval` on a spline `is_valid` has accepted, given its `domain()`, so sampling many points
|
||||
/// validates once (`is_valid` walks the knot vector).
|
||||
#[expect(clippy::many_single_char_names, reason = "De Boor evaluation keeps the standard p/w/b/k notation shared with basis_ref.")]
|
||||
fn eval_valid(&self, t: f64, lo: f64, hi: f64) -> Vec2 {
|
||||
let n = self.control.len().saturating_sub(1);
|
||||
let t = t.clamp(lo, hi);
|
||||
@@ -128,16 +129,22 @@ impl Spline {
|
||||
|
||||
/// The segments for a control polygon `ratio` times the tolerance: dimensionless, so a
|
||||
/// spline and its scaled copy sample alike at any scale.
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "The floating count is clamped to 8..=2000 before its truncating conversion to usize."
|
||||
)]
|
||||
fn segments_for(&self, ratio: f64) -> usize {
|
||||
let n = (ratio.sqrt() * 2.0).clamp(8.0, 2000.0) as usize * self.degree.max(1);
|
||||
n.min(MAX_SAMPLES)
|
||||
}
|
||||
|
||||
fn polygon_length(&self) -> f64 {
|
||||
self.control.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum()
|
||||
self.control.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum()
|
||||
}
|
||||
|
||||
/// `n + 1` points evenly spaced in parameter over the domain (the spline must be valid).
|
||||
#[expect(clippy::cast_precision_loss, reason = "Internal callers cap sample counts at MAX_SAMPLES (4000), so every index is exact as f64.")]
|
||||
fn samples(&self, n: usize) -> impl Iterator<Item = Vec2> + '_ {
|
||||
let (lo, hi) = self.domain();
|
||||
(0..=n).map(move |i| self.eval_valid(lo + (hi - lo) * i as f64 / n as f64, lo, hi))
|
||||
@@ -159,6 +166,12 @@ impl Spline {
|
||||
/// is its control polygon, so its control box is exact; a degenerate spline gets its control
|
||||
/// box, which contains the curve (the box of the finite control points when one is not
|
||||
/// finite: `hull` skips it, but it would poison every sample).
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "Budgets and per-span counts are capped at MAX_SAMPLES; span fractions are nonnegative before conversion."
|
||||
)]
|
||||
pub fn bounds(&self) -> Bounds2 {
|
||||
let hull = Bounds2::from_points(self.control.iter().copied());
|
||||
let diag = hull.min.dist(hull.max);
|
||||
@@ -275,6 +288,10 @@ impl Spline {
|
||||
/// control points took minutes).
|
||||
const MAX_SAMPLES: usize = 4000;
|
||||
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
reason = "Knot indices are sampled as normalized f64 parameters; any precision loss would only be beyond 2^53 allocated control points."
|
||||
)]
|
||||
pub(crate) fn clamped_uniform_knots(n: usize, degree: usize) -> Vec<f64> {
|
||||
let mut k = vec![0.0; degree + 1];
|
||||
let inner = n.saturating_sub(degree + 1);
|
||||
@@ -292,7 +309,7 @@ pub(crate) fn find_span(n: usize, p: usize, u: f64, knots: &[f64]) -> usize {
|
||||
}
|
||||
let mut low = p;
|
||||
let mut high = n + 1;
|
||||
let mut mid = (low + high) / 2;
|
||||
let mut mid = usize::midpoint(low, high);
|
||||
let mut guard = 0;
|
||||
while guard < 200 {
|
||||
guard += 1;
|
||||
@@ -305,7 +322,7 @@ pub(crate) fn find_span(n: usize, p: usize, u: f64, knots: &[f64]) -> usize {
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
mid = (low + high) / 2;
|
||||
mid = usize::midpoint(low, high);
|
||||
}
|
||||
mid
|
||||
}
|
||||
@@ -325,6 +342,11 @@ pub(crate) fn basis(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec<f64> {
|
||||
|
||||
/// `basis` into `n[..=p]`, with `left` and `right` as scratch; each must hold `p + 1` values or
|
||||
/// `n` stays as it was.
|
||||
#[expect(
|
||||
clippy::cast_possible_wrap,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "Spline indices are bounded by slice lengths, and max(0) makes the converted index nonnegative."
|
||||
)]
|
||||
fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left: &mut [f64], right: &mut [f64]) {
|
||||
if n.len() <= p || left.len() <= p || right.len() <= p {
|
||||
return;
|
||||
@@ -358,6 +380,7 @@ fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left:
|
||||
/// NaN, infinity or magnitudes above `1e100` (which could overflow) takes the full sweep, and so
|
||||
/// does a back-substitution row whose banded sum is zero (skipped zero terms can flip its sign).
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
#[expect(clippy::many_single_char_names, reason = "Gaussian elimination keeps conventional matrix/row/column notation.")]
|
||||
pub(crate) fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
|
||||
#[cfg(test)]
|
||||
if tests::DENSE_ORACLE.get() {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
use super::*;
|
||||
|
||||
/// `basis` before it evaluated on the stack, kept as the reference.
|
||||
#[expect(
|
||||
clippy::cast_possible_wrap,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "Spline indices are bounded by slice lengths, and max(0) makes the converted index nonnegative."
|
||||
)]
|
||||
fn basis_ref(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec<f64> {
|
||||
let mut n = vec![0.0; p + 1];
|
||||
let mut left = vec![0.0; p + 1];
|
||||
@@ -23,6 +28,7 @@ fn basis_ref(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec<f64> {
|
||||
}
|
||||
|
||||
/// `eval` before it evaluated on the stack, kept as the reference.
|
||||
#[expect(clippy::many_single_char_names, reason = "The reference implementation keeps the NURBS equation notation used by the algorithm under test.")]
|
||||
fn eval_ref(s: &Spline, t: f64) -> Vec2 {
|
||||
let n = s.control.len() - 1;
|
||||
let (lo, hi) = s.domain();
|
||||
@@ -41,21 +47,26 @@ fn eval_ref(s: &Spline, t: f64) -> Vec2 {
|
||||
}
|
||||
|
||||
/// Deterministic pseudo-random numbers in `0..1`.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")]
|
||||
fn noise(seed: &mut u64) -> f64 {
|
||||
*seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
*seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||
(*seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
|
||||
/// Splines of degree 1..=11 over 14 control points: clamped and unclamped (uniform) knots,
|
||||
/// unit and random weights.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
reason = "The test uses 14 control points and degrees through 11, so every knot index is exactly representable as f64."
|
||||
)]
|
||||
fn samples() -> Vec<Spline> {
|
||||
let mut seed = 7;
|
||||
let mut out = Vec::new();
|
||||
for degree in 1..=11 {
|
||||
let control: Vec<Vec2> = (0..14).map(|i| Vec2::new(i as f64 * 3.0 + noise(&mut seed), 10.0 * noise(&mut seed) - 5.0)).collect();
|
||||
let control: Vec<Vec2> = (0..14).map(|i| Vec2::new(f64::from(i) * 3.0 + noise(&mut seed), 10.0 * noise(&mut seed) - 5.0)).collect();
|
||||
let weights: Vec<f64> = (0..14).map(|_| 0.5 + 1.5 * noise(&mut seed)).collect();
|
||||
let clamped = Spline::from_control(control.clone(), degree);
|
||||
let uniform = Spline { knots: (0..control.len() + degree + 1).map(|i| i as f64 * 0.25).collect(), ..clamped.clone() };
|
||||
let uniform = Spline { knots: (0..=(control.len() + degree)).map(|i| i as f64 * 0.25).collect(), ..clamped.clone() };
|
||||
for base in [clamped, uniform] {
|
||||
out.push(Spline { weights: weights.clone(), ..base.clone() });
|
||||
out.push(base);
|
||||
@@ -70,7 +81,7 @@ fn stack_basis_matches_the_heap_basis_bit_for_bit() {
|
||||
assert!(s.is_valid());
|
||||
let (lo, hi) = s.domain();
|
||||
for i in -20..=1020 {
|
||||
let t = lo + (hi - lo) * i as f64 / 1000.0;
|
||||
let t = lo + (hi - lo) * f64::from(i) / 1000.0;
|
||||
let got = s.eval(t);
|
||||
let want = eval_ref(&s, t);
|
||||
assert_eq!((got.x.to_bits(), got.y.to_bits()), (want.x.to_bits(), want.y.to_bits()), "degree {} at {t}: {got:?} vs {want:?}", s.degree);
|
||||
@@ -87,14 +98,14 @@ fn basis_into_needs_room_for_every_function() {
|
||||
let knots = clamped_uniform_knots(6, 3);
|
||||
let (mut n, mut left, mut right) = ([0.5; 3], [0.0; 4], [0.0; 4]);
|
||||
basis_into(3, 0.5, 3, &knots, &mut n, &mut left, &mut right);
|
||||
assert_eq!(n, [0.5; 3]);
|
||||
assert_eq!(n.map(f64::to_bits), [0.5; 3].map(f64::to_bits));
|
||||
}
|
||||
|
||||
/// A cubic through 300 points of a sine wave, open or closed.
|
||||
fn wiggly(closed: bool) -> Spline {
|
||||
let fit: Vec<Vec2> = (0..300)
|
||||
.map(|i| {
|
||||
let x = i as f64 / 299.0;
|
||||
let x = f64::from(i) / 299.0;
|
||||
Vec2::new(x * 100.0, 10.0 * (x * 60.0).sin())
|
||||
})
|
||||
.collect();
|
||||
@@ -108,6 +119,7 @@ fn fine_box(s: &Spline) -> Bounds2 {
|
||||
|
||||
/// The box of `n + 1` samples evenly spaced in parameter over the domain, as `bounds` sampled
|
||||
/// before it spread its samples over the knot spans.
|
||||
#[expect(clippy::cast_precision_loss, reason = "Test grids are capped at MAX_SAMPLES (4000), so sample indices are exactly representable as f64.")]
|
||||
fn uniform_box(s: &Spline, n: usize) -> Bounds2 {
|
||||
let (lo, hi) = s.domain();
|
||||
Bounds2::from_points((0..=n).map(|i| s.eval(lo + (hi - lo) * i as f64 / n as f64)))
|
||||
@@ -118,7 +130,7 @@ fn uniform_box(s: &Spline, n: usize) -> Bounds2 {
|
||||
/// except for a peak of 50 at t = 0.50035, inside a span of width 1e-4 that no point of a
|
||||
/// uniform grid of up to 4000 hits (0.50025 and 0.5005 are the nearest).
|
||||
fn narrow_span() -> Spline {
|
||||
let control = (0..7).map(|i| Vec2::new(i as f64, if i == 3 { 100.0 } else { 0.0 })).collect();
|
||||
let control = (0..7).map(|i| Vec2::new(f64::from(i), if i == 3 { 100.0 } else { 0.0 })).collect();
|
||||
Spline { degree: 2, knots: vec![0.0, 0.0, 0.0, 0.5003, 0.5003, 0.5004, 0.5004, 1.0, 1.0, 1.0], control, ..Spline::default() }
|
||||
}
|
||||
|
||||
@@ -132,14 +144,14 @@ fn an_off_grid_peak_in_a_narrow_span_is_within_a_percent() {
|
||||
s.control[4].y = 30.0;
|
||||
assert!(s.is_valid());
|
||||
let (a, b) = (0.5003, 0.5004);
|
||||
let peak = (0..=10_000).map(|i| s.eval(a + (b - a) * i as f64 / 10_000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m });
|
||||
let peak = (0..=10_000).map(|i| s.eval(a + (b - a) * f64::from(i) / 10_000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m });
|
||||
assert!(peak.y > 58.0 && peak.y < 59.0, "{peak:?}");
|
||||
let hull = Bounds2::from_points(s.control.iter().copied());
|
||||
let diag = hull.min.dist(hull.max);
|
||||
let got = s.bounds();
|
||||
assert!(got.max.y <= peak.y + 1e-9 * diag && got.max.y >= peak.y - 1e-2 * diag, "{got:?} vs peak {peak:?}");
|
||||
// Four segments, the floor before, missed it by more than that.
|
||||
let four = (0..=4).map(|i| s.eval(a + (b - a) * i as f64 / 4.0)).fold(f64::MIN, |m, p| m.max(p.y));
|
||||
let four = (0..=4).map(|i| s.eval(a + (b - a) * f64::from(i) / 4.0)).fold(f64::MIN, |m, p| m.max(p.y));
|
||||
assert!(four < peak.y - 1e-2 * diag, "{four} vs {peak:?}");
|
||||
}
|
||||
|
||||
@@ -148,7 +160,7 @@ fn bounds_see_an_extreme_inside_a_narrow_knot_span() {
|
||||
let s = narrow_span();
|
||||
assert!(s.is_valid());
|
||||
let (a, b) = (0.5003, 0.5004);
|
||||
let peak = (0..=1000).map(|i| s.eval(a + (b - a) * i as f64 / 1000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m });
|
||||
let peak = (0..=1000).map(|i| s.eval(a + (b - a) * f64::from(i) / 1000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m });
|
||||
assert!((peak.x - 3.0).abs() < 1e-9 && (peak.y - 50.0).abs() < 1e-9, "{peak:?}");
|
||||
let hull = Bounds2::from_points(s.control.iter().copied());
|
||||
let diag = hull.min.dist(hull.max);
|
||||
@@ -165,6 +177,7 @@ fn bounds_see_an_extreme_inside_a_narrow_knot_span() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(clippy::cast_precision_loss, reason = "The test grids contain 1502 or 2502 points, so all sample indices are exact as f64.")]
|
||||
fn bounds_keep_their_cap_over_many_spans() {
|
||||
// 1500 spans: eight per span would pass the cap, so two; 2500 spans: more than the cap
|
||||
// allows two for, so the control box, which contains the curve. A smooth curve stays
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Fit-point splines: knot parametrisation (chord, square root, uniform), end tangents and fit
|
||||
//! tolerance (least-squares approximation with fewer control points), as AutoCAD's SPLINE Fit
|
||||
//! tolerance (least-squares approximation with fewer control points), as `AutoCAD`'s SPLINE Fit
|
||||
//! method offers them. Construction follows the textbook global interpolation and approximation
|
||||
//! schemes (Piegl & Tiller, *The NURBS Book*, ch. 9).
|
||||
|
||||
@@ -110,17 +110,16 @@ impl Spline {
|
||||
pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline {
|
||||
let opts = opts.sanitized();
|
||||
let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None };
|
||||
let mut s = match kinked {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
// Repeats at the ends of an open curve are no corners: fit without them.
|
||||
let (pts, _) = kinks(fit, false);
|
||||
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) };
|
||||
if pts.len() != fit.len() && !closed {
|
||||
s.fit = fit.to_vec();
|
||||
}
|
||||
s
|
||||
let mut s = if let Some(s) = kinked {
|
||||
s
|
||||
} else {
|
||||
// Repeats at the ends of an open curve are no corners: fit without them.
|
||||
let (pts, _) = kinks(fit, false);
|
||||
let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) };
|
||||
if pts.len() != fit.len() && !closed {
|
||||
s.fit = fit.to_vec();
|
||||
}
|
||||
s
|
||||
};
|
||||
s.fit_opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts };
|
||||
s
|
||||
@@ -210,19 +209,19 @@ pub(crate) fn params(pts: &[Vec2], kind: KnotParam, closed: bool) -> Vec<f64> {
|
||||
let mut u = vec![0.0; count];
|
||||
let mut total = 0.0;
|
||||
for i in 1..count {
|
||||
total += pts.get(i - 1).zip(pts.get(i % n.max(1))).map(|(a, b)| kind.step(a.dist(*b))).unwrap_or(1.0);
|
||||
total += pts.get(i - 1).zip(pts.get(i % n.max(1))).map_or(1.0, |(a, b)| kind.step(a.dist(*b)));
|
||||
if let Some(x) = u.get_mut(i) {
|
||||
*x = total;
|
||||
}
|
||||
}
|
||||
for x in u.iter_mut() {
|
||||
for x in &mut u {
|
||||
*x /= total.max(1e-300);
|
||||
}
|
||||
u
|
||||
}
|
||||
|
||||
fn chord_length(pts: &[Vec2]) -> f64 {
|
||||
pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum()
|
||||
pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum()
|
||||
}
|
||||
|
||||
fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
|
||||
@@ -262,6 +261,11 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
|
||||
/// Global interpolation: one control point per fit point plus one per end-derivative
|
||||
/// constraint, knots by averaging the parameters (an end with a derivative counts its
|
||||
/// parameter twice).
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Interpolation uses NURBS matrix notation, and its degree is capped at three, so p is exact as f64."
|
||||
)]
|
||||
fn interpolate(fit: &[Vec2], u: &[f64], d0: Option<Vec2>, d1: Option<Vec2>) -> Option<Spline> {
|
||||
let (p, knots) = interp_knots(u, d0.is_some(), d1.is_some());
|
||||
let m = knots.len().checked_sub(p + 1)?;
|
||||
@@ -305,6 +309,7 @@ fn interpolate(fit: &[Vec2], u: &[f64], d0: Option<Vec2>, d1: Option<Vec2>) -> O
|
||||
|
||||
/// Degree and clamped knots for interpolating at parameters `u`, with optional end derivatives:
|
||||
/// knots average the parameters, an end with a derivative counting its parameter twice.
|
||||
#[expect(clippy::cast_precision_loss, reason = "The interpolation degree is capped at three, so p is exact as f64.")]
|
||||
fn interp_knots(u: &[f64], d0: bool, d1: bool) -> (usize, Vec<f64>) {
|
||||
let m = u.len() + usize::from(d0) + usize::from(d1);
|
||||
let p = 3.min(m.saturating_sub(1)).max(1);
|
||||
@@ -323,6 +328,13 @@ fn interp_knots(u: &[f64], d0: bool, d1: bool) -> (usize, Vec<f64>) {
|
||||
|
||||
/// Clamped knots for a least-squares fit with `m` control points of degree `p` so every span
|
||||
/// holds parameters (The NURBS Book eq. 9.69). Needs `p < m < u.len()`.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Fit sizes are bounded by MAX_APPROX_POINTS, knot indices are nonnegative and clamped, and the equations use NURBS Book notation."
|
||||
)]
|
||||
fn lsq_knots(u: &[f64], m: usize, p: usize) -> Vec<f64> {
|
||||
let n = u.len();
|
||||
let d = n as f64 / m.saturating_sub(p).max(1) as f64;
|
||||
@@ -339,12 +351,18 @@ fn lsq_knots(u: &[f64], m: usize, p: usize) -> Vec<f64> {
|
||||
|
||||
/// Periodic knots for `n` points with closed parameters `t` (`n + 1` values): knots[j] =
|
||||
/// t_(j-p), extended by whole periods on both sides.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::cast_possible_wrap,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Indices are bounded by slice lengths, period offsets are f64 by design, and the periodic equations use standard notation."
|
||||
)]
|
||||
fn periodic_knots(t: &[f64], n: usize, p: usize) -> Vec<f64> {
|
||||
let tk = |i: isize| {
|
||||
let (q, r) = (i.div_euclid(n.max(1) as isize), i.rem_euclid(n.max(1) as isize) as usize);
|
||||
t.get(r).copied().unwrap_or(0.0) + q as f64
|
||||
};
|
||||
(0..n + 2 * p + 1).map(|j| tk(j as isize - p as isize)).collect()
|
||||
(0..=(n + 2 * p)).map(|j| tk(j as isize - p as isize)).collect()
|
||||
}
|
||||
|
||||
/// Least-squares approximation within `tol`: the fewest control points (searched by bisection)
|
||||
@@ -357,7 +375,7 @@ fn approximate(fit: &[Vec2], u: &[f64], d0: Option<Vec2>, d1: Option<Vec2>, tol:
|
||||
let (mut lo, mut hi) = (p + 1, n.checked_sub(1)?);
|
||||
let mut best = None;
|
||||
while lo <= hi {
|
||||
let mid = (lo + hi) / 2;
|
||||
let mid = usize::midpoint(lo, hi);
|
||||
match least_squares(fit, u, mid, p, d0, d1) {
|
||||
Some(s) if max_deviation(&s, fit, u) <= tol => {
|
||||
best = Some(s);
|
||||
@@ -373,6 +391,11 @@ fn max_deviation(s: &Spline, fit: &[Vec2], u: &[f64]) -> f64 {
|
||||
fit.iter().zip(u).map(|(q, t)| s.eval(*t).dist(*q)).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Open least-squares fitting is cubic and keeps the NURBS Book matrix notation, so p is exact as f64."
|
||||
)]
|
||||
fn least_squares(fit: &[Vec2], u: &[f64], m: usize, p: usize, d0: Option<Vec2>, d1: Option<Vec2>) -> Option<Spline> {
|
||||
let n = fit.len();
|
||||
if m <= p || m >= n {
|
||||
@@ -522,6 +545,11 @@ fn kinked_fit(fit: &[Vec2], closed: bool, opts: FitOptions) -> Option<Spline> {
|
||||
|
||||
/// A clamped, non-rational fitted piece raised to degree 3: interpolation through two or three
|
||||
/// points gives a single Bézier segment of lower degree, which is raised exactly.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Degree elevation stops at three and keeps the Bézier coefficient notation, so all indices are exact as f64."
|
||||
)]
|
||||
fn cubic(mut s: Spline) -> Option<Spline> {
|
||||
if s.degree == 3 {
|
||||
return Some(s);
|
||||
@@ -555,7 +583,7 @@ fn approximate_closed(pts: &[Vec2], t: &[f64], p: usize, tol: f64) -> Option<Spl
|
||||
let (mut lo, mut hi) = (p + 1, n.checked_sub(1)?);
|
||||
let mut best = None;
|
||||
while lo <= hi {
|
||||
let mid = (lo + hi) / 2;
|
||||
let mid = usize::midpoint(lo, hi);
|
||||
match periodic_least_squares(pts, t, mid, p) {
|
||||
Some(s) if pts.iter().zip(t).all(|(q, u)| s.eval(*u).dist(*q) <= tol) => {
|
||||
best = Some(s);
|
||||
@@ -570,6 +598,13 @@ fn approximate_closed(pts: &[Vec2], t: &[f64], p: usize, tol: f64) -> Option<Spl
|
||||
/// A periodic spline with `m` distinct control points (`p < m < pts.len()`) closest in the
|
||||
/// least-squares sense to `pts` at closed parameters `t`. The period's breakpoints spread over
|
||||
/// the parameters so every span holds some (the closed counterpart of `lsq_knots`).
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
clippy::many_single_char_names,
|
||||
reason = "Fit sizes are bounded by MAX_APPROX_POINTS, periodic indices are nonnegative and bounded, and the matrix equations use standard notation."
|
||||
)]
|
||||
fn periodic_least_squares(pts: &[Vec2], t: &[f64], m: usize, p: usize) -> Option<Spline> {
|
||||
let n = pts.len();
|
||||
if m <= p || m >= n || t.len() != n + 1 {
|
||||
@@ -620,6 +655,7 @@ fn periodic_least_squares(pts: &[Vec2], t: &[f64], m: usize, p: usize) -> Option
|
||||
Some(Spline { degree: p, knots, control, fit: pts.to_vec(), closed: true, ..Spline::default() })
|
||||
}
|
||||
|
||||
#[expect(clippy::many_single_char_names, reason = "Closed interpolation keeps the NURBS Book parameter, degree and matrix notation.")]
|
||||
fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> Spline {
|
||||
let mut pts = fit.to_vec();
|
||||
if pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
|
||||
@@ -748,7 +784,7 @@ mod tests {
|
||||
// Thirty noisy points along a gentle arc.
|
||||
let fit: Vec<Vec2> = (0..30)
|
||||
.map(|i| {
|
||||
let t = i as f64 / 29.0;
|
||||
let t = f64::from(i) / 29.0;
|
||||
Vec2::new(t * 10.0, (t * 3.0).sin() * 2.0 + if i % 2 == 0 { 0.01 } else { -0.01 })
|
||||
})
|
||||
.collect();
|
||||
@@ -761,7 +797,7 @@ mod tests {
|
||||
assert!(max_deviation(&s, &fit, &u) <= tol + 1e-9);
|
||||
assert!(s.eval(0.0).near(fit[0], 1e-9) && s.eval(1.0).near(fit[29], 1e-9), "ends stay exact");
|
||||
assert_eq!(s.fit, fit, "the fit points are kept");
|
||||
assert_eq!(s.fit_opts.tolerance, tol);
|
||||
assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits());
|
||||
// With tangents too.
|
||||
let t = Spline::fit_with(
|
||||
&fit,
|
||||
@@ -781,7 +817,7 @@ mod tests {
|
||||
// Forty slightly noisy points round a circle.
|
||||
let fit: Vec<Vec2> = (0..40)
|
||||
.map(|i| {
|
||||
let a = i as f64 / 40.0 * std::f64::consts::TAU;
|
||||
let a = f64::from(i) / 40.0 * std::f64::consts::TAU;
|
||||
let r = 5.0 + if i % 2 == 0 { 0.01 } else { -0.01 };
|
||||
Vec2::new(a.cos() * r, a.sin() * r)
|
||||
})
|
||||
@@ -796,7 +832,7 @@ mod tests {
|
||||
let (lo, hi) = s.domain();
|
||||
assert!(s.eval(lo).near(s.eval(hi), 1e-9), "still closed");
|
||||
assert_eq!(s.fit, fit);
|
||||
assert_eq!(s.fit_opts.tolerance, tol);
|
||||
assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits());
|
||||
// Too tight a tolerance interpolates.
|
||||
let tiny = Spline::fit_with(&fit, true, FitOptions { tolerance: 1e-9, ..FitOptions::default() });
|
||||
assert_eq!(tiny.control.len(), exact.control.len());
|
||||
@@ -809,10 +845,14 @@ mod tests {
|
||||
|
||||
fn on_curve(s: &Spline, q: Vec2) -> bool {
|
||||
let (lo, hi) = s.domain();
|
||||
(0..=4000).any(|i| s.eval(lo + (hi - lo) * i as f64 / 4000.0).dist(q) < 1e-2)
|
||||
(0..=4000).any(|i| s.eval(lo + (hi - lo) * f64::from(i) / 4000.0).dist(q) < 1e-2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(
|
||||
clippy::many_single_char_names,
|
||||
reason = "The test names spline values and points with the same short notation as the fitting equations."
|
||||
)]
|
||||
fn repeated_fit_points_make_kinks() {
|
||||
let fit = [Vec2::new(0.0, 0.0), Vec2::new(2.0, 2.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(6.0, 2.0), Vec2::new(8.0, 0.0)];
|
||||
let s = Spline::fit_with(&fit, false, FitOptions::default());
|
||||
@@ -873,13 +913,17 @@ mod tests {
|
||||
let _ = Spline::fit_with(&pairs[..n], closed, FitOptions { tolerance: 0.1, ..FitOptions::default() });
|
||||
}
|
||||
}
|
||||
let tight: Vec<Vec2> = (0..8).map(|i| Vec2::new(i as f64 * 1e-13, 0.0)).collect();
|
||||
let tight: Vec<Vec2> = (0..8).map(|i| Vec2::new(f64::from(i) * 1e-13, 0.0)).collect();
|
||||
let _ = Spline::fit_with(&tight, true, FitOptions { tolerance: 1.0, ..FitOptions::default() });
|
||||
}
|
||||
|
||||
/// Above the interpolation cap the fit points become control points instead of a dense
|
||||
/// system the size of their count squared (issue #702); just below it they still interpolate.
|
||||
#[test]
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
reason = "The generated test grids are bounded by MAX_INTERP_POINTS + 1, so their indices are exact as f64."
|
||||
)]
|
||||
fn too_many_fit_points_are_not_interpolated() {
|
||||
let wave = |n: usize| -> Vec<Vec2> { (0..n).map(|i| Vec2::new((i * i) as f64 * 1e-3, (i % 5) as f64)).collect() };
|
||||
let fit = wave(MAX_INTERP_POINTS + 1);
|
||||
|
||||
@@ -214,7 +214,7 @@ fn segment_offset() {
|
||||
let s = Segment::Arc { arc: Arc::new(Vec2::ZERO, 5.0, 0.0, PI), ccw: true };
|
||||
let o = s.offset(1.0).unwrap();
|
||||
if let Segment::Arc { arc, .. } = o {
|
||||
assert!(close(arc.radius, 4.0))
|
||||
assert!(close(arc.radius, 4.0));
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
@@ -237,7 +237,7 @@ fn polyline_tessellation_is_bounded() {
|
||||
fn arc_segments_bounded() {
|
||||
assert_eq!(arc_segments(0.0, 1.0, 0.1), 1);
|
||||
assert!(arc_segments(1e9, TAU, 1e-12) <= 4096);
|
||||
assert!(arc_segments(f64::NAN, TAU, 0.1) == 1);
|
||||
assert_eq!(arc_segments(f64::NAN, TAU, 0.1), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -341,8 +341,8 @@ fn polyline_area_is_stable_far_from_the_origin() {
|
||||
fn shoelace_preserves_small_polygon_area_at_large_coordinates() {
|
||||
let o = 1.0e12;
|
||||
let corners = [Vec2::new(o, o), Vec2::new(o + 10.0, o), Vec2::new(o + 10.0, o + 10.0), Vec2::new(o, o + 10.0)];
|
||||
assert_eq!(shoelace(&corners), 100.0);
|
||||
assert_eq!(shoelace(&corners.iter().rev().copied().collect::<Vec<_>>()), -100.0);
|
||||
assert_eq!(shoelace(&corners).to_bits(), 100.0_f64.to_bits());
|
||||
assert_eq!(shoelace(&corners.iter().rev().copied().collect::<Vec<_>>()).to_bits(), (-100.0_f64).to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -13,23 +13,25 @@ cadcraft-geom = { workspace = true }
|
||||
cadcraft-color = { workspace = true }
|
||||
cadcraft-doc = { workspace = true }
|
||||
craft-dxf = { workspace = true }
|
||||
cadcraft-dwg = { workspace = true }
|
||||
craft-dwg = { workspace = true }
|
||||
craft-svg = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
cadcraft-render = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
miniz_oxide = "0.9"
|
||||
craft-pdf = { workspace = true, features = ["write"] }
|
||||
quick-xml = { workspace = true }
|
||||
image = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
miniz_oxide = "0.9"
|
||||
tiff = "0.11"
|
||||
image = { workspace = true }
|
||||
tiny-skia = { workspace = true }
|
||||
# Reads plotted PDFs back.
|
||||
craft-pdf = { workspace = true, features = ["read"] }
|
||||
|
||||
# Inspect DWG output only where cadcraft-dwg builds its native bridge. An unconditional
|
||||
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
|
||||
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
|
||||
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
|
||||
acadrust = "0.6.6"
|
||||
|
||||
@@ -344,7 +344,10 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
|
||||
fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) {
|
||||
if let EntityKind::Insert(i) = &e.kind {
|
||||
w.s(0, "INSERT");
|
||||
common(w, e, owner, paper, "AcDbBlockReference");
|
||||
// A reference repeated in rows or columns (MINSERT, groups 70/71) is an AcDbMInsertBlock;
|
||||
// readers that go by the marker draw only the first copy of an AcDbBlockReference.
|
||||
let array = i.cols > 1 || i.rows > 1;
|
||||
common(w, e, owner, paper, if array { "AcDbMInsertBlock" } else { "AcDbBlockReference" });
|
||||
if !i.attribs.is_empty() {
|
||||
w.i(66, 1);
|
||||
}
|
||||
@@ -354,7 +357,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
|
||||
w.f(42, i.scale.y);
|
||||
w.f(43, i.scale.z);
|
||||
w.f(50, i.rotation.to_degrees());
|
||||
if i.cols > 1 || i.rows > 1 {
|
||||
if array {
|
||||
w.i(70, i64::from(i.cols));
|
||||
w.i(71, i64::from(i.rows));
|
||||
w.f(44, i.col_spacing);
|
||||
|
||||
+23
-10
@@ -61,11 +61,24 @@ pub enum IoError {
|
||||
|
||||
pub type Result<T> = std::result::Result<T, IoError>;
|
||||
|
||||
/// How a program runs the DWG reader and writer in a child process (`cadcraft_dwg::worker`).
|
||||
/// Restore CADCraft's public diagnostics after the shared byte bridge supplies generic wording.
|
||||
fn cadcraft_dwg_message(message: &str) -> String {
|
||||
message
|
||||
.replace("accepted by this bridge", "CADCraft opens")
|
||||
.replace("types this bridge can't preserve", "types CADCraft doesn't keep")
|
||||
.replace("this bridge writes", "CADCraft writes")
|
||||
.replace("accepted for DWG conversion", "CADCraft converts to DWG")
|
||||
}
|
||||
|
||||
fn dwg_error(message: String) -> IoError {
|
||||
IoError::Format(cadcraft_dwg_message(&message))
|
||||
}
|
||||
|
||||
/// How a program runs the DWG reader and writer in a child process (`craft_dwg::worker`).
|
||||
pub mod dwg_worker {
|
||||
pub use cadcraft_dwg::{WORKER_ARG, serve_if_asked, use_own_worker};
|
||||
pub use craft_dwg::{WORKER_ARG, serve_if_asked, use_own_worker};
|
||||
#[cfg(all(not(target_arch = "wasm32"), not(all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
pub use cadcraft_dwg::{crash_worker_for_test, use_worker};
|
||||
pub use craft_dwg::{crash_worker_for_test, use_worker};
|
||||
}
|
||||
|
||||
fn ext(name: impl AsRef<Path>) -> String {
|
||||
@@ -81,10 +94,10 @@ pub fn read(bytes: &[u8], name: impl AsRef<Path>) -> Result<Drawing> {
|
||||
/// [`read`], also returning the DXF rendition a DWG was read through (`None` for other files),
|
||||
/// which the round-trip harness counts.
|
||||
pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option<Vec<u8>>)> {
|
||||
if cadcraft_dwg::is_dwg(bytes) {
|
||||
let (dxf, notes) = cadcraft_dwg::decode(bytes, cadcraft_dwg::Limits::DEFAULT).map_err(IoError::Format)?;
|
||||
if craft_dwg::is_dwg(bytes) {
|
||||
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(dwg_error)?;
|
||||
let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
|
||||
d.read_notes = notes;
|
||||
d.read_notes = notes.into_iter().map(|note| cadcraft_dwg_message(¬e)).collect();
|
||||
return Ok((d, Some(dxf)));
|
||||
}
|
||||
let d = match (Format::from_path(name), ext(name).as_str()) {
|
||||
@@ -132,21 +145,21 @@ pub fn write_with(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> Re
|
||||
/// [`write_with`], also returning what the file leaves out of the drawing: for a DWG, how many
|
||||
/// records of each DXF type the DWG writer can't write (other programs' custom entities and
|
||||
/// objects); for other formats, nothing.
|
||||
pub fn write_noted(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> Result<(Vec<u8>, cadcraft_dwg::Unwritten)> {
|
||||
pub fn write_noted(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> Result<(Vec<u8>, craft_dwg::Unwritten)> {
|
||||
let name = name.as_ref();
|
||||
if matches!(Format::from_path(name), Some(Format::Dwg)) && !opts.binary {
|
||||
return write_dwg(d, opts.version.unwrap_or_else(|| save_version(d).max(Version::R2004)));
|
||||
}
|
||||
write_with(d, name, opts).map(|b| (b, cadcraft_dwg::Unwritten::new()))
|
||||
write_with(d, name, opts).map(|b| (b, craft_dwg::Unwritten::new()))
|
||||
}
|
||||
|
||||
/// The DWG bridge reads our R2000 DXF and writes the DWG at `version`, in the DWG worker when
|
||||
/// there is one. The objects CADCraft keeps without modelling them are still in the groups of the
|
||||
/// file they came from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge
|
||||
/// reads them as that version.
|
||||
fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, cadcraft_dwg::Unwritten)> {
|
||||
fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwritten)> {
|
||||
let bridge = dxf_write::dwg_bridge(d, version);
|
||||
cadcraft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(IoError::Format)
|
||||
craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)
|
||||
}
|
||||
|
||||
/// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in
|
||||
|
||||
@@ -116,7 +116,7 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
|
||||
// PDF clips a placed plot to the printable area: blank the rest of the sheet.
|
||||
raster::blank_outside_printable(&mut pm, &sheet.printable, k);
|
||||
}
|
||||
pm.encode_png().map_err(|_| IoError::Format("render failed".into()))
|
||||
raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into()))
|
||||
}
|
||||
|
||||
fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
|
||||
|
||||
+31
-43
@@ -2,11 +2,9 @@
|
||||
//! from the content. Files are hostile input: the size is read from the header and checked
|
||||
//! before any pixel is decoded.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use cadcraft_doc::Raster;
|
||||
|
||||
use crate::{IoError, Result};
|
||||
use cadcraft_doc::Raster;
|
||||
use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType};
|
||||
|
||||
/// Largest image file read (bytes).
|
||||
pub const MAX_IMAGE_BYTES: usize = 256 << 20;
|
||||
@@ -17,22 +15,18 @@ fn bad(e: impl std::fmt::Display) -> IoError {
|
||||
IoError::Format(format!("image: {e}"))
|
||||
}
|
||||
|
||||
/// A reader over an image file, once it is small enough and of a format we read.
|
||||
fn reader(bytes: &[u8]) -> Result<image::ImageReader<Cursor<&[u8]>>> {
|
||||
/// The width and height in pixels of the first stored image, read without decoding pixels.
|
||||
pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> {
|
||||
if bytes.len() > MAX_IMAGE_BYTES {
|
||||
return Err(bad(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20)));
|
||||
}
|
||||
// The format comes from the file's first bytes, not from its name.
|
||||
let file = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(bad)?;
|
||||
if file.format().is_none() {
|
||||
let format = craft_image_codecs::detect(bytes).ok_or_else(|| bad("not a PNG, JPEG, BMP or TIFF file"))?;
|
||||
if !matches!(format, Format::Png | Format::Jpeg | Format::Bmp | Format::Tiff) {
|
||||
return Err(bad("not a PNG, JPEG, BMP or TIFF file"));
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// The width and height in pixels of the image in `bytes`, read from its header.
|
||||
pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> {
|
||||
let (width, height) = reader(bytes)?.into_dimensions().map_err(bad)?;
|
||||
// Match ImageReader's original header budget; check pixels ourselves for the existing diagnostic.
|
||||
let limits = Limits::new(u32::MAX, u32::MAX, u64::MAX, 512 << 20);
|
||||
let (width, height) = craft_image_codecs::probe_stored_size(bytes, &limits).map_err(bad)?;
|
||||
if width == 0 || height == 0 {
|
||||
return Err(bad("the image is empty"));
|
||||
}
|
||||
@@ -42,38 +36,32 @@ pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> {
|
||||
Ok((width, height))
|
||||
}
|
||||
|
||||
/// Decode the image in `bytes`.
|
||||
/// Decode the first image, keeping its stored orientation.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Raster> {
|
||||
// The size is checked first, from the header alone.
|
||||
let (width, height) = probe(bytes)?;
|
||||
let mut file = reader(bytes)?;
|
||||
file.limits(decode_limits(width, height));
|
||||
let pixels = file.decode().map_err(bad)?.into_rgba8();
|
||||
Raster::new(pixels.width(), pixels.height(), pixels.into_raw()).ok_or_else(|| bad("the image is empty"))
|
||||
}
|
||||
|
||||
/// What the decoder may allocate for an image of this size: the pixels themselves (up to 16
|
||||
/// bytes each before they become 8-bit RGBA) and its own working buffers.
|
||||
fn decode_limits(width: u32, height: u32) -> image::Limits {
|
||||
let pixels = u64::from(width).saturating_mul(u64::from(height));
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(width);
|
||||
limits.max_image_height = Some(height);
|
||||
limits.max_alloc = Some(pixels.saturating_mul(16).saturating_add(64 << 20));
|
||||
limits
|
||||
let limits = Limits::new(width, height, MAX_IMAGE_PIXELS, pixels.saturating_mul(16).saturating_add(64 << 20));
|
||||
let opts = DecodeOptions { limits, keep_orientation: true };
|
||||
let format = craft_image_codecs::detect(bytes).ok_or_else(|| bad("not an image"))?;
|
||||
let image = if format == Format::Tiff {
|
||||
craft_image_codecs::decode_tiff_page(bytes, 0, &opts)
|
||||
} else {
|
||||
craft_image_codecs::decode_as_with(format, bytes, &opts)
|
||||
}
|
||||
.map_err(bad)?;
|
||||
if image.warnings.iter().any(|w| matches!(w, DecodeWarning::Truncated { .. })) {
|
||||
return Err(bad("image data is truncated"));
|
||||
}
|
||||
if image.dimensions() != (width, height) {
|
||||
return Err(bad("decoded image size does not match its header"));
|
||||
}
|
||||
let rgba = if image.layout() == ChannelLayout::Rgba && image.sample_type() == SampleType::U8 { image.into_data() } else { image.to_rgba8() };
|
||||
Raster::new(width, height, rgba).ok_or_else(|| bad("the image is empty"))
|
||||
}
|
||||
|
||||
/// `raster` as a PNG file.
|
||||
/// `raster` as a PNG file, encoded in rows to avoid a full extra image copy.
|
||||
pub fn encode_png(raster: &Raster) -> Result<Vec<u8>> {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
image::write_buffer_with_format(
|
||||
&mut out,
|
||||
raster.rgba(),
|
||||
raster.width(),
|
||||
raster.height(),
|
||||
image::ExtendedColorType::Rgba8,
|
||||
image::ImageFormat::Png,
|
||||
)
|
||||
.map_err(bad)?;
|
||||
Ok(out.into_inner())
|
||||
let mut out = Vec::new();
|
||||
cadcraft_render::raster::write_rgba_png(&mut out, raster.width(), raster.height(), raster.rgba()).ok_or_else(|| bad("PNG encoding failed"))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ impl Format {
|
||||
}
|
||||
/// The format of a file's bytes: DWG by its magic, otherwise DXF.
|
||||
pub fn of(bytes: &[u8]) -> Format {
|
||||
if cadcraft_dwg::is_dwg(bytes) { Format::Dwg } else { Format::Dxf }
|
||||
if craft_dwg::is_dwg(bytes) { Format::Dwg } else { Format::Dxf }
|
||||
}
|
||||
fn other(self) -> Format {
|
||||
match self {
|
||||
@@ -279,7 +279,7 @@ pub fn check_bytes(bytes: &[u8], rel: &str, opts: &CorpusOptions) -> FileReport
|
||||
let format = Format::of(bytes);
|
||||
let mut f = FileReport { path: rel.to_string(), format: Some(format), bytes: bytes.len() as u64, ..FileReport::default() };
|
||||
if format == Format::Dwg {
|
||||
f.version = cadcraft_dwg::version(bytes).unwrap_or_default();
|
||||
f.version = craft_dwg::version(bytes).unwrap_or_default();
|
||||
}
|
||||
let start = Instant::now();
|
||||
let name = format!("source.{}", format.ext());
|
||||
|
||||
+48
-43
@@ -1,7 +1,5 @@
|
||||
//! SVG export of a space (vector, for the web and documents).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use cadcraft_color::Rgb;
|
||||
use cadcraft_doc::{Drawing, Space};
|
||||
use cadcraft_geom::Bounds2;
|
||||
@@ -25,12 +23,9 @@ pub fn export_window_with(d: &Drawing, space: &Space, window: Option<Bounds2>, t
|
||||
export_list(&list, window)
|
||||
}
|
||||
|
||||
/// ` opacity="…"` for a transparent primitive (none for an opaque one or a wipeout's mask).
|
||||
fn opacity(p: &cadcraft_render::DPrim) -> String {
|
||||
if p.kind == Kind::Mask || p.transparency == 0 {
|
||||
return String::new();
|
||||
}
|
||||
format!(r#" opacity="{:.2}""#, f64::from(p.alpha()) / 255.0)
|
||||
/// Opacity for a transparent primitive (none for an opaque one or a wipeout's mask).
|
||||
fn opacity(p: &cadcraft_render::DPrim) -> Option<String> {
|
||||
(p.kind != Kind::Mask && p.transparency != 0).then(|| format!("{:.2}", f64::from(p.alpha()) / 255.0))
|
||||
}
|
||||
|
||||
/// Write a display list (as [`export_window`] does for a space's own).
|
||||
@@ -59,13 +54,15 @@ pub fn export_list(list: &cadcraft_render::DisplayList, window: Option<Bounds2>)
|
||||
let stroke = vw.max(vh) / 1500.0;
|
||||
// Decimals: at least 6, more when the stroke would otherwise lose its leading digits.
|
||||
let dp = (3.0 - stroke.log10().floor()).clamp(6.0, 15.0) as usize;
|
||||
let mut s = String::new();
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {vw:.dp$} {vh:.dp$}" width="{:.0}" height="{:.0}"><rect width="100%" height="100%" fill="white"/>"#,
|
||||
1600.0,
|
||||
1600.0 * vh / vw
|
||||
);
|
||||
use craft_svg::write::{SvgWriter, num};
|
||||
let mut writer = SvgWriter::fragment();
|
||||
writer
|
||||
.root()
|
||||
.attr("viewBox", format!("0 0 {} {}", num(vw, dp), num(vh, dp)))
|
||||
.attr("width", format!("{:.0}", 1600.0))
|
||||
.attr("height", format!("{:.0}", 1600.0 * vh / vw))
|
||||
.open();
|
||||
writer.tag("rect").attr("width", "100%").attr("height", "100%").attr("fill", "white").empty();
|
||||
let white = Rgb(255, 255, 255);
|
||||
let tx = |x: f64| x - x0;
|
||||
let ty = |y: f64| y1 - y;
|
||||
@@ -75,52 +72,60 @@ pub fn export_list(list: &cadcraft_render::DisplayList, window: Option<Bounds2>)
|
||||
let pts = list.points(p);
|
||||
match p.kind {
|
||||
Kind::Polyline => {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<polyline fill="none" stroke="{c}"{op} stroke-width="{stroke:.dp$}" stroke-linecap="round" stroke-linejoin="round" points=""#
|
||||
);
|
||||
for q in pts {
|
||||
let _ = write!(s, "{:.dp$},{:.dp$} ", tx(q.x), ty(q.y));
|
||||
let points = craft_svg::drawing_write::points(pts.iter().map(|q| [tx(q.x), ty(q.y)]), dp);
|
||||
let mut tag = writer.tag("polyline").attr("fill", "none").attr("stroke", &c);
|
||||
if let Some(op) = &op {
|
||||
tag = tag.attr("opacity", op);
|
||||
}
|
||||
s.push_str(r#""/>"#);
|
||||
tag.attr("stroke-width", num(stroke, dp))
|
||||
.attr("stroke-linecap", "round")
|
||||
.attr("stroke-linejoin", "round")
|
||||
.attr("points", points)
|
||||
.empty();
|
||||
}
|
||||
Kind::Tris | Kind::Mask => {
|
||||
// A wipeout's mask hides what lies under it with the white background.
|
||||
let c = if p.kind == Kind::Mask { white.hex() } else { c };
|
||||
let _ = write!(s, r#"<path fill="{c}"{op} d=""#);
|
||||
for t in pts.chunks(3) {
|
||||
if let [a, b2, cc] = t {
|
||||
let _ =
|
||||
write!(s, "M{:.dp$} {:.dp$}L{:.dp$} {:.dp$}L{:.dp$} {:.dp$}Z", tx(a.x), ty(a.y), tx(b2.x), ty(b2.y), tx(cc.x), ty(cc.y));
|
||||
}
|
||||
let triangles = pts
|
||||
.chunks(3)
|
||||
.filter_map(|t| if let [a, b, c] = t { Some([[tx(a.x), ty(a.y)], [tx(b.x), ty(b.y)], [tx(c.x), ty(c.y)]]) } else { None });
|
||||
let path = craft_svg::drawing_write::triangles(triangles, dp);
|
||||
let mut tag = writer.tag("path").attr("fill", &c);
|
||||
if let Some(op) = &op {
|
||||
tag = tag.attr("opacity", op);
|
||||
}
|
||||
s.push_str(r#""/>"#);
|
||||
tag.attr("d", path).empty();
|
||||
}
|
||||
// Raster images are not written to SVG yet: their frame is.
|
||||
Kind::Image { .. } => {}
|
||||
Kind::Point => {
|
||||
if let Some(q) = pts.first() {
|
||||
let _ = write!(s, r#"<circle cx="{:.dp$}" cy="{:.dp$}" r="{:.dp$}" fill="{c}"{op}/>"#, tx(q.x), ty(q.y), stroke);
|
||||
let mut tag =
|
||||
writer.tag("circle").attr("cx", num(tx(q.x), dp)).attr("cy", num(ty(q.y), dp)).attr("r", num(stroke, dp)).attr("fill", &c);
|
||||
if let Some(op) = &op {
|
||||
tag = tag.attr("opacity", op);
|
||||
}
|
||||
tag.empty();
|
||||
}
|
||||
}
|
||||
Kind::Infinite { ray } => {
|
||||
if let (Some(bp), Some(dir)) = (pts.first(), pts.get(1)) {
|
||||
// A window can lie far from the base point: reach past it.
|
||||
let far = (vw + vh) * 2.0 + if window.is_some() { bp.dist(b.center()) } else { 0.0 };
|
||||
let a = if ray { *bp } else { *bp - *dir * far };
|
||||
let e = *bp + *dir * far;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<line x1="{:.dp$}" y1="{:.dp$}" x2="{:.dp$}" y2="{:.dp$}" stroke="{c}"{op} stroke-width="{stroke:.dp$}"/>"#,
|
||||
tx(a.x),
|
||||
ty(a.y),
|
||||
tx(e.x),
|
||||
ty(e.y)
|
||||
);
|
||||
let mut tag = writer
|
||||
.tag("line")
|
||||
.attr("x1", num(tx(a.x), dp))
|
||||
.attr("y1", num(ty(a.y), dp))
|
||||
.attr("x2", num(tx(e.x), dp))
|
||||
.attr("y2", num(ty(e.y), dp))
|
||||
.attr("stroke", &c);
|
||||
if let Some(op) = &op {
|
||||
tag = tag.attr("opacity", op);
|
||||
}
|
||||
tag.attr("stroke-width", num(stroke, dp)).empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.push_str("</svg>");
|
||||
s
|
||||
writer.close();
|
||||
writer.finish()
|
||||
}
|
||||
|
||||
+97
-728
@@ -13,14 +13,11 @@
|
||||
//! line segments instead of losing the shape). What the drawing shows of those (all but fills,
|
||||
//! gradients and patterns) is named in a read note, so it is never left out silently.
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Circle, Common, Drawing, Ellipse, EntityKind, Layer, Line, LwPolyline, Space};
|
||||
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3};
|
||||
use quick_xml::Reader;
|
||||
use quick_xml::XmlVersion;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
|
||||
use crate::{IoError, Result};
|
||||
|
||||
@@ -28,47 +25,20 @@ use crate::{IoError, Result};
|
||||
const MAX_DECOMPRESSED: usize = 64 << 20;
|
||||
/// Shape elements per file (rect, circle, path, …; each counted once).
|
||||
const MAX_ELEMENTS: usize = 500_000;
|
||||
/// Path data segments per `d` attribute.
|
||||
const MAX_PATH_SEGMENTS: usize = 100_000;
|
||||
/// Vertices in one polyline, and control points in one spline.
|
||||
const MAX_CURVE_POINTS: usize = 100_001;
|
||||
/// Layers created from Inkscape layer groups.
|
||||
const MAX_LAYERS: usize = 256;
|
||||
/// Nested `<g>`/`<svg>` transforms.
|
||||
const MAX_TRANSFORM_DEPTH: usize = 64;
|
||||
/// Flattened chords per elliptical arc under a non-uniform transform.
|
||||
const MAX_ARC_CHORDS: usize = 10_000;
|
||||
/// Generated vertices retained across the whole document (all paths and shapes), so repeated
|
||||
/// arc/curve flattening cannot amplify a compact input into unbounded geometry.
|
||||
const MAX_TOTAL_VERTS: usize = 8_000_000;
|
||||
|
||||
/// Elements whose whole subtree is skipped (paint servers, text, raster images, metadata).
|
||||
const SKIP: &[&[u8]] = &[
|
||||
b"defs",
|
||||
b"symbol",
|
||||
b"clipPath",
|
||||
b"mask",
|
||||
b"pattern",
|
||||
b"marker",
|
||||
b"linearGradient",
|
||||
b"radialGradient",
|
||||
b"filter",
|
||||
b"style",
|
||||
b"text",
|
||||
b"image",
|
||||
b"title",
|
||||
b"desc",
|
||||
b"metadata",
|
||||
];
|
||||
|
||||
/// Elements that hold children and push a transform stack frame.
|
||||
const CONTAINERS: &[&[u8]] = &[b"g", b"svg", b"a", b"switch"];
|
||||
|
||||
/// Read an SVG document, or a gzip-compressed one (`.svgz`, Inkscape's "Compressed SVG").
|
||||
pub fn read(bytes: &[u8]) -> Result<Drawing> {
|
||||
let unpacked;
|
||||
let plain: &[u8] = if bytes.starts_with(&[0x1f, 0x8b]) {
|
||||
unpacked = gunzip(bytes)?;
|
||||
unpacked =
|
||||
craft_svg::svgz::inflate(bytes, MAX_DECOMPRESSED).map_err(|_| IoError::Format("this SVGZ file's gzip stream is damaged".into()))?;
|
||||
&unpacked
|
||||
} else {
|
||||
bytes
|
||||
@@ -79,39 +49,6 @@ pub fn read(bytes: &[u8]) -> Result<Drawing> {
|
||||
Ok(parser.drawing)
|
||||
}
|
||||
|
||||
/// Decompress a gzip member (RFC 1952) with a hard output cap.
|
||||
fn gunzip(bytes: &[u8]) -> Result<Vec<u8>> {
|
||||
let damaged = || IoError::Format("this SVGZ file's gzip stream is damaged".into());
|
||||
if bytes.get(2) != Some(&8) {
|
||||
return Err(damaged());
|
||||
}
|
||||
let flg = bytes.get(3).copied().unwrap_or(0);
|
||||
let mut pos = 10usize;
|
||||
if flg & 0x04 != 0 {
|
||||
// FEXTRA
|
||||
let extra = bytes.get(pos..pos + 2).ok_or_else(damaged)?;
|
||||
pos += 2 + usize::from(u16::from_le_bytes([extra[0], extra[1]]));
|
||||
}
|
||||
if flg & 0x08 != 0 {
|
||||
pos = skip_cstring(bytes, pos).ok_or_else(damaged)?; // FNAME
|
||||
}
|
||||
if flg & 0x10 != 0 {
|
||||
pos = skip_cstring(bytes, pos).ok_or_else(damaged)?; // FCOMMENT
|
||||
}
|
||||
if flg & 0x02 != 0 {
|
||||
pos = pos.saturating_add(2); // FHCRC
|
||||
}
|
||||
let end = bytes.len().checked_sub(8).filter(|e| *e >= pos).ok_or_else(damaged)?;
|
||||
miniz_oxide::inflate::decompress_to_vec_with_limit(&bytes[pos..end], MAX_DECOMPRESSED).map_err(|_| damaged())
|
||||
}
|
||||
|
||||
/// Skip a NUL-terminated field; `None` when the terminator is missing.
|
||||
fn skip_cstring(bytes: &[u8], from: usize) -> Option<usize> {
|
||||
let rest = bytes.get(from..)?;
|
||||
let nul = rest.iter().position(|b| *b == 0)?;
|
||||
Some(from + nul + 1)
|
||||
}
|
||||
|
||||
fn parse_err<E: std::fmt::Display>(e: E) -> IoError {
|
||||
IoError::Format(format!("SVG: {e}"))
|
||||
}
|
||||
@@ -126,15 +63,11 @@ struct Parser {
|
||||
stack: Vec<Mat3>,
|
||||
/// Current Inkscape layer name.
|
||||
layer: String,
|
||||
layers: HashSet<String>,
|
||||
layer_color: u8,
|
||||
elements: usize,
|
||||
/// Generated vertices still allowed across the whole document. Arc/curve flattening can turn
|
||||
/// a compact path into many samples, and each flushed run is retained, so without a shared
|
||||
/// budget repeated arcs amplify a small input into gigabytes of geometry (CWE-400).
|
||||
verts_left: usize,
|
||||
/// > 0 while inside a skipped subtree; counts the starts seen there.
|
||||
skip: usize,
|
||||
/// What was left out, by kind ([`LeftOut`]).
|
||||
left_out: BTreeMap<LeftOut, usize>,
|
||||
}
|
||||
@@ -150,15 +83,6 @@ enum LeftOut {
|
||||
}
|
||||
|
||||
impl LeftOut {
|
||||
/// The kind of a skipped element ([`SKIP`]) that the drawing shows.
|
||||
fn of(name: &[u8]) -> Option<Self> {
|
||||
match name {
|
||||
b"text" => Some(Self::Text),
|
||||
b"image" => Some(Self::Image),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn describe(self, n: usize) -> String {
|
||||
let (one, many) = match self {
|
||||
Self::Text => ("text", "texts"),
|
||||
@@ -178,19 +102,12 @@ impl Parser {
|
||||
drawing: Drawing::new_metric(),
|
||||
stack: vec![Mat3::IDENTITY],
|
||||
layer: "0".into(),
|
||||
layers: HashSet::from(["0".to_string()]),
|
||||
layer_color: 1,
|
||||
elements: 0,
|
||||
verts_left: MAX_TOTAL_VERTS,
|
||||
skip: 0,
|
||||
left_out: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn left_out(&mut self, kind: LeftOut) {
|
||||
*self.left_out.entry(kind).or_default() += 1;
|
||||
}
|
||||
|
||||
/// The read note on what was left out, if anything was.
|
||||
fn note(&self) -> Option<String> {
|
||||
if self.left_out.is_empty() {
|
||||
@@ -201,140 +118,85 @@ impl Parser {
|
||||
}
|
||||
|
||||
fn parse(&mut self, text: &str) -> Result<()> {
|
||||
let mut reader = Reader::from_str(text);
|
||||
reader.config_mut().trim_text(true);
|
||||
loop {
|
||||
match reader.read_event().map_err(parse_err)? {
|
||||
Event::Start(e) => {
|
||||
let name = e.name();
|
||||
self.on_start(name.into_inner().as_bytes(), &e)?;
|
||||
use craft_svg::neutral_document::{self, Event, Skipped};
|
||||
let mut failure = None;
|
||||
let mut layer_color = 1u8;
|
||||
let result = neutral_document::visit(text, &mut |event| {
|
||||
let r = match event {
|
||||
Event::Layer(name) => {
|
||||
let color = Color::Index(layer_color);
|
||||
layer_color = if layer_color >= 7 { 1 } else { layer_color + 1 };
|
||||
self.drawing.layers.push(Layer { name, color, ..Layer::default() });
|
||||
Ok(())
|
||||
}
|
||||
Event::Empty(e) => {
|
||||
let name = e.name();
|
||||
self.on_element(name.into_inner().as_bytes(), &e)?;
|
||||
}
|
||||
Event::End(e) => {
|
||||
let name = e.name();
|
||||
self.on_end(name.into_inner().as_bytes());
|
||||
}
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
Event::Shape(shape) => self.map_shape(shape),
|
||||
};
|
||||
r.map_err(|e| {
|
||||
failure = Some(e);
|
||||
neutral_document::Error("CAD geometry mapping failed".into())
|
||||
})
|
||||
});
|
||||
if let Some(e) = failure {
|
||||
return Err(e);
|
||||
}
|
||||
let doc = result.map_err(|e| IoError::Format(e.to_string()))?;
|
||||
for (kind, count) in doc.skipped {
|
||||
let kind = match kind {
|
||||
Skipped::Text => LeftOut::Text,
|
||||
Skipped::Image => LeftOut::Image,
|
||||
Skipped::Use => LeftOut::Use,
|
||||
Skipped::Style => LeftOut::Style,
|
||||
Skipped::RoundedCorners => LeftOut::RoundedCorners,
|
||||
};
|
||||
self.left_out.insert(kind, count);
|
||||
}
|
||||
self.drawing.read_notes.extend(self.note());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A start tag: open a transform frame, descend into a skipped subtree, or treat a
|
||||
/// shape written as start+end the same as a self-closed one.
|
||||
fn on_start(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
|
||||
// A style sheet applies wherever it is (Inkscape keeps it in `<defs>`).
|
||||
if name == b"style" {
|
||||
self.left_out(LeftOut::Style);
|
||||
fn map_shape(&mut self, shape: craft_svg::neutral_document::Shape) -> Result<()> {
|
||||
use craft_svg::neutral_document::Primitive;
|
||||
let point = |p: craft_svg::path_data::Point| Vec2::new(p.x, p.y);
|
||||
let [a, b, c, d, e, f] = shape.transform;
|
||||
if let Some(current) = self.stack.first_mut() {
|
||||
*current = Mat3 { a, b, c, d, e, f };
|
||||
}
|
||||
if self.skip > 0 {
|
||||
self.skip += 1;
|
||||
return Ok(());
|
||||
}
|
||||
if hidden(e) {
|
||||
self.skip = 1;
|
||||
return Ok(());
|
||||
}
|
||||
if SKIP.contains(&name) {
|
||||
if let Some(kind) = LeftOut::of(name) {
|
||||
self.left_out(kind);
|
||||
self.layer = shape.layer;
|
||||
match shape.primitive {
|
||||
Primitive::Rect { x, y, width, height } => {
|
||||
let pts = [Vec2::new(x, y), Vec2::new(x + width, y), Vec2::new(x + width, y + height), Vec2::new(x, y + height)];
|
||||
self.add_polyline(&pts.map(|p| self.map(p)), true)?;
|
||||
}
|
||||
self.skip = 1;
|
||||
return Ok(());
|
||||
}
|
||||
if CONTAINERS.contains(&name) { self.enter_group(name, e) } else { self.on_element(name, e) }
|
||||
}
|
||||
|
||||
fn on_element(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
|
||||
if self.skip > 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if SKIP.contains(&name) || hidden(e) {
|
||||
if !hidden(e)
|
||||
&& let Some(kind) = LeftOut::of(name)
|
||||
{
|
||||
self.left_out(kind);
|
||||
Primitive::Circle { center, radius } => self.add_rounded(point(center), radius, radius)?,
|
||||
Primitive::Ellipse { center, rx, ry } => self.add_rounded(point(center), rx, ry)?,
|
||||
Primitive::Line { a, b } => self.add(EntityKind::Line(Line { a: v3(self.map(point(a))), b: v3(self.map(point(b))) }))?,
|
||||
Primitive::Polyline { points, closed } => {
|
||||
self.add_polyline(&points.into_iter().map(|p| self.map(point(p))).collect::<Vec<_>>(), closed)?
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// A shape's own `transform` (SVG 1.1 §7.5) maps it after its groups', for this element only.
|
||||
let local = attr(e, b"transform").as_deref().and_then(parse_transform);
|
||||
if let Some(local) = local {
|
||||
self.stack.push(self.cur().then_before(local));
|
||||
}
|
||||
let read = self.shape(name, e);
|
||||
if local.is_some() {
|
||||
self.stack.pop();
|
||||
}
|
||||
read
|
||||
}
|
||||
|
||||
fn shape(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
|
||||
match name {
|
||||
b"use" => {
|
||||
self.left_out(LeftOut::Use);
|
||||
Ok(())
|
||||
}
|
||||
b"rect" => self.rect(e),
|
||||
b"circle" => self.circle(e),
|
||||
b"ellipse" => self.ellipse(e),
|
||||
b"line" => self.line(e),
|
||||
b"polyline" => self.poly_points(e, false),
|
||||
b"polygon" => self.poly_points(e, true),
|
||||
b"path" => self.path(e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn on_end(&mut self, name: &[u8]) {
|
||||
if self.skip > 0 {
|
||||
self.skip -= 1;
|
||||
} else if CONTAINERS.contains(&name) && self.stack.len() > 1 {
|
||||
self.stack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn enter_group(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
|
||||
if name == b"svg" && self.stack.len() == 1 {
|
||||
self.stack[0] = viewport(e)?;
|
||||
}
|
||||
if name == b"g" && attr(e, b"inkscape:groupmode").as_deref() == Some("layer") {
|
||||
let raw = attr(e, b"inkscape:label").or_else(|| attr(e, b"id"));
|
||||
if let Some(raw) = raw {
|
||||
self.set_layer(&raw);
|
||||
Primitive::Path(paths) => {
|
||||
for path in paths {
|
||||
let path = Subpath {
|
||||
start: point(path.start),
|
||||
closed: path.closed,
|
||||
segs: path
|
||||
.segs
|
||||
.into_iter()
|
||||
.map(|seg| match seg {
|
||||
craft_svg::path_data::Segment::Line(p) => Seg::Line(point(p)),
|
||||
craft_svg::path_data::Segment::Cubic(a, b, c) => Seg::Cubic(point(a), point(b), point(c)),
|
||||
craft_svg::path_data::Segment::Arc { rx, ry, rot, large, sweep, end } => {
|
||||
Seg::Arc { rx, ry, rot, large, sweep, end: point(end) }
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
self.emit_subpath(&path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.stack.len() >= MAX_TRANSFORM_DEPTH {
|
||||
return Err(IoError::Format(format!("SVG: more than {MAX_TRANSFORM_DEPTH} nested groups")));
|
||||
}
|
||||
let current = *self.stack.last().unwrap_or(&Mat3::IDENTITY);
|
||||
let next = match attr(e, b"transform").as_deref().and_then(parse_transform) {
|
||||
Some(local) => current.then_before(local),
|
||||
None => current,
|
||||
};
|
||||
self.stack.push(next);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_layer(&mut self, raw: &str) {
|
||||
let name = sanitize_layer(raw);
|
||||
if !self.layers.contains(&name) {
|
||||
if self.layers.len() >= MAX_LAYERS {
|
||||
return;
|
||||
}
|
||||
let color = Color::Index(self.layer_color);
|
||||
self.layer_color = if self.layer_color >= 7 { 1 } else { self.layer_color + 1 };
|
||||
self.drawing.layers.push(Layer { name: name.clone(), color, ..Layer::default() });
|
||||
self.layers.insert(name.clone());
|
||||
}
|
||||
self.layer = name;
|
||||
}
|
||||
|
||||
/// The composed mapping for the current nesting: SVG user units → drawing units (mm).
|
||||
fn cur(&self) -> Mat3 {
|
||||
*self.stack.last().unwrap_or(&Mat3::IDENTITY)
|
||||
@@ -366,40 +228,6 @@ impl Parser {
|
||||
self.drawing.add(&Space::Model, common, kind).map(|_| ()).map_err(parse_err)
|
||||
}
|
||||
|
||||
// --- shapes -------------------------------------------------------------
|
||||
|
||||
fn rect(&mut self, e: &BytesStart) -> Result<()> {
|
||||
let x = num(e, b"x", 0.0);
|
||||
let y = num(e, b"y", 0.0);
|
||||
let w = num(e, b"width", 0.0);
|
||||
let h = num(e, b"height", 0.0);
|
||||
if w <= 0.0 || h <= 0.0 {
|
||||
return Ok(());
|
||||
}
|
||||
if num(e, b"rx", 0.0) > 0.0 || num(e, b"ry", 0.0) > 0.0 {
|
||||
self.left_out(LeftOut::RoundedCorners);
|
||||
}
|
||||
let pts = [Vec2::new(x, y), Vec2::new(x + w, y), Vec2::new(x + w, y + h), Vec2::new(x, y + h)];
|
||||
self.add_polyline(&pts.map(|p| self.map(p)), true)
|
||||
}
|
||||
|
||||
fn circle(&mut self, e: &BytesStart) -> Result<()> {
|
||||
let r = num(e, b"r", 0.0);
|
||||
if r <= 0.0 {
|
||||
return Ok(());
|
||||
}
|
||||
self.add_rounded(Vec2::new(num(e, b"cx", 0.0), num(e, b"cy", 0.0)), r, r)
|
||||
}
|
||||
|
||||
fn ellipse(&mut self, e: &BytesStart) -> Result<()> {
|
||||
let rx = num(e, b"rx", 0.0);
|
||||
let ry = num(e, b"ry", 0.0);
|
||||
if rx <= 0.0 || ry <= 0.0 {
|
||||
return Ok(());
|
||||
}
|
||||
self.add_rounded(Vec2::new(num(e, b"cx", 0.0), num(e, b"cy", 0.0)), rx, ry)
|
||||
}
|
||||
|
||||
/// A circle or ellipse through a transform. A circle stays a `CIRCLE` under rotations,
|
||||
/// uniform scales and reflections; anything else becomes an `ELLIPSE` holding the axes
|
||||
/// of the transformed shape — a linear map sends the unit circle to an ellipse whose
|
||||
@@ -439,24 +267,6 @@ impl Parser {
|
||||
self.add(EntityKind::Ellipse(Ellipse { center: v3(center), major: v3(major), ratio, start: 0.0, end: std::f64::consts::TAU }))
|
||||
}
|
||||
|
||||
fn line(&mut self, e: &BytesStart) -> Result<()> {
|
||||
let a = Vec2::new(num(e, b"x1", 0.0), num(e, b"y1", 0.0));
|
||||
let b = Vec2::new(num(e, b"x2", 0.0), num(e, b"y2", 0.0));
|
||||
self.add(EntityKind::Line(Line { a: v3(self.map(a)), b: v3(self.map(b)) }))
|
||||
}
|
||||
|
||||
fn poly_points(&mut self, e: &BytesStart, closed: bool) -> Result<()> {
|
||||
let Some(raw) = attr(e, b"points") else {
|
||||
return Ok(());
|
||||
};
|
||||
let nums: Vec<f64> = Numbers::new(&raw).collect();
|
||||
let mut pts: Vec<Vec2> = nums.as_chunks::<2>().0.iter().map(|[x, y]| self.map(Vec2::new(*x, *y))).collect();
|
||||
if pts.len() > MAX_CURVE_POINTS {
|
||||
pts.truncate(MAX_CURVE_POINTS);
|
||||
}
|
||||
self.add_polyline(&pts, closed)
|
||||
}
|
||||
|
||||
fn add_polyline(&mut self, pts: &[Vec2], closed: bool) -> Result<()> {
|
||||
if pts.len() < 2 {
|
||||
return Ok(());
|
||||
@@ -465,18 +275,6 @@ impl Parser {
|
||||
self.add(EntityKind::LwPolyline(LwPolyline { vertices, closed, const_width: 0.0, elevation: 0.0, plinegen: false }))
|
||||
}
|
||||
|
||||
// --- path data ----------------------------------------------------------
|
||||
|
||||
fn path(&mut self, e: &BytesStart) -> Result<()> {
|
||||
let Some(d) = attr(e, b"d") else {
|
||||
return Ok(());
|
||||
};
|
||||
for sp in parse_path(&d)? {
|
||||
self.emit_subpath(&sp)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Emit one subpath: runs of lines and arcs become an `LWPOLYLINE` (an arc becomes a
|
||||
/// bulge vertex, exactly like DXF's polyline bulge), runs of Bézier curves become a
|
||||
/// `SPLINE`. Under a non-uniform transform a circular arc is no longer circular, so it
|
||||
@@ -581,182 +379,6 @@ impl Parser {
|
||||
}
|
||||
}
|
||||
|
||||
/// The element is not rendered (`display="none"`, or a style that says so).
|
||||
fn hidden(e: &BytesStart) -> bool {
|
||||
if attr(e, b"display").as_deref() == Some("none") {
|
||||
return true;
|
||||
}
|
||||
attr(e, b"style").is_some_and(|s| s.replace(' ', "").contains("display:none"))
|
||||
}
|
||||
|
||||
fn attr(e: &BytesStart, name: &[u8]) -> Option<String> {
|
||||
// Stop at the first malformed attribute: skipping errors resumed the parser's duplicate check,
|
||||
// which rescans the attributes before it each time, so many duplicates were quadratic.
|
||||
for a in e.attributes() {
|
||||
let Ok(a) = a else { return None };
|
||||
if a.key.into_inner().as_bytes() == name {
|
||||
return a.normalized_value(XmlVersion::Explicit1_0).ok().map(|v| v.into_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn num(e: &BytesStart, name: &[u8], fallback: f64) -> f64 {
|
||||
attr(e, name).as_deref().and_then(parse_length_mm).unwrap_or(fallback)
|
||||
}
|
||||
|
||||
/// A bare number, or a number with an absolute CSS/SVG unit: millimetres here, everything
|
||||
/// else (px, the default; pt, pc, in, cm) through the CSS reference pixel (96 per inch).
|
||||
fn parse_length_mm(s: &str) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
let cut = s.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')).unwrap_or(s.len());
|
||||
let (n, unit) = s.split_at(cut);
|
||||
let value: f64 = n.trim().parse().ok()?;
|
||||
if !value.is_finite() {
|
||||
return None;
|
||||
}
|
||||
match unit.trim() {
|
||||
"" | "px" => Some(value),
|
||||
"mm" => Some(value),
|
||||
"cm" => Some(value * 10.0),
|
||||
"in" => Some(value * 25.4),
|
||||
"pt" => Some(value * 25.4 / 72.0),
|
||||
"pc" => Some(value * 25.4 / 6.0),
|
||||
_ => Some(value * 25.4 / 96.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The root mapping: `viewBox` and unit-bearing `width`/`height` become millimetres per user
|
||||
/// unit, and the page's Y axis is flipped so the drawing keeps its appearance with Y up.
|
||||
fn viewport(e: &BytesStart) -> Result<Mat3> {
|
||||
let vb = attr(e, b"viewBox").and_then(|raw| {
|
||||
let nums: Vec<f64> = Numbers::new(&raw).collect();
|
||||
match nums.as_slice() {
|
||||
[x, y, w, h] if w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0 => Some((*x, *y, *w, *h)),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
// A bare or `px` root size is in CSS pixels, not millimetres.
|
||||
let root_mm = |name: &[u8]| {
|
||||
let raw = attr(e, name)?;
|
||||
let mm = parse_length_mm(&raw)?;
|
||||
let unit = raw.trim().trim_start_matches(|c: char| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).trim();
|
||||
Some(if matches!(unit, "" | "px") { mm * 25.4 / 96.0 } else { mm })
|
||||
};
|
||||
let w_mm = root_mm(b"width");
|
||||
let h_mm = root_mm(b"height");
|
||||
let unit = match (vb, w_mm, h_mm) {
|
||||
(Some((_, _, vw, _)), Some(w), _) if w > 0.0 => w / vw,
|
||||
(Some((_, _, _, vh)), _, Some(h)) if h > 0.0 => h / vh,
|
||||
(Some(_), _, _) => 25.4 / 96.0,
|
||||
(None, _, _) => 25.4 / 96.0,
|
||||
};
|
||||
let (vx, vy, vh) = match vb {
|
||||
Some((x, y, _, h)) => (x, y, h),
|
||||
None => (0.0, 0.0, 0.0),
|
||||
};
|
||||
Ok(Mat3 { a: unit, b: 0.0, c: 0.0, d: -unit, e: -vx * unit, f: (vy + vh) * unit })
|
||||
}
|
||||
|
||||
/// `transform="…"`: a list of functions, applied left to right.
|
||||
fn parse_transform(s: &str) -> Option<Mat3> {
|
||||
let mut out: Option<Mat3> = None;
|
||||
let mut rest = s.trim();
|
||||
while !rest.is_empty() {
|
||||
let open = rest.find('(')?;
|
||||
let name = rest[..open].trim();
|
||||
let close = rest[open..].find(')')? + open;
|
||||
let args: Vec<f64> = Numbers::new(&rest[open + 1..close]).collect();
|
||||
let m = match (name, args.as_slice()) {
|
||||
("matrix", [a, b, c, d, e, f]) => Mat3 { a: *a, b: *b, c: *c, d: *d, e: *e, f: *f },
|
||||
("translate", [x]) => Mat3::translate(Vec2::new(*x, 0.0)),
|
||||
("translate", [x, y]) => Mat3::translate(Vec2::new(*x, *y)),
|
||||
("scale", [s]) => Mat3::scale(*s, *s),
|
||||
("scale", [sx, sy]) => Mat3::scale(*sx, *sy),
|
||||
("rotate", [a]) => Mat3::rotate(a.to_radians()),
|
||||
("rotate", [a, cx, cy]) => Mat3::rotate_about(Vec2::new(*cx, *cy), a.to_radians()),
|
||||
("skewX", [a]) => Mat3 { a: 1.0, b: 0.0, c: a.to_radians().tan(), d: 1.0, e: 0.0, f: 0.0 },
|
||||
("skewY", [a]) => Mat3 { a: 1.0, b: a.to_radians().tan(), c: 0.0, d: 1.0, e: 0.0, f: 0.0 },
|
||||
_ => return None,
|
||||
};
|
||||
out = Some(match out {
|
||||
Some(prev) => prev.then_before(m),
|
||||
None => m,
|
||||
});
|
||||
rest = rest[close + 1..].trim_start_matches(|c: char| c == ',' || c.is_whitespace());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn sanitize_layer(raw: &str) -> String {
|
||||
let cleaned: String =
|
||||
raw.trim().chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '$') { c } else { '_' }).take(128).collect();
|
||||
let cleaned = cleaned.trim_matches('_').to_string();
|
||||
if cleaned.is_empty() { "SVG".into() } else { cleaned }
|
||||
}
|
||||
|
||||
/// A scanner over an SVG number list: separators are whitespace and commas, and a sign
|
||||
/// starts a new number, so `10-20` is two numbers and `1e-5 2` is two numbers.
|
||||
struct Numbers<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl<'a> Numbers<'a> {
|
||||
fn new(s: &'a str) -> Self {
|
||||
Numbers { s: s.as_bytes(), i: 0 }
|
||||
}
|
||||
|
||||
fn skip_seps(&mut self) {
|
||||
while matches!(self.s.get(self.i), Some(b' ' | b'\t' | b'\r' | b'\n' | b',')) {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn next_num(&mut self) -> Option<f64> {
|
||||
self.skip_seps();
|
||||
let start = self.i;
|
||||
if matches!(self.s.get(self.i), Some(b'+' | b'-')) {
|
||||
self.i += 1;
|
||||
}
|
||||
let mut digits = 0;
|
||||
let mut dot = false;
|
||||
let mut exp = false;
|
||||
while let Some(c) = self.s.get(self.i) {
|
||||
match c {
|
||||
b'0'..=b'9' => {
|
||||
digits += 1;
|
||||
self.i += 1;
|
||||
}
|
||||
b'.' if !dot && !exp => {
|
||||
dot = true;
|
||||
self.i += 1;
|
||||
}
|
||||
b'e' | b'E' if !exp && digits > 0 => {
|
||||
exp = true;
|
||||
self.i += 1;
|
||||
if matches!(self.s.get(self.i), Some(b'+' | b'-')) {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
if digits == 0 {
|
||||
self.i = start;
|
||||
return None;
|
||||
}
|
||||
std::str::from_utf8(&self.s[start..self.i]).ok()?.parse::<f64>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for Numbers<'_> {
|
||||
type Item = f64;
|
||||
fn next(&mut self) -> Option<f64> {
|
||||
self.next_num()
|
||||
}
|
||||
}
|
||||
|
||||
/// One `M …` run of a `d` attribute.
|
||||
struct Subpath {
|
||||
start: Vec2,
|
||||
@@ -770,252 +392,9 @@ enum Seg {
|
||||
Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Vec2 },
|
||||
}
|
||||
|
||||
/// Tokens of a `d` attribute: command letters and numbers, in order.
|
||||
enum Tok {
|
||||
Cmd(u8),
|
||||
Num(f64),
|
||||
}
|
||||
|
||||
struct Tokenizer<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
/// Start of the most recently returned token.
|
||||
tok_start: usize,
|
||||
}
|
||||
|
||||
impl<'a> Tokenizer<'a> {
|
||||
fn new(s: &'a str) -> Self {
|
||||
Tokenizer { s: s.as_bytes(), i: 0, tok_start: 0 }
|
||||
}
|
||||
|
||||
/// Read an arc flag: a single `0` or `1` character, which needs no separator after it.
|
||||
fn next_flag(&mut self) -> Option<f64> {
|
||||
let mut nums = Numbers { s: self.s, i: self.i };
|
||||
nums.skip_seps();
|
||||
let v = match self.s.get(nums.i)? {
|
||||
b'0' => 0.0,
|
||||
b'1' => 1.0,
|
||||
_ => return None,
|
||||
};
|
||||
self.i = nums.i + 1;
|
||||
Some(v)
|
||||
}
|
||||
|
||||
fn next_tok(&mut self) -> Option<Tok> {
|
||||
let mut nums = Numbers { s: self.s, i: self.i };
|
||||
nums.skip_seps();
|
||||
self.i = nums.i;
|
||||
self.tok_start = self.i;
|
||||
let c = self.s.get(self.i).copied()?;
|
||||
if c.is_ascii_alphabetic() {
|
||||
self.i += 1;
|
||||
return Some(Tok::Cmd(c));
|
||||
}
|
||||
let tok = nums.next_num().map(Tok::Num);
|
||||
self.i = nums.i;
|
||||
tok
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `d` into subpaths, resolving relative commands and the S/T control reflections.
|
||||
fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
let mut tk = Tokenizer::new(d);
|
||||
let mut lookahead: Option<Tok> = None;
|
||||
let mut cmd = 0u8;
|
||||
let mut cur = Vec2::ZERO;
|
||||
let mut start = Vec2::ZERO;
|
||||
let mut segs: Vec<Seg> = Vec::new();
|
||||
let mut out: Vec<Subpath> = Vec::new();
|
||||
let closed = false;
|
||||
let mut prev_cubic: Option<Vec2> = None;
|
||||
let mut prev_quad: Option<Vec2> = None;
|
||||
let mut segments = 0usize;
|
||||
|
||||
let next_num = |tk: &mut Tokenizer, look: &mut Option<Tok>| -> Result<f64> {
|
||||
match look.take() {
|
||||
Some(Tok::Num(v)) => Ok(v),
|
||||
Some(other @ Tok::Cmd(_)) => {
|
||||
*look = Some(other);
|
||||
Err(IoError::Format("SVG: path command is missing coordinates".into()))
|
||||
}
|
||||
None => match tk.next_tok() {
|
||||
Some(Tok::Num(v)) => Ok(v),
|
||||
Some(other @ Tok::Cmd(_)) => {
|
||||
*look = Some(other);
|
||||
Err(IoError::Format("SVG: path command is missing coordinates".into()))
|
||||
}
|
||||
None => Err(IoError::Format("SVG: path command is missing coordinates".into())),
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
while let Some(tok) = lookahead.take().or_else(|| tk.next_tok()) {
|
||||
let rel = match tok {
|
||||
Tok::Cmd(c) => {
|
||||
if c.eq_ignore_ascii_case(&b'z') {
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed: true });
|
||||
segs = Vec::new();
|
||||
}
|
||||
cur = start;
|
||||
cmd = 0;
|
||||
continue;
|
||||
}
|
||||
cmd = c;
|
||||
c.is_ascii_lowercase()
|
||||
}
|
||||
tok @ Tok::Num(_) => {
|
||||
if cmd == 0 {
|
||||
return Err(IoError::Format("SVG: path data does not start with a command".into()));
|
||||
}
|
||||
lookahead = Some(tok);
|
||||
cmd.is_ascii_lowercase()
|
||||
}
|
||||
};
|
||||
let abs = cmd.to_ascii_uppercase();
|
||||
let count = match abs {
|
||||
b'M' | b'L' => 2,
|
||||
b'H' | b'V' | b'T' => 1,
|
||||
b'C' => 6,
|
||||
b'S' | b'Q' => 4,
|
||||
b'A' => 7,
|
||||
_ => return Err(IoError::Format(format!("SVG: unknown path command `{}`", cmd as char))),
|
||||
};
|
||||
let mut args = [0.0f64; 7];
|
||||
for (idx, slot) in args.iter_mut().enumerate().take(count) {
|
||||
if abs == b'A' && (idx == 3 || idx == 4) {
|
||||
// Flags are single characters; re-scan a pending number token from its start.
|
||||
if matches!(lookahead, Some(Tok::Num(_))) {
|
||||
lookahead = None;
|
||||
tk.i = tk.tok_start;
|
||||
}
|
||||
if lookahead.is_none() {
|
||||
*slot = tk.next_flag().ok_or_else(|| IoError::Format("SVG: path command is missing coordinates".into()))?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
*slot = next_num(&mut tk, &mut lookahead)?;
|
||||
}
|
||||
let point = |x: f64, y: f64| if rel { cur + Vec2::new(x, y) } else { Vec2::new(x, y) };
|
||||
match abs {
|
||||
b'M' => {
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed: false });
|
||||
segs = Vec::new();
|
||||
}
|
||||
cur = point(args[0], args[1]);
|
||||
start = cur;
|
||||
cmd = if rel { b'l' } else { b'L' };
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'L' => {
|
||||
cur = point(args[0], args[1]);
|
||||
segs.push(Seg::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'H' => {
|
||||
cur = Vec2::new(if rel { cur.x + args[0] } else { args[0] }, cur.y);
|
||||
segs.push(Seg::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'V' => {
|
||||
cur = Vec2::new(cur.x, if rel { cur.y + args[0] } else { args[0] });
|
||||
segs.push(Seg::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'C' => {
|
||||
let (c1, c2, p) = (point(args[0], args[1]), point(args[2], args[3]), point(args[4], args[5]));
|
||||
segs.push(Seg::Cubic(c1, c2, p));
|
||||
prev_cubic = Some(c2);
|
||||
prev_quad = None;
|
||||
cur = p;
|
||||
}
|
||||
b'S' => {
|
||||
let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2);
|
||||
let (c2, p) = (point(args[0], args[1]), point(args[2], args[3]));
|
||||
segs.push(Seg::Cubic(c1, c2, p));
|
||||
prev_cubic = Some(c2);
|
||||
prev_quad = None;
|
||||
cur = p;
|
||||
}
|
||||
b'Q' => {
|
||||
let (q, p) = (point(args[0], args[1]), point(args[2], args[3]));
|
||||
segs.push(Seg::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p));
|
||||
prev_quad = Some(q);
|
||||
prev_cubic = None;
|
||||
cur = p;
|
||||
}
|
||||
b'T' => {
|
||||
let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q);
|
||||
let p = point(args[0], args[1]);
|
||||
segs.push(Seg::Cubic(cur + (reflect - cur) * (2.0 / 3.0), p + (reflect - p) * (2.0 / 3.0), p));
|
||||
prev_quad = Some(reflect);
|
||||
prev_cubic = None;
|
||||
cur = p;
|
||||
}
|
||||
b'A' => {
|
||||
let end = point(args[5], args[6]);
|
||||
segs.push(Seg::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end });
|
||||
cur = end;
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
_ => return Err(IoError::Format("SVG: unsupported path command".into())),
|
||||
}
|
||||
segments += 1;
|
||||
if segments > MAX_PATH_SEGMENTS {
|
||||
return Err(IoError::Format("SVG: path has too many segments".into()));
|
||||
}
|
||||
if segs.len() > MAX_CURVE_POINTS {
|
||||
return Err(IoError::Format("SVG: path has too many segments".into()));
|
||||
}
|
||||
}
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The centre and signed sweep of a circular arc from `p0` to `p1` in a Y-up frame, per the
|
||||
/// SVG endpoint parameterisation (F.6.5). Radii that cannot span the chord are scaled up,
|
||||
/// as the specification requires.
|
||||
fn arc_center_circular(p0: Vec2, p1: Vec2, r: f64, large: bool, sweep: bool) -> Option<(Vec2, f64)> {
|
||||
if r <= 0.0 || !r.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let d = p1 - p0;
|
||||
let dist = d.x.hypot(d.y);
|
||||
let r = if dist > 2.0 * r { dist / 2.0 } else { r };
|
||||
if dist <= f64::EPSILON {
|
||||
return None;
|
||||
}
|
||||
let mid = (p0 + p1) * 0.5;
|
||||
let h = (r * r - (dist * dist) / 4.0).max(0.0).sqrt();
|
||||
let n = Vec2::new(-d.y / dist, d.x / dist);
|
||||
let sign = if large != sweep { 1.0 } else { -1.0 };
|
||||
let center = mid + n * (h * sign);
|
||||
let a0 = (p0.y - center.y).atan2(p0.x - center.x);
|
||||
let a1 = (p1.y - center.y).atan2(p1.x - center.x);
|
||||
let ccw = (a1 - a0).rem_euclid(std::f64::consts::TAU);
|
||||
Some((center, pick_sweep(ccw, large, sweep)))
|
||||
}
|
||||
|
||||
/// The signed sweep (CCW positive) for a chord sweep `ccw` in `[0, 2π)`: the centre is
|
||||
/// already chosen so that the magnitude matches `large`, so only the direction is left.
|
||||
fn pick_sweep(ccw: f64, large: bool, sweep: bool) -> f64 {
|
||||
let tau = std::f64::consts::TAU;
|
||||
let eps = f64::EPSILON;
|
||||
if sweep {
|
||||
if ccw <= eps { if large { tau } else { eps } } else { ccw }
|
||||
} else if ccw >= tau - eps {
|
||||
if large { -tau } else { -eps }
|
||||
} else {
|
||||
ccw - tau
|
||||
}
|
||||
let point = |p: Vec2| craft_svg::path_data::Point::new(p.x, p.y);
|
||||
craft_svg::path_data::arc_center_circular(point(p0), point(p1), r, large, sweep).map(|(p, angle)| (Vec2::new(p.x, p.y), angle))
|
||||
}
|
||||
|
||||
/// Flatten a general elliptical arc (any `rx`/`ry`/rotation) from `p0` to `p1` in user
|
||||
@@ -1041,44 +420,34 @@ fn flatten_arc(m: &Mat3, p0: Vec2, p1: Vec2, (rx, ry): (f64, f64), rot_deg: f64,
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Endpoint → centre parameterisation for a rotated elliptical arc (SVG F.6.5), in the
|
||||
/// frame the points are given in. Returns the centre, the start parameter and the signed
|
||||
/// sweep.
|
||||
fn elliptical_params(p0: Vec2, p1: Vec2, rx: f64, ry: f64, phi: f64, large: bool, sweep: bool) -> Option<(Vec2, f64, f64)> {
|
||||
if rx <= 0.0 || ry <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let (sphi, cphi) = phi.sin_cos();
|
||||
let dx = (p0.x - p1.x) / 2.0;
|
||||
let dy = (p0.y - p1.y) / 2.0;
|
||||
let x1 = cphi * dx + sphi * dy;
|
||||
let y1 = -sphi * dx + cphi * dy;
|
||||
let (rx, ry) = {
|
||||
let lambda = x1 * x1 / (rx * rx) + y1 * y1 / (ry * ry);
|
||||
if lambda > 1.0 {
|
||||
let s = lambda.sqrt();
|
||||
(rx * s, ry * s)
|
||||
} else {
|
||||
(rx, ry)
|
||||
}
|
||||
};
|
||||
let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
|
||||
let den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
|
||||
let coef = if sweep != large { 1.0 } else { -1.0 } * (num.max(0.0) / den.max(f64::MIN_POSITIVE)).sqrt();
|
||||
let cxp = coef * rx * y1 / ry;
|
||||
let cyp = -coef * ry * x1 / rx;
|
||||
let center = Vec2::new(cphi * cxp - sphi * cyp + (p0.x + p1.x) / 2.0, sphi * cxp + cphi * cyp + (p0.y + p1.y) / 2.0);
|
||||
let angle = |ux: f64, uy: f64, vx: f64, vy: f64| {
|
||||
let dot = ux * vx + uy * vy;
|
||||
let det = ux * vy - uy * vx;
|
||||
let denom = (ux.hypot(uy) * vx.hypot(vy)).max(f64::MIN_POSITIVE);
|
||||
(dot / denom).clamp(-1.0, 1.0).acos().copysign(det)
|
||||
};
|
||||
let (ux, uy) = ((x1 - cxp) / rx, (y1 - cyp) / ry);
|
||||
let (vx, vy) = ((-x1 - cxp) / rx, (-y1 - cyp) / ry);
|
||||
let theta = angle(1.0, 0.0, ux, uy);
|
||||
let ccw = angle(ux, uy, vx, vy).rem_euclid(std::f64::consts::TAU);
|
||||
Some((center, theta, pick_sweep(ccw, large, sweep)))
|
||||
let point = |p: Vec2| craft_svg::path_data::Point::new(p.x, p.y);
|
||||
craft_svg::path_data::elliptical_params(point(p0), point(p1), rx, ry, phi, large, sweep)
|
||||
.map(|(p, start, sweep)| (Vec2::new(p.x, p.y), start, sweep))
|
||||
}
|
||||
|
||||
/// Convert shared SVG path segments to CADCraft's geometry types.
|
||||
#[cfg(test)]
|
||||
fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
use craft_svg::path_data::{Point, Segment};
|
||||
let point = |p: Point| Vec2::new(p.x, p.y);
|
||||
let paths = craft_svg::path_data::parse_path(d).map_err(|e| IoError::Format(e.to_string()))?;
|
||||
Ok(paths
|
||||
.into_iter()
|
||||
.map(|sp| Subpath {
|
||||
start: point(sp.start),
|
||||
closed: sp.closed,
|
||||
segs: sp
|
||||
.segs
|
||||
.into_iter()
|
||||
.map(|seg| match seg {
|
||||
Segment::Line(p) => Seg::Line(point(p)),
|
||||
Segment::Cubic(c1, c2, p) => Seg::Cubic(point(c1), point(c2), point(p)),
|
||||
Segment::Arc { rx, ry, rot, large, sweep, end } => Seg::Arc { rx, ry, rot, large, sweep, end: point(end) },
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+78
-22
@@ -797,7 +797,7 @@ fn landscape_media_keeps_its_size_order_and_rotation() {
|
||||
assert_eq!(p.paper, media);
|
||||
|
||||
let dwg = write(&d, "t.dwg").unwrap();
|
||||
let back = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned();
|
||||
let back = String::from_utf8_lossy(&craft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned();
|
||||
assert_eq!(plot_paper_groups(&back, "Layout1"), (420.0, 297.0, rotation), "DWG, landscape {landscape}");
|
||||
let r = read(&dwg, "t.dwg").unwrap();
|
||||
let p = &r.layout("Layout1").unwrap().page;
|
||||
@@ -844,7 +844,7 @@ fn a_files_own_paper_groups_are_written_back() {
|
||||
assert_eq!((p.width_mm, p.height_mm, p.landscape), (pw, ph, landscape), "{media} {groups:?} read");
|
||||
assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), groups, "{media} {groups:?} DXF");
|
||||
let dwg = write(&r, "t.dwg").unwrap();
|
||||
let back = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned();
|
||||
let back = String::from_utf8_lossy(&craft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned();
|
||||
assert_eq!(plot_paper_groups(&back, "Layout1"), groups, "{media} {groups:?} DWG");
|
||||
let r = read(&dwg, "t.dwg").unwrap();
|
||||
assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), groups, "{media} {groups:?} DWG read and saved again");
|
||||
@@ -1234,7 +1234,7 @@ fn viewport_frozen_layers_survive_dwg() {
|
||||
let back = read(&dwg, "t.dwg").unwrap();
|
||||
assert_eq!(viewport_frozen(&back, 2), vec!["Walls".to_string(), "A B".to_string()]);
|
||||
// The DWG holds them in group 331, what AutoCAD reads.
|
||||
let p = pairs(&String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap());
|
||||
let p = pairs(&String::from_utf8(craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap());
|
||||
assert_eq!(frozen_331(&p), [layer_handle(&p, "Walls"), layer_handle(&p, "A B")]);
|
||||
}
|
||||
|
||||
@@ -1376,8 +1376,8 @@ fn generated_arrowhead_blocks_are_not_kept_as_user_blocks() {
|
||||
for (_, name) in crate::dxf_ext::ARROWS.iter().filter(|(k, _)| *k != cadcraft_render::Arrowhead::ClosedFilled) {
|
||||
assert!(dxf.contains(&format!("\r\n{name}\r\n")), "{name} is written");
|
||||
}
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap();
|
||||
let from_dwg = read_dxf(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let dwg = craft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap();
|
||||
let from_dwg = read_dxf(&craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
for (back, what) in [(read_dxf(dxf.as_bytes()).unwrap(), "DXF"), (from_dwg, "DWG")] {
|
||||
assert!(back.blocks.keys().all(|k| !k.starts_with('_')), "{what}: {:?}", back.blocks.keys().collect::<Vec<_>>());
|
||||
assert!(roundtrip(&back).blocks.keys().all(|k| !k.starts_with('_')), "{what}: second save");
|
||||
@@ -1408,8 +1408,8 @@ fn file_arrowhead_blocks_with_standard_names_are_kept() {
|
||||
d.dim_styles.push(DimStyle { name: "Dots".into(), arrow_block1: "_Dot".into(), arrow_block2: "_DotSmall".into(), ..DimStyle::default() });
|
||||
let kinds = |d: &Drawing, name: &str| d.block(name).map(|b| b.entities.iter().map(|e| e.kind.clone()).collect::<Vec<_>>()).unwrap_or_default();
|
||||
let dxf = write_dxf(&d);
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap();
|
||||
let from_dwg = read_dxf(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let dwg = craft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap();
|
||||
let from_dwg = read_dxf(&craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
for (back, what) in [(read_dxf(dxf.as_bytes()).unwrap(), "DXF"), (from_dwg, "DWG")] {
|
||||
for name in ["_Dot", "_DotSmall"] {
|
||||
assert_eq!(kinds(&back, name), kinds(&d, name), "{what}: {name}");
|
||||
@@ -1479,8 +1479,8 @@ fn many_entities(n: usize) -> Drawing {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ac1024_dwg(n: usize) -> Vec<u8> {
|
||||
let dxf = write_dxf(&many_entities(n)).replacen("AC1015", "AC1024", 1);
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap();
|
||||
assert_eq!(cadcraft_dwg::version(&dwg).as_deref(), Some("AC1024"));
|
||||
let dwg = craft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap();
|
||||
assert_eq!(craft_dwg::version(&dwg).as_deref(), Some("AC1024"));
|
||||
dwg
|
||||
}
|
||||
|
||||
@@ -1492,7 +1492,7 @@ fn ac1024_dwg(n: usize) -> Vec<u8> {
|
||||
fn ac1024_dwg_with_many_entities_opens() {
|
||||
let n = 30_000;
|
||||
let dwg = ac1024_dwg(n);
|
||||
let dxf = cadcraft_dwg::dwg_to_dxf(&dwg).unwrap();
|
||||
let dxf = craft_dwg::dwg_to_dxf(&dwg).unwrap();
|
||||
let tags = craft_dxf::parse(&dxf).unwrap().len();
|
||||
assert!(dxf.len() < dwg.len() * 20, "DXF {} bytes from {} DWG bytes", dxf.len(), dwg.len());
|
||||
assert!(tags < dwg.len(), "{tags} group codes from {} DWG bytes", dwg.len());
|
||||
@@ -1509,16 +1509,16 @@ fn ac1024_dwg_with_many_entities_opens() {
|
||||
#[test]
|
||||
fn oversized_dwg_and_dxf_are_rejected_early() {
|
||||
let dwg = ac1024_dwg(3000);
|
||||
let full = cadcraft_dwg::dwg_to_dxf(&dwg).unwrap().len();
|
||||
let full = craft_dwg::dwg_to_dxf(&dwg).unwrap().len();
|
||||
assert!(full > 400_000, "{full}");
|
||||
let limits = cadcraft_dwg::Limits { max_dxf_bytes: 300_000, ..cadcraft_dwg::Limits::DEFAULT };
|
||||
let e = cadcraft_dwg::dwg_to_dxf_with(&dwg, limits).unwrap_err();
|
||||
let limits = craft_dwg::Limits { max_dxf_bytes: 300_000, ..craft_dwg::Limits::DEFAULT };
|
||||
let e = craft_dwg::dwg_to_dxf_with(&dwg, limits).unwrap_err();
|
||||
assert!(e.starts_with("DWG: converting this 0."), "{e}");
|
||||
assert!(e.contains("MB file produced more than 0.3 MB of drawing data (the limit)"), "{e}");
|
||||
|
||||
let limits = cadcraft_dwg::Limits { max_dwg_bytes: 100_000, ..cadcraft_dwg::Limits::DEFAULT };
|
||||
let e = cadcraft_dwg::dwg_to_dxf_with(&dwg, limits).unwrap_err();
|
||||
assert!(e.starts_with("DWG: the file is 0.") && e.ends_with("MB, larger than the 0.1 MB CADCraft opens"), "{e}");
|
||||
let limits = craft_dwg::Limits { max_dwg_bytes: 100_000, ..craft_dwg::Limits::DEFAULT };
|
||||
let e = craft_dwg::dwg_to_dxf_with(&dwg, limits).unwrap_err();
|
||||
assert!(e.starts_with("DWG: the file is 0.") && e.ends_with("MB, larger than the 0.1 MB accepted by this bridge"), "{e}");
|
||||
|
||||
// Lines that aren't even group codes: the size is reported before anything is parsed.
|
||||
let text = "not a group code\nx\n".repeat(60);
|
||||
@@ -1526,6 +1526,26 @@ fn oversized_dwg_and_dxf_are_rejected_early() {
|
||||
assert_eq!(e.to_string(), "drawing too large: 60 DXF group codes, more than the 50 CADCraft reads (set CADCRAFT_MAX_DXF_TAGS to read more)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_dwg_diagnostics_keep_cadcraft_vocabulary() {
|
||||
assert_eq!(
|
||||
cadcraft_dwg_message("DWG: the file is 0.1 MB, larger than the 0.1 MB accepted by this bridge"),
|
||||
"DWG: the file is 0.1 MB, larger than the 0.1 MB CADCraft opens"
|
||||
);
|
||||
assert_eq!(
|
||||
cadcraft_dwg_message("DWG: 2 objects of types this bridge can't preserve were left out (FOO × 2)"),
|
||||
"DWG: 2 objects of types CADCraft doesn't keep were left out (FOO × 2)"
|
||||
);
|
||||
assert_eq!(
|
||||
cadcraft_dwg_message("DWG version `AC1015` can't be written (this bridge writes AC1018+)"),
|
||||
"DWG version `AC1015` can't be written (CADCraft writes AC1018+)"
|
||||
);
|
||||
assert_eq!(
|
||||
cadcraft_dwg_message("DXF: the input is 1024 MB, larger than the 1024 MB accepted for DWG conversion"),
|
||||
"DXF: the input is 1024 MB, larger than the 1024 MB CADCraft converts to DWG"
|
||||
);
|
||||
}
|
||||
|
||||
/// Issue #800: one unreadable object record doesn't fail the whole DWG. The reader skips it, the
|
||||
/// rest opens, and the drawing's read notes say how many records were left out and of which
|
||||
/// types, so a partial read never passes for a complete one. A complete read has no notes.
|
||||
@@ -2336,8 +2356,8 @@ fn arc_length_dimension_keeps_its_kind_and_centre_on_roundtrip() {
|
||||
_ => panic!("not a dimension"),
|
||||
}
|
||||
// And through DWG.
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg(text.as_bytes()).unwrap();
|
||||
let back = read_dxf(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let dwg = craft_dwg::dxf_to_dwg(text.as_bytes()).unwrap();
|
||||
let back = read_dxf(&craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let dims: Vec<_> = back.model.iter().filter_map(|e| if let EntityKind::Dimension(x) = &e.kind { Some(x.clone()) } else { None }).collect();
|
||||
assert_eq!(dims.len(), 1);
|
||||
assert!(matches!(dims[0].kind, DimKind::ArcLength), "{:?}", dims[0].kind);
|
||||
@@ -2923,6 +2943,15 @@ fn svg_path_lines_curves_and_arcs() {
|
||||
assert!((bulge.abs() - 1.0).abs() < 1e-6, "semicircle bulge is ±1, got {bulge}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_smooth_quadratic_has_two_coordinates() {
|
||||
let smooth = format!("{SVG_PAGE}<path d=\"M0 0 Q3 3 6 0 T12 0\"/></svg>");
|
||||
let explicit = format!("{SVG_PAGE}<path d=\"M0 0 Q3 3 6 0 Q9 -3 12 0\"/></svg>");
|
||||
let smooth = read(smooth.as_bytes(), "smooth.svg").unwrap();
|
||||
let explicit = read(explicit.as_bytes(), "explicit.svg").unwrap();
|
||||
assert_eq!(geometry(&smooth), geometry(&explicit));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_group_transforms_apply() {
|
||||
let svg = format!("{SVG_PAGE}<g transform=\"translate(5,2)\"><line x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\"/></g></svg>");
|
||||
@@ -3052,6 +3081,33 @@ fn svgz_gunzips_to_the_same_drawing() {
|
||||
assert_eq!(plain.model.iter().map(|e| &e.kind).collect::<Vec<_>>(), packed.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svgz_checks_the_gzip_trailer_and_combines_members() {
|
||||
let svg = format!("{SVG_PAGE}<circle cx=\"5\" cy=\"5\" r=\"1\"/></svg>");
|
||||
let split = svg.len() / 2;
|
||||
let mut members = gzip_of(&svg.as_bytes()[..split]);
|
||||
members.extend(gzip_of(&svg.as_bytes()[split..]));
|
||||
let plain = read(svg.as_bytes(), "a.svg").unwrap();
|
||||
let decoded = read(&members, "a.svgz").unwrap();
|
||||
assert_eq!(plain.model.iter().map(|e| &e.kind).collect::<Vec<_>>(), decoded.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
|
||||
|
||||
let mut corrupt = gzip_of(svg.as_bytes());
|
||||
let crc_offset = corrupt.len() - 8;
|
||||
corrupt[crc_offset] ^= 1;
|
||||
assert!(read(&corrupt, "a.svgz").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svgz_open_and_svg_export_follow_the_public_dispatch() {
|
||||
let source = format!("{SVG_PAGE}<line x1=\"1\" y1=\"2\" x2=\"9\" y2=\"7\"/></svg>");
|
||||
let drawing = read(&gzip_of(source.as_bytes()), "input.svgz").unwrap();
|
||||
assert_eq!(kinds(&drawing), ["Line"]);
|
||||
let output = write(&drawing, "output.svg").unwrap();
|
||||
assert!(std::str::from_utf8(&output).unwrap().contains("<polyline"));
|
||||
let reopened = read(&output, "output.svg").unwrap();
|
||||
assert!(!reopened.model.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_read_dispatches_by_extension() {
|
||||
let svg = format!("{SVG_PAGE}<circle cx=\"5\" cy=\"5\" r=\"1\"/></svg>");
|
||||
@@ -3568,7 +3624,7 @@ fn proxies_keep_their_class_in_dwg() {
|
||||
fn a_proxy_whose_class_is_unknown_is_left_out_of_the_dwg() {
|
||||
use acadrust::entities::{EntityType, ExtendedEntityData};
|
||||
use acadrust::objects::ObjectType;
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg_as(&proxy_file(), "AC1032").unwrap();
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&proxy_file(), "AC1032").unwrap();
|
||||
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap();
|
||||
let class_of = |id: i32| doc.classes.iter().find(|c| i32::from(c.class_number) == id).map(|c| c.dxf_name.clone());
|
||||
let mut objects: Vec<Option<String>> = doc
|
||||
@@ -3599,11 +3655,11 @@ fn a_proxy_whose_class_is_unknown_is_left_out_of_the_dwg() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_proxy_left_out_of_the_dwg_is_counted_as_unwritten() {
|
||||
let (_, unwritten) = cadcraft_dwg::dxf_to_dwg_noted(&proxy_file(), "AC1032").unwrap();
|
||||
let (_, unwritten) = craft_dwg::dxf_to_dwg_noted(&proxy_file(), "AC1032").unwrap();
|
||||
assert_eq!(unwritten, [("ACAD_PROXY_OBJECT".to_string(), 1)].into_iter().collect());
|
||||
let d = read(&proxy_file(), "p.dxf").unwrap();
|
||||
let binary = write_with(&d, "p.dxf", &SaveOptions { version: Some(Version::R2018), binary: true }).unwrap();
|
||||
let (_, unwritten) = cadcraft_dwg::dxf_to_dwg_noted(&binary, "AC1032").unwrap();
|
||||
let (_, unwritten) = craft_dwg::dxf_to_dwg_noted(&binary, "AC1032").unwrap();
|
||||
// CADCraft's own save already left the stray proxy out; the binary DXF's other three go.
|
||||
assert_eq!(unwritten, [("ACAD_PROXY_ENTITY".to_string(), 1), ("ACAD_PROXY_OBJECT".to_string(), 2)].into_iter().collect());
|
||||
}
|
||||
@@ -3620,7 +3676,7 @@ fn a_binary_dxf_leaves_its_proxies_out_of_the_dwg() {
|
||||
let d = read(&proxy_file(), "p.dxf").unwrap();
|
||||
let binary = write_with(&d, "p.dxf", &SaveOptions { version: Some(Version::R2018), binary: true }).unwrap();
|
||||
assert!(binary.starts_with(b"AutoCAD Binary DXF"));
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg_as(&binary, "AC1032").unwrap();
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&binary, "AC1032").unwrap();
|
||||
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap();
|
||||
let proxies = doc.objects.values().filter(|o| matches!(o, ObjectType::ProxyObject(_))).count()
|
||||
+ doc.entities().filter(|e| matches!(e, EntityType::Extended(x) if matches!(x.data, ExtendedEntityData::Proxy(_)))).count();
|
||||
|
||||
@@ -285,7 +285,7 @@ fn standard_dimassoc_associates_in_dxf_and_dwg() {
|
||||
let back = read_dxf(plain.as_bytes()).unwrap();
|
||||
assert_standard_assoc(&c, &back, "DXF");
|
||||
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg_as(plain.as_bytes(), Version::R2018.code()).unwrap();
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(plain.as_bytes(), Version::R2018.code()).unwrap();
|
||||
let back = read(&dwg, "case.dwg").unwrap();
|
||||
assert_standard_assoc(&c, &back, "DWG");
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ fn an_ac1018_dwg_gets_the_variable_dictionary_autocad_always_writes() {
|
||||
#[test]
|
||||
fn the_dictionary_keeps_the_drawings_dimassoc_and_hidetext() {
|
||||
let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DIMASSOC\n70\n1\n9\n$HIDETEXT\n70\n0\n0\nENDSEC\n0\nEOF\n";
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG");
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG");
|
||||
let doc = read_dwg(&dwg);
|
||||
let vars = variable_dictionary(&doc).expect("AC1018 DWG: the named object dictionary has an AcDbVariableDictionary");
|
||||
assert_eq!(value(&vars, "DIMASSOC"), Some("1"), "DIMASSOC in {vars:?}");
|
||||
@@ -107,7 +107,7 @@ fn the_dictionary_keeps_the_drawings_dimassoc_and_hidetext() {
|
||||
#[test]
|
||||
fn impossible_header_values_fall_back_to_the_defaults() {
|
||||
let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DIMASSOC\n70\n9\n9\n$HIDETEXT\n70\n7\n0\nENDSEC\n0\nEOF\n";
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG");
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1018").expect("write the DWG");
|
||||
let doc = read_dwg(&dwg);
|
||||
let vars = variable_dictionary(&doc).expect("AC1018 DWG: the named object dictionary has an AcDbVariableDictionary");
|
||||
assert_eq!(value(&vars, "DIMASSOC"), Some("2"), "DIMASSOC in {vars:?}");
|
||||
@@ -139,7 +139,7 @@ fn a_variable_dictionary_the_drawing_has_is_left_alone() {
|
||||
assert!(source.set_drawing_variable("CMLEADERSTYLE", "Notes"));
|
||||
let dxf = acadrust::DxfWriter::new(&source).write_to_vec().expect("write a DXF with the dictionary");
|
||||
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg_as(&dxf, "AC1018").expect("write the DWG");
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&dxf, "AC1018").expect("write the DWG");
|
||||
let doc = read_dwg(&dwg);
|
||||
let vars = variable_dictionary(&doc).expect("the drawing's dictionary is kept");
|
||||
assert_eq!(vars.len(), 1, "{vars:?}");
|
||||
|
||||
@@ -155,7 +155,7 @@ fn a_rotated_linear_dimension_stores_its_projected_length() {
|
||||
Vec3::new(-40.0, 105.0, 0.0),
|
||||
);
|
||||
let dwg = write_with(&d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap();
|
||||
let dxf = String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let dxf = String::from_utf8(craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let t = tags(&dxf);
|
||||
let dim = t.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap();
|
||||
let m: f64 = t[dim..].iter().find(|(c, _)| *c == 42).unwrap().1.parse().unwrap();
|
||||
@@ -242,7 +242,7 @@ fn justified_text_made_here_writes_its_baseline_start_for_every_justification()
|
||||
/// Group 42 of a dimension in the DXF AutoCAD reads from `d`'s DWG.
|
||||
fn stored_measurement(d: &Drawing) -> f64 {
|
||||
let dwg = write_with(d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap();
|
||||
let dxf = String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let dxf = String::from_utf8(craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let t = tags(&dxf);
|
||||
let dim = t.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap();
|
||||
t[dim..].iter().find(|(c, _)| *c == 42).unwrap().1.parse().unwrap()
|
||||
|
||||
@@ -93,7 +93,7 @@ fn dwg_keeps_the_solids_geometry() {
|
||||
let d = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
// The DWG read back (as the bridge's DXF) binds the same bytes to both solids.
|
||||
let back = String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let back = String::from_utf8(craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let mut got = asm_data(&back);
|
||||
got.sort();
|
||||
assert_eq!(got, vec![("2A".to_string(), SAB_HEX.to_string()), ("2B".to_string(), SAB_HEX.to_string())]);
|
||||
|
||||
@@ -99,7 +99,7 @@ fn utf8_wins_when_valid() {
|
||||
/// A code page CADCraft doesn't know (or none) reads as ANSI_1252, as before.
|
||||
#[test]
|
||||
fn unknown_code_page_falls_back_to_ansi_1252() {
|
||||
for cp in ["ANSI_1361", "EBCDIC", "", "\u{1}"] {
|
||||
for cp in ["ANSI_UNKNOWN", "EBCDIC", "", "\u{1}"] {
|
||||
let d = cadcraft_io::read_dxf(&ascii_dxf("AC1015", cp, b"Caf\xE9", b"B", b"\x80 \xD8")).unwrap();
|
||||
assert_eq!(names(&d), ("Café".into(), "B".into(), "€ Ø".into()), "{cp:?}");
|
||||
}
|
||||
@@ -209,7 +209,9 @@ fn binary_dxf_honours_the_code_page() {
|
||||
// a pre-R2007 binary file has no way to escape to UTF-8, so its strings are never read as it.
|
||||
assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xD1\xB2")), "СІ");
|
||||
assert_eq!(read(&bin("AC1021", "ANSI_1251", "Привет".as_bytes())), "Привет");
|
||||
assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Café");
|
||||
assert_eq!(read(&bin("AC1015", "ANSI_UNKNOWN", b"Caf\xE9")), "Café");
|
||||
assert_eq!(read(&bin("AC1015", "ANSI_1361", b"\xD0\x65\x8B\x69")), "한글");
|
||||
assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Caf\u{FFFD}");
|
||||
}
|
||||
|
||||
/// Truncated and invalid multibyte sequences become U+FFFD; nothing panics and the structure of
|
||||
@@ -248,7 +250,7 @@ fn hostile_multibyte_never_panics() {
|
||||
#[test]
|
||||
fn pre_2007_dwg_text_decodes_through_the_bridge() {
|
||||
let dxf = ascii_dxf("AC1015", "ANSI_1251", b"\xD1\xEB\xEE\xE9", b"\xC1\xEB\xEE\xEA", b"\xCF\xF0\xE8\xE2\xE5\xF2");
|
||||
let dwg = cadcraft_dwg::dxf_to_dwg(&dxf).unwrap();
|
||||
let dwg = craft_dwg::dxf_to_dwg(&dxf).unwrap();
|
||||
let d = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
assert_eq!(names(&d), ("Слой".into(), "Блок".into(), "Привет".into()));
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ fn dwg_keeps_true_colours_and_transparency() {
|
||||
);
|
||||
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
assert_eq!(cadcraft_dwg::version(&dwg).as_deref(), Some("AC1032"));
|
||||
assert_eq!(craft_dwg::version(&dwg).as_deref(), Some("AC1032"));
|
||||
let header = records(&cadcraft_io::write_dxf(&d), "SECTION");
|
||||
assert_eq!(header.first().and_then(|h| group(h, "1")), Some("AC1015"), "the DXF stays R2000");
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ fn dwg_at_every_version_reads_back() {
|
||||
let d = sample();
|
||||
for v in Version::ALL {
|
||||
let dwg = write_with(&d, "x.dwg", &opts(v, false)).unwrap();
|
||||
assert_eq!(cadcraft_dwg::version(&dwg).as_deref(), Some(v.code()), "{v}");
|
||||
assert_eq!(craft_dwg::version(&dwg).as_deref(), Some(v.code()), "{v}");
|
||||
let back = read(&dwg, "x.dwg").unwrap();
|
||||
assert_eq!(save_version(&back), v, "{v}");
|
||||
assert_eq!(back.model.len(), d.model.len(), "{v}");
|
||||
@@ -187,6 +187,6 @@ fn dwg_at_every_version_reads_back() {
|
||||
#[test]
|
||||
fn dwg_default_is_at_least_2004() {
|
||||
let from_r2000 = read(write_dxf(&sample()).as_bytes(), "x.dxf").unwrap();
|
||||
assert_eq!(cadcraft_dwg::version(&write(&from_r2000, "x.dwg").unwrap()).as_deref(), Some("AC1018"));
|
||||
assert_eq!(cadcraft_dwg::version(&write(&sample(), "x.dwg").unwrap()).as_deref(), Some("AC1032"));
|
||||
assert_eq!(craft_dwg::version(&write(&from_r2000, "x.dwg").unwrap()).as_deref(), Some("AC1018"));
|
||||
assert_eq!(craft_dwg::version(&write(&sample(), "x.dwg").unwrap()).as_deref(), Some("AC1032"));
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ fn with_scale_action() -> String {
|
||||
|
||||
/// A scale action goes through CADCraft's own DWG save (the bridge DXF, then acadrust) whole:
|
||||
/// the DWG holds it with its connections, and it reads back as the same action. AutoCAD refused
|
||||
/// such DWGs while acadrust left out the byte after its connections (cadcraft-dwg's
|
||||
/// such DWGs while acadrust left out the byte after its connections (craft-dwg's
|
||||
/// `scale_actions_keep_the_byte_autocad_reads_after_their_connections` covers the byte).
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
|
||||
@@ -37,6 +37,7 @@ mod layout_plot_window;
|
||||
mod leader_vertex_elevation;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod low_handseed;
|
||||
mod minsert_marker;
|
||||
mod mleader_content;
|
||||
mod mleader_roundtrip;
|
||||
mod mline_roundtrip;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user