mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 22:30:47 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
789aa38030 | ||
|
|
5ef8b342de | ||
|
|
5f751ee30d | ||
|
|
0f7940a986 |
@@ -22,11 +22,17 @@ Generated-in-code assets are original and have no file to list:
|
||||
- the sample drawings (`crates/engine/src/sample.rs`);
|
||||
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
|
||||
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
|
||||
- the self-contained line drawings/DXF bytes generated by provider regressions in
|
||||
`crates/ui-egui/src/file_provider_app/tests.rs` and
|
||||
`apps/cadcraft-web/src/file_providers/browser_tests.rs` (CADCraft contributors, original test
|
||||
code/data, MIT OR Apache-2.0; no vendor drawing, external image, font or other asset is added).
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
|
||||
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
|
||||
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
|
||||
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
|
||||
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
|
||||
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
|
||||
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
|
||||
|
||||
Generated
+71
@@ -959,6 +959,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
@@ -1022,6 +1023,12 @@ dependencies = [
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.10.0"
|
||||
@@ -4064,6 +4071,16 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minicov"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
@@ -4263,6 +4280,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
@@ -4798,6 +4824,12 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
||||
|
||||
[[package]]
|
||||
name = "open"
|
||||
version = "5.4.5"
|
||||
@@ -6824,6 +6856,45 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test"
|
||||
version = "0.3.79"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"cast",
|
||||
"js-sys",
|
||||
"libm",
|
||||
"minicov",
|
||||
"nu-ansi-term",
|
||||
"num-traits",
|
||||
"oorandom",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test-macro",
|
||||
"wasm-bindgen-test-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-macro"
|
||||
version = "0.3.79"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-shared"
|
||||
version = "0.2.129"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
|
||||
|
||||
[[package]]
|
||||
name = "wayland-backend"
|
||||
version = "0.3.17"
|
||||
|
||||
@@ -85,6 +85,7 @@ egui = { version = "0.37", default-features = false, features = ["default_fonts"
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
wasm-bindgen-test = "0.3.79"
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
|
||||
@@ -10,9 +10,435 @@ docs/brand/LICENSE-brand.txt.
|
||||
Third-party material
|
||||
|
||||
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
|
||||
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the
|
||||
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
|
||||
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
|
||||
is available from crates.io and the repository above.
|
||||
is available from crates.io and the repository above. The licence text and upstream third-party
|
||||
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
|
||||
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
|
||||
|
||||
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
|
||||
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
|
||||
The Mozilla Public License 2.0 text and the upstream third-party notices follow.
|
||||
|
||||
The following text is reproduced verbatim from licenses/dwg/acadrust-MPL-2.0.txt:
|
||||
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under the name "LEGAL", and included in all Covered Software
|
||||
distributed in Source Code Form. Except to the extent prohibited by
|
||||
statute or regulation, such description must be sufficiently detailed
|
||||
for a recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
|
||||
The following text is reproduced verbatim from licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md:
|
||||
|
||||
# Third-Party Notices
|
||||
|
||||
## ACadSharp
|
||||
|
||||
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
|
||||
history's initial DWG support commit identifies the source classes explicitly, including
|
||||
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
|
||||
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
|
||||
|
||||
Copyright (c) 2021 Albert Domenech
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## DWG Format References
|
||||
|
||||
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
|
||||
specification and reverse engineering, including comparison with drawings produced by CAD
|
||||
applications. LibreDWG is used as a secondary cross-check for selected field names and
|
||||
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
|
||||
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
|
||||
translated routines. The repository history and source review found no LibreDWG routines
|
||||
ported into the implementation. The source comments identify the specific cross-checks.
|
||||
|
||||
|
||||
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
|
||||
|
||||
@@ -61,6 +61,8 @@ fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
//! An INSERT's ATTRIBs and SEQEND reached from AutoLISP through the CLI (`entnext`, `entget`,
|
||||
//! `entmod`, `entdel`): the walk, a value edit (one Undo step), names that stop holding (erase,
|
||||
//! ATTSYNC, Undo, a reinsert that reuses the parent handle), edits that are refused, and the
|
||||
//! name bounds.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A scratch directory, removed on drop also when an assertion fails.
|
||||
struct Dir(PathBuf);
|
||||
|
||||
impl Dir {
|
||||
fn new(tag: &str) -> Dir {
|
||||
let p = std::env::temp_dir().join(format!("cc-cli-attribs-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&p);
|
||||
std::fs::create_dir_all(&p).expect("create scratch dir");
|
||||
Dir(p)
|
||||
}
|
||||
|
||||
fn path(&self, name: &str) -> PathBuf {
|
||||
self.0.join(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One `cadcraft-cli run`: a fresh profile, an optional drawing to open, and the steps to run.
|
||||
struct Run {
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn new(dir: &Dir, file: Option<&Path>) -> Run {
|
||||
let mut args: Vec<String> = vec!["run".into(), "--config-dir".into(), dir.path("profile").to_string_lossy().into_owned()];
|
||||
match file {
|
||||
Some(f) => args.push(f.to_string_lossy().into_owned()),
|
||||
None => args.push("--metric".into()),
|
||||
}
|
||||
Run { args }
|
||||
}
|
||||
|
||||
fn cmd(&mut self, id: &str, params: Value) -> &mut Run {
|
||||
self.args.push("--cmd".into());
|
||||
self.args.push(format!("{id} {params}"));
|
||||
self
|
||||
}
|
||||
|
||||
fn lisp(&mut self, code: &str) -> &mut Run {
|
||||
self.cmd("lisp", json!({ "code": code }))
|
||||
}
|
||||
|
||||
fn save(&mut self, path: &Path) -> &mut Run {
|
||||
self.args.push("--save".into());
|
||||
self.args.push(path.to_string_lossy().into_owned());
|
||||
self
|
||||
}
|
||||
|
||||
fn output(&self) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&self.args).output().expect("run cadcraft-cli")
|
||||
}
|
||||
|
||||
/// Run it: the value each `lisp` step returned, in order (commands' own results are left out).
|
||||
fn out(&self) -> Vec<Value> {
|
||||
let out = self.output();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{}: {}", self.args.join(" "), err);
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.lines()
|
||||
.map(|l| serde_json::from_str::<Value>(l).unwrap_or_else(|e| panic!("not a result: {l}: {e}")))
|
||||
.filter(|v| v.get("value").is_some())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The value a `lisp` step returned, as AutoLISP's `prin1` shows it.
|
||||
fn value(results: &[Value], i: usize) -> String {
|
||||
match results.get(i).and_then(|r| r.get("value")) {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
other => panic!("step {i}: no value: {other:?} in {results:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` without the quotes `prin1` puts round a string.
|
||||
fn text(results: &[Value], i: usize) -> String {
|
||||
value(results, i).trim_matches('"').to_string()
|
||||
}
|
||||
|
||||
/// TAGBLK.dxf: block TAGBLK with a circle and four attribute definitions (TAG1 D1, TAG2 D2
|
||||
/// verify, TAG3 P3 preset, TAG4 C4 constant). Opening the file again gives the drawing fresh
|
||||
/// names.
|
||||
const FIXTURE: &str = r#"(progn
|
||||
(entmake '((0 . "BLOCK") (2 . "TAGBLK") (70 . 2) (10 0.0 0.0 0.0)))
|
||||
(entmake '((0 . "CIRCLE") (10 -5.0 0.0 0.0) (40 . 2.0)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 0.0 0.0) (40 . 2.5) (1 . "D1") (3 . "P1") (2 . "TAG1") (70 . 0)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 5.0 0.0) (40 . 2.5) (1 . "D2") (3 . "P2") (2 . "TAG2") (70 . 4)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 10.0 0.0) (40 . 2.5) (1 . "P3") (3 . "P3") (2 . "TAG3") (70 . 8)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 15.0 0.0) (40 . 2.5) (1 . "C4") (3 . "P4") (2 . "TAG4") (70 . 2)))
|
||||
(entmake '((0 . "ENDBLK"))))"#;
|
||||
|
||||
/// The first reference: INSERT TAGBLK at (10,10) with TAG1 "A1", TAG2 verified as "B1" and
|
||||
/// TAG3 preset ("P3"); TAG4 is constant, so it is not asked.
|
||||
const INSERT: &str = r#"(command "_.-INSERT" "TAGBLK" '(10 10) 1 1 0 "A1" "B1" "")"#;
|
||||
|
||||
fn fixture(dir: &Dir) -> PathBuf {
|
||||
let file = dir.path("TAGBLK.dxf");
|
||||
let mut run = Run::new(dir, None);
|
||||
let out = run.lisp(FIXTURE).save(&file).out();
|
||||
assert_eq!(text(&out, 0), "TAGBLK");
|
||||
file
|
||||
}
|
||||
|
||||
/// The walk from the entity named `i`: its records' tags and values, then the type of the record
|
||||
/// that ends the run.
|
||||
const WALK: &str = r#"(progn
|
||||
(setq e (entnext i) n 0 ts nil ed nil)
|
||||
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
|
||||
(setq ts (append ts (list (cdr (assoc 2 ed)) (cdr (assoc 1 ed)))) n (1+ n) e (entnext e)))
|
||||
(list n ts (cdr (assoc 0 ed))))"#;
|
||||
|
||||
#[test]
|
||||
fn the_walk_reaches_each_attrib_and_ends_at_the_seqend() {
|
||||
let dir = Dir::new("walk");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn
|
||||
{INSERT}
|
||||
(setq i (entlast))
|
||||
(setvar "ATTREQ" 0)
|
||||
(command "_.-INSERT" "TAGBLK" '(60 10) 1 1 0)
|
||||
(setvar "ATTREQ" 1)
|
||||
(setq second (entlast))
|
||||
"inserted")"#
|
||||
))
|
||||
// Three attributes, then the SEQEND owned by the reference, then the next main entity.
|
||||
.lisp(&format!(
|
||||
r#"(progn {WALK}
|
||||
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (equal (entnext e) second) (cdr (assoc 0 (entget (entnext e))))))"#
|
||||
))
|
||||
// The second reference (no attribute answers, ATTREQ 0) took the definitions' values; its
|
||||
// own run ends at its SEQEND, with nothing drawn after it.
|
||||
.lisp(&format!(
|
||||
r#"(progn (setq i second) {WALK}
|
||||
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (entnext e)))"#
|
||||
))
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), "inserted");
|
||||
assert_eq!(value(&out, 1), "(3 (\"TAG1\" \"A1\" \"TAG2\" \"B1\" \"TAG3\" \"P3\") \"SEQEND\" T T \"INSERT\")");
|
||||
// Its record ends with its own SEQEND, and nothing is drawn after the reference.
|
||||
assert_eq!(value(&out, 2), "(3 (\"TAG1\" \"D1\" \"TAG2\" \"D2\" \"TAG3\" \"P3\") \"SEQEND\" T nil)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_edit_changes_group_one_only_and_is_one_undo_step() {
|
||||
let dir = Dir::new("value");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 2 (entget a))) (cdr (assoc 1 (entget a)))))"#))
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq d (entget a) r (entmod (subst (cons 1 "A2") (assoc 1 d) d)))
|
||||
(list (cdr (assoc 0 r)) (cdr (assoc 1 r)) (cdr (assoc 1 (entget a))) (cdr (assoc 2 (entget a)))
|
||||
(cdr (assoc 40 (entget a))) (cdr (assoc 8 (entget a))) (equal (cdr (assoc -2 (entget a))) i)))"#,
|
||||
)
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
// The edit is one Undo step: the value is back, and the name given before it holds no
|
||||
// longer (the drawing it was given in was restored from another state).
|
||||
.lisp(
|
||||
r#"(list (entget a) (progn (setq e (entnext (entlast)))
|
||||
(list (cdr (assoc 2 (entget e))) (cdr (assoc 1 (entget e))))))"#,
|
||||
)
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"TAG1\" \"A1\")");
|
||||
assert_eq!(value(&out, 1), "(\"ATTRIB\" \"A2\" \"A2\" \"TAG1\" 2.5 \"0\" T)");
|
||||
assert_eq!(value(&out, 2), "(nil (\"TAG1\" \"A1\"))");
|
||||
// Redo brings the edit back; the name given before the Undo still names nothing.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i) d (entget a)) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#))
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.cmd("redo", json!({ "count": 1 }))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(nil \"A2\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_stops_holding_after_erase_attsync_and_undo() {
|
||||
let dir = Dir::new("stale");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run.lisp(&format!(r#"(progn {INSERT} (setq i (entlast)) (cdr (assoc 5 (entget i))))"#)).out();
|
||||
let handle = text(&out, 0);
|
||||
|
||||
// Erased: the reference's records are gone with it, and the name names nothing.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (cdr (assoc 2 (entget a))))"#))
|
||||
.cmd("erase", json!({ "handles": [handle] }))
|
||||
.lisp("(list (entget a) (entnext a))")
|
||||
// Undone: the reference is back, but a name given before the Undo does not come back with
|
||||
// it: a walk gives its records new ones.
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
// ATTSYNC rebuilds the reference's attributes: the name given before names nothing, and
|
||||
// the rebuilt attribute keeps the value.
|
||||
.lisp("(progn (setq b (entnext (entlast))) (cdr (assoc 2 (entget b))))")
|
||||
.cmd("attsync", json!({ "name": "TAGBLK" }))
|
||||
.lisp("(list (entget b) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "\"TAG1\"");
|
||||
assert_eq!(value(&out, 1), "(nil nil)");
|
||||
assert_eq!(value(&out, 2), "(nil \"A1\")");
|
||||
assert_eq!(value(&out, 3), "\"TAG1\"");
|
||||
assert_eq!(value(&out, 4), "(nil \"A1\")");
|
||||
|
||||
// A reinsert after an Undo takes the parent handle back: the old name must not name its
|
||||
// attribute.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 5 (entget i))) (cdr (assoc 2 (entget a)))))"#))
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.lisp(&format!(r#"(progn {INSERT} (list (cdr (assoc 5 (entget (entlast)))) (entget a)))"#))
|
||||
.lisp("(list (cdr (assoc 2 (entget (entnext (entlast))))) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), format!("(\"{handle}\" \"TAG1\")"));
|
||||
// The same handle, and the old name names nothing in the new reference.
|
||||
assert_eq!(value(&out, 1), format!("(\"{handle}\" nil)"));
|
||||
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_of_anything_but_the_value_is_refused() {
|
||||
let dir = Dir::new("refused");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn {INSERT} (setq i (entlast) a (entnext i) s (entnext (entnext (entnext a))) p0 (cdr (assoc 10 (entget a)))) "named")"#
|
||||
))
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq d (entget a))
|
||||
(list
|
||||
(entmod (subst (cons 2 "TAGX") (assoc 2 d) d))
|
||||
(entmod (subst (cons 40 9.0) (assoc 40 d) d))
|
||||
(entmod (subst (cons 0 "SEQEND") (assoc 0 d) d))
|
||||
(entmod (entget s))
|
||||
(entmod (subst (cons 410 "Layout2") (assoc 410 d) d))
|
||||
(entmod (subst (cons 1 "A2") (assoc 1 d) (subst (cons 410 "Layout2") (assoc 410 d) d)))
|
||||
(entdel a) (entdel s)))"#,
|
||||
)
|
||||
// Nothing changed: the same tag, value, height and place, and the name still holds.
|
||||
.lisp(
|
||||
r#"(progn (setq e (entnext (entlast)) d (entget e))
|
||||
(list (cdr (assoc 2 d)) (cdr (assoc 1 d)) (cdr (assoc 40 d)) (equal p0 (cdr (assoc 10 d))) (equal (entget a) d)))"#,
|
||||
)
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), "named");
|
||||
assert_eq!(value(&out, 1), "(nil nil nil nil nil nil nil nil)");
|
||||
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\" 2.5 T T)");
|
||||
}
|
||||
|
||||
/// A minimal drawing: `before` (records written as they are), then an INSERT with `attribs`
|
||||
/// ATTRIBs (each tag T, value V) and its SEQEND, last in the file. A header `$HANDSEED` is
|
||||
/// written when `handseed` is given (a hostile file can name any next handle).
|
||||
fn insert_dxf_seed(attribs: usize, before: &str, handseed: Option<&str>) -> String {
|
||||
let mut s = String::with_capacity(before.len().saturating_add(attribs.saturating_mul(96)));
|
||||
if let Some(seed) = handseed {
|
||||
s.push_str("0\nSECTION\n2\nHEADER\n9\n$HANDSEED\n5\n");
|
||||
s.push_str(seed);
|
||||
s.push('\n');
|
||||
s.push_str("0\nENDSEC\n");
|
||||
}
|
||||
s.push_str("0\nSECTION\n2\nENTITIES\n");
|
||||
s.push_str(before);
|
||||
s.push_str("0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nTAGBLK\n10\n0\n20\n0\n30\n0\n");
|
||||
for _ in 0..attribs {
|
||||
s.push_str("0\nATTRIB\n5\n21\n8\n0\n10\n0\n20\n0\n30\n0\n40\n1\n1\nV\n2\nT\n70\n0\n");
|
||||
}
|
||||
s.push_str("0\nSEQEND\n5\n22\n0\nENDSEC\n0\nEOF\n");
|
||||
s
|
||||
}
|
||||
|
||||
fn insert_dxf(attribs: usize, before: &str) -> String {
|
||||
insert_dxf_seed(attribs, before, None)
|
||||
}
|
||||
|
||||
/// The number of records a walk from `i` reaches, counting each `entnext`.
|
||||
const COUNT: &str = r#"(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"#;
|
||||
|
||||
#[test]
|
||||
fn a_walk_is_stable_and_its_names_are_no_handles() {
|
||||
let dir = Dir::new("stable");
|
||||
// A file's line one below the top of the handle range: it keeps its handle, and the
|
||||
// records' names, which are no handles, never name it.
|
||||
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n";
|
||||
let file = dir.path("hostile.dxf");
|
||||
std::fs::write(&file, insert_dxf(2, before)).expect("write the DXF");
|
||||
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq i (handent "20") line (handent "FFFFFFFFFFFFFFFE") a (entnext i) b (entnext i))
|
||||
(list (cdr (assoc 5 (entget line))) (equal (handent "FFFFFFFFFFFFFFFE") line)
|
||||
(not (equal a line)) (cdr (assoc 0 (entget a))) (equal a b) (equal (entnext a) (entnext b))))"#,
|
||||
)
|
||||
.lisp(&format!(r#"(progn (setq i (handent "20")) {COUNT})"#))
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"FFFFFFFFFFFFFFFE\" T T \"ATTRIB\" T T)");
|
||||
// Two ATTRIBs and the SEQEND, then the line (it sorts last by its handle), then the end.
|
||||
assert_eq!(value(&out, 1), "4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_reference_does_not_revive_an_old_name() {
|
||||
let dir = Dir::new("restored");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn {INSERT} (setq i (entlast) a (entnext i))
|
||||
(entdel i)
|
||||
(setq gone (entget a))
|
||||
(entdel i)
|
||||
(list gone (entget a) (cdr (assoc 1 (entget (entnext i))))))"#
|
||||
))
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(nil nil \"A1\")", "the reference comes back, the old name does not");
|
||||
|
||||
// ERASE, then OOPS: the same. The old name never comes back with the reference.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let handle = text(&run.lisp(&format!(r#"(progn {INSERT} (cdr (assoc 5 (entget (entlast)))))"#)).out(), 0);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq a (entnext (entlast))) "named")"#))
|
||||
.cmd("erase", json!({ "handles": [handle] }))
|
||||
.cmd("oops", json!({}))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(nil \"A1\")", "OOPS restores the reference, not the old name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_line_is_never_a_record() {
|
||||
let dir = Dir::new("handseed");
|
||||
let file = dir.path("hostile.dxf");
|
||||
// A file's $HANDSEED in the reserved band is the file's own handle and is not followed (#913),
|
||||
// so the line made after the walk gets the drawing's seed. The record's name is no handle:
|
||||
// the line is the line, and the name still names the attribute. The engine's
|
||||
// `a_new_object_at_any_handle_is_never_a_record` puts the seed at the top of the range.
|
||||
std::fs::write(&file, insert_dxf_seed(1, "", Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(r#"(progn (setq i (handent "20") a (entnext i)) (list (cdr (assoc 0 (entget a))) (cdr (assoc 5 (entget (entlast))))))"#)
|
||||
.lisp(r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#)
|
||||
.lisp(r#"(list (cdr (assoc 0 (entget a))) (entdel a))"#)
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"ATTRIB\" \"20\")");
|
||||
assert_eq!(value(&out, 1), "\"100\"");
|
||||
assert_eq!(value(&out, 2), "(\"ATTRIB\" nil)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_at_the_top_of_the_handle_range_walk_as_lines() {
|
||||
let dir = Dir::new("walkrange");
|
||||
let file = dir.path("hostile.dxf");
|
||||
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n\
|
||||
0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0\n20\n0\n30\n0\n11\n6\n21\n6\n31\n0\n";
|
||||
std::fs::write(&file, insert_dxf_seed(1, before, Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(r#"(progn (setq i (handent "20")) (entnext i))"#)
|
||||
// The line at the top of the range is in the drawing. Without it, the walk from the line
|
||||
// below would end in nil, and nil equals the nil `handent` gives for a handle not there.
|
||||
.lisp(r#"(progn (setq top (handent "FFFFFFFFFFFFFFFF")) (list (cdr (assoc 0 (entget top))) (cdr (assoc 5 (entget top)))))"#)
|
||||
.lisp(r#"(equal (entnext (handent "FFFFFFFFFFFFFFFE")) top)"#)
|
||||
.lisp("(entnext top)")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(\"LINE\" \"FFFFFFFFFFFFFFFF\")");
|
||||
assert_eq!(value(&out, 2), "T");
|
||||
assert_eq!(value(&out, 3), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_session_names_at_most_65536_records() {
|
||||
let dir = Dir::new("names");
|
||||
let file = dir.path("many.dxf");
|
||||
// One more attribute than the limit of names: the walk stops at the limit, and nothing in the
|
||||
// drawing changed.
|
||||
std::fs::write(&file, insert_dxf(65_537, "")).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run.lisp(&format!("(progn (setq i (entlast)) {COUNT})")).lisp(&format!("(progn (setq i (entlast)) {COUNT})")).out();
|
||||
assert_eq!(value(&out, 0), "65536");
|
||||
// The names given by the first walk hold: the second walk is the same.
|
||||
assert_eq!(value(&out, 1), "65536");
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod block_resources;
|
||||
mod cli;
|
||||
mod dash_limit_note;
|
||||
mod drafting_spacing;
|
||||
|
||||
@@ -37,3 +37,6 @@ wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
||||
wasm-bindgen-test = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Same-origin file-provider bridge. Persistence belongs to the registered provider, not WASM.
|
||||
//!
|
||||
//! Callbacks enqueue commands for a later egui frame. Exporting bytes never acknowledges them.
|
||||
|
||||
use cadcraft_ui_egui::file_providers::{Host, Resource};
|
||||
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure, prelude::wasm_bindgen};
|
||||
|
||||
thread_local! {
|
||||
static CURRENT_CONTEXT: std::cell::RefCell<Option<egui::Context>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
const API: &str = "cadcraftFileProviders";
|
||||
const EVENT: &str = "cadcraft-file-provider";
|
||||
const MAX_BYTES: u32 = 80 * 1024 * 1024;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(catch, js_namespace = Uint8Array, js_name = from)]
|
||||
fn copy_event_bytes(bytes: &[u8]) -> Result<Uint8Array, JsValue>;
|
||||
}
|
||||
|
||||
fn error(message: impl ToString) -> JsValue {
|
||||
JsValue::from_str(&message.to_string())
|
||||
}
|
||||
|
||||
fn object(value: &serde_json::Value) -> Result<JsValue, JsValue> {
|
||||
js_sys::JSON::parse(&value.to_string())
|
||||
}
|
||||
|
||||
fn set(target: &JsValue, key: &str, value: &JsValue) -> Result<(), JsValue> {
|
||||
if Reflect::set(target, &key.into(), value)? { Ok(()) } else { Err(error("file-provider API is not writable")) }
|
||||
}
|
||||
|
||||
// Inspect UTF-16 length before copying a host string into WASM memory.
|
||||
fn bounded_string(value: JsValue, max_units: u32) -> Result<String, JsValue> {
|
||||
let text = value.dyn_into::<js_sys::JsString>().map_err(|_| error("resource fields must be strings"))?;
|
||||
if text.length() > max_units {
|
||||
return Err(error("resource field is too large"));
|
||||
}
|
||||
text.as_string().ok_or_else(|| error("invalid resource field"))
|
||||
}
|
||||
|
||||
fn resource(value: JsValue) -> Result<Resource, JsValue> {
|
||||
if value.is_null() || !value.is_object() || Array::is_array(&value) {
|
||||
return Err(error("resource entries must be objects"));
|
||||
}
|
||||
let entry = value.dyn_into::<Object>()?;
|
||||
let id = bounded_string(Reflect::get(&entry, &"id".into())?, 160)?;
|
||||
let name = bounded_string(Reflect::get(&entry, &"name".into())?, 255)?;
|
||||
let updated = Reflect::get(&entry, &"updatedAt".into())?;
|
||||
let updated_at = if updated.is_undefined() { String::new() } else { bounded_string(updated, 100)? };
|
||||
Ok(Resource { id, name, updated_at })
|
||||
}
|
||||
|
||||
fn wake_later(ctx: &egui::Context) {
|
||||
let fallback = ctx.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
CURRENT_CONTEXT.with(|current| current.borrow().as_ref().unwrap_or(&fallback).request_repaint());
|
||||
});
|
||||
}
|
||||
|
||||
/// Makes the capability discoverable without enabling it or changing the browser's writer.
|
||||
pub fn install(host: Host, ctx: egui::Context) -> Result<(), JsValue> {
|
||||
let window = web_sys::window().ok_or_else(|| error("no window"))?;
|
||||
CURRENT_CONTEXT.with(|current| *current.borrow_mut() = Some(ctx.clone()));
|
||||
if Reflect::has(&window, &API.into())? {
|
||||
// A graphics restart keeps the page capability and pending requests, and renews its wake target.
|
||||
return Ok(());
|
||||
}
|
||||
// A delayed result from an earlier page must never address a new document's request.
|
||||
let crypto = Reflect::get(&window, &"crypto".into())?;
|
||||
let random = Reflect::get(&crypto, &"getRandomValues".into())?.dyn_into::<Function>()?;
|
||||
let nonce = Uint8Array::new_with_length(16);
|
||||
random.call1(&crypto, &nonce)?;
|
||||
host.set_session(nonce.to_vec().iter().map(|byte| format!("{byte:02x}")).collect()).map_err(error)?;
|
||||
|
||||
let api = Object::new();
|
||||
set(&api, "protocolVersion", &1.into())?;
|
||||
set(&api, "app", &"cadcraft".into())?;
|
||||
set(&api, "capabilities", &object(&serde_json::json!(["revisionAck", "externalRecents", "saveDestination", "openBytes"]))?)?;
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let register = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<String, JsValue>>::new(move |id, label, namespace| {
|
||||
let id = bounded_string(id, 160)?;
|
||||
let label = bounded_string(label, 100)?;
|
||||
let namespace = bounded_string(namespace, 160)?;
|
||||
let connection = h.connect(id, label, namespace).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(connection)
|
||||
});
|
||||
set(&api, "registerProvider", register.as_ref())?;
|
||||
register.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let unregister = Closure::<dyn FnMut() -> Result<bool, JsValue>>::new(move || {
|
||||
h.disconnect().map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(true)
|
||||
});
|
||||
set(&api, "unregisterProvider", unregister.as_ref())?;
|
||||
unregister.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let enabled = Closure::<dyn FnMut(JsValue) -> Result<bool, JsValue>>::new(move |value: JsValue| {
|
||||
let value = value.as_bool().ok_or_else(|| error("enabled must be a boolean"))?;
|
||||
h.set_enabled(value).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(true)
|
||||
});
|
||||
set(&api, "setEnabled", enabled.as_ref())?;
|
||||
enabled.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let resources = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |connection, value: JsValue| {
|
||||
let connection = bounded_string(connection, 160)?;
|
||||
if !Array::is_array(&value) {
|
||||
return Err(error("resources must be an array of at most 100 entries"));
|
||||
}
|
||||
let entries = value.dyn_into::<Array>()?;
|
||||
if entries.length() > 100 {
|
||||
return Err(error("resources must be an array of at most 100 entries"));
|
||||
}
|
||||
// Read only bounded metadata; do not copy or serialize arbitrary host properties.
|
||||
let resources = entries.iter().map(resource).collect::<Result<Vec<_>, _>>()?;
|
||||
h.set_resources(&connection, resources).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "setResources", resources.as_ref())?;
|
||||
resources.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let request_open = Closure::<dyn FnMut(JsValue) -> Result<String, JsValue>>::new(move |resource| {
|
||||
let resource = bounded_string(resource, 160)?;
|
||||
let request = h.request_open(&resource).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(request)
|
||||
});
|
||||
set(&api, "requestOpen", request_open.as_ref())?;
|
||||
request_open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let open = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, name, value: JsValue| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let name = bounded_string(name, 255)?;
|
||||
let bytes = value.dyn_into::<Uint8Array>().map_err(|_| error("bytes must be a Uint8Array"))?;
|
||||
if bytes.length() > MAX_BYTES {
|
||||
return Err(error("file exceeds the provider limit"));
|
||||
}
|
||||
h.open(request, name, bytes.to_vec()).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "openResource", open.as_ref())?;
|
||||
open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let cancel_open = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, message| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let message = bounded_string(message, 1024)?;
|
||||
h.cancel_open(request, message).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "cancelOpen", cancel_open.as_ref())?;
|
||||
cancel_open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let result = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, status, resource| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let status = bounded_string(status, 8)?;
|
||||
let resource = bounded_string(resource, 160)?;
|
||||
h.result(request, status, resource).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "saveResult", result.as_ref())?;
|
||||
result.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let dialog = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, destination, name| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let destination = bounded_string(destination, 8)?;
|
||||
let name = bounded_string(name, 255)?;
|
||||
h.resolve_dialog(&request, &destination, &name).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "resolveSaveDialog", dialog.as_ref())?;
|
||||
dialog.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let snapshot = Closure::<dyn FnMut() -> Result<JsValue, JsValue>>::new(move || object(&h.snapshot()));
|
||||
set(&api, "snapshot", snapshot.as_ref())?;
|
||||
snapshot.forget();
|
||||
set(&window, API, &Object::freeze(&api))?;
|
||||
dispatch(&serde_json::json!({"type": "ready", "protocolVersion": 1}), None)
|
||||
}
|
||||
|
||||
fn dispatch(metadata: &serde_json::Value, bytes: Option<Vec<u8>>) -> Result<(), JsValue> {
|
||||
let detail = object(metadata)?;
|
||||
if let Some(bytes) = bytes {
|
||||
set(&detail, "bytes", ©_event_bytes(&bytes)?.into())?;
|
||||
}
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_detail(&detail);
|
||||
let event = web_sys::CustomEvent::new_with_event_init_dict(EVENT, &init)?;
|
||||
web_sys::window().ok_or_else(|| error("no window"))?.dispatch_event(&event)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn publish(host: &Host) {
|
||||
if host.publish_events_with(dispatch, |error| log::error!("file-provider event delivery failed: {error:?}")) {
|
||||
CURRENT_CONTEXT.with(|current| {
|
||||
if let Some(ctx) = current.borrow().as_ref() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod browser_tests;
|
||||
@@ -0,0 +1,271 @@
|
||||
//! Original, self-contained DXF fixture. Rust closures create genuine JS exceptions; no JS source.
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::{Session, cmd::file};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
fn error(message: impl ToString) -> JsValue {
|
||||
JsValue::from_str(&message.to_string())
|
||||
}
|
||||
fn field(object: &JsValue, name: &str) -> Result<JsValue, JsValue> {
|
||||
Reflect::get(object, &name.into())
|
||||
}
|
||||
fn text(object: &JsValue, name: &str) -> Result<String, JsValue> {
|
||||
field(object, name)?.as_string().ok_or_else(|| error(format!("missing string field {name}")))
|
||||
}
|
||||
fn call(object: &JsValue, name: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
let function = field(object, name)?.dyn_into::<Function>()?;
|
||||
let array = Array::new();
|
||||
for argument in arguments {
|
||||
array.push(argument);
|
||||
}
|
||||
function.apply(object, &array)
|
||||
}
|
||||
|
||||
struct Page {
|
||||
window: web_sys::Window,
|
||||
api: JsValue,
|
||||
host: cadcraft_ui_egui::file_providers::Host,
|
||||
ctx: egui::Context,
|
||||
events: Rc<RefCell<Vec<JsValue>>>,
|
||||
listener: Closure<dyn FnMut(web_sys::Event)>,
|
||||
}
|
||||
impl Page {
|
||||
fn install(app: &CadApp) -> Result<Self, JsValue> {
|
||||
let window = web_sys::window().ok_or_else(|| error("no browser window"))?;
|
||||
if Reflect::has(&window, &super::API.into())? {
|
||||
return Err(error("fixture requires a fresh owned page"));
|
||||
}
|
||||
let host = app.file_providers.clone();
|
||||
let ctx = egui::Context::default();
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = events.clone();
|
||||
let listener = Closure::<dyn FnMut(web_sys::Event)>::new(move |event: web_sys::Event| {
|
||||
if let Ok(event) = event.dyn_into::<web_sys::CustomEvent>() {
|
||||
seen.borrow_mut().push(event.detail());
|
||||
}
|
||||
});
|
||||
window.add_event_listener_with_callback(super::EVENT, listener.as_ref().unchecked_ref())?;
|
||||
let mut page = Self { window, api: JsValue::UNDEFINED, host, ctx, events, listener };
|
||||
super::install(page.host.clone(), page.ctx.clone())?;
|
||||
page.api = field(&page.window, super::API)?;
|
||||
Ok(page)
|
||||
}
|
||||
fn api(&self, method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
call(&self.api, method, arguments)
|
||||
}
|
||||
fn latest(&self, kind: &str) -> Result<JsValue, JsValue> {
|
||||
self.events
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|event| text(event, "type").is_ok_and(|name| name == kind))
|
||||
.cloned()
|
||||
.ok_or_else(|| error(format!("missing real window event {kind}")))
|
||||
}
|
||||
fn tick(&self, app: &mut CadApp) {
|
||||
self.ctx.run_ui(Default::default(), |ui| app.logic(ui.ctx())).drop_without_applying_deltas();
|
||||
}
|
||||
fn choose(&self, app: &mut CadApp) -> Result<String, JsValue> {
|
||||
let value = app.run("qsave", serde_json::Value::Null).map_err(error)?;
|
||||
value
|
||||
.get("requestId")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| error("qsave did not create a real provider choice"))
|
||||
}
|
||||
fn captured_save(&self, app: &mut CadApp) -> Result<String, JsValue> {
|
||||
let request = self.choose(app)?;
|
||||
super::publish(&self.host);
|
||||
assert_eq!(text(&self.latest("saveDialog")?, "requestId")?, request);
|
||||
self.api("resolveSaveDialog", &[request.clone().into(), "provider".into(), "Fixture.dxf".into()])?;
|
||||
Ok(request)
|
||||
}
|
||||
// Both the injected callback and production publisher are entered through catch-enabled
|
||||
// Function::call0. Restore the exact own descriptor (or remove our inherited-method shadow)
|
||||
// BEFORE assertions, even when an uncaught production exception returns Err from call0.
|
||||
fn with_replacement(&self, target: &JsValue, key: &str, replacement: &JsValue) -> Result<Result<JsValue, JsValue>, JsValue> {
|
||||
let object = field(&js_sys::global(), "Object")?;
|
||||
let descriptor = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
|
||||
let original = field(target, key)?;
|
||||
let host = self.host.clone();
|
||||
let operation = Closure::<dyn FnMut()>::new(move || super::publish(&host));
|
||||
let outcome = match Reflect::set(target, &key.into(), replacement) {
|
||||
Ok(true) => operation.as_ref().unchecked_ref::<Function>().call0(&JsValue::UNDEFINED),
|
||||
Ok(false) => Err(error("injected method is not writable")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
if descriptor.is_undefined() {
|
||||
if !Reflect::delete_property(target.unchecked_ref::<Object>(), &key.into())? {
|
||||
return Err(error("could not remove injected method"));
|
||||
}
|
||||
} else {
|
||||
call(&object, "defineProperty", &[target.clone(), key.into(), descriptor.clone()])?;
|
||||
}
|
||||
let restored = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
|
||||
if field(target, key)? != original || restored.is_undefined() != descriptor.is_undefined() {
|
||||
return Err(error("injected property was not restored exactly"));
|
||||
}
|
||||
if !descriptor.is_undefined() {
|
||||
for attribute in ["value", "get", "set", "writable", "enumerable", "configurable"] {
|
||||
if field(&restored, attribute)? != field(&descriptor, attribute)? {
|
||||
return Err(error("injected property descriptor changed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
fn fail_copy(&self) -> Result<u32, JsValue> {
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let seen = calls.clone();
|
||||
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |_| {
|
||||
seen.set(seen.get() + 1);
|
||||
Err(js_sys::RangeError::new("synthetic CAD byte-copy failure").into())
|
||||
});
|
||||
let array = field(&js_sys::global(), "Uint8Array")?;
|
||||
self.with_replacement(&array, "from", fault.as_ref())??;
|
||||
Ok(calls.get())
|
||||
}
|
||||
fn fail_dispatch(&self, kind: &str) -> Result<u32, JsValue> {
|
||||
let original = field(&self.window, "dispatchEvent")?.dyn_into::<Function>()?;
|
||||
let window: JsValue = self.window.clone().into();
|
||||
let wanted = kind.to_string();
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let seen = calls.clone();
|
||||
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |event: JsValue| {
|
||||
if text(&field(&event, "detail")?, "type")? == wanted {
|
||||
seen.set(seen.get() + 1);
|
||||
Err(js_sys::RangeError::new("synthetic CAD metadata dispatch failure").into())
|
||||
} else {
|
||||
original.call1(&window, &event)
|
||||
}
|
||||
});
|
||||
self.with_replacement(&self.window, "dispatchEvent", fault.as_ref())??;
|
||||
Ok(calls.get())
|
||||
}
|
||||
}
|
||||
impl Drop for Page {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.window.remove_event_listener_with_callback(super::EVENT, self.listener.as_ref().unchecked_ref());
|
||||
let _ = Reflect::delete_property(self.window.unchecked_ref::<Object>(), &super::API.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn real_window_delivery_recovery_preserves_dxf_and_consumes_actual_cad_actions() -> Result<(), JsValue> {
|
||||
// Production codec hooks, on this fixture's fresh browser page only. Native app fixtures
|
||||
// use cadcraft_io directly and never replace their process-global test hooks.
|
||||
file::set_io(file::IoHooks {
|
||||
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|error| error.to_string()),
|
||||
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|error| error.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
file::set_write_as(|drawing, name, options| {
|
||||
cadcraft_io::write_with(drawing, name, &cadcraft_io::SaveOptions { version: options.version, binary: options.binary })
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
let mut app = CadApp::new(Session::new(), Services { no_file_system: true, ..Default::default() });
|
||||
app.run("line", json!({"points":[[0,0],[10,10]]})).map_err(error)?;
|
||||
let page = Page::install(&app)?;
|
||||
let connection = page.api("registerProvider", &["fixture".into(), "Fixture storage".into(), "account-one".into()])?;
|
||||
let resources = Array::new();
|
||||
for id in ["file-1", "file-2"] {
|
||||
let resource = Object::new();
|
||||
Reflect::set(&resource, &"id".into(), &id.into())?;
|
||||
Reflect::set(&resource, &"name".into(), &"Fixture.dxf".into())?;
|
||||
Reflect::set(&resource, &"updatedAt".into(), &"".into())?;
|
||||
resources.push(&resource);
|
||||
}
|
||||
page.api("setResources", &[connection.clone(), resources.into()])?;
|
||||
let uid = app.session.state().map_err(error)?.uid;
|
||||
let checkpoint = app.session.state().map_err(error)?.saved.clone();
|
||||
let chooser = page.choose(&mut app)?;
|
||||
assert_eq!(page.fail_dispatch("saveDialog")?, 1);
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, chooser);
|
||||
assert!(page.api("resolveSaveDialog", &[chooser.into(), "provider".into(), "Late.dxf".into()]).is_err());
|
||||
assert!(!page.host.busy());
|
||||
assert!(Arc::ptr_eq(&app.session.state().map_err(error)?.saved, &checkpoint));
|
||||
|
||||
let read = page.api("requestOpen", &["file-2".into()])?;
|
||||
assert_eq!(page.fail_dispatch("openRequested")?, 1);
|
||||
let failed_read = page.latest("openFailed")?;
|
||||
assert_eq!(field(&failed_read, "requestId")?, read);
|
||||
assert_eq!(text(&failed_read, "resourceId")?, "file-2");
|
||||
assert_eq!(field(&failed_read, "connectionId")?, connection);
|
||||
assert!(!page.host.busy());
|
||||
|
||||
let failed = page.captured_save(&mut app)?;
|
||||
let later_read = page.api("requestOpen", &["file-2".into()])?;
|
||||
app.set_status("Awaiting the synthetic byte-copy failure");
|
||||
assert_eq!(page.fail_copy()?, 1, "actual catch-enabled production copy must throw exactly once");
|
||||
assert!(!page.events.borrow().iter().any(|event| text(event, "type").is_ok_and(|kind| kind == "save")));
|
||||
assert_eq!(field(&page.latest("openRequested")?, "requestId")?, later_read);
|
||||
assert!(page.api("saveResult", &[failed.clone().into(), "saved".into(), "file-1".into()]).is_err());
|
||||
page.api("cancelOpen", &[later_read, "".into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, failed);
|
||||
let state = app.session.state().map_err(error)?;
|
||||
assert_eq!(state.uid, uid);
|
||||
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &checkpoint));
|
||||
assert!(!page.host.busy() && page.host.bound_document("file-1").is_none());
|
||||
assert!(app.status.as_ref().is_some_and(|(message, _)| message.contains("File provider save failed")));
|
||||
|
||||
let retry = page.captured_save(&mut app)?;
|
||||
assert_ne!(retry, failed);
|
||||
super::publish(&page.host);
|
||||
let saved = page.latest("save")?;
|
||||
assert_eq!(text(&saved, "requestId")?, retry);
|
||||
assert_eq!(text(&saved, "filename")?, "Fixture.dxf");
|
||||
assert_eq!(text(&saved, "documentId")?, uid.to_string());
|
||||
assert_eq!(field(&saved, "connectionId")?, connection);
|
||||
let bytes = field(&saved, "bytes")?.dyn_into::<Uint8Array>()?;
|
||||
assert!(bytes.length() > 0);
|
||||
let drawing = cadcraft_io::read(&bytes.to_vec(), "Fixture.dxf").map_err(error)?;
|
||||
assert_eq!(drawing.model.len(), app.session.state().map_err(error)?.doc.model.len());
|
||||
assert!(!drawing.model.is_empty());
|
||||
assert!(page.host.pending_for(uid) && app.session.state().map_err(error)?.is_dirty());
|
||||
let captured = app.session.state().map_err(error)?.doc.clone();
|
||||
let captured_revision = app.session.state().map_err(error)?.revision;
|
||||
app.run("line", json!({"points":[[20,20],[30,30]]})).map_err(error)?;
|
||||
page.api("saveResult", &[retry.clone().into(), "saved".into(), "file-1".into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
let terminal = page.latest("saved")?;
|
||||
assert_eq!(text(&terminal, "requestId")?, retry);
|
||||
assert_eq!(text(&terminal, "resourceId")?, "file-1");
|
||||
assert_eq!(text(&terminal, "revision")?, captured_revision.to_string());
|
||||
let state = app.session.state().map_err(error)?;
|
||||
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &captured), "ACK owns its snapshot, never later edits");
|
||||
assert_eq!(page.host.bound_document("file-1"), Some(uid));
|
||||
assert!(!page.host.busy());
|
||||
|
||||
let open = page.api("requestOpen", &["file-2".into()])?;
|
||||
super::publish(&page.host);
|
||||
page.api("openResource", &[open.clone(), "Fixture.dxf".into(), bytes.into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
let opened = page.latest("opened")?;
|
||||
assert_eq!(field(&opened, "requestId")?, open);
|
||||
assert_eq!(text(&opened, "resourceId")?, "file-2");
|
||||
assert_eq!(field(&opened, "connectionId")?, connection);
|
||||
assert_eq!(text(&opened, "namespace")?, "account-one");
|
||||
let imported = app.session.state().map_err(error)?;
|
||||
assert_ne!(imported.uid, uid);
|
||||
assert_eq!(imported.doc.model.len(), drawing.model.len());
|
||||
let original = app.session.docs.iter().find(|doc| doc.uid == uid).ok_or_else(|| error("original drawing was lost on provider open"))?;
|
||||
assert!(original.is_dirty() && Arc::ptr_eq(&original.saved, &captured));
|
||||
assert!(!page.host.busy());
|
||||
page.api("unregisterProvider", &[])?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,6 +15,8 @@ mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod download;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod file_providers;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
@@ -47,6 +49,7 @@ mod web {
|
||||
self.1.drain(&mut self.0);
|
||||
self.0.system_animations = self.3.as_ref().map(|reduced| !reduced.matches());
|
||||
self.0.logic(ctx);
|
||||
crate::file_providers::publish(&self.0.file_providers);
|
||||
let drawing = self.0.session.state().ok();
|
||||
crate::push_title(&mut self.4, drawing.map(|d| d.title.as_str()), drawing.is_some_and(|d| d.is_dirty()), set_page_title);
|
||||
// The crate suppresses duplicates, so reporting after every logic callback
|
||||
@@ -82,6 +85,7 @@ mod web {
|
||||
self.1.take_dropped(ui.ctx());
|
||||
}
|
||||
self.0.ui(ui);
|
||||
crate::file_providers::publish(&self.0.file_providers);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +140,8 @@ mod web {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
@@ -179,6 +185,13 @@ mod web {
|
||||
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
|
||||
let control = crate::api::install(cc.egui_ctx.clone());
|
||||
let mut app = CadApp::new(session, services()).with_control(control);
|
||||
// The provider capability is independent of the parent and same-document host modes.
|
||||
// Avoid two hosts competing for the same Save command.
|
||||
if app_bridge.is_none() {
|
||||
if let Err(error) = crate::file_providers::install(app.file_providers.clone(), cc.egui_ctx.clone()) {
|
||||
log::error!("file provider capability could not be installed: {error:?}");
|
||||
}
|
||||
}
|
||||
app.system_languages =
|
||||
web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default();
|
||||
if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) {
|
||||
|
||||
@@ -199,6 +199,8 @@ pub fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
|
||||
@@ -154,7 +154,43 @@ impl AttribProps {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TagKey<'a>(pub &'a str);
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static TAG_CROSS_PROBE: std::cell::Cell<Option<(usize, [usize; 2])>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn record_tag_cross_probe(left: &str, right: &str) {
|
||||
TAG_CROSS_PROBE.with(|probe| {
|
||||
let Some((position, mut counts)) = probe.get() else { return };
|
||||
match (left.as_bytes().get(position), right.as_bytes().get(position)) {
|
||||
(Some(b'A'), Some(b'D')) => counts[0] += 1,
|
||||
(Some(b'D'), Some(b'A')) => counts[1] += 1,
|
||||
_ => return,
|
||||
}
|
||||
probe.set(Some((position, counts)));
|
||||
});
|
||||
}
|
||||
|
||||
impl TagKey<'_> {
|
||||
/// Count comparisons in both directions between the A and D fixture tag sets.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_cross_probes<T>(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) {
|
||||
struct Restore(Option<(usize, [usize; 2])>);
|
||||
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
TAG_CROSS_PROBE.with(|probe| probe.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
TAG_CROSS_PROBE.with(|probe| {
|
||||
let _restore = Restore(probe.replace(Some((position, [0; 2]))));
|
||||
let value = f();
|
||||
(value, probe.get().map_or([0; 2], |(_, counts)| counts))
|
||||
})
|
||||
}
|
||||
|
||||
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
|
||||
/// finds equal.
|
||||
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
|
||||
@@ -164,6 +200,8 @@ impl TagKey<'_> {
|
||||
|
||||
impl PartialEq for TagKey<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
record_tag_cross_probe(self.0, other.0);
|
||||
self.0.eq_ignore_ascii_case(other.0)
|
||||
}
|
||||
}
|
||||
@@ -172,6 +210,8 @@ impl Eq for TagKey<'_> {}
|
||||
|
||||
impl Ord for TagKey<'_> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
#[cfg(test)]
|
||||
record_tag_cross_probe(self.0, other.0);
|
||||
self.folded().cmp(other.folded())
|
||||
}
|
||||
}
|
||||
|
||||
+74
-1
@@ -6,12 +6,19 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::{Entity, Handle};
|
||||
|
||||
const CHUNK_MAX: usize = 1024;
|
||||
const SHARDS: usize = 64;
|
||||
|
||||
/// A content token no store has had: one count for the process (a `u64` does not run out).
|
||||
fn next_token() -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Chunk {
|
||||
id: u32,
|
||||
@@ -24,11 +31,19 @@ pub struct EntityStore {
|
||||
shards: Vec<Arc<HashMap<Handle, u32>>>,
|
||||
len: usize,
|
||||
next_chunk: u32,
|
||||
/// This state of the entities ([`EntityStore::content_token`]). Not part of [`PartialEq`].
|
||||
token: u64,
|
||||
}
|
||||
|
||||
impl Default for EntityStore {
|
||||
fn default() -> Self {
|
||||
EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 }
|
||||
EntityStore {
|
||||
chunks: Vec::new(),
|
||||
shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(),
|
||||
len: 0,
|
||||
next_chunk: 0,
|
||||
token: next_token(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +62,17 @@ impl EntityStore {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
/// A number for this state of the entities: a clone has it too, and every edit gives the
|
||||
/// store a number no store has had, so two stores with one token hold the same entities in
|
||||
/// the same order. What is derived from the entities (a block's ATTDEFs by tag) can be kept
|
||||
/// under it. Not part of [`PartialEq`]: equal stores can have different tokens.
|
||||
pub fn content_token(&self) -> u64 {
|
||||
self.token
|
||||
}
|
||||
/// The entities are about to change: a new token.
|
||||
fn edited(&mut self) {
|
||||
self.token = next_token();
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
@@ -101,6 +127,7 @@ impl EntityStore {
|
||||
self.replace(e);
|
||||
return;
|
||||
}
|
||||
self.edited();
|
||||
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
|
||||
if needs_new {
|
||||
let c = self.new_chunk();
|
||||
@@ -120,6 +147,7 @@ impl EntityStore {
|
||||
self.replace(e);
|
||||
return;
|
||||
}
|
||||
self.edited();
|
||||
let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX);
|
||||
if needs_new {
|
||||
let c = self.new_chunk();
|
||||
@@ -137,6 +165,7 @@ impl EntityStore {
|
||||
pub fn replace(&mut self, e: Entity) -> bool {
|
||||
let Some(id) = self.chunk_id(e.handle) else { return false };
|
||||
let Some(pos) = self.chunk_pos(id) else { return false };
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else { return false };
|
||||
let chunk = Arc::make_mut(c);
|
||||
if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) {
|
||||
@@ -149,6 +178,7 @@ impl EntityStore {
|
||||
pub fn remove(&mut self, h: Handle) -> Option<Arc<Entity>> {
|
||||
let id = self.chunk_id(h)?;
|
||||
let pos = self.chunk_pos(id)?;
|
||||
self.edited();
|
||||
let c = self.chunks.get_mut(pos)?;
|
||||
let chunk = Arc::make_mut(c);
|
||||
let i = chunk.items.iter().position(|x| x.handle == h)?;
|
||||
@@ -165,6 +195,7 @@ impl EntityStore {
|
||||
pub fn modify<F: FnOnce(&mut Entity)>(&mut self, h: Handle, f: F) -> bool {
|
||||
let Some(id) = self.chunk_id(h) else { return false };
|
||||
let Some(pos) = self.chunk_pos(id) else { return false };
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else { return false };
|
||||
let chunk = Arc::make_mut(c);
|
||||
match chunk.items.iter_mut().find(|x| x.handle == h) {
|
||||
@@ -219,6 +250,7 @@ impl EntityStore {
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
return false;
|
||||
};
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else {
|
||||
// Unreachable in practice too; never lose the object.
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
@@ -297,6 +329,47 @@ mod tests {
|
||||
Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 }))
|
||||
}
|
||||
|
||||
/// One token per state of the entities: shared by clones, new after every kind of edit, and
|
||||
/// different for copies edited apart (#1660's ATTDEF index is kept by it).
|
||||
#[test]
|
||||
fn a_content_token_names_one_state_of_the_entities() {
|
||||
let mut a = EntityStore::new();
|
||||
for h in 1..=3 {
|
||||
a.push(ent(h));
|
||||
}
|
||||
assert_eq!(a.clone().content_token(), a.content_token(), "a clone holds the same entities");
|
||||
let (mut b, mut c) = (a.clone(), a.clone());
|
||||
assert!(b.modify(Handle(1), |e| e.common.layer = "B".into()));
|
||||
assert!(c.modify(Handle(1), |e| e.common.layer = "C".into()));
|
||||
assert_ne!(b.content_token(), c.content_token(), "copies edited apart");
|
||||
assert_ne!(b.content_token(), a.content_token());
|
||||
let edits: [fn(&mut EntityStore); 8] = [
|
||||
|s| s.push(ent(9)),
|
||||
|s| s.push_front(ent(8)),
|
||||
|s| {
|
||||
s.replace(ent(2));
|
||||
},
|
||||
|s| {
|
||||
s.remove(Handle(3));
|
||||
},
|
||||
|s| {
|
||||
s.bring_to_front(Handle(1));
|
||||
},
|
||||
|s| {
|
||||
s.send_to_back(Handle(2));
|
||||
},
|
||||
|s| {
|
||||
s.move_next_to(Handle(1), Handle(2), true);
|
||||
},
|
||||
|s| s.sort_by_key(|e| std::cmp::Reverse(e.handle.0)),
|
||||
];
|
||||
for (i, edit) in edits.iter().enumerate() {
|
||||
let mut s = a.clone();
|
||||
edit(&mut s);
|
||||
assert_ne!(s.content_token(), a.content_token(), "edit {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_get_remove() {
|
||||
let mut s = EntityStore::new();
|
||||
|
||||
@@ -1076,9 +1076,13 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
assert!(!d.extents(&Space::Model).is_empty());
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model));
|
||||
assert!(!bounds.is_empty());
|
||||
// Layer inheritance and the constant-value filter each query the opposite set.
|
||||
// With no matches, an unindexed scan bypasses the probe (zero) or compares every pair.
|
||||
for probes in cross_probes {
|
||||
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
|
||||
|
||||
@@ -280,6 +280,9 @@ impl DocState {
|
||||
self.view_history.clear();
|
||||
self.block_edit = Some(be);
|
||||
self.revision += 1;
|
||||
// The editor's drawing is another drawing with the host's handles: a name given in the
|
||||
// host must not resolve in it (BCLOSE ends the editor's names the same way, #1660).
|
||||
self.expire_names();
|
||||
}
|
||||
|
||||
/// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name`
|
||||
@@ -346,6 +349,9 @@ impl DocState {
|
||||
self.views = host.views;
|
||||
self.view_history = host.view_history;
|
||||
self.revision += 1;
|
||||
// The editor's drawing shares the host's handles: a name given in it must never resolve
|
||||
// to a host record (or the other way round) after the drawing comes back.
|
||||
self.expire_names();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,8 +117,10 @@ fn run_recover(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.state_mut()?;
|
||||
let report = crate::audit::fix(Arc::make_mut(&mut st.doc));
|
||||
if report.issues.is_empty() {
|
||||
// Nothing to fix: the drawing opens unchanged, like OPEN.
|
||||
st.doc = st.saved.clone();
|
||||
// Nothing to fix: the drawing opens unchanged, like OPEN. `fix` may already
|
||||
// have copied it, so put the saved one back; no record name exists yet.
|
||||
let saved = st.saved.clone();
|
||||
st.restore_drawing(saved);
|
||||
}
|
||||
if copy && !st.is_dirty() {
|
||||
// An unsaved copy (Drawing Recovery): closing it asks to save it under a name.
|
||||
|
||||
@@ -104,12 +104,17 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib>
|
||||
let m = ins.transform(blk.base.xy());
|
||||
// The reference's attributes by tag, gathered once for all the definitions (#1923).
|
||||
let carried = ins.attribs_by_tag();
|
||||
#[cfg(test)]
|
||||
let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::<std::collections::BTreeMap<_, _>>();
|
||||
defs.iter()
|
||||
.map(|ad| {
|
||||
let mut k = EntityKind::Text(ad.text.clone());
|
||||
k.transform(&m);
|
||||
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
|
||||
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
let key = TagKey(&ad.tag);
|
||||
#[cfg(test)]
|
||||
let key = tests::MeasuredTag(key);
|
||||
t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
Attrib {
|
||||
tag: ad.tag.clone(),
|
||||
text: t,
|
||||
@@ -204,6 +209,8 @@ pub(super) fn sync(s: &mut Session, name: &str) -> Result<(String, usize)> {
|
||||
let defs = attdefs(&blk);
|
||||
let d = s.doc_mut()?;
|
||||
let n = update_references(d, &blk.name, |ins| ins.attribs = synced(&blk, &defs, ins));
|
||||
// The references have new ATTRIBs: names given to the old ones hold no longer (#1660).
|
||||
s.state_mut()?.expire_names();
|
||||
Ok((blk.name.clone(), n))
|
||||
}
|
||||
|
||||
@@ -359,6 +366,74 @@ impl Interactive for AttsyncM {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
std::thread_local! {
|
||||
static SYNC_CROSS_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Use the actual tag ordering and count only probes between different fixture sets.
|
||||
pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>);
|
||||
|
||||
impl MeasuredTag<'_> {
|
||||
fn record(&self, other: &Self) {
|
||||
let TagKey(left) = self.0;
|
||||
let TagKey(right) = other.0;
|
||||
let sides = (left.as_bytes().first(), right.as_bytes().first());
|
||||
if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) {
|
||||
SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for MeasuredTag<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.record(other);
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for MeasuredTag<'_> {}
|
||||
|
||||
impl PartialOrd for MeasuredTag<'_> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for MeasuredTag<'_> {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.record(other);
|
||||
self.0.cmp(&other.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_uses_indexed_cross_set_tag_matching() {
|
||||
const N: usize = 512;
|
||||
let mut s = Session::new();
|
||||
s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap();
|
||||
s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap();
|
||||
let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
|
||||
s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap();
|
||||
let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap();
|
||||
let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let blk = doc.block("B").unwrap();
|
||||
let base = (*attdefs(blk)[0]).clone();
|
||||
let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") };
|
||||
let value = ins.attribs[0].clone();
|
||||
let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect();
|
||||
let defs: Vec<_> = defs.iter().collect();
|
||||
ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect();
|
||||
|
||||
SYNC_CROSS_PROBES.with(|count| count.set(Some(0)));
|
||||
let result = synced(blk, &defs, &ins);
|
||||
let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap());
|
||||
assert_eq!(result.len(), N);
|
||||
assert!(result.iter().all(|a| a.text.value == "d"));
|
||||
// No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N.
|
||||
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attdisp_keywords_map_to_attmode() {
|
||||
assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]);
|
||||
|
||||
@@ -81,6 +81,8 @@ fn replace(s: &mut Session, old: &str, new: &str, purge: bool) -> Result<(usize,
|
||||
});
|
||||
let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&old)).cloned();
|
||||
let purged = purge && !referenced(d, &old) && key.is_some_and(|k| d.blocks.remove(&k).is_some());
|
||||
// Replaced references have new ATTRIBs: names given to the old ones hold no longer (#1660).
|
||||
s.state_mut()?.expire_names();
|
||||
Ok((n, purged))
|
||||
}
|
||||
|
||||
|
||||
@@ -1073,7 +1073,7 @@ pub(crate) fn after_command(s: &mut Session, before: &Arc<Drawing>, id: &str) ->
|
||||
.iter()
|
||||
.any(|store| store.iter().any(|e| !owned.contains(&e.handle) && !st.doc.entity(e.handle).is_some_and(|a| Arc::ptr_eq(a, e))));
|
||||
if touched {
|
||||
st.doc = before.clone();
|
||||
st.restore_drawing(before.clone());
|
||||
return Some("Only the working set can be edited during REFEDIT (REFSET adds objects, REFCLOSE ends the edit).".into());
|
||||
}
|
||||
let seed = before.handseed;
|
||||
|
||||
@@ -108,6 +108,47 @@ pub fn entity_codec() -> Option<&'static EntityCodec> {
|
||||
CODEC.get()
|
||||
}
|
||||
|
||||
/// One record written after an entity's own, at `index` (an INSERT's ATTRIB, then its SEQEND):
|
||||
/// its type name and the groups of its record, without its `0` group. AutoLISP's `entnext` and
|
||||
/// `entget` reach an INSERT's attributes through it, one record at a time (the attributes have no
|
||||
/// handle of their own in the drawing). Installed by the app with the DXF writer, a lower layer;
|
||||
/// optional, so a host without one simply has no such records ([`EntityCodec`] is unchanged).
|
||||
pub type EntitySubRecord = fn(&Drawing, &cadcraft_doc::Entity, usize) -> Option<(String, Vec<craft_dxf::Tag>)>;
|
||||
|
||||
static SUB_RECORD: OnceLock<EntitySubRecord> = OnceLock::new();
|
||||
|
||||
// This thread hid the optional provider ([`without_entity_sub_record`], tests only).
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static SUB_RECORD_HIDDEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
pub fn set_entity_sub_record(f: EntitySubRecord) {
|
||||
let _ = SUB_RECORD.set(f);
|
||||
}
|
||||
pub fn entity_sub_record() -> Option<EntitySubRecord> {
|
||||
#[cfg(test)]
|
||||
if SUB_RECORD_HIDDEN.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
SUB_RECORD.get().copied()
|
||||
}
|
||||
|
||||
/// Run `f` as a host that did not install [`EntitySubRecord`]: `entnext` must walk the drawing's
|
||||
/// entities as it did before the provider existed. Tests only.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn without_entity_sub_record<R>(f: impl FnOnce() -> R) -> R {
|
||||
struct Unhide;
|
||||
impl Drop for Unhide {
|
||||
fn drop(&mut self) {
|
||||
SUB_RECORD_HIDDEN.with(|h| h.set(false));
|
||||
}
|
||||
}
|
||||
SUB_RECORD_HIDDEN.with(|h| h.set(true));
|
||||
let _unhide = Unhide;
|
||||
f()
|
||||
}
|
||||
|
||||
/// The drawing's non-graphic records as written (tables, BLOCK records, objects): each one's
|
||||
/// type, groups after the type and role (see [`cadcraft_doc::foreign::ForeignKey`]). AutoLISP's
|
||||
/// `namedobjdict`, `tblobjname` and `handent` of non-graphic objects read them (installed by the
|
||||
|
||||
@@ -276,9 +276,10 @@ impl GripEdit {
|
||||
}
|
||||
"Undo" => match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
@@ -574,8 +574,9 @@ fn run_boundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for q in pts {
|
||||
out.extend(boundary_at(s, q)?.into_iter().map(|h| h.hex()));
|
||||
if out.len() > MAX_BOUNDARY_OUTPUT {
|
||||
// The refused call leaves no partial result behind.
|
||||
s.state_mut()?.doc = before;
|
||||
// The refused call leaves no partial result behind. Handles it gave out can
|
||||
// be given again, so names of INSERT records end.
|
||||
s.state_mut()?.restore_drawing(before);
|
||||
return Err(bad("boundary", format!("more than {MAX_BOUNDARY_OUTPUT} boundary polylines in one call; split the work")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,7 +267,7 @@ pub(crate) fn explode_with(
|
||||
// pieces are copies of the block's objects and keep theirs.
|
||||
let own_pieces = !matches!(e.kind, EntityKind::Insert(_));
|
||||
let d = s.doc_mut()?;
|
||||
d.remove_entity(*h);
|
||||
let Some(removed) = d.remove_entity(*h) else { continue };
|
||||
for mut p in parts {
|
||||
if own_pieces {
|
||||
p.common.xdata.clear();
|
||||
@@ -278,6 +278,9 @@ pub(crate) fn explode_with(
|
||||
st.push(p);
|
||||
}
|
||||
}
|
||||
if !own_pieces && let Some(names) = s.record_names() {
|
||||
names.erased(&removed);
|
||||
}
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
Ok(out)
|
||||
|
||||
@@ -328,9 +328,10 @@ impl Interactive for FilletM {
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
None => s.echo("Nothing to undo."),
|
||||
|
||||
@@ -491,9 +491,10 @@ impl Interactive for OffsetM {
|
||||
(_, Input::Keyword(k)) if k == "Undo" => {
|
||||
match self.undo.pop() {
|
||||
Some((doc, picked)) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
self.picked = if self.multiple { picked } else { None };
|
||||
if self.picked.is_none() {
|
||||
|
||||
@@ -55,6 +55,13 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result<usize> {
|
||||
// (`refedit::after_command`), so what OOPS had stays.
|
||||
let refused = taken.iter().any(|t| crate::cmd::blocks::refedit::locked(d, t.entity.handle));
|
||||
if n > 0 && !refused {
|
||||
// The names of the erased references' records went with them: OOPS bringing them back
|
||||
// brings none back. Other references' names keep holding (#1660).
|
||||
if let Some(names) = s.record_names() {
|
||||
for t in &taken {
|
||||
names.erased(&t.entity);
|
||||
}
|
||||
}
|
||||
s.state_mut()?.erased = Erased(taken);
|
||||
}
|
||||
Ok(n)
|
||||
|
||||
@@ -178,9 +178,10 @@ impl MocoroM {
|
||||
fn undo(&mut self, s: &mut Session) -> Result<Step> {
|
||||
match self.history.pop() {
|
||||
Some((doc, base)) => {
|
||||
// Settings changed meanwhile (a transparent command) stay.
|
||||
// Settings changed meanwhile (a transparent command) stay. The drawing put
|
||||
// back is an earlier one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
if s.doc()?.header != header {
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
|
||||
@@ -126,7 +126,8 @@ impl PeditM {
|
||||
"reverse" | "r" => self.apply_all(s, "reverse", &json!({}))?,
|
||||
"undo" | "u" => match self.mundo.pop() {
|
||||
Some((d, multi, morig)) => {
|
||||
*s.doc_mut()? = d;
|
||||
// The saved drawing includes its handle seed.
|
||||
s.state_mut()?.restore_drawing(std::sync::Arc::new(d));
|
||||
self.multi = multi;
|
||||
self.morig = morig;
|
||||
s.set_selection(self.multi.clone());
|
||||
|
||||
@@ -696,9 +696,10 @@ impl Interactive for TrimM {
|
||||
}
|
||||
"Undo" => match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an
|
||||
// earlier one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
None => s.echo("Nothing to undo."),
|
||||
|
||||
@@ -302,7 +302,7 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => 0.0,
|
||||
};
|
||||
if !s.state_mut()?.set_view(View { center: c, height: h, twist }) {
|
||||
s.state_mut()?.doc = before.0;
|
||||
s.state_mut()?.restore_drawing(before.0);
|
||||
return Err(bad("view.set", "the view is too large to show. Nothing was changed"));
|
||||
}
|
||||
if let Some(dview::Target::Viewport(h)) = target {
|
||||
|
||||
@@ -237,7 +237,7 @@ impl DviewM {
|
||||
set_twist(s, t, twist)?;
|
||||
}
|
||||
if !s.state_mut()?.set_view(View { twist, ..v }) {
|
||||
s.state_mut()?.doc = before;
|
||||
s.state_mut()?.restore_drawing(before);
|
||||
return Err(EngineError::Other("The view is too large to show.".into()));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -28,6 +28,13 @@ pub struct DocState {
|
||||
pub title: String,
|
||||
pub saved: Arc<Drawing>,
|
||||
pub revision: u64,
|
||||
/// How many times the names AutoLISP gave this drawing's INSERTs' ATTRIBs and SEQENDs ended all
|
||||
/// at once (#1660): another state of the drawing was shown (Undo, Redo, opening or closing the
|
||||
/// Block Editor, a change taken back, or a command putting an earlier drawing back through
|
||||
/// [`DocState::restore_drawing`]), or attribute sets were rebuilt in place (ATTSYNC,
|
||||
/// -BLOCKREPLACE). A name given before names nothing after one of these, never another
|
||||
/// record.
|
||||
pub(crate) names_epoch: u64,
|
||||
pub space: Space,
|
||||
/// Tiled model viewports (VPORTS).
|
||||
pub tiles: ModelTiles,
|
||||
@@ -71,6 +78,7 @@ impl DocState {
|
||||
path,
|
||||
title: title.into(),
|
||||
revision: 1,
|
||||
names_epoch: 0,
|
||||
space: Space::Model,
|
||||
tiles: ModelTiles::default(),
|
||||
mspace: None,
|
||||
@@ -97,8 +105,26 @@ impl DocState {
|
||||
self.follow_layout(&cur.doc);
|
||||
self.reconcile_untiled_twist();
|
||||
self.revision += 1;
|
||||
self.expire_names();
|
||||
cur
|
||||
}
|
||||
/// Names given to records without handles (an INSERT's ATTRIBs and SEQEND) stop holding: the
|
||||
/// records of the drawing they were given for may be gone or replaced. They are never given
|
||||
/// to another record, so a routine's stale name names nothing (`nil`) rather than something
|
||||
/// else.
|
||||
pub(crate) fn expire_names(&mut self) {
|
||||
self.names_epoch = self.names_epoch.wrapping_add(1);
|
||||
}
|
||||
/// Show `doc` again. It is a drawing this document already showed, so its handle seed can
|
||||
/// give the next object a handle a removed one had. Names of INSERT records end, as they do
|
||||
/// for Undo. The same drawing already on show is left as it is: nothing was given out again.
|
||||
pub(crate) fn restore_drawing(&mut self, doc: Arc<Drawing>) {
|
||||
if Arc::ptr_eq(&self.doc, &doc) {
|
||||
return;
|
||||
}
|
||||
self.doc = doc;
|
||||
self.expire_names();
|
||||
}
|
||||
/// After undo/redo replaced the drawing (`before` is the one shown until then): if the current
|
||||
/// layout no longer exists, follow it to its other name when it was renamed (same tab order,
|
||||
/// a name `before` did not have), else go to the Model tab.
|
||||
|
||||
@@ -26,7 +26,7 @@ impl Session {
|
||||
};
|
||||
let Some(st) = st.filter(|st| !Arc::ptr_eq(before, &st.doc)) else { return Ok(()) };
|
||||
let Some(h) = first_non_finite(before, &st.doc) else { return Ok(()) };
|
||||
st.doc = before.clone();
|
||||
st.restore_drawing(before.clone());
|
||||
st.selection = selection.to_vec();
|
||||
Err(EngineError::BadParams {
|
||||
cmd: cmd.into(),
|
||||
|
||||
@@ -126,6 +126,11 @@ impl Env {
|
||||
#[derive(Default)]
|
||||
pub struct LispState {
|
||||
envs: HashMap<u64, Env>,
|
||||
/// The names given to records without a handle of their own (an INSERT's ATTRIBs and SEQEND,
|
||||
/// #1660), by drawing. They are the session's, not a snapshot's, so the drawing's undo states
|
||||
/// and the Block Editor's drawing share them; each use checks what a name stands for against
|
||||
/// the drawing.
|
||||
pub(crate) records: HashMap<u64, drawing::RecordNames>,
|
||||
run: Option<Box<Run>>,
|
||||
/// A routine runs, from its start to its end (also while its machine is out of `run`).
|
||||
active: bool,
|
||||
@@ -251,6 +256,13 @@ impl Session {
|
||||
pub(crate) fn lisp_forget_closed(&mut self) {
|
||||
let docs = &self.docs;
|
||||
self.lisp.envs.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
|
||||
self.lisp.records.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
|
||||
}
|
||||
|
||||
/// The active drawing's names of an INSERT's records (#1660), made on first use.
|
||||
pub(crate) fn record_names(&mut self) -> Option<&mut drawing::RecordNames> {
|
||||
let uid = self.state().ok()?.uid;
|
||||
Some(self.lisp.records.entry(uid).or_default())
|
||||
}
|
||||
|
||||
/// A routine is running (possibly waiting for input).
|
||||
@@ -432,7 +444,7 @@ impl Session {
|
||||
if let Some((doc, sel)) = self.lisp.steps.base.as_ref().or(run.before.as_ref())
|
||||
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid)
|
||||
{
|
||||
st.doc = doc.clone();
|
||||
st.restore_drawing(doc.clone());
|
||||
st.selection = sel.clone();
|
||||
}
|
||||
run.handler = true;
|
||||
|
||||
@@ -21,7 +21,7 @@ use craft_dxf::Tag;
|
||||
|
||||
use super::builtins::args_err;
|
||||
use super::eval::{Ctx, Flow, Need};
|
||||
use super::value::{PickSet, Value, to_text};
|
||||
use super::value::{PickSet, RecordName, Value, equal, to_text};
|
||||
use super::{BlockSlots, LispError};
|
||||
use crate::{Input, Session};
|
||||
|
||||
@@ -119,6 +119,8 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
}
|
||||
}
|
||||
Value::Ename(h) => named(ctx.s, *h, None),
|
||||
// An INSERT's record (#1660) is no object of the drawing: it picks nothing.
|
||||
Value::Record(_) => feed(ctx.s, Input::Pick(Vec::new())),
|
||||
Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))),
|
||||
Value::Cons(_) => {
|
||||
if let Some(p) = arg.as_point() {
|
||||
@@ -326,8 +328,8 @@ pub(super) fn groups_to_list(tags: &[Tag]) -> Vec<Value> {
|
||||
const MAX_GROUP_TEXT: usize = 32 << 20;
|
||||
|
||||
/// An association list back to DXF groups (points split into x, y, z groups). The type
|
||||
/// (`0`), the entity name (`-1`), the handle (`5`), the owner (`330`) and the layout (`410`) are
|
||||
/// left out: they aren't the entity's to set.
|
||||
/// (`0`), the entity name (`-1`), the owner of a record (`-2`) and of the entity (`330`), the
|
||||
/// handle (`5`) and the layout (`410`) are left out: they aren't the entity's to set.
|
||||
fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
|
||||
let mut kind = None;
|
||||
let mut tags = Vec::new();
|
||||
@@ -343,7 +345,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
|
||||
other => return Err(LispError::bad_arg("stringp", other)),
|
||||
})
|
||||
}
|
||||
-1 | -3 | 5 | 330 | 360 | 410 | 102 => {}
|
||||
-1 | -2 | -3 | 5 | 330 | 360 | 410 | 102 => {}
|
||||
_ if point_group(code) && matches!(v, Value::Cons(_)) => {
|
||||
let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?;
|
||||
tags.push(Tag::f(code, p[0]));
|
||||
@@ -374,8 +376,310 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<Space> {
|
||||
d.space_of(h)
|
||||
}
|
||||
|
||||
// ---------------- an INSERT's ATTRIBs and SEQEND ----------------
|
||||
|
||||
/// The most names one drawing's LISP holds for an INSERT's records at once: a routine can't fill
|
||||
/// memory by walking. At the limit `entnext` gives no *new* name (`nil`) until names end (an
|
||||
/// erased reference, Undo, ATTSYNC) and make room; the names already given still hold.
|
||||
const MAX_RECORD_NAMES: usize = 65_536;
|
||||
|
||||
/// What a name given to an INSERT's ATTRIB or SEQEND stands for, while it holds.
|
||||
struct Record {
|
||||
owner: Handle,
|
||||
/// The record's place after the INSERT's own: an ATTRIB's index, or `attribs.len()` for the
|
||||
/// SEQEND.
|
||||
slot: usize,
|
||||
/// The ATTRIB's tag, which can be empty. A SEQEND has no tag.
|
||||
tag: Option<String>,
|
||||
}
|
||||
|
||||
impl Record {
|
||||
/// Whether the reference still has the same kind of record in this slot, with the same tag.
|
||||
fn holds(&self, attribs: &[cadcraft_doc::Attrib]) -> bool {
|
||||
match (attribs.get(self.slot), self.tag.as_deref()) {
|
||||
(Some(a), Some(tag)) => a.tag.eq_ignore_ascii_case(tag),
|
||||
(None, None) => self.slot == attribs.len(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a drawing's LISP gave to INSERTs' ATTRIBs and SEQENDs (#1660). These records have no
|
||||
/// handle of their own in the drawing, and their names are not handles ([`RecordName`]): nothing
|
||||
/// a drawing, a copy of it or another session gives out can ever be one. A name holds while its
|
||||
/// reference keeps the record in that place with that tag, in the drawing's name epoch it was
|
||||
/// given in (`DocState::expire_names`); otherwise it names nothing (`nil`), never another record.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RecordNames {
|
||||
/// Names by INSERT and then by slot. Removing an INSERT ends all its names, even after a
|
||||
/// change to the length of its attribute run.
|
||||
by_owner: HashMap<Handle, HashMap<usize, RecordName>>,
|
||||
/// What each name that still holds stands for, by its number.
|
||||
by_name: HashMap<u64, Record>,
|
||||
/// The drawing's name epoch the names were given in.
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
impl RecordNames {
|
||||
/// Forget every name once the drawing's name epoch moved on: the records they named may be
|
||||
/// gone or rebuilt.
|
||||
fn expire(&mut self, epoch: u64) {
|
||||
if self.epoch != epoch {
|
||||
self.by_owner.clear();
|
||||
self.by_name.clear();
|
||||
self.epoch = epoch;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the name numbered `id`: it names nothing from now on.
|
||||
fn retire(&mut self, id: u64) {
|
||||
if let Some(r) = self.by_name.remove(&id)
|
||||
&& let Some(slots) = self.by_owner.get_mut(&r.owner)
|
||||
&& slots.get(&r.slot).is_some_and(|n| n.id == id)
|
||||
{
|
||||
slots.remove(&r.slot);
|
||||
if slots.is_empty() {
|
||||
self.by_owner.remove(&r.owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// End the names of the removed reference. Restoring it does not revive any of its names.
|
||||
pub(crate) fn erased(&mut self, e: &Entity) {
|
||||
if let Some(slots) = self.by_owner.remove(&e.handle) {
|
||||
for n in slots.into_values() {
|
||||
self.by_name.remove(&n.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many names hold now (tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn count(&self) -> usize {
|
||||
self.by_name.len()
|
||||
}
|
||||
|
||||
/// The INSERT and place `name` stands for in `d` now. A name that no longer holds is dropped:
|
||||
/// it names nothing from then on, also if its record comes back.
|
||||
fn lookup(&mut self, epoch: u64, d: &cadcraft_doc::Drawing, name: RecordName) -> Option<(Handle, usize)> {
|
||||
self.expire(epoch);
|
||||
let r = self.by_name.get(&name.id)?;
|
||||
let at = insert_attribs(d, r.owner).filter(|attribs| r.holds(attribs)).map(|_| (r.owner, r.slot));
|
||||
if at.is_none() {
|
||||
self.retire(name.id);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The name of record `slot` after INSERT `owner`'s own (its attributes, then its SEQEND),
|
||||
/// given now if it has none that holds: the same one while the record holds, so a repeated
|
||||
/// walk is stable. None past the SEQEND, at the limit of names, or when the numbers run out.
|
||||
fn name(&mut self, epoch: u64, attribs: &[cadcraft_doc::Attrib], owner: Handle, slot: usize) -> Option<RecordName> {
|
||||
self.expire(epoch);
|
||||
if let Some(n) = self.by_owner.get(&owner).and_then(|slots| slots.get(&slot)).copied() {
|
||||
if self.by_name.get(&n.id).is_some_and(|r| r.holds(attribs)) {
|
||||
return Some(n);
|
||||
}
|
||||
self.retire(n.id);
|
||||
}
|
||||
let tag = match attribs.get(slot) {
|
||||
Some(a) => Some(a.tag.clone()),
|
||||
None if slot == attribs.len() => None,
|
||||
None => return None,
|
||||
};
|
||||
if self.by_name.len() >= MAX_RECORD_NAMES {
|
||||
return None;
|
||||
}
|
||||
let name = RecordName::fresh(owner)?;
|
||||
self.by_owner.entry(owner).or_default().insert(slot, name);
|
||||
self.by_name.insert(name.id, Record { owner, slot, tag });
|
||||
Some(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The attributes of the block reference `h` in `d` (none for anything else, and for a reference
|
||||
/// with no attributes: an empty run of records is not written).
|
||||
fn insert_attribs(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&[cadcraft_doc::Attrib]> {
|
||||
match d.entity(h).map(|e| &e.kind) {
|
||||
Some(cadcraft_doc::EntityKind::Insert(i)) if !i.attribs.is_empty() => Some(&i.attribs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing and its name epoch, without holding a borrow of the session.
|
||||
fn doc_and_epoch(ctx: &Ctx<'_>) -> Option<(Arc<cadcraft_doc::Drawing>, u64)> {
|
||||
let st = ctx.s.state().ok()?;
|
||||
Some((st.doc.clone(), st.names_epoch))
|
||||
}
|
||||
|
||||
/// The INSERT and record the name `name` stands for now (none when it no longer holds).
|
||||
fn record_of(ctx: &mut Ctx<'_>, name: RecordName) -> Option<(Handle, usize)> {
|
||||
let (d, epoch) = doc_and_epoch(ctx)?;
|
||||
ctx.s.record_names()?.lookup(epoch, &d, name)
|
||||
}
|
||||
|
||||
/// The name of record `slot` after INSERT `owner`'s own (#1660): an ATTRIB, or its SEQEND (one
|
||||
/// past the last attribute). None when it has no such record, when the host has no record
|
||||
/// mapping, or when no name is left to give.
|
||||
fn name_record(ctx: &mut Ctx<'_>, owner: Handle, slot: usize) -> Option<RecordName> {
|
||||
crate::cmd::file::entity_sub_record()?;
|
||||
let (d, epoch) = doc_and_epoch(ctx)?;
|
||||
let attribs = insert_attribs(&d, owner)?;
|
||||
ctx.s.record_names()?.name(epoch, attribs, owner, slot)
|
||||
}
|
||||
|
||||
/// An entity list: `head` (its name, type and, for an INSERT's record, its owner), then the
|
||||
/// groups of its record with the layout name after the AcDbEntity marker, as AutoCAD lists it.
|
||||
/// The layout is the one object `at` is in; without a layout of its own (an entity of a block
|
||||
/// definition) it has none.
|
||||
fn entity_list(d: &cadcraft_doc::Drawing, mut items: Vec<Value>, at: Handle, tags: &[Tag], in_block: bool) -> Value {
|
||||
let layout = match space_of(d, at) {
|
||||
Some(Space::Paper(name)) => name,
|
||||
_ => "Model".into(),
|
||||
};
|
||||
let mut placed_layout = in_block;
|
||||
for v in groups_to_list(tags) {
|
||||
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
|
||||
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
|
||||
items.push(v);
|
||||
if after_marker {
|
||||
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
|
||||
placed_layout = true;
|
||||
}
|
||||
}
|
||||
Value::list(items)
|
||||
}
|
||||
|
||||
/// The list of record `slot` of the reference `owner` named `name`: the DXF writer's record,
|
||||
/// its name (`-1`), type (`0`) and reference (`-2`). None when the host has no record mapping.
|
||||
fn record_list(d: &cadcraft_doc::Drawing, name: RecordName, owner: Handle, slot: usize) -> Option<(Value, Vec<Tag>)> {
|
||||
let e = d.entity(owner)?;
|
||||
let (kind, mut tags) = (crate::cmd::file::entity_sub_record()?)(d, e, slot)?;
|
||||
convert_angles(&kind, &mut tags, f64::to_radians);
|
||||
let head = vec![
|
||||
Value::cons(Value::Int(-1), Value::Record(name)),
|
||||
Value::cons(Value::Int(0), Value::str(&kind)),
|
||||
Value::cons(Value::Int(-2), Value::Ename(owner)),
|
||||
];
|
||||
Some((entity_list(d, head, owner, &tags, false), tags))
|
||||
}
|
||||
|
||||
/// `entget` of an INSERT's ATTRIB or SEQEND (#1660), while `name` names one.
|
||||
fn record_entget(ctx: &mut Ctx<'_>, name: RecordName) -> Option<Value> {
|
||||
let (owner, slot) = record_of(ctx, name)?;
|
||||
let d = ctx.s.doc().ok()?;
|
||||
record_list(d, name, owner, slot).map(|(list, _)| list)
|
||||
}
|
||||
|
||||
/// What an ATTRIB's submitted list asks to change: `Some(None)` when it asks for nothing, and
|
||||
/// `Some(Some(value))` for its value (group 1). `None` when it asks for any other edit: a group
|
||||
/// added, dropped, moved or changed other than the attribute's own value.
|
||||
fn value_edit(now: &[Tag], asked: &[Tag]) -> Option<Option<String>> {
|
||||
if now.len() != asked.len() {
|
||||
return None;
|
||||
}
|
||||
let mut value = None;
|
||||
let mut seen = false;
|
||||
for (n, a) in now.iter().zip(asked) {
|
||||
if n.code != a.code {
|
||||
return None;
|
||||
}
|
||||
if n.code == 1 {
|
||||
// A multiline attribute's embedded text has a group 1 of its own, after its marker
|
||||
// (101): only the attribute's value, before it, may differ.
|
||||
match (&n.value, &a.value) {
|
||||
(craft_dxf::Value::Str(old), craft_dxf::Value::Str(new)) if !seen => {
|
||||
seen = true;
|
||||
if old != new {
|
||||
value = Some(new.clone());
|
||||
}
|
||||
}
|
||||
_ if n == a => {}
|
||||
_ => return None,
|
||||
}
|
||||
} else if n != a {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
|
||||
/// The submitted list has the items `entget` would return, in order, except at group 1 (the
|
||||
/// value): `value_edit` checks which group 1 may differ. Every other group, including the ones
|
||||
/// an entity cannot set (`-2`, `5`, `330`, `360`, `410`, `102`), must be the same.
|
||||
fn only_value_diff(expected: &Value, asked: &Value) -> bool {
|
||||
let (mut expected, mut asked) = (expected.iter(), asked.iter());
|
||||
loop {
|
||||
match (expected.next(), asked.next()) {
|
||||
(None, None) => return true,
|
||||
(Some(x), Some(y)) => {
|
||||
let code = x.car().as_number();
|
||||
if code != y.car().as_number() {
|
||||
return false;
|
||||
}
|
||||
if code != Some(1.0) && !equal(&x, &y, 0.0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `entmod` of the INSERT's record `name` stands for (#1660): only an ATTRIB's value may change,
|
||||
/// the group 1 value; its tag, place, flags and properties are the reference's. A SEQEND holds
|
||||
/// nothing to change, and a name that no longer holds names nothing: both give `nil`, the drawing
|
||||
/// as it is.
|
||||
fn entmod_attrib(ctx: &mut Ctx<'_>, list: &Value, name: RecordName) -> Value {
|
||||
let Some((owner, slot)) = record_of(ctx, name) else { return Value::Nil };
|
||||
// An outer list with an atom tail is not the list `entget` returned: iterating it would drop
|
||||
// the tail and accept the malformed list. The group pairs inside are dotted, as DXF has them.
|
||||
if !list.is_list() {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Ok((kind, asked)) = list_to_groups(list) else { return Value::Nil };
|
||||
if !kind.eq_ignore_ascii_case("ATTRIB") {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Ok(d) = ctx.s.doc() else { return Value::Nil };
|
||||
if crate::cmd::blocks::refedit::locked(d, owner) {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Some((expected, now)) = record_list(d, name, owner, slot) else { return Value::Nil };
|
||||
// The type, layout, owner, handle and any other group are not the attribute's to change: a
|
||||
// list that differs from `entget` anywhere but its group 1 value is refused (a SEQEND's
|
||||
// list too), the drawing untouched.
|
||||
if !only_value_diff(&expected, list) {
|
||||
return Value::Nil;
|
||||
}
|
||||
match value_edit(&now, &asked) {
|
||||
None => Value::Nil,
|
||||
Some(None) => list.clone(),
|
||||
Some(Some(value)) => {
|
||||
let ok = ctx.s.doc_mut().is_ok_and(|d| {
|
||||
d.modify_entity(owner, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.get_mut(slot)
|
||||
{
|
||||
a.text.value = value.clone();
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
});
|
||||
if ok {
|
||||
ctx.s.touch();
|
||||
}
|
||||
if ok { list.clone() } else { Value::Nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
// An INSERT's ATTRIB or SEQEND (#1660) is not an entity of the drawing: its name reaches it.
|
||||
if let Value::Record(r) = &a[0] {
|
||||
return Ok(Flow::Value(record_entget(ctx, *r).unwrap_or_default()));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
// The applications whose xdata to list: names or wildcard patterns ("*": every application).
|
||||
let apps: Option<Vec<String>> = match a.get(1) {
|
||||
@@ -396,21 +700,8 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let (kind, mut tags) = (codec()?.groups)(d, e);
|
||||
let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil());
|
||||
convert_angles(&kind, &mut tags, f64::to_radians);
|
||||
let layout = match space_of(d, h) {
|
||||
Some(Space::Paper(name)) => name,
|
||||
_ => "Model".into(),
|
||||
};
|
||||
let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
|
||||
let mut placed_layout = in_block;
|
||||
for v in groups_to_list(&tags) {
|
||||
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
|
||||
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
|
||||
items.push(v);
|
||||
if after_marker {
|
||||
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
|
||||
placed_layout = true;
|
||||
}
|
||||
}
|
||||
let head = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
|
||||
let mut items = entity_list(d, head, h, &tags, in_block).to_vec();
|
||||
if let Some(x) = xdata {
|
||||
items.push(Value::cons(Value::Int(-3), x));
|
||||
}
|
||||
@@ -698,7 +989,12 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value {
|
||||
pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let list = &a[0];
|
||||
let Some(Value::Ename(h)) = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()) else {
|
||||
let name = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr());
|
||||
// An INSERT's record takes a value edit only (#1660); any other edit of one is refused.
|
||||
if let Some(Value::Record(r)) = name {
|
||||
return Ok(Flow::Value(entmod_attrib(ctx, list, r)));
|
||||
}
|
||||
let Some(Value::Ename(h)) = name else {
|
||||
return Err(LispError::bad_arg("lentityp", &Value::Nil));
|
||||
};
|
||||
let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
@@ -742,9 +1038,15 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Ok(Flow::Value(if ok { list.clone() } else { Value::Nil }))
|
||||
}
|
||||
|
||||
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own).
|
||||
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). For an INSERT's record
|
||||
/// (#1660) its reference: the record's name while it holds.
|
||||
pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
if let Value::Record(r) = &a[0] {
|
||||
let holds = record_of(ctx, *r).is_some();
|
||||
ctx.s.touch();
|
||||
return Ok(Flow::Value(if holds { a[0].clone() } else { Value::Nil }));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
ctx.s.touch();
|
||||
Ok(Flow::Value(if ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()) { Value::Ename(h) } else { Value::Nil }))
|
||||
@@ -753,10 +1055,18 @@ pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
/// `(entdel ename)`: delete an entity, or bring back one this routine's drawing deleted.
|
||||
pub fn entdel(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
// An INSERT's ATTRIB or SEQEND is the reference's: it is not deleted on its own (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
if let Some(space) = d.space_of(h) {
|
||||
if let Some(e) = d.remove_entity(h) {
|
||||
// The names of its records went with it: `entdel` bringing it back brings none back.
|
||||
if let Some(names) = ctx.s.record_names() {
|
||||
names.erased(&e);
|
||||
}
|
||||
ctx.env.deleted.insert(h, (space, e));
|
||||
ctx.s.touch();
|
||||
return Ok(Flow::Value(Value::Ename(h)));
|
||||
@@ -852,24 +1162,41 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn entnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 1)?;
|
||||
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
|
||||
if let Some(v) = a.first().filter(|v| !v.is_nil()) {
|
||||
let h = ename(v)?;
|
||||
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
|
||||
&& let Some((_, next)) = block_slots(ctx).get(&h)
|
||||
{
|
||||
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
|
||||
let after = match a.first() {
|
||||
None | Some(Value::Nil) => None,
|
||||
// From a record of an INSERT (#1660): the next record of its run, and after its SEQEND the
|
||||
// next main entity after the INSERT. A name that no longer holds names nothing.
|
||||
Some(Value::Record(r)) => {
|
||||
let Some((owner, slot)) = record_of(ctx, *r) else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let attribs = ctx.s.doc().ok().and_then(|d| insert_attribs(d, owner)).map_or(0, <[cadcraft_doc::Attrib]>::len);
|
||||
if slot < attribs {
|
||||
return Ok(Flow::Value(name_record(ctx, owner, slot.saturating_add(1)).map(Value::Record).unwrap_or_default()));
|
||||
}
|
||||
Some(owner)
|
||||
}
|
||||
}
|
||||
let order = handles_in_order(ctx);
|
||||
let next = match a.first() {
|
||||
None | Some(Value::Nil) => order.first().copied(),
|
||||
Some(v) => {
|
||||
let h = ename(v)?;
|
||||
let i = order.partition_point(|x| *x <= h);
|
||||
order.get(i).copied()
|
||||
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
|
||||
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
|
||||
&& let Some((_, next)) = block_slots(ctx).get(&h)
|
||||
{
|
||||
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
|
||||
}
|
||||
// An INSERT with attributes is followed by its ATTRIBs and its SEQEND (#1660): its
|
||||
// first ATTRIB, or nil when no name is left to give (the walk stops rather than skip
|
||||
// records it can't name). A host without the optional record mapping has no such
|
||||
// records: the walk goes on to the next entity, as it always did.
|
||||
if crate::cmd::file::entity_sub_record().is_some() && ctx.s.doc().is_ok_and(|d| insert_attribs(d, h).is_some()) {
|
||||
return Ok(Flow::Value(name_record(ctx, h, 0).map(Value::Record).unwrap_or_default()));
|
||||
}
|
||||
Some(h)
|
||||
}
|
||||
};
|
||||
let order = handles_in_order(ctx);
|
||||
let next = match after {
|
||||
Some(h) => order.get(order.partition_point(|x| *x <= h)).copied(),
|
||||
None => order.first().copied(),
|
||||
};
|
||||
Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -1151,6 +1478,13 @@ fn compare(h: f64, w: f64, op: &str) -> bool {
|
||||
|
||||
pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 2)?;
|
||||
// A selection set holds objects of the drawing; an INSERT's record (#1660) is not one.
|
||||
if matches!(a.first(), Some(Value::Record(_))) {
|
||||
if let Some(ss) = a.get(1) {
|
||||
pickset(ss)?;
|
||||
}
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
match (a.first(), a.get(1)) {
|
||||
(None, _) => Ok(Flow::Value(new_pickset(ctx, Vec::new()))),
|
||||
(Some(e), None) => {
|
||||
@@ -1172,6 +1506,11 @@ pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn ssdel(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
// Never in a selection set (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
pickset(&a[1])?;
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
let p = pickset(&a[1])?;
|
||||
let removed = p.items.lock().map(|mut v| {
|
||||
@@ -1199,6 +1538,11 @@ pub fn ssname(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn ssmemb(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
// Never in a selection set (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
pickset(&a[1])?;
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
Ok(Flow::Value(if items(&pickset(&a[1])?).contains(&h) { Value::Ename(h) } else { Value::Nil }))
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use cadcraft_doc::Handle;
|
||||
use serde_json::json;
|
||||
|
||||
use super::value::{Value, to_text};
|
||||
use crate::Session;
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec, set_object_records};
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec, set_entity_sub_record, set_object_records};
|
||||
|
||||
pub(super) fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
set_object_records(cadcraft_io::object_records);
|
||||
Session::new()
|
||||
@@ -1966,3 +1971,704 @@ fn append_checks_the_cell_cap_before_building_its_result() {
|
||||
assert!(super::value::live_cells() < before + 50_000, "no oversized result was built");
|
||||
assert_eq!(ok(&mut s, "(setq l nil m nil) (length (append '(1) '(2 3)))"), "3");
|
||||
}
|
||||
|
||||
// ---------------- an INSERT's ATTRIBs and SEQEND (#1660) ----------------
|
||||
|
||||
/// A session with block K: a circle and attributes (tag, DXF flags, default value). `entmake`
|
||||
/// goes through the DXF codec, as in the app.
|
||||
fn with_attributes(defs: &[(&str, i32, &str)]) -> Session {
|
||||
let mut s = session();
|
||||
let mut code =
|
||||
String::from("(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0)))");
|
||||
for (i, (tag, flags, default)) in defs.iter().enumerate() {
|
||||
let y = 5.0 + 3.0 * i as f64;
|
||||
code += &format!(
|
||||
" (entmake '((0 . \"ATTDEF\") (10 0.0 {y:.1} 0.0) (40 . 2.5) (1 . \"{default}\") (3 . \"P{tag}\") (2 . \"{tag}\") (70 . {flags})))"
|
||||
);
|
||||
}
|
||||
code += " (entmake '((0 . \"ENDBLK\")))";
|
||||
s.cmdline(&format!("(progn {code})")).unwrap();
|
||||
s.log.clear();
|
||||
s
|
||||
}
|
||||
|
||||
/// `s` with one reference of K at (10,10), its values `attribs`, and the reference's handle; the
|
||||
/// LISP global `i` names it.
|
||||
fn inserted(s: &mut Session, attribs: serde_json::Value) -> Handle {
|
||||
s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": attribs })).unwrap();
|
||||
let h = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
ok(s, &format!("(setq i (handent \"{}\")) i", h.hex()));
|
||||
h
|
||||
}
|
||||
|
||||
/// Every reference's attributes (tag, value) from the model, in order.
|
||||
fn attribute_values(s: &Session) -> Vec<(String, String)> {
|
||||
let d = s.doc().unwrap();
|
||||
d.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The records from `i` in order: (type, tag, value) and the SEQEND's owner.
|
||||
const WALK: &str = r#"(progn
|
||||
(setq e (entnext i) out nil)
|
||||
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
|
||||
(setq out (append out (list (list (cdr (assoc 0 ed)) (cdr (assoc 2 ed)) (cdr (assoc 1 ed))
|
||||
(if (equal (cdr (assoc -2 ed)) i) T nil))))
|
||||
e (entnext e)))
|
||||
(list out (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i)))"#;
|
||||
|
||||
#[test]
|
||||
fn entnext_walks_an_inserts_attribs_then_the_seqend_then_the_next_entity() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2"), ("T3", 0, "D3")]);
|
||||
inserted(&mut s, json!({ "T1": "A1", "T3": "A3" }));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget i)))"), "\"INSERT\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 66 (entget i)))"), "1");
|
||||
assert_eq!(ok(&mut s, WALK), "(((\"ATTRIB\" \"T1\" \"A1\" T) (\"ATTRIB\" \"T2\" \"P2\" T) (\"ATTRIB\" \"T3\" \"A3\" T)) \"SEQEND\" T)");
|
||||
// After the SEQEND the main order goes on: a line made later is next, then nil.
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext (entnext (entnext (entnext (entnext i))))))))"), "\"LINE\"");
|
||||
assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil");
|
||||
// A reference of a block without attributes is followed by the next main entity, no SEQEND.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
s.cmdline("(progn (entmake '((0 . \"BLOCK\") (2 . \"E\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entmake '((0 . \"ENDBLK\"))))").unwrap();
|
||||
s.execute("insert", &json!({ "name": "E", "at": [0, 0] })).unwrap();
|
||||
let plain = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (entnext (handent \"{}\")))))", plain.hex())), "\"LINE\"");
|
||||
// The owner is group -2 in a record's list and not 330, and the reference's own list has
|
||||
// neither (as `entity_groups` keeps it).
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
assert_eq!(ok(&mut s, "(assoc 330 (entget (entnext i)))"), "nil");
|
||||
assert!(attribute_values(&s).iter().any(|(t, v)| t == "T1" && v == "A1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entmod_of_an_attrib_changes_only_its_value() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a) seq (entnext (entnext a)))");
|
||||
// The value (group 1) is the one edit an ATTRIB's list takes.
|
||||
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
assert!(r.contains("(1 . \"A2\")"), "{r}");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
|
||||
// A list asking for anything else, and any edit of the SEQEND, is refused and changes nothing.
|
||||
for code in [
|
||||
"(entmod (subst (cons 2 \"X\") (assoc 2 d) d))",
|
||||
"(entmod (subst (cons 40 9.0) (assoc 40 d) d))",
|
||||
"(entmod (subst (cons 8 \"L\") (assoc 8 d) d))",
|
||||
"(entmod (subst (cons 0 \"SEQEND\") (assoc 0 d) d))",
|
||||
"(entmod (entget seq))",
|
||||
// Groups `list_to_groups` does not keep are still the reference's: an edit (or an added
|
||||
// group) is refused, also when the same list changes group 1.
|
||||
"(entmod (subst (cons 410 \"Layout2\") (assoc 410 d) d))",
|
||||
"(entmod (subst (cons -2 a) (assoc -2 d) d))",
|
||||
"(entmod (append d (list (cons 5 \"FF\"))))",
|
||||
"(entmod (append d (list (cons 330 a))))",
|
||||
"(entmod (append d (list (cons 360 \"FF\"))))",
|
||||
"(entmod (append d (list (cons 102 \"{X\"))))",
|
||||
"(entmod (subst (cons 1 \"A2\") (assoc 1 d) (subst (cons 410 \"Layout2\") (assoc 410 d) d)))",
|
||||
// The same items, but the outer list ends in an atom: iterating it would drop the tail
|
||||
// and accept a list `entget` never returned.
|
||||
"(progn (setq r \"X\" p (reverse d)) (while p (setq r (cons (car p) r) p (cdr p))) (entmod r))",
|
||||
] {
|
||||
assert_eq!(ok(&mut s, code), "nil", "{code}");
|
||||
}
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "no refused edit changed the value");
|
||||
// `entdel` of a record, and `entdel` of the SEQEND, do nothing either.
|
||||
assert_eq!(ok(&mut s, "(progn (entdel a) (entdel seq))"), "nil");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "the name still holds: nothing changed");
|
||||
// The edit is one undo step: the value goes back with it.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subentity_name_expires_when_its_record_is_rebuilt() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// Erased: the records go with the reference.
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (entnext a))"), "(nil nil)");
|
||||
// Undone: the reference is back, the name given before the Undo is not.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", h.hex())), "\"A1\"");
|
||||
// ATTSYNC rebuilds the attributes in place: the old name names nothing, the values stay.
|
||||
ok(&mut s, "(setq b (entnext i))");
|
||||
s.execute("attsync", &json!({ "name": "K" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget b)"), "nil");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
// A name never resolves to another attribute: when the record at its place has another tag
|
||||
// now, it names nothing (the change makes no new epoch), and a new walk reaches the new tag.
|
||||
ok(&mut s, "(setq c (entnext i))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget c)))"), "\"T1\"");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.first_mut()
|
||||
{
|
||||
a.tag = "T9".into();
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget c)"), "nil", "the record at that place has another tag now");
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 0 (entget (entnext i)))) (cdr (assoc 2 (entget (entnext i)))))"), "(\"ATTRIB\" \"T9\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_attrib_and_a_seqend_have_distinct_names() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) end (entnext a))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget end)))"), "\"SEQEND\"");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
let mut blank = i.attribs[0].clone();
|
||||
blank.tag.clear();
|
||||
i.attribs.push(blank);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget end)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(setq b (entnext a)) (list (cdr (assoc 0 (entget b))) (eq b (entnext a)))"), "(\"ATTRIB\" T)");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.attribs.truncate(1);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (entget b) (cdr (assoc 0 (entget (entnext a)))))"), "(nil \"SEQEND\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explode_and_burst_retire_the_removed_inserts_record_names() {
|
||||
for command in ["explode", "burst"] {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) end (entnext (entnext a)))");
|
||||
let original = s.doc().unwrap().entity(h).unwrap().as_ref().clone();
|
||||
inserted(&mut s, json!({ "T1": "B1" }));
|
||||
ok(&mut s, "(setq b (entnext i))");
|
||||
// A host can shorten the run before removal and later reuse the handle.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.attribs.truncate(1);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let result = s.execute(command, &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert!(!result["handles"].as_array().unwrap().is_empty(), "{command} creates pieces");
|
||||
assert!(s.doc().unwrap().entity(h).is_none(), "{command} removes the reference");
|
||||
s.doc_mut().unwrap().model.push(original);
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (entget end) (cdr (assoc 1 (entget b))))"), "(nil nil \"B1\")", "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entmod_obeys_the_refedit_working_set_for_attrib_owners() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let editing = inserted(&mut s, json!({ "T1": "E1" }));
|
||||
let outside = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("refedit", &json!({ "handle": editing.hex() })).unwrap();
|
||||
let read = "(cdr (assoc 1 (entget (entnext i))))";
|
||||
let edit = r#"(progn (setq d (entget (entnext i))) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#;
|
||||
assert_eq!(ok(&mut s, read), "\"A1\"");
|
||||
assert_eq!(ok(&mut s, edit), "nil");
|
||||
assert_eq!(ok(&mut s, read), "\"A1\"");
|
||||
s.execute("refset", &json!({ "add": [outside.hex()] })).unwrap();
|
||||
assert_ne!(ok(&mut s, edit), "nil");
|
||||
assert_eq!(ok(&mut s, read), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_reference_does_not_revive_an_old_name() {
|
||||
// entdel of the reference, then entdel again to bring it back: the name given before the
|
||||
// first entdel names nothing, also after the reference returns.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil");
|
||||
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil", "the name must not come back");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
// ERASE, then OOPS: the same. Erasing expires the names it took with it.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("oops", &json!({})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "OOPS must not revive the name");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erasing_another_object_keeps_an_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
let line = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
// Erasing another object leaves the reference and its records as they were: the name holds
|
||||
// and takes the value edit it always took.
|
||||
s.execute("erase", &json!({ "handles": [line.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
|
||||
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
assert!(r.contains("(1 . \"A2\")"), "{r}");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into())]);
|
||||
// Erasing the reference itself ends its names, and OOPS bringing it back revives none.
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("oops", &json!({})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "the name of an erased reference stays dead");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entdel_of_another_object_keeps_an_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
ok(&mut s, "(setq line (entlast))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget line)))"), "\"LINE\"");
|
||||
ok(&mut s, "(entdel line)");
|
||||
assert_eq!(ok(&mut s, "(entget line)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_in_the_block_editor_never_resolves_in_the_host() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("bedit", &json!({ "name": "K" })).unwrap();
|
||||
// A reference made in the editor's drawing, named there. The editor starts from the host's
|
||||
// drawing, so its handle is the one the host gives its next new object.
|
||||
s.execute("insert", &json!({ "name": "K", "at": [40, 40], "attribs": { "T1": "E1" } })).unwrap();
|
||||
let editor = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
ok(&mut s, &format!("(setq a (entnext (handent \"{}\")))", editor.hex()));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"E1\"");
|
||||
s.execute("bclose", &json!({ "save": false })).unwrap();
|
||||
// The host's next reference takes the handle the editor's reference had: the name given in
|
||||
// the editor must not reach its ATTRIB, or `entmod` through it would edit the wrong one.
|
||||
s.execute("insert", &json!({ "name": "K", "at": [80, 80], "attribs": { "T1": "H1" } })).unwrap();
|
||||
let host = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
assert_eq!(host, editor, "the host takes the handle the editor's reference had");
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(entdel a)"), "nil");
|
||||
assert_eq!(
|
||||
ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", host.hex())),
|
||||
"\"H1\"",
|
||||
"the host's own attribute is untouched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_record_provider_entnext_walks_the_next_entity() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
|
||||
// A host that installed no provider has no records to name: the walk goes on to the next
|
||||
// main entity as it always did, rather than answering nil at the reference.
|
||||
let next = crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(entnext i)"));
|
||||
assert_ne!(next, "nil");
|
||||
assert_eq!(crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(cdr (assoc 0 (entget (entnext i))))")), "\"LINE\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_redo_does_not_revive_an_old_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.redo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "Redo must not revive the name");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_replace_expires_an_old_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
// A replacement block with the same tag as K's first attribute: without the expiry, the old
|
||||
// name would keep naming that place and return the new record.
|
||||
s.cmdline(
|
||||
"(progn (entmake '((0 . \"BLOCK\") (2 . \"L\") (70 . 2) (10 0.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"ATTDEF\") (10 0.0 0.0 0.0) (40 . 2.5) (1 . \"Z1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \
|
||||
(entmake '((0 . \"ENDBLK\"))))",
|
||||
)
|
||||
.unwrap();
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("blockreplace", &json!({ "block": "K", "with": "L" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "-BLOCKREPLACE rebuilt the record");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reinsert_after_undo_takes_the_handle_and_no_old_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// U takes the reference back; INSERT then gives a new one the handle it had.
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc().unwrap().entity(h).is_none());
|
||||
let again = inserted(&mut s, json!({ "T1": "B1" }));
|
||||
assert_eq!(again, h, "the same handle");
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (cdr (assoc 1 (entget (entnext i)))))"), "(nil \"B1\")");
|
||||
}
|
||||
|
||||
/// A drawing with one reference of `attribs` attributes (all value V), for the bounds.
|
||||
fn drawing_with_attributes(attribs: usize) -> (Session, Handle) {
|
||||
let text = |v: &str| cadcraft_doc::Text {
|
||||
insert: cadcraft_geom::Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 1.0,
|
||||
value: v.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: cadcraft_doc::HAlign::Left,
|
||||
valign: cadcraft_doc::VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
};
|
||||
let mut d = cadcraft_doc::Drawing::new_metric();
|
||||
let list = (0..attribs)
|
||||
.map(|i| cadcraft_doc::Attrib {
|
||||
tag: format!("T{i}"),
|
||||
text: text("V"),
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: cadcraft_doc::AttribProps::default(),
|
||||
multiline: None,
|
||||
modes: cadcraft_doc::AttribModes::default(),
|
||||
})
|
||||
.collect();
|
||||
let insert = cadcraft_doc::Insert { block: "B".into(), attribs: list, ..cadcraft_doc::Insert::default() };
|
||||
let h = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(insert)).expect("add");
|
||||
let mut s = session();
|
||||
s.open_drawing(d, "attributes", None);
|
||||
ok(&mut s, &format!("(setq i (handent \"{}\"))", h.hex()));
|
||||
(s, h)
|
||||
}
|
||||
|
||||
/// The number of records a walk from `i` names.
|
||||
const COUNT: &str = "(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)";
|
||||
|
||||
#[test]
|
||||
fn a_session_names_at_most_65536_records_and_nothing_changes() {
|
||||
let (mut s, h) = drawing_with_attributes(65_537);
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
// The names given hold: a second walk is the same, and the drawing kept every attribute.
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
// Erasing and bringing the reference back frees the 65,536 names it held: the old name names
|
||||
// nothing, and a new walk can name the records again.
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
ok(&mut s, "(progn (entdel i) (entdel i))");
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
let d = s.doc().unwrap();
|
||||
let kept = d.entity(h).and_then(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.len()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(kept, Some(65_537));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_object_at_any_handle_is_never_a_record() {
|
||||
// A hostile $HANDSEED at the top of the range: the line made after the walk takes that
|
||||
// handle, and the record keeps its own name, which is no handle.
|
||||
let (mut s, _) = drawing_with_attributes(1);
|
||||
s.doc_mut().unwrap().handseed = u64::MAX - 1;
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
assert_eq!(
|
||||
ok(&mut s, r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#),
|
||||
"\"FFFFFFFFFFFFFFFE\""
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (eq a (entlast)) (entdel a) (cdr (assoc 0 (entget (entlast)))))"),
|
||||
"(\"ATTRIB\" nil nil \"LINE\")"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_at_the_top_of_the_handle_range_walk_as_objects() {
|
||||
let (mut s, _) = drawing_with_attributes(1);
|
||||
{
|
||||
let d = s.doc_mut().unwrap();
|
||||
d.handseed = u64::MAX;
|
||||
for handle in [Handle(u64::MAX - 1), Handle(u64::MAX)] {
|
||||
let line =
|
||||
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) });
|
||||
d.model.push(cadcraft_doc::Entity { handle, common: cadcraft_doc::Common::default(), kind: line });
|
||||
}
|
||||
}
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// The lines' handles are theirs: `entnext` of the first finds the second, then the end.
|
||||
assert_eq!(ok(&mut s, "(equal (entnext (handent \"FFFFFFFFFFFFFFFE\")) (handent \"FFFFFFFFFFFFFFFF\"))"), "T");
|
||||
assert_eq!(ok(&mut s, "(entnext (handent \"FFFFFFFFFFFFFFFF\"))"), "nil");
|
||||
// The record, a table record and the lines each keep their own name.
|
||||
assert_eq!(
|
||||
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (equal a (tblobjname \"LAYER\" \"0\")) (equal a (handent \"FFFFFFFFFFFFFFFE\")))"),
|
||||
"(\"ATTRIB\" nil nil)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_name_is_an_entity_name_but_no_handle() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) b (entnext a))");
|
||||
assert_eq!(ok(&mut s, "(type a)"), "ENAME");
|
||||
// The same record has the same name on every walk; another record and the reference have
|
||||
// their own.
|
||||
assert_eq!(ok(&mut s, "(list (eq a (entnext i)) (equal a (entnext i)) (eq a b) (eq a i) (equal a i))"), "(T T nil nil nil)");
|
||||
// It prints as the reference's handle, a dot and its number: never a handle's text.
|
||||
let printed = ok(&mut s, "a");
|
||||
assert!(printed.starts_with(&format!("<Entity name: {:x}.", h.0)) && printed.ends_with('>'), "{printed}");
|
||||
// No handle reaches it: its list has no group 5, and `handent` of the reference's handle is
|
||||
// the reference.
|
||||
assert_eq!(ok(&mut s, "(list (assoc 5 (entget a)) (eq a (handent (cdr (assoc 5 (entget i))))))"), "(nil nil)");
|
||||
// A DXF group cannot point at it: `entmake` of a list that does is refused.
|
||||
assert_eq!(ok(&mut s, "(entmake (list '(0 . \"LINE\") '(10 0.0 0.0 0.0) '(11 1.0 0.0 0.0) (cons 340 a)))"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_sets_and_commands_take_no_record() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) ss (ssadd i))");
|
||||
// A selection set holds objects of the drawing; a record is not one on its own.
|
||||
assert_eq!(ok(&mut s, "(list (ssadd a) (ssadd a ss) (sslength ss) (ssmemb a ss) (ssdel a ss) (sslength ss))"), "(nil nil 1 nil nil 1)");
|
||||
// A command given the name picks nothing: the reference stays, and the name holds.
|
||||
ok(&mut s, "(command \"_.ERASE\" a \"\")");
|
||||
assert!(s.doc().unwrap().entity(h).is_some());
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entupd_of_a_record_answers_its_name_while_it_holds() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
assert_eq!(ok(&mut s, "(progn (entmod (subst (cons 1 \"A2\") (assoc 1 d) d)) (eq (entupd a) a))"), "T");
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entupd a)"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_name_holds_while_commands_keep_its_record() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// Moving the reference, or changing its colour, keeps its records in their places.
|
||||
s.execute("move", &json!({ "handles": [h.hex()], "delta": [5, 5] })).unwrap();
|
||||
s.execute("chprop", &json!({ "handles": [h.hex()], "color": 1 })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 1 (entget a))) (eq a (entnext i)))"), "(\"A1\" T)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_record_name_is_one_entry_and_walking_again_adds_none() {
|
||||
const N: usize = 64;
|
||||
let (mut s, _) = drawing_with_attributes(N);
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
ok(&mut s, "(setq e nil)");
|
||||
// The R3 pattern: each new name, then state access. Nothing is copied or replayed.
|
||||
for _ in 0..=N {
|
||||
ok(&mut s, "(setq e (if e (entnext e) (entnext i)))");
|
||||
let _ = s.state_mut().unwrap();
|
||||
}
|
||||
let uid = s.state().unwrap().uid;
|
||||
let held = |s: &Session| s.lisp.records.get(&uid).map_or(0, super::drawing::RecordNames::count);
|
||||
assert_eq!(held(&s), N + 1, "the attributes and the SEQEND, one entry each");
|
||||
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
|
||||
assert_eq!(held(&s), N + 1, "a walk again gives the same names");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "naming changes nothing in the drawing");
|
||||
// Undo or redo ends them: the next walk starts over with as many.
|
||||
s.execute("line", &json!({ "points": [[0, -4], [1, -4]] })).unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
|
||||
assert_eq!(held(&s), N + 1);
|
||||
}
|
||||
|
||||
/// A saved drawing with one named attribute. The name comes from the command line, which does
|
||||
/// not run the after-command pass.
|
||||
fn clean_named() -> Session {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
{
|
||||
let st = s.state_mut().unwrap();
|
||||
st.saved = st.doc.clone();
|
||||
st.undo.clear();
|
||||
st.redo.clear();
|
||||
}
|
||||
s.cmdline("(setq a (entnext i))").unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\"");
|
||||
assert!(!s.state().unwrap().is_dirty(), "naming from the command line saves nothing");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_reads_keep_the_drawing_clean() {
|
||||
let mut s = clean_named();
|
||||
s.cmdline("(getvar \"DBMOD\")").unwrap();
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
|
||||
// A programmatic read runs the after-command pass. That pass must not make a saved drawing dirty.
|
||||
s.execute("lisp", &json!({ "code": "(entget a)" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0, "a read is not an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_selection_keeps_the_drawing_clean() {
|
||||
let mut s = clean_named();
|
||||
let saved = s.state().unwrap().saved.clone();
|
||||
s.execute("select", &json!({ "clear": true })).unwrap();
|
||||
assert!(s.state().unwrap().selection.is_empty());
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved));
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0, "clearing an empty selection is not an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_undo_restores_the_saved_drawing() {
|
||||
let mut s = clean_named();
|
||||
let saved = s.state().unwrap().saved.clone();
|
||||
// A selection change writes no undo step. If it also changes the drawing, the next command
|
||||
// records that copy, and undo cannot return to the saved drawing.
|
||||
s.execute("select", &json!({ "clear": true })).unwrap();
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0);
|
||||
s.execute("line", &json!({ "points": [[0, -3], [1, -3]] })).unwrap();
|
||||
assert!(s.undo().unwrap().is_some());
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved), "undo returns the saved drawing, not a reservation copy");
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_in_the_host_never_resolves_in_the_block_editor() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
let mut same = cadcraft_doc::Entity::clone(s.doc().unwrap().entity(h).unwrap());
|
||||
if let cadcraft_doc::EntityKind::Insert(ins) = &mut same.kind
|
||||
&& let Some(at) = ins.attribs.first_mut()
|
||||
{
|
||||
at.text.value = "E1".into();
|
||||
}
|
||||
s.execute("bedit", &json!({ "name": "K" })).unwrap();
|
||||
// An object of the editor's drawing with the handle the host's reference has: the host's
|
||||
// name must not reach its ATTRIB.
|
||||
s.doc_mut().unwrap().model.push(same);
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("bclose", &json!({ "save": false })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawing_put_back_after_a_refused_change_ends_its_names() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// A change with a number that is not finite: the drawing goes back as it was, without the
|
||||
// reference the name was given for.
|
||||
let bad = cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(f64::NAN, 0.0, 0.0), b: cadcraft_geom::Vec3::ZERO });
|
||||
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), bad).unwrap();
|
||||
assert!(s.refuse_non_finite(None, &before, &[], "line").is_err());
|
||||
assert!(s.doc().unwrap().entity(h).is_none());
|
||||
// The next reference takes the handle back: the old name names nothing in it.
|
||||
assert_eq!(inserted(&mut s, json!({ "T1": "B1" })), h);
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"B1\"");
|
||||
}
|
||||
|
||||
/// MOCORO's own Undo puts the drawing from before the Copy back, handle seed included.
|
||||
/// The next Copy is given that handle again. The name of the removed copy's attribute
|
||||
/// must not read it, walk from it, or change it.
|
||||
#[test]
|
||||
fn mocoro_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(sssetfirst nil nil)
|
||||
(command "_.MOCORO" i "" '(0 0) "_Copy" '(10 0))
|
||||
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c) v (cdr (assoc 1 (entget a))))
|
||||
(command "_Undo" "_Copy" '(20 0) "_eXit"))"#,
|
||||
);
|
||||
// The name was given for a copy with a handle of its own, and it read that copy's attribute.
|
||||
// The copy made after the Undo has the removed copy's handle.
|
||||
assert_eq!(ok(&mut s, "(list (= ch (cdr (assoc 5 (entget i)))) v (= ch (cdr (assoc 5 (entget (entlast))))))"), "(nil \"A1\" T)");
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq d (entget a) w (entnext a))
|
||||
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
|
||||
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
|
||||
),
|
||||
"(T T \"A1\")"
|
||||
);
|
||||
}
|
||||
|
||||
/// A grip Copy's Undo is the same kind of restore: the next copy reuses the handle.
|
||||
#[test]
|
||||
fn grip_copy_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.start_grip_edit(&[(h, 0)]).unwrap();
|
||||
// Enter leaves STRETCH for MOVE, which copies the reference whole.
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
s.input(crate::Input::Keyword("Copy".into())).unwrap();
|
||||
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(20.0, 10.0))).unwrap();
|
||||
// The name is given for a copy with a handle of its own, and it reads that copy's attribute.
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c))
|
||||
(list (= ch (cdr (assoc 5 (entget i)))) (cdr (assoc 1 (entget a)))))"#
|
||||
),
|
||||
"(nil \"A1\")"
|
||||
);
|
||||
s.input(crate::Input::Keyword("Undo".into())).unwrap();
|
||||
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(30.0, 10.0))).unwrap();
|
||||
assert_eq!(ok(&mut s, "(= ch (cdr (assoc 5 (entget (entlast)))))"), "T", "the next copy takes the removed copy's handle");
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq d (entget a) w (entnext a))
|
||||
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
|
||||
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
|
||||
),
|
||||
"(T T \"A1\")"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! ([`charge_bytes`]).
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cadcraft_doc::Handle;
|
||||
@@ -207,6 +207,26 @@ pub enum BuiltinKind {
|
||||
Special(super::eval::Special),
|
||||
}
|
||||
|
||||
/// The name AutoLISP gives an INSERT's ATTRIB or SEQEND (#1660). Those records have no handle of
|
||||
/// their own in the drawing, so their names are not handles: `id` comes from one count for the
|
||||
/// whole process and is never given again, so no object of any drawing, and no other record,
|
||||
/// ever has it. `owner` is the reference's handle, for printing. What a name stands for is kept
|
||||
/// by the session; a name that no longer holds names nothing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RecordName {
|
||||
pub(crate) owner: Handle,
|
||||
pub(crate) id: u64,
|
||||
}
|
||||
|
||||
impl RecordName {
|
||||
/// A name never given before, for a record of `owner`; `None` once the count runs out.
|
||||
pub(crate) fn fresh(owner: Handle) -> Option<RecordName> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
let id = NEXT.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)).ok()?;
|
||||
Some(RecordName { owner, id })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub enum Value {
|
||||
#[default]
|
||||
@@ -217,6 +237,8 @@ pub enum Value {
|
||||
Sym(Sym),
|
||||
Cons(Arc<Cons>),
|
||||
Ename(Handle),
|
||||
/// An INSERT's ATTRIB or SEQEND (#1660): an entity name that is no handle.
|
||||
Record(RecordName),
|
||||
PickSet(PickSet),
|
||||
File(u32),
|
||||
Subr(&'static Builtin),
|
||||
@@ -310,7 +332,7 @@ impl Value {
|
||||
Value::Str(_) => "STR",
|
||||
Value::Sym(_) => "SYM",
|
||||
Value::Cons(_) => "LIST",
|
||||
Value::Ename(_) => "ENAME",
|
||||
Value::Ename(_) | Value::Record(_) => "ENAME",
|
||||
Value::PickSet(_) => "PICKSET",
|
||||
Value::File(_) => "FILE",
|
||||
Value::Subr(_) => "SUBR",
|
||||
@@ -423,6 +445,7 @@ fn atom_equal(a: &Value, b: &Value, fuzz: f64) -> bool {
|
||||
(Value::Str(x), Value::Str(y)) => x == y,
|
||||
(Value::Sym(x), Value::Sym(y)) => x == y,
|
||||
(Value::Ename(x), Value::Ename(y)) => x == y,
|
||||
(Value::Record(x), Value::Record(y)) => x == y,
|
||||
(Value::File(x), Value::File(y)) => x == y,
|
||||
(Value::PickSet(x), Value::PickSet(y)) => x.id == y.id,
|
||||
(Value::Subr(x), Value::Subr(y)) => std::ptr::eq(*x, *y),
|
||||
@@ -567,6 +590,8 @@ fn write_value(out: &mut String, v: &Value, escape: bool, depth: usize) {
|
||||
out.push(')');
|
||||
}
|
||||
Value::Ename(h) => out.push_str(&format!("<Entity name: {:x}>", h.0)),
|
||||
// The reference's handle, a dot and the record's number: never a handle's text.
|
||||
Value::Record(r) => out.push_str(&format!("<Entity name: {:x}.{:x}>", r.owner.0, r.id)),
|
||||
Value::PickSet(p) => out.push_str(&format!("<Selection set: {:x}>", p.id)),
|
||||
Value::File(f) => out.push_str(&format!("#<FILE {f:x}>")),
|
||||
Value::Subr(b) => out.push_str(&format!("#<SUBR @{} {}>", "0", b.name)),
|
||||
|
||||
@@ -16,7 +16,7 @@ impl Session {
|
||||
if let Some((doc, sel, uid)) = before
|
||||
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid)
|
||||
{
|
||||
st.doc = doc;
|
||||
st.restore_drawing(doc);
|
||||
st.selection = sel;
|
||||
}
|
||||
Err(EngineError::Internal(id.into(), crate::guard::message(&*p)))
|
||||
@@ -50,7 +50,7 @@ impl Session {
|
||||
if let Some((doc, sel, uid)) = &before
|
||||
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == *uid)
|
||||
{
|
||||
st.doc = doc.clone();
|
||||
st.restore_drawing(doc.clone());
|
||||
st.selection = sel.clone();
|
||||
}
|
||||
return Err(EngineError::Internal(id.into(), msg));
|
||||
|
||||
@@ -479,7 +479,7 @@ impl Session {
|
||||
Err(EngineError::Internal(id, m)) => {
|
||||
// Restore and end the command.
|
||||
if let Ok(st) = self.state_mut() {
|
||||
st.doc = run.before.clone();
|
||||
st.restore_drawing(run.before.clone());
|
||||
}
|
||||
self.echo(format!("Internal error in {id}: {m}"));
|
||||
self.resume_suspended();
|
||||
@@ -501,7 +501,7 @@ impl Session {
|
||||
let (id, before, selection) = (run.id.clone(), run.before.clone(), run.selection_before.clone());
|
||||
if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.finish_guarded(run, cancelled))) {
|
||||
if let Ok(st) = self.state_mut() {
|
||||
st.doc = before;
|
||||
st.restore_drawing(before);
|
||||
st.selection = selection;
|
||||
}
|
||||
self.echo(format!("Internal error in {id}: {}", crate::guard::message(&*p)));
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
//! AutoLISP's name of an INSERT's ATTRIB keeps naming that attribute when a command, another
|
||||
//! session, another document or another thread gives out handles in the drawing or in a copy of
|
||||
//! it, and installs the result (#1660).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{EntityCodec, IoHooks, set_entity_codec, set_entity_sub_record, set_io, set_object_records};
|
||||
use cadcraft_engine::doc::geom::Vec3;
|
||||
use cadcraft_engine::doc::{Block, Common, Drawing, Entity, EntityKind, Handle, Line, Space};
|
||||
use cadcraft_engine::lisp::value::to_text;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::temp_dir::TempDir;
|
||||
|
||||
fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
set_object_records(cadcraft_io::object_records);
|
||||
set_io(IoHooks {
|
||||
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|e| e.to_string()),
|
||||
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
Session::new()
|
||||
}
|
||||
|
||||
fn eval(s: &mut Session, code: &str) -> String {
|
||||
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||
Ok(Some(Ok(v))) => to_text(&v, true),
|
||||
Ok(Some(Err(e))) => panic!("{code}: {e}"),
|
||||
Ok(None) => panic!("{code}: did not finish"),
|
||||
Err(e) => panic!("{code}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Block K with one attribute, one reference, and `i` naming that reference.
|
||||
fn attributed() -> Session {
|
||||
let mut s = session();
|
||||
s.cmdline(
|
||||
"(progn (entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 1.0))) \
|
||||
(entmake '((0 . \"ATTDEF\") (10 0.0 5.0 0.0) (40 . 2.5) (1 . \"D1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \
|
||||
(entmake '((0 . \"ENDBLK\"))))",
|
||||
)
|
||||
.unwrap();
|
||||
let ins = s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": { "T1": "A1" } })).unwrap();
|
||||
let href = ins["handle"].as_str().unwrap();
|
||||
eval(&mut s, &format!("(setq i (handent \"{href}\"))"));
|
||||
s
|
||||
}
|
||||
|
||||
/// The command line names the reference's first ATTRIB `a`, with `$HANDSEED` one below the top:
|
||||
/// the next handle the drawing, or a copy of it, gives out. The command line does not run the
|
||||
/// after-command pass.
|
||||
fn name_at_top(s: &mut Session) {
|
||||
s.doc_mut().unwrap().handseed = u64::MAX - 1;
|
||||
s.cmdline("(setq a (entnext i))").unwrap();
|
||||
assert_eq!(eval(s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\"");
|
||||
}
|
||||
|
||||
/// Every object's handle: model space, layouts and block definitions.
|
||||
fn every_handle(d: &Drawing) -> Vec<Handle> {
|
||||
let mut v = d.model.handles();
|
||||
for l in &d.layouts {
|
||||
v.extend(l.entities.handles());
|
||||
}
|
||||
for b in d.blocks.values() {
|
||||
v.extend(b.entities.handles());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// `a` still names the attribute, and no object of the drawing is `a`: whatever handles were
|
||||
/// given out, each object keeps its own name.
|
||||
fn assert_kept(s: &mut Session) {
|
||||
assert_eq!(
|
||||
eval(s, "(list (cdr (assoc 0 (entget a))) (cdr (assoc 1 (entget a))))"),
|
||||
"(\"ATTRIB\" \"A1\")",
|
||||
"the old name still means the attribute"
|
||||
);
|
||||
let handles = every_handle(s.doc().unwrap());
|
||||
for h in handles {
|
||||
let hex = h.hex();
|
||||
assert_eq!(eval(s, &format!("(eq a (handent \"{hex}\"))")), "nil", "object {hex} is not the attribute");
|
||||
}
|
||||
}
|
||||
|
||||
/// A line added to `d` with the drawing's next handle.
|
||||
fn add_line(d: &mut Drawing) -> Handle {
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).unwrap()
|
||||
}
|
||||
|
||||
/// After a copy of the drawing took `line`, the name still means the attribute and the line is
|
||||
/// the line.
|
||||
fn assert_line_and_name(s: &mut Session, line: Handle) {
|
||||
assert_kept(s);
|
||||
let hex = line.hex();
|
||||
assert_eq!(eval(s, &format!("(cdr (assoc 0 (entget (handent \"{hex}\"))))")), "\"LINE\"");
|
||||
}
|
||||
|
||||
fn one_line(dir: &TempDir) -> String {
|
||||
let mut d = Drawing::new_metric();
|
||||
add_line(&mut d);
|
||||
dir.file("one-line.dxf", cadcraft_io::write_dxf(&d))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_sessions_read_leaves_a_record_name_alone() {
|
||||
// Session A names an attribute and keeps a copy of its drawing; session B, which named
|
||||
// nothing, is read; then A's copy gives out a handle and A installs it.
|
||||
let mut a = attributed();
|
||||
let b = attributed();
|
||||
name_at_top(&mut a);
|
||||
let mut copy = a.doc().unwrap().clone();
|
||||
let _ = b.doc().unwrap();
|
||||
let line = add_line(&mut copy);
|
||||
*a.doc_mut().unwrap() = copy;
|
||||
assert_line_and_name(&mut a, line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_edited_on_another_thread_leaves_a_record_name_alone() {
|
||||
let mut a = attributed();
|
||||
name_at_top(&mut a);
|
||||
let copy = a.doc().unwrap().clone();
|
||||
let (copy, line) = std::thread::spawn(move || {
|
||||
let mut copy = copy;
|
||||
let line = add_line(&mut copy);
|
||||
(copy, line)
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
*a.doc_mut().unwrap() = copy;
|
||||
assert_line_and_name(&mut a, line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_made_while_another_document_is_current_leaves_a_record_name_alone() {
|
||||
let mut s = attributed();
|
||||
name_at_top(&mut s);
|
||||
let first = s.active;
|
||||
let mut copy = s.doc().unwrap().clone();
|
||||
s.open_drawing(Drawing::new_metric(), "other", None);
|
||||
let _ = s.doc().unwrap();
|
||||
let line = add_line(&mut copy);
|
||||
s.active = first;
|
||||
*s.doc_mut().unwrap() = copy;
|
||||
assert_line_and_name(&mut s, line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_from_file_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
name_at_top(&mut s);
|
||||
let dir = TempDir::new("attrib-insert");
|
||||
let path = one_line(&dir);
|
||||
s.execute("insert", &json!({ "file": path, "name": "SRC", "at": [4.0, 4.0] })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xattach_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
name_at_top(&mut s);
|
||||
let dir = TempDir::new("attrib-xref");
|
||||
let path = one_line(&dir);
|
||||
s.execute("xattach", &json!({ "path": path, "name": "XR", "at": [8.0, 8.0] })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audit_fix_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
{
|
||||
let d = s.doc_mut().unwrap();
|
||||
let line = Entity::new(Handle(0xABC), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }));
|
||||
d.model.push(line.clone());
|
||||
let mut b = Block::new("DUP");
|
||||
b.entities.push(line);
|
||||
d.blocks.insert("DUP".into(), Arc::new(b));
|
||||
}
|
||||
name_at_top(&mut s);
|
||||
s.execute("audit", &json!({ "fix": true })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refclose_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
s.cmdline(
|
||||
"(progn (entmake '((0 . \"BLOCK\") (2 . \"R\") (70 . 0) (10 0.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 2.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"ENDBLK\"))))",
|
||||
)
|
||||
.unwrap();
|
||||
let r = s.execute("insert", &json!({ "name": "R", "at": [0, 0] })).unwrap();
|
||||
s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 1], [3, 1]] })).unwrap();
|
||||
name_at_top(&mut s);
|
||||
s.execute("refclose", &json!({ "save": true })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
@@ -65,9 +65,9 @@ fn burst_matches_many_attributes_without_comparing_every_pair() {
|
||||
#[test]
|
||||
fn attsync_matches_many_definitions_without_comparing_every_pair() {
|
||||
let (mut s, h) = reference(N);
|
||||
let t = std::time::Instant::now();
|
||||
// The adjacent engine unit test checks exact indexed lookup work; this keeps
|
||||
// the same end-to-end ATTSYNC fixture and its result checks.
|
||||
s.execute("attsync", &json!({"name": "B"})).unwrap();
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
// An attribute for each definition (T and the N others), with its default value: the
|
||||
// reference carried none of their tags.
|
||||
let a = attribs(&s, h);
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
use cadcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
use crate::temp_dir::TempDir;
|
||||
|
||||
/// `(findfile name)` as LISP prints it.
|
||||
fn findfile(name: &str) -> String {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
mod angle_prompts;
|
||||
mod angle_settings;
|
||||
mod annotate_options;
|
||||
@@ -12,6 +15,7 @@ mod attdef_command;
|
||||
mod attdisp_attsync;
|
||||
mod attedit_prompts;
|
||||
mod attrib_modes;
|
||||
mod attrib_names;
|
||||
mod attrib_props;
|
||||
mod attribute_tag_matching;
|
||||
mod attribute_tools;
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::dxf_ext::{self, DimVal, K};
|
||||
mod assoc;
|
||||
mod blocks;
|
||||
mod common;
|
||||
#[cfg(test)]
|
||||
pub(crate) use common::{attdef_definition_visits, reset_attdef_definition_visits};
|
||||
mod ctx;
|
||||
mod entity;
|
||||
mod header;
|
||||
@@ -166,6 +168,45 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::Hash
|
||||
(tags, kept)
|
||||
}
|
||||
|
||||
/// One record written after an entity's own, at `index`: an INSERT's ATTRIB, then its SEQEND
|
||||
/// (items of a POLYLINE's sequence are not records `entnext` reaches yet). The record's type name
|
||||
/// and groups without its `0` group; its handle (5) and owner (330) are left out: it has no
|
||||
/// handle of its own in the drawing (the writer makes one per file), and its owner is the entity.
|
||||
/// `None` past the last record, and for an entity written as a single record. AutoLISP's
|
||||
/// `entnext` and `entget` read one record at a time through it, never writing the entity's other
|
||||
/// records.
|
||||
pub fn entity_sub_record(d: &Drawing, e: &Entity, index: usize) -> Option<(String, Vec<Tag>)> {
|
||||
let cadcraft_doc::EntityKind::Insert(i) = &e.kind else { return None };
|
||||
if i.attribs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut w = W {
|
||||
t: Vec::new(),
|
||||
next: d.handseed.max(0x100).saturating_add(0x1000),
|
||||
used: HashSet::new(),
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: HashMap::new(),
|
||||
xdicts: HashMap::new(),
|
||||
};
|
||||
let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() };
|
||||
match i.attribs.get(index) {
|
||||
Some(a) => {
|
||||
let base = d.block(&i.block).and_then(|b| common::attdef_base(b, &a.tag));
|
||||
entity::attrib_record(&mut w, d, e, index, a, base, &cx);
|
||||
}
|
||||
None if index == i.attribs.len() => entity::seqend_record(&mut w, e),
|
||||
None => return None,
|
||||
}
|
||||
let mut tags = w.t.into_iter();
|
||||
let kind = tags.next().filter(|t| t.code == 0).map(|t| t.value.as_str())?;
|
||||
let mut tags: Vec<Tag> = tags.filter(|t| t.code != 5 && t.code != 330).collect();
|
||||
// Strings as AutoLISP sees them (`10^2`, not the file's `10^ 2`), as in `entity_groups`.
|
||||
crate::dxf_read::mtext_dxf::map_text_groups(&kind, &mut tags, crate::dxf_read::mtext_dxf::decode_line);
|
||||
Some((kind, tags))
|
||||
}
|
||||
/// The most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in
|
||||
/// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256),
|
||||
/// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so).
|
||||
|
||||
@@ -1,9 +1,138 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::ctx::{AssocObj, Ctx};
|
||||
use super::{
|
||||
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W,
|
||||
dxf_ext,
|
||||
Attrib, Block, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, HashMap, Lineweight, Text, Transparency,
|
||||
VAlign, Vec3, Version, W, dxf_ext,
|
||||
};
|
||||
|
||||
/// The most ATTDEF tags the definition indexes on one thread hold in all (a block with none
|
||||
/// counts as one). An index that fits but would pass this total drops the indexes already
|
||||
/// stored, then takes their place. A definition with more distinct tags than this is not indexed:
|
||||
/// its state is remembered as too large, and each read of it scans the definition for the first
|
||||
/// matching ATTDEF and keeps nothing, so one block cannot grow the cache past the budget, and the
|
||||
/// written file still takes its properties from the right definition.
|
||||
const MAX_INDEXED_TAGS: usize = 1 << 18;
|
||||
|
||||
/// The most block states remembered as too large to index; past it the list starts again.
|
||||
const MAX_TOO_LARGE: usize = 1 << 10;
|
||||
|
||||
/// For each state of a block definition's entities read on this thread, by its content token
|
||||
/// ([`cadcraft_doc::EntityStore::content_token`]): the handle of the first ATTDEF of each tag
|
||||
/// (upper case). A token names one state of one store, so an index is never used for another
|
||||
/// copy or another edit of the block, and blocks read in turn keep their indexes. A definition
|
||||
/// past [`MAX_INDEXED_TAGS`] has no entry here.
|
||||
#[derive(Default)]
|
||||
struct AttdefIndexes {
|
||||
/// Order tags from the drawing so lookup cost does not depend on hash collisions.
|
||||
by_store: HashMap<u64, BTreeMap<String, Handle>>,
|
||||
/// Tags held in all, for [`MAX_INDEXED_TAGS`].
|
||||
tags: usize,
|
||||
/// States of definitions with more distinct tags than [`MAX_INDEXED_TAGS`], so a read of one
|
||||
/// goes straight to [`scan_attdef`] without building and dropping an index again.
|
||||
too_large: std::collections::HashSet<u64>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ATTDEF_INDEXES: RefCell<AttdefIndexes> = RefCell::new(AttdefIndexes::default());
|
||||
/// Entities of a block definition examined while matching an attribute to its ATTDEF.
|
||||
#[cfg(test)]
|
||||
static ATTDEF_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The first ATTDEF of each tag in `block`, by upper-case tag, when there are at most `budget`
|
||||
/// distinct tags. `None` when another distinct tag would pass `budget`: the partial map is
|
||||
/// dropped, so a prefix is not stored in place of the definition.
|
||||
fn attdef_index_within(block: &Block, budget: usize) -> Option<BTreeMap<String, Handle>> {
|
||||
let mut by_tag = BTreeMap::new();
|
||||
for e in block.entities.iter() {
|
||||
count_attdef_visit();
|
||||
if let EntityKind::AttDef(ad) = &e.kind {
|
||||
let key = ad.tag.to_ascii_uppercase();
|
||||
if by_tag.contains_key(&key) {
|
||||
continue;
|
||||
}
|
||||
if by_tag.len() >= budget {
|
||||
return None;
|
||||
}
|
||||
by_tag.insert(key, e.handle);
|
||||
}
|
||||
}
|
||||
Some(by_tag)
|
||||
}
|
||||
|
||||
/// The first ATTDEF of `block` whose tag matches `tag`, ignoring ASCII case: one pass over the
|
||||
/// definition at most, stopping at the match. Nothing from the scan is stored.
|
||||
fn scan_attdef(block: &Block, tag: &str) -> Option<Handle> {
|
||||
for e in block.entities.iter() {
|
||||
count_attdef_visit();
|
||||
if let EntityKind::AttDef(ad) = &e.kind
|
||||
&& ad.tag.eq_ignore_ascii_case(tag)
|
||||
{
|
||||
return Some(e.handle);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The definition properties of the first ATTDEF in `block` whose tag matches `tag`, ignoring
|
||||
/// ASCII case. Each state of a block's entities that fits in [`MAX_INDEXED_TAGS`] is read once
|
||||
/// on a thread: later attributes, of this reference or another, find their definition in its
|
||||
/// index. A definition with more distinct tags is not stored: the first read of that state builds
|
||||
/// at most [`MAX_INDEXED_TAGS`] index entries, then gives up and remembers the state; every read
|
||||
/// of it scans the definition once at most, stopping at the first match.
|
||||
pub(super) fn attdef_base<'a>(block: &'a Block, tag: &str) -> Option<&'a Common> {
|
||||
let token = block.entities.content_token();
|
||||
let want = tag.to_ascii_uppercase();
|
||||
let found = ATTDEF_INDEXES
|
||||
.try_with(|cell| {
|
||||
let Ok(mut ix) = cell.try_borrow_mut() else { return scan_attdef(block, tag) };
|
||||
if let Some(by_tag) = ix.by_store.get(&token) {
|
||||
return by_tag.get(&want).copied();
|
||||
}
|
||||
if ix.too_large.contains(&token) {
|
||||
return scan_attdef(block, tag);
|
||||
}
|
||||
let Some(by_tag) = attdef_index_within(block, MAX_INDEXED_TAGS) else {
|
||||
if ix.too_large.len() >= MAX_TOO_LARGE {
|
||||
ix.too_large.clear();
|
||||
}
|
||||
ix.too_large.insert(token);
|
||||
return scan_attdef(block, tag);
|
||||
};
|
||||
let found = by_tag.get(&want).copied();
|
||||
let cost = by_tag.len().max(1);
|
||||
if ix.tags.saturating_add(cost) > MAX_INDEXED_TAGS {
|
||||
ix.by_store.clear();
|
||||
ix.tags = 0;
|
||||
}
|
||||
ix.tags = ix.tags.saturating_add(cost);
|
||||
ix.by_store.insert(token, by_tag);
|
||||
found
|
||||
})
|
||||
.unwrap_or_else(|_| scan_attdef(block, tag));
|
||||
block.entities.get(found?).map(|e| &e.common)
|
||||
}
|
||||
|
||||
/// One more definition entity examined (counted in tests).
|
||||
fn count_attdef_visit() {
|
||||
#[cfg(test)]
|
||||
ATTDEF_VISITS.with(|n| n.set(n.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
/// How many definition entities attribute reads have examined on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn attdef_definition_visits() -> u64 {
|
||||
ATTDEF_VISITS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Start a definition-visit count from zero.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset_attdef_definition_visits() {
|
||||
ATTDEF_VISITS.with(|n| n.set(0));
|
||||
}
|
||||
|
||||
/// `AcadAnnotative` xdata marking an annotative style or block.
|
||||
pub(super) fn annotative_xdata(w: &mut W) {
|
||||
w.s(1001, "AcadAnnotative");
|
||||
@@ -146,13 +275,10 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
|
||||
/// definition's, from the block's definitions by tag `defs`; an attribute that takes layer 0 from
|
||||
/// its definition is on the reference's layer, one set on layer 0 itself stays there. Also the
|
||||
/// definition's properties.
|
||||
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
|
||||
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
|
||||
let base = def.map(|de| de.common.clone()).unwrap_or_default();
|
||||
/// Attribute `a` takes its own properties over its definition's. A layer 0 inherited from the
|
||||
/// definition takes the reference's layer; an explicit layer 0 stays. Return both properties.
|
||||
pub(super) fn attrib_common(e: &Entity, a: &Attrib, base: Option<&Common>) -> (Common, Common) {
|
||||
let base = base.cloned().unwrap_or_default();
|
||||
let mut c = a.props.over(&base);
|
||||
if a.props.layer.is_none() && c.layer == "0" {
|
||||
c.layer.clone_from(&e.common.layer);
|
||||
|
||||
@@ -3,7 +3,8 @@ use super::common::{attrib_common, common, common_x, dim_xdata, layer_and_props,
|
||||
use super::ctx::Ctx;
|
||||
use super::layout::paper_view;
|
||||
use super::{
|
||||
Bounds2, Color, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3, Version, W, dxf_ext,
|
||||
Attrib, Bounds2, Color, Common, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3,
|
||||
Version, W, dxf_ext,
|
||||
};
|
||||
|
||||
/// The persistent reactors of boundary objects: each source object of an associative hatch in
|
||||
@@ -425,33 +426,45 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
|
||||
// The block's definitions by tag, gathered once for all the attributes (#1923).
|
||||
let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
|
||||
for (index, a) in i.attribs.iter().enumerate() {
|
||||
let ah = w.h();
|
||||
w.s(0, "ATTRIB");
|
||||
w.s(5, ah);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
let (c, base) = attrib_common(e, &defs, a);
|
||||
layer_and_props(w, &c, Some(&base));
|
||||
// Hidden with its definition (a dynamic block's visibility state hides it).
|
||||
if !base.visible {
|
||||
w.i(60, 1);
|
||||
}
|
||||
w.s(100, "AcDbText");
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
|
||||
if cx.target >= Version::R2007 {
|
||||
multiline_tags(w, a, false);
|
||||
}
|
||||
let base = defs.get(&cadcraft_doc::TagKey(&a.tag)).map(|de| &de.common);
|
||||
attrib_record(w, d, e, index, a, base, cx);
|
||||
}
|
||||
let sh = w.h();
|
||||
w.s(0, "SEQEND");
|
||||
w.s(5, sh);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
w.s(8, &e.common.layer);
|
||||
seqend_record(w, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One ATTRIB record of the block reference `e`, for its attribute `a` (as written after its
|
||||
/// INSERT): its handle is a new one, its owner the reference's.
|
||||
pub(super) fn attrib_record(w: &mut W, d: &Drawing, e: &Entity, index: usize, a: &Attrib, base: Option<&Common>, cx: &Ctx) {
|
||||
let ah = w.h();
|
||||
w.s(0, "ATTRIB");
|
||||
w.s(5, ah);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
let (c, base) = attrib_common(e, a, base);
|
||||
layer_and_props(w, &c, Some(&base));
|
||||
// Hidden with its definition (a dynamic block's visibility state hides it).
|
||||
if !base.visible {
|
||||
w.i(60, 1);
|
||||
}
|
||||
w.s(100, "AcDbText");
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
|
||||
if cx.target >= Version::R2007 {
|
||||
multiline_tags(w, a, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// The SEQEND record that ends a block reference's attributes (written after its last ATTRIB).
|
||||
pub(super) fn seqend_record(w: &mut W, e: &Entity) {
|
||||
let sh = w.h();
|
||||
w.s(0, "SEQEND");
|
||||
w.s(5, sh);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
w.s(8, &e.common.layer);
|
||||
}
|
||||
|
||||
fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) {
|
||||
if let EntityKind::Dimension(dm) = &e.kind {
|
||||
w.s(0, "DIMENSION");
|
||||
|
||||
@@ -40,7 +40,7 @@ pub use cadcraft_doc::Format;
|
||||
pub use craft_dxf::Version;
|
||||
pub use dxf_raw::{ObjectRecord, object_records};
|
||||
pub use dxf_read::entity_from_groups;
|
||||
pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost};
|
||||
pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, entity_sub_record, proxies_lost};
|
||||
pub use pdf::{PdfOptions, pdf, plot};
|
||||
|
||||
/// How a drawing is saved as DXF or DWG.
|
||||
|
||||
@@ -5487,3 +5487,324 @@ fn a_layer_state_saved_before_masks_restores_everything() {
|
||||
let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect();
|
||||
assert_eq!(got, [("S", LayerState::ALL, "", "")]);
|
||||
}
|
||||
|
||||
/// The value of group `code` in `tags`.
|
||||
fn tag_text(tags: &[craft_dxf::Tag], code: i32) -> Option<String> {
|
||||
tags.iter().find(|t| t.code == code).map(craft_dxf::Tag::str)
|
||||
}
|
||||
|
||||
/// An INSERT with two attributes, for the records written after it (#1660).
|
||||
fn insert_with_attribs() -> (Drawing, Handle) {
|
||||
let text = |value: &str| Text {
|
||||
insert: Vec3::new(1.0, 2.0, 0.0),
|
||||
align_pt: None,
|
||||
height: 2.5,
|
||||
value: value.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: HAlign::Left,
|
||||
valign: VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
};
|
||||
let attrib = |tag: &str, value: &str| Attrib {
|
||||
tag: tag.into(),
|
||||
text: text(value),
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: AttribProps::default(),
|
||||
multiline: None,
|
||||
modes: AttribModes::default(),
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
let insert =
|
||||
Insert { block: "B".into(), insert: Vec3::new(10.0, 10.0, 0.0), attribs: vec![attrib("T1", "A1"), attrib("T2", "A2")], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
(d, h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inserts_records_are_read_one_at_a_time() {
|
||||
let (mut d, h) = insert_with_attribs();
|
||||
let e = d.entity(h).expect("the reference");
|
||||
// The reference's own list is its record, with no attribute in it.
|
||||
let (kind, own) = entity_groups(&d, e);
|
||||
assert_eq!(kind, "INSERT");
|
||||
assert_eq!(tag_text(&own, 66).as_deref(), Some("1"));
|
||||
// The records after it: each attribute, then the SEQEND.
|
||||
let first = entity_sub_record(&d, e, 0).expect("the first attribute");
|
||||
assert_eq!(first.0, "ATTRIB");
|
||||
assert_eq!((tag_text(&first.1, 2).as_deref(), tag_text(&first.1, 1).as_deref()), (Some("T1"), Some("A1")));
|
||||
assert_eq!(tag_text(&first.1, 10).as_deref(), Some("1.0"), "its place is written as for the file");
|
||||
let second = entity_sub_record(&d, e, 1).expect("the second attribute");
|
||||
assert_eq!((tag_text(&second.1, 2).as_deref(), tag_text(&second.1, 1).as_deref()), (Some("T2"), Some("A2")));
|
||||
let seqend = entity_sub_record(&d, e, 2).expect("the SEQEND");
|
||||
assert_eq!(seqend.0, "SEQEND");
|
||||
assert!(entity_sub_record(&d, e, 3).is_none(), "past the last record");
|
||||
// They have no handle or owner of their own in the drawing: their names are LISP's.
|
||||
for tags in [&first.1, &second.1, &seqend.1] {
|
||||
assert!(tags.iter().all(|t| t.code != 5 && t.code != 330), "{tags:?}");
|
||||
}
|
||||
// An entity with no records after it has none, at any index.
|
||||
let line = d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).expect("line");
|
||||
let e = d.entity(line).expect("the line");
|
||||
assert!(entity_sub_record(&d, e, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attributes_value_reads_as_lisp_text() {
|
||||
let (mut d, h) = insert_with_attribs();
|
||||
// A caret is written `^ ` and read back as the caret LISP typed: what `entget` lists is
|
||||
// what `entmod` takes again.
|
||||
d.modify_entity(h, |e| {
|
||||
if let EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.first_mut()
|
||||
{
|
||||
a.text.value = "10^2".into();
|
||||
}
|
||||
})
|
||||
.expect("modify");
|
||||
let e = d.entity(h).expect("the reference");
|
||||
let (_, tags) = entity_sub_record(&d, e, 0).expect("the first attribute");
|
||||
assert_eq!(tag_text(&tags, 1).as_deref(), Some("10^2"));
|
||||
}
|
||||
|
||||
/// Reading every attribute of one reference examines the block definition once, and an edit of
|
||||
/// the definition once more.
|
||||
#[test]
|
||||
fn reading_attributes_scans_the_definition_once() {
|
||||
const M: usize = 32;
|
||||
let tags: Vec<String> = (0..M).map(|i| format!("T{i}")).collect();
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = add_attributed(&mut d, "B", 1, &tags, "WALLS");
|
||||
crate::dxf_write::reset_attdef_definition_visits();
|
||||
let e = d.entity(h).expect("the reference").clone();
|
||||
for i in 0..M {
|
||||
let (kind, tags) = entity_sub_record(&d, &e, i).expect("attribute");
|
||||
assert_eq!(kind, "ATTRIB");
|
||||
assert_eq!(tag_text(&tags, 8).as_deref(), Some("WALLS"));
|
||||
}
|
||||
assert_eq!(crate::dxf_write::attdef_definition_visits(), M as u64, "one pass over the definition, not one scan per attribute");
|
||||
// An edit of the definition is read on the next read, with one more pass.
|
||||
set_attdef_layer(&mut d, "B", "DOOR");
|
||||
let before = crate::dxf_write::attdef_definition_visits();
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("DOOR"));
|
||||
assert_eq!(crate::dxf_write::attdef_definition_visits() - before, M as u64, "the edit builds the index once");
|
||||
}
|
||||
|
||||
/// An attribute with value V and `tag`, for the definition tests below.
|
||||
fn plain_attrib(tag: &str) -> Attrib {
|
||||
Attrib {
|
||||
tag: tag.into(),
|
||||
text: Text {
|
||||
insert: Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 1.0,
|
||||
value: "V".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: HAlign::Left,
|
||||
valign: VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
},
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: AttribProps::default(),
|
||||
multiline: None,
|
||||
modes: AttribModes::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Block `name` with an ATTDEF per tag on `layer`, its handles from `first` up, and a reference
|
||||
/// to it with the same attributes. The reference's handle.
|
||||
fn add_attributed(d: &mut Drawing, name: &str, first: u64, tags: &[String], layer: &str) -> Handle {
|
||||
let mut block = Block::new(name);
|
||||
for (i, tag) in tags.iter().enumerate() {
|
||||
let mut e = Entity::new(Handle(first + i as u64), EntityKind::AttDef(plain_attrib(tag)));
|
||||
e.common.layer = layer.into();
|
||||
block.entities.push(e);
|
||||
}
|
||||
d.blocks.insert(name.into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: name.into(), attribs: tags.iter().map(|t| plain_attrib(t)).collect(), ..Insert::default() };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add")
|
||||
}
|
||||
|
||||
/// Block `name`'s first ATTDEF moved to `layer`: one edit of the definition's store.
|
||||
fn set_attdef_layer(d: &mut Drawing, name: &str, layer: &str) {
|
||||
let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block"));
|
||||
let h = b.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).expect("an ATTDEF");
|
||||
assert!(b.entities.modify(h, |e| e.common.layer = layer.into()));
|
||||
}
|
||||
|
||||
/// Block B with ATTDEF T on layer BASE and ATTDEF U on layer DOOR, and a reference to it with
|
||||
/// both attributes. The reference's handle.
|
||||
fn add_on_two_layers(d: &mut Drawing) -> Handle {
|
||||
let h = add_attributed(d, "B", 1, &["T".to_string(), "U".to_string()], "DOOR");
|
||||
set_attdef_layer(d, "B", "BASE");
|
||||
h
|
||||
}
|
||||
|
||||
/// Block `name`'s ATTDEFs given `tags` in their order, so a tag can pass to another ATTDEF's
|
||||
/// handle: one edit of the definition's store for each ATTDEF.
|
||||
fn set_attdef_tags(d: &mut Drawing, name: &str, tags: &[&str]) {
|
||||
let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block"));
|
||||
let handles: Vec<Handle> = b.entities.iter().filter(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).collect();
|
||||
assert_eq!(handles.len(), tags.len(), "a tag for each ATTDEF");
|
||||
for (h, tag) in handles.into_iter().zip(tags) {
|
||||
assert!(b.entities.modify(h, |e| {
|
||||
if let EntityKind::AttDef(ad) = &mut e.kind {
|
||||
ad.tag = (*tag).into();
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer reference `h`'s first ATTRIB record is read on.
|
||||
fn read_attrib_layer(d: &Drawing, h: Handle) -> Option<String> {
|
||||
let e = d.entity(h)?;
|
||||
let (_, tags) = entity_sub_record(d, e, 0)?;
|
||||
tag_text(&tags, 8)
|
||||
}
|
||||
|
||||
/// The layer the first ATTRIB of `d`'s DXF is written on.
|
||||
fn written_attrib_layer(d: &Drawing) -> Option<String> {
|
||||
let text = write_dxf(d);
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = lines.windows(2).position(|w| w == ["0", "ATTRIB"])?;
|
||||
let pairs = lines.get(at + 2..)?.chunks(2);
|
||||
pairs.take_while(|p| p.first() != Some(&"0")).find(|p| p.first() == Some(&"8")).and_then(|p| p.get(1)).map(|s| s.to_string())
|
||||
}
|
||||
|
||||
/// Two copies of one drawing, each with its definition edited: each reads and writes its own
|
||||
/// definition's properties, whichever was read first. T stays with the first ATTDEF in one copy
|
||||
/// and passes to the second in the other, so an index kept from one copy names the wrong ATTDEF
|
||||
/// in the other.
|
||||
#[test]
|
||||
fn copies_edited_apart_read_their_own_definitions() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = add_on_two_layers(&mut d);
|
||||
let (mut a, mut b) = (d.clone(), d.clone());
|
||||
set_attdef_layer(&mut a, "B", "WALLS");
|
||||
set_attdef_tags(&mut b, "B", &["U", "T"]);
|
||||
assert_eq!(read_attrib_layer(&a, h).as_deref(), Some("WALLS"));
|
||||
assert_eq!(read_attrib_layer(&b, h).as_deref(), Some("DOOR"), "the other copy's edit is its own");
|
||||
assert_eq!(written_attrib_layer(&b).as_deref(), Some("DOOR"));
|
||||
assert_eq!(written_attrib_layer(&a).as_deref(), Some("WALLS"));
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("BASE"), "the drawing both came from is unchanged");
|
||||
}
|
||||
|
||||
/// Undo back to a state, then a different edit of the definition: the edit that was undone is
|
||||
/// not read or written again. The second edit passes T to the other ATTDEF, so the index of
|
||||
/// the undone edit names the wrong one.
|
||||
#[test]
|
||||
fn an_edit_after_undo_reads_its_own_definition() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = add_on_two_layers(&mut d);
|
||||
let mut undone = d.clone();
|
||||
set_attdef_layer(&mut undone, "B", "WALLS");
|
||||
assert_eq!(read_attrib_layer(&undone, h).as_deref(), Some("WALLS"));
|
||||
// Undo: the drawing before the edit, then another edit, read nothing in between.
|
||||
let mut redone = d.clone();
|
||||
set_attdef_tags(&mut redone, "B", &["U", "T"]);
|
||||
assert_eq!(written_attrib_layer(&redone).as_deref(), Some("DOOR"));
|
||||
assert_eq!(read_attrib_layer(&redone, h).as_deref(), Some("DOOR"));
|
||||
}
|
||||
|
||||
/// Reads that alternate between two references of two blocks examine each definition once.
|
||||
#[test]
|
||||
fn alternating_definitions_are_each_indexed_once() {
|
||||
const M: usize = 64;
|
||||
let tags: Vec<String> = (0..M).map(|i| format!("T{i}")).collect();
|
||||
let mut d = Drawing::new_metric();
|
||||
let first = add_attributed(&mut d, "B1", 1, &tags, "ONE");
|
||||
let second = add_attributed(&mut d, "B2", 1 + M as u64, &tags, "TWO");
|
||||
let (first, second) = (d.entity(first).expect("first").clone(), d.entity(second).expect("second").clone());
|
||||
crate::dxf_write::reset_attdef_definition_visits();
|
||||
for i in 0..M {
|
||||
for (e, layer) in [(&first, "ONE"), (&second, "TWO")] {
|
||||
let (_, tags) = entity_sub_record(&d, e, i).expect("attribute");
|
||||
assert_eq!(tag_text(&tags, 8).as_deref(), Some(layer));
|
||||
}
|
||||
}
|
||||
assert_eq!(crate::dxf_write::attdef_definition_visits(), 2 * M as u64, "each definition is read once, not once per read");
|
||||
}
|
||||
|
||||
/// Of two ATTDEFs whose tags differ only in case, the first is the attribute's definition.
|
||||
#[test]
|
||||
fn the_first_definition_of_a_tag_in_any_case_is_used() {
|
||||
let mut block = Block::new("C");
|
||||
for (i, (tag, layer)) in [("t", "FIRST"), ("T", "SECOND")].into_iter().enumerate() {
|
||||
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag)));
|
||||
e.common.layer = layer.into();
|
||||
block.entities.push(e);
|
||||
}
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("C".into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: "C".into(), attribs: vec![plain_attrib("T")], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
|
||||
}
|
||||
|
||||
/// A definition with more distinct tags than the index may store (`1 << 18`) is not cached.
|
||||
/// The first read builds and drops one bounded index and remembers the state; later reads go
|
||||
/// straight to one scan that stops at the first match. The first ATTDEF of the tag still wins,
|
||||
/// in any case.
|
||||
#[test]
|
||||
fn an_oversized_definition_is_not_indexed() {
|
||||
const LIMIT: usize = 1 << 18;
|
||||
// One extra distinct tag past the budget, plus a second ATTDEF of the first tag in
|
||||
// another case, so the first match is not the only entity of that tag.
|
||||
let mut tags = Vec::with_capacity(LIMIT + 2);
|
||||
tags.push("Ab".to_string());
|
||||
tags.push("AB".to_string());
|
||||
for i in 0..LIMIT {
|
||||
tags.push(format!("U{i}"));
|
||||
}
|
||||
let mut block = Block::new("HUGE");
|
||||
for (i, tag) in tags.iter().enumerate() {
|
||||
let layer = if i == 0 { "FIRST" } else { "SECOND" };
|
||||
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag)));
|
||||
e.common.layer = layer.into();
|
||||
block.entities.push(e);
|
||||
}
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("HUGE".into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib("ab")], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
crate::dxf_write::reset_attdef_definition_visits();
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
|
||||
let first = crate::dxf_write::attdef_definition_visits();
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
|
||||
let second = crate::dxf_write::attdef_definition_visits() - first;
|
||||
// The failed index walks every entity (the last tag is the one past the budget), then
|
||||
// the scan reads the first entity, where the tag matches.
|
||||
assert_eq!(first, (LIMIT as u64) + 3, "one bounded pass, then the first match");
|
||||
assert_eq!(second, 1, "the state is remembered as too large: the next read scans to the first match only");
|
||||
}
|
||||
|
||||
/// An attribute whose ATTDEF lies past the index budget, at the end of an oversized definition,
|
||||
/// still reads and writes that definition's properties: the scan for a definition past the
|
||||
/// budget covers all of it.
|
||||
#[test]
|
||||
fn a_definition_past_the_index_budget_matches_its_last_tag() {
|
||||
const LIMIT: usize = 1 << 18;
|
||||
let mut block = Block::new("HUGE");
|
||||
for i in 0..=LIMIT {
|
||||
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(&format!("U{i}"))));
|
||||
e.common.layer = if i == LIMIT { "LAST".into() } else { "OTHER".into() };
|
||||
block.entities.push(e);
|
||||
}
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("HUGE".into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib(&format!("u{LIMIT}"))], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("LAST"), "entget reads the matching definition");
|
||||
assert_eq!(written_attrib_layer(&d).as_deref(), Some("LAST"), "the written ATTRIB keeps the definition's layer");
|
||||
}
|
||||
|
||||
@@ -552,9 +552,23 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
y += 44.0;
|
||||
}
|
||||
let main = Rect::from_min_max(pos2(left.right() + 36.0, r.top() + 40.0), r.max);
|
||||
p.text(main.min, egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
|
||||
let mut local_top = main.top();
|
||||
if app.file_providers.enabled() {
|
||||
let mut provider_ui = ui.new_child(egui::UiBuilder::new().max_rect(main).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
let resource = egui::ScrollArea::vertical()
|
||||
.id_salt("provider-recents")
|
||||
.max_height((r.height() * 0.4).clamp(80.0, 240.0))
|
||||
.show(&mut provider_ui, |ui| app.file_providers.provider_recent_ui(ui))
|
||||
.inner;
|
||||
app.file_providers.device_recent_ui(&mut provider_ui);
|
||||
local_top += provider_ui.min_rect().height() + 20.0;
|
||||
if let Some(resource) = resource {
|
||||
let _ = app.run(crate::menus::PROVIDER_RECENT_OPEN, serde_json::json!({"resource":resource}));
|
||||
}
|
||||
}
|
||||
p.text(pos2(main.left(), local_top), egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
|
||||
let mut recent = None;
|
||||
let mut y = main.top() + 44.0;
|
||||
let mut y = local_top + 44.0;
|
||||
for (i, path) in app.ui.recent_files.iter().enumerate() {
|
||||
let row = Rect::from_min_size(pos2(main.left(), y), vec2((r.right() - main.left() - 36.0).clamp(0.0, 640.0), 42.0));
|
||||
let resp = ui.interact(row, ui.scope_id().with(("recent", i)), Sense::click());
|
||||
|
||||
@@ -68,6 +68,10 @@ impl CadApp {
|
||||
/// about each drawing first and quit once all are dealt with. Returns whether the close has to
|
||||
/// wait (the caller then cancels the window close).
|
||||
pub fn request_quit(&mut self) -> bool {
|
||||
if self.file_providers.busy() {
|
||||
self.set_status("Finish or cancel the pending file provider operation before quitting");
|
||||
return true;
|
||||
}
|
||||
if self.quit_confirmed || !self.session.docs.iter().any(|d| d.is_dirty()) {
|
||||
return false;
|
||||
}
|
||||
@@ -171,6 +175,10 @@ impl CadApp {
|
||||
}
|
||||
|
||||
fn begin_close(&mut self, uids: Vec<u64>) {
|
||||
if self.file_providers.busy() {
|
||||
self.set_status("Finish or cancel the pending file provider operation before closing");
|
||||
return;
|
||||
}
|
||||
if self.closing.is_some() {
|
||||
// A prompt is already open; it has to be answered first.
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! DXF capture over the existing format hooks; no storage backend or filesystem authority.
|
||||
use crate::{CadApp, file_providers::Action};
|
||||
use cadcraft_engine::cmd::file::{self, SaveAs};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(crate) fn save(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
|
||||
let result = capture(app, save_as);
|
||||
if let Err(error) = &result {
|
||||
app.session.echo(error.clone());
|
||||
app.set_status(error.clone());
|
||||
}
|
||||
result
|
||||
}
|
||||
/// Queue a provider read through CadApp::run without creating a filesystem picker.
|
||||
pub(crate) fn open_recent(app: &mut CadApp, params: &Value) -> Result<Value, String> {
|
||||
let result = params
|
||||
.get("resource")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| "a file provider resource ID is required".to_string())
|
||||
.and_then(|resource| app.file_providers.request_open(resource))
|
||||
.map(|request| json!({"pending":"fileProvider","requestId":request}));
|
||||
if let Err(error) = &result {
|
||||
app.session.echo(error.clone());
|
||||
app.set_status(error.clone());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn capture(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
|
||||
let host = app.file_providers.clone();
|
||||
let state = app.session.state().map_err(|e| e.to_string())?;
|
||||
if host.pending_for(state.uid) {
|
||||
return Err("a provider save is already pending for this drawing".into());
|
||||
}
|
||||
if state.block_unsaved() {
|
||||
return Err("save or discard Block Editor changes before saving with a provider".into());
|
||||
}
|
||||
let drawing = state.drawing();
|
||||
// This single-file transfer does not upload external image or drawing bytes.
|
||||
if has_external_files(drawing) {
|
||||
return Err(
|
||||
"DXF references external images or drawings; make a self-contained drawing before provider save (external files are not uploaded)".into(),
|
||||
);
|
||||
}
|
||||
let mut name = host.bound_filename(state.uid).unwrap_or_else(|| match state.title.rsplit_once('.') {
|
||||
Some((_, extension)) if extension.eq_ignore_ascii_case("dxf") => state.title.clone(),
|
||||
Some((stem, extension)) if extension.eq_ignore_ascii_case("dwg") => format!("{stem}.dxf"),
|
||||
_ => format!("{}.dxf", state.title),
|
||||
});
|
||||
if name.trim() == ".dxf" {
|
||||
name = "Drawing.dxf".into();
|
||||
}
|
||||
let bytes = match file::write_as() {
|
||||
Some(writer) => writer(drawing, &name, &SaveAs::default())?,
|
||||
None => (file::io().ok_or("file formats are unavailable")?.write)(drawing, &name)?,
|
||||
};
|
||||
let request = host.begin(vec![state.clone()], state.uid, state.revision, name, bytes, save_as)?;
|
||||
app.set_status("Choose where to save the DXF drawing");
|
||||
Ok(json!({"pending":"fileProvider","requestId":request}))
|
||||
}
|
||||
pub(crate) fn tick(app: &mut CadApp) {
|
||||
let host = app.file_providers.clone();
|
||||
if !host.connected() {
|
||||
return;
|
||||
}
|
||||
for action in host.take_actions() {
|
||||
match action {
|
||||
Action::Save { request, capture, status, resource } => {
|
||||
let alive = app.session.docs.iter().any(|d| d.uid == capture.doc);
|
||||
if status == "saved" {
|
||||
for snapshot in &capture.snapshots {
|
||||
if let Some(doc) = app.session.docs.iter_mut().find(|d| d.uid == snapshot.uid) {
|
||||
doc.saved = snapshot.drawing().clone();
|
||||
doc.path = None;
|
||||
}
|
||||
}
|
||||
app.set_status("Drawing saved with file provider");
|
||||
} else if status == "failed" {
|
||||
app.set_status("File provider save failed; drawing remains unsaved");
|
||||
}
|
||||
host.finish_save(&request, &capture, &status, &resource, alive);
|
||||
}
|
||||
Action::Open { request, resource, name, bytes } => {
|
||||
let result = open_resource(app, &resource, &name, &bytes);
|
||||
if let Err(error) = &result {
|
||||
app.open_failed(error);
|
||||
}
|
||||
host.finish_open(&request, &resource, &name, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
host.refresh(app.session.docs.iter().map(|d| (d.uid, d.revision, d.title.clone(), d.is_dirty())).collect());
|
||||
}
|
||||
|
||||
/// The same modeled dependency boundary applies before provider Save and Open. In particular,
|
||||
/// provider bytes must not reach native OPEN's automatic IMAGE/XREF filesystem loaders.
|
||||
fn has_external_files(drawing: &cadcraft_doc::Drawing) -> bool {
|
||||
drawing
|
||||
.model
|
||||
.iter()
|
||||
.chain(drawing.layouts.iter().flat_map(|layout| layout.entities.iter()))
|
||||
.chain(drawing.blocks.values().flat_map(|block| block.entities.iter()))
|
||||
.any(|entity| matches!(&entity.kind, cadcraft_doc::EntityKind::Image(image) if !image.path.is_empty()))
|
||||
|| drawing.blocks.values().any(|block| block.xref_path.as_ref().is_some_and(|path| !path.is_empty()))
|
||||
}
|
||||
|
||||
fn open_resource(app: &mut CadApp, resource: &str, name: &str, bytes: &[u8]) -> Result<u64, String> {
|
||||
if let Some((index, uid)) =
|
||||
app.file_providers.bound_document(resource).and_then(|uid| app.session.docs.iter().position(|doc| doc.uid == uid).map(|index| (index, uid)))
|
||||
{
|
||||
return app.run("document.switch", json!({"index":index})).map(|_| uid);
|
||||
}
|
||||
// Host admission already bounds these bytes. Preflight with the installed native decoder,
|
||||
// before any document is opened or the unchanged native command follows external paths.
|
||||
// The actual Open still runs through CadApp's existing command route and format hooks.
|
||||
let hooks = file::io().ok_or("file formats are unavailable")?;
|
||||
// `catch_unwind` only helps native builds: a panic aborts on wasm, where this bridge runs, so the
|
||||
// readers must stay panic-free and nothing here may rely on recovering from one.
|
||||
let drawing = std::panic::catch_unwind(|| (hooks.read)(bytes, name)).map_err(|_| "file provider drawing decoder failed".to_string())??;
|
||||
if has_external_files(&drawing) {
|
||||
return Err(
|
||||
"DXF references external images or drawings; open a self-contained drawing with the file provider (external files are not loaded)".into(),
|
||||
);
|
||||
}
|
||||
drop(drawing);
|
||||
app.run("open", json!({"data":file::base64_encode(bytes),"name":name})).and_then(|value| {
|
||||
app.opened(Ok(value));
|
||||
app.session.state().map(|doc| doc.uid).map_err(|error| error.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,210 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use cadcraft_engine::Session;
|
||||
fn pending() -> (CadApp, String, u64) {
|
||||
let app = CadApp::new(Session::new(), crate::Services::default());
|
||||
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
|
||||
let doc = app.session.state().unwrap().clone();
|
||||
let uid = doc.uid;
|
||||
// Lifecycle fixture: a fake capture is isolated from the engine's process-global format hooks.
|
||||
let request = app.file_providers.begin(vec![doc.clone()], uid, doc.revision, "Drawing.dxf".into(), vec![1], false).unwrap();
|
||||
(app, request, uid)
|
||||
}
|
||||
#[test]
|
||||
fn rejected_provider_save_is_reported_without_consuming_the_capture() {
|
||||
let (mut app, _, uid) = pending();
|
||||
let error = save(&mut app, false).unwrap_err();
|
||||
assert!(error.contains("already pending"));
|
||||
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
|
||||
assert_eq!(app.session.log.last(), Some(&error));
|
||||
assert!(app.file_providers.pending_for(uid));
|
||||
}
|
||||
#[test]
|
||||
fn ack_owns_its_document_and_does_not_clean_newer_edits() {
|
||||
let (mut app, request, uid) = pending();
|
||||
app.file_providers.resolve_dialog(&request, "provider", "Drawing.dxf").unwrap();
|
||||
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
|
||||
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
|
||||
app.session.new_drawing(false);
|
||||
app.file_providers.result(request, "saved".into(), "drawing-1".into()).unwrap();
|
||||
tick(&mut app);
|
||||
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
|
||||
assert_eq!(app.file_providers.bound_document("drawing-1"), Some(uid));
|
||||
}
|
||||
#[test]
|
||||
fn device_result_is_terminal_without_claiming_durable_storage() {
|
||||
let (mut app, request, uid) = pending();
|
||||
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
|
||||
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
|
||||
app.file_providers.resolve_dialog(&request, "device", "Drawing.dxf").unwrap();
|
||||
app.file_providers.result(request, "download".into(), String::new()).unwrap();
|
||||
tick(&mut app);
|
||||
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
|
||||
assert!(app.file_providers.bound_document("drawing-1").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_dxf_delivery_failure_preserves_the_owned_drawing_and_later_edits_through_retry() {
|
||||
let mut app = CadApp::new(Session::new(), crate::Services::default());
|
||||
app.run("line", json!({"points":[[0,0],[10,10]]})).unwrap();
|
||||
let host = app.file_providers.clone();
|
||||
host.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
host.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
|
||||
let snapshot = app.session.state().unwrap().clone();
|
||||
let uid = snapshot.uid;
|
||||
let checkpoint = snapshot.saved.clone();
|
||||
// Use the actual native drawing codec without mutating process-global engine hooks.
|
||||
let bytes = cadcraft_io::write(&snapshot.doc, "Owned.dxf").unwrap();
|
||||
assert_eq!(cadcraft_io::read(&bytes, "Owned.dxf").unwrap().model.len(), snapshot.doc.model.len());
|
||||
let request = host.begin(vec![snapshot.clone()], uid, snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
|
||||
host.take_events();
|
||||
host.resolve_dialog(&request, "provider", "Owned.dxf").unwrap();
|
||||
app.run("line", json!({"points":[[20,20],[30,30]]})).unwrap();
|
||||
let later_revision = app.session.state().unwrap().revision;
|
||||
app.session.new_drawing(false);
|
||||
let active = app.session.state().unwrap().uid;
|
||||
assert!(host.publish_events_with(
|
||||
|metadata, bytes| {
|
||||
assert_eq!(metadata["type"], "save");
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert!(bytes.is_some_and(|bytes| !bytes.is_empty()));
|
||||
Err("synthetic native delivery exception")
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert!(host.pending_for(uid));
|
||||
tick(&mut app);
|
||||
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
|
||||
assert_eq!(owned.revision, later_revision);
|
||||
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &checkpoint));
|
||||
assert_eq!(app.session.state().unwrap().uid, active);
|
||||
assert!(app.status.as_ref().unwrap().0.contains("File provider save failed"));
|
||||
assert!(host.result(request.clone(), "saved".into(), "late".into()).is_err());
|
||||
let mut failed = 0;
|
||||
assert!(!host.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert_eq!(metadata["type"], "saveFailed");
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert_eq!(metadata["documentId"], uid.to_string());
|
||||
failed += 1;
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(failed, 1);
|
||||
assert!(!host.busy());
|
||||
let retry_snapshot = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap().clone();
|
||||
let bytes = cadcraft_io::write(&retry_snapshot.doc, "Owned.dxf").unwrap();
|
||||
let retry = host.begin(vec![retry_snapshot.clone()], uid, retry_snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
|
||||
host.take_events();
|
||||
host.resolve_dialog(&retry, "provider", "Owned.dxf").unwrap();
|
||||
assert!(!host.publish_events_with(
|
||||
|metadata, bytes| {
|
||||
assert_eq!(metadata["requestId"], retry);
|
||||
assert_eq!(cadcraft_io::read(&bytes.unwrap(), "Owned.dxf").unwrap().model.len(), retry_snapshot.doc.model.len());
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
let index = app.session.docs.iter().position(|doc| doc.uid == uid).unwrap();
|
||||
app.run("document.switch", json!({"index":index})).unwrap();
|
||||
app.run("line", json!({"points":[[40,40],[50,50]]})).unwrap();
|
||||
let current_revision = app.session.state().unwrap().revision;
|
||||
let back = app.session.docs.iter().position(|doc| doc.uid == active).unwrap();
|
||||
app.run("document.switch", json!({"index":back})).unwrap();
|
||||
host.result(retry.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
tick(&mut app);
|
||||
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
|
||||
assert_eq!(owned.revision, current_revision);
|
||||
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &retry_snapshot.doc));
|
||||
assert_eq!(app.session.state().unwrap().uid, active);
|
||||
assert_eq!(host.bound_document("file-1"), Some(uid));
|
||||
assert_eq!(host.take_events()[0].metadata["type"], "saved");
|
||||
assert!(!host.busy());
|
||||
}
|
||||
|
||||
fn recent_provider_app() -> CadApp {
|
||||
let app = CadApp::new(Session::new(), crate::Services::default());
|
||||
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
let connection = app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
|
||||
app.file_providers
|
||||
.set_resources(
|
||||
&connection,
|
||||
vec![
|
||||
crate::file_providers::Resource { id: "owned".into(), name: "Owned.dxf".into(), updated_at: String::new() },
|
||||
crate::file_providers::Resource { id: "other".into(), name: "Other.dxf".into(), updated_at: String::new() },
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
app.file_providers.take_events();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_recent_command_queues_only_the_selected_resource_without_retargeting_the_drawing() {
|
||||
let mut app = recent_provider_app();
|
||||
let before = app.session.state().unwrap().clone();
|
||||
let local = app.ui.recent_files.clone();
|
||||
assert!(crate::menus::is_ui_command(crate::menus::PROVIDER_RECENT_OPEN));
|
||||
let result = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap();
|
||||
assert_eq!(result["pending"], "fileProvider");
|
||||
let events = app.file_providers.take_events();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].metadata["type"], "openRequested");
|
||||
assert_eq!(events[0].metadata["resourceId"], "owned");
|
||||
assert_eq!(events[0].metadata["requestId"], result["requestId"]);
|
||||
let after = app.session.state().unwrap();
|
||||
assert_eq!((after.uid, after.revision), (before.uid, before.revision));
|
||||
assert!(std::sync::Arc::ptr_eq(&after.doc, &before.doc));
|
||||
assert_eq!(after.path, before.path);
|
||||
assert_eq!(app.ui.recent_files, local);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_recent_command_backpressure_remains_in_status_and_command_history() {
|
||||
let mut app = recent_provider_app();
|
||||
let mut full = false;
|
||||
for _ in 0..128 {
|
||||
if app.file_providers.request_open("owned").is_err() {
|
||||
full = true;
|
||||
break;
|
||||
}
|
||||
app.file_providers.take_events();
|
||||
}
|
||||
assert!(full, "the fixture must reach the actual bounded read capacity");
|
||||
let before = app.session.state().unwrap().clone();
|
||||
let error = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
|
||||
assert!(app.file_providers.take_events().is_empty(), "a refused command cannot publish a partial read");
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| app.logic(ctx));
|
||||
output.textures_delta.clear();
|
||||
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
|
||||
assert_eq!(app.session.log.last(), Some(&error));
|
||||
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_recent_command_rejects_malformed_and_disabled_requests_without_opening_files() {
|
||||
let mut app = CadApp::new(Session::new(), crate::Services::default());
|
||||
let before = app.session.state().unwrap().clone();
|
||||
for params in [Value::Null, json!({}), json!({"resource":42}), json!({"resource":""}), json!({"resource":"owned"})] {
|
||||
assert!(app.run(crate::menus::PROVIDER_RECENT_OPEN, params).is_err());
|
||||
assert!(!app.file_providers.enabled());
|
||||
assert!(app.file_providers.take_events().is_empty());
|
||||
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
|
||||
assert!(std::sync::Arc::ptr_eq(&app.session.state().unwrap().doc, &before.doc));
|
||||
}
|
||||
|
||||
let mut connected = recent_provider_app();
|
||||
let before = connected.session.state().unwrap().clone();
|
||||
let connection = connected.file_providers.snapshot()["connectionId"].clone();
|
||||
connected.file_providers.set_enabled(false).unwrap();
|
||||
connected.file_providers.take_events();
|
||||
let error = connected.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
|
||||
assert!(connected.file_providers.connected() && !connected.file_providers.enabled());
|
||||
assert_eq!(connected.file_providers.snapshot()["connectionId"], connection);
|
||||
assert!(connected.file_providers.take_events().is_empty());
|
||||
assert!(std::sync::Arc::ptr_eq(&connected.session.state().unwrap().doc, &before.doc));
|
||||
assert_eq!(connected.session.log.last(), Some(&error));
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Optional same-origin storage capability. No provider is enabled by default.
|
||||
//!
|
||||
//! Requests own immutable native project captures. A host result never selects a live tab,
|
||||
//! revision, filesystem path or account. This module contains no storage or authentication.
|
||||
use cadcraft_engine::DocState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
const MAX_BYTES: usize = 80 * 1024 * 1024;
|
||||
const MAX_PENDING: usize = 16;
|
||||
const MAX_EVENTS: usize = 64;
|
||||
const MAX_RESOURCES: usize = 100;
|
||||
const EXTENSION: &str = ".dxf";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Resource {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub updated_at: String,
|
||||
}
|
||||
pub struct Event {
|
||||
pub metadata: Value,
|
||||
pub bytes: Option<Vec<u8>>,
|
||||
}
|
||||
impl Event {
|
||||
fn terminal(&self) -> bool {
|
||||
matches!(
|
||||
self.metadata.get("type").and_then(Value::as_str),
|
||||
Some("saved" | "downloaded" | "saveCancelled" | "saveFailed" | "opened" | "openFailed" | "openCancelled")
|
||||
)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Identity {
|
||||
provider_id: String,
|
||||
label: String,
|
||||
namespace: String,
|
||||
}
|
||||
/// The exact states encoded at Save, including a main document's branch tabs where applicable.
|
||||
pub(crate) struct Capture {
|
||||
pub doc: u64,
|
||||
pub revision: u64,
|
||||
pub snapshots: Vec<DocState>,
|
||||
pub name: String,
|
||||
intent: String,
|
||||
destination: String,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
pub(crate) enum Action {
|
||||
Save { request: String, capture: Capture, status: String, resource: String },
|
||||
Open { request: String, resource: String, name: String, bytes: Vec<u8> },
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
enum TerminalOwner {
|
||||
Open,
|
||||
Save,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Terminal {
|
||||
request: String,
|
||||
metadata: Value,
|
||||
owner: TerminalOwner,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
provider: Option<Identity>,
|
||||
enabled: bool,
|
||||
nonce: String,
|
||||
serial: u64,
|
||||
connection: String,
|
||||
resources: Vec<Resource>,
|
||||
bindings: HashMap<u64, String>,
|
||||
names: HashMap<u64, String>,
|
||||
dialogs: HashMap<String, Capture>,
|
||||
pending: HashMap<String, Capture>,
|
||||
// Keep every captured document alias owned until its terminal event can be queued.
|
||||
finishing_saves: HashMap<String, Vec<u64>>,
|
||||
opens: HashMap<String, String>,
|
||||
queued_opens: HashSet<String>,
|
||||
actions: Vec<Action>,
|
||||
// Only captures already admitted in dialogs/pending enter this inbox: at most 16, no bytes.
|
||||
delivery_failures: Vec<Action>,
|
||||
events: Vec<Event>,
|
||||
// At most MAX_PENDING saves plus MAX_PENDING reads; never stores transfer bytes.
|
||||
finished: VecDeque<Terminal>,
|
||||
publishing_terminals: usize,
|
||||
documents: Value,
|
||||
}
|
||||
impl State {
|
||||
fn busy(&self) -> bool {
|
||||
!self.dialogs.is_empty()
|
||||
|| !self.pending.is_empty()
|
||||
|| !self.finishing_saves.is_empty()
|
||||
|| !self.opens.is_empty()
|
||||
|| !self.actions.is_empty()
|
||||
|| !self.delivery_failures.is_empty()
|
||||
|| !self.finished.is_empty()
|
||||
|| self.events.iter().any(Event::terminal)
|
||||
|| self.publishing_terminals != 0
|
||||
}
|
||||
fn next(&mut self, kind: &str) -> Result<String, String> {
|
||||
if self.nonce.is_empty() {
|
||||
return Err("file provider session is not initialized".into());
|
||||
}
|
||||
self.serial = self.serial.checked_add(1).ok_or("file provider request counter exhausted")?;
|
||||
Ok(format!("{}-{kind}-{}", self.nonce, self.serial))
|
||||
}
|
||||
fn event(&mut self, mut metadata: Value, bytes: Option<Vec<u8>>) {
|
||||
if let (Some(provider), Some(fields)) = (&self.provider, metadata.as_object_mut()) {
|
||||
fields.insert("providerId".into(), provider.provider_id.clone().into());
|
||||
fields.insert("namespace".into(), provider.namespace.clone().into());
|
||||
fields.insert("connectionId".into(), self.connection.clone().into());
|
||||
}
|
||||
self.events.push(Event { metadata, bytes });
|
||||
}
|
||||
fn retained_bytes(&self) -> usize {
|
||||
let captures = self.dialogs.values().chain(self.pending.values()).map(|p| p.bytes.as_ref().map_or(0, Vec::len));
|
||||
let events = self.events.iter().map(|e| e.bytes.as_ref().map_or(0, Vec::len));
|
||||
let actions = self.actions.iter().chain(&self.delivery_failures).map(|a| match a {
|
||||
Action::Open { bytes, .. } => bytes.len(),
|
||||
_ => 0,
|
||||
});
|
||||
captures.chain(events).chain(actions).fold(0, usize::saturating_add)
|
||||
}
|
||||
fn pending_for(&self, doc: u64) -> bool {
|
||||
self.dialogs.values().chain(self.pending.values()).any(|c| c.snapshots.iter().any(|d| d.uid == doc))
|
||||
|| self.finishing_saves.values().any(|aliases| aliases.contains(&doc))
|
||||
|| self.actions.iter().any(|a| matches!(a, Action::Save { capture, .. } if capture.snapshots.iter().any(|d| d.uid == doc)))
|
||||
}
|
||||
fn flush_finished(&mut self) {
|
||||
while self.events.len() < MAX_EVENTS {
|
||||
let Some(terminal) = self.finished.pop_front() else { break };
|
||||
self.event(terminal.metadata, None);
|
||||
match terminal.owner {
|
||||
TerminalOwner::Open => {
|
||||
self.opens.remove(&terminal.request);
|
||||
self.queued_opens.remove(&terminal.request);
|
||||
}
|
||||
TerminalOwner::Save => {
|
||||
self.finishing_saves.remove(&terminal.request);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn take_events(&mut self) -> Vec<Event> {
|
||||
let events = std::mem::take(&mut self.events);
|
||||
self.flush_finished();
|
||||
if events.is_empty() { std::mem::take(&mut self.events) } else { events }
|
||||
}
|
||||
fn fail_delivery(&mut self, metadata: &Value) {
|
||||
let Some(request) = metadata.get("requestId").and_then(Value::as_str) else { return };
|
||||
match metadata.get("type").and_then(Value::as_str) {
|
||||
Some(kind @ ("save" | "saveDialog")) => {
|
||||
let capture = if kind == "save" { self.pending.remove(request) } else { self.dialogs.remove(request) };
|
||||
if let Some(mut capture) = capture {
|
||||
capture.bytes = None;
|
||||
self.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
|
||||
self.delivery_failures.push(Action::Save { request: request.into(), capture, status: "failed".into(), resource: String::new() });
|
||||
}
|
||||
}
|
||||
Some("openRequested") if !self.queued_opens.contains(request) => {
|
||||
if let Some(resource) = self.opens.get(request).cloned() {
|
||||
// The terminal can wait behind a full event queue. Reject late payloads
|
||||
// now, while retaining the read's account owner until it can be queued.
|
||||
self.queued_opens.insert(request.into());
|
||||
self.finished.push_back(Terminal {
|
||||
request: request.into(),
|
||||
metadata: json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":"file-provider event delivery failed"}),
|
||||
owner: TerminalOwner::Open,
|
||||
});
|
||||
self.flush_finished();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Host(Arc<Mutex<State>>);
|
||||
struct PublishingBatch {
|
||||
host: Host,
|
||||
terminals: usize,
|
||||
}
|
||||
impl Drop for PublishingBatch {
|
||||
fn drop(&mut self) {
|
||||
let mut state = self.host.state();
|
||||
state.publishing_terminals = state.publishing_terminals.saturating_sub(self.terminals);
|
||||
}
|
||||
}
|
||||
impl Host {
|
||||
fn state(&self) -> MutexGuard<'_, State> {
|
||||
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
pub fn set_session(&self, nonce: String) -> Result<(), String> {
|
||||
let mut s = self.state();
|
||||
if !s.nonce.is_empty() || s.provider.is_some() || !valid_id(&nonce) || nonce.len() < 16 {
|
||||
return Err("invalid or already initialized file provider session".into());
|
||||
}
|
||||
s.nonce = nonce;
|
||||
Ok(())
|
||||
}
|
||||
pub fn connect(&self, provider_id: String, label: String, namespace: String) -> Result<String, String> {
|
||||
if !valid_id(&provider_id) || !valid_label(&label) || !valid_id(&namespace) {
|
||||
return Err("invalid file provider identity".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
let identity = Identity { provider_id, label, namespace };
|
||||
if let Some(current) = &s.provider {
|
||||
return if *current == identity { Ok(s.connection.clone()) } else { Err("unregister before changing provider or account".into()) };
|
||||
}
|
||||
s.connection = s.next("connection")?;
|
||||
s.provider = Some(identity);
|
||||
s.enabled = true;
|
||||
Ok(s.connection.clone())
|
||||
}
|
||||
pub fn disconnect(&self) -> Result<(), String> {
|
||||
let mut s = self.state();
|
||||
if s.busy() {
|
||||
return Err("finish or cancel pending operations and consume completion events before unregistering".into());
|
||||
}
|
||||
s.provider = None;
|
||||
s.enabled = false;
|
||||
s.connection.clear();
|
||||
s.resources.clear();
|
||||
s.bindings.clear();
|
||||
s.names.clear();
|
||||
s.events.clear();
|
||||
s.documents = Value::Null;
|
||||
Ok(())
|
||||
}
|
||||
pub fn connected(&self) -> bool {
|
||||
self.state().provider.is_some()
|
||||
}
|
||||
pub fn enabled(&self) -> bool {
|
||||
let s = self.state();
|
||||
s.provider.is_some() && s.enabled
|
||||
}
|
||||
pub fn set_enabled(&self, enabled: bool) -> Result<(), String> {
|
||||
let mut s = self.state();
|
||||
if s.provider.is_none() {
|
||||
return Err("file provider is not connected".into());
|
||||
}
|
||||
s.enabled = enabled;
|
||||
Ok(())
|
||||
}
|
||||
pub fn busy(&self) -> bool {
|
||||
self.state().busy()
|
||||
}
|
||||
pub fn pending_for(&self, doc: u64) -> bool {
|
||||
self.state().pending_for(doc)
|
||||
}
|
||||
pub fn bound_document(&self, resource: &str) -> Option<u64> {
|
||||
self.state().bindings.iter().find(|(_, r)| r.as_str() == resource).map(|(d, _)| *d)
|
||||
}
|
||||
pub fn bound_filename(&self, doc: u64) -> Option<String> {
|
||||
self.state().names.get(&doc).cloned()
|
||||
}
|
||||
/// Captures are produced synchronously by the editor before this event is issued.
|
||||
pub(crate) fn begin(
|
||||
&self,
|
||||
snapshots: Vec<DocState>,
|
||||
doc: u64,
|
||||
revision: u64,
|
||||
name: String,
|
||||
bytes: Vec<u8>,
|
||||
save_as: bool,
|
||||
) -> Result<String, String> {
|
||||
let mut s = self.state();
|
||||
if s.provider.is_none()
|
||||
|| !s.enabled
|
||||
|| !valid_native_name(&name)
|
||||
|| bytes.is_empty()
|
||||
|| bytes.len() > MAX_BYTES
|
||||
|| s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES
|
||||
|| s.pending_for(doc)
|
||||
|| s.dialogs.len() + s.pending.len() + s.finishing_saves.len() >= MAX_PENDING
|
||||
|| s.events.len() >= MAX_EVENTS
|
||||
|| !snapshots.iter().any(|snapshot| snapshot.uid == doc)
|
||||
{
|
||||
return Err("provider unavailable, a save is pending, or capture exceeds 80 MiB".into());
|
||||
}
|
||||
let request = s.next("dialog")?;
|
||||
let intent = if save_as { "saveAs" } else { "save" }.to_string();
|
||||
s.event(json!({"type":"saveDialog","requestId":request,"documentId":doc.to_string(),"revision":revision.to_string(),"intent":intent,"filename":name}), None);
|
||||
s.dialogs.insert(request.clone(), Capture { doc, revision, snapshots, name, intent, destination: String::new(), bytes: Some(bytes) });
|
||||
Ok(request)
|
||||
}
|
||||
pub fn resolve_dialog(&self, request: &str, destination: &str, name: &str) -> Result<(), String> {
|
||||
if !matches!(destination, "provider" | "device" | "cancel") || (destination != "cancel" && !valid_native_name(name)) {
|
||||
return Err("choose provider, device or cancel and a native project filename".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.events.len() >= MAX_EVENTS {
|
||||
return Err("provider event queue is full".into());
|
||||
}
|
||||
let mut capture = s.dialogs.remove(request).ok_or("unknown or completed save dialog")?;
|
||||
if destination == "cancel" {
|
||||
capture.bytes = None;
|
||||
s.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
|
||||
s.actions.push(Action::Save { request: request.into(), capture, status: "cancel".into(), resource: String::new() });
|
||||
return Ok(());
|
||||
}
|
||||
capture.name = name.into();
|
||||
capture.destination = destination.into();
|
||||
let resource = if capture.intent == "save" { s.bindings.get(&capture.doc).cloned() } else { None };
|
||||
let bytes = capture.bytes.take();
|
||||
s.event(json!({"type":"save","requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"intent":capture.intent,"filename":name,"resourceId":resource,"destination":destination}), bytes);
|
||||
s.pending.insert(request.into(), capture);
|
||||
Ok(())
|
||||
}
|
||||
pub fn result(&self, request: String, status: String, resource: String) -> Result<(), String> {
|
||||
if !matches!(status.as_str(), "saved" | "download" | "failed" | "cancel") || (!resource.is_empty() && !valid_id(&resource)) {
|
||||
return Err("invalid provider result".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
let capture = s.pending.get(&request).ok_or("unknown or completed save request")?;
|
||||
if (status == "saved" && (capture.destination != "provider" || !valid_id(&resource)))
|
||||
|| (status == "download" && capture.destination != "device")
|
||||
{
|
||||
return Err("result does not match the chosen destination".into());
|
||||
}
|
||||
if status == "saved" && s.bindings.iter().any(|(doc, id)| *doc != capture.doc && *id == resource) {
|
||||
return Err("resource is bound to another open document".into());
|
||||
}
|
||||
if status == "saved" && capture.intent == "saveAs" && s.bindings.get(&capture.doc) == Some(&resource) {
|
||||
return Err("Save As must produce a distinct resource".into());
|
||||
}
|
||||
if s.actions.len() >= MAX_PENDING {
|
||||
return Err("provider command queue is full".into());
|
||||
}
|
||||
let capture = s.pending.remove(&request).ok_or("unknown save request")?;
|
||||
s.finishing_saves.insert(request.clone(), capture.snapshots.iter().map(|doc| doc.uid).collect());
|
||||
s.actions.push(Action::Save { request, capture, status, resource });
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_resources(&self, connection: &str, resources: Vec<Resource>) -> Result<(), String> {
|
||||
let mut seen = HashSet::new();
|
||||
if resources.len() > MAX_RESOURCES
|
||||
|| resources.iter().any(|r| !valid_id(&r.id) || !valid_native_name(&r.name) || r.updated_at.len() > 100 || !seen.insert(r.id.clone()))
|
||||
{
|
||||
return Err("invalid native project resource list".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.provider.is_none() || s.connection != connection {
|
||||
return Err("resource list belongs to another connection".into());
|
||||
}
|
||||
s.resources = resources;
|
||||
Ok(())
|
||||
}
|
||||
pub fn request_open(&self, resource: &str) -> Result<String, String> {
|
||||
let mut s = self.state();
|
||||
if !s.enabled
|
||||
|| s.provider.is_none()
|
||||
|| s.opens.len() >= MAX_PENDING
|
||||
|| s.events.len() >= MAX_EVENTS
|
||||
|| !s.resources.iter().any(|r| r.id == resource)
|
||||
{
|
||||
return Err("resource is unavailable in the current provider account".into());
|
||||
}
|
||||
let request = s.next("open")?;
|
||||
s.opens.insert(request.clone(), resource.into());
|
||||
s.event(json!({"type":"openRequested","requestId":request,"resourceId":resource}), None);
|
||||
Ok(request)
|
||||
}
|
||||
pub fn open(&self, request: String, name: String, bytes: Vec<u8>) -> Result<(), String> {
|
||||
if !valid_native_name(&name) || bytes.is_empty() || bytes.len() > MAX_BYTES {
|
||||
return Err("invalid native project resource".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.actions.len() >= MAX_PENDING || s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES {
|
||||
return Err("provider command queue is full".into());
|
||||
}
|
||||
if s.queued_opens.contains(&request) {
|
||||
return Err("open response already queued".into());
|
||||
}
|
||||
let resource = s.opens.get(&request).cloned().ok_or("unknown or completed open request")?;
|
||||
s.queued_opens.insert(request.clone());
|
||||
s.actions.push(Action::Open { request, resource, name, bytes });
|
||||
Ok(())
|
||||
}
|
||||
pub fn cancel_open(&self, request: String, error: String) -> Result<(), String> {
|
||||
if error.len() > 1024 {
|
||||
return Err("invalid open result".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.queued_opens.contains(&request) {
|
||||
return Err("open response already queued".into());
|
||||
}
|
||||
if s.events.len() >= MAX_EVENTS {
|
||||
return Err("provider event queue is full".into());
|
||||
}
|
||||
let resource = s.opens.remove(&request).ok_or("unknown or completed open request")?;
|
||||
s.event(json!({"type":if error.is_empty(){"openCancelled"}else{"openFailed"},"requestId":request,"resourceId":resource,"error":error}), None);
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn take_actions(&self) -> Vec<Action> {
|
||||
let mut state = self.state();
|
||||
let mut actions = std::mem::take(&mut state.actions);
|
||||
actions.append(&mut state.delivery_failures);
|
||||
actions
|
||||
}
|
||||
pub fn take_events(&self) -> Vec<Event> {
|
||||
self.state().take_events()
|
||||
}
|
||||
/// Failed publication consumes only a still-owned request, never an accepted callback.
|
||||
/// Recovery actions retain captured aliases until the real application produces a terminal.
|
||||
/// Returns whether the platform must request a repaint for failure consumption.
|
||||
pub fn publish_events_with<E>(&self, mut dispatch: impl FnMut(&Value, Option<Vec<u8>>) -> Result<(), E>, mut on_error: impl FnMut(E)) -> bool {
|
||||
let mut failed = false;
|
||||
for _ in 0..2 {
|
||||
let (events, _publishing) = {
|
||||
let mut state = self.state();
|
||||
let events = state.take_events();
|
||||
let terminals = events.iter().filter(|event| event.terminal()).count();
|
||||
state.publishing_terminals = state.publishing_terminals.saturating_add(terminals);
|
||||
(events, PublishingBatch { host: self.clone(), terminals })
|
||||
};
|
||||
if events.is_empty() {
|
||||
break;
|
||||
}
|
||||
for event in events {
|
||||
if let Err(error) = dispatch(&event.metadata, event.bytes) {
|
||||
failed = true;
|
||||
self.state().fail_delivery(&event.metadata);
|
||||
on_error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
failed
|
||||
}
|
||||
pub fn snapshot(&self) -> Value {
|
||||
let s = self.state();
|
||||
json!({"protocolVersion":1,"enabled":s.enabled && s.provider.is_some(),"provider":s.provider.as_ref().map(|p|json!({"id":p.provider_id,"label":p.label,"namespace":p.namespace})),"connectionId":s.connection,"resources":s.resources,"documents":s.documents,"pending":s.busy()})
|
||||
}
|
||||
pub(crate) fn refresh(&self, docs: Vec<(u64, u64, String, bool)>) {
|
||||
let mut s = self.state();
|
||||
let live: HashSet<_> = docs.iter().map(|d| d.0).collect();
|
||||
s.bindings.retain(|id, _| live.contains(id));
|
||||
s.names.retain(|id, _| live.contains(id));
|
||||
s.documents = json!(docs.into_iter().map(|(id,rev,name,dirty)|json!({"id":id.to_string(),"revision":rev.to_string(),"name":name,"dirty":dirty,"resourceId":s.bindings.get(&id)})).collect::<Vec<_>>());
|
||||
}
|
||||
pub(crate) fn finish_save(&self, request: &str, capture: &Capture, status: &str, resource: &str, alive: bool) {
|
||||
let mut s = self.state();
|
||||
if !s.finishing_saves.get(request).is_some_and(|aliases| aliases.contains(&capture.doc))
|
||||
|| s.finished.iter().any(|terminal| terminal.request == request)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if status == "saved" {
|
||||
if alive {
|
||||
s.bindings.insert(capture.doc, resource.into());
|
||||
s.names.insert(capture.doc, capture.name.clone());
|
||||
}
|
||||
s.resources.retain(|r| r.id != resource);
|
||||
s.resources.insert(0, Resource { id: resource.into(), name: capture.name.clone(), updated_at: String::new() });
|
||||
s.resources.truncate(MAX_RESOURCES);
|
||||
}
|
||||
let metadata = json!({"type":match status { "saved"=>"saved", "download"=>"downloaded", "cancel"=>"saveCancelled", _=>"saveFailed" },"requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"resourceId":resource,"filename":capture.name,"documentOpen":alive});
|
||||
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Save });
|
||||
s.flush_finished();
|
||||
}
|
||||
pub(crate) fn finish_open(&self, request: &str, resource: &str, name: &str, result: Result<u64, String>) {
|
||||
let mut s = self.state();
|
||||
if !s.opens.get(request).is_some_and(|owned| owned == resource)
|
||||
|| !s.queued_opens.contains(request)
|
||||
|| s.finished.iter().any(|terminal| terminal.request == request)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let metadata = match result {
|
||||
Ok(doc) => {
|
||||
s.bindings.insert(doc, resource.into());
|
||||
s.names.insert(doc, name.into());
|
||||
json!({"type":"opened","requestId":request,"resourceId":resource,"documentId":doc.to_string()})
|
||||
}
|
||||
Err(error) => json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":bounded_error(&error)}),
|
||||
};
|
||||
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Open });
|
||||
s.flush_finished();
|
||||
}
|
||||
/// Draw the recent lists and return a selected resource; the caller dispatches its command.
|
||||
pub fn recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
|
||||
let selected = self.provider_recent_ui(ui);
|
||||
self.device_recent_ui(ui);
|
||||
selected
|
||||
}
|
||||
pub(crate) fn provider_recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
|
||||
let (label, resources, enabled) = {
|
||||
let s = self.state();
|
||||
(s.provider.as_ref().map(|p| p.label.clone()), s.resources.clone(), s.enabled)
|
||||
};
|
||||
let label = label.filter(|_| enabled)?;
|
||||
ui.add_space(12.0);
|
||||
ui.strong(format!("Recent files — {label}"));
|
||||
if resources.is_empty() {
|
||||
ui.weak("No recent files from this provider");
|
||||
}
|
||||
let mut selected = None;
|
||||
for resource in resources {
|
||||
if ui.button(&resource.name).on_hover_text(&resource.updated_at).clicked() {
|
||||
selected = Some(resource.id);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
selected
|
||||
}
|
||||
pub(crate) fn device_recent_ui(&self, ui: &mut egui::Ui) {
|
||||
if self.enabled() {
|
||||
ui.separator();
|
||||
ui.weak("Recent files on this device");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn bounded_error(message: &str) -> String {
|
||||
let mut error = String::new();
|
||||
for ch in message.chars().filter(|ch| !ch.is_control()) {
|
||||
if error.len().saturating_add(ch.len_utf8()) > 1024 {
|
||||
break;
|
||||
}
|
||||
error.push(ch);
|
||||
}
|
||||
error
|
||||
}
|
||||
fn valid_id(value: &str) -> bool {
|
||||
!value.is_empty() && value.len() <= 160 && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b':'))
|
||||
}
|
||||
fn valid_label(value: &str) -> bool {
|
||||
!value.trim().is_empty() && value.len() <= 100 && !value.chars().any(char::is_control)
|
||||
}
|
||||
fn valid_native_name(value: &str) -> bool {
|
||||
!value.trim().is_empty()
|
||||
&& value.len() <= 255
|
||||
&& !value.chars().any(|c| c.is_control() || matches!(c, '/' | '\\'))
|
||||
&& value.to_ascii_lowercase().ends_with(EXTENSION)
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,518 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use cadcraft_engine::Session;
|
||||
fn host() -> Host {
|
||||
let h = Host::default();
|
||||
h.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
h.connect("test".into(), "Test storage".into(), "account-a".into()).unwrap();
|
||||
h
|
||||
}
|
||||
fn capture(h: &Host, save_as: bool) -> (String, u64) {
|
||||
let mut session = Session::new();
|
||||
session.execute("new", &json!({})).unwrap();
|
||||
let doc = session.state().unwrap().clone();
|
||||
let uid = doc.uid;
|
||||
(h.begin(vec![doc.clone()], uid, doc.revision, "example.dxf".into(), vec![1, 2, 3], save_as).unwrap(), uid)
|
||||
}
|
||||
#[test]
|
||||
fn off_until_explicit_registration_and_session_is_single_use() {
|
||||
let h = Host::default();
|
||||
assert!(!h.enabled());
|
||||
assert!(!h.connected());
|
||||
assert!(h.connect("test".into(), "Test".into(), "a".into()).is_err());
|
||||
assert!(host().set_session("0123456789abcdef".into()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn each_save_has_a_choice_and_cancel_never_acknowledges_a_document() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
assert_eq!(h.take_events()[0].metadata["type"], "saveDialog");
|
||||
assert!(h.pending_for(uid));
|
||||
h.resolve_dialog(&request, "cancel", "").unwrap();
|
||||
let actions = h.take_actions();
|
||||
assert!(matches!(&actions[..],[Action::Save { status, .. }] if status == "cancel"));
|
||||
assert!(h.state().bindings.is_empty());
|
||||
assert!(h.result(request, "saved".into(), "file".into()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn durable_ack_owns_its_capture_and_is_single_use() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.take_events();
|
||||
assert!(h.disconnect().is_err());
|
||||
h.resolve_dialog(&request, "provider", "durable.dxf").unwrap();
|
||||
let event = h.take_events().remove(0);
|
||||
assert_eq!(event.metadata["type"], "save");
|
||||
assert_eq!(event.bytes, Some(vec![1, 2, 3]));
|
||||
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
assert!(h.result(request, "saved".into(), "file-1".into()).is_err());
|
||||
assert!(matches!(h.take_actions().as_slice(),[Action::Save { capture,resource,.. }] if capture.doc==uid && resource=="file-1"));
|
||||
}
|
||||
#[test]
|
||||
fn replies_cannot_cross_the_chosen_destination_or_an_open_resource_alias() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.resolve_dialog(&request, "device", "local.dxf").unwrap();
|
||||
assert!(h.result(request.clone(), "saved".into(), "remote".into()).is_err());
|
||||
h.result(request, "download".into(), String::new()).unwrap();
|
||||
h.take_actions();
|
||||
h.take_events();
|
||||
let (request, _) = capture(&h, false);
|
||||
h.state().bindings.insert(uid, "already-open".into());
|
||||
h.resolve_dialog(&request, "provider", "new.dxf").unwrap();
|
||||
assert!(h.result(request, "saved".into(), "already-open".into()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn unregister_clears_cached_account_documents_before_reconnect() {
|
||||
let h = host();
|
||||
h.state().bindings.insert(42, "account-a-resource".into());
|
||||
h.state().names.insert(42, "Account A.dxf".into());
|
||||
h.refresh(vec![(42, 1, "Account A.dxf".into(), false)]);
|
||||
assert_eq!(h.snapshot()["documents"][0]["resourceId"], "account-a-resource");
|
||||
h.disconnect().unwrap();
|
||||
let disconnected = h.snapshot();
|
||||
assert!(disconnected["documents"].is_null());
|
||||
assert!(disconnected["resources"].as_array().unwrap().is_empty());
|
||||
assert!(h.state().bindings.is_empty());
|
||||
assert!(h.state().names.is_empty());
|
||||
h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
|
||||
assert!(h.snapshot()["documents"].is_null());
|
||||
}
|
||||
#[test]
|
||||
fn resource_reads_and_lists_are_scoped_to_current_account_connection() {
|
||||
let h = host();
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let rows = vec![Resource { id: "file-1".into(), name: "remote.dxf".into(), updated_at: String::new() }];
|
||||
assert!(h.set_resources("another-connection", rows.clone()).is_err());
|
||||
h.set_resources(&connection, rows).unwrap();
|
||||
assert!(h.request_open("unknown").is_err());
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
assert!(h.open("forged".into(), "remote.dxf".into(), vec![1]).is_err());
|
||||
h.open(request.clone(), "remote.dxf".into(), vec![1]).unwrap();
|
||||
assert!(h.open(request.clone(), "remote.dxf".into(), vec![1]).is_err());
|
||||
assert!(h.cancel_open(request.clone(), String::new()).is_err());
|
||||
assert!(h.disconnect().is_err());
|
||||
h.take_actions();
|
||||
h.finish_open(&request, "file-1", "remote.dxf", Err("invalid archive".into()));
|
||||
assert!(h.disconnect().is_err());
|
||||
let completion = h.take_events();
|
||||
assert!(completion.iter().any(|event| event.metadata["type"] == "openFailed" && event.metadata["requestId"] == request));
|
||||
h.disconnect().unwrap();
|
||||
let next = h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
|
||||
assert_ne!(connection, next);
|
||||
assert!(h.set_resources(&connection, Vec::new()).is_err());
|
||||
assert!(h.snapshot()["resources"].as_array().unwrap().is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn names_are_native_filenames_and_resource_ids_are_opaque() {
|
||||
assert!(valid_native_name("with accents áé.dxf"));
|
||||
assert!(!valid_native_name("../project.dxf"));
|
||||
assert!(!valid_native_name("project.svg"));
|
||||
assert!(!valid_id("../../project"));
|
||||
assert!(!valid_native_name("project.dxf\0"));
|
||||
}
|
||||
#[test]
|
||||
fn disabled_provider_does_not_discard_a_capture_already_awaiting_ack() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.set_enabled(false).unwrap();
|
||||
assert!(!h.enabled());
|
||||
assert!(h.pending_for(uid));
|
||||
h.resolve_dialog(&request, "provider", "in-flight.dxf").unwrap();
|
||||
h.result(request, "saved".into(), "file-1".into()).unwrap();
|
||||
assert!(matches!(h.take_actions().as_slice(),[Action::Save { status,.. }] if status=="saved"));
|
||||
}
|
||||
|
||||
fn fill_transport_event_queue(h: &Host) {
|
||||
let mut state = h.state();
|
||||
for ordinal in state.events.len()..MAX_EVENTS {
|
||||
state.event(json!({"type":"queued","ordinal":ordinal}), None);
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal_resource(h: &Host) -> String {
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let filename = format!("Remote{EXTENSION}");
|
||||
h.set_resources(&connection, vec![Resource { id: "file-1".into(), name: filename.clone(), updated_at: String::new() }]).unwrap();
|
||||
filename
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_event_queue_retains_open_terminals_until_ordered_drain() {
|
||||
let h = host();
|
||||
let filename = terminal_resource(&h);
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let success = h.request_open("file-1").unwrap();
|
||||
h.open(success.clone(), filename.clone(), vec![1]).unwrap();
|
||||
let failure = h.request_open("file-1").unwrap();
|
||||
h.open(failure.clone(), filename.clone(), vec![1]).unwrap();
|
||||
h.take_actions();
|
||||
fill_transport_event_queue(&h);
|
||||
h.finish_open(&success, "file-1", &filename, Ok(42));
|
||||
h.finish_open(&failure, "file-1", &filename, Err("é\n".repeat(1000)));
|
||||
h.finish_open(&success, "file-1", &filename, Err("duplicate".into()));
|
||||
h.finish_open("unowned", "file-1", &filename, Ok(99));
|
||||
assert_eq!(h.state().events.len(), MAX_EVENTS);
|
||||
assert_eq!(h.state().finished.len(), 2);
|
||||
assert!(h.disconnect().is_err());
|
||||
let first = h.take_events();
|
||||
assert_eq!(first.len(), MAX_EVENTS);
|
||||
assert!(!first.iter().any(|event| matches!(event.metadata["type"].as_str(), Some("opened" | "openFailed"))));
|
||||
let terminals = h.take_events();
|
||||
assert_eq!(terminals.len(), 2);
|
||||
assert_eq!(terminals[0].metadata["type"], "opened");
|
||||
assert_eq!(terminals[1].metadata["type"], "openFailed");
|
||||
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), [success.as_str(), failure.as_str()]);
|
||||
for event in &terminals {
|
||||
assert_eq!(event.metadata["connectionId"], connection);
|
||||
assert_eq!(event.metadata["namespace"], "account-a");
|
||||
}
|
||||
let error = terminals[1].metadata["error"].as_str().unwrap();
|
||||
assert!(error.len() <= 1024 && error.chars().all(|ch| !ch.is_control()));
|
||||
assert_eq!(h.bound_document("file-1"), Some(42));
|
||||
assert!(!h.busy());
|
||||
assert!(h.take_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_event_queue_retains_save_failure_without_duplicate_or_unowned_terminals() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
|
||||
h.result(request.clone(), "failed".into(), String::new()).unwrap();
|
||||
let Action::Save { capture, .. } = h.take_actions().remove(0) else { panic!("expected save action") };
|
||||
fill_transport_event_queue(&h);
|
||||
h.finish_save(&request, &capture, "failed", "", true);
|
||||
h.finish_save(&request, &capture, "failed", "", true);
|
||||
h.finish_save("unowned", &capture, "failed", "", true);
|
||||
assert_eq!(h.state().events.len(), MAX_EVENTS);
|
||||
assert_eq!(h.state().finished.len(), 1);
|
||||
assert!(h.pending_for(uid));
|
||||
assert_eq!(h.take_events().len(), MAX_EVENTS);
|
||||
let terminals = h.take_events();
|
||||
assert_eq!(terminals.len(), 1);
|
||||
assert_eq!(terminals[0].metadata["type"], "saveFailed");
|
||||
assert_eq!(terminals[0].metadata["requestId"], request);
|
||||
assert!(!h.pending_for(uid));
|
||||
assert!(!h.busy());
|
||||
assert!(h.take_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_terminals_are_bounded_by_admitted_reads_and_saves() {
|
||||
let h = host();
|
||||
let filename = terminal_resource(&h);
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
for _ in 0..MAX_PENDING {
|
||||
let (request, _) = capture(&h, false);
|
||||
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
|
||||
h.result(request, "failed".into(), String::new()).unwrap();
|
||||
}
|
||||
let saves: Vec<_> = h
|
||||
.take_actions()
|
||||
.into_iter()
|
||||
.map(|action| match action {
|
||||
Action::Save { request, capture, .. } => (request, capture),
|
||||
_ => panic!("expected save action"),
|
||||
})
|
||||
.collect();
|
||||
assert!(h.state().events.len() < MAX_EVENTS);
|
||||
let mut extra = saves[0].1.snapshots.clone();
|
||||
extra[0].uid = u64::MAX;
|
||||
assert!(h.begin(extra, u64::MAX, 1, format!("Extra{EXTENSION}"), vec![1], false).is_err());
|
||||
let mut reads = Vec::new();
|
||||
for _ in 0..MAX_PENDING {
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
h.open(request.clone(), filename.clone(), vec![1]).unwrap();
|
||||
reads.push(request);
|
||||
}
|
||||
h.take_actions();
|
||||
fill_transport_event_queue(&h);
|
||||
for (request, capture) in &saves {
|
||||
h.finish_save(request, capture, "failed", "", true);
|
||||
}
|
||||
for request in &reads {
|
||||
h.finish_open(request, "file-1", &filename, Err("read failed".into()));
|
||||
}
|
||||
assert_eq!(h.state().finished.len(), 2 * MAX_PENDING);
|
||||
assert_eq!(h.state().finishing_saves.len(), MAX_PENDING);
|
||||
assert_eq!(h.state().opens.len(), MAX_PENDING);
|
||||
assert!(h.request_open("file-1").is_err());
|
||||
assert!(h.disconnect().is_err());
|
||||
assert_eq!(h.take_events().len(), MAX_EVENTS);
|
||||
let terminals = h.take_events();
|
||||
assert_eq!(terminals.len(), 2 * MAX_PENDING);
|
||||
let expected: Vec<_> = saves.iter().map(|(request, _)| request.as_str()).chain(reads.iter().map(String::as_str)).collect();
|
||||
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), expected);
|
||||
for event in &terminals {
|
||||
assert_eq!(event.metadata["connectionId"], connection);
|
||||
assert_eq!(event.metadata["namespace"], "account-a");
|
||||
}
|
||||
assert!(!h.busy());
|
||||
assert!(h.take_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_target_must_belong_to_its_snapshot_aliases() {
|
||||
let h = host();
|
||||
let (request, _) = capture(&h, false);
|
||||
let snapshots = h.state().dialogs.get(&request).unwrap().snapshots.clone();
|
||||
assert!(h.begin(snapshots, u64::MAX, 1, format!("Other{EXTENSION}"), vec![1], false).is_err());
|
||||
assert!(!h.pending_for(u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_save_delivery_has_a_bounded_inbox_and_keeps_all_captured_aliases() {
|
||||
let h = host();
|
||||
let mut session = Session::new();
|
||||
session.execute("new", &json!({})).unwrap();
|
||||
let first = session.state().unwrap().clone();
|
||||
session.execute("new", &json!({})).unwrap();
|
||||
let alias = session.state().unwrap().clone();
|
||||
let request = h.begin(vec![first.clone(), alias.clone()], first.uid, first.revision, "Captured.dxf".into(), vec![1, 2, 3], false).unwrap();
|
||||
h.take_events();
|
||||
h.resolve_dialog(&request, "provider", "Captured.dxf").unwrap();
|
||||
let name = terminal_resource(&h);
|
||||
for _ in 0..MAX_PENDING {
|
||||
let read = h.request_open("file-1").unwrap();
|
||||
h.open(read, name.clone(), vec![1]).unwrap();
|
||||
}
|
||||
assert!(h.result(request.clone(), "saved".into(), "file-1".into()).unwrap_err().contains("queue is full"));
|
||||
let mut errors = 0;
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, bytes| {
|
||||
if metadata["type"] == "save" {
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert_eq!(bytes, Some(vec![1, 2, 3]));
|
||||
Err("copy failed")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| errors += 1,
|
||||
));
|
||||
assert_eq!(errors, 1);
|
||||
assert_eq!(h.state().actions.len(), MAX_PENDING, "ordinary admission capacity is unchanged");
|
||||
assert_eq!(h.state().delivery_failures.len(), 1);
|
||||
assert!(h.pending_for(first.uid) && h.pending_for(alias.uid));
|
||||
assert!(h.result(request.clone(), "saved".into(), "late".into()).is_err());
|
||||
let actions = h.take_actions();
|
||||
assert_eq!(actions.len(), MAX_PENDING + 1);
|
||||
for action in actions {
|
||||
match action {
|
||||
Action::Save { request: owned, capture, status, resource } => {
|
||||
assert_eq!(owned, request);
|
||||
assert_eq!((capture.doc, capture.revision), (first.uid, first.revision));
|
||||
assert_eq!(capture.snapshots.iter().map(|doc| doc.uid).collect::<Vec<_>>(), vec![first.uid, alias.uid]);
|
||||
assert!(Arc::ptr_eq(&capture.snapshots[0].doc, &first.doc));
|
||||
assert!(capture.bytes.is_none() && resource.is_empty());
|
||||
assert_eq!(status, "failed");
|
||||
h.finish_save(&owned, &capture, &status, &resource, true);
|
||||
}
|
||||
Action::Open { request, resource, name, .. } => h.finish_open(&request, &resource, &name, Err("fixture complete".into())),
|
||||
}
|
||||
}
|
||||
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
|
||||
assert!(!h.busy() && !h.pending_for(first.uid) && !h.pending_for(alias.uid));
|
||||
assert!(h.bound_document("file-1").is_none());
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_and_reentrant_save_results_are_not_replaced_by_delivery_recovery() {
|
||||
for reentrant in [false, true] {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.take_events();
|
||||
h.resolve_dialog(&request, "provider", "Original.dxf").unwrap();
|
||||
let failed = h.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert_eq!(metadata["type"], "save");
|
||||
if reentrant {
|
||||
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
Err("dispatch failed after an accepted result")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
assert_eq!(failed, reentrant);
|
||||
assert!(h.state().delivery_failures.is_empty());
|
||||
if !reentrant {
|
||||
assert!(h.pending_for(uid), "successful delivery is not an ACK");
|
||||
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
}
|
||||
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected save action") };
|
||||
assert_eq!((owned.as_str(), status.as_str(), resource.as_str()), (request.as_str(), "saved", "file-1"));
|
||||
h.finish_save(&owned, &capture, &status, &resource, true);
|
||||
assert!(h.disconnect().is_err(), "the queued saved terminal still owns its account");
|
||||
assert_eq!(h.take_events()[0].metadata["type"], "saved");
|
||||
assert_eq!(h.bound_document("file-1"), Some(uid));
|
||||
assert!(!h.busy());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_chooser_delivery_preserves_capacity_errors_and_synchronous_resolution() {
|
||||
for accepted in [false, true] {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
if !accepted {
|
||||
fill_transport_event_queue(&h);
|
||||
assert!(h.resolve_dialog(&request, "provider", "Retry.dxf").is_err());
|
||||
assert!(h.state().dialogs.contains_key(&request));
|
||||
}
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, _| {
|
||||
if metadata["type"] == "saveDialog" {
|
||||
if accepted {
|
||||
h.resolve_dialog(&request, "provider", "Accepted.dxf").unwrap();
|
||||
}
|
||||
Err("chooser delivery failed")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
if accepted {
|
||||
assert!(h.state().pending.contains_key(&request));
|
||||
assert!(h.state().delivery_failures.is_empty());
|
||||
h.result(request.clone(), "failed".into(), String::new()).unwrap();
|
||||
} else {
|
||||
assert!(h.resolve_dialog(&request, "provider", "Late.dxf").is_err());
|
||||
assert_eq!(h.state().delivery_failures.len(), 1);
|
||||
}
|
||||
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected failure action") };
|
||||
assert_eq!(owned, request);
|
||||
assert_eq!(status, "failed");
|
||||
assert!(capture.bytes.is_none());
|
||||
h.finish_save(&owned, &capture, &status, &resource, true);
|
||||
let terminal = h.take_events();
|
||||
assert_eq!(terminal[0].metadata["type"], "saveFailed");
|
||||
assert_eq!(terminal[0].metadata["requestId"], request);
|
||||
assert!(!h.busy() && !h.pending_for(uid));
|
||||
let retry = h.begin(capture.snapshots.clone(), capture.doc, capture.revision, "Retry.dxf".into(), vec![1], false).unwrap();
|
||||
assert_ne!(retry, request);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_read_delivery_releases_only_unconsumed_owners_and_preserves_queued_open() {
|
||||
let h = host();
|
||||
let name = terminal_resource(&h);
|
||||
let failed = h.request_open("file-1").unwrap();
|
||||
let accepted = h.request_open("file-1").unwrap();
|
||||
let mut terminals = Vec::new();
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, _| {
|
||||
if metadata["type"] == "openRequested" {
|
||||
if metadata["requestId"] == accepted {
|
||||
h.open(accepted.clone(), name.clone(), vec![7]).unwrap();
|
||||
}
|
||||
Err("open request delivery failed")
|
||||
} else {
|
||||
terminals.push(metadata.clone());
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(terminals.len(), 1);
|
||||
assert_eq!(terminals[0]["type"], "openFailed");
|
||||
assert_eq!(terminals[0]["requestId"], failed);
|
||||
assert_eq!(terminals[0]["resourceId"], "file-1");
|
||||
assert!(h.open(failed, name.clone(), vec![1]).is_err());
|
||||
let actions = h.take_actions();
|
||||
assert_eq!(actions.len(), 1);
|
||||
let Action::Open { request, resource, name, bytes } = &actions[0] else { panic!("expected accepted open") };
|
||||
assert_eq!(request, &accepted);
|
||||
assert_eq!(bytes.as_slice(), [7]);
|
||||
h.finish_open(request, resource, name, Err("fixture complete".into()));
|
||||
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
|
||||
assert!(!h.busy());
|
||||
let retry = h.request_open("file-1").unwrap();
|
||||
h.cancel_open(retry, String::new()).unwrap();
|
||||
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_batch_and_nested_terminal_delivery_keep_the_original_account_owned() {
|
||||
let h = host();
|
||||
let name = terminal_resource(&h);
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
h.open(request.clone(), name.clone(), vec![7]).unwrap();
|
||||
h.take_actions();
|
||||
h.finish_open(&request, "file-1", &name, Ok(42));
|
||||
let mut delivered = Vec::new();
|
||||
assert!(!h.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert!(h.disconnect().is_err());
|
||||
assert_eq!(h.snapshot()["connectionId"], connection);
|
||||
if metadata["type"] == "openRequested" {
|
||||
let nested = h.request_open("file-1").unwrap();
|
||||
h.cancel_open(nested, String::new()).unwrap();
|
||||
assert!(!h.publish_events_with(
|
||||
|_, _| {
|
||||
assert!(h.disconnect().is_err(), "nested delivery cannot release an outer taken terminal");
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert!(h.disconnect().is_err());
|
||||
} else {
|
||||
delivered.push(metadata.clone());
|
||||
}
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(delivered.len(), 1);
|
||||
assert_eq!(delivered[0]["type"], "opened");
|
||||
assert_eq!(delivered[0]["requestId"], request);
|
||||
assert_eq!(delivered[0]["connectionId"], connection);
|
||||
assert_eq!(h.bound_document("file-1"), Some(42));
|
||||
assert!(!h.busy());
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_delivery_recovery_retains_its_terminal_through_a_reentrant_full_event_queue() {
|
||||
let h = host();
|
||||
terminal_resource(&h);
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, _| {
|
||||
if metadata["type"] == "openRequested" {
|
||||
fill_transport_event_queue(&h);
|
||||
Err("delivery failed after another callback filled the queue")
|
||||
} else {
|
||||
assert_eq!(metadata["type"], "queued");
|
||||
assert!(h.disconnect().is_err());
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {
|
||||
assert!(h.open(request.clone(), "Remote.dxf".into(), vec![1]).is_err(), "a retained failure cannot accept a late payload");
|
||||
assert!(h.cancel_open(request.clone(), String::new()).is_err());
|
||||
},
|
||||
));
|
||||
assert!(h.busy() && h.disconnect().is_err(), "bounded drains leave the undelivered terminal owned for the next call");
|
||||
let mut seen = 0;
|
||||
assert!(!h.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert_eq!(metadata["type"], "openFailed");
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert!(h.disconnect().is_err());
|
||||
seen += 1;
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(seen, 1);
|
||||
assert!(!h.busy());
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
@@ -499,6 +499,7 @@
|
||||
One of the Crafting Apps by the ArtCraft team and community. 由 ArtCraft 团队和社区打造的 Crafting 系列应用之一。
|
||||
Oops 恢复已擦除对象
|
||||
Open (⌘O) 打开 (⌘O)
|
||||
Open Provider File 打开提供方文件
|
||||
Open Sample Drawing 打开示例图形
|
||||
Open sample drawing 打开示例图形
|
||||
Open... 打开...
|
||||
|
||||
|
@@ -81,6 +81,8 @@ pub mod vpscale;
|
||||
pub mod wblock;
|
||||
|
||||
pub mod exchange;
|
||||
mod file_provider_app;
|
||||
pub mod file_providers;
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::mpsc::Receiver;
|
||||
@@ -304,6 +306,8 @@ pub struct CadApp {
|
||||
/// The interface's own preferences from the Options dialog ([`options`]).
|
||||
pub options: options::UiOptions,
|
||||
pub services: Services,
|
||||
/// Disabled until an explicit same-origin web host registers a provider.
|
||||
pub file_providers: file_providers::Host,
|
||||
pub canvas: canvas::CanvasState,
|
||||
/// Desktop HID status and navigation preferences; the web host supplies no HID backend.
|
||||
pub spacemouse: spacemouse::State,
|
||||
@@ -414,6 +418,7 @@ impl CadApp {
|
||||
ui: UiState::default(),
|
||||
options: options::UiOptions::default(),
|
||||
services,
|
||||
file_providers: file_providers::Host::default(),
|
||||
canvas: canvas::CanvasState::default(),
|
||||
spacemouse: spacemouse::State::default(),
|
||||
quickcalc: palettes::quickcalc::State::default(),
|
||||
@@ -620,6 +625,9 @@ impl CadApp {
|
||||
|
||||
/// Run a command programmatically (or a UI command).
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
if self.file_providers.busy() && matches!(id, "close" | "closeall" | "revert") {
|
||||
return Err("finish or cancel the pending file provider operation before closing or reverting".into());
|
||||
}
|
||||
if let Some(r) = menus::run_ui_command(self, id, ¶ms) {
|
||||
return r;
|
||||
}
|
||||
@@ -1007,6 +1015,7 @@ impl CadApp {
|
||||
/// pass index is zero. `current_pass_index() == 0` is therefore the frame guard: true on the
|
||||
/// first pass and every hidden tick, false on later passes.
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
file_provider_app::tick(self);
|
||||
// Consume-based queues: each item is handled once, whichever callback delivers it. A
|
||||
// reply arriving during a later pass is never starved until the next frame.
|
||||
self.drain_control(ctx);
|
||||
|
||||
@@ -74,6 +74,8 @@ pub const OPEN_RECENT: &str = "Open Recent";
|
||||
pub const CLEAR_RECENT: &str = "Clear Recent Files";
|
||||
const RECENT_ITEM: &str = "ui.recent.";
|
||||
pub const RECENT_CLEAR: &str = "ui.recent.clear";
|
||||
/// Open a resource from the registered provider through the ordinary application command route.
|
||||
pub const PROVIDER_RECENT_OPEN: &str = "ui.provider.open";
|
||||
|
||||
/// UI-only commands: (id, label, menu path, shortcut).
|
||||
pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
@@ -83,6 +85,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
("ui.dock", "Arrange Panel", &[], None),
|
||||
("ui.dock.reset", "Reset Panel Layout", &["Window", "Reset Panel Layout"], None),
|
||||
("ui.open", "Open...", &[], Some("Cmd+O")),
|
||||
(PROVIDER_RECENT_OPEN, "Open Provider File", &[], None),
|
||||
("ui.newtemplate", "New from Template...", &["File", "New from Template..."], None),
|
||||
("ui.saveas", "Save As...", &[], None),
|
||||
("ui.sample", "Open Sample Drawing", &["Help", "Open Sample Drawing"], None),
|
||||
@@ -211,6 +214,19 @@ fn run_recent_file_command(app: &mut CadApp, id: &str) -> Option<Result<Value, S
|
||||
None
|
||||
}
|
||||
|
||||
fn run_provider_file_command(app: &mut CadApp, id: &str, params: &Value, no_path: bool) -> Option<Result<Value, String>> {
|
||||
let result = match id {
|
||||
PROVIDER_RECENT_OPEN => crate::file_provider_app::open_recent(app, params),
|
||||
"ui.saveas" | "saveas" if no_path && app.file_providers.enabled() => match suggested_save_format(params, crate::SaveFormat::Dxf) {
|
||||
Ok(crate::SaveFormat::Dxf) => crate::file_provider_app::save(app, true),
|
||||
Ok(crate::SaveFormat::Dwg) => return None,
|
||||
Err(error) => Err(error),
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
fn run_preference_command(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
let r = match id {
|
||||
"ui.theme.system" | "ui.theme.light" | "ui.theme.dark" => {
|
||||
@@ -387,12 +403,31 @@ fn should_pick_file_path(id: &str, params: &Value) -> bool {
|
||||
/// content asks first. `None` lets the engine save. JSON calls carry params and never get here;
|
||||
/// they report the loss in their result instead.
|
||||
fn user_qsave(app: &mut CadApp) -> Option<Result<Value, String>> {
|
||||
if app.file_providers.enabled() {
|
||||
return Some(crate::file_provider_app::save(app, false));
|
||||
}
|
||||
if app.session.state().is_ok_and(|s| s.path.is_none()) {
|
||||
return run_ui_command(app, "ui.saveas", &Value::Null);
|
||||
}
|
||||
app.hold_lossy_save().then_some(Ok(Value::Null))
|
||||
}
|
||||
|
||||
fn run_settings_and_close_command(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
if let Some(result) = run_preference_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_ui_toggle_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_language_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_close_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
if let Some(result) = route_ui_subsystems(app, id, params) {
|
||||
return Some(result);
|
||||
@@ -404,16 +439,10 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
|
||||
if let Some(result) = run_recent_file_command(app, id) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_preference_command(app, id, params) {
|
||||
if let Some(result) = run_settings_and_close_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_ui_toggle_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_language_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_close_command(app, id, params) {
|
||||
if let Some(result) = run_provider_file_command(app, id, params, no_path) {
|
||||
return Some(result);
|
||||
}
|
||||
// FIND typed, or chosen from Edit ▸ Find..., opens the window; a JSON call carries `find`
|
||||
@@ -807,8 +836,16 @@ pub fn menu_bar(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
// Titles first, so a hovered title can take over before any menu is drawn.
|
||||
let titles: Vec<egui::Response> = tree.iter().map(|(name, _)| ui.add(egui::Button::new(crate::i18n::menu(name)))).collect();
|
||||
switch_on_hover(ui.ctx(), &titles);
|
||||
for ((_, entries), title) in tree.iter().zip(&titles) {
|
||||
for ((menu, entries), title) in tree.iter().zip(&titles) {
|
||||
egui::Popup::menu(title).show(|ui| {
|
||||
if menu == "File" && app.file_providers.enabled() {
|
||||
let resource = ui.menu_button("Open Recent — file provider", |ui| app.file_providers.recent_ui(ui)).inner.flatten();
|
||||
if let Some(resource) = resource
|
||||
&& app.run(PROVIDER_RECENT_OPEN, json!({"resource":resource})).is_ok()
|
||||
{
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
for e in entries {
|
||||
entry_ui(ui, e, &mut clicked);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
//! Real CadApp command/format boundaries. This integration binary owns its process-global
|
||||
//! format hooks: every hook delegates to cadcraft-io, and no writer reports synthetic success.
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_write_as};
|
||||
use cadcraft_engine::doc::geom::Vec3;
|
||||
use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Image, Layout, Line};
|
||||
use cadcraft_engine::{DocState, Session};
|
||||
use cadcraft_ui_egui::file_providers::{Event, Resource};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use serde_json::{Value, json};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
const EXTERNAL_REFERENCE_ERROR: &str =
|
||||
"DXF references external images or drawings; make a self-contained drawing before provider save (external files are not uploaded)";
|
||||
|
||||
thread_local! {
|
||||
// Hooks run synchronously on the command's thread. Parallel cases cannot consume one
|
||||
// another's observations; all cases install exactly the same immutable OnceLock hooks.
|
||||
static WRITES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn real_read(bytes: &[u8], name: &str) -> Result<Drawing, String> {
|
||||
cadcraft_io::read(bytes, name).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn real_write(drawing: &Drawing, name: &str) -> Result<Vec<u8>, String> {
|
||||
WRITES.with(|writes| writes.borrow_mut().push(name.into()));
|
||||
cadcraft_io::write(drawing, name).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn real_write_as(drawing: &Drawing, name: &str, options: &SaveAs) -> Result<Vec<u8>, String> {
|
||||
WRITES.with(|writes| writes.borrow_mut().push(name.into()));
|
||||
let options = cadcraft_io::SaveOptions { version: options.version, binary: options.binary };
|
||||
cadcraft_io::write_with(drawing, name, &options).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn writes() -> Vec<String> {
|
||||
WRITES.with(|writes| writes.borrow().clone())
|
||||
}
|
||||
|
||||
/// Observe the actual picker invocation without replacing either the encoder or disk writer.
|
||||
fn picker(path: Option<String>) -> (Services, Rc<RefCell<Vec<String>>>) {
|
||||
let names = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = names.clone();
|
||||
let services = Services {
|
||||
pick_save: Some(Box::new(move |name| {
|
||||
seen.borrow_mut().push(name.into());
|
||||
path.clone()
|
||||
})),
|
||||
..Services::default()
|
||||
};
|
||||
(services, names)
|
||||
}
|
||||
|
||||
fn app_with_real_formats(services: Services) -> Result<CadApp, String> {
|
||||
set_io(IoHooks { read: real_read, write: real_write, plot: None });
|
||||
set_write_as(real_write_as);
|
||||
WRITES.with(|writes| writes.borrow_mut().clear());
|
||||
let mut app = CadApp::new(Session::new(), services);
|
||||
app.run("line", json!({"points":[[0,0],[10,20]]}))?;
|
||||
assert!(app.session.state().map_err(|error| error.to_string())?.is_dirty());
|
||||
app.ui.recent_files = vec!["existing-local-history.dxf".into()];
|
||||
Ok(app)
|
||||
}
|
||||
|
||||
fn logic(app: &mut CadApp) {
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| app.logic(ctx));
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
|
||||
fn connect(app: &mut CadApp) -> Result<(), String> {
|
||||
let host = &app.file_providers;
|
||||
host.set_session("0123456789abcdef0123456789abcdef".into())?;
|
||||
let connection = host.connect("boundary-provider".into(), "Boundary storage".into(), "boundary-account".into())?;
|
||||
host.set_resources(
|
||||
&connection,
|
||||
vec![Resource { id: "existing-provider-resource".into(), name: "Existing.dxf".into(), updated_at: "before".into() }],
|
||||
)?;
|
||||
logic(app);
|
||||
assert!(app.file_providers.take_events().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Before {
|
||||
document: DocState,
|
||||
active: usize,
|
||||
epoch: u64,
|
||||
document_count: usize,
|
||||
recents: Vec<String>,
|
||||
provider: Value,
|
||||
log_len: usize,
|
||||
}
|
||||
|
||||
fn before(app: &CadApp) -> Result<Before, String> {
|
||||
Ok(Before {
|
||||
document: app.session.state().map_err(|error| error.to_string())?.clone(),
|
||||
active: app.session.active,
|
||||
epoch: app.session.doc_epoch,
|
||||
document_count: app.session.docs.len(),
|
||||
recents: app.ui.recent_files.clone(),
|
||||
provider: app.file_providers.snapshot(),
|
||||
log_len: app.session.log.len(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A refusal or an unacknowledged capture must not change the drawing or its saved checkpoint.
|
||||
fn assert_document_unchanged(app: &CadApp, before: &Before) -> Result<(), String> {
|
||||
let after = app.session.state().map_err(|error| error.to_string())?;
|
||||
let original = &before.document;
|
||||
assert_eq!((app.session.active, app.session.doc_epoch, app.session.docs.len()), (before.active, before.epoch, before.document_count));
|
||||
assert_eq!((after.uid, after.revision), (original.uid, original.revision));
|
||||
assert!(Arc::ptr_eq(&after.doc, &original.doc));
|
||||
assert!(Arc::ptr_eq(&after.saved, &original.saved));
|
||||
assert_eq!((&after.path, &after.title, &after.space), (&original.path, &original.title, &original.space));
|
||||
assert_eq!((&after.selection, &after.previous_selection), (&original.selection, &original.previous_selection));
|
||||
assert_eq!((after.undo.len(), after.redo.len(), after.is_dirty()), (original.undo.len(), original.redo.len(), original.is_dirty()));
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ImageSpace {
|
||||
Model,
|
||||
Layout,
|
||||
Block,
|
||||
}
|
||||
|
||||
fn insert_external_image(app: &mut CadApp, space: ImageSpace) -> Result<(), String> {
|
||||
let state = app.session.state_mut().map_err(|error| error.to_string())?;
|
||||
let drawing = Arc::make_mut(&mut state.doc);
|
||||
let handle = drawing.new_handle();
|
||||
let image = Entity::new(handle, EntityKind::Image(Image { path: "synthetic-external-image.png".into(), ..Image::default() }));
|
||||
match space {
|
||||
ImageSpace::Model => drawing.model.push(image),
|
||||
ImageSpace::Layout => {
|
||||
let mut layout = Layout::new("External image layout", 3);
|
||||
layout.entities.push(image);
|
||||
drawing.layouts.push(layout);
|
||||
}
|
||||
ImageSpace::Block => {
|
||||
let mut block = Block::new("ExternalImageBlock");
|
||||
block.entities.push(image);
|
||||
drawing.blocks.insert(block.name.clone(), Arc::new(block));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_external_xref(app: &mut CadApp) -> Result<(), String> {
|
||||
let state = app.session.state_mut().map_err(|error| error.to_string())?;
|
||||
let drawing = Arc::make_mut(&mut state.doc);
|
||||
let mut block = Block::new("ExternalDrawing");
|
||||
block.xref_path = Some("synthetic-external-drawing.dxf".into());
|
||||
drawing.blocks.insert(block.name.clone(), Arc::new(block));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_refused_before_encoding(app: &mut CadApp, command: &str) -> Result<(), String> {
|
||||
// Refresh the public document snapshot after the synthetic fixture was installed.
|
||||
logic(app);
|
||||
let before = before(app)?;
|
||||
let error = app.run(command, Value::Null).err().ok_or("external references unexpectedly admitted a provider capture")?;
|
||||
assert_eq!(error, EXTERNAL_REFERENCE_ERROR);
|
||||
assert!(writes().is_empty(), "the app must refuse external references before calling its real encoder");
|
||||
assert_document_unchanged(app, &before)?;
|
||||
assert!(!app.file_providers.busy());
|
||||
assert!(!app.file_providers.pending_for(before.document.uid));
|
||||
assert!(app.file_providers.take_events().is_empty(), "no provider chooser, write or ACK may be published");
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(EXTERNAL_REFERENCE_ERROR));
|
||||
assert_eq!(app.session.log.len(), before.log_len + 1);
|
||||
assert_eq!(app.session.log.last(), Some(&error));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_save_and_save_as_refuse_external_images_in_model_layout_and_blocks() -> Result<(), String> {
|
||||
for space in [ImageSpace::Model, ImageSpace::Layout, ImageSpace::Block] {
|
||||
for command in ["qsave", "ui.saveas"] {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
insert_external_image(&mut app, space)?;
|
||||
assert_refused_before_encoding(&mut app, command)?;
|
||||
assert!(picked.borrow().is_empty(), "{space:?}/{command} must not fall back to a local picker");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_save_and_save_as_refuse_external_xrefs_before_encoding_or_admission() -> Result<(), String> {
|
||||
for command in ["qsave", "ui.saveas"] {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
insert_external_xref(&mut app)?;
|
||||
assert_refused_before_encoding(&mut app, command)?;
|
||||
assert!(picked.borrow().is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_open_refuses_external_images_and_xrefs_before_native_path_loading() -> Result<(), String> {
|
||||
for image_space in [Some(ImageSpace::Model), Some(ImageSpace::Layout), Some(ImageSpace::Block), None] {
|
||||
let mut incoming = app_with_real_formats(Services::default())?;
|
||||
if let Some(space) = image_space {
|
||||
insert_external_image(&mut incoming, space)?;
|
||||
} else {
|
||||
insert_external_xref(&mut incoming)?;
|
||||
}
|
||||
let bytes =
|
||||
cadcraft_io::write(incoming.session.doc().map_err(|error| error.to_string())?, "External.dxf").map_err(|error| error.to_string())?;
|
||||
let mut app = app_with_real_formats(Services::default())?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
let value = app.run("ui.provider.open", json!({"resource":"existing-provider-resource"}))?;
|
||||
let request = value["requestId"].as_str().ok_or("provider Open omitted its request ID")?;
|
||||
only_event(&app, "openRequested", request)?;
|
||||
app.file_providers.open(request.into(), "External.dxf".into(), bytes)?;
|
||||
logic(&mut app);
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
assert!(app.file_providers.bound_document("existing-provider-resource").is_none());
|
||||
let terminal = only_event(&app, "openFailed", request)?;
|
||||
assert_eq!(terminal.metadata["resourceId"], "existing-provider-resource");
|
||||
assert_eq!(
|
||||
terminal.metadata["error"],
|
||||
"DXF references external images or drawings; open a self-contained drawing with the file provider (external files are not loaded)"
|
||||
);
|
||||
assert!(!app.file_providers.busy());
|
||||
assert!(app.file_providers.request_open("existing-provider-resource").is_ok(), "a refused Open must release its owner for retry");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn only_event(app: &CadApp, event_type: &str, request: &str) -> Result<Event, String> {
|
||||
let events = app.file_providers.take_events();
|
||||
assert_eq!(events.len(), 1, "expected exactly one {event_type}");
|
||||
let event = events.into_iter().next().ok_or("missing provider event")?;
|
||||
assert_eq!(event.metadata["type"], event_type);
|
||||
assert_eq!(event.metadata["requestId"], request);
|
||||
Ok(event)
|
||||
}
|
||||
|
||||
/// Check actual native decoder output rather than accepting arbitrary nonempty writer bytes.
|
||||
fn assert_native_line(bytes: &[u8], name: &str) -> Result<(), String> {
|
||||
let drawing = real_read(bytes, name)?;
|
||||
assert_eq!(drawing.model.len(), 1);
|
||||
let entity = drawing.model.iter().next().ok_or("native format lost the synthetic line")?;
|
||||
assert_eq!(entity.kind, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 20.0, 0.0) }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn provider_positive_control(command: &str, intent: &str) -> Result<(), String> {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
let value = app.run(command, Value::Null)?;
|
||||
assert_eq!(value["pending"], "fileProvider");
|
||||
let request = value["requestId"].as_str().ok_or("save command did not return its capture ID")?;
|
||||
let dialog = only_event(&app, "saveDialog", request)?;
|
||||
assert_eq!(dialog.metadata["documentId"], before.document.uid.to_string());
|
||||
assert_eq!(dialog.metadata["revision"], before.document.revision.to_string());
|
||||
assert_eq!(dialog.metadata["intent"], intent);
|
||||
let encoded_name = dialog.metadata["filename"].as_str().ok_or("save dialog lost its native filename")?;
|
||||
assert_eq!(encoded_name, format!("{}.dxf", before.document.title));
|
||||
assert_eq!(writes(), vec![encoded_name.to_string()]);
|
||||
assert!(dialog.bytes.is_none());
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
app.file_providers.resolve_dialog(request, "provider", "SelfContained.dxf")?;
|
||||
let save = only_event(&app, "save", request)?;
|
||||
assert_eq!(save.metadata["destination"], "provider");
|
||||
assert_eq!(save.metadata["documentId"], before.document.uid.to_string());
|
||||
assert_eq!(save.metadata["revision"], before.document.revision.to_string());
|
||||
assert_eq!(save.metadata["filename"], "SelfContained.dxf");
|
||||
assert_native_line(save.bytes.as_deref().ok_or("provider write omitted its real DXF bytes")?, "SelfContained.dxf")?;
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
assert_eq!(app.file_providers.snapshot()["resources"], before.provider["resources"]);
|
||||
app.file_providers.result(request.into(), "saved".into(), "self-contained-resource".into())?;
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
logic(&mut app);
|
||||
assert_provider_ack(&app, &before, request)?;
|
||||
assert!(picked.borrow().is_empty());
|
||||
assert_eq!(writes().len(), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_provider_ack(app: &CadApp, before: &Before, request: &str) -> Result<(), String> {
|
||||
let state = app.session.state().map_err(|error| error.to_string())?;
|
||||
assert_eq!((state.uid, state.revision), (before.document.uid, before.document.revision));
|
||||
assert!(Arc::ptr_eq(&state.doc, &before.document.doc));
|
||||
assert!(Arc::ptr_eq(&state.saved, &before.document.doc));
|
||||
assert!(!state.is_dirty());
|
||||
assert_eq!(state.path, before.document.path);
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
assert_eq!(app.file_providers.bound_document("self-contained-resource"), Some(state.uid));
|
||||
let terminal = only_event(app, "saved", request)?;
|
||||
assert_eq!(terminal.metadata["documentId"], state.uid.to_string());
|
||||
assert_eq!(terminal.metadata["revision"], before.document.revision.to_string());
|
||||
assert_eq!(terminal.metadata["resourceId"], "self-contained-resource");
|
||||
assert!(terminal.bytes.is_none());
|
||||
assert!(!app.file_providers.busy());
|
||||
assert_eq!(app.file_providers.snapshot()["resources"][0]["name"], "SelfContained.dxf");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_contained_provider_save_and_save_as_encode_real_dxf_and_wait_for_app_ack() -> Result<(), String> {
|
||||
for (command, intent) in [("qsave", "save"), ("ui.saveas", "saveAs")] {
|
||||
provider_positive_control(command, intent)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_local_save(app: &CadApp, path: &str, value: &Value) -> Result<(), String> {
|
||||
let bytes = std::fs::read(path).map_err(|error| error.to_string())?;
|
||||
assert_eq!(value["path"], path);
|
||||
assert_eq!(value["bytes"].as_u64(), Some(bytes.len() as u64));
|
||||
assert_native_line(&bytes, path)?;
|
||||
let state = app.session.state().map_err(|error| error.to_string())?;
|
||||
assert_eq!(state.path.as_deref(), Some(path));
|
||||
assert!(Arc::ptr_eq(&state.doc, &state.saved));
|
||||
assert!(!state.is_dirty());
|
||||
assert_eq!(writes(), vec![path.to_string()]);
|
||||
assert!(!app.file_providers.busy());
|
||||
assert!(!app.file_providers.pending_for(state.uid));
|
||||
assert!(app.file_providers.take_events().is_empty(), "a local file must not create a provider chooser, write or ACK");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))]
|
||||
fn provider_connected_explicit_dwg_save_as_uses_the_real_local_format_and_writer() -> Result<(), String> {
|
||||
// The DWG writer and reader only handle this fixture's own synthetic drawing.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let directory = TempDir::new("provider-explicit-local-dwg");
|
||||
let path = directory.path_str("Explicit local drawing.dwg");
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
let value = app.run("saveas", json!({"path":path,"version":2018}))?;
|
||||
assert_local_save(&app, &path, &value)?;
|
||||
let bytes = std::fs::read(&path).map_err(|error| error.to_string())?;
|
||||
assert!(bytes.starts_with(b"AC1032"), "the actual local file must be a 2018 DWG, not renamed DXF");
|
||||
assert!(picked.borrow().is_empty(), "a programmatic explicit path must not open either chooser");
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
assert_eq!(app.session.state().map_err(|error| error.to_string())?.uid, before.document.uid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_save_as_preserves_explicit_format_validation_and_the_local_dwg_picker() -> Result<(), String> {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
|
||||
assert!(app.run("ui.saveas", json!({"format":"unknown"})).is_err());
|
||||
assert!(app.run("ui.saveas", json!({"format":42})).is_err());
|
||||
assert!(picked.borrow().is_empty());
|
||||
|
||||
app.run("ui.saveas", json!({"format":"dwg"}))?;
|
||||
assert_eq!(*picked.borrow(), vec![format!("{}.dwg", before.document.title)]);
|
||||
assert!(writes().is_empty());
|
||||
assert!(app.file_providers.take_events().is_empty());
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_document_unchanged(&app, &before)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_provider_save_as_keeps_the_ordinary_picker_and_real_local_dxf_writer() -> Result<(), String> {
|
||||
let directory = TempDir::new("provider-disabled-local-picker");
|
||||
let path = directory.path_str("Picked local drawing.dxf");
|
||||
let (services, picked) = picker(Some(path.clone()));
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
assert!(!app.file_providers.connected() && !app.file_providers.enabled());
|
||||
let before = before(&app)?;
|
||||
let value = app.run("ui.saveas", Value::Null)?;
|
||||
assert_local_save(&app, &path, &value)?;
|
||||
assert_eq!(*picked.borrow(), vec![format!("{}.dxf", before.document.title)]);
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
assert!(!app.file_providers.connected() && !app.file_providers.enabled());
|
||||
Ok(())
|
||||
}
|
||||
@@ -136,6 +136,75 @@ fn start_page_lists_recent_files_and_opens_one_on_click() {
|
||||
assert_eq!(app.ui.recent_files, [plan, section]);
|
||||
}
|
||||
|
||||
/// The same native Start page with the storage capability absent and connected. Optional PNGs
|
||||
/// use the existing offscreen renderer; no app window, backend, or provider filesystem is made.
|
||||
#[test]
|
||||
fn provider_recents_render_separately_from_device_history() {
|
||||
let directory = std::env::var_os("CRAFT_PROVIDER_UI_FIXTURES").map(std::path::PathBuf::from);
|
||||
if let Some(path) = &directory {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
}
|
||||
for (enabled, provider_count) in [(false, 0), (true, 1), (true, 100)] {
|
||||
let (_dir, plan, _) = drawings("provider-home");
|
||||
let mut app = CadApp::new(Session::empty(), Services::default());
|
||||
app.ui.recent_files = vec![plan];
|
||||
if enabled {
|
||||
let host = &app.file_providers;
|
||||
host.set_session("fixture-session-0123456789abcdef".into()).unwrap();
|
||||
let connection = host.connect("fixture".into(), "External storage".into(), "fixture-account".into()).unwrap();
|
||||
host.set_resources(
|
||||
&connection,
|
||||
(0..provider_count)
|
||||
.map(|index| cadcraft_ui_egui::file_providers::Resource {
|
||||
id: format!("provider-drawing-{index}"),
|
||||
name: if index == 0 { "Provider drawing.dxf".into() } else { format!("Provider drawing {index}.dxf") },
|
||||
updated_at: String::new(),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let mut builder = Harness::builder().with_size(vec2(1280.0, 900.0));
|
||||
if directory.is_some() {
|
||||
builder = builder.wgpu();
|
||||
}
|
||||
let mut ready = false;
|
||||
let mut h = builder.build_ui_state(
|
||||
move |ui, app: &mut CadApp| {
|
||||
if !ready {
|
||||
ready = true;
|
||||
return;
|
||||
}
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.input_mut().max_texture_side = Some(8192);
|
||||
h.run_steps(6);
|
||||
let mut found = Vec::new();
|
||||
for shape in &h.output().shapes {
|
||||
texts(&shape.shape, &mut found);
|
||||
}
|
||||
assert!(found.iter().any(|(text, _)| text == "plan.dxf"), "{found:?}");
|
||||
assert_eq!(found.iter().any(|(text, _)| text == "Provider drawing.dxf"), enabled, "{found:?}");
|
||||
assert_eq!(found.iter().any(|(text, _)| text == "Recent files — External storage"), enabled, "{found:?}");
|
||||
assert_eq!(found.iter().any(|(text, _)| text == "Recent files on this device"), enabled, "{found:?}");
|
||||
let mut visible = Vec::new();
|
||||
for shape in &h.output().shapes {
|
||||
let mut labels = Vec::new();
|
||||
texts(&shape.shape, &mut labels);
|
||||
visible.extend(labels.into_iter().filter(|(_, rect)| shape.clip_rect.contains_rect(*rect)));
|
||||
}
|
||||
assert_eq!(visible.iter().any(|(text, _)| text == "Recent files on this device"), enabled, "{visible:?}");
|
||||
assert!(visible.iter().any(|(text, _)| text == "plan.dxf"), "device history remains visible even when provider files overflow: {visible:?}");
|
||||
if let Some(path) = directory.as_ref().filter(|_| provider_count <= 1) {
|
||||
let state = if enabled { "on" } else { "off" };
|
||||
h.render().unwrap().save(path.join(format!("cadcraft-provider-recents-{state}.png"))).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_file_that_no_longer_exists_is_dropped_when_opening_it_fails() {
|
||||
let (_dir, plan, _section) = drawings("missing");
|
||||
|
||||
@@ -134,6 +134,32 @@ xref (flag 4), an invalid name, a block that inserts itself and a block being ed
|
||||
(REFEDIT) return nil. A definition stays open across routines until ENDBLK, but a routine that
|
||||
fails drops the one it began.
|
||||
|
||||
An INSERT in the drawing (not one inside a block definition) has its attributes as records
|
||||
after it, and `entnext` reaches them: from the block reference to its first ATTRIB, from an
|
||||
ATTRIB to the next, and from the last one to the SEQEND (group `-2`, its reference's name), then
|
||||
on to the next main entity or nil. `entget` of an ATTRIB lists its groups with `-2` (its
|
||||
reference) beside its name (group `-1`). CADCraft keeps no handle of its own for these records (a
|
||||
DXF file's are the writer's), so their names are not handles: such a name is an entity name
|
||||
(`type` gives `ENAME`) that no object of any drawing can ever have, printed as the reference's
|
||||
handle, a dot and a number (`<Entity name: 2a.5>`). `handent` never returns one, and its list has
|
||||
no group 5. `entmod` of an ATTRIB takes its value (group 1) only, as one undo step, and leaves its
|
||||
tag, place, flags and properties as they are; any other edit, including one of the layout, owner,
|
||||
handle or other groups the entity can't set, a `SEQEND` list, `entdel` and `entmake` of one
|
||||
return nil and change nothing. `entupd` of one returns its name while it holds. A selection set
|
||||
holds objects of the drawing only: `ssadd`, `ssdel` and `ssmemb` of such a name return nil, and
|
||||
`command` given one picks nothing. `trans` does not take a record name: the coordinate system
|
||||
has to be a number, an entity name or an extrusion direction, and a record name is an argument
|
||||
error. `eq` and `equal` are true only for the same record name, the one a later walk returns
|
||||
while that record holds, and they are false for another record and for an entity name. A fuzz
|
||||
distance does not change that result. A name holds while its reference keeps that record in its
|
||||
place with that tag: erasing the reference (also when OOPS or `entdel` brings it back), ATTSYNC,
|
||||
-BLOCKREPLACE, opening and closing the Block Editor, Undo, Redo, a change taken back (a
|
||||
refused or failed command) and a command that puts an earlier drawing back (MOCORO's Undo, a
|
||||
grip copy's Undo, and the other restores of a saved drawing) end it (erasing another object
|
||||
does not), and a name that ended names nothing (nil), never another record. A drawing holds at
|
||||
most 65,536 such names at once; at the limit `entnext` gives no new one (nil) until names end
|
||||
and make room.
|
||||
|
||||
Non-graphic objects (the named object dictionary and its dictionaries, layouts, table records)
|
||||
are listed as a DXF file of the drawing holds them, pointers as entity names and group 5 (105 for a DIMSTYLE) as the
|
||||
object's own name. An object read from a file keeps that file's handle as its name, so
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
# Optional external file providers (web)
|
||||
|
||||
The web editor can delegate native project persistence to one **trusted same-origin host**.
|
||||
The capability is **disabled by default**. Merely loading the editor exposes a protocol object;
|
||||
it does not enable storage, render provider Recents, change ordinary local saves, or contact a server.
|
||||
A host must explicitly call registerProvider. No server, account system, login, VM, domain,
|
||||
filesystem mount or cloud vendor is built into this feature.
|
||||
|
||||
## Contract
|
||||
|
||||
window.cadcraftFileProviders has protocolVersion 1 and app cadcraft. Events are dispatched on window
|
||||
as cadcraft-file-provider CustomEvents; detail contains bounded metadata and, on save,
|
||||
a Uint8Array named bytes. The host subscribes before registering, and can discover an already-ready
|
||||
editor through the protocol object. The capability is independent of the optional control API.
|
||||
|
||||
The application command `ui.provider.open` accepts `{"resource":"resource-id"}` and returns
|
||||
the queued provider request ID. Home and File-menu provider Recents both dispatch through
|
||||
`CadApp::run`; rejected reads remain in the status and command history instead of a one-frame
|
||||
inline label. This command uses the current account's resource list and never opens a local path.
|
||||
|
||||
| Method | Arguments / result |
|
||||
| --- | --- |
|
||||
| registerProvider | (providerId, label, namespace) -> connectionId. Repeating the exact identity is idempotent. |
|
||||
| unregisterProvider | No arguments. Refused while an operation is unresolved; clears account resources and bindings. |
|
||||
| setEnabled | (boolean). Suspends new provider choices/Recents without discarding pending work. |
|
||||
| setResources | (connectionId, resources). Replace this account's native project list. |
|
||||
| requestOpen | (resourceId) -> requestId. IDs must occur in the current connection's resource list. |
|
||||
| openResource | (requestId, filename, Uint8Array). Replies only to a live, single-use open request. |
|
||||
| cancelOpen | (requestId, error). Empty error means cancellation. |
|
||||
| resolveSaveDialog | (requestId, destination, filename). destination is provider, device or cancel. |
|
||||
| saveResult | (requestId, status, resourceId). status is saved, download, failed or cancel. |
|
||||
| snapshot | Returns provider/namespace/connectionId, enabled, resources, documents and pending state. |
|
||||
|
||||
The namespace must identify the authenticated account, not its display name. A new connection ID
|
||||
and per-page cryptographic request nonce prevent old account/page callbacks from matching new work.
|
||||
This is correlation and separation of identities, **not authentication**. The host and its backend
|
||||
must authenticate users, authorize every list/read/write, and scope durable storage by account.
|
||||
Do not trust a filename, user-supplied account ID, browser page or request ID as an authorization check.
|
||||
Only the hosting page's own script environment can use this capability; no postMessage listener,
|
||||
foreign-origin message channel or filesystem authority is added.
|
||||
|
||||
Every script executing in the editor page, including third-party analytics, can call registerProvider
|
||||
and receive saved drawings through provider events. Load only scripts you trust with drawing contents.
|
||||
The host/backend remains responsible for authenticating users and authorizing each account-scoped operation.
|
||||
|
||||
A resource is an object with id, name and optional updatedAt strings. IDs are opaque and never used as
|
||||
paths. The list is limited to 100 unique resources. Names must be native .dxf filenames, at most
|
||||
255 UTF-8 bytes, with no path separators or control characters. IDs/namespaces are at most 160 ASCII
|
||||
characters (letters, numbers, dash, underscore, dot, colon). Labels are at most 100 UTF-8 bytes.
|
||||
Native captures/read responses are limited to 80 MiB; retained transfer bytes and pending work are bounded.
|
||||
The WASM adapter checks string/array lengths before copying host input and accepts only Uint8Array bytes.
|
||||
|
||||
## Save and Save As
|
||||
|
||||
With the provider enabled, interactive Save and Save As capture a native DXF and emit saveDialog.
|
||||
A Save As requested with `format: "dwg"` opens the ordinary local file picker.
|
||||
The event carries requestId, documentId, revision, intent and suggested filename. The host presents
|
||||
its own choice of **provider / device / cancel**, then calls resolveSaveDialog. The editor owns the
|
||||
captured state while the choice is open, so changing tabs or editing cannot silently change the target.
|
||||
No save happens merely because a dialog was opened or a byte capture was produced.
|
||||
|
||||
Choosing provider emits save with the immutable native bytes, filename, intent, documentId, revision,
|
||||
providerId, namespace, connectionId and requestId. Save includes a previously bound resourceId;
|
||||
Save As requests a distinct resource. The provider must finish its durable write before returning
|
||||
saveResult(requestId, saved, resourceId). An ACK cannot nominate a document or revision, cannot be
|
||||
replayed, and cannot bind a resource already owned by another open document. Failed/cancelled writes
|
||||
keep edits unsaved. Later edits remain dirty when an older capture succeeds. There is no pretend local
|
||||
path for an external resource.
|
||||
|
||||
Choosing device emits save with destination device and the capture. The host hands the bytes to the device using the
|
||||
browser's ordinary download mechanism, then returns download as the result. This is a terminal transfer
|
||||
result, **not durable provider confirmation**, and does not clear the document's saved checkpoint.
|
||||
Save Copy, Export and programmatic commands keep their existing local behavior. With the capability
|
||||
disabled or unregistered, the original browser/native save flow remains in use.
|
||||
|
||||
Provider Save/Save As captures one native DXF. DXF stores external image/drawing references as paths, not their bytes. To prevent an incomplete upload being marked saved, this bridge refuses provider capture when the modeled drawing contains external images or xrefs; bind/remove those references first. Provider Open checks the decoded drawing for those same modeled references before running the native Open command, so provider bytes cannot trigger its automatic image/xref filesystem loaders. A refusal leaves existing documents unchanged and reports the correlated openFailed terminal. Ordinary local Open keeps its existing native behavior.
|
||||
|
||||
Single-file transfers inherit the existing [DXF codec limits](file-format-parity.md). Font files, including SHX/bigfonts, and other dependencies are not collected or packaged. The bridge does not certify arbitrary foreign DXF as lossless or scan unmodeled records for dependencies. It adds no linked-file negotiation, resource-set checkpoints, attachment bundle or atomic multi-file save. The host receives the one DXF produced by the native writer and remains responsible for its durable storage.
|
||||
Use the existing local Copy/Export commands for interchange formats. The host must preserve the native
|
||||
extension; changing a suffix cannot turn native bytes into PDF, SVG or another interchange format.
|
||||
Native capture uses the existing IoHooks / write_as DXF encoder. The existing ?host=parent and data-host="page" host modes are preserved. The optional provider capability is installed only when neither mode connects, so two hosts do not compete for Save. DWG and interchange outputs remain in the original local flow.
|
||||
|
||||
Normal close/revert actions wait or refuse while provider work is unresolved. The browser can still
|
||||
force-close/reload a tab; the host should provide an unsaved-work warning and must not acknowledge a
|
||||
write it cannot recover. This bridge does not add automatic saving, cross-client conflict resolution,
|
||||
offline persistence, autosave recovery or an inactivity/login implementation.
|
||||
|
||||
## Open and Recents
|
||||
|
||||
The existing Home screen and File > Open Recent display a separate provider section while enabled.
|
||||
Local Recents retain their own storage and behavior. Publish only the current account's native files
|
||||
with setResources; the editor never scans a VM or guesses a path from a name.
|
||||
|
||||
A click emits openRequested with requestId and resourceId. After authorization, the provider fetches
|
||||
bytes and responds with openResource using that request ID. The editor parses the native project before
|
||||
emitting opened or openFailed. Selecting an already-bound open resource focuses its existing document
|
||||
without replacing unsaved edits. Unknown, duplicate or cancelled request replies are rejected.
|
||||
The host handles failed fetches using cancelOpen rather than leaving the operation pending forever.
|
||||
|
||||
Completion events are saved, downloaded, saveFailed, saveCancelled, opened, openFailed and openCancelled.
|
||||
Events associated with an account include providerId, namespace and connectionId. Storage keys should
|
||||
use the provider/account/resource identities, never display names, and the backend should use versioning
|
||||
or conditional writes if it allows concurrent clients.
|
||||
|
||||
## Recoverable publication failures
|
||||
|
||||
The byte publisher calls an explicit catch-enabled `Uint8Array.from` import. Recoverable JavaScript
|
||||
copy/allocation errors become returned errors, are logged, and do not bypass later events in the
|
||||
batch. This is not recovery from fatal memory exhaustion, WASM traps or process termination; DOM
|
||||
listener exceptions swallowed by the browser are not assumed to propagate from dispatchEvent.
|
||||
|
||||
A failed `save` or `saveDialog` moves only its still-owned capture into a bounded failure inbox.
|
||||
It retains every captured document alias in finishing-saves ownership until the actual CAD
|
||||
application consumes the failed Action and queues its correlated `saveFailed` terminal. Retained
|
||||
bytes are discarded. No saved checkpoint, binding or durable acknowledgement is manufactured.
|
||||
Public action/result admission checks are unchanged. At most 16 previously admitted captures can
|
||||
await failure consumption separately, including when the ordinary queue is full. Repaint is requested through
|
||||
the installed editor context. Accepted synchronous results/choices remain authoritative.
|
||||
|
||||
A failed `openRequested` retires only an unanswered read and retains its correlated `openFailed`
|
||||
terminal across event-queue capacity limits. An already queued open response survives a later
|
||||
dispatch error. Fresh choices/reads can retry after failure consumption; IDs are never reused.
|
||||
|
||||
Busy/account ownership includes all seven completion event types while queued or in a taken
|
||||
publication batch. Batch protection is acquired atomically and released independently for nested
|
||||
publishers. Hosts must defer unregisterProvider until the publication batch returns and all outstanding
|
||||
operations and terminal deliveries finish. Independent save/open admission rules are unchanged.
|
||||
The publisher still performs two bounded drains in order.
|
||||
|
||||
## Validation
|
||||
|
||||
Regression fixtures cover the default-off gate, single-use/late replies, account reconnection, resource
|
||||
scope and alias rejection, cancellation, immutable captures, switching tabs, edits after capture and
|
||||
conservative device results. The source includes the WASM adapter and native encoder/decoder integration.
|
||||
Run the required repository CI and the actual Window fixture on the complete candidate. This document does not claim those checks
|
||||
have been executed merely because fixtures are present.
|
||||
|
||||
New source regressions cover full ordinary action queues, a bounded failure inbox, captured aliases,
|
||||
failed chooser/read publication, accepted reentrant callbacks, current/nested terminal ownership
|
||||
and recovery through a full event queue. The native application fixture uses the real DXF codec and
|
||||
CAD failure consumer without altering process-global format hooks, preserving another active drawing
|
||||
and later edits. The WASM fixture uses the exported window API, production publisher, actual CadApp
|
||||
logic and native DXF encoder/decoder. Rust closures produce real JS RangeErrors for byte and metadata
|
||||
dispatch failures; catch-enabled calls restore exact property descriptors before assertions. It
|
||||
observes continuation, correlated failure terminals, a nonempty DXF retry and opening that payload
|
||||
under a distinct resource, without marking later edits saved.
|
||||
|
||||
The native provider_format_boundaries integration binary covers the real DXF Save/Save As refusal,
|
||||
self-contained capture and ACK, ordinary explicit DWG and disabled-provider local save behavior. Its
|
||||
provider_open_refuses_external_images_and_xrefs_before_native_path_loading fixture exercises provider
|
||||
Open refusals for model/layout/block images and xrefs without adding a document or binding.
|
||||
|
||||
The actual Window fixture is in
|
||||
[browser_tests.rs](../apps/cadcraft-web/src/file_providers/browser_tests.rs). With a real browser and
|
||||
the wasm-bindgen-test browser runner configured, run the existing WASM main harness:
|
||||
|
||||
```sh
|
||||
cargo test --locked --offline -j1 -p cadcraft-web --bin cadcraft-web --target wasm32-unknown-unknown file_providers::browser_tests:: -- --nocapture
|
||||
```
|
||||
|
||||
Simulated user Save/Save As uses the existing Null parameter form. JSON object parameters continue
|
||||
to mean explicit programmatic operations and never acquire dialogs.
|
||||
|
||||
These are authored fixtures, not execution receipts. Real browser/runner execution remains required;
|
||||
native tests or WASM compilation alone do not establish the window assertions. The fixture does not
|
||||
run a rendered WebRunner, prove backend durability or simulate true out-of-memory failure. The web
|
||||
test dependency is wasm32-only; the UI's existing workspace IO crate is a test-only dependency for
|
||||
real drawing-codec fixtures. The existing locked graph is retained; its candidate must be reviewed
|
||||
before checks.
|
||||
|
||||
Contributor credit: @alejocapo04.
|
||||
|
||||
## Native UI evidence
|
||||
|
||||
The existing recent-files test harness covers the real Start page with the optional provider absent
|
||||
and connected, retaining the separate device history in both states. It uses synthetic drawing names
|
||||
and metadata, with no storage or authentication backend. The native label assertions also run without
|
||||
a GPU when the output variable is unset.
|
||||
|
||||
```sh
|
||||
CRAFT_PROVIDER_UI_FIXTURES=/absolute/output cargo test --locked -p cadcraft-ui-egui --test recent_files provider_recents_render_separately_from_device_history -- --exact --test-threads=1
|
||||
```
|
||||
|
||||
This saves `cadcraft-provider-recents-off.png` and `cadcraft-provider-recents-on.png` using
|
||||
egui_kittest's existing offscreen renderer. Keep the generated review artifacts outside Git.
|
||||
@@ -0,0 +1,374 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under the name "LEGAL", and included in all Covered Software
|
||||
distributed in Source Code Form. Except to the extent prohibited by
|
||||
statute or regulation, such description must be sufficiently detailed
|
||||
for a recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Third-Party Notices
|
||||
|
||||
## ACadSharp
|
||||
|
||||
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
|
||||
history's initial DWG support commit identifies the source classes explicitly, including
|
||||
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
|
||||
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
|
||||
|
||||
Copyright (c) 2021 Albert Domenech
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## DWG Format References
|
||||
|
||||
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
|
||||
specification and reverse engineering, including comparison with drawings produced by CAD
|
||||
applications. LibreDWG is used as a secondary cross-check for selected field names and
|
||||
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
|
||||
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
|
||||
translated routines. The repository history and source review found no LibreDWG routines
|
||||
ported into the implementation. The source comments identify the specific cross-checks.
|
||||
Reference in New Issue
Block a user