mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-21 20:40:02 +00:00
Compare commits
648
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d2ca90783 | ||
|
|
af9798e200 | ||
|
|
c042e98abb | ||
|
|
994af5cac9 | ||
|
|
970e6bb9d4 | ||
|
|
736a83464a | ||
|
|
aa5dfc2099 | ||
|
|
f12b7570b7 | ||
|
|
795eb62762 | ||
|
|
e7b92c5b8e | ||
|
|
6028cdf187 | ||
|
|
172f9ca44c | ||
|
|
c5e7db78e4 | ||
|
|
31a04e3dbe | ||
|
|
627ffb8d7e | ||
|
|
18f47e021f | ||
|
|
21d80b3231 | ||
|
|
62deed7880 | ||
|
|
45bcfa6f77 | ||
|
|
627b5a3350 | ||
|
|
1006e487da | ||
|
|
fcd4a0c9eb | ||
|
|
dbd2bf5dad | ||
|
|
d7915c5f3b | ||
|
|
1bbc5ec76b | ||
|
|
012732136c | ||
|
|
273303134e | ||
|
|
48d25a0414 | ||
|
|
6021d96628 | ||
|
|
ad329273f2 | ||
|
|
f3796d1f7a | ||
|
|
3a64a190ea | ||
|
|
5074d2a54c | ||
|
|
bccba7261e | ||
|
|
c8ee56a44f | ||
|
|
d3ae8a6af0 | ||
|
|
2a2d4e2582 | ||
|
|
d1cf06cbea | ||
|
|
7d33d9d4dd | ||
|
|
53080b1748 | ||
|
|
21c48cc05b | ||
|
|
47237bd4dd | ||
|
|
2521605713 | ||
|
|
f56be09993 | ||
|
|
1b6861698c | ||
|
|
f24af47ffb | ||
|
|
055b06a2f4 | ||
|
|
660a7881d1 | ||
|
|
3d8301b965 | ||
|
|
cb8b1709e9 | ||
|
|
66ecce06f5 | ||
|
|
004287d919 | ||
|
|
656dd4d09a | ||
|
|
876de8ad2f | ||
|
|
4feccf0abd | ||
|
|
dfddd13656 | ||
|
|
2f82ecdbf1 | ||
|
|
7fc9f2756d | ||
|
|
754b609d09 | ||
|
|
d6e712db41 | ||
|
|
d73e379fd2 | ||
|
|
8343045863 | ||
|
|
2528671106 | ||
|
|
3f92d57b79 | ||
|
|
c3c455fbbf | ||
|
|
d0a1ea5268 | ||
|
|
2994b52e03 | ||
|
|
0de051049c | ||
|
|
cddf09beb2 | ||
|
|
1c85d339c3 | ||
|
|
63a5569970 | ||
|
|
5acec7d0be | ||
|
|
8f7421737d | ||
|
|
422d42411a | ||
|
|
0c15f7106c | ||
|
|
31de470926 | ||
|
|
0f60269868 | ||
|
|
3e6e1e534d | ||
|
|
52aae9c1fb | ||
|
|
a89be5f2dd | ||
|
|
a4a3a342a0 | ||
|
|
36fcc896f7 | ||
|
|
a0a691e1f7 | ||
|
|
097c53bee3 | ||
|
|
5ec3a18aa7 | ||
|
|
b37b7ceb7b | ||
|
|
1d9ddd2406 | ||
|
|
0a14fc7d3a | ||
|
|
bbbd9eec51 | ||
|
|
f2b35e957e | ||
|
|
1fcf654ea8 | ||
|
|
e86d895ba1 | ||
|
|
c6c3aefe3f | ||
|
|
b34477d580 | ||
|
|
3d7e298b7d | ||
|
|
23d44cd9c8 | ||
|
|
8296bbc642 | ||
|
|
b90d68ec34 | ||
|
|
c42763ba0f | ||
|
|
642c3a59a3 | ||
|
|
53049d82e0 | ||
|
|
e23a362c54 | ||
|
|
f46a220375 | ||
|
|
8171c9be17 | ||
|
|
4dbcbfdaaa | ||
|
|
429554b389 | ||
|
|
17952af3fb | ||
|
|
1b0cefce9c | ||
|
|
e1cab10d01 | ||
|
|
05cad7db49 | ||
|
|
4e73fb5bb3 | ||
|
|
84e3478863 | ||
|
|
fac2d18df6 | ||
|
|
23a0bd4fdb | ||
|
|
75c54ce35d | ||
|
|
313fab8827 | ||
|
|
bda4a9924c | ||
|
|
3e64cc5d06 | ||
|
|
20087b4b5f | ||
|
|
5685085add | ||
|
|
32be8a655e | ||
|
|
b901656669 | ||
|
|
1271b06b02 | ||
|
|
6dc336160d | ||
|
|
8a64e42100 | ||
|
|
fcfdf33001 | ||
|
|
898b539630 | ||
|
|
bfa30e2192 | ||
|
|
432cbfb106 | ||
|
|
596ea36465 | ||
|
|
dc081c6f7f | ||
|
|
746942613c | ||
|
|
1b8be0b77d | ||
|
|
7fe832b284 | ||
|
|
1fcdfc87b4 | ||
|
|
5a82f090df | ||
|
|
41d9b5e957 | ||
|
|
6fe715e11c | ||
|
|
028b98d71c | ||
|
|
b9f96d3dd3 | ||
|
|
39e9b62829 | ||
|
|
4aed7a2267 | ||
|
|
63394e872d | ||
|
|
e59195edb8 | ||
|
|
5e39af933f | ||
|
|
c66f6f45b8 | ||
|
|
b062030a03 | ||
|
|
7aa952b8da | ||
|
|
5cfe1a4149 | ||
|
|
9f2060d674 | ||
|
|
9fc626a33b | ||
|
|
fef32761af | ||
|
|
9562d951df | ||
|
|
f05fa9cec3 | ||
|
|
73e7486dc9 | ||
|
|
fde62a39ab | ||
|
|
7db656fdc7 | ||
|
|
9d9e4c3b0d | ||
|
|
c92bb5cdad | ||
|
|
1c35d7f8c1 | ||
|
|
a94fc0898b | ||
|
|
a0dced6d45 | ||
|
|
532c4ccc1c | ||
|
|
88a73b7618 | ||
|
|
0fc8e5241c | ||
|
|
cff2eb7262 | ||
|
|
ab6bff5e4e | ||
|
|
1a76e10c20 | ||
|
|
941ea341bc | ||
|
|
71882cf5e6 | ||
|
|
64c35cadff | ||
|
|
63dec85749 | ||
|
|
1c3c25035c | ||
|
|
2bc3b02ea1 | ||
|
|
6842b8774b | ||
|
|
78c1653f50 | ||
|
|
fda82da3df | ||
|
|
2c59eb19c5 | ||
|
|
0299a3eaa0 | ||
|
|
1c7d3f0fae | ||
|
|
4f282b30cc | ||
|
|
b9d59c64ab | ||
|
|
4c327cccd0 | ||
|
|
587d1dcd69 | ||
|
|
e04056f714 | ||
|
|
25faf34d28 | ||
|
|
dadd1f227f | ||
|
|
1428174159 | ||
|
|
f686a595e6 | ||
|
|
7d2fbd959a | ||
|
|
829909274a | ||
|
|
f8f13c3f4e | ||
|
|
f119610287 | ||
|
|
620e6a664c | ||
|
|
8dd8635e10 | ||
|
|
4251f1e253 | ||
|
|
9a32aa5613 | ||
|
|
6ee6e652fd | ||
|
|
76f7cea83f | ||
|
|
47e978b58e | ||
|
|
a68d0a458b | ||
|
|
60265a1eee | ||
|
|
20b0c9c11a | ||
|
|
b517e0749d | ||
|
|
5c911ad824 | ||
|
|
15147260c1 | ||
|
|
bbbf4465c4 | ||
|
|
7bf5905ac9 | ||
|
|
c1dd60ffd6 | ||
|
|
bec28d6b87 | ||
|
|
d3e6111cf1 | ||
|
|
dd1f0531ac | ||
|
|
37150774c6 | ||
|
|
9cf115e808 | ||
|
|
d0e83aefa6 | ||
|
|
9d8f16c825 | ||
|
|
f043540d13 | ||
|
|
78decf80f7 | ||
|
|
8ad9a3ce15 | ||
|
|
251fddb658 | ||
|
|
51db2d52e4 | ||
|
|
9621dcbd94 | ||
|
|
5648a06ac4 | ||
|
|
f344cf4460 | ||
|
|
e61e328edb | ||
|
|
611eb9f5a9 | ||
|
|
1977a493c7 | ||
|
|
a08fd7c1d1 | ||
|
|
fa6bb0351b | ||
|
|
bad1073fdf | ||
|
|
48b4165591 | ||
|
|
01bbdb24bc | ||
|
|
15ba3dc5cc | ||
|
|
07bb604214 | ||
|
|
dc4bbe86f6 | ||
|
|
953a6b3b01 | ||
|
|
8085745a22 | ||
|
|
ca578a8fb7 | ||
|
|
916be26ed3 | ||
|
|
2dbc7699a0 | ||
|
|
7c72ec45a9 | ||
|
|
0158712bfd | ||
|
|
683eb5e6e7 | ||
|
|
345fb27a69 | ||
|
|
8f988f630d | ||
|
|
acd109d97c | ||
|
|
f4e6873130 | ||
|
|
e4214f7180 | ||
|
|
35934718ea | ||
|
|
916d440bed | ||
|
|
632967aa78 | ||
|
|
f15be2305c | ||
|
|
f2dadec23a | ||
|
|
00acec952e | ||
|
|
78254b4d3f | ||
|
|
8094d7746f | ||
|
|
4ad4f4f598 | ||
|
|
477eec5026 | ||
|
|
38750c6eb8 | ||
|
|
75d9d72703 | ||
|
|
fdcd9610f2 | ||
|
|
54d96834d5 | ||
|
|
47a8fb02e7 | ||
|
|
896a390b42 | ||
|
|
345eb60ef3 | ||
|
|
0cf3bdea83 | ||
|
|
82424e47c9 | ||
|
|
7fef8cbe2f | ||
|
|
f2b473dc51 | ||
|
|
4d826ed91f | ||
|
|
e86eacf094 | ||
|
|
a7bb28d722 | ||
|
|
27bff9cc30 | ||
|
|
d600a80354 | ||
|
|
81f0aa53ff | ||
|
|
27861ad0ed | ||
|
|
b72680cfb7 | ||
|
|
d9adce038c | ||
|
|
0b32c2e6a1 | ||
|
|
323f4629eb | ||
|
|
c02027abc8 | ||
|
|
8c249aa722 | ||
|
|
a0aa0863bf | ||
|
|
b4509d2368 | ||
|
|
13a3ebc0d1 | ||
|
|
41e0860725 | ||
|
|
0d23cc3cb3 | ||
|
|
81acc9b8e4 | ||
|
|
397b8e156a | ||
|
|
12567f14f2 | ||
|
|
95e86caea5 | ||
|
|
7adf8d89cd | ||
|
|
006f71f650 | ||
|
|
b0ed57f1c7 | ||
|
|
30db7296c4 | ||
|
|
a76775bf2b | ||
|
|
6576cac1a3 | ||
|
|
4125b351cd | ||
|
|
6d15a40f43 | ||
|
|
5f390e6e6a | ||
|
|
00f521858a | ||
|
|
bcd0b3745e | ||
|
|
ba27f36b58 | ||
|
|
9f7a2422ea | ||
|
|
148091aa93 | ||
|
|
c82d6228ff | ||
|
|
786c8c46e4 | ||
|
|
62329310d7 | ||
|
|
6bd09ea468 | ||
|
|
0440fa77ff | ||
|
|
471478868d | ||
|
|
0f833358b9 | ||
|
|
64e55f903c | ||
|
|
94aad92f1d | ||
|
|
1738d3805e | ||
|
|
bf6d9fd46a | ||
|
|
f17be3d7ad | ||
|
|
582d9535b6 | ||
|
|
2a3b0c2626 | ||
|
|
abce3a718b | ||
|
|
acb28313c6 | ||
|
|
2be9d00796 | ||
|
|
286d3de0aa | ||
|
|
cd3e8478d6 | ||
|
|
12d0235b2c | ||
|
|
1ac2ebaad2 | ||
|
|
a3b3e1281f | ||
|
|
ca5a34be12 | ||
|
|
c400d6d48c | ||
|
|
e635248b1e | ||
|
|
739e083f4b | ||
|
|
3fa7275e4f | ||
|
|
aba903dbb3 | ||
|
|
493addc2dd | ||
|
|
a2bee8b49e | ||
|
|
c68420221c | ||
|
|
a5fa5ca064 | ||
|
|
ef599e58e0 | ||
|
|
27fd074f54 | ||
|
|
2db6ab069a | ||
|
|
d33a6e634a | ||
|
|
0bfe609567 | ||
|
|
7e830044ab | ||
|
|
6546f0eecd | ||
|
|
15b5395c06 | ||
|
|
cdc61f32b5 | ||
|
|
d4bacce885 | ||
|
|
9aea9b16c4 | ||
|
|
9e3f584a68 | ||
|
|
3bd7510f2b | ||
|
|
b464a947ec | ||
|
|
f76ca751cc | ||
|
|
e0ad0ef33e | ||
|
|
56d73ceb21 | ||
|
|
691bdbe0b8 | ||
|
|
162d5c6820 | ||
|
|
632c2d4f1f | ||
|
|
f0e4fef003 | ||
|
|
7164b6b5b1 | ||
|
|
38fdfa4ac4 | ||
|
|
baa9c00fb7 | ||
|
|
0cc66ad306 | ||
|
|
3370a91fe9 | ||
|
|
cda7381c3d | ||
|
|
b23d362f6a | ||
|
|
714111d528 | ||
|
|
ff6cc8b3fc | ||
|
|
98d22f0c68 | ||
|
|
4c75b0c458 | ||
|
|
ba02572b31 | ||
|
|
8fe7c421ea | ||
|
|
972ae7888c | ||
|
|
ea6d7beca2 | ||
|
|
9b2308b138 | ||
|
|
69fc442ea6 | ||
|
|
be3ce73895 | ||
|
|
8a2b8f4bdf | ||
|
|
fc4e98315a | ||
|
|
e707ab4d7c | ||
|
|
8cd0d46d58 | ||
|
|
1e075f76c5 | ||
|
|
7fc29b056e | ||
|
|
aed2ae9615 | ||
|
|
033ee15e01 | ||
|
|
4a9dd31a58 | ||
|
|
26179f7428 | ||
|
|
261d46adcf | ||
|
|
e74b276dfd | ||
|
|
d826450e03 | ||
|
|
abe352564e | ||
|
|
d80920cc25 | ||
|
|
43972c82e8 | ||
|
|
767576ec9e | ||
|
|
62fb5ae79a | ||
|
|
3199de4951 | ||
|
|
48352f2baf | ||
|
|
0d138c2954 | ||
|
|
f8521ab299 | ||
|
|
73b8edac61 | ||
|
|
fbc7037a10 | ||
|
|
e773d93164 | ||
|
|
a2b6c9ac4a | ||
|
|
8abc0909f3 | ||
|
|
8166e4a809 | ||
|
|
dc92f38772 | ||
|
|
1c4d0a543f | ||
|
|
ef9898d57f | ||
|
|
33fe98a6dc | ||
|
|
5630529464 | ||
|
|
3b16f2d516 | ||
|
|
2f5bbbd68d | ||
|
|
76b0ef8897 | ||
|
|
966356545d | ||
|
|
4257674dfa | ||
|
|
64b7825d08 | ||
|
|
d2a9159e51 | ||
|
|
678ff555ae | ||
|
|
d0438577ed | ||
|
|
63b448bee9 | ||
|
|
7b767ddab9 | ||
|
|
79efd97515 | ||
|
|
cddcbe7a2a | ||
|
|
b209bb53e9 | ||
|
|
5d39f8710c | ||
|
|
6394c7c6f3 | ||
|
|
2483993218 | ||
|
|
cc57dff527 | ||
|
|
724c18c6af | ||
|
|
8e0b867f6c | ||
|
|
36f938e90a | ||
|
|
636b041a4e | ||
|
|
bb7e1046be | ||
|
|
f807e65e30 | ||
|
|
69f2b9724a | ||
|
|
28b8160407 | ||
|
|
5b037b8f92 | ||
|
|
5fd23f75fc | ||
|
|
a6200fa34f | ||
|
|
25e4900fcd | ||
|
|
4efb01332e | ||
|
|
d134079f11 | ||
|
|
591692a264 | ||
|
|
50246683c3 | ||
|
|
2effc8bf3e | ||
|
|
5b0238fc26 | ||
|
|
7b723b7bc0 | ||
|
|
a10e43cb2a | ||
|
|
7e38081b54 | ||
|
|
3f709bed2e | ||
|
|
caad180e98 | ||
|
|
80ec2dcc60 | ||
|
|
46ab40d211 | ||
|
|
9464945f82 | ||
|
|
3dd678ff3d | ||
|
|
ea768ee92a | ||
|
|
5ce44acfb2 | ||
|
|
853b2915b6 | ||
|
|
0b92b59fcd | ||
|
|
f26588a357 | ||
|
|
8073453d86 | ||
|
|
89c834155d | ||
|
|
14343212a9 | ||
|
|
ecdb8f96b2 | ||
|
|
4c63ba1470 | ||
|
|
c0335161c3 | ||
|
|
419d8848d6 | ||
|
|
c781169b95 | ||
|
|
f314d3a591 | ||
|
|
e9d8462828 | ||
|
|
6ab800e64c | ||
|
|
565cadaa51 | ||
|
|
bca698a588 | ||
|
|
5de2324973 | ||
|
|
266ee7e6ea | ||
|
|
045212139a | ||
|
|
6772150bc4 | ||
|
|
b2ba585251 | ||
|
|
7fcdc6e3bc | ||
|
|
b19188919d | ||
|
|
488308a2de | ||
|
|
f5d58913cc | ||
|
|
5ce1ea3dfc | ||
|
|
483a9304ca | ||
|
|
5183f63bc5 | ||
|
|
bcd6322ee9 | ||
|
|
e71e17a8df | ||
|
|
08cfbd5dd7 | ||
|
|
00c7613f1a | ||
|
|
0ecffdab4a | ||
|
|
4cb9e8a535 | ||
|
|
a12c85c585 | ||
|
|
890f7f1c6f | ||
|
|
4bb3acb913 | ||
|
|
0675648de8 | ||
|
|
c2f8782cc2 | ||
|
|
d365b60704 | ||
|
|
cf797cbafe | ||
|
|
935cb98eed | ||
|
|
0178858e79 | ||
|
|
875f99d26f | ||
|
|
69ea207617 | ||
|
|
546eefc58a | ||
|
|
61c018845a | ||
|
|
9a0d1b3a62 | ||
|
|
507c5e5b34 | ||
|
|
bc6dc997ef | ||
|
|
6ca8cec97d | ||
|
|
f8cb50eaa3 | ||
|
|
b6f2e86f78 | ||
|
|
c57879a5c8 | ||
|
|
2404719c3b | ||
|
|
90cd443000 | ||
|
|
ac9483c9c1 | ||
|
|
ade5469a24 | ||
|
|
6d7c652b65 | ||
|
|
3aeedf4856 | ||
|
|
f7c6293d09 | ||
|
|
89064fd82a | ||
|
|
1e1f68bf40 | ||
|
|
244feb6e89 | ||
|
|
135c928fea | ||
|
|
9477f37503 | ||
|
|
370150186b | ||
|
|
2fa967db65 | ||
|
|
4e276db858 | ||
|
|
9b3674e01f | ||
|
|
c5ebf4d1cd | ||
|
|
83b8a84050 | ||
|
|
54ea5e743a | ||
|
|
d7f3e48362 | ||
|
|
f967dc7aca | ||
|
|
e1e61a13b5 | ||
|
|
5ef32b3afa | ||
|
|
04aa716920 | ||
|
|
5e71a75383 | ||
|
|
d431b485bd | ||
|
|
41c3c83fb9 | ||
|
|
5cb54c3969 | ||
|
|
0b5a0a2eb8 | ||
|
|
73c91cbac5 | ||
|
|
d51971b6d7 | ||
|
|
0fcf46d487 | ||
|
|
f1919e31a5 | ||
|
|
6ef1e62755 | ||
|
|
9e22617679 | ||
|
|
c245e1de35 | ||
|
|
f59b32cac7 | ||
|
|
3f781c3395 | ||
|
|
b23b45e976 | ||
|
|
fc30f2c2ea | ||
|
|
63a0ab4a32 | ||
|
|
d3ae8f3a8b | ||
|
|
3363d4a78c | ||
|
|
a5a9e3ef63 | ||
|
|
40aa4fbf49 | ||
|
|
a181bbd609 | ||
|
|
ce1cc631d5 | ||
|
|
b6383b5f3c | ||
|
|
74e72c93f8 | ||
|
|
7e437cb62d | ||
|
|
18b4a8d0dd | ||
|
|
7a13ca7d05 | ||
|
|
70b0cce997 | ||
|
|
a880f8a4b0 | ||
|
|
8f59410c33 | ||
|
|
0bab712575 | ||
|
|
c4cc40355a | ||
|
|
d2fda54e8a | ||
|
|
d0dd5cfe16 | ||
|
|
9fd1b8988d | ||
|
|
52015c0b17 | ||
|
|
0135e793f7 | ||
|
|
58eefa8432 | ||
|
|
9ca0dcf7d4 | ||
|
|
784a7937ef | ||
|
|
8005201db9 | ||
|
|
a4504cc098 | ||
|
|
235ef4f9ab | ||
|
|
b13f1e6fa4 | ||
|
|
afae36cb60 | ||
|
|
bc7744b27b | ||
|
|
0230250bf5 | ||
|
|
c390364a16 | ||
|
|
57f70b6b46 | ||
|
|
8ca4265627 | ||
|
|
c334fedf31 | ||
|
|
b7b37e29cd | ||
|
|
63af07f782 | ||
|
|
fa0ce3c70f | ||
|
|
48cce34a52 | ||
|
|
289855aa67 | ||
|
|
997aef85d5 | ||
|
|
836badce4c | ||
|
|
43958b537e | ||
|
|
7dead193e4 | ||
|
|
78944a8341 | ||
|
|
7ecac5fb66 | ||
|
|
c9c3031de9 | ||
|
|
b4b62e4cf0 | ||
|
|
8e07de0f4e | ||
|
|
e7bb447d58 | ||
|
|
c0a19dfb9e | ||
|
|
ea0f866c7c | ||
|
|
10f7a9b2a3 | ||
|
|
0371c448f6 | ||
|
|
f3553783a0 | ||
|
|
6aa7c03fad | ||
|
|
d42313cde2 | ||
|
|
61a8a5f984 | ||
|
|
d6aa802c75 | ||
|
|
bd2a7597c5 | ||
|
|
e02d1ebd08 | ||
|
|
61812b25de | ||
|
|
6f1ca71e98 | ||
|
|
a652c57537 | ||
|
|
151722feb0 | ||
|
|
9b136d6c19 | ||
|
|
9427b77209 | ||
|
|
77de6af455 | ||
|
|
7429e7dcbe | ||
|
|
25c9658908 | ||
|
|
608aa225a7 | ||
|
|
65d5ee48d3 | ||
|
|
b3a73626b2 | ||
|
|
9e3379882f | ||
|
|
139d98bf6f | ||
|
|
475a70e573 | ||
|
|
64eed455e5 | ||
|
|
b4777fa8b3 | ||
|
|
d74f7a4108 | ||
|
|
becb109cc1 | ||
|
|
6900110291 | ||
|
|
4e505a6adb | ||
|
|
c35a952271 | ||
|
|
699dd1aeca | ||
|
|
50ffb767c7 | ||
|
|
a3f43a700f | ||
|
|
58a8494f98 | ||
|
|
fc4220e9b7 | ||
|
|
58a349772e | ||
|
|
87d1e28345 | ||
|
|
a395ec3d2d | ||
|
|
3ffe1ca2af | ||
|
|
ee34f423cc | ||
|
|
f537377355 | ||
|
|
315751e3ec | ||
|
|
1f7f08db8a | ||
|
|
e09fb50627 |
@@ -0,0 +1,6 @@
|
||||
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
|
||||
reviews:
|
||||
auto_review:
|
||||
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
|
||||
ignore_usernames:
|
||||
- "dependabot[bot]"
|
||||
@@ -0,0 +1,41 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Maintain Rust / Cargo dependencies
|
||||
- package-ecosystem: "cargo"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
time: "06:00"
|
||||
timezone: "America/New_York"
|
||||
# Consolidate updates into a single PR rather than one PR per crate
|
||||
groups:
|
||||
cargo-dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
commit-message:
|
||||
prefix: "chore(deps)"
|
||||
# craft-ui is still on egui 0.36, and two eguis in the graph don't build (#1990). Remove this
|
||||
# once craft-ui moves to egui 0.37 (storytold/craft-libs#199).
|
||||
ignore:
|
||||
- dependency-name: "egui"
|
||||
versions: [">=0.37"]
|
||||
- dependency-name: "eframe"
|
||||
versions: [">=0.37"]
|
||||
- dependency-name: "egui-wgpu"
|
||||
versions: [">=0.37"]
|
||||
- dependency-name: "egui_kittest"
|
||||
versions: [">=0.37"]
|
||||
|
||||
# Maintain GitHub Actions workflows
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
time: "06:00"
|
||||
timezone: "America/New_York"
|
||||
groups:
|
||||
actions:
|
||||
patterns:
|
||||
- "*"
|
||||
commit-message:
|
||||
prefix: "ci(deps)"
|
||||
@@ -0,0 +1,30 @@
|
||||
name: CI
|
||||
|
||||
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
|
||||
# suite's shared gate workflow in craft-common-actions.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a PR branch cancels its older run; every push to main runs to the end.
|
||||
concurrency:
|
||||
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
timeout-minutes: 90
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
|
||||
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
libgl1-mesa-dev
|
||||
@@ -0,0 +1,32 @@
|
||||
# Builds and tests the workspace on FreeBSD, inside a FreeBSD VM on a Linux runner
|
||||
# (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter.
|
||||
name: FreeBSD
|
||||
|
||||
# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every pull
|
||||
# request: a drifted dependency still shows up within a day, and always before a release ships.
|
||||
# PRs that change the FreeBSD workflow or packaging itself still run it.
|
||||
on:
|
||||
push:
|
||||
branches: [release]
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/freebsd.yml
|
||||
- packaging/freebsd/**
|
||||
- packaging/env.sh
|
||||
schedule:
|
||||
- cron: "27 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: freebsd-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
freebsd:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
@@ -0,0 +1,61 @@
|
||||
# Evaluates the Nix flake (no build, about a minute): `nix build` / `nix develop` stop at evaluation
|
||||
# when Cargo.lock gains something nix/package.nix can't vendor, and nothing else would notice.
|
||||
name: Nix
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
|
||||
pull_request:
|
||||
paths: ["flake.nix", "flake.lock", "nix/**", "Cargo.lock", ".github/workflows/nix.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nix-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
nix:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
|
||||
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
@@ -19,48 +19,5 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
ACTIONLINT_VERSION: 1.7.12
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends shellcheck desktop-file-utils appstream libxml2-utils python3-yaml
|
||||
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
|
||||
| tar -xz -C "$RUNNER_TEMP" actionlint
|
||||
- name: actionlint
|
||||
run: |
|
||||
"$RUNNER_TEMP/actionlint" -color
|
||||
- name: shellcheck
|
||||
run: shellcheck packaging/*.sh packaging/*/*.sh
|
||||
- name: PowerShell
|
||||
shell: pwsh
|
||||
run: |
|
||||
foreach ($f in Get-ChildItem packaging/windows/*.ps1) {
|
||||
$errors = $null
|
||||
[System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) | Out-Null
|
||||
if ($errors) { $errors | ForEach-Object { Write-Output "::error file=$($f.Name)::$_" }; exit 1 }
|
||||
Write-Output "ok $($f.Name)"
|
||||
}
|
||||
- name: XML, desktop entry, AppStream, Flatpak manifest
|
||||
run: |
|
||||
xmllint --noout packaging/windows/cadcraft.wxs packaging/macos/*.plist* packaging/linux/*.xml*
|
||||
# Windows Installer needs Icon ids ending in .ico or .exe, or shortcuts show a blank icon.
|
||||
if grep -oE '<Icon Id="[^"]*"' packaging/windows/cadcraft.wxs | grep -vE '\.(ico|exe)"$'; then
|
||||
echo "::error::Icon Id must end in .ico or .exe"; exit 1
|
||||
fi
|
||||
desktop-file-validate packaging/linux/ai.storyteller.cadcraft.desktop
|
||||
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.cadcraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.cadcraft.metainfo.xml"
|
||||
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.cadcraft.metainfo.xml"
|
||||
python3 - <<'EOF'
|
||||
import yaml
|
||||
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.cadcraft.yml"))
|
||||
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml"))
|
||||
for m in (src, bundle):
|
||||
assert m["id"] == "ai.storyteller.cadcraft" and m["command"] == "cadcraft", m["id"]
|
||||
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
|
||||
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
|
||||
print("Flatpak manifests ok")
|
||||
EOF
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
|
||||
|
||||
+59
-415
@@ -1,13 +1,3 @@
|
||||
# Release pipeline: every push to `release` builds signed installers for every platform and
|
||||
# creates or updates the draft GitHub Release "CADCraft v<version>". See docs/releasing.md.
|
||||
#
|
||||
# Pushes to `release` trigger the run; pushing there is limited by a repository ruleset to org
|
||||
# admins and the release-managers team. The jobs that sign (macOS, Windows) and the one that
|
||||
# drafts the GitHub Release run in the `release` environment (restricted to the `release` branch),
|
||||
# which holds the signing secrets. Every secret is optional: missing ones produce unsigned
|
||||
# artifacts and a warning, never a failed build. The other jobs (version, Linux, Flatpak, FreeBSD,
|
||||
# web) sign nothing and get no secrets, so a manual dispatch on any other branch is a dry run of
|
||||
# them: the environment refuses the signing jobs there, and the draft-release job is skipped.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
@@ -25,418 +15,72 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
# Never cancel a run mid-notarization or mid-upload; a newer push waits its turn.
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
CADCRAFT_BUILD_SHA: ${{ github.sha }}
|
||||
INPUT_VERSION: ${{ inputs.version }}
|
||||
|
||||
jobs:
|
||||
version:
|
||||
name: version
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.v.outputs.version }}
|
||||
date: ${{ steps.v.outputs.date }}
|
||||
prerelease: ${{ steps.v.outputs.prerelease }}
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- id: v
|
||||
name: Resolve version
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
. packaging/env.sh
|
||||
v="${INPUT_VERSION#v}"
|
||||
v="${v:-$VERSION}"
|
||||
if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
|
||||
echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1"
|
||||
exit 1
|
||||
fi
|
||||
case "$v" in *-*) pre=true ;; *) pre=false ;; esac
|
||||
{
|
||||
echo "version=$v"
|
||||
echo "date=$(date -u +%Y-%m-%d)"
|
||||
echo "prerelease=$pre"
|
||||
} >>"$GITHUB_OUTPUT"
|
||||
echo "### CADCraft v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
|
||||
|
||||
macos:
|
||||
name: macOS universal
|
||||
needs: version
|
||||
runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend)
|
||||
environment: release
|
||||
env:
|
||||
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-apple-darwin, x86_64-apple-darwin
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: release-macos-universal
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
run: cargo xtask version set "$CADCRAFT_VERSION"
|
||||
- name: Import signing certificate
|
||||
env:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
run: packaging/macos/import-cert.sh
|
||||
- name: Build, sign, notarize
|
||||
env:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: packaging/macos/package.sh --arch universal
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-macos
|
||||
path: dist/release/*
|
||||
if-no-files-found: error
|
||||
- name: Remove temporary keychain
|
||||
if: always()
|
||||
run: |
|
||||
if [ -n "${MACOS_KEYCHAIN:-}" ]; then security delete-keychain "$MACOS_KEYCHAIN" || true; fi
|
||||
|
||||
windows:
|
||||
name: Windows ${{ matrix.arch }}
|
||||
needs: version
|
||||
runs-on: windows-latest
|
||||
environment: release
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { arch: x64, target: x86_64-pc-windows-msvc }
|
||||
- { arch: x86, target: i686-pc-windows-msvc }
|
||||
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
|
||||
- { arch: arm64, target: aarch64-pc-windows-msvc }
|
||||
env:
|
||||
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: release-windows-${{ matrix.arch }}
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
shell: bash
|
||||
run: cargo xtask version set "$CADCRAFT_VERSION"
|
||||
- name: Install WiX
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet tool install --global wix --version 5.0.2
|
||||
wix extension add -g WixToolset.UI.wixext/5.0.2
|
||||
- name: Build, sign, package
|
||||
shell: pwsh
|
||||
env:
|
||||
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
|
||||
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-windows-${{ matrix.arch }}
|
||||
path: dist/release/*
|
||||
if-no-files-found: error
|
||||
|
||||
linux:
|
||||
name: Linux ${{ matrix.arch }}
|
||||
needs: version
|
||||
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
|
||||
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
|
||||
runs-on: ${{ matrix.runner }}
|
||||
# No `environment: release`: this job signs nothing, so it gets no release secrets.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { arch: x86_64, runner: ubuntu-22.04, deb: amd64 }
|
||||
- { arch: aarch64, runner: ubuntu-22.04-arm, deb: arm64 }
|
||||
env:
|
||||
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
NFPM_VERSION: 2.47.0
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install build and packaging tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev \
|
||||
desktop-file-utils appstream python3-yaml zsync
|
||||
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
|
||||
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
|
||||
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: release-linux-${{ matrix.arch }}
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
run: cargo xtask version set "$CADCRAFT_VERSION"
|
||||
- name: Build and package (AppImage, deb, rpm, tar.gz)
|
||||
run: packaging/linux/package.sh
|
||||
- name: Check the packages
|
||||
run: |
|
||||
dpkg-deb --info dist/release/*.deb
|
||||
dpkg-deb --contents dist/release/*.deb | grep -E 'usr/bin/cadcraft$|metainfo|applications'
|
||||
ldd target/release/cadcraft
|
||||
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.cadcraft.yml')); assert m['id'] == 'ai.storyteller.cadcraft'"
|
||||
for appimage in dist/release/*.AppImage; do
|
||||
chmod +x "$appimage"
|
||||
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
|
||||
# Update information is embedded, and the .zsync for delta updates sits beside it.
|
||||
# Without APPIMAGE_EXTRACT_AND_RUN: with it, the runtime passes --appimage-* options
|
||||
# on to the app (which then tries to open a window) instead of answering them.
|
||||
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
|
||||
test -s "$appimage.zsync"
|
||||
done
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-linux-${{ matrix.arch }}
|
||||
path: dist/release/*
|
||||
if-no-files-found: error
|
||||
|
||||
linux-riscv64:
|
||||
name: Linux riscv64
|
||||
needs: version
|
||||
# Cross-compiled on x86_64 (no hosted RISC-V runners) against the runner's own Ubuntu release
|
||||
# from ports.ubuntu.com, so the binaries need that release's glibc (24.04: 2.39). 22.04's
|
||||
# riscv64 ports lag its amd64 updates, which breaks the multiarch install. tar.gz only; the
|
||||
# CLI is smoke-tested under QEMU.
|
||||
runs-on: ubuntu-24.04
|
||||
# No `environment: release`: this job signs nothing, so it gets no release secrets.
|
||||
env:
|
||||
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: riscv64gc-unknown-linux-gnu
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: release-linux-riscv64
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
run: cargo xtask version set "$CADCRAFT_VERSION"
|
||||
- name: Install cross-compilation dependencies
|
||||
run: |
|
||||
. /etc/os-release
|
||||
sudo dpkg --add-architecture riscv64
|
||||
# Pin the existing (archive.ubuntu.com) sources to amd64; riscv64 comes from ports.
|
||||
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
|
||||
sudo sed -i '/^Types: deb/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
|
||||
fi
|
||||
if [ -f /etc/apt/sources.list ]; then
|
||||
sudo sed -i 's/^deb /deb [arch=amd64] /g' /etc/apt/sources.list
|
||||
sudo sed -i 's/^deb-src /deb-src [arch=amd64] /g' /etc/apt/sources.list
|
||||
fi
|
||||
for suite in "$VERSION_CODENAME" "$VERSION_CODENAME-updates" "$VERSION_CODENAME-security"; do
|
||||
echo "deb [arch=riscv64] http://ports.ubuntu.com/ubuntu-ports $suite main universe restricted multiverse"
|
||||
done | sudo tee /etc/apt/sources.list.d/riscv64.list
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
gcc-riscv64-linux-gnu binutils-riscv64-linux-gnu libc6-dev-riscv64-cross libc6-dev:riscv64 qemu-user \
|
||||
libxkbcommon-dev:riscv64 libwayland-dev:riscv64 libx11-dev:riscv64 libxrandr-dev:riscv64 \
|
||||
libxi-dev:riscv64 libgl1-mesa-dev:riscv64
|
||||
- name: Build and package (tar.gz)
|
||||
env:
|
||||
CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER: riscv64-linux-gnu-gcc
|
||||
PKG_CONFIG_SYSROOT_DIR: /
|
||||
PKG_CONFIG_PATH: /usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig
|
||||
PKG_CONFIG_ALLOW_CROSS: "1"
|
||||
CROSS_ARCH: riscv64
|
||||
CROSS_TARGET: riscv64gc-unknown-linux-gnu
|
||||
CROSS_COMPILE: riscv64-linux-gnu-
|
||||
EMULATOR: qemu-riscv64
|
||||
QEMU_LD_PREFIX: /usr/riscv64-linux-gnu
|
||||
run: packaging/linux/package.sh --formats tar
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-linux-riscv64
|
||||
path: dist/release/*.tar.gz
|
||||
if-no-files-found: error
|
||||
|
||||
flatpak:
|
||||
name: Flatpak ${{ matrix.arch }}
|
||||
needs: [version, linux]
|
||||
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
|
||||
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
|
||||
runs-on: ${{ matrix.runner }}
|
||||
# No `environment: release`: this job signs nothing, so it gets no release secrets.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { arch: x86_64, runner: ubuntu-24.04 }
|
||||
- { arch: aarch64, runner: ubuntu-24.04-arm }
|
||||
env:
|
||||
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-linux-${{ matrix.arch }}
|
||||
path: dist/linux
|
||||
- name: Install flatpak-builder
|
||||
run: |
|
||||
sudo apt-get update
|
||||
# librsvg2-common: the SVG pixbuf loader that the host's `appstreamcli compose` (run by
|
||||
# flatpak-builder) needs for any scalable icon.
|
||||
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
|
||||
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
|
||||
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
- name: Build the Flatpak bundle
|
||||
run: packaging/linux/flatpak-bundle.sh "dist/linux/cadcraft-$CADCRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-flatpak-${{ matrix.arch }}
|
||||
path: dist/release/*.flatpak
|
||||
if-no-files-found: error
|
||||
|
||||
web:
|
||||
name: Web (wasm)
|
||||
needs: version
|
||||
runs-on: ubuntu-latest
|
||||
# No `environment: release`: this job signs nothing, so it gets no release secrets.
|
||||
env:
|
||||
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
TRUNK_VERSION: 0.21.14
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: release-web
|
||||
- name: Install trunk
|
||||
run: |
|
||||
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
|
||||
| tar -xz -C "$HOME/.cargo/bin" trunk
|
||||
trunk --version
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
run: cargo xtask version set "$CADCRAFT_VERSION"
|
||||
- name: Build and zip
|
||||
run: packaging/web/package.sh
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-web
|
||||
path: dist/release/*
|
||||
if-no-files-found: error
|
||||
|
||||
freebsd:
|
||||
name: FreeBSD x86_64
|
||||
needs: version
|
||||
# GitHub has no FreeBSD runners: build inside a FreeBSD VM on a Linux runner.
|
||||
runs-on: ubuntu-latest
|
||||
# No `environment: release`: this job signs nothing, so it gets no release secrets.
|
||||
timeout-minutes: 300
|
||||
env:
|
||||
CADCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
CADCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build and package in a FreeBSD VM
|
||||
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1
|
||||
with:
|
||||
release: "14.3"
|
||||
usesh: true
|
||||
cpu: 4
|
||||
mem: 12288
|
||||
envs: "CADCRAFT_VERSION CADCRAFT_BUILD_DATE CADCRAFT_BUILD_SHA INPUT_VERSION"
|
||||
copyback: true
|
||||
prepare: |
|
||||
pkg install -y git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2 alsa-lib
|
||||
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||
run: |
|
||||
set -e
|
||||
. "$HOME/.cargo/env"
|
||||
git config --global --add safe.directory "*"
|
||||
if [ -n "$INPUT_VERSION" ]; then cargo xtask version set "$CADCRAFT_VERSION"; fi
|
||||
cargo build --release --locked -p cadcraft -p cadcraft-cli
|
||||
name="cadcraft-$CADCRAFT_VERSION-freebsd-x86_64"
|
||||
mkdir -p "dist/release/$name"
|
||||
cp target/release/cadcraft target/release/cadcraft-cli README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md "dist/release/$name/"
|
||||
mkdir -p "dist/release/$name/icons"
|
||||
cp -R assets/app-icon/hicolor "dist/release/$name/icons/" 2>/dev/null || true
|
||||
(cd dist/release && tar -czf "$name.tar.gz" "$name" && rm -rf "$name")
|
||||
# Keep the copy back to the runner small.
|
||||
rm -rf target
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-freebsd
|
||||
path: dist/release/*
|
||||
if-no-files-found: error
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
release:
|
||||
name: Draft GitHub Release
|
||||
needs: [version, macos, windows, linux, linux-riscv64, flatpak, web, freebsd]
|
||||
# Only the `release` branch publishes; a dry run on another branch stops before this job.
|
||||
if: github.ref == 'refs/heads/release'
|
||||
runs-on: ubuntu-latest
|
||||
environment: release
|
||||
needs: git-sources
|
||||
permissions:
|
||||
# The reusable release workflow tags and uploads the draft release.
|
||||
contents: write
|
||||
env:
|
||||
VERSION: ${{ needs.version.outputs.version }}
|
||||
PRERELEASE: ${{ needs.version.outputs.prerelease }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: release-*
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: Checksums
|
||||
working-directory: artifacts
|
||||
run: |
|
||||
sha256sum -- * | tee SHA256SUMS.txt
|
||||
- name: Create or update the draft release
|
||||
working-directory: artifacts
|
||||
run: |
|
||||
tag="v$VERSION"
|
||||
title="CADCraft v$VERSION"
|
||||
pre=()
|
||||
if [ "$PRERELEASE" = true ]; then pre=(--prerelease); fi
|
||||
if draft="$(gh release view "$tag" --json isDraft --jq .isDraft 2>/dev/null)"; then
|
||||
if [ "$draft" != "true" ]; then
|
||||
echo "::error::Release $tag is already published. Bump the version (cargo xtask version set) before pushing to release."
|
||||
exit 1
|
||||
fi
|
||||
echo "Updating draft $tag: replacing its assets"
|
||||
gh release view "$tag" --json assets --jq '.assets[].name' | while read -r asset; do
|
||||
gh release delete-asset "$tag" "$asset" --yes
|
||||
done
|
||||
gh release edit "$tag" --draft --title "$title" --target "$GITHUB_SHA" --prerelease="$PRERELEASE"
|
||||
gh release upload "$tag" --clobber -- *
|
||||
else
|
||||
echo "Creating draft $tag"
|
||||
gh release create "$tag" --draft --title "$title" --target "$GITHUB_SHA" --generate-notes "${pre[@]}" -- *
|
||||
fi
|
||||
{
|
||||
echo "Draft release **$title** at \`${GITHUB_SHA::9}\`:"
|
||||
echo
|
||||
sed 's/^/ /' SHA256SUMS.txt
|
||||
} >>"$GITHUB_STEP_SUMMARY"
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
app-name: cadcraft
|
||||
app-title: CADCraft
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
version: ${{ inputs.version }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
|
||||
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
name: SonarCloud
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
sonarcloud:
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
secrets: inherit
|
||||
@@ -0,0 +1,32 @@
|
||||
# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64
|
||||
# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed
|
||||
# binaries are ARM64, run the CLI natively, and uninstall.
|
||||
name: Windows ARM64
|
||||
|
||||
# Nightly on main and on pushes to `release` (dependency and runner-image drift shows up within a
|
||||
# day, and always before a release ships), and on PRs that change the Windows packaging itself.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "3 5 * * *"
|
||||
push:
|
||||
branches: [release]
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/windows-arm64.yml
|
||||
- packaging/windows/**
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: windows-arm64-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
windows-arm64:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
|
||||
with:
|
||||
app-name: cadcraft
|
||||
app-dir: CADCraft
|
||||
@@ -24,12 +24,13 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr
|
||||
## Non-negotiables
|
||||
- **Clean-room.** AutoCAD is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic drawings, take screenshots (by window id) stored only under `plan/autocad/screenshots/` (never committed). **Never** read, disassemble or copy anything inside the AutoCAD bundle (names/listings only); never copy Autodesk fonts (SHX), hatch patterns (`.pat`), linetypes (`.lin`), templates, CUI/PGP files, icons, artwork or help text; never commit files produced by AutoCAD. File formats come from public specifications (Autodesk's published DXF Reference, the Open Design Alliance's public DWG specification) and our own synthetic tests. Never copy or link GPL/LGPL/AGPL code (LibreDWG, LibreCAD, QCAD, FreeCAD's planegcs, SolveSpace, OpenCASCADE) — don't even read their sources.
|
||||
- **Assets — absolutely essential.** CADCraft contains **no Autodesk, Adobe or Avid iconography, images, fonts, patterns or artwork — ever.** Every icon is drawn in code (`crates/ui-egui/src/icons.rs`), every hatch pattern and linetype is our own definition (`crates/doc/src/library.rs`), the drafting font is our own (`crates/fonts/src/stroke.rs`). Any file asset must be original, public domain/CC0, OSI-licensed, or redistributable Creative Commons (or licensed open source by a contributor who made it), and **must have a row in `ATTRIBUTION.md`** with author, source and licence (`cargo xtask assets` enforces it). The only exception is the ArtCraft brand in `docs/brand/` (trademarks, `docs/brand/LICENSE-brand.txt`). Screenshots of Autodesk software are never committed. Breaking this rule is the most serious mistake you can make in this repo.
|
||||
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`), never a `Cargo.toml` dependency. Code and tests must work without it.
|
||||
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`, embedded by `crates/fonts/build.rs`), never a `Cargo.toml` dependency. Code and tests must work without it.
|
||||
- **Shared test corpora** live in separate repos (`storytold/<app>-corpus`); never commit large binary fixtures here.
|
||||
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (`CommandSpec`: id = AutoCAD's command name in lower case, label, menu path, shortcut, aliases, params doc, `enabled`, JSON `run`, optional `interactive` prompt machine) + tests. UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The command line, menus, toolbar, Tool Sets, scripts, CLI, control channel and MCP all reach the same commands.
|
||||
- **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence.
|
||||
- **Layering** is enforced by `cargo xtask layers`: L0 `geom`, `dxf` → L1 `color`, `doc` → L2 `fonts`, `render`, `constraints` → L3 `io` → L4 `engine` → L5 `ui-egui`, `mcp` → apps. Nothing below L5 depends on egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.**
|
||||
- **The UI is thin**: panels read engine state and act through `app.run(id, params)` / `app.start(id)` / `app.cmdline(text)`. Colours come from `theme::Tokens`.
|
||||
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
|
||||
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
|
||||
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds, and push to `main`.
|
||||
|
||||
|
||||
@@ -23,6 +23,11 @@ Generated-in-code assets are original and have no file to list:
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `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`. |
|
||||
| `krilla 0.8.2 / icc/sRGB-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sRGB-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sRGB-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 `af4efe28f6d311799865f325ba39184a2e978b113ca74124d60af7de22b105f4`. |
|
||||
| `krilla 0.8.2 / icc/sRGB-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sRGB-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sRGB-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 `c56e1685d888f5edb92fe07f2750f387f8fe8e91b32ff8fb0b56bfbbb9458353`. |
|
||||
| `assets/app-icon/hicolor/128x128/apps/ai.storyteller.cadcraft.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | Linux hicolor icon |
|
||||
| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.cadcraft.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | Linux hicolor icon |
|
||||
| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.cadcraft.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | Linux hicolor icon |
|
||||
@@ -57,3 +62,17 @@ Generated-in-code assets are original and have no file to list:
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | @dmatviichuk | Original Ukrainian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/de.tsv` | the CADCraft contributors | Original German translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/es.tsv` | @PedroGuille | Original Spanish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/pt_br.tsv` | @WladmirJunior | Original Brazilian Portuguese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending |
|
||||
|
||||
@@ -24,7 +24,7 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr
|
||||
## Non-negotiables
|
||||
- **Clean-room.** AutoCAD is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic drawings, take screenshots (by window id) stored only under `plan/autocad/screenshots/` (never committed). **Never** read, disassemble or copy anything inside the AutoCAD bundle (names/listings only); never copy Autodesk fonts (SHX), hatch patterns (`.pat`), linetypes (`.lin`), templates, CUI/PGP files, icons, artwork or help text; never commit files produced by AutoCAD. File formats come from public specifications (Autodesk's published DXF Reference, the Open Design Alliance's public DWG specification) and our own synthetic tests. Never copy or link GPL/LGPL/AGPL code (LibreDWG, LibreCAD, QCAD, FreeCAD's planegcs, SolveSpace, OpenCASCADE) — don't even read their sources.
|
||||
- **Assets — absolutely essential.** CADCraft contains **no Autodesk, Adobe or Avid iconography, images, fonts, patterns or artwork — ever.** Every icon is drawn in code (`crates/ui-egui/src/icons.rs`), every hatch pattern and linetype is our own definition (`crates/doc/src/library.rs`), the drafting font is our own (`crates/fonts/src/stroke.rs`). Any file asset must be original, public domain/CC0, OSI-licensed, or redistributable Creative Commons (or licensed open source by a contributor who made it), and **must have a row in `ATTRIBUTION.md`** with author, source and licence (`cargo xtask assets` enforces it). The only exception is the ArtCraft brand in `docs/brand/` (trademarks, `docs/brand/LICENSE-brand.txt`). Screenshots of Autodesk software are never committed. Breaking this rule is the most serious mistake you can make in this repo.
|
||||
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`), never a `Cargo.toml` dependency. Code and tests must work without it.
|
||||
- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`, embedded by `crates/fonts/build.rs`), never a `Cargo.toml` dependency. Code and tests must work without it.
|
||||
- **Shared test corpora** live in separate repos (`storytold/<app>-corpus`); never commit large binary fixtures here.
|
||||
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (`CommandSpec`: id = AutoCAD's command name in lower case, label, menu path, shortcut, aliases, params doc, `enabled`, JSON `run`, optional `interactive` prompt machine) + tests. UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The command line, menus, toolbar, Tool Sets, scripts, CLI, control channel and MCP all reach the same commands.
|
||||
- **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence.
|
||||
|
||||
Generated
+1359
-338
File diff suppressed because it is too large
Load Diff
+54
-7
@@ -4,10 +4,10 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
# default-members
|
||||
|
||||
[workspace.package]
|
||||
version = "0.5.0"
|
||||
version = "0.13.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.90"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/cadcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
@@ -24,23 +24,44 @@ cadcraft-io = { path = "crates/io" }
|
||||
cadcraft-engine = { path = "crates/engine" }
|
||||
cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab" }
|
||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab", default-features = false }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
rayon = "1"
|
||||
|
||||
# rendering / formats
|
||||
tiny-skia = { version = "0.11", default-features = false, features = ["std", "simd", "png-format"] }
|
||||
skrifa = "0.47"
|
||||
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd", "png-format"] }
|
||||
lyon_tessellation = "1.0.22"
|
||||
skrifa = "0.48"
|
||||
# Text shaping (OpenType GSUB/GPOS, HarfBuzz port on read-fonts; egui's epaint is still on 0.12,
|
||||
# so the graph has both) and the Unicode Bidirectional Algorithm for right-to-left drawing text.
|
||||
harfrust = "0.14"
|
||||
unicode-bidi = "0.3.18"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
encoding_rs = "0.8.35"
|
||||
# XML for the SVG reader (streaming parser, no entity expansion beyond the five predefined ones)
|
||||
quick-xml = "0.42"
|
||||
|
||||
# ui
|
||||
egui = "0.36"
|
||||
eframe = { version = "0.36", default-features = false }
|
||||
egui-wgpu = "0.36"
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab", features = ["egui"] }
|
||||
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
egui_kittest = "0.37"
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
web-time = "1.1"
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab", features = ["egui"] }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -55,12 +76,38 @@ type_complexity = "allow"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
debug = false
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = "thin"
|
||||
codegen-units = 16
|
||||
debug = 0
|
||||
|
||||
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
|
||||
# (Cargo ignores dependency-local patches).
|
||||
[patch.crates-io]
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9f89fe8f6d72ab4db4cc06f186381a6a254463ab" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -15,10 +15,36 @@ Mozilla Public License 2.0 and is used unmodified as a separate library (crates/
|
||||
is available from crates.io and the repository above.
|
||||
|
||||
|
||||
None: every bundled asset is original to CADCraft (icons, drafting font, hatch patterns and
|
||||
linetypes are drawn or defined in code). The per-file list is in ATTRIBUTION.md. Builds made with
|
||||
the optional craft-fonts input (CRAFT_FONTS_DIR) embed the fonts listed in its ATTRIBUTION.md,
|
||||
each under the SIL Open Font License 1.1.
|
||||
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
|
||||
The UI also bundles the egui font inputs described below. The per-file list is in ATTRIBUTION.md.
|
||||
Builds made with the optional craft-fonts input (CRAFT_FONTS_DIR) embed the fonts listed in its
|
||||
ATTRIBUTION.md, each under the SIL Open Font License 1.1.
|
||||
|
||||
CADCraft is an independent project and is not affiliated with, sponsored by or endorsed by
|
||||
Autodesk, Inc. AutoCAD and DWG are trademarks of Autodesk, Inc.
|
||||
|
||||
|
||||
The PDF writer in the pinned craft-pdf 0.1.0 / Krilla 0.8.2 dependency embeds four Compact ICC
|
||||
Profiles by Clinton Ingram, under CC0-1.0. They are unmodified dependency assets; no profile file
|
||||
is copied into this repository. Per-file sources and SHA-256 hashes are in ATTRIBUTION.md.
|
||||
Source: https://github.com/LaurenzV/krilla/tree/3ffdf0588cf98050aad6edba51ca70162e1fb5b5/crates/krilla/icc
|
||||
(pinned through https://github.com/storytold/craft-libs/tree/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc).
|
||||
CC0 1.0 Universal: https://creativecommons.org/publicdomain/zero/1.0/
|
||||
Pinned licence text: https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/LICENSE
|
||||
|
||||
The UI's egui-icons.ttf subset and emoji-icon-font.ttf fallback are provided by epaint_default_fonts
|
||||
and registered through egui's default font definitions. They derive from emoji-icon-font by
|
||||
John Slegers, under the MIT License. The subset and full face share the following upstream notice.
|
||||
Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
|
||||
Original: https://github.com/jslegers/emoji-icon-font
|
||||
The following text is reproduced verbatim from emoji-icon-font-mit-license.txt:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014 John Slegers
|
||||
|
||||
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.
|
||||
|
||||
@@ -7,14 +7,18 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.cadcraft.png" width="128" height="128" alt="CADCraft icon: a drafting set square and compass arc on a blue grid tile">
|
||||
</p>
|
||||
|
||||
<h1 align="center">CADCraft</h1>
|
||||
|
||||
<p align="center">
|
||||
<b>Computer-aided design and drafting; an open-source, clean-room reimplementation of Autodesk AutoCAD, rebuilt in pure Rust.</b>
|
||||
<b>Computer-aided design and drafting; an open-source, modern 2D and 3D CAD application, built in pure Rust.</b>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
A fast, open-source take on the AutoCAD workflow: the command line, object snaps, layers,
|
||||
A fast, open-source CAD workflow: the command line, object snaps, layers,
|
||||
dimensions, hatches, blocks and DXF drawings you already know. It runs natively on macOS,
|
||||
Windows, Linux and FreeBSD, and in the browser via WebAssembly.<br>
|
||||
<i>By the ArtCraft team.</i>
|
||||
@@ -26,6 +30,9 @@
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-0b6f88?style=flat-square">
|
||||
<img alt="Agent-drivable over MCP" src="https://img.shields.io/badge/agents-MCP-14a3c7?style=flat-square">
|
||||
<img alt="Status: early development" src="https://img.shields.io/badge/status-early%20development-f07a3a?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_cadcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/cadcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -111,11 +118,13 @@ numbers):
|
||||
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
|
||||
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
|
||||
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
|
||||
| Interface languages | English and Ukrainian (Українська), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
|
||||
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar) and Turkish (Türkçe), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
|
||||
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
|
||||
|
||||
## Quick start
|
||||
|
||||
CADCraft requires Rust 1.95 or later.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/storytold/cadcraft
|
||||
cd cadcraft
|
||||
@@ -131,11 +140,17 @@ offset 0.25 then pick the circle and a side
|
||||
zoom e zoom to extents
|
||||
```
|
||||
|
||||
The web build: `cd apps/cadcraft-web && trunk serve` (needs [trunk](https://trunkrs.dev)).
|
||||
The web build: `cd apps/cadcraft-web && trunk serve` (needs [trunk](https://github.com/trunk-rs/trunk)).
|
||||
|
||||
### Fonts
|
||||
|
||||
CADCraft never ships fonts; it uses the TrueType/OpenType fonts installed on your system. SHX
|
||||
CADCraft has no fonts in its repository; it uses the TrueType/OpenType fonts installed on your
|
||||
system. Builds made with the optional [craft-fonts](https://github.com/storytold/craft-fonts)
|
||||
input (`CRAFT_FONTS_DIR=<absolute path to a checkout> cargo build --release`) also embed its
|
||||
fonts: BIZ UDPGothic, BIZ UDMincho and Shippori Mincho (Japanese) and Noto Sans Arabic (the web
|
||||
build, which has no system fonts, only BIZ UDPGothic Regular and Noto Sans Arabic). A text style
|
||||
can use them by family name, and they draw characters a text's font lacks when no installed
|
||||
wide-coverage CJK font has them. Without `CRAFT_FONTS_DIR` nothing is embedded. SHX
|
||||
fonts (including big fonts such as `chineset.shx`) aren't read yet: text in an SHX style is drawn
|
||||
with our own stroke font, and any character a text's font lacks (CJK, for example) is drawn from
|
||||
an installed font that has it, preferring wide-coverage fonts such as Noto Sans CJK, Source Han
|
||||
@@ -149,6 +164,26 @@ run) an environment variable, steer this:
|
||||
|
||||
`.` clears either one.
|
||||
|
||||
**Your own fonts.** Any `.ttf`, `.otf` or `.ttc` font works: install it in the system font folder
|
||||
(Windows `C:\Windows\Fonts` or per-user fonts, macOS `/Library/Fonts` or `~/Library/Fonts`,
|
||||
Linux and the BSDs `/usr/share/fonts`, `/usr/local/share/fonts`, `~/.local/share/fonts` or
|
||||
`~/.fonts`) and name it in a text style (`STYLE`, or `style {"name":"FA","font":"Vazirmatn"}`)
|
||||
by file name (`Vazirmatn-Regular.ttf`) or family name (`Vazirmatn`), or inline in MTEXT with
|
||||
`\fVazirmatn;`. Restart CADCraft after installing a font: the font folders are scanned once.
|
||||
|
||||
**Right-to-left text (Persian, Arabic, Urdu, Hebrew).** TEXT and MTEXT lines are laid out with the
|
||||
Unicode Bidirectional Algorithm (the paragraph direction comes from its first letter, so numbers
|
||||
and Latin words inside Persian text keep their own order), and Arabic-script text is shaped with
|
||||
OpenType (contextual letter forms, lam-alef and other ligatures, ZWNJ / ZWJ, mark positioning).
|
||||
Justification (left, centre, right, MTEXT attachment and wrapping) still refers to the text's box.
|
||||
Our stroke font has no Arabic letters, so Persian in a stroke-font style is drawn from an
|
||||
installed font that has them: Vazirmatn, Noto Naskh Arabic, Noto Sans Arabic, Segoe UI, Tahoma,
|
||||
Arial and DejaVu Sans are looked for first. To choose the font, install a free Persian font such
|
||||
as [Vazirmatn](https://github.com/rastikerdar/vazirmatn) (SIL Open Font License) and either use it
|
||||
in the text style or set `FONTFALLBACK` (`CADCRAFT_FONTFALLBACK="Vazirmatn"`). Formatting changes
|
||||
inside a word (an MTEXT colour change in the middle of a Persian word) break the joining at that
|
||||
point.
|
||||
|
||||
### Logs
|
||||
|
||||
The desktop app writes its `log` records to standard error and to `logs/cadcraft.log` in the
|
||||
@@ -183,6 +218,10 @@ cadcraft-cli convert drawing.dxf drawing.svg
|
||||
cadcraft-cli convert drawing.dwg detail.png --window 0,0,20000,15000
|
||||
cadcraft-cli run drawing.dwg --cmd 'zoom {"mode":"window","p1":[0,0],"p2":[20000,15000]}' --export detail.png
|
||||
cadcraft-cli run drawing.dwg --cmd 'select {"window":[[0,0],[20000,15000]]}' --cmd 'zoom {"mode":"object"}' --export sel.png
|
||||
|
||||
# Act on what an earlier --cmd made: {last} is the last handle it returned.
|
||||
cadcraft-cli run --metric --cmd 'layout.set {"name":"Layout1"}' \
|
||||
--cmd 'mview {"p1":[20,20],"p2":[200,150]}' --cmd 'viewport.set {"handle":"{last}","scale":1}'
|
||||
```
|
||||
|
||||
How image exports (PNG 2400×1600, SVG, PDF) are framed: `convert` fits the model-space extents.
|
||||
@@ -196,6 +235,9 @@ MCP tools include `command_line` (type at the prompt), `execute` (any command wi
|
||||
`screenshot` and `ui_click`. The desktop app's JSON control channel is documented in
|
||||
[docs/control-protocol.md](docs/control-protocol.md).
|
||||
|
||||
To run LISP routines, scripts and alias files, or to drive CADCraft from your own programs, see
|
||||
[docs/customization.md](docs/customization.md).
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
@@ -213,10 +255,35 @@ apps: cadcraft · cadcraft-cli · cadcraft-web
|
||||
Nothing below `ui-egui` knows about egui, so the front end can be replaced. `cargo xtask ci`
|
||||
checks formatting, clippy, tests, asset attribution, the crate layering and the wasm build.
|
||||
|
||||
Drafting and layer-palette icon buttons use the pinned `craft-ui` button component for interaction,
|
||||
accessible labels and keyboard focus. CADCraft keeps its multicolor icon painter, dark palette,
|
||||
disabled tint and tool commands. The native host saves workspace visibility and toolset choices
|
||||
atomically; `CADCRAFT_CONFIG_DIR` selects an isolated profile. Compact toolbar groups move into a
|
||||
More menu, and status readouts truncate with a full-value tooltip before they reach layout tabs.
|
||||
Painted toolbar and tab controls
|
||||
have accessible labels and visible keyboard focus. Property controls remain application-specific.
|
||||
|
||||
## Accessibility
|
||||
|
||||
### System cursor
|
||||
|
||||
Over the drawing area CADCraft hides the system cursor and draws its own crosshair. Tools that follow the system cursor (Windows Magnifier set to follow or centre the mouse pointer, other screen magnifiers, screen recorders, remote desktops) lose track of it there. Turn on **View ▸ Accessibility ▸ Show System Cursor** to keep a small system crosshair visible at the centre of the drawn one, or start CADCraft with the environment variable `CADCRAFT_SYSTEM_CURSOR=1` (on Windows, set it once with `setx CADCRAFT_SYSTEM_CURSOR 1` and start CADCraft again). Agents can switch it with the control channel: `ui.set {"systemCursor": true}`.
|
||||
|
||||
### Animation effects
|
||||
|
||||
CADCraft follows the operating system's animation setting. When the system is set to show no animations, dialogs, menus and tooltips appear at once instead of fading in, collapsing sections and scroll bars change at once, and the mouse wheel scrolls lists a whole step at a time instead of gliding. Zooming the drawing with the wheel always moves a whole step; with Ctrl held (a touchpad pinch, on Windows) it glides to the new zoom only while animation effects show.
|
||||
|
||||
| System | Where the setting is |
|
||||
|---|---|
|
||||
| Windows | Settings ▸ Accessibility ▸ Visual effects ▸ Animation effects |
|
||||
| macOS | System Settings ▸ Accessibility ▸ Reduce motion |
|
||||
| Linux, BSD | the desktop's reduced-motion (or animations) setting, read through the XDG Desktop Portal |
|
||||
| Web | the browser's `prefers-reduced-motion` |
|
||||
|
||||
A change to the system setting is picked up while CADCraft runs, within a few seconds. To choose for CADCraft alone, use **View ▸ Accessibility ▸ Animation Effects**: **Use System Setting** (the default), **On** or **Off**. Options ▸ Display has the same choice. Agents can set it with the control channel: `ui.set {"animations": "off"}` (`"system"`, `"on"` or `"off"`), and `ui.inspect` reports whether animations show (`animations`).
|
||||
|
||||
Drafting feedback is not an animation effect and stays as it is: rubber bands and previews, snap markers, the pause that acquires an object snap tracking point, the text cursor's blink, the spinner shown while a drawing opens, and pan and zoom, which follow the pointer and the wheel directly.
|
||||
|
||||
## Roadmap
|
||||
|
||||
See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of remaining work, and [docs/gaps.md](docs/gaps.md) for everything still missing.
|
||||
@@ -225,6 +292,14 @@ See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of
|
||||
|
||||
**Download CADCraft** from GitHub: the [latest release](https://github.com/storytold/cadcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/cadcraft/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
|
||||
|
||||
> [!WARNING]
|
||||
> Download official CADCraft builds from the [storytold/cadcraft releases](https://github.com/storytold/cadcraft/releases). Verify that the repository owner is `storytold`. Before you run a download, check that its checksum matches the line for that file in the release's `SHA256SUMS.txt`:
|
||||
>
|
||||
> ```sh
|
||||
> shasum -a 256 cadcraft-<ver>-macos-universal.dmg # macOS (on Linux: sha256sum FILE)
|
||||
> Get-FileHash .\cadcraft-<ver>-windows-x64.msi # Windows PowerShell
|
||||
> ```
|
||||
|
||||
### Windows
|
||||
|
||||
| Build | Installer | Portable |
|
||||
@@ -340,9 +415,9 @@ ArtCraft Team and are not covered by this license. They may be used only unmodif
|
||||
part of this repository and CADCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
Forks and modified versions must remove them.
|
||||
|
||||
<sub>Autodesk, AutoCAD and DWG are trademarks or registered trademarks of Autodesk, Inc. in the United States and/or other countries. CADCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Autodesk, Inc.; these names are used only to describe the workflows and file formats it is compatible with.</sub>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
|
||||
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
|
||||
</p>
|
||||
|
||||
Tool Sets, Layers, and Properties can be regrouped, split, floated within the app window, closed, and reopened. The drawing canvas stays visible and cannot be closed or turned into a tab. Drag a panel header to a target edge or another header. Its context menu offers Float panel, Move to group, and Close panel. Existing panel toggles reopen panels at their saved location; Reset Panel Layout restores the app layout. Floating panels remain inside the current app window.
|
||||
|
||||
+20
-7
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, ~2 points (38% → 40% ready for real work) and ~125–190 Opus 5.5 hours away (the four failing core workflows of the [alpha gate](docs/roadmap.md#alpha-gate))
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (hours to ~95% for each readiness number) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** trivial (progress log: proxy objects keep their class through a save, #1812; previously minor: HATCHEDIT boundary add/remove progress) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
|
||||
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
|
||||
@@ -10,8 +10,8 @@ scriptable CLI, a web build, Linux and FreeBSD builds, and a free licence.
|
||||
|
||||
**Why pre-alpha:** four of AutoCAD's five core workflows fail the [alpha gate](docs/roadmap.md#alpha-gate).
|
||||
Precise drafting lacks object snap tracking and has stubbed TRIM/EXTEND/OFFSET options; blocks
|
||||
can't be edited (no block editor, REFEDIT or xrefs); plots ignore plot styles; and a DWG saved by
|
||||
CADCraft drops everything it doesn't model, is always R2000 and has never been checked in
|
||||
can't be edited in a block editor (REFEDIT edits them in place, xrefs not yet); plots ignore plot styles; and a DWG saved by
|
||||
CADCraft drops everything it doesn't model and has never been checked in
|
||||
AutoCAD. Dimensioning passes. Ready for real work (≈ 38%) is also under the ~40% alpha bar. Beta
|
||||
is ≈ 600–930 h away.
|
||||
|
||||
@@ -80,8 +80,8 @@ Hours are Opus 5.5 agent wall-clock hours, calibrated on this repo's own build:
|
||||
|
||||
## Languages
|
||||
|
||||
AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English only. Detail:
|
||||
[localization-parity.md](docs/localization-parity.md).
|
||||
AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus partial
|
||||
Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
| Language | Status | UI translated |
|
||||
|---|---|---:|
|
||||
@@ -94,11 +94,12 @@ AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English only. D
|
||||
| Portuguese | none | 0% |
|
||||
| Indonesian | none | 0% |
|
||||
| Japanese | none | 0% |
|
||||
| German | none | 0% |
|
||||
| Greek | complete current catalog | 1,330 current source keys; independent proofreading pending |
|
||||
| German | partial | ≈ 100% of the catalog (989 rows) |
|
||||
| Korean | none | 0% |
|
||||
| Vietnamese | none | 0% |
|
||||
|
||||
Other languages shipped: Ukrainian, partial (936 catalog rows, landed with #36; engine messages stay English).
|
||||
Other languages shipped: Ukrainian and German (989 catalog rows each; Ukrainian landed with #36), Brazilian Portuguese, Spanish, Czech, Russian, French, Simplified Chinese and Italian (1,227 rows, 2026-10-12); engine messages stay English.
|
||||
|
||||
## Upcoming
|
||||
|
||||
@@ -118,6 +119,10 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md)
|
||||
|
||||
| Date | Entry |
|
||||
|---|---|
|
||||
| 2026-10-21 | DXF save keeps each proxy object's and proxy entity's class: its class number (group 91) is renumbered to the rewritten CLASSES instead of naming another class, so AutoCAD's visual styles in an R14 file no longer come back as SCALE or MLEADERSTYLE (#1812) |
|
||||
| 2026-10-14 | HATCHEDIT adds boundaries from internal points or closed objects and removes selected loops in the dialog, command line and JSON command; associative links and undo are covered by tests. |
|
||||
| 2026-10-12 | TRIM: a pick after a closed polyline's last cut keeps only the complementary run instead of an extra circuit of the outline (#726) |
|
||||
| 2026-10-12 | HATCHEDIT refuses an explicit bad `scale` or `angle` before it edits anything, so a rejected request leaves the drawing, undo and redo as they were (#724) |
|
||||
| 2026-10-10 | Merged main: Ukrainian interface (#36, first string catalog), Dynamic Input pointer boxes with Tab and relative entry (#60), press-drag selection windows (#63), WIPEOUT and hatch gradients kept through DXF/DWG save (#147, #162), SETVAR DIM* as style overrides (#129), UNITS dialog (#38), close-window save prompt (#47), DIMANGULAR on circles (#20), cargo fmt fixed on main. UI/UX 40% → 43% (dynamic input 15% → 45%), localization 3% → 5%; ready for real work ≈ 37% → 38% (weighted 37.2% → 37.7%), mainstream 27% → 28%, essentials 45% → 46%. Beta is now ~37 points away; hours unchanged within rounding. |
|
||||
| 2026-10-10 | Added mainstream practitioner (≈ 27%) and essentials user (≈ 45%) numbers; ready for real work unchanged at ≈ 37%. User evidence: 2 praise comments, 0 "switched from AutoCAD" reports, 27 of 37 open issues on the core path. |
|
||||
| 2026-10-10 | Stage re-normalized from alpha to **pre-alpha** under the craftrules core-workflow gate: drafting with tracking, blocks, plotting and lossless DWG save fail; dimensioning passes. Alpha is ≈ 125–190 h away. |
|
||||
@@ -131,9 +136,17 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md)
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-21 | trivial | Progress log: proxy objects keep their class through a save (#1812) |
|
||||
| 2026-10-14 | minor | Progress log: HATCHEDIT boundary add/remove |
|
||||
| 2026-10-12 | trivial | Progress log: closed-polyline TRIM (#726) |
|
||||
| 2026-10-12 | trivial | Progress log: HATCHEDIT numeric validation (#724) |
|
||||
| 2026-10-10 | minor | Merged main's changes (Ukrainian catalog, dynamic input pointer boxes, DXF fixes); UI/UX and localization numbers updated |
|
||||
| 2026-10-10 | minor | Readiness-by-audience table with hours to ~95% for each number |
|
||||
| 2026-10-10 | minor | Mainstream practitioner and essentials user headline numbers |
|
||||
| 2026-10-10 | minor | Stage alpha → pre-alpha under the core-workflow gate; banner, why, headline row |
|
||||
| 2026-10-10 | major | Restructured to the progress-docs standard (stage, two numbers, dimensions, features, languages, upcoming, log); full re-measure; milestone detail moved to docs/roadmap.md, parity assessment to docs/target-app-parity.md |
|
||||
| 2026-10-07 | major | Alpha checklist, milestone table, ≈ 29% weighted parity estimate |
|
||||
|
||||
## Shared UI workspace integration
|
||||
|
||||
Tool Sets, Layers and Properties use shared docking with persisted layouts, keyboard focus and compact toolbar overflow. No milestone percentage change.
|
||||
|
||||
+403
-27
@@ -5,26 +5,63 @@
|
||||
//! cadcraft-cli convert IN.dxf OUT.(dxf|svg|png) [--window x0,y0,x1,y1 | --view extents|current]
|
||||
//! cadcraft-cli run [FILE|--sample|--metric] [--script TEXT|--script-file F.scr] [--cmd 'id {json}']... [--save OUT] [--export OUT.png] [--window ... | --view ...]
|
||||
//! cadcraft-cli commands [FILTER] command catalog (JSON)
|
||||
//! cadcraft-cli mcp [--connect HOST:PORT] MCP server on stdio (headless or bridged to the app)
|
||||
//! cadcraft-cli mcp [--connect HOST:PORT [--lazy] [--launch]] MCP server on stdio (headless or bridged to the app)
|
||||
//! cadcraft-cli perf [N] timing table on a synthetic N-entity drawing
|
||||
//! cadcraft-cli perf FILE canvas display-list build of a drawing, zoomed in step by step
|
||||
//! cadcraft-cli sample (bracket|floorplan) OUT write a built-in sample drawing
|
||||
//! ```
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
/// `println!` that doesn't panic when stdout is closed (`cadcraft-cli commands | head`) with
|
||||
/// "failed printing to stdout: Broken pipe (os error 32)". Once stdout has failed, later output is
|
||||
/// dropped and the work goes on: see `stdout_failed`.
|
||||
macro_rules! outln {
|
||||
($($arg:tt)*) => {{
|
||||
use std::io::Write as _;
|
||||
if !$crate::stdout_gone() {
|
||||
if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
|
||||
$crate::stdout_failed(e);
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
use cadcraft_engine::doc::Space;
|
||||
use cadcraft_engine::doc::{Handle, Space};
|
||||
use cadcraft_engine::geom::{Bounds2, Vec2};
|
||||
use cadcraft_engine::{Session, View};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
/// Set once a write to stdout has failed; later output is dropped.
|
||||
static STDOUT_GONE: AtomicBool = AtomicBool::new(false);
|
||||
/// Set when stdout failed for a reason other than a closed reader: the exit status becomes 1.
|
||||
static STDOUT_ERROR: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
fn stdout_gone() -> bool {
|
||||
STDOUT_GONE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// stdout went away. The program doesn't stop there: the rest of `run` (later `--cmd` results,
|
||||
/// `--save`, `--export`) still happens, so `cadcraft-cli run … --save out.dxf | head` keeps the
|
||||
/// drawing. A reader that stopped early (a closed pipe) is not an error, as in ripgrep; any other
|
||||
/// write error is reported and makes the exit status 1.
|
||||
fn stdout_failed(e: std::io::Error) {
|
||||
if STDOUT_GONE.swap(true, Ordering::Relaxed) || e.kind() == std::io::ErrorKind::BrokenPipe {
|
||||
return;
|
||||
}
|
||||
eprintln!("cadcraft-cli: can't write to stdout: {e}");
|
||||
STDOUT_ERROR.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
const USAGE: &str = "usage:
|
||||
cadcraft-cli info FILE.dxf
|
||||
cadcraft-cli convert IN.dxf OUT.(dxf|dwg|svg|png|pdf) [FRAMING]
|
||||
cadcraft-cli run [FILE | --sample | --metric] [--script TEXT] [--script-file F.scr] [--cmd 'id {json}']... [--save OUT.dxf] [--export OUT.(png|svg|pdf)] [FRAMING]
|
||||
cadcraft-cli commands [FILTER]
|
||||
cadcraft-cli mcp [--connect HOST:PORT]
|
||||
cadcraft-cli perf [N]
|
||||
cadcraft-cli mcp [--connect HOST:PORT [--lazy] [--launch]]
|
||||
cadcraft-cli perf [N | FILE]
|
||||
cadcraft-cli sample (bracket|floorplan) OUT.(dxf|dwg|svg|png)
|
||||
cadcraft-cli --version
|
||||
|
||||
@@ -36,7 +73,15 @@ image framing (png 2400x1600, svg, pdf; always model space):
|
||||
scaled to fit the image without distortion.
|
||||
--view extents always fit the drawing extents.
|
||||
--view current the current view (as last set by zoom/pan/view.set; a freshly
|
||||
opened drawing's view is its extents plus a 10% margin).";
|
||||
opened drawing's view is its extents plus a 10% margin).
|
||||
|
||||
--cmd chaining (run):
|
||||
A --cmd parameter value of exactly \"{last}\" is replaced with the last object handle an
|
||||
earlier --cmd in the same run returned, so a command can act on what the previous one made:
|
||||
--cmd 'mview {\"p1\":[20,20],\"p2\":[200,150]}' prints {\"viewports\":[\"100\"]}
|
||||
--cmd 'viewport.set {\"handle\":\"{last}\",\"scale\":1}' changes viewport 100
|
||||
It works in any parameter, at any depth (e.g. \"handles\":[\"{last}\"]); every other string is
|
||||
passed unchanged. With no earlier returned handle the run fails and says so.";
|
||||
|
||||
/// What part of model space an image export shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -130,7 +175,15 @@ fn install_io() {
|
||||
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
});
|
||||
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -169,10 +222,16 @@ fn info(path: &str) -> Result<(), String> {
|
||||
let mut s = Session::empty();
|
||||
open(&mut s, path)?;
|
||||
let v = s.execute("drawing.inspect", &json!({ "entities": false })).map_err(|e| e.to_string())?;
|
||||
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
|
||||
outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `bytes` to `out` through the engine's atomic writer (an exclusively created sibling file
|
||||
/// renamed over `out`), so a failed or interrupted write leaves the previous file untouched.
|
||||
fn write_atomic(out: &str, bytes: &[u8]) -> std::io::Result<()> {
|
||||
cadcraft_engine::atomic_write::write_atomic(std::path::Path::new(out), bytes)
|
||||
}
|
||||
|
||||
fn export(s: &Session, out: &str) -> Result<(), String> {
|
||||
export_framed(s, out, None)
|
||||
}
|
||||
@@ -180,9 +239,9 @@ fn export(s: &Session, out: &str) -> Result<(), String> {
|
||||
fn export_framed(s: &Session, out: &str, window: Option<Bounds2>) -> Result<(), String> {
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
let bytes = cadcraft_io::write_framed(d, out, window).map_err(|e| e.to_string())?;
|
||||
std::fs::write(out, &bytes).map_err(|e| format!("{out}: {e}"))?;
|
||||
write_atomic(out, &bytes).map_err(|e| format!("{out}: {e}"))?;
|
||||
eprintln!("wrote {out} ({} bytes)", bytes.len());
|
||||
if !cadcraft_io::is_image(out) {
|
||||
if cadcraft_engine::cmd::file::drops_unknown(out) {
|
||||
let lost = cadcraft_engine::cmd::file::not_saved(d);
|
||||
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
|
||||
eprintln!("{m}");
|
||||
@@ -199,7 +258,7 @@ fn sample(args: &[String]) -> Result<(), String> {
|
||||
other => return Err(format!("unknown sample `{other}` (bracket, floorplan)")),
|
||||
};
|
||||
let bytes = cadcraft_io::write(&d, out).map_err(|e| e.to_string())?;
|
||||
std::fs::write(out, &bytes).map_err(|e| format!("{out}: {e}"))?;
|
||||
write_atomic(out, &bytes).map_err(|e| format!("{out}: {e}"))?;
|
||||
eprintln!("wrote {out} ({} bytes)", bytes.len());
|
||||
Ok(())
|
||||
}
|
||||
@@ -227,10 +286,175 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
check_framed_output(framing, Some(o))?;
|
||||
let mut s = Session::empty();
|
||||
open(&mut s, i)?;
|
||||
if let Some(m) = skipped_message(s.doc().map_err(|e| e.to_string())?, i) {
|
||||
eprintln!("{m}");
|
||||
}
|
||||
if cadcraft_io::is_image(o)
|
||||
&& let Some(m) = undrawn_message(s.doc().map_err(|e| e.to_string())?, i)
|
||||
{
|
||||
eprintln!("{m}");
|
||||
}
|
||||
let window = export_window(&s, framing, None)?;
|
||||
export_framed(&s, o, window)
|
||||
}
|
||||
|
||||
/// The warning for the model-space entities of `path` an image can't show, by type (those kept
|
||||
/// as unknown objects, `Proxy` in `info`), or `None` when there are none.
|
||||
fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option<String> {
|
||||
let mut types: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
|
||||
for e in d.model.iter() {
|
||||
if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind {
|
||||
let n = types.entry(u.dxf_type.as_str()).or_insert(0);
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
let n = types.values().fold(0usize, |a, n| a.saturating_add(*n));
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
let list: Vec<String> = types.iter().map(|(t, n)| format!("{t}: {n}")).collect();
|
||||
let entities = if n == 1 { "entity" } else { "entities" };
|
||||
Some(format!("{path}: {n} {entities} not drawn ({})", list.join(", ")))
|
||||
}
|
||||
|
||||
/// The warning for the records of `path` the reader could not place, or `None` when there are none.
|
||||
fn skipped_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option<String> {
|
||||
let n = d.skipped_records.values().fold(0usize, |a, n| a.saturating_add(*n));
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
let list: Vec<String> = d.skipped_records.iter().map(|(section, n)| format!("{section}: {n}")).collect();
|
||||
let records = if n == 1 { "record" } else { "records" };
|
||||
Some(format!("{path}: {n} {records} could not be read and are left out ({})", list.join(", ")))
|
||||
}
|
||||
|
||||
/// A `--cmd` parameter value of exactly `{last}` is filled in with the last object handle an
|
||||
/// earlier `--cmd` in the same run returned: `mview` answers `{"viewports":["100"]}`, so
|
||||
/// `viewport.set {"handle":"{last}","scale":1}` changes viewport 100. Any other string is passed
|
||||
/// through unchanged, and `--script` text is never rewritten.
|
||||
const LAST_HANDLE: &str = "{last}";
|
||||
|
||||
/// How deep [`result_handles`] walks a command result (results are the engine's own JSON).
|
||||
const RESULT_DEPTH: usize = 16;
|
||||
|
||||
/// Result keys whose values are object references: the engine's result convention for handles.
|
||||
/// A handle can be a string (`handle`, `viewport`, `insert`…) or a list of them (`handles`,
|
||||
/// `viewports`, `members`…). Every other field may hold a user-defined name, a message or a
|
||||
/// count, and is never read as a handle — a group named `100` is a name, not object `100`.
|
||||
fn handle_field(key: &str) -> bool {
|
||||
matches!(
|
||||
key,
|
||||
"handle"
|
||||
| "handles"
|
||||
| "viewport"
|
||||
| "viewports"
|
||||
| "boundary"
|
||||
| "clip"
|
||||
| "insert"
|
||||
| "members"
|
||||
| "source"
|
||||
| "objects"
|
||||
| "entities"
|
||||
| "selection"
|
||||
| "parts"
|
||||
| "refs"
|
||||
| "matches"
|
||||
| "line"
|
||||
| "arc"
|
||||
| "blocks"
|
||||
)
|
||||
}
|
||||
|
||||
/// Collect the handles of `v`, a value under a handle field: a handle string, an array of them,
|
||||
/// or objects that carry handle fields of their own (`entities`, `parts`).
|
||||
fn collect_result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec<Handle>) {
|
||||
if depth > RESULT_DEPTH {
|
||||
return;
|
||||
}
|
||||
match v {
|
||||
Value::String(t) => {
|
||||
if let Some(h) = Handle::parse_hex(t)
|
||||
&& s.doc().is_ok_and(|d| d.entity(h).is_some())
|
||||
{
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|x| collect_result_handles(s, x, depth + 1, out)),
|
||||
Value::Object(m) => {
|
||||
for (k, x) in m {
|
||||
if handle_field(k) {
|
||||
collect_result_handles(s, x, depth + 1, out);
|
||||
} else {
|
||||
find_result_handles(s, x, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Find handle fields nested in containers that are not handles themselves (`groups` in
|
||||
/// `groups.list`, whose members are handles): strings here are names, never references.
|
||||
fn find_result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec<Handle>) {
|
||||
if depth > RESULT_DEPTH {
|
||||
return;
|
||||
}
|
||||
match v {
|
||||
Value::Array(a) => a.iter().for_each(|x| find_result_handles(s, x, depth + 1, out)),
|
||||
Value::Object(m) => {
|
||||
for (k, x) in m {
|
||||
if handle_field(k) {
|
||||
collect_result_handles(s, x, depth + 1, out);
|
||||
} else {
|
||||
find_result_handles(s, x, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The object handles a command result mentions, in the order it lists them. A handle-only result
|
||||
/// (a handle string or an array of them) counts as it is; otherwise only handle fields do.
|
||||
fn result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec<Handle>) {
|
||||
match v {
|
||||
Value::String(_) => collect_result_handles(s, v, depth, out),
|
||||
Value::Array(a) if a.iter().all(Value::is_string) => collect_result_handles(s, v, depth, out),
|
||||
Value::Array(_) | Value::Object(_) => find_result_handles(s, v, depth, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The last handle `r` returned: what a later `{last}` stands for.
|
||||
fn returned_handle(s: &Session, r: &Value) -> Option<Handle> {
|
||||
let mut hs = Vec::new();
|
||||
result_handles(s, r, 0, &mut hs);
|
||||
hs.last().copied()
|
||||
}
|
||||
|
||||
/// The active drawing's identity ([`cadcraft_engine::DocState::uid`]): a handle is only meaningful
|
||||
/// in the drawing it came from, and `new`, `open`, `document.switch` and `close` can make another
|
||||
/// drawing current.
|
||||
fn active_drawing(s: &Session) -> Option<u64> {
|
||||
s.docs.get(s.active).map(|st| st.uid)
|
||||
}
|
||||
|
||||
/// Every `{last}` in `p`, at any depth, replaced by `h`. With no handle to fill in it is an
|
||||
/// error, never a token reaching the command as a (bad) handle.
|
||||
fn fill_last(p: &Value, h: Option<Handle>) -> Result<Value, String> {
|
||||
match p {
|
||||
Value::String(t) if t.as_str() == LAST_HANDLE => match h {
|
||||
Some(h) => Ok(Value::String(h.hex())),
|
||||
None => Err(format!("`{LAST_HANDLE}` needs an earlier --cmd in this run to have returned a handle")),
|
||||
},
|
||||
Value::Array(a) => a.iter().map(|x| fill_last(x, h)).collect::<Result<Vec<_>, _>>().map(Value::Array),
|
||||
Value::Object(m) => {
|
||||
m.iter().map(|(k, x)| Ok((k.clone(), fill_last(x, h)?))).collect::<Result<serde_json::Map<String, Value>, _>>().map(Value::Object)
|
||||
}
|
||||
other => Ok(other.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<(), String> {
|
||||
let mut s = Session::empty();
|
||||
let mut it = args.iter();
|
||||
@@ -266,15 +490,33 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
check_framed_output(framing, exp.as_deref())?;
|
||||
let before = model_views(&s);
|
||||
let mut last_handle: Option<Handle> = None;
|
||||
for (kind, body) in steps {
|
||||
// A handle belongs to the drawing that returned it: if this step makes another drawing
|
||||
// current (`new`, `open`, `document.switch`, `close`, or a script running one of them),
|
||||
// the remembered handle is stale. A handle the step itself returns is taken afterwards,
|
||||
// so it is a handle of the drawing it made current.
|
||||
let drawing = active_drawing(&s);
|
||||
match kind.as_str() {
|
||||
"script" => s.script(&body).map_err(|e| e.to_string())?,
|
||||
"script" => {
|
||||
s.script(&body).map_err(|e| e.to_string())?;
|
||||
if active_drawing(&s) != drawing {
|
||||
last_handle = None;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let (id, json) = body.split_once(' ').unwrap_or((&body, "{}"));
|
||||
let params: Value = serde_json::from_str(json).map_err(|e| format!("--cmd {id}: {e}"))?;
|
||||
let params = fill_last(¶ms, last_handle).map_err(|e| format!("--cmd {id}: {e}"))?;
|
||||
let r = s.execute(id, ¶ms).map_err(|e| e.to_string())?;
|
||||
if active_drawing(&s) != drawing {
|
||||
last_handle = None;
|
||||
}
|
||||
if let Some(h) = returned_handle(&s, &r) {
|
||||
last_handle = Some(h);
|
||||
}
|
||||
if !r.is_null() {
|
||||
println!("{r}");
|
||||
outln!("{r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -354,11 +596,55 @@ fn synthetic(n: usize, side: f64) -> Result<cadcraft_engine::doc::Drawing, Strin
|
||||
Ok(dr)
|
||||
}
|
||||
|
||||
/// `perf FILE`: the display list built as the canvas builds it (a 1600 x 1000 px view at the
|
||||
/// drawing's centre: tolerance, dash level of detail and view window from the zoom band), at
|
||||
/// zoom extents and zoomed in 4x at a time, next to the full-detail build plots use.
|
||||
fn perf_file(path: &str) -> Result<(), String> {
|
||||
use cadcraft_engine::geom::{Bounds2, Vec2};
|
||||
use cadcraft_engine::render::{Options, build};
|
||||
use std::time::Instant;
|
||||
let ms = |t: Instant| t.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut s = Session::empty();
|
||||
let t = Instant::now();
|
||||
open(&mut s, path)?;
|
||||
let open_ms = ms(t);
|
||||
let st = s.state().map_err(|e| e.to_string())?;
|
||||
let (d, space) = (&st.doc, &st.space);
|
||||
let ext = d.extents(space);
|
||||
let size = ext.width().max(ext.height());
|
||||
if ext.is_empty() || !(size.is_finite() && size > 0.0) {
|
||||
return Err("perf: the drawing is empty".into());
|
||||
}
|
||||
outln!("open {open_ms:.0} ms, {} entities, extents {:.1} x {:.1}", d.entity_count(), ext.width(), ext.height());
|
||||
outln!("{:>8} {:>10} {:>10}", "zoom", "build ms", "prims");
|
||||
let mut finest = Options::default();
|
||||
for k in 0..5 {
|
||||
let zoom = 4f64.powi(k);
|
||||
let h = size / zoom;
|
||||
let pixel = 2f64.powi((h / 1000.0).max(1e-300).log2().floor() as i32);
|
||||
let half = Vec2::new(h * 0.8, h * 0.5);
|
||||
let visible = Bounds2::new(ext.center() - half, ext.center() + half);
|
||||
let screen = Options { tolerance: pixel * 0.5, min_dash: pixel * 2.0, view: Some(visible.expand(h * 0.8)), ..Default::default() };
|
||||
let t = Instant::now();
|
||||
let n = build(d, space, &screen).prims.len();
|
||||
outln!("{:>7}x {:>10.1} {n:>10}", zoom, ms(t));
|
||||
finest = screen;
|
||||
}
|
||||
// Plots: every pattern line, everywhere (last, so its large list doesn't weigh on the above).
|
||||
let t = Instant::now();
|
||||
let n = build(d, space, &Options { min_dash: 0.0, view: None, ..finest }).prims.len();
|
||||
outln!("{:>8} {:>10.1} {n:>10}", "full", ms(t));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn perf(args: &[String]) -> Result<(), String> {
|
||||
use cadcraft_engine::doc::Space;
|
||||
use cadcraft_engine::geom::{Bounds2, Vec2};
|
||||
use cadcraft_engine::{select, snap};
|
||||
use std::time::Instant;
|
||||
if let Some(path) = args.first().filter(|a| a.parse::<usize>().is_err()) {
|
||||
return perf_file(path);
|
||||
}
|
||||
let n: usize = match args.first() {
|
||||
Some(a) => a.parse().map_err(|_| format!("perf: bad entity count {a}"))?,
|
||||
None => 200_000,
|
||||
@@ -427,10 +713,10 @@ fn perf(args: &[String]) -> Result<(), String> {
|
||||
let back = cadcraft_io::read(&bytes, "perf.dxf").map_err(|e| e.to_string())?;
|
||||
rows.push(("DXF read".into(), ms(t), format!("{} entities", back.entity_count())));
|
||||
|
||||
println!("{:<40} {:>12} notes", "operation", "ms");
|
||||
println!("{}", "-".repeat(80));
|
||||
outln!("{:<40} {:>12} notes", "operation", "ms");
|
||||
outln!("{}", "-".repeat(80));
|
||||
for (name, t, note) in rows {
|
||||
println!("{name:<40} {t:>12.2} {note}");
|
||||
outln!("{name:<40} {t:>12.2} {note}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -440,37 +726,47 @@ fn perf(args: &[String]) -> Result<(), String> {
|
||||
enum McpTarget {
|
||||
/// An in-process drawing session (no `--connect`).
|
||||
Headless,
|
||||
/// The running app's control channel at `HOST:PORT`.
|
||||
Connect(String),
|
||||
/// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call;
|
||||
/// `launch`: opened then if it isn't running.
|
||||
Connect { addr: String, lazy: bool, launch: bool },
|
||||
}
|
||||
|
||||
/// Parses the arguments after `mcp`. `--connect` must be followed by a `HOST:PORT`; a missing,
|
||||
/// empty or flag-like value is an error, never a silent fall back to a headless session (#103).
|
||||
fn parse_mcp_args(args: &[String]) -> Result<McpTarget, String> {
|
||||
let mut target = McpTarget::Headless;
|
||||
let mut addr: Option<String> = None;
|
||||
let (mut lazy, mut launch) = (false, false);
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--connect" => {
|
||||
let addr = it
|
||||
let a = it
|
||||
.next()
|
||||
.map(|v| v.trim())
|
||||
.filter(|v| !v.is_empty() && !v.starts_with('-'))
|
||||
.ok_or("--connect needs HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)")?;
|
||||
if target != McpTarget::Headless {
|
||||
if addr.is_some() {
|
||||
return Err("--connect given more than once".into());
|
||||
}
|
||||
target = McpTarget::Connect(addr.to_string());
|
||||
addr = Some(a.to_string());
|
||||
}
|
||||
"--lazy" => lazy = true,
|
||||
"--launch" => launch = true,
|
||||
other => return Err(format!("mcp: unknown argument {other}\n{USAGE}")),
|
||||
}
|
||||
}
|
||||
Ok(target)
|
||||
match addr {
|
||||
// `--launch` connects at the first call too (the app opens then).
|
||||
Some(addr) => Ok(McpTarget::Connect { addr, lazy: lazy || launch, launch }),
|
||||
None if lazy || launch => Err("--lazy and --launch need --connect HOST:PORT".into()),
|
||||
None => Ok(McpTarget::Headless),
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(args: &[String]) -> Result<(), String> {
|
||||
let backend: Box<dyn cadcraft_mcp::Backend> = match parse_mcp_args(args)? {
|
||||
McpTarget::Connect(addr) => match cadcraft_mcp::Remote::connect(&addr) {
|
||||
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
|
||||
McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) {
|
||||
Ok(r) => Box::new(r),
|
||||
Err(e) => return Err(format!("cadcraft-cli: cannot connect to {addr}: {e}")),
|
||||
},
|
||||
@@ -496,8 +792,14 @@ mod mcp_args_tests {
|
||||
|
||||
#[test]
|
||||
fn mcp_connect_with_address_selects_remote() {
|
||||
assert_eq!(parse_mcp_args(&args(&["--connect", "127.0.0.1:7979"])), Ok(McpTarget::Connect("127.0.0.1:7979".into())));
|
||||
assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979"])), Ok(McpTarget::Connect("localhost:7979".into())));
|
||||
let to = |addr: &str, lazy, launch| Ok(McpTarget::Connect { addr: addr.into(), lazy, launch });
|
||||
assert_eq!(parse_mcp_args(&args(&["--connect", "127.0.0.1:7979"])), to("127.0.0.1:7979", false, false));
|
||||
assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979"])), to("localhost:7979", false, false));
|
||||
assert_eq!(parse_mcp_args(&args(&["--lazy", "--connect", "localhost:7979"])), to("localhost:7979", true, false));
|
||||
assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979", "--launch"])), to("localhost:7979", true, true));
|
||||
// Without an app to reach they mean nothing: never a headless session.
|
||||
assert!(parse_mcp_args(&args(&["--lazy"])).is_err());
|
||||
assert!(parse_mcp_args(&args(&["--launch"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -518,6 +820,11 @@ mod mcp_args_tests {
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let code = cli();
|
||||
if STDOUT_ERROR.load(Ordering::Relaxed) { ExitCode::FAILURE } else { code }
|
||||
}
|
||||
|
||||
fn cli() -> ExitCode {
|
||||
install_io();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let rest: Vec<String> = args.iter().skip(1).cloned().collect();
|
||||
@@ -535,11 +842,15 @@ fn main() -> ExitCode {
|
||||
.filter(|c| f.as_ref().is_none_or(|f| c.id.contains(f.as_str()) || c.label.to_ascii_lowercase().contains(f.as_str())))
|
||||
.map(|c| serde_json::to_value(c.info(&s)).unwrap_or_default())
|
||||
.collect();
|
||||
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
|
||||
outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
|
||||
}),
|
||||
Some("mcp") => mcp(&rest),
|
||||
Some("--version" | "-V") => {
|
||||
println!("cadcraft-cli {}", env!("CARGO_PKG_VERSION"));
|
||||
outln!("cadcraft-cli {}", env!("CARGO_PKG_VERSION"));
|
||||
Ok(())
|
||||
}
|
||||
Some("--help" | "-h" | "help") => {
|
||||
outln!("{USAGE}");
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(USAGE.into()),
|
||||
@@ -557,6 +868,37 @@ fn main() -> ExitCode {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn scratch_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-cli-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("create scratch dir");
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_atomic_replaces_file_and_leaves_no_staging_files() {
|
||||
let dir = scratch_dir("replace");
|
||||
let out = dir.join("a.dxf");
|
||||
let out = out.to_str().expect("utf-8 path");
|
||||
write_atomic(out, b"old").expect("create");
|
||||
write_atomic(out, b"new").expect("overwrite");
|
||||
assert_eq!(std::fs::read(out).expect("read"), b"new");
|
||||
assert_eq!(std::fs::read_dir(&dir).expect("list").count(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_atomic_failure_keeps_destination_and_cleans_up() {
|
||||
let dir = scratch_dir("fail");
|
||||
let out = dir.join("target");
|
||||
std::fs::create_dir(&out).expect("dir as destination");
|
||||
std::fs::write(out.join("keep"), b"x").expect("seed");
|
||||
assert!(write_atomic(out.to_str().expect("utf-8 path"), b"new").is_err());
|
||||
assert_eq!(std::fs::read(out.join("keep")).expect("kept"), b"x");
|
||||
assert_eq!(std::fs::read_dir(&dir).expect("list").count(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn b(x0: f64, y0: f64, x1: f64, y1: f64) -> Bounds2 {
|
||||
Bounds2::new(Vec2::new(x0, y0), Vec2::new(x1, y1))
|
||||
}
|
||||
@@ -628,6 +970,40 @@ mod tests {
|
||||
assert!(check_framed_output(Framing::Auto, Some("a.dxf")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_placeholder_takes_the_previous_handle() {
|
||||
let mut s = sample_session();
|
||||
let r = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let h = returned_handle(&s, &r).expect("LINE returns its handle");
|
||||
assert_eq!(fill_last(&json!({"handle": "{last}"}), Some(h)), Ok(json!({"handle": h.hex()})));
|
||||
// Nested, as in a selection list.
|
||||
assert_eq!(fill_last(&json!({"handles": ["{last}", "1"]}), Some(h)), Ok(json!({"handles": [h.hex(), "1"]})));
|
||||
// Only the exact token: a name or a sentence that merely contains it stays as written.
|
||||
for p in [json!("last"), json!("{last} "), json!({"name": "last"})] {
|
||||
assert_eq!(fill_last(&p, Some(h)), Ok(p.clone()));
|
||||
}
|
||||
// Nothing returned yet: an error, not a token passed to the command as a bad handle.
|
||||
assert!(fill_last(&json!({"handle": "{last}"}), None).unwrap_err().contains("{last}"));
|
||||
}
|
||||
|
||||
/// Handles are read from a result by looking the strings up in the drawing: counts and names
|
||||
/// are not mistaken for handles, and `mview`'s `viewports` works like `handle`/`handles`.
|
||||
#[test]
|
||||
fn returned_handle_reads_only_real_handles() {
|
||||
let mut s = Session::empty();
|
||||
s.new_drawing(false);
|
||||
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
|
||||
let r = s.execute("mview", &json!({"p1": [20, 20], "p2": [200, 150]})).unwrap();
|
||||
let h = returned_handle(&s, &r).expect("mview returns its viewport handle");
|
||||
assert!(r["viewports"].as_array().is_some_and(|a| a.iter().any(|v| v.as_str() == Some(h.hex().as_str()))), "{r}");
|
||||
assert_eq!(returned_handle(&s, &json!({"changed": 3, "name": "A1"})), None);
|
||||
// The most recent of several.
|
||||
let a = s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap();
|
||||
let b = s.execute("line", &json!({"points": [[0, 0], [2, 0]]})).unwrap();
|
||||
let (ha, hb) = (returned_handle(&s, &a).unwrap(), returned_handle(&s, &b).unwrap());
|
||||
assert_eq!(returned_handle(&s, &json!({"handles": [ha.hex(), hb.hex()]})), Some(hb));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_framing_is_extents() {
|
||||
// convert: nothing ran, always the extents.
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
//! A `--cmd` can act on a handle an earlier `--cmd` in the same run returned (#1663).
|
||||
//!
|
||||
//! `mview` answers `{"viewports":["100"]}`, but a following `viewport.set` could not use that
|
||||
//! handle: it had to be guessed, selected by point, or activated with `mspace`. A `--cmd` parameter
|
||||
//! value of exactly `{last}` is now filled in with the last handle an earlier `--cmd` returned.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn run(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
|
||||
.args(args)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.output()
|
||||
.expect("run cadcraft-cli")
|
||||
}
|
||||
|
||||
/// The issue's sequence: `viewport.set` straight after `mview`, addressing the new viewport by the
|
||||
/// handle the runner remembers.
|
||||
#[test]
|
||||
fn viewport_set_after_mview_uses_the_returned_handle() {
|
||||
let out = run(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
r#"layout.set {"name":"Layout1"}"#,
|
||||
"--cmd",
|
||||
r#"mview {"p1":[20,20],"p2":[200,150]}"#,
|
||||
"--cmd",
|
||||
r#"viewport.set {"handle":"{last}","scale":1}"#,
|
||||
]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "exit {:?}\nstdout: {stdout}\nstderr: {stderr}", out.status);
|
||||
let mview = stdout.lines().find(|l| l.contains("\"viewports\"")).unwrap_or_else(|| panic!("no mview result in {stdout:?}"));
|
||||
let created: serde_json::Value = serde_json::from_str(mview).expect("mview result is JSON");
|
||||
let handle = created["viewports"].as_array().and_then(|a| a.first()).and_then(|h| h.as_str()).expect("a viewport handle");
|
||||
assert!(handle.eq_ignore_ascii_case("100"), "{mview}");
|
||||
let set = stdout.lines().find(|l| l.contains("\"viewHeight\"")).unwrap_or_else(|| panic!("no viewport.set result in {stdout:?}"));
|
||||
let vp: serde_json::Value = serde_json::from_str(set).expect("viewport.set result is JSON");
|
||||
assert_eq!(vp[0]["handle"].as_str(), Some(handle), "viewport.set changed the viewport `{handle}`: {set}");
|
||||
assert_eq!(vp[0]["scale"].as_f64(), Some(1.0), "{set}");
|
||||
}
|
||||
|
||||
/// `{last}` with no handle to fill in is a clear error, not the token reaching the command.
|
||||
#[test]
|
||||
fn last_without_an_earlier_handle_is_an_error() {
|
||||
let out = run(&["run", "--metric", "--cmd", r#"viewport.set {"handle":"{last}","scale":1}"#]);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(1), "stdout: {:?}\nstderr: {stderr}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.contains("{last}"), "the error names the placeholder: {stderr}");
|
||||
assert!(!stderr.contains("panicked"), "{stderr}");
|
||||
}
|
||||
|
||||
/// The last JSON value a run printed: command results are one JSON value a line (`null` is not
|
||||
/// printed).
|
||||
fn last_json(stdout: &str) -> serde_json::Value {
|
||||
let line = stdout
|
||||
.lines()
|
||||
.rev()
|
||||
.find(|l| {
|
||||
let t = l.trim_start();
|
||||
t.starts_with('{') || t.starts_with('[')
|
||||
})
|
||||
.unwrap_or_else(|| panic!("no JSON result in {stdout:?}"));
|
||||
serde_json::from_str(line).expect("command result is JSON")
|
||||
}
|
||||
|
||||
/// `{last}` was not replaced: the error names the placeholder, and the run fails cleanly.
|
||||
fn assert_needs_an_earlier_handle(out: &Output) {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert_eq!(out.status.code(), Some(1), "stdout: {:?}\nstderr: {stderr}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.contains("{last}"), "the error names the placeholder: {stderr}");
|
||||
assert!(!stderr.contains("panicked"), "{stderr}");
|
||||
}
|
||||
|
||||
/// A user-defined name that happens to look like a handle is not a returned handle. `group`
|
||||
/// answers `{"name":"100","members":1}`: `100` is the first line's handle, but the name is not an
|
||||
/// object reference and must not replace the last handle the `line` command returned (`101`).
|
||||
#[test]
|
||||
fn a_group_name_that_looks_like_a_handle_is_not_last() {
|
||||
let out = run(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,0],[10,0]]}"#,
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,10],[10,10]]}"#,
|
||||
"--cmd",
|
||||
r#"group {"name":"100","handles":["101"]}"#,
|
||||
"--cmd",
|
||||
r#"erase {"handles":["{last}"]}"#,
|
||||
"--cmd",
|
||||
r#"entities {"type":"LINE"}"#,
|
||||
]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "exit {:?}\nstdout: {stdout}\nstderr: {stderr}", out.status);
|
||||
let r = last_json(&stdout);
|
||||
assert_eq!(r["count"].as_u64(), Some(1), "one line is left: {stdout}");
|
||||
let left: Vec<&str> = r["entities"].as_array().into_iter().flatten().filter_map(|e| e["handle"].as_str()).collect();
|
||||
assert_eq!(left, ["100"], "the group name 100 did not replace the handle 101 the line command returned: {stdout}");
|
||||
}
|
||||
|
||||
/// `new` makes another drawing current: the handle an earlier `--cmd` returned in the old drawing
|
||||
/// is not a handle of the new one.
|
||||
#[test]
|
||||
fn last_is_cleared_when_new_switches_drawings() {
|
||||
let out = run(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,0],[10,0]]}"#,
|
||||
"--cmd",
|
||||
r#"new {"metric":true}"#,
|
||||
"--cmd",
|
||||
r#"erase {"handles":["{last}"]}"#,
|
||||
]);
|
||||
assert_needs_an_earlier_handle(&out);
|
||||
}
|
||||
|
||||
/// `open` makes the opened file the current drawing: a handle from the drawing before it is stale.
|
||||
#[test]
|
||||
fn last_is_cleared_when_open_switches_drawings() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-last-open-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let dxf = dir.join("opened.dxf");
|
||||
let sample = run(&["sample", "bracket", dxf.to_str().expect("temp path")]);
|
||||
assert!(sample.status.success(), "sample failed: {}", String::from_utf8_lossy(&sample.stderr));
|
||||
let open = format!(r#"open {{"path":{}}}"#, serde_json::to_string(dxf.to_str().expect("temp path")).expect("path JSON"));
|
||||
let out = run(&["run", "--metric", "--cmd", r#"line {"points":[[0,0],[10,0]]}"#, "--cmd", &open, "--cmd", r#"erase {"handles":["{last}"]}"#]);
|
||||
assert_needs_an_earlier_handle(&out);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `document.switch` changes the current drawing without adding one: a handle remembered from the
|
||||
/// drawing left behind must not be used in the one switched to.
|
||||
#[test]
|
||||
fn last_is_cleared_when_document_switch_changes_drawings() {
|
||||
let out = run(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,0],[10,0]]}"#,
|
||||
"--cmd",
|
||||
r#"new {"metric":true}"#,
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,10],[10,10]]}"#,
|
||||
"--cmd",
|
||||
r#"document.switch {"index":0}"#,
|
||||
"--cmd",
|
||||
r#"erase {"handles":["{last}"]}"#,
|
||||
]);
|
||||
assert_needs_an_earlier_handle(&out);
|
||||
}
|
||||
|
||||
/// A handle a command returns after a switch belongs to the drawing now current, so it is kept.
|
||||
#[test]
|
||||
fn a_handle_returned_after_a_switch_is_last() {
|
||||
let out = run(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,0],[10,0]]}"#,
|
||||
"--cmd",
|
||||
r#"new {"metric":true}"#,
|
||||
"--cmd",
|
||||
r#"document.switch {"index":0}"#,
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,10],[10,10]]}"#,
|
||||
"--cmd",
|
||||
r#"erase {"handles":["{last}"]}"#,
|
||||
"--cmd",
|
||||
r#"entities {"type":"LINE"}"#,
|
||||
]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "exit {:?}\nstdout: {stdout}\nstderr: {stderr}", out.status);
|
||||
let r = last_json(&stdout);
|
||||
assert_eq!(r["count"].as_u64(), Some(1), "one line is left: {stdout}");
|
||||
let left: Vec<&str> = r["entities"].as_array().into_iter().flatten().filter_map(|e| e["handle"].as_str()).collect();
|
||||
assert_eq!(left, ["100"], "the line created after the switch was erased: {stdout}");
|
||||
}
|
||||
|
||||
/// A script can change the current drawing too (`new {"metric":true}` at a script line), so the
|
||||
/// remembered handle is cleared after a script that changed it.
|
||||
#[test]
|
||||
fn last_is_cleared_by_a_script_that_changes_drawings() {
|
||||
let out = run(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
r#"line {"points":[[0,0],[10,0]]}"#,
|
||||
"--script",
|
||||
r#"new {"metric":true}"#,
|
||||
"--cmd",
|
||||
r#"erase {"handles":["{last}"]}"#,
|
||||
]);
|
||||
assert_needs_an_earlier_handle(&out);
|
||||
}
|
||||
|
||||
/// Only the exact token is a placeholder: ordinary JSON strings are left alone.
|
||||
#[test]
|
||||
fn ordinary_values_are_not_placeholders() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-last-placeholder-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let out_dxf = dir.join("text.dxf");
|
||||
let out = run(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
r#"layout.set {"name":"Layout1"}"#,
|
||||
"--cmd",
|
||||
r#"mview {"p1":[20,20],"p2":[200,150]}"#,
|
||||
"--cmd",
|
||||
r#"text {"at":[0,0],"height":2,"text":"last and {last}"}"#,
|
||||
"--save",
|
||||
out_dxf.to_str().expect("temp path"),
|
||||
]);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "exit {:?}\nstderr: {stderr}", out.status);
|
||||
let saved = std::fs::read_to_string(&out_dxf).expect("saved DXF");
|
||||
assert!(saved.contains("last and {last}"), "the text is stored literally");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! `cadcraft-cli` against a stdout nobody reads any more (#537).
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
|
||||
/// `cadcraft-cli commands | head` panicked with "failed printing to stdout: Broken pipe (os error
|
||||
/// 32)" and exit status 101: `commands` prints a few thousand lines, which no pipe buffer holds,
|
||||
/// so the reader is gone before the last write.
|
||||
#[test]
|
||||
fn closed_stdout_ends_quietly() {
|
||||
for args in [&["commands"][..], &["commands", "ellipse"], &["--version"]] {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut first = [0u8; 10];
|
||||
child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap();
|
||||
drop(child.stdout.take());
|
||||
let out = child.wait_with_output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.is_empty(), "{args:?}: {:?}: {err}", out.status);
|
||||
}
|
||||
}
|
||||
|
||||
/// The CLI keeps working once stdout is gone: `run` still executes its commands and still saves,
|
||||
/// so `cadcraft-cli run … --save out.dxf | head` keeps the drawing.
|
||||
fn run_with_closed_stdout(args: &[&str]) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
drop(child.stdout.take());
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_stdout_still_runs_the_commands_and_saves() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-pipe-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let drawing = dir.join("piped.dxf");
|
||||
let out = run_with_closed_stdout(&[
|
||||
"run",
|
||||
"--metric",
|
||||
"--cmd",
|
||||
"ellipse {\"center\":[0,0],\"major\":[10,0],\"ratio\":0.5}",
|
||||
"--cmd",
|
||||
"drawing.inspect {}",
|
||||
"--save",
|
||||
drawing.to_str().unwrap(),
|
||||
]);
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
let saved = std::fs::read_to_string(&drawing).unwrap();
|
||||
assert!(saved.contains("ELLIPSE"), "the drawing is saved all the same: {}", &saved[..saved.len().min(200)]);
|
||||
|
||||
// A failing command is still a failure, whether or not anyone reads stdout.
|
||||
let out = run_with_closed_stdout(&["run", "--metric", "--cmd", "no.such.command {}"]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Drawing snap/grid spacing survives saving and opening in a fresh CLI process (#607).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
static NEXT_FILE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct DxfFile(PathBuf);
|
||||
|
||||
impl DxfFile {
|
||||
fn new() -> Self {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("cadcraft-drafting-spacing-{}-{}.dxf", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::File::options().write(true).create_new(true).open(&path).expect("reserve test DXF");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DxfFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn cli(args: &[&str]) -> Vec<Value> {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().expect("run cadcraft-cli");
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).lines().map(|line| serde_json::from_str(line).expect("CLI JSON reply")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quarter_unit_spacing_survives_save_and_reopen() {
|
||||
let file = DxfFile::new();
|
||||
let path = file.0.to_str().expect("test file path");
|
||||
cli(&[
|
||||
"run",
|
||||
"--sample",
|
||||
"--cmd",
|
||||
r#"setvar {"name":"SNAPUNIT","value":[0.25,0.25]}"#,
|
||||
"--cmd",
|
||||
r#"setvar {"name":"GRIDUNIT","value":[0.25,0.25]}"#,
|
||||
"--save",
|
||||
path,
|
||||
]);
|
||||
let replies = cli(&["run", path, "--cmd", r#"getvar {"name":"SNAPUNIT"}"#, "--cmd", r#"getvar {"name":"GRIDUNIT"}"#]);
|
||||
for name in ["SNAPUNIT", "GRIDUNIT"] {
|
||||
let reply = replies.iter().find(|r| r["name"] == name).expect("getvar reply");
|
||||
assert_eq!(reply["value"], json!([0.25, 0.25]), "{name} reset on reopen");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drafting_settings_spacing_roundtrips_without_persisting_osmode() {
|
||||
let file = DxfFile::new();
|
||||
let path = file.0.to_str().expect("test file path");
|
||||
cli(&[
|
||||
"run",
|
||||
"--sample",
|
||||
"--cmd",
|
||||
r#"dsettings {"snapunit":[0.25,0.125],"gridunit":[0.75,1.5]}"#,
|
||||
"--cmd",
|
||||
r#"setvar {"name":"OSMODE","value":0}"#,
|
||||
"--save",
|
||||
path,
|
||||
]);
|
||||
let replies = cli(&[
|
||||
"run",
|
||||
path,
|
||||
"--cmd",
|
||||
r#"getvar {"name":"SNAPUNIT"}"#,
|
||||
"--cmd",
|
||||
r#"getvar {"name":"GRIDUNIT"}"#,
|
||||
"--cmd",
|
||||
r#"getvar {"name":"OSMODE"}"#,
|
||||
]);
|
||||
for (name, expected) in [("SNAPUNIT", json!([0.25, 0.125])), ("GRIDUNIT", json!([0.75, 1.5])), ("OSMODE", json!(4133))] {
|
||||
let reply = replies.iter().find(|r| r["name"] == name).expect("getvar reply");
|
||||
assert_eq!(reply["value"], expected, "{name} after reopening");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! `--help` is a request, not a failure (#1525): it goes to stdout with exit 0, like `--version`.
|
||||
//! Bare `cadcraft-cli` keeps reporting on stderr with exit 1.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn help_flags_print_usage_to_stdout_and_exit_zero() {
|
||||
for args in [&["--help"][..], &["-h"], &["help"]] {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().expect("run cadcraft-cli");
|
||||
assert!(out.status.success(), "{args:?}: {:?}", out.status);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(stdout.starts_with("usage:"), "{args:?}: {stdout:?}");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).is_empty(), "{args:?}: stderr should be empty");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_invocation_still_reports_on_stderr() {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).output().expect("run cadcraft-cli");
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "bare invocation keeps its usage on stderr");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).starts_with("usage:"));
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
mod cli;
|
||||
mod drafting_spacing;
|
||||
mod help;
|
||||
mod mcp_connect;
|
||||
mod skipped_records;
|
||||
mod undrawn_entities;
|
||||
@@ -0,0 +1,44 @@
|
||||
//! `info` reports the records a DXF file lost on reading, by section, and `convert` warns about
|
||||
//! them before writing the copy (#865). The exit code stays 0.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A LINE after the last ENDSEC and a VERTEX with no POLYLINE before it.
|
||||
const DAMAGED: &str = "0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n5\n21\n5\n0\nVERTEX\n8\n0\n10\n1\n20\n1\n0\nENDSEC\n0\nLINE\n8\n0\n10\n9\n20\n9\n11\n8\n21\n8\n0\nEOF\n";
|
||||
|
||||
#[test]
|
||||
fn info_counts_and_convert_warns_about_skipped_records() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-skipped-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged = dir.join("damaged.dxf");
|
||||
std::fs::write(&damaged, DAMAGED).unwrap();
|
||||
let damaged = damaged.to_str().unwrap();
|
||||
|
||||
let out = cli(&["info", damaged]);
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(v["skipped"], serde_json::json!({ "count": 2, "sections": { "(no section)": 1, "ENTITIES": 1 } }));
|
||||
|
||||
let copy = dir.join("copy.dxf");
|
||||
let out = cli(&["convert", damaged, copy.to_str().unwrap()]);
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("could not be read")).collect();
|
||||
assert_eq!(warnings.len(), 1, "{err}");
|
||||
assert!(warnings[0].contains("2 records") && warnings[0].contains("ENTITIES: 1") && warnings[0].contains("(no section): 1"), "{err}");
|
||||
|
||||
// An intact file: a zero count, and no warning.
|
||||
let sample = dir.join("sample.dxf");
|
||||
assert!(cli(&["sample", "floorplan", sample.to_str().unwrap()]).status.success());
|
||||
let out = cli(&["info", sample.to_str().unwrap()]);
|
||||
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(v["skipped"], serde_json::json!({ "count": 0, "sections": {} }));
|
||||
let out = cli(&["convert", sample.to_str().unwrap(), copy.to_str().unwrap()]);
|
||||
assert!(out.status.success());
|
||||
assert!(!String::from_utf8_lossy(&out.stderr).contains("could not be read"), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
|
||||
//! leaving them out silently (#1208). The exit code stays 0.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A line, two foreign REGIONs and a PDF underlay: the last three are kept as unknown entities.
|
||||
const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\
|
||||
0\nLINE\n8\n0\n10\n0\n20\n0\n11\n5\n21\n5\n\
|
||||
0\nREGION\n8\n0\n70\n1\n1\nabc\n\
|
||||
0\nREGION\n8\n0\n70\n1\n1\ndef\n\
|
||||
0\nPDFUNDERLAY\n8\n0\n10\n0\n20\n0\n41\n1\n42\n1\n43\n1\n\
|
||||
0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
#[test]
|
||||
fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-undrawn-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let input = dir.join("proxies.dxf");
|
||||
std::fs::write(&input, PROXIES).unwrap();
|
||||
let input = input.to_str().unwrap();
|
||||
|
||||
let out = cli(&["info", input]);
|
||||
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(v["counts"]["Proxy"], 3, "{v}");
|
||||
|
||||
for ext in ["svg", "png", "pdf"] {
|
||||
let image = dir.join(format!("out.{ext}"));
|
||||
let out = cli(&["convert", input, image.to_str().unwrap()]);
|
||||
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
|
||||
assert_eq!(warnings.len(), 1, "{ext}: {err}");
|
||||
assert_eq!(warnings[0], format!("{input}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)"), "{ext}");
|
||||
}
|
||||
|
||||
// A DXF copy keeps them, so there is nothing to warn about.
|
||||
let copy = dir.join("copy.dxf");
|
||||
let out = cli(&["convert", input, copy.to_str().unwrap()]);
|
||||
assert!(out.status.success());
|
||||
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
|
||||
// A drawing without them: no warning.
|
||||
let sample = dir.join("sample.dxf");
|
||||
assert!(cli(&["sample", "floorplan", sample.to_str().unwrap()]).status.success());
|
||||
let out = cli(&["convert", sample.to_str().unwrap(), dir.join("sample.svg").to_str().unwrap()]);
|
||||
assert!(out.status.success());
|
||||
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ description = "CADCraft in the browser (eframe web runner, WebGPU with WebGL2 fa
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.95"
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
@@ -26,7 +27,7 @@ serde_json = { workspace = true }
|
||||
web-sys = { version = "0.3", features = ["HtmlInputElement", "FileList", "File"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
eframe = { workspace = true, features = ["persistence", "default_fonts", "wgpu", "accesskit"] }
|
||||
eframe = { workspace = true, features = ["persistence", "wgpu", "accesskit"] }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList"] }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>CADCraft</title>
|
||||
<link data-trunk rel="rust" data-bin="cadcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<style>
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed
|
||||
//! CADCraft in an `<iframe>` (such as a Nextcloud app). Messages are plain objects with a `type`:
|
||||
//!
|
||||
//! - `cadcraft:ready` (to the parent): `{ version }`, the app is listening; send a drawing now.
|
||||
//! - `cadcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
|
||||
//! `Uint8Array`. It opens like a file picked with File › Open or dropped on the window.
|
||||
//! - `cadcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
|
||||
//! file CADCraft would otherwise download (SAVE, SAVEAS, exports): it replaces the engine's
|
||||
//! delivery hook. The parent stores the file and reports failures itself.
|
||||
//! - `cadcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
|
||||
//! - `cadcraft:failed` (to the parent): `{ error }` when the app couldn't start.
|
||||
//!
|
||||
//! Only the parent window on the page's own origin is heard or answered. In host mode the app
|
||||
//! starts on the Start tab rather than an empty Drawing1, and the parent guards leaving the page.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
use web_sys::js_sys;
|
||||
|
||||
/// Longest file name taken from the parent page.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
|
||||
thread_local! {
|
||||
/// The bridge [`deliver`] posts through (the engine's hook is a plain `fn`).
|
||||
static BRIDGE: RefCell<Option<Bridge>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
window: web_sys::Window,
|
||||
parent: web_sys::Window,
|
||||
origin: String,
|
||||
}
|
||||
|
||||
/// The unsaved-changes state last reported to the parent.
|
||||
#[derive(Default)]
|
||||
pub struct DirtyReport(Cell<Option<bool>>);
|
||||
|
||||
impl Bridge {
|
||||
/// `None` when the page isn't framed (there is no parent to talk to).
|
||||
pub fn new() -> Option<Self> {
|
||||
let window = web_sys::window()?;
|
||||
let parent = window.parent().ok().flatten()?;
|
||||
if js_sys::Object::is(&parent, &window) {
|
||||
return None;
|
||||
}
|
||||
let origin = window.location().origin().ok()?;
|
||||
Some(Self { window, parent, origin })
|
||||
}
|
||||
|
||||
/// Make this the bridge [`deliver`] uses.
|
||||
pub fn install(&self) {
|
||||
BRIDGE.with(|b| *b.borrow_mut() = Some(self.clone()));
|
||||
}
|
||||
|
||||
pub fn post_ready(&self) {
|
||||
self.send(&[("type", "cadcraft:ready".into()), ("version", env!("CARGO_PKG_VERSION").into())]);
|
||||
}
|
||||
|
||||
pub fn post_failed(&self, error: &str) {
|
||||
self.send(&[("type", "cadcraft:failed".into()), ("error", error.into())]);
|
||||
}
|
||||
|
||||
/// Hear drawings from the parent; they arrive through the upload inbox.
|
||||
pub fn listen(&self, inbox: crate::upload::Inbox) {
|
||||
let parent = self.parent.clone();
|
||||
let origin = self.origin.clone();
|
||||
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
|
||||
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
|
||||
return;
|
||||
}
|
||||
let data = event.data();
|
||||
if string(&data, "type").as_deref() != Some("cadcraft:open") {
|
||||
return;
|
||||
}
|
||||
let name = string(&data, "name")
|
||||
.filter(|n| !n.trim().is_empty())
|
||||
.map(|n| n.chars().take(MAX_NAME_CHARS).collect())
|
||||
.unwrap_or_else(|| "Drawing.dxf".to_string());
|
||||
// Refuse an oversized drawing before copying it into the app's memory.
|
||||
let Some(array) = byte_array(&data) else { return };
|
||||
if let Some(e) = CadApp::open_size_error(&name, u64::from(array.length())) {
|
||||
inbox.refuse(e);
|
||||
return;
|
||||
}
|
||||
inbox.receive(name, array.to_vec());
|
||||
});
|
||||
if self.window.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok() {
|
||||
// The listener lives as long as the page.
|
||||
on_message.forget();
|
||||
}
|
||||
}
|
||||
|
||||
/// After each logic callback (including a hidden tab's): tell the parent when unsaved changes
|
||||
/// appear or go away. `DirtyReport` suppresses duplicates, so this is idempotent.
|
||||
pub fn report_dirty(&self, app: &CadApp, reported: &DirtyReport) {
|
||||
let dirty = app.session.docs.iter().any(|d| d.is_dirty());
|
||||
if reported.0.get() != Some(dirty) && self.send(&[("type", "cadcraft:dirty".into()), ("dirty", dirty.into())]) {
|
||||
reported.0.set(Some(dirty));
|
||||
}
|
||||
}
|
||||
|
||||
fn post_save(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let buffer = js_sys::Uint8Array::from(bytes).buffer();
|
||||
let message = message(&[("type", "cadcraft:save".into()), ("name", name.into()), ("bytes", buffer.clone().into())])
|
||||
.ok_or_else(|| "couldn't build the message".to_string())?;
|
||||
self.parent
|
||||
.post_message_with_transfer(&message, &self.origin, &js_sys::Array::of1(&buffer))
|
||||
.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// Post a message to the parent; false if it couldn't be sent.
|
||||
fn send(&self, fields: &[(&str, JsValue)]) -> bool {
|
||||
message(fields).is_some_and(|m| self.parent.post_message(&m, &self.origin).is_ok())
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's delivery hook in host mode ([`cadcraft_engine::cmd::file::set_deliver`]): hand
|
||||
/// the file to the parent page. `Ok` once it was posted; the engine then counts a drawing as saved.
|
||||
pub fn deliver(name: &str, _mime: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let bridge = BRIDGE.with(|b| b.borrow().clone()).ok_or("the page that embeds CADCraft is gone")?;
|
||||
bridge.post_save(name, bytes)
|
||||
}
|
||||
|
||||
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
|
||||
let m = js_sys::Object::new();
|
||||
for (key, value) in fields {
|
||||
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
fn string(data: &JsValue, key: &str) -> Option<String> {
|
||||
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
|
||||
}
|
||||
|
||||
/// `bytes` (an `ArrayBuffer` or `Uint8Array`) as a view, not yet copied.
|
||||
fn byte_array(data: &JsValue) -> Option<js_sys::Uint8Array> {
|
||||
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
|
||||
if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
|
||||
Some(array.clone())
|
||||
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
|
||||
Some(js_sys::Uint8Array::new(&bytes))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
+215
-16
@@ -2,12 +2,17 @@
|
||||
//!
|
||||
//! Runs the same [`cadcraft_ui_egui::CadApp`] as the desktop app through eframe's web runner
|
||||
//! (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release` from this
|
||||
//! directory (output in `dist/web`). URL flags: `?webgl` forces WebGL2, `?sample` opens the sample
|
||||
//! drawing. Saving downloads the drawing through the browser (`download.rs`).
|
||||
//! directory (output in `dist/web`). URL flags: `?webgl` forces WebGL2, `?cpu` draws the drawing
|
||||
//! with egui shapes instead of the GPU canvas, `?sample` opens the sample drawing. Saving downloads
|
||||
//! the drawing through the browser (`download.rs`). With `?host=parent` (inside an `<iframe>`), a
|
||||
//! same-origin parent page sends the drawing to open and stores what CADCraft saves instead
|
||||
//! (`host.rs`).
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod download;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web {
|
||||
@@ -18,39 +23,86 @@ mod web {
|
||||
const CANVAS_ID: &str = "cadcraft_canvas";
|
||||
const LOADING_ID: &str = "cadcraft_loading";
|
||||
|
||||
/// The app, and the files File > Open… and drag and drop read for it in the background.
|
||||
struct Shell(CadApp, crate::upload::Inbox);
|
||||
/// The app, the files File > Open… and drag and drop read for it in the background, the
|
||||
/// page embedding it (`?host=parent`), the browser's `prefers-reduced-motion` (it stays
|
||||
/// live, so View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting follows a change),
|
||||
/// and the document title last written to the page.
|
||||
struct Shell(
|
||||
CadApp,
|
||||
crate::upload::Inbox,
|
||||
Option<(crate::host::Bridge, crate::host::DirtyReport)>,
|
||||
Option<web_sys::MediaQueryList>,
|
||||
Option<String>,
|
||||
);
|
||||
|
||||
impl eframe::App for Shell {
|
||||
/// Runs one frame: takes in files dropped on or picked for the page, drains the background
|
||||
/// uploads, follows the browser's reduced-motion setting, runs the app, writes the browser
|
||||
/// document title when it changed (so the tab and an embedding page name the open
|
||||
/// drawing), and reports unsaved changes to that page.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.1.take_dropped(ctx);
|
||||
// Background reads are consume-based and run on hidden ticks too. Dropped files are
|
||||
// input and are read from `ui` only.
|
||||
self.1.drain(&mut self.0);
|
||||
self.0.system_animations = self.3.as_ref().map(|reduced| !reduced.matches());
|
||||
self.0.logic(ctx);
|
||||
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);
|
||||
// `DirtyReport` suppresses duplicates, so reporting after every logic callback
|
||||
// (including a hidden tab's) is idempotent and keeps the parent's guard current.
|
||||
if let Some((bridge, reported)) = &self.2 {
|
||||
bridge.report_dirty(&self.0, reported);
|
||||
}
|
||||
}
|
||||
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(raw);
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
}
|
||||
/// Preferences (interface theme and language) survive reloads; egui state is not kept.
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
storage.set_string(cadcraft_ui_egui::options::PROFILE_KEY, self.0.profile_json());
|
||||
storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.0.prefs_json());
|
||||
}
|
||||
fn persist_egui_memory(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// On the first pass consume files dropped on the page, then delegate drawing to `CadApp::ui`.
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
let first_pass = ui.ctx().current_pass_index() == 0;
|
||||
if first_pass {
|
||||
// `take_dropped` consumes the raw list; a second pass or hidden tick cannot
|
||||
// re-read the same file.
|
||||
self.1.take_dropped(ui.ctx());
|
||||
}
|
||||
self.0.ui(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the browser's document title, which names the tab and is what an embedding page
|
||||
/// (`?host=parent`) reads. eframe's web runner ignores [`egui::ViewportCommand::Title`], so
|
||||
/// the title has to reach the DOM directly.
|
||||
fn set_page_title(title: &str) {
|
||||
match web_sys::window().and_then(|window| window.document()) {
|
||||
Some(document) => document.set_title(title),
|
||||
None => log::warn!("cannot set the page title to {title:?}: there is no document"),
|
||||
}
|
||||
}
|
||||
|
||||
fn query() -> String {
|
||||
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn query_param(key: &str) -> Option<String> {
|
||||
web_sys::UrlSearchParams::new_with_str(&query()).ok()?.get(key)
|
||||
}
|
||||
|
||||
/// No file picker on the web: Save / Save As from the menu (and the close prompt) download the
|
||||
/// drawing under its current name; `saveas {"path": "name.dxf"}` picks another name.
|
||||
/// drawing under its current name; `saveas {"path": "name.dxf"}` picks another name. There is
|
||||
/// no file system either, so a dropped file is opened from its contents and APPLOAD says to
|
||||
/// drop a `.lsp` file rather than asking for a name it cannot read.
|
||||
fn services() -> Services {
|
||||
Services { pick_save: Some(Box::new(|name: &str| Some(name.to_string()))), ..Services::default() }
|
||||
Services { pick_save: Some(Box::new(|name: &str| Some(name.to_string()))), no_file_system: true, ..Services::default() }
|
||||
}
|
||||
|
||||
pub fn start() {
|
||||
@@ -58,11 +110,29 @@ mod web {
|
||||
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
});
|
||||
// No file system here: saved files reach the user as browser downloads.
|
||||
cadcraft_engine::cmd::file::set_deliver(crate::download::download);
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// `?host=parent`: a same-origin page framing CADCraft (such as a Nextcloud app) opens
|
||||
// drawings in it and stores what it saves. Otherwise there is no file system here: saved
|
||||
// files reach the user as browser downloads.
|
||||
let bridge = if query_param("host").as_deref() == Some("parent") { crate::host::Bridge::new() } else { None };
|
||||
match &bridge {
|
||||
Some(bridge) => {
|
||||
bridge.install();
|
||||
cadcraft_engine::cmd::file::set_deliver(crate::host::deliver);
|
||||
}
|
||||
None => cadcraft_engine::cmd::file::set_deliver(crate::download::download),
|
||||
}
|
||||
let app_bridge = bridge.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
|
||||
let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
@@ -79,14 +149,24 @@ mod web {
|
||||
canvas,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let mut app = CadApp::new(Session::new(), services());
|
||||
// Embedded, the parent sends the drawing: start on the Start tab, not Drawing1.
|
||||
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
|
||||
let mut app = CadApp::new(session, services());
|
||||
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)) {
|
||||
app.load_profile(&profile);
|
||||
}
|
||||
if let Some(prefs) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::PREFS_KEY)) {
|
||||
app.load_prefs(&prefs);
|
||||
}
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
app.set_wgpu(rs);
|
||||
// `?cpu`: no render state for the app, so the canvas draws with egui shapes.
|
||||
if !crate::wants_cpu(&query())
|
||||
&& let Some(rs) = &cc.wgpu_render_state
|
||||
{
|
||||
// eframe's web runner has no stencil buffer: clipped layout
|
||||
// viewports stay in the layout's display list.
|
||||
app.set_wgpu(rs, None);
|
||||
}
|
||||
if query().contains("sample") {
|
||||
let _ = app.run("ui.sample", serde_json::json!({}));
|
||||
@@ -99,10 +179,19 @@ mod web {
|
||||
picker.pick();
|
||||
None
|
||||
}));
|
||||
Ok(Box::new(Shell(app, inbox)))
|
||||
let host = app_bridge.map(|bridge| {
|
||||
bridge.listen(inbox.clone());
|
||||
bridge.post_ready();
|
||||
(bridge, crate::host::DirtyReport::default())
|
||||
});
|
||||
let reduced_motion = web_sys::window().and_then(|w| w.match_media("(prefers-reduced-motion: reduce)").ok().flatten());
|
||||
Ok(Box::new(Shell(app, inbox, host, reduced_motion, None)))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
if let (Err(e), Some(bridge)) = (&result, &bridge) {
|
||||
bridge.post_failed(&format!("{e:?}"));
|
||||
}
|
||||
if let Some(el) = document.get_element_by_id(LOADING_ID) {
|
||||
match result {
|
||||
Ok(()) => el.remove(),
|
||||
@@ -115,6 +204,50 @@ mod web {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the URL query (`?cpu&sample`) has a `cpu` flag: the CPU canvas path is requested.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
fn wants_cpu(query: &str) -> bool {
|
||||
query.trim_start_matches('?').split('&').any(|p| p == "cpu" || p.starts_with("cpu="))
|
||||
}
|
||||
|
||||
/// The browser tab title: the open drawing's file name, a bullet once it has unsaved changes,
|
||||
/// and the app name (`drawing.dwg • — CADCraft`), or just the app name with no drawing. An
|
||||
/// embedding page (`?host=parent`) reads it to tell which drawing opened and whether it is dirty.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
fn document_title(name: Option<&str>, dirty: bool) -> String {
|
||||
match name.filter(|n| !n.trim().is_empty()) {
|
||||
Some(name) => format!("{name}{} — CADCraft", if dirty { " •" } else { "" }),
|
||||
None => "CADCraft".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The title to write this frame, or `None` while the page already shows it: the browser needs
|
||||
/// the document title only when it changes, not on every frame.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
fn title_to_send(sent: &mut Option<String>, name: Option<&str>, dirty: bool) -> Option<String> {
|
||||
let title = document_title(name, dirty);
|
||||
if sent.as_deref() == Some(title.as_str()) {
|
||||
return None;
|
||||
}
|
||||
*sent = Some(title.clone());
|
||||
Some(title)
|
||||
}
|
||||
|
||||
/// Writes a changed title through `write` (on the web, the browser's document title) and reports
|
||||
/// whether it wrote one. Split from [`title_to_send`] so the change decision and the write are
|
||||
/// both testable: eframe's web backend ignores `egui::ViewportCommand::Title`, so a title that is
|
||||
/// computed but not written leaves the tab on `CADCraft`.
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
fn push_title(sent: &mut Option<String>, name: Option<&str>, dirty: bool, write: impl FnOnce(&str)) -> bool {
|
||||
match title_to_send(sent, name, dirty) {
|
||||
Some(title) => {
|
||||
write(&title);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod upload;
|
||||
|
||||
@@ -127,3 +260,69 @@ fn main() {
|
||||
fn main() {
|
||||
eprintln!("cadcraft-web only runs in the browser: build it with `trunk build --release` in apps/cadcraft-web");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{document_title, push_title, title_to_send, wants_cpu};
|
||||
|
||||
/// Guards the `?cpu` URL flag: only a whole `cpu` query parameter (bare or with a value)
|
||||
/// selects the CPU canvas, so `?sample` and `?gpucpu` stay on the GPU path.
|
||||
#[test]
|
||||
fn cpu_flag_is_detected() {
|
||||
assert!(wants_cpu("?cpu"));
|
||||
assert!(wants_cpu("?cpu&sample"));
|
||||
assert!(wants_cpu("?sample&cpu"));
|
||||
assert!(!wants_cpu(""));
|
||||
assert!(!wants_cpu("?sample"));
|
||||
assert!(!wants_cpu("?webgl&sample"));
|
||||
assert!(!wants_cpu("?gpucpu"));
|
||||
}
|
||||
|
||||
/// Guards the tab title text: a drawing contributes its name and, when dirty, a trailing
|
||||
/// bullet; a blank or missing name leaves the app name alone and never shows a bullet.
|
||||
#[test]
|
||||
fn viewport_title_names_the_document_and_marks_unsaved_changes() {
|
||||
assert_eq!(document_title(Some("drawing.dwg"), false), "drawing.dwg — CADCraft");
|
||||
assert_eq!(document_title(Some("drawing.dwg"), true), "drawing.dwg • — CADCraft");
|
||||
assert_eq!(document_title(Some("Drawing1"), false), "Drawing1 — CADCraft");
|
||||
assert_eq!(document_title(None, false), "CADCraft");
|
||||
assert_eq!(document_title(None, true), "CADCraft");
|
||||
assert_eq!(document_title(Some(" "), true), "CADCraft");
|
||||
}
|
||||
|
||||
/// Guards the change signal: a title is sent on open, rename, dirty change and close, but
|
||||
/// never twice in a row, so an idle tab is not repainted by a repeated title command.
|
||||
#[test]
|
||||
fn viewport_title_follows_open_rename_and_dirty_changes_only() {
|
||||
let mut sent = None;
|
||||
assert_eq!(title_to_send(&mut sent, Some("drawing.dwg"), false).as_deref(), Some("drawing.dwg — CADCraft"));
|
||||
// The page already has it: send nothing.
|
||||
assert_eq!(title_to_send(&mut sent, Some("drawing.dwg"), false), None);
|
||||
// Unsaved changes add the bullet.
|
||||
assert_eq!(title_to_send(&mut sent, Some("drawing.dwg"), true).as_deref(), Some("drawing.dwg • — CADCraft"));
|
||||
// A rename shows the new name.
|
||||
assert_eq!(title_to_send(&mut sent, Some("plan.dwg"), true).as_deref(), Some("plan.dwg • — CADCraft"));
|
||||
// Saving clears it again.
|
||||
assert_eq!(title_to_send(&mut sent, Some("plan.dwg"), false).as_deref(), Some("plan.dwg — CADCraft"));
|
||||
// Closing the last drawing leaves the app name only.
|
||||
assert_eq!(title_to_send(&mut sent, None, false).as_deref(), Some("CADCraft"));
|
||||
assert_eq!(title_to_send(&mut sent, None, false), None);
|
||||
}
|
||||
|
||||
/// Guards the title write: every changed title reaches the writer (on the web, the browser
|
||||
/// document title) exactly once, and an unchanged one is not written again. Without the write
|
||||
/// the tab and an embedding page stay on `CADCraft` however the drawing changes.
|
||||
#[test]
|
||||
fn changed_title_reaches_the_document_title_writer_once() {
|
||||
let mut sent = None;
|
||||
let mut written: Vec<String> = Vec::new();
|
||||
assert!(push_title(&mut sent, Some("drawing.dwg"), false, |title| written.push(title.to_owned())));
|
||||
// Unchanged: nothing is written again.
|
||||
assert!(!push_title(&mut sent, Some("drawing.dwg"), false, |title| written.push(title.to_owned())));
|
||||
// Unsaved changes are written.
|
||||
assert!(push_title(&mut sent, Some("drawing.dwg"), true, |title| written.push(title.to_owned())));
|
||||
// Closing the drawing writes the app name.
|
||||
assert!(push_title(&mut sent, None, false, |title| written.push(title.to_owned())));
|
||||
assert_eq!(written, ["drawing.dwg — CADCraft", "drawing.dwg • — CADCraft", "CADCraft"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,8 +68,9 @@ impl Inbox {
|
||||
}
|
||||
|
||||
/// Read the files dropped on the page this frame (eframe hands them over unread on the web).
|
||||
/// The list is taken, not cloned: a later pass or hidden tick must not read the same drop.
|
||||
pub fn take_dropped(&self, ctx: &egui::Context) {
|
||||
for f in ctx.input(|i| i.raw.dropped_files.clone()) {
|
||||
for f in ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)) {
|
||||
if let Some(file) = f.web_file() {
|
||||
self.read(file.clone());
|
||||
}
|
||||
@@ -96,6 +97,20 @@ impl Inbox {
|
||||
});
|
||||
}
|
||||
|
||||
/// A file read elsewhere (sent by the page embedding CADCraft): opened on the next frame like
|
||||
/// a picked file, or refused when too large to open.
|
||||
pub fn receive(&self, name: String, bytes: Vec<u8>) {
|
||||
match CadApp::open_size_error(&name, bytes.len() as u64) {
|
||||
Some(e) => self.push(Err(e)),
|
||||
None => self.push(Ok((name, bytes))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A file from elsewhere refused before it was read (`error` says why).
|
||||
pub fn refuse(&self, error: String) {
|
||||
self.push(Err(error));
|
||||
}
|
||||
|
||||
fn push(&self, upload: Upload) {
|
||||
let mut files = self.files.take();
|
||||
files.push(upload);
|
||||
|
||||
@@ -4,6 +4,7 @@ description = "CADCraft desktop app"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.95"
|
||||
publish = false
|
||||
default-run = "cadcraft"
|
||||
|
||||
@@ -14,20 +15,46 @@ workspace = true
|
||||
cadcraft-engine = { workspace = true }
|
||||
cadcraft-ui-egui = { workspace = true }
|
||||
cadcraft-io = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links", "persistence"] }
|
||||
# For the shared per-session control-token helper (control_server.rs authentication).
|
||||
cadcraft-mcp = { workspace = true }
|
||||
eframe = { workspace = true, features = ["clipboard", "wgpu", "accesskit", "wayland", "x11", "links", "persistence"] }
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
# View ▸ Theme ▸ System: the desktop's light/dark choice from the XDG desktop portal
|
||||
# (desktop_theme.rs). Already in Cargo.lock through accesskit; pinned to that version so nothing
|
||||
# is built twice.
|
||||
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
|
||||
craft-ui = { workspace = true, features = ["native-windows"] }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
|
||||
# controls and under floating panels.
|
||||
craft-window = { workspace = true }
|
||||
muda = { version = "0.21", default-features = false }
|
||||
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
|
||||
# (system_animations.rs). Already in Cargo.lock through muda.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
|
||||
|
||||
# Rust HID backends: no proprietary SDK or C HID library.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
hidapi = { version = "2.6.7", default-features = false, features = ["windows-native"] }
|
||||
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: Windows' Animation effects
|
||||
# setting (system_animations.rs). Already in Cargo.lock through wgpu's DirectX 12 backend.
|
||||
windows = { version = "0.62", features = ["UI_ViewManagement"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
hidapi = { version = "2.6.7", default-features = false, features = ["linux-native-basic-udev"] }
|
||||
|
||||
@@ -1,64 +1,474 @@
|
||||
//! Loopback JSON-lines control server: one request per line, one reply per line.
|
||||
//! This is the transport the MCP server (`cadcraft-cli mcp --connect`) wraps.
|
||||
//!
|
||||
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
|
||||
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
|
||||
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
|
||||
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
|
||||
//! socket may sit idle or blocked on a write.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
|
||||
use std::time::Duration;
|
||||
|
||||
use cadcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
|
||||
return rx;
|
||||
}
|
||||
};
|
||||
log::info!("control server listening on 127.0.0.1:{port}");
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let tx = tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || serve(stream, tx, ctx));
|
||||
}
|
||||
});
|
||||
rx
|
||||
/// Resource bounds for the control server.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Limits {
|
||||
/// Connections served at once; more get an error line and are closed.
|
||||
max_clients: usize,
|
||||
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
|
||||
max_line: usize,
|
||||
/// Requests waiting for the app at once; more are answered `busy`.
|
||||
queue: usize,
|
||||
/// How long a connection may go without sending a byte before it is closed.
|
||||
idle_timeout: Duration,
|
||||
/// How long a reply write may block before the connection is closed.
|
||||
write_timeout: Duration,
|
||||
/// How long a request waits for the app's answer.
|
||||
reply_timeout: Duration,
|
||||
}
|
||||
|
||||
fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context) {
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
for line in BufReader::new(read).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let reply = match serde_json::from_str::<Value>(&line) {
|
||||
Ok(msg) => {
|
||||
let id = msg.get("id").cloned().unwrap_or(Value::Null);
|
||||
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let params = msg.get("params").cloned().unwrap_or(json!({}));
|
||||
let (req, pending) = ControlRequest::new(method, params);
|
||||
if tx.send(req).is_err() {
|
||||
break;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
// On timeout the request is cancelled if the app hasn't started it, and the reply's
|
||||
// `state` says whether it can still have run.
|
||||
let mut r = pending.wait(Duration::from_secs(60));
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("id".into(), id);
|
||||
}
|
||||
r
|
||||
}
|
||||
Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}),
|
||||
};
|
||||
if writeln!(out, "{reply}").is_err() {
|
||||
break;
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_clients: 16,
|
||||
// Generous, so requests that carry whole drawings or images as base64 still fit.
|
||||
max_line: 256 * 1024 * 1024,
|
||||
queue: 64,
|
||||
idle_timeout: Duration::from_secs(600),
|
||||
write_timeout: Duration::from_secs(30),
|
||||
reply_timeout: Duration::from_secs(60),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the loopback server with a fresh session token and a bounded request queue.
|
||||
/// Binding or token-issuance failure returns a disconnected receiver.
|
||||
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => {
|
||||
// Loopback TCP cannot tell local users apart, so issue an unguessable per-session
|
||||
// token in an owner-only file and require it on every request (CWE-306). A client
|
||||
// (the MCP bridge) reads it from the file, which needs the desktop user's filesystem
|
||||
// access; another local account cannot.
|
||||
let token = match cadcraft_mcp::control_token::issue(port) {
|
||||
Ok(t) => Arc::new(t),
|
||||
Err(e) => {
|
||||
log::error!("control server not started: could not write the control token: {e}");
|
||||
return sync_channel::<ControlRequest>(0).1;
|
||||
}
|
||||
};
|
||||
if let Ok(path) = cadcraft_mcp::control_token::token_path(port) {
|
||||
log::info!("control server listening on 127.0.0.1:{port} (token in {})", path.display());
|
||||
}
|
||||
serve_listener(l, Limits::default(), ctx, token)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
|
||||
sync_channel::<ControlRequest>(0).1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the accepting thread waits after a failed accept. Accepting can keep failing, for
|
||||
/// example while the process has no file descriptors left, and retrying at once would keep a
|
||||
/// core busy until it recovers.
|
||||
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
|
||||
|
||||
/// The connections `incoming` accepts, calling `wait` after each failed accept.
|
||||
fn accepted<T>(incoming: impl Iterator<Item = std::io::Result<T>>, mut wait: impl FnMut()) -> impl Iterator<Item = T> {
|
||||
incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok())
|
||||
}
|
||||
|
||||
/// Accept connections on `listener` under `limits`; requests arrive on the returned receiver.
|
||||
fn serve_listener(listener: TcpListener, limits: Limits, ctx: egui::Context, token: Arc<String>) -> Receiver<ControlRequest> {
|
||||
let (tx, rx) = sync_channel::<ControlRequest>(limits.queue.max(1));
|
||||
std::thread::spawn(move || accept_loop(listener, tx, ctx, limits, token));
|
||||
rx
|
||||
}
|
||||
|
||||
/// A connection's place among [`Limits::max_clients`], given back when the connection ends (also
|
||||
/// when its thread can't be started, or panics).
|
||||
struct Slot(Arc<AtomicUsize>);
|
||||
|
||||
impl Drop for Slot {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept clients within the connection limit and give each worker the same session token.
|
||||
fn accept_loop(listener: TcpListener, tx: SyncSender<ControlRequest>, ctx: egui::Context, limits: Limits, token: Arc<String>) {
|
||||
let open = Arc::new(AtomicUsize::new(0));
|
||||
for mut stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) {
|
||||
let _ = stream.set_write_timeout(Some(limits.write_timeout));
|
||||
if open.fetch_add(1, Ordering::SeqCst) >= limits.max_clients {
|
||||
open.fetch_sub(1, Ordering::SeqCst);
|
||||
let _ = writeln!(stream, "{}", json!({"ok": false, "error": "too many control connections"}));
|
||||
continue;
|
||||
}
|
||||
let slot = Slot(Arc::clone(&open));
|
||||
let tx = tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
let token = Arc::clone(&token);
|
||||
let _ = std::thread::Builder::new().spawn(move || {
|
||||
let _slot = slot;
|
||||
serve(stream, &tx, &ctx, limits, &token);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
|
||||
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
|
||||
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
|
||||
buf.clear();
|
||||
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
|
||||
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
|
||||
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() {
|
||||
// The idle timeout ran out (Windows reports it as TimedOut, Unix as WouldBlock).
|
||||
ErrorKind::TimedOut | ErrorKind::WouldBlock => "request line not completed in time; closing the connection".to_string(),
|
||||
_ => e.to_string(),
|
||||
})?;
|
||||
if n == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
if buf.last() == Some(&b'\n') {
|
||||
buf.pop();
|
||||
if buf.last() == Some(&b'\r') {
|
||||
buf.pop();
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
if buf.len() > max {
|
||||
return Err(format!("request line longer than {max} bytes; closing the connection"));
|
||||
}
|
||||
// Last line without a newline, then end of stream.
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// One request line, parsed.
|
||||
enum Line {
|
||||
Request {
|
||||
id: Value,
|
||||
method: String,
|
||||
params: Value,
|
||||
token: Option<String>,
|
||||
},
|
||||
Blank,
|
||||
/// Not a request: reply with this error and close the connection.
|
||||
Reject(String),
|
||||
}
|
||||
|
||||
/// Parse a UTF-8 JSON request and its optional token, distinguishing blank lines from rejected input.
|
||||
fn parse_line(bytes: &[u8]) -> Line {
|
||||
let Ok(text) = std::str::from_utf8(bytes) else {
|
||||
return Line::Reject("not a control request (invalid UTF-8); closing the connection".into());
|
||||
};
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Line::Blank;
|
||||
}
|
||||
if is_http_request_line(text) {
|
||||
return Line::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
|
||||
}
|
||||
let msg = match serde_json::from_str::<Value>(text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")),
|
||||
};
|
||||
let Some(obj) = msg.as_object() else {
|
||||
return Line::Reject("not a control request (expected a JSON object); closing the connection".into());
|
||||
};
|
||||
let Some(method) = obj.get("method").and_then(Value::as_str) else {
|
||||
return Line::Reject("not a control request (missing string `method`); closing the connection".into());
|
||||
};
|
||||
Line::Request {
|
||||
id: obj.get("id").cloned().unwrap_or(Value::Null),
|
||||
method: method.to_string(),
|
||||
params: obj.get("params").cloned().unwrap_or(json!({})),
|
||||
token: obj.get("token").and_then(Value::as_str).map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
/// An HTTP/1 request line (`POST / HTTP/1.1`) or the HTTP/2 preface (`PRI * HTTP/2.0`).
|
||||
fn is_http_request_line(text: &str) -> bool {
|
||||
const METHODS: [&str; 10] = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"];
|
||||
text.split_once(' ').is_some_and(|(method, _)| METHODS.contains(&method))
|
||||
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
|
||||
}
|
||||
|
||||
/// Serve bounded JSON lines, authenticating each request before enqueueing it for the UI.
|
||||
/// Invalid credentials close the connection; queue and reply limits report whether a request ran.
|
||||
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits, token: &str) {
|
||||
if stream.set_read_timeout(Some(limits.idle_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
let mut reader = BufReader::new(read);
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line) {
|
||||
Ok(false) => break,
|
||||
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
|
||||
// A line nobody asked for would be read as the reply to the client's next request.
|
||||
Err(_) if buf.is_empty() => break,
|
||||
Err(e) => e,
|
||||
Ok(true) => match parse_line(&buf) {
|
||||
Line::Blank => continue,
|
||||
Line::Reject(e) => e,
|
||||
Line::Request { id, method, params, token: given } => {
|
||||
// Authenticate the peer before dispatching: loopback TCP does not identify the
|
||||
// OS user, so only a client holding the owner-only session token may drive the
|
||||
// desktop user's commands (CWE-306).
|
||||
if !given.map(|g| cadcraft_mcp::control_token::matches(token, &g)).unwrap_or(false) {
|
||||
let mut r = json!({"ok": false, "error": "unauthorized: missing or invalid control token", "state": "not-run"});
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("id".into(), id);
|
||||
}
|
||||
let _ = writeln!(out, "{r}");
|
||||
break;
|
||||
}
|
||||
let (req, pending) = ControlRequest::new(method, params);
|
||||
let mut r = match tx.try_send(req) {
|
||||
Ok(()) => {
|
||||
ctx.request_repaint();
|
||||
// On timeout the request is cancelled if the app hasn't started it, and
|
||||
// the reply's `state` says whether it can still have run.
|
||||
pending.wait(limits.reply_timeout)
|
||||
}
|
||||
Err(TrySendError::Full(_)) => json!({"ok": false, "error": "busy: too many queued requests", "state": "not-run"}),
|
||||
Err(TrySendError::Disconnected(_)) => break,
|
||||
};
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("id".into(), id);
|
||||
}
|
||||
if writeln!(out, "{r}").is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
},
|
||||
};
|
||||
// The connection closes either way; a peer that can't read the reason loses nothing.
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject}));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A failed accept is followed by a wait before the next one, so a listener that keeps
|
||||
/// failing does not spin, and the connections around the failures still come through.
|
||||
#[test]
|
||||
fn a_failed_accept_waits_before_the_next() {
|
||||
let failed = || Err(std::io::Error::other("no file descriptors left"));
|
||||
let incoming = vec![failed(), Ok(1), failed(), failed(), Ok(2)];
|
||||
let mut waits = 0;
|
||||
let connections: Vec<i32> = super::accepted(incoming.into_iter(), || waits += 1).collect();
|
||||
assert_eq!(connections, [1, 2]);
|
||||
assert_eq!(waits, 3, "one wait per failed accept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_are_read_up_to_the_limit() {
|
||||
let mut buf = Vec::new();
|
||||
let mut input: &[u8] = b"aaaaaaaaaa\nbb\r\ncc";
|
||||
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true));
|
||||
assert_eq!(buf, b"aaaaaaaaaa", "a line exactly at the limit is accepted");
|
||||
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true));
|
||||
assert_eq!(buf, b"bb", "CRLF is stripped");
|
||||
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true));
|
||||
assert_eq!(buf, b"cc", "a last line without a newline is still read");
|
||||
assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(false), "then end of stream");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overlong_line_is_refused_without_reading_the_rest() {
|
||||
let mut buf = Vec::new();
|
||||
let long = [b'x'; 100];
|
||||
let mut input: &[u8] = &long;
|
||||
assert!(read_bounded_line(&mut input, &mut buf, 10).is_err());
|
||||
assert!(buf.len() <= 11, "at most limit + 1 bytes are buffered, got {}", buf.len());
|
||||
assert_eq!(input.len(), 100 - 11, "the rest of the line is left unread");
|
||||
}
|
||||
|
||||
fn short() -> Limits {
|
||||
Limits {
|
||||
queue: 1,
|
||||
idle_timeout: Duration::from_millis(300),
|
||||
write_timeout: Duration::from_millis(300),
|
||||
reply_timeout: Duration::from_millis(300),
|
||||
..Limits::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixed token for tests; real tokens are random (see `cadcraft_mcp::control_token`).
|
||||
const TEST_TOKEN: &str = "test-control-token";
|
||||
|
||||
/// The control server on a loopback port under `limits`; requests arrive on the receiver.
|
||||
fn serve_with(limits: Limits) -> (std::net::SocketAddr, Receiver<ControlRequest>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
(addr, serve_listener(listener, limits, egui::Context::default(), Arc::new(TEST_TOKEN.to_string())))
|
||||
}
|
||||
|
||||
/// The control server on a loopback port, with a stand-in UI that echoes each method.
|
||||
fn serve_echo() -> std::net::SocketAddr {
|
||||
let (addr, rx) = serve_with(Limits::default());
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
|
||||
}
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
/// A request line carrying the test token, so it authenticates.
|
||||
fn req_line(id: i64, method: &str) -> String {
|
||||
json!({"id": id, "method": method, "token": TEST_TOKEN}).to_string() + "\n"
|
||||
}
|
||||
|
||||
/// Send `input` on a new connection and read reply lines until the server closes it.
|
||||
fn exchange(addr: std::net::SocketAddr, input: &[u8]) -> Vec<Value> {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(input).unwrap();
|
||||
let mut replies = Vec::new();
|
||||
for line in BufReader::new(c).lines() {
|
||||
// A read timeout here means the server kept the connection open.
|
||||
let line = line.unwrap();
|
||||
replies.push(serde_json::from_str(&line).unwrap());
|
||||
}
|
||||
replies
|
||||
}
|
||||
|
||||
/// A browser can POST to the port: its request line closes the connection before the JSON
|
||||
/// line in its body is read, so nothing is dispatched.
|
||||
#[test]
|
||||
fn an_http_request_closes_the_connection_before_its_body_is_dispatched() {
|
||||
let (addr, rx) = serve_with(short());
|
||||
let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: text/plain\r\n\r\n\
|
||||
{\"id\":1,\"method\":\"cmdline.input\",\"params\":{\"text\":\"circle 0,0 5\"}}\n";
|
||||
let replies = exchange(addr, http);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert_eq!(replies[0]["ok"], false);
|
||||
assert!(replies[0]["error"].as_str().unwrap().contains("closing the connection"), "{replies:?}");
|
||||
assert!(rx.try_recv().is_err(), "the body was dispatched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_is_not_a_request_closes_the_connection() {
|
||||
for junk in [&b"hello\n"[..], b"[1,2]\n", b"{\"id\":1}\n", b"{\"method\":5}\n", b"\xff\xfe\n", b"GET /x HTTP/1.1\n"] {
|
||||
let addr = serve_echo();
|
||||
let mut input = junk.to_vec();
|
||||
input.extend_from_slice(b"{\"id\":2,\"method\":\"ping\"}\n");
|
||||
let replies = exchange(addr, &input);
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert_eq!(replies[0]["ok"], false);
|
||||
}
|
||||
assert!(is_http_request_line("OPTIONS * HTTP/1.1"));
|
||||
assert!(is_http_request_line("PRI * HTTP/2.0"));
|
||||
assert!(!is_http_request_line("{\"method\":\"GET /\"}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_connection_is_closed() {
|
||||
let (addr, _rx) = serve_with(short());
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
let mut got = Vec::new();
|
||||
c.read_to_end(&mut got).unwrap();
|
||||
assert!(got.is_empty(), "{}", String::from_utf8_lossy(&got));
|
||||
assert!(t.elapsed() < Duration::from_secs(4));
|
||||
}
|
||||
|
||||
/// Authenticated requests rejected by a full queue retain their IDs and report that they did not run.
|
||||
#[test]
|
||||
fn a_full_queue_answers_busy() {
|
||||
let (addr, rx) = serve_with(short());
|
||||
// No UI drains the one-place queue: the first request fills it, the second finds it full.
|
||||
let first = std::thread::spawn(move || exchange(addr, req_line(1, "m").as_bytes()));
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(4);
|
||||
let busy = loop {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(req_line(2, "m").as_bytes()).unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(c).read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
if v["error"].as_str().is_some_and(|e| e.starts_with("busy")) || std::time::Instant::now() > deadline {
|
||||
break v;
|
||||
}
|
||||
};
|
||||
assert_eq!((busy["id"].as_i64(), busy["state"].as_str()), (Some(2), Some("not-run")), "{busy}");
|
||||
assert_eq!(first.join().unwrap()[0]["state"], "not-run");
|
||||
drop(rx);
|
||||
}
|
||||
|
||||
/// Replies on one authenticated connection preserve the ID of each request.
|
||||
#[test]
|
||||
fn requests_are_answered_with_their_ids() {
|
||||
let addr = serve_echo();
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let input = format!("{}\n{}", req_line(3, "ping").trim_end(), req_line(4, "pong"));
|
||||
c.write_all(input.as_bytes()).unwrap();
|
||||
let mut r = BufReader::new(c);
|
||||
for (id, method) in [(3, "ping"), (4, "pong")] {
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!((v["id"].as_i64(), v["method"].as_str()), (Some(id), Some(method)), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Missing and incorrect session tokens are rejected before dispatch.
|
||||
#[test]
|
||||
fn a_request_without_the_token_is_unauthorized() {
|
||||
// A local peer that does not hold the session token cannot drive the app (CWE-306).
|
||||
let addr = serve_echo();
|
||||
let replies = exchange(addr, b"{\"id\":9,\"method\":\"ping\"}\n");
|
||||
assert_eq!(replies.len(), 1, "{replies:?}");
|
||||
assert_eq!(replies[0]["ok"], false);
|
||||
assert!(replies[0]["error"].as_str().unwrap().contains("unauthorized"), "{replies:?}");
|
||||
// A wrong token is also refused.
|
||||
let wrong = exchange(addr, b"{\"id\":9,\"method\":\"ping\",\"token\":\"nope\"}\n");
|
||||
assert_eq!(wrong[0]["ok"], false);
|
||||
assert!(wrong[0]["error"].as_str().unwrap().contains("unauthorized"), "{wrong:?}");
|
||||
}
|
||||
|
||||
/// A request carrying the session token reaches the control dispatcher.
|
||||
#[test]
|
||||
fn a_request_with_the_token_is_dispatched() {
|
||||
let addr = serve_echo();
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(req_line(10, "ping").as_bytes()).unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(c).read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!((v["ok"].as_bool(), v["method"].as_str()), (Some(true), Some("ping")), "{line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_connections_are_refused() {
|
||||
let addr = serve_echo();
|
||||
// Idle connections are accepted in order and held open.
|
||||
let held: Vec<TcpStream> = (0..Limits::default().max_clients).map(|_| TcpStream::connect(addr).unwrap()).collect();
|
||||
let mut extra = TcpStream::connect(addr).unwrap();
|
||||
extra.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(&mut extra).read_line(&mut line).unwrap();
|
||||
assert!(line.contains("too many control connections"), "{line}");
|
||||
drop(held);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! The desktop's own light/dark choice, for View ▸ Theme ▸ System.
|
||||
//!
|
||||
//! winit reports no system theme on Linux and the BSDs (`RawInput::system_theme` stays `None`),
|
||||
//! so the System choice fell back to dark whatever the desktop said. This asks the desktop itself:
|
||||
//! the XDG Desktop Portal's Settings interface, which answers on GNOME, KDE and XFCE alike, over
|
||||
//! X11 and Wayland alike. The answer is handed to egui as the system theme
|
||||
//! (`App::raw_input_hook`), so the app and egui's own widgets follow it as they follow macOS and
|
||||
//! Windows.
|
||||
//!
|
||||
//! Ported from PdfCraft (storytold/pdfcraft#881).
|
||||
|
||||
use std::sync::mpsc::{Receiver, TryRecvError, channel};
|
||||
use std::time::Duration;
|
||||
|
||||
/// How often the watcher re-reads the desktop's answer. The portal also publishes a change
|
||||
/// signal, but subscribing needs a connection kept alive for the life of the window; one round
|
||||
/// trip every few seconds is cheap and reacts soon enough after a theme switch.
|
||||
const POLL: Duration = Duration::from_secs(4);
|
||||
|
||||
/// Watches the desktop and reports its choice when it changes.
|
||||
#[derive(Default)]
|
||||
pub struct DesktopTheme {
|
||||
/// `None` when no watcher thread could be started (or on a platform where winit answers).
|
||||
changes: Option<Receiver<Option<egui::Theme>>>,
|
||||
/// The desktop's last answer.
|
||||
current: Option<egui::Theme>,
|
||||
}
|
||||
|
||||
impl DesktopTheme {
|
||||
/// Start watching. The first answer is sent straight away; `wake` is called after each
|
||||
/// answer, so an idle window repaints and picks it up.
|
||||
pub fn start(wake: impl Fn() + Send + 'static) -> Self {
|
||||
if !ASKS_THE_DESKTOP {
|
||||
return Self::default();
|
||||
}
|
||||
let (tx, rx) = channel();
|
||||
let started = std::thread::Builder::new().name("cadcraft-desktop-theme".into()).spawn(move || {
|
||||
let mut last = read();
|
||||
if tx.send(last).is_err() {
|
||||
return;
|
||||
}
|
||||
wake();
|
||||
loop {
|
||||
std::thread::sleep(POLL);
|
||||
let now = read();
|
||||
if now != last {
|
||||
last = now;
|
||||
if tx.send(now).is_err() {
|
||||
return;
|
||||
}
|
||||
wake();
|
||||
}
|
||||
}
|
||||
});
|
||||
Self { changes: started.ok().map(|_| rx), current: None }
|
||||
}
|
||||
|
||||
/// The desktop's choice, `None` when it states none or there is nobody to ask (no session
|
||||
/// bus, no portal). Polled once a frame; a desktop that stops answering keeps the last answer.
|
||||
pub fn current(&mut self) -> Option<egui::Theme> {
|
||||
if let Some(changes) = &self.changes {
|
||||
loop {
|
||||
match changes.try_recv() {
|
||||
Ok(Some(theme)) => self.current = Some(theme),
|
||||
Ok(None) => {}
|
||||
Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
/// Where winit has no answer and the portal does.
|
||||
const ASKS_THE_DESKTOP: bool = cfg!(all(unix, not(target_os = "macos")));
|
||||
|
||||
/// Ask the portal once. D-Bus calls block, so this belongs off the UI thread: the watcher's
|
||||
/// thread is its only caller.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn read() -> Option<egui::Theme> {
|
||||
const PORTAL: &str = "org.freedesktop.portal.Desktop";
|
||||
const PATH: &str = "/org/freedesktop/portal/desktop";
|
||||
const SETTINGS: &str = "org.freedesktop.portal.Settings";
|
||||
// The standard key first (GNOME and KDE answer it: 0 no preference, 1 dark, 2 light); then
|
||||
// GNOME's own schema, which XFCE's portal proxies without the standard key.
|
||||
const KEYS: [(&str, &str); 2] = [("org.freedesktop.appearance", "color-scheme"), ("org.gnome.desktop.interface", "color-scheme")];
|
||||
let connection = zbus::blocking::Connection::session().ok()?;
|
||||
for (namespace, key) in KEYS {
|
||||
// `ReadOne` (Settings version 2) answers the value; older portals only have `Read`, which
|
||||
// wraps it in one more variant. `parse` unwraps either.
|
||||
let reply = connection
|
||||
.call_method(Some(PORTAL), PATH, Some(SETTINGS), "ReadOne", &(namespace, key))
|
||||
.or_else(|_| connection.call_method(Some(PORTAL), PATH, Some(SETTINGS), "Read", &(namespace, key)));
|
||||
let Ok(reply) = reply else { continue };
|
||||
let Ok((answer,)) = reply.body().deserialize::<(zbus::zvariant::OwnedValue,)>() else { continue };
|
||||
if let Some(scheme) = parse(&answer, 0) {
|
||||
return scheme;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The portal's `color-scheme` answer: `Some(choice)` when it read as an answer (`Some(None)`
|
||||
/// for "no preference"), `None` when it didn't. Variants are unwrapped a few levels deep.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn parse(value: &zbus::zvariant::Value<'_>, depth: u8) -> Option<Option<egui::Theme>> {
|
||||
use zbus::zvariant::Value;
|
||||
match value {
|
||||
Value::U32(1) => Some(Some(egui::Theme::Dark)),
|
||||
Value::U32(2) => Some(Some(egui::Theme::Light)),
|
||||
Value::U32(_) => Some(None),
|
||||
Value::Str(s) => Some(match s.as_str() {
|
||||
"prefer-dark" => Some(egui::Theme::Dark),
|
||||
"prefer-light" => Some(egui::Theme::Light),
|
||||
_ => None,
|
||||
}),
|
||||
Value::Value(inner) if depth < 4 => parse(inner, depth + 1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
fn read() -> Option<egui::Theme> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The standard key answers a number, GNOME's schema a string; either may come wrapped in
|
||||
/// variants (the older `Read`). Only "dark" and "light" are a choice.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn the_portal_answer_reads_as_a_choice_or_as_none() {
|
||||
use zbus::zvariant::Value;
|
||||
assert_eq!(parse(&Value::U32(1), 0), Some(Some(egui::Theme::Dark)));
|
||||
assert_eq!(parse(&Value::U32(2), 0), Some(Some(egui::Theme::Light)));
|
||||
assert_eq!(parse(&Value::U32(0), 0), Some(None));
|
||||
assert_eq!(parse(&Value::U32(7), 0), Some(None));
|
||||
assert_eq!(parse(&Value::from("prefer-dark"), 0), Some(Some(egui::Theme::Dark)));
|
||||
assert_eq!(parse(&Value::from("prefer-light"), 0), Some(Some(egui::Theme::Light)));
|
||||
assert_eq!(parse(&Value::from("default"), 0), Some(None));
|
||||
let wrapped = Value::Value(Box::new(Value::Value(Box::new(Value::U32(1)))));
|
||||
assert_eq!(parse(&wrapped, 0), Some(Some(egui::Theme::Dark)));
|
||||
assert_eq!(parse(&Value::Bool(true), 0), None);
|
||||
let mut deep = Value::U32(1);
|
||||
for _ in 0..10 {
|
||||
deep = Value::Value(Box::new(deep));
|
||||
}
|
||||
assert_eq!(parse(&deep, 0), None, "nesting is bounded");
|
||||
}
|
||||
|
||||
/// A watcher that was never started is inert rather than a panic.
|
||||
#[test]
|
||||
fn a_watcher_without_a_thread_is_inert() {
|
||||
assert_eq!(DesktopTheme::default().current(), None);
|
||||
}
|
||||
|
||||
/// Answers arrive as changes; "no preference" or silence keeps the last real answer.
|
||||
#[test]
|
||||
fn the_last_answer_stands_until_a_new_one() {
|
||||
let (tx, rx) = channel();
|
||||
let mut watcher = DesktopTheme { changes: Some(rx), current: None };
|
||||
assert_eq!(watcher.current(), None);
|
||||
tx.send(Some(egui::Theme::Light)).unwrap();
|
||||
assert_eq!(watcher.current(), Some(egui::Theme::Light));
|
||||
tx.send(Some(egui::Theme::Dark)).unwrap();
|
||||
tx.send(None).unwrap();
|
||||
assert_eq!(watcher.current(), Some(egui::Theme::Dark));
|
||||
drop(tx);
|
||||
assert_eq!(watcher.current(), Some(egui::Theme::Dark));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
//! Windows graphics instance configuration, applied before wgpu can initialize any driver.
|
||||
|
||||
use eframe::{NativeOptions, egui_wgpu::WgpuSetup, wgpu::Backends};
|
||||
use eframe::{
|
||||
NativeOptions,
|
||||
egui_wgpu::WgpuSetup,
|
||||
wgpu::{Backends, Dx12Compiler},
|
||||
};
|
||||
|
||||
/// Restrict the wgpu instance to DirectX 12 unless `backend_override` (normally
|
||||
/// `Backends::from_env()`, i.e. `WGPU_BACKEND`) names other backends.
|
||||
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>) {
|
||||
/// Default to DirectX 12 with FXC before creating the wgpu instance. Explicit
|
||||
/// `WGPU_BACKEND` and `WGPU_DX12_COMPILER` choices, read by the caller, take precedence.
|
||||
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>, compiler_override: Option<Dx12Compiler>) {
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
// eframe's default includes GL. Creating that backend can crash inside AMD's
|
||||
// atio6axx.dll before adapter selection or any Rust error handling runs, so the
|
||||
@@ -12,6 +16,15 @@ pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>
|
||||
// out of the instance avoids it. This matches the verified WGPU_BACKEND=dx12
|
||||
// workaround without mutating process environment variables.
|
||||
create.instance_descriptor.backends = backend_override.unwrap_or(Backends::DX12);
|
||||
// Auto can load another program's dxcompiler.dll without a matching dxil.dll.
|
||||
// That fails wgpu's indirect-validation pipeline and loses the device before
|
||||
// the first frame (issue #608). FXC uses the Windows-provided compiler runtime.
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler = compiler_override.unwrap_or(Dx12Compiler::Fxc);
|
||||
log::info!(
|
||||
"Windows graphics: backends={:?}, DX12 compiler={:?}",
|
||||
create.instance_descriptor.backends,
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +34,7 @@ mod tests {
|
||||
|
||||
fn configured_backends(backend_override: Option<Backends>) -> Backends {
|
||||
let mut options = NativeOptions::default();
|
||||
configure(&mut options, backend_override);
|
||||
configure(&mut options, backend_override, None);
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
@@ -38,6 +51,44 @@ mod tests {
|
||||
assert_eq!(configured_backends(None), Backends::DX12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_uses_fxc_instead_of_searching_for_dxc() {
|
||||
let mut options = NativeOptions::default();
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
// Auto can find an unrelated DXC without its matching DXIL runtime (issue #608).
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler = Dx12Compiler::Auto;
|
||||
}
|
||||
configure(&mut options, None, None);
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(matches!(create.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Fxc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_compiler_and_backend_overrides_are_preserved() {
|
||||
let backends = Backends::VULKAN | Backends::DX12;
|
||||
for compiler in
|
||||
[Dx12Compiler::Fxc, Dx12Compiler::Auto, Dx12Compiler::StaticDxc, Dx12Compiler::DynamicDxc { dxc_path: "custom/dxcompiler.dll".into() }]
|
||||
{
|
||||
let mut options = NativeOptions::default();
|
||||
configure(&mut options, Some(backends), Some(compiler.clone()));
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert_eq!(create.instance_descriptor.backends, backends);
|
||||
match (compiler, create.instance_descriptor.backend_options.dx12.shader_compiler) {
|
||||
(Dx12Compiler::Fxc, Dx12Compiler::Fxc)
|
||||
| (Dx12Compiler::Auto, Dx12Compiler::Auto)
|
||||
| (Dx12Compiler::StaticDxc, Dx12Compiler::StaticDxc) => {}
|
||||
(Dx12Compiler::DynamicDxc { dxc_path: expected }, Dx12Compiler::DynamicDxc { dxc_path: actual }) => {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
(expected, actual) => panic!("compiler override changed from {expected:?} to {actual:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_backend_override_is_preserved() {
|
||||
for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] {
|
||||
|
||||
@@ -93,7 +93,10 @@ fn matches(name: &str, target: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch.
|
||||
/// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch (the
|
||||
/// `duration_since` clamp); past the last date chrono can represent (year 262143) the proleptic
|
||||
/// Gregorian date is kept via the 400-year cycle rather than falling back to the epoch, so the
|
||||
/// output never changes for a value the old formatter accepted and logging never panics.
|
||||
pub fn timestamp(t: SystemTime) -> String {
|
||||
let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
|
||||
let secs = since.as_secs();
|
||||
@@ -102,20 +105,25 @@ pub fn timestamp(t: SystemTime) -> String {
|
||||
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis())
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's
|
||||
/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch; saturating so an absurd
|
||||
/// clock can't overflow).
|
||||
fn civil_from_days(days: u64) -> (u64, u64, u64) {
|
||||
let z = days.saturating_add(719_468);
|
||||
let era = z / 146_097;
|
||||
let doe = z % 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = era.saturating_mul(400).saturating_add(yoe).saturating_add(u64::from(m <= 2));
|
||||
(y, m, d)
|
||||
/// Days since 1970-01-01 → proleptic Gregorian (year, month, day).
|
||||
///
|
||||
/// `timestamp` clamps a pre-1970 clock to the epoch, so `days` is an unsigned count that can run
|
||||
/// past `NaiveDate`'s ±262143-year range. The Gregorian calendar repeats every 400 years
|
||||
/// (146_097 days), so chrono converts the day within one cycle and whole cycles go back into the
|
||||
/// year (an `i128`, then saturated into `i64`), keeping chrono as the only calendar logic and
|
||||
/// reproducing the old saturating `civil_from_days` result exactly without hand-rolled day math.
|
||||
/// 1970-01-01 is `num_days_from_ce` 719_163.
|
||||
fn civil_from_days(days: u64) -> (i64, u32, u32) {
|
||||
use chrono::Datelike;
|
||||
let (cycles, rest) = (days / 146_097, days % 146_097);
|
||||
// `rest + 719_163` is 719_163..865_259, always a valid CE day.
|
||||
match i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt) {
|
||||
Some(d) => {
|
||||
let y = i128::from(d.year()) + i128::from(cycles) * 400;
|
||||
(i64::try_from(y).unwrap_or(i64::MAX), d.month(), d.day())
|
||||
}
|
||||
None => (1970, 1, 1), // unreachable
|
||||
}
|
||||
}
|
||||
|
||||
fn numbered(dir: &Path, n: usize) -> PathBuf {
|
||||
@@ -385,8 +393,20 @@ mod tests {
|
||||
// 2000 is a leap year (divisible by 400), 2100 is not.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
|
||||
// Before the epoch (a clock set wrong) clamps instead of panicking.
|
||||
// Before the epoch (a clock set wrong) clamps to the epoch instead of panicking.
|
||||
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
|
||||
// Past chrono's range (a clock set absurdly far ahead) keeps the proleptic Gregorian date
|
||||
// the old formatter gave, rather than falling back to the epoch.
|
||||
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
|
||||
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
|
||||
}
|
||||
// Windows' SystemTime can't hold u64::MAX / 2 seconds, so it is only checked where it exists.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
|
||||
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
|
||||
}
|
||||
// Years past 9999 keep the plain zero-padded year (no `+`).
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+227
-28
@@ -15,43 +15,117 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod control_server;
|
||||
mod desktop_theme;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod graphics;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod spacemouse;
|
||||
mod system_animations;
|
||||
mod workspace;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services, i18n};
|
||||
|
||||
struct App(CadApp, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
|
||||
struct App {
|
||||
cad: CadApp,
|
||||
spacemouse: spacemouse::SpaceMouse,
|
||||
/// The desktop's light/dark choice where winit reports none (Linux, the BSDs).
|
||||
desktop_theme: desktop_theme::DesktopTheme,
|
||||
/// Whether the OS shows animations, for the System choice of View ▸ Accessibility ▸ Animation Effects.
|
||||
system_animations: system_animations::SystemAnimations,
|
||||
workspace: workspace::Workspace,
|
||||
workspace_error: Option<String>,
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: Option<native_menu::NativeMenu>,
|
||||
/// The `movable` flag last set on the main window.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// `ctx` is `None` only for the final attempt at exit.
|
||||
fn persist_workspace(&mut self, ctx: Option<&egui::Context>) {
|
||||
let result = match ctx {
|
||||
None => self.workspace.save_on_exit(&self.cad.ui),
|
||||
Some(ctx) => self.workspace.save_if_changed(&self.cad.ui, std::time::Instant::now()).map(|wait| {
|
||||
if let Some(wait) = wait {
|
||||
ctx.request_repaint_after(wait);
|
||||
}
|
||||
}),
|
||||
};
|
||||
if let Err(error) = result {
|
||||
if self.workspace_error.as_ref() != Some(&error) {
|
||||
eprintln!("CADCraft workspace: {error}");
|
||||
self.cad.set_status(format!("Workspace could not be saved: {error}"));
|
||||
self.workspace_error = Some(error);
|
||||
}
|
||||
} else {
|
||||
self.workspace_error = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// View ▸ Theme ▸ System resolves against `raw.system_theme`, which winit leaves empty on Linux
|
||||
/// and the BSDs: the desktop's answer, where it gives one, stands in for it.
|
||||
fn follow_desktop(raw: &mut egui::RawInput, desktop: Option<egui::Theme>) {
|
||||
if desktop.is_some() {
|
||||
raw.system_theme = desktop;
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
/// eframe logic callback: syncs the OS animation setting and runs `CadApp::logic`; when the pass index is 0 (the first pass or a hidden tick) it also installs/polls the macOS native menu, polls the spacemouse and persists the workspace; a quit request closes the viewport.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if self.1.is_none() && std::env::var_os("CADCRAFT_NO_NATIVE_MENU").is_none() {
|
||||
self.1 = Some(native_menu::NativeMenu::install(&mut self.0));
|
||||
}
|
||||
if let Some(m) = &mut self.1 {
|
||||
m.poll(&mut self.0, ctx);
|
||||
self.cad.system_animations = self.system_animations.current();
|
||||
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
|
||||
self.cad.logic(ctx);
|
||||
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
|
||||
// never reaches `App::ui`): native menus stay current, the spacemouse still navigates and a
|
||||
// workspace changed while hidden is persisted. `current_pass_index()` is zero on the first
|
||||
// pass and on every hidden tick, and non-zero on later passes of a multi-pass frame.
|
||||
if ctx.current_pass_index() == 0 {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if self.native_menu.is_none() && std::env::var_os("CADCRAFT_NO_NATIVE_MENU").is_none() {
|
||||
self.native_menu = Some(native_menu::NativeMenu::install(&mut self.cad, ctx));
|
||||
}
|
||||
if let Some(m) = &mut self.native_menu {
|
||||
m.poll(&mut self.cad, ctx);
|
||||
}
|
||||
}
|
||||
self.spacemouse.poll(&mut self.cad, ctx);
|
||||
// After `cad.logic`, so a control command's workspace change is saved in the same frame.
|
||||
self.persist_workspace(Some(ctx));
|
||||
}
|
||||
self.0.logic(ctx);
|
||||
if std::mem::take(&mut self.0.quit_requested) {
|
||||
if std::mem::take(&mut self.cad.quit_requested) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(raw);
|
||||
follow_desktop(raw, self.desktop_theme.current());
|
||||
self.cad.raw_input_hook(ctx, raw);
|
||||
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.0.ui(ui);
|
||||
self.cad.ui(ui);
|
||||
#[cfg(target_os = "macos")]
|
||||
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
|
||||
}
|
||||
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
|
||||
/// crash leaves them for recovery).
|
||||
fn on_exit(&mut self) {
|
||||
self.persist_workspace(None);
|
||||
self.cad.cancel_screenshots();
|
||||
self.cad.shutdown_autosave();
|
||||
}
|
||||
/// Preferences (the interface theme) survive restarts; window and egui state are not kept.
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.0.prefs_json());
|
||||
storage.set_string(cadcraft_ui_egui::options::PROFILE_KEY, self.cad.profile_json());
|
||||
storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.cad.prefs_json());
|
||||
storage.set_string(cadcraft_ui_egui::autosave::PREFS_KEY, cadcraft_ui_egui::autosave::prefs_json());
|
||||
}
|
||||
fn persist_egui_memory(&self) -> bool {
|
||||
false
|
||||
@@ -63,7 +137,15 @@ pub fn install_io() {
|
||||
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
|
||||
});
|
||||
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -71,7 +153,8 @@ fn services() -> Services {
|
||||
Services {
|
||||
pick_open: Some(Box::new(|| {
|
||||
rfd::FileDialog::new()
|
||||
.add_filter(i18n::t("Drawings (DWG, DXF)"), &["dwg", "dxf"])
|
||||
.add_filter(i18n::t("Drawings (DWG, DXF)"), &["dwg", "dxf", "dwt"])
|
||||
.add_filter(i18n::t("SVG drawings (SVG, SVGZ)"), &["svg", "svgz"])
|
||||
.add_filter(i18n::t("All files"), &["*"])
|
||||
.pick_file()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
@@ -83,6 +166,13 @@ fn services() -> Services {
|
||||
.save_file()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
// APPLOAD: AutoLISP routines only, starting where the last one was loaded from.
|
||||
pick_lisp: Some(Box::new(|dir: &str| {
|
||||
let dialog = rfd::FileDialog::new().add_filter(i18n::t("AutoLISP (LSP)"), &["lsp"]).add_filter(i18n::t("All files"), &["*"]);
|
||||
let dialog = if dir.is_empty() { dialog } else { dialog.set_directory(dir) };
|
||||
dialog.pick_file().map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
no_file_system: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,14 +180,15 @@ fn services() -> Services {
|
||||
/// filter's extension, and macOS accepts only listed extensions, replacing any other with the
|
||||
/// first one. DWG must be listed for a `.dwg` name to survive, and a drawing opened from DWG
|
||||
/// then defaults to DWG; other names keep DXF first.
|
||||
fn filters_for_save(name: &str) -> [(&'static str, &'static str); 5] {
|
||||
let mut filters = [("Drawing (DXF)", "dxf"), ("Drawing (DWG)", "dwg"), ("SVG", "svg"), ("PNG", "png"), ("PDF", "pdf")];
|
||||
fn filters_for_save(name: &str) -> [(&'static str, &'static str); 6] {
|
||||
let mut filters =
|
||||
[("Drawing (DXF)", "dxf"), ("Drawing (DWG)", "dwg"), ("Drawing Template (DWT)", "dwt"), ("SVG", "svg"), ("PNG", "png"), ("PDF", "pdf")];
|
||||
let lower = name.to_ascii_lowercase();
|
||||
filters.sort_by_key(|(_, ext)| !lower.ends_with(&format!(".{ext}")));
|
||||
filters
|
||||
}
|
||||
|
||||
/// The per-user settings directory (today it holds `logs/`): `CADCRAFT_CONFIG_DIR` if set, else
|
||||
/// The per-user settings directory (it holds `logs/` and `autosave/`): `CADCRAFT_CONFIG_DIR` if set, else
|
||||
/// `$XDG_CONFIG_HOME/cadcraft` or `~/.config/cadcraft` on Linux and the BSDs,
|
||||
/// `~/Library/Application Support/CADCraft` on macOS, `%APPDATA%\CADCraft` on Windows.
|
||||
fn config_dir() -> Option<std::path::PathBuf> {
|
||||
@@ -123,6 +214,9 @@ fn config_dir_from(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<s
|
||||
|
||||
const APP_ID: &str = "ai.storyteller.cadcraft";
|
||||
|
||||
/// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`).
|
||||
const STENCIL_BITS: u8 = 8;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -148,9 +242,32 @@ fn control_port_from(source: &str, value: Option<String>) -> Option<u16> {
|
||||
port
|
||||
}
|
||||
|
||||
/// `--control` followed by `value`: a bare `--control` (last argument) keeps the port already
|
||||
/// read from `CADCRAFT_CONTROL_PORT` (`current`) instead of turning the control channel off.
|
||||
fn control_flag(current: Option<u16>, value: Option<String>) -> Option<u16> {
|
||||
if value.is_some() {
|
||||
return control_port_from("--control", value);
|
||||
}
|
||||
match current {
|
||||
Some(port) => log::warn!("--control: no port given; using CADCRAFT_CONTROL_PORT ({port})"),
|
||||
None => log::warn!("--control: no port given; the control channel is off"),
|
||||
}
|
||||
current
|
||||
}
|
||||
|
||||
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
|
||||
fn main() -> eframe::Result {
|
||||
// First, so every start-up record is captured; see `logging`.
|
||||
let logger = logging::install();
|
||||
// The update helper relaunches this binary after a self-update; it runs and exits here.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(done) = craft_update::self_update::finish(&craft_update::suite::CADCRAFT, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if let Err(e) = done {
|
||||
eprintln!("CADCraft update helper failed: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// lossy, so a value that is not Unicode is reported like any other bad port instead of ignored
|
||||
let mut control_port =
|
||||
control_port_from("CADCRAFT_CONTROL_PORT", std::env::var_os("CADCRAFT_CONTROL_PORT").map(|p| p.to_string_lossy().into_owned()));
|
||||
@@ -159,7 +276,7 @@ fn main() -> eframe::Result {
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--control" => control_port = control_port_from("--control", args.next()),
|
||||
"--control" => control_port = control_flag(control_port, args.next()),
|
||||
"--sample" => sample = true,
|
||||
"--version" | "-V" => {
|
||||
println!("{}", version_string());
|
||||
@@ -196,14 +313,30 @@ fn main() -> eframe::Result {
|
||||
.with_title_shown(false)
|
||||
.with_app_id(APP_ID),
|
||||
persist_window: false,
|
||||
// CADCraft installs its own capped font chain (`theme::install_fonts`); never run
|
||||
// system-font discovery as a hidden fallback.
|
||||
system_font_fallback: false,
|
||||
// A stencil buffer clips the contents of clipped layout viewports on the GPU.
|
||||
stencil_buffer: STENCIL_BITS,
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
}
|
||||
// Before eframe creates the wgpu instance: default Windows to DirectX 12 only (see graphics.rs).
|
||||
// Before eframe creates the wgpu instance: default Windows to DirectX 12 with FXC (see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
graphics::configure(&mut options, eframe::wgpu::Backends::from_env());
|
||||
graphics::configure(&mut options, eframe::wgpu::Backends::from_env(), eframe::wgpu::Dx12Compiler::from_env());
|
||||
// Command previews (COPY, MOVE...) of large selections are tessellated by egui, whose index
|
||||
// buffer outgrew wgpu's default 256 MiB cap; the validation error is fatal. Ask for what the
|
||||
// adapter actually supports.
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
let base = std::sync::Arc::clone(&create.device_descriptor);
|
||||
create.device_descriptor = std::sync::Arc::new(move |adapter| {
|
||||
let mut d = base(adapter);
|
||||
d.required_limits.max_buffer_size = d.required_limits.max_buffer_size.max(adapter.limits().max_buffer_size);
|
||||
d
|
||||
});
|
||||
}
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
@@ -219,16 +352,43 @@ fn main() -> eframe::Result {
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let mut app = CadApp::new(Session::empty(), services());
|
||||
let (workspace, restored, workspace_error) = workspace::Workspace::load();
|
||||
if let Some(ui) = restored {
|
||||
app.ui = ui;
|
||||
}
|
||||
if let Some(error) = &workspace_error {
|
||||
eprintln!("CADCraft workspace: {error}");
|
||||
app.set_status(error);
|
||||
}
|
||||
app.system_languages = std::env::var("CADCRAFT_LOCALE").map(|s| vec![s]).unwrap_or_else(|_| sys_locale::get_locales().collect());
|
||||
// The user profile (Options): drafting settings, selection sizes, drawing-area colours.
|
||||
if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) {
|
||||
app.load_profile(&profile);
|
||||
}
|
||||
if let Some(prefs) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::PREFS_KEY)) {
|
||||
app.load_prefs(&prefs);
|
||||
}
|
||||
if let Some(prefs) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::autosave::PREFS_KEY)) {
|
||||
cadcraft_ui_egui::autosave::load_prefs(&prefs);
|
||||
}
|
||||
// Autosave files (SAVEFILEPATH) default to `<settings dir>/autosave`.
|
||||
if let Some(dir) = config_dir() {
|
||||
app.enable_autosave(&dir.join("autosave"));
|
||||
app.enable_update_check();
|
||||
// Startup LISP (acad.lsp, acaddoc.lsp) is read from `<settings>/support`; the
|
||||
// folder is made so it is there to put them in.
|
||||
let support = dir.join("support");
|
||||
if let Err(e) = std::fs::create_dir_all(&support) {
|
||||
log::warn!("no LISP support folder {}: {e}", support.display());
|
||||
}
|
||||
app.session.set_lisp_support_dir(Some(support));
|
||||
}
|
||||
app.integrated_titlebar = cfg!(target_os = "macos");
|
||||
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
|
||||
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
|
||||
}
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
app.set_wgpu(rs);
|
||||
app.set_wgpu(rs, eframe::egui_wgpu::depth_format_from_bits(0, STENCIL_BITS));
|
||||
}
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
@@ -241,20 +401,33 @@ fn main() -> eframe::Result {
|
||||
app.open_path(f);
|
||||
}
|
||||
if app.session.docs.is_empty() {
|
||||
app.session.new_drawing(false);
|
||||
// In the units the profile asks for (MEASUREINIT, restored above).
|
||||
let metric = app.session.settings.measureinit;
|
||||
app.session.new_drawing(metric);
|
||||
}
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let desktop_theme = desktop_theme::DesktopTheme::start(move || ctx.request_repaint());
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let system_animations = system_animations::SystemAnimations::start(move || ctx.request_repaint());
|
||||
Ok(Box::new(App {
|
||||
desktop_theme,
|
||||
system_animations,
|
||||
cad: app,
|
||||
spacemouse: spacemouse::SpaceMouse::start(cc.egui_ctx.clone()),
|
||||
workspace,
|
||||
workspace_error,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
)))
|
||||
native_menu: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{config_dir_from, control_port_from, filters_for_save};
|
||||
use super::{config_dir_from, control_flag, control_port_from, filters_for_save, follow_desktop};
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -271,6 +444,7 @@ mod tests {
|
||||
assert_eq!(first("Drawing1.dxf"), "dxf");
|
||||
assert_eq!(first("Drawing1"), "dxf");
|
||||
assert_eq!(first("plan.pdf"), "pdf");
|
||||
assert_eq!(first("office.dwt"), "dwt");
|
||||
for name in ["a.dwg", "b.dxf", "c"] {
|
||||
let exts: Vec<_> = filters_for_save(name).iter().map(|(_, e)| *e).collect();
|
||||
assert!(exts.contains(&"dwg") && exts.contains(&"dxf"), "{name}");
|
||||
@@ -287,6 +461,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_without_a_port_keeps_the_environment_port() {
|
||||
// `CADCRAFT_CONTROL_PORT=47321 cadcraft --control` (#844)
|
||||
assert_eq!(control_flag(Some(47321), None), Some(47321));
|
||||
assert_eq!(control_flag(None, None), None);
|
||||
// A port given on the command line still wins over the variable.
|
||||
assert_eq!(control_flag(Some(47321), Some("7979".into())), Some(7979));
|
||||
assert_eq!(control_flag(Some(47321), Some("abc".into())), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_override_variable_wins_and_empty_values_are_unset() {
|
||||
let vars = [("CADCRAFT_CONFIG_DIR", "/tmp/cc"), ("HOME", "/home/u"), ("XDG_CONFIG_HOME", "/x"), ("APPDATA", "C:\\a")];
|
||||
@@ -319,4 +503,19 @@ mod tests {
|
||||
Some(PathBuf::from("C:\\Users\\u\\AppData\\Roaming").join("CADCraft"))
|
||||
);
|
||||
}
|
||||
|
||||
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
|
||||
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
|
||||
#[test]
|
||||
fn the_desktop_answers_for_the_system_theme() {
|
||||
let mut raw = egui::RawInput::default();
|
||||
follow_desktop(&mut raw, Some(egui::Theme::Light));
|
||||
assert_eq!(raw.system_theme, Some(egui::Theme::Light));
|
||||
let mut raw = egui::RawInput { system_theme: Some(egui::Theme::Dark), ..Default::default() };
|
||||
follow_desktop(&mut raw, None);
|
||||
assert_eq!(raw.system_theme, Some(egui::Theme::Dark));
|
||||
let mut raw = egui::RawInput::default();
|
||||
follow_desktop(&mut raw, None);
|
||||
assert_eq!(raw.system_theme, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
use std::sync::mpsc;
|
||||
|
||||
use cadcraft_ui_egui::menus::{self, Entry};
|
||||
use cadcraft_ui_egui::{CadApp, i18n};
|
||||
@@ -15,7 +16,14 @@ pub struct NativeMenu {
|
||||
submenus: Vec<(String, Submenu)>,
|
||||
predefined: Vec<(&'static str, PredefinedMenuItem)>,
|
||||
language: &'static str,
|
||||
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
|
||||
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
|
||||
/// ~300 ms of menu enablement.
|
||||
last_refresh: f64,
|
||||
/// The recent files File ▸ Open Recent lists now (it is rebuilt when they change).
|
||||
recent: Vec<String>,
|
||||
counter: usize,
|
||||
events: mpsc::Receiver<MenuEvent>,
|
||||
}
|
||||
|
||||
/// Accelerator for "Cmd+Shift+S" (modifier-less shortcuts stay in the app so typing works).
|
||||
@@ -27,7 +35,16 @@ fn accel(sc: &str) -> Option<Accelerator> {
|
||||
}
|
||||
|
||||
impl NativeMenu {
|
||||
pub fn install(app: &mut CadApp) -> Self {
|
||||
/// Build and register the macOS menu (app menu, Settings and the translated command tree); returns the state holding item ids and submenus.
|
||||
pub fn install(app: &mut CadApp, ctx: &egui::Context) -> Self {
|
||||
// A menu choice (or its shortcut, such as Cmd+W) is no window event, so winit would not
|
||||
// wake the app for it: the handler does, and the choice runs in the next frame.
|
||||
let (sender, events) = mpsc::channel();
|
||||
let wake = ctx.clone();
|
||||
MenuEvent::set_event_handler(Some(move |event| {
|
||||
let _ = sender.send(event);
|
||||
wake.request_repaint();
|
||||
}));
|
||||
let menu = Menu::new();
|
||||
let mut items = HashMap::new();
|
||||
let language = app.language();
|
||||
@@ -43,7 +60,9 @@ impl NativeMenu {
|
||||
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
|
||||
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
|
||||
];
|
||||
let _ = app_menu.append_items(&[&about, &discord, &PredefinedMenuItem::separator()]);
|
||||
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
|
||||
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
|
||||
let _ = app_menu.append_items(&[&about, &discord, &PredefinedMenuItem::separator(), &settings, &PredefinedMenuItem::separator()]);
|
||||
for (label, item) in &predefined {
|
||||
let _ = app_menu.append(item);
|
||||
if ["Services", "Show All"].contains(label) {
|
||||
@@ -52,28 +71,59 @@ impl NativeMenu {
|
||||
}
|
||||
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
|
||||
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
|
||||
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
|
||||
let _ = menu.append(&app_menu);
|
||||
for (title, entries) in menus::tree(app) {
|
||||
let sub = Submenu::new(i18n::tr(language, &title), true);
|
||||
let sub = Submenu::new(i18n::tr_menu(language, &title), true);
|
||||
build(&sub, &entries, &mut items, &mut submenus, &mut counter, language);
|
||||
let _ = menu.append(&sub);
|
||||
submenus.push((title, sub));
|
||||
}
|
||||
menu.init_for_nsapp();
|
||||
Self { _menu: menu, items, submenus, predefined, language, last_refresh: 0.0 }
|
||||
Self {
|
||||
_menu: menu,
|
||||
items,
|
||||
submenus,
|
||||
predefined,
|
||||
language,
|
||||
last_refresh: f64::NEG_INFINITY,
|
||||
recent: app.ui.recent_files.clone(),
|
||||
counter,
|
||||
events,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild File ▸ Open Recent after a drawing was opened or the list was cleared: the native
|
||||
/// menu is built once, and its items name the files by position.
|
||||
fn refresh_recent(&mut self, app: &CadApp) {
|
||||
if self.recent == app.ui.recent_files {
|
||||
return;
|
||||
}
|
||||
self.recent = app.ui.recent_files.clone();
|
||||
let Some(sub) = self.submenus.iter().find(|(label, _)| label == menus::OPEN_RECENT).map(|(_, s)| s.clone()) else { return };
|
||||
for _ in sub.items() {
|
||||
sub.remove_at(0);
|
||||
}
|
||||
let ids: Vec<String> = self.items.iter().filter(|(_, (cmd, _, _))| cmd.starts_with("ui.recent.")).map(|(id, _)| id.clone()).collect();
|
||||
for id in ids {
|
||||
self.items.remove(&id);
|
||||
}
|
||||
build(&sub, &menus::recent_entries(app), &mut self.items, &mut self.submenus, &mut self.counter, self.language);
|
||||
}
|
||||
|
||||
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
|
||||
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
|
||||
while let Ok(ev) = MenuEvent::receiver().try_recv() {
|
||||
while let Ok(ev) = self.events.try_recv() {
|
||||
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
|
||||
if cmd == "ui.discord" {
|
||||
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
|
||||
} else {
|
||||
menus::activate(app, &cmd.clone());
|
||||
menus::activate_native(app, ctx, &cmd.clone());
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
self.refresh_recent(app);
|
||||
let language = app.language();
|
||||
if self.language != language {
|
||||
self.language = language;
|
||||
@@ -84,21 +134,29 @@ impl NativeMenu {
|
||||
item.set_text(i18n::tr(language, label));
|
||||
}
|
||||
for (label, submenu) in &self.submenus {
|
||||
submenu.set_text(i18n::tr(language, label));
|
||||
submenu.set_text(i18n::tr_menu(language, label));
|
||||
}
|
||||
}
|
||||
let now = cadcraft_ui_egui::now_ms();
|
||||
if now - self.last_refresh < 300.0 {
|
||||
if !refresh_due(now, self.last_refresh) {
|
||||
return;
|
||||
}
|
||||
self.last_refresh = now;
|
||||
let typing = menus::text_field_window(ctx).is_some();
|
||||
for (cmd, _, item) in self.items.values() {
|
||||
let en = cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
|
||||
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
|
||||
item.set_enabled(en);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The periodic enablement refresh is due every 300 ms. Split out so the first-poll sentinel is
|
||||
/// testable without a macOS menu: `now_ms` starts near zero, so a `0.0` initial value would
|
||||
/// suppress the first refresh for 300 ms.
|
||||
fn refresh_due(now: f64, last_refresh: f64) -> bool {
|
||||
now - last_refresh >= 300.0
|
||||
}
|
||||
|
||||
fn build(
|
||||
parent: &Submenu,
|
||||
entries: &[Entry],
|
||||
@@ -110,7 +168,7 @@ fn build(
|
||||
for e in entries {
|
||||
match e {
|
||||
Entry::Sub { label, children } => {
|
||||
let sub = Submenu::new(i18n::tr(language, label), true);
|
||||
let sub = Submenu::new(i18n::tr_menu(language, label), true);
|
||||
build(&sub, children, items, submenus, counter, language);
|
||||
let _ = parent.append(&sub);
|
||||
submenus.push((label.clone(), sub));
|
||||
@@ -125,3 +183,17 @@ fn build(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::refresh_due;
|
||||
|
||||
/// `refresh_due` treats `NEG_INFINITY` as due at any finite time and `0.0` as due once 300 ms have elapsed; `install` initializes a fresh menu with `last_refresh = NEG_INFINITY`.
|
||||
#[test]
|
||||
fn the_first_poll_refreshes_immediately() {
|
||||
assert!(refresh_due(0.5, f64::NEG_INFINITY), "a fresh menu refreshes on its first poll");
|
||||
assert!(!refresh_due(0.5, 0.0), "the old 0.0 sentinel delayed the first refresh");
|
||||
assert!(!refresh_due(299.9, 0.0));
|
||||
assert!(refresh_due(300.0, 0.0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Native 3Dconnexion input. The reader publishes one latest sample, never an input queue;
|
||||
//! only movement starting/stopping or status/buttons wake egui. Active motion runs at 60 Hz.
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
mod motion;
|
||||
|
||||
use cadcraft_ui_egui::{CadApp, spacemouse::Status};
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
use std::time::Duration;
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
status: Status,
|
||||
device: Option<String>,
|
||||
detail: Option<String>,
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
motion: motion::Motion,
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
last_report: Option<Instant>,
|
||||
buttons: u8,
|
||||
recalibrate: bool,
|
||||
}
|
||||
|
||||
pub struct SpaceMouse {
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
stop: Arc<AtomicBool>,
|
||||
last_frame: Instant,
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
moving: bool,
|
||||
}
|
||||
|
||||
impl SpaceMouse {
|
||||
pub fn start(ctx: egui::Context) -> Self {
|
||||
let shared = Arc::new(Mutex::new(Shared::default()));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
{
|
||||
let (input, quit, context) = (Arc::clone(&shared), Arc::clone(&stop), ctx.clone());
|
||||
if let Err(error) = std::thread::Builder::new().name("spacemouse-hid".into()).spawn(move || read(input, quit, context)) {
|
||||
set_status(&shared, &ctx, Status::Error, None, Some(error.to_string()));
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
|
||||
let _ = ctx;
|
||||
Self {
|
||||
shared,
|
||||
stop,
|
||||
last_frame: Instant::now(),
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
moving: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
|
||||
let now = Instant::now();
|
||||
let elapsed = now.saturating_duration_since(self.last_frame).as_secs_f64().min(0.05);
|
||||
self.last_frame = now;
|
||||
let Ok(mut shared) = self.shared.lock() else { return };
|
||||
if std::mem::take(&mut app.spacemouse.calibrate_requested) {
|
||||
shared.recalibrate = true;
|
||||
}
|
||||
let changed = app.spacemouse.status != shared.status || app.spacemouse.device != shared.device || app.spacemouse.detail != shared.detail;
|
||||
app.spacemouse.status = shared.status;
|
||||
app.spacemouse.device.clone_from(&shared.device);
|
||||
app.spacemouse.detail.clone_from(&shared.detail);
|
||||
if changed && !matches!(shared.status, Status::Unavailable | Status::Searching) {
|
||||
app.set_status(cadcraft_ui_egui::i18n::tr(app.language(), shared.status.message()));
|
||||
}
|
||||
let buttons = std::mem::take(&mut shared.buttons);
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
let motion = if shared.last_report.is_some_and(|at| now.saturating_duration_since(at) < Duration::from_millis(250)) {
|
||||
shared.motion
|
||||
} else {
|
||||
motion::Motion::default()
|
||||
};
|
||||
drop(shared);
|
||||
let allowed = app.spacemouse.settings.enabled
|
||||
&& ctx.input(|i| i.focused)
|
||||
&& !app.ui.start_tab
|
||||
&& app.ui.dialog.is_none()
|
||||
&& app.closing.is_none()
|
||||
&& app.canvas.rect.is_some()
|
||||
&& !egui::Popup::is_any_open(ctx);
|
||||
if allowed && buttons & 1 != 0 {
|
||||
let _ = app.run("zoom", serde_json::json!({"mode": "extents"}));
|
||||
}
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
{
|
||||
let moving = allowed && motion.active();
|
||||
if moving {
|
||||
if self.moving {
|
||||
let settings = app.spacemouse.settings;
|
||||
let rate = if settings.reverse_zoom { -settings.zoom_speed } else { settings.zoom_speed };
|
||||
if let Err(error) = app.run(
|
||||
"ui.spacemouse.navigate",
|
||||
serde_json::json!({
|
||||
"pan": motion.pan.map(|v| v * settings.pan_speed * elapsed),
|
||||
"zoom": (motion.zoom * rate * elapsed).exp()
|
||||
}),
|
||||
) {
|
||||
app.set_status(error);
|
||||
}
|
||||
}
|
||||
ctx.request_repaint_after(Duration::from_millis(16));
|
||||
}
|
||||
self.moving = moving;
|
||||
}
|
||||
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
|
||||
let _ = elapsed;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SpaceMouse {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
fn set_status(shared: &Mutex<Shared>, ctx: &egui::Context, status: Status, device: Option<String>, detail: Option<String>) {
|
||||
let Ok(mut state) = shared.lock() else { return };
|
||||
let changed = state.status != status || state.device != device || state.detail != detail;
|
||||
if !changed {
|
||||
return;
|
||||
}
|
||||
if let Some(error) = &detail {
|
||||
log::warn!("3D mouse: {error}");
|
||||
}
|
||||
state.status = status;
|
||||
state.device = device;
|
||||
state.detail = detail;
|
||||
state.motion = motion::Motion::default();
|
||||
state.last_report = None;
|
||||
state.buttons = 0;
|
||||
drop(state);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
fn retry(stop: &AtomicBool) {
|
||||
for _ in 0..40 {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
fn read(shared: Arc<Mutex<Shared>>, stop: Arc<AtomicBool>, ctx: egui::Context) {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let mut api = match hidapi::HidApi::new() {
|
||||
Ok(api) => api,
|
||||
Err(error) => {
|
||||
set_status(&shared, &ctx, Status::Error, None, Some(error.to_string()));
|
||||
retry(&stop);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
if let Err(error) = api.refresh_devices() {
|
||||
set_status(&shared, &ctx, Status::Error, None, Some(error.to_string()));
|
||||
break;
|
||||
}
|
||||
let device =
|
||||
api.device_list().find(|device| matches!(device.vendor_id(), 0x046d | 0x256f) && device.usage_page() == 1 && device.usage() == 8);
|
||||
let Some(info) = device else {
|
||||
set_status(&shared, &ctx, Status::Searching, None, None);
|
||||
retry(&stop);
|
||||
continue;
|
||||
};
|
||||
let name = info.product_string().unwrap_or("3Dconnexion SpaceMouse").to_string();
|
||||
match info.open_device(&api) {
|
||||
Ok(device) => {
|
||||
set_status(&shared, &ctx, Status::Calibrating, Some(name.clone()), None);
|
||||
if let Err(error) = read_device(&device, &shared, &stop, &ctx, &name) {
|
||||
set_status(&shared, &ctx, Status::Disconnected, Some(name), Some(error.to_string()));
|
||||
}
|
||||
}
|
||||
Err(error) => set_status(&shared, &ctx, Status::OpenFailed, Some(name), Some(error.to_string())),
|
||||
}
|
||||
retry(&stop);
|
||||
}
|
||||
retry(&stop);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
fn read_device(device: &hidapi::HidDevice, shared: &Mutex<Shared>, stop: &AtomicBool, ctx: &egui::Context, name: &str) -> hidapi::HidResult<()> {
|
||||
let mut filter = motion::Filter::default();
|
||||
let mut buffer = [0; 64];
|
||||
let mut buttons = 0;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let recalibrate = if let Ok(mut state) = shared.lock() { std::mem::take(&mut state.recalibrate) } else { return Ok(()) };
|
||||
if recalibrate {
|
||||
filter.recalibrate();
|
||||
set_status(shared, ctx, Status::Calibrating, Some(name.into()), None);
|
||||
}
|
||||
let len = device.read_timeout(&mut buffer, 50)?;
|
||||
let now = Instant::now();
|
||||
let report = buffer.get(..len).and_then(motion::decode);
|
||||
let Ok(mut state) = shared.lock() else { return Ok(()) };
|
||||
let mut wake = false;
|
||||
match report {
|
||||
Some(motion::Report::Buttons(next)) => {
|
||||
let pressed = next & !buttons;
|
||||
buttons = next;
|
||||
state.buttons |= pressed & 1;
|
||||
state.recalibrate |= pressed & 2 != 0;
|
||||
wake = pressed != 0;
|
||||
}
|
||||
Some(motion::Report::Axes { values, mask }) => {
|
||||
let motion = filter.update(values, mask, now);
|
||||
wake = state.motion.active() != motion.active();
|
||||
state.motion = motion;
|
||||
state.last_report = Some(now);
|
||||
if filter.calibrated() && state.status != Status::Connected {
|
||||
state.status = Status::Connected;
|
||||
wake = true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if state.motion.active() && state.last_report.is_some_and(|at| now.saturating_duration_since(at) >= Duration::from_millis(250)) {
|
||||
state.motion = motion::Motion::default();
|
||||
wake = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
if wake {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Bounded, dependency-free decoding and rest calibration of 3Dconnexion HID input reports.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const FULL_SCALE: f64 = 500.0;
|
||||
const DEADZONE: f64 = 0.04;
|
||||
const REST_LIMIT: f64 = 60.0;
|
||||
const REST_RANGE: f64 = 10.0;
|
||||
const CALIBRATION_TIME: Duration = Duration::from_millis(400);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Report {
|
||||
/// Mask 1 = translation, 2 = rotation, 3 = a combined six-axis report.
|
||||
Axes {
|
||||
values: [i16; 6],
|
||||
mask: u8,
|
||||
},
|
||||
Buttons(u8),
|
||||
}
|
||||
|
||||
/// hidapi includes the report ID. A legacy motion report has six payload bytes; combined
|
||||
/// report 1 has twelve. Windows may pad the short button report to the input-report size.
|
||||
pub fn decode(bytes: &[u8]) -> Option<Report> {
|
||||
let (&id, payload) = bytes.split_first()?;
|
||||
if id == 3 {
|
||||
return payload.first().copied().map(Report::Buttons);
|
||||
}
|
||||
let (mask, offset, count) = match id {
|
||||
1 if payload.len() >= 12 => (3, 0, 6),
|
||||
1 if payload.len() >= 6 => (1, 0, 3),
|
||||
2 if payload.len() >= 6 => (2, 3, 3),
|
||||
_ => return None,
|
||||
};
|
||||
let mut values = [0; 6];
|
||||
for (out, pair) in values.iter_mut().skip(offset).take(count).zip(payload.as_chunks::<2>().0.iter()) {
|
||||
*out = i16::from_le_bytes([*pair.first()?, *pair.get(1)?]);
|
||||
}
|
||||
Some(Report::Axes { values, mask })
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Motion {
|
||||
pub pan: [f64; 2],
|
||||
pub zoom: f64,
|
||||
}
|
||||
|
||||
impl Motion {
|
||||
pub fn active(self) -> bool {
|
||||
self.pan.iter().any(|v| *v != 0.0) || self.zoom != 0.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Rest {
|
||||
since: Option<Instant>,
|
||||
count: u32,
|
||||
sum: [f64; 6],
|
||||
min: [f64; 6],
|
||||
max: [f64; 6],
|
||||
}
|
||||
|
||||
impl Rest {
|
||||
fn observe(&mut self, raw: [f64; 6], now: Instant) -> Option<[f64; 6]> {
|
||||
if raw.iter().any(|v| v.abs() > REST_LIMIT) {
|
||||
*self = Self::default();
|
||||
return None;
|
||||
}
|
||||
if self.since.is_none() || raw.iter().zip(self.min.iter().zip(&self.max)).any(|(v, (min, max))| v.max(*max) - v.min(*min) > REST_RANGE) {
|
||||
*self = Self { since: Some(now), count: 1, sum: raw, min: raw, max: raw };
|
||||
return None;
|
||||
}
|
||||
for ((min, max), value) in self.min.iter_mut().zip(&mut self.max).zip(raw) {
|
||||
*min = min.min(value);
|
||||
*max = max.max(value);
|
||||
}
|
||||
// A fixed bound even if a device sends far more than the expected 125 reports/sec.
|
||||
if self.count < 128 {
|
||||
self.count += 1;
|
||||
for (sum, value) in self.sum.iter_mut().zip(raw) {
|
||||
*sum += value;
|
||||
}
|
||||
}
|
||||
if self.count >= 16 && self.since.is_some_and(|since| now.saturating_duration_since(since) >= CALIBRATION_TIME) {
|
||||
Some(self.sum.map(|sum| sum / f64::from(self.count)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Filter {
|
||||
raw: [f64; 6],
|
||||
bias: Option<[f64; 6]>,
|
||||
rest: Rest,
|
||||
parts: u8,
|
||||
seen: [Option<Instant>; 2],
|
||||
idle_since: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub fn calibrated(&self) -> bool {
|
||||
self.bias.is_some()
|
||||
}
|
||||
|
||||
pub fn recalibrate(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
|
||||
fn update_drift(&mut self, complete: bool, now: Instant, bias: &mut [f64; 6]) {
|
||||
if !complete {
|
||||
return;
|
||||
}
|
||||
if self.raw.iter().zip(*bias).all(|(raw, b)| (*raw - b).abs() <= FULL_SCALE * DEADZONE) {
|
||||
let since = *self.idle_since.get_or_insert(now);
|
||||
if now.saturating_duration_since(since) >= Duration::from_secs(2) {
|
||||
for (b, raw) in bias.iter_mut().zip(self.raw) {
|
||||
*b += (raw - *b) * 0.01;
|
||||
}
|
||||
self.bias = Some(*bias);
|
||||
}
|
||||
} else {
|
||||
self.idle_since = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, values: [i16; 6], mask: u8, now: Instant) -> Motion {
|
||||
for (index, seen) in self.seen.iter_mut().enumerate() {
|
||||
if mask & (1 << index) != 0 {
|
||||
*seen = Some(now);
|
||||
}
|
||||
}
|
||||
for (index, (raw, value)) in self.raw.iter_mut().zip(values).enumerate() {
|
||||
if mask & if index < 3 { 1 } else { 2 } != 0 {
|
||||
*raw = f64::from(value);
|
||||
}
|
||||
}
|
||||
self.parts |= mask & 3;
|
||||
let complete = self.parts == 3;
|
||||
if complete {
|
||||
self.parts = 0;
|
||||
}
|
||||
if self.bias.is_none() && complete {
|
||||
self.bias = self.rest.observe(self.raw, now);
|
||||
}
|
||||
let Some(mut bias) = self.bias else { return Motion::default() };
|
||||
// Follow small resting drift only after two seconds entirely inside the deadzone.
|
||||
self.update_drift(complete, now, &mut bias);
|
||||
let mut axes = [0.0; 6];
|
||||
for ((axis, raw), bias) in axes.iter_mut().zip(self.raw).zip(bias) {
|
||||
let value = ((raw - bias) / FULL_SCALE).clamp(-1.0, 1.0);
|
||||
*axis = if value.abs() <= DEADZONE { 0.0 } else { value.signum() * (value.abs() - DEADZONE) / (1.0 - DEADZONE) };
|
||||
}
|
||||
// A missing rotation report must not keep zooming while translations still arrive.
|
||||
for (group, seen) in axes.as_chunks_mut::<3>().0.iter_mut().zip(self.seen) {
|
||||
if seen.is_none_or(|at| now.saturating_duration_since(at) >= Duration::from_millis(250)) {
|
||||
group.fill(0.0);
|
||||
}
|
||||
}
|
||||
let [tx, ty, tz, _rx, _ry, rz] = axes;
|
||||
Motion { pan: [tx, ty], zoom: (tz + rz).clamp(-1.0, 1.0) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decode_reports() {
|
||||
assert_eq!(decode(&[]), None);
|
||||
assert_eq!(decode(&[3]), None);
|
||||
assert_eq!(decode(&[3, 5]), Some(Report::Buttons(5)));
|
||||
let values = [1_i16, -2, 3, 4, -5, 6];
|
||||
let mut bytes = vec![1_u8];
|
||||
for v in values {
|
||||
bytes.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
assert_eq!(decode(&bytes), Some(Report::Axes { values, mask: 3 }));
|
||||
bytes[0] = 2;
|
||||
assert_eq!(decode(&bytes), Some(Report::Axes { values: [0, 0, 0, 1, -2, 3], mask: 2 }));
|
||||
assert_eq!(decode(&[2, 1, 2, 3]), None, "too short for a rotation report");
|
||||
}
|
||||
|
||||
/// Sixteen complete reports at rest, spread over more than CALIBRATION_TIME, all stamped
|
||||
/// on a made-up point in time big enough that they sit in the past of later updates.
|
||||
fn calibrated(t0: Instant) -> Filter {
|
||||
let mut f = Filter::default();
|
||||
for i in 0..17 {
|
||||
let at = t0 + Duration::from_millis(50 * i);
|
||||
assert_eq!(f.update([0; 6], 1, at), Motion::default());
|
||||
assert_eq!(f.update([0; 6], 2, at), Motion::default());
|
||||
}
|
||||
assert!(f.calibrated());
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axes_deflect_and_expire() {
|
||||
let t0 = Instant::now();
|
||||
let mut f = calibrated(t0);
|
||||
let at = t0 + Duration::from_secs(2);
|
||||
let ms = Duration::from_millis;
|
||||
let m = f.update([500, 500, 0, 0, 0, 0], 1, at);
|
||||
assert!((m.pan[0] - 1.0).abs() < 1e-9);
|
||||
assert!((m.pan[1] - 1.0).abs() < 1e-9);
|
||||
assert_eq!(m.zoom, 0.0, "no rotation input");
|
||||
// A fresh rotation report drives the zoom.
|
||||
let m = f.update([0, 0, 0, 0, 0, 500], 2, at + ms(100));
|
||||
assert!((m.zoom - 1.0).abs() < 1e-9);
|
||||
// The rotation axes went quiet for over 250 ms while translations still arrive.
|
||||
let m = f.update([500, 500, 0, 0, 0, 0], 1, at + ms(400));
|
||||
assert_eq!(m.zoom, 0.0);
|
||||
// A fresh rotation report puts the zoom back.
|
||||
let m = f.update([500, 500, 0, 0, 0, 500], 2, at + ms(500));
|
||||
assert!((m.zoom - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drift_tracks_rest_after_two_idle_seconds() {
|
||||
// Five axes units of drift sit inside the deadzone (FULL_SCALE * DEADZONE = 20).
|
||||
let mut f = Filter { raw: [5.0; 6], bias: Some([0.0; 6]), ..Filter::default() };
|
||||
let t0 = Instant::now();
|
||||
let mut b = [0.0; 6];
|
||||
f.update_drift(true, t0, &mut b); // starts the idle window: no shift yet
|
||||
assert_eq!(b, [0.0; 6]);
|
||||
f.update_drift(true, t0 + Duration::from_secs(3), &mut b);
|
||||
assert!((b[0] - 0.05).abs() < 1e-12, "bias follows resting drift");
|
||||
assert_eq!(f.bias, Some(b));
|
||||
// Motion outside the deadzone resets the idle window.
|
||||
f.raw = [100.0; 6];
|
||||
f.update_drift(true, t0 + Duration::from_secs(4), &mut b);
|
||||
assert_eq!(f.idle_since, None);
|
||||
f.update_drift(true, t0 + Duration::from_secs(5), &mut b);
|
||||
assert!((b[0] - 0.05).abs() < 1e-12, "no shift before two seconds at rest");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! Whether the operating system shows animations, for View ▸ Accessibility ▸ Animation Effects ▸
|
||||
//! Use System Setting.
|
||||
//!
|
||||
//! egui animates whatever the OS says (windows and menus fade in, wheel scrolling glides), and
|
||||
//! winit reports no such setting. This asks the OS itself:
|
||||
//!
|
||||
//! - Windows: Settings ▸ Accessibility ▸ Visual effects ▸ Animation effects.
|
||||
//! - macOS: System Settings ▸ Accessibility ▸ Reduce motion.
|
||||
//! - Linux and the BSDs: the XDG Desktop Portal's Settings interface, as for the theme
|
||||
//! (`desktop_theme.rs`): its `reduced-motion`, or GNOME's own `enable-animations`.
|
||||
//!
|
||||
//! The answer goes to `CadApp::system_animations` once a frame.
|
||||
|
||||
use std::sync::mpsc::{Receiver, TryRecvError, channel};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How often the OS is asked again, so a change to its setting is followed while CADCraft runs.
|
||||
const POLL: Duration = Duration::from_secs(3);
|
||||
|
||||
/// Watches the OS setting.
|
||||
#[derive(Default)]
|
||||
pub struct SystemAnimations {
|
||||
/// The watcher thread's answers, where asking can block (the portal); `None` elsewhere, or
|
||||
/// when no thread could be started.
|
||||
changes: Option<Receiver<Option<bool>>>,
|
||||
/// The OS's last answer.
|
||||
current: Option<bool>,
|
||||
/// When the OS was last asked from the UI thread, where asking is one quick call.
|
||||
asked: Option<Instant>,
|
||||
}
|
||||
|
||||
impl SystemAnimations {
|
||||
/// Start watching. Where a thread does the asking, `wake` is called after each answer, so an
|
||||
/// idle window repaints and picks it up.
|
||||
pub fn start(wake: impl Fn() + Send + 'static) -> Self {
|
||||
if !ASKS_THE_PORTAL {
|
||||
return Self::default();
|
||||
}
|
||||
let (tx, rx) = channel();
|
||||
let started = std::thread::Builder::new().name("cadcraft-system-animations".into()).spawn(move || {
|
||||
let mut last = read();
|
||||
if tx.send(last).is_err() {
|
||||
return;
|
||||
}
|
||||
wake();
|
||||
loop {
|
||||
std::thread::sleep(POLL);
|
||||
let now = read();
|
||||
if now != last {
|
||||
last = now;
|
||||
if tx.send(now).is_err() {
|
||||
return;
|
||||
}
|
||||
wake();
|
||||
}
|
||||
}
|
||||
});
|
||||
Self { changes: started.ok().map(|_| rx), ..Self::default() }
|
||||
}
|
||||
|
||||
/// Whether the OS shows animations; `None` when it states nothing or there is nobody to ask.
|
||||
/// Polled once a frame; an OS that stops answering keeps its last answer.
|
||||
pub fn current(&mut self) -> Option<bool> {
|
||||
if let Some(changes) = &self.changes {
|
||||
loop {
|
||||
match changes.try_recv() {
|
||||
Ok(Some(animate)) => self.current = Some(animate),
|
||||
Ok(None) => {}
|
||||
Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
} else if !ASKS_THE_PORTAL && self.asked.is_none_or(|at| at.elapsed() >= POLL) {
|
||||
self.asked = Some(Instant::now());
|
||||
if let Some(animate) = read() {
|
||||
self.current = Some(animate);
|
||||
}
|
||||
}
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the answer comes over D-Bus, which can block: a thread asks. Elsewhere the UI thread asks.
|
||||
const ASKS_THE_PORTAL: bool = cfg!(all(unix, not(target_os = "macos")));
|
||||
|
||||
/// Ask Windows once: `UISettings::AnimationsEnabled`, the setting behind
|
||||
/// `SPI_GETCLIENTAREAANIMATION`.
|
||||
#[cfg(windows)]
|
||||
fn read() -> Option<bool> {
|
||||
windows::UI::ViewManagement::UISettings::new().and_then(|settings| settings.AnimationsEnabled()).ok()
|
||||
}
|
||||
|
||||
/// Ask macOS once. Called on the main thread (`SystemAnimations::current`).
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read() -> Option<bool> {
|
||||
Some(!objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion())
|
||||
}
|
||||
|
||||
/// Ask the portal once. D-Bus calls block, so this belongs off the UI thread: the watcher's
|
||||
/// thread is its only caller.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn read() -> Option<bool> {
|
||||
const PORTAL: &str = "org.freedesktop.portal.Desktop";
|
||||
const PATH: &str = "/org/freedesktop/portal/desktop";
|
||||
const SETTINGS: &str = "org.freedesktop.portal.Settings";
|
||||
// The standard key first (0 no preference, 1 reduced motion); then GNOME's own switch, which
|
||||
// its portal answered before the standard key existed.
|
||||
const KEYS: [(&str, &str); 2] = [("org.freedesktop.appearance", "reduced-motion"), ("org.gnome.desktop.interface", "enable-animations")];
|
||||
let connection = zbus::blocking::Connection::session().ok()?;
|
||||
for (namespace, key) in KEYS {
|
||||
// `ReadOne` (Settings version 2) answers the value; older portals only have `Read`, which
|
||||
// wraps it in one more variant. `parse` unwraps either.
|
||||
let reply = connection
|
||||
.call_method(Some(PORTAL), PATH, Some(SETTINGS), "ReadOne", &(namespace, key))
|
||||
.or_else(|_| connection.call_method(Some(PORTAL), PATH, Some(SETTINGS), "Read", &(namespace, key)));
|
||||
let Ok(reply) = reply else { continue };
|
||||
let Ok((answer,)) = reply.body().deserialize::<(zbus::zvariant::OwnedValue,)>() else { continue };
|
||||
if let Some(animate) = parse(&answer, 0) {
|
||||
return Some(animate);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The portal's answer as "show animations": `reduced-motion` is a number (1 asks for less
|
||||
/// motion; 0 and values from a later version state no preference), `enable-animations` a
|
||||
/// boolean. `None` when it reads as neither. Variants are unwrapped a few levels deep.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn parse(value: &zbus::zvariant::Value<'_>, depth: u8) -> Option<bool> {
|
||||
use zbus::zvariant::Value;
|
||||
match value {
|
||||
Value::U32(reduced) => Some(*reduced != 1),
|
||||
Value::Bool(enabled) => Some(*enabled),
|
||||
Value::Value(inner) if depth < 4 => parse(inner, depth + 1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn read() -> Option<bool> {
|
||||
None
|
||||
}
|
||||
|
||||
// macOS is asked on the main thread only, so there is nothing to test off it.
|
||||
#[cfg(all(test, not(target_os = "macos")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Windows is asked on the first frame, then not again until the poll interval has passed.
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn the_os_is_asked_on_the_first_frame_and_its_answer_kept() {
|
||||
let mut watch = SystemAnimations::start(|| {});
|
||||
assert!(watch.changes.is_none(), "no thread: asking is one quick call");
|
||||
let first = watch.current();
|
||||
assert_eq!(first, read());
|
||||
let asked = watch.asked;
|
||||
assert!(asked.is_some());
|
||||
assert_eq!(watch.current(), first);
|
||||
assert_eq!(watch.asked, asked, "not asked again within the poll interval");
|
||||
}
|
||||
|
||||
/// The standard key answers a number, GNOME's switch a boolean; either may come wrapped in
|
||||
/// variants (the older `Read`).
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn the_portal_answer_reads_as_show_animations_or_as_none() {
|
||||
use zbus::zvariant::Value;
|
||||
assert_eq!(parse(&Value::U32(1), 0), Some(false));
|
||||
assert_eq!(parse(&Value::U32(0), 0), Some(true));
|
||||
assert_eq!(parse(&Value::U32(7), 0), Some(true), "unknown values are no preference");
|
||||
assert_eq!(parse(&Value::Bool(false), 0), Some(false));
|
||||
assert_eq!(parse(&Value::Bool(true), 0), Some(true));
|
||||
assert_eq!(parse(&Value::Value(Box::new(Value::U32(1))), 0), Some(false));
|
||||
assert_eq!(parse(&Value::Str("off".into()), 0), None);
|
||||
// A hostile answer nested without end is given up on.
|
||||
let mut nested = Value::U32(1);
|
||||
for _ in 0..16 {
|
||||
nested = Value::Value(Box::new(nested));
|
||||
}
|
||||
assert_eq!(parse(&nested, 0), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
//! Native workspace preferences. Drawing data and transient dialogs never enter this file.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use cadcraft_ui_egui::UiState;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const MAX_BYTES: u64 = 64 * 1024;
|
||||
/// Dragging a floating window changes its rect every frame; writes (each with an fsync) are
|
||||
/// spaced at least this far apart, and the newest state is written when the interval ends.
|
||||
const MIN_WRITE_INTERVAL: Duration = Duration::from_millis(500);
|
||||
static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub struct Workspace {
|
||||
path: Option<PathBuf>,
|
||||
last_attempt: Option<Value>,
|
||||
read_failed: bool,
|
||||
pending_write_error: Option<String>,
|
||||
last_write: Option<Instant>,
|
||||
}
|
||||
|
||||
fn config_dir_from(platform: &str, get: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
if let Some(root) = get("CADCRAFT_CONFIG_DIR") {
|
||||
return (!root.is_empty()).then(|| PathBuf::from(root));
|
||||
}
|
||||
let nonempty = |key| get(key).filter(|value| !value.is_empty()).map(PathBuf::from);
|
||||
match platform {
|
||||
"macos" => nonempty("HOME").map(|home| home.join("Library/Application Support/CADCraft")),
|
||||
"windows" => nonempty("APPDATA").map(|root| root.join("CADCraft")),
|
||||
_ => nonempty("XDG_CONFIG_HOME").map(|root| root.join("cadcraft")).or_else(|| nonempty("HOME").map(|home| home.join(".config/cadcraft"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(ui: &UiState) -> Result<Value, String> {
|
||||
cadcraft_ui_egui::docking::validate(&ui.docking)?;
|
||||
if !matches!(ui.toolset_tab.as_str(), "Drafting" | "Modeling") {
|
||||
return Err("toolsetTab must be Drafting or Modeling".into());
|
||||
}
|
||||
if ui.collapsed_groups.len() > 64 || ui.collapsed_groups.iter().any(|name| name.len() > 256) {
|
||||
return Err("collapsedGroups exceeds the workspace size limit".into());
|
||||
}
|
||||
if ui.history_lines > 12 {
|
||||
return Err("historyLines must be between 0 and 12".into());
|
||||
}
|
||||
Ok(json!({
|
||||
"docking": ui.docking,
|
||||
"dockingVersion": cadcraft_ui_egui::docking::LAYOUT_VERSION,
|
||||
"showToolsets": ui.show_toolsets,
|
||||
"showPalettes": ui.show_palettes,
|
||||
"showToolbar": ui.show_toolbar,
|
||||
"showFileTabs": ui.show_file_tabs,
|
||||
"showStatusBar": ui.show_status_bar,
|
||||
"showCommandLine": ui.show_command_line,
|
||||
"showViewcube": ui.show_viewcube,
|
||||
"showUcsIcon": ui.show_ucs_icon,
|
||||
"showLayerList": ui.show_layer_list,
|
||||
"toolsetTab": ui.toolset_tab,
|
||||
"collapsedGroups": ui.collapsed_groups,
|
||||
"propertiesAll": ui.properties_all,
|
||||
"inWindowMenu": ui.in_window_menu,
|
||||
"historyLines": ui.history_lines,
|
||||
}))
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<Option<UiState>, String> {
|
||||
let file = match File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(format!("{}: {error}", path.display())),
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_BYTES + 1).read_to_end(&mut bytes).map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return Err(format!("{}: workspace file exceeds 64 KiB", path.display()));
|
||||
}
|
||||
let value: Value = serde_json::from_slice(&bytes).map_err(|error| format!("{}: invalid workspace JSON: {error}", path.display()))?;
|
||||
if value.get("version").and_then(Value::as_u64) != Some(1) {
|
||||
return Err(format!("{}: unsupported workspace version", path.display()));
|
||||
}
|
||||
let workspace =
|
||||
value.get("workspace").filter(|value| value.is_object()).ok_or_else(|| format!("{}: missing workspace object", path.display()))?;
|
||||
// Dock schemas can evolve independently of the other saved workspace preferences.
|
||||
// Recover only this optional field; runtime UiState deserialization remains strict.
|
||||
// A layout from before the current shape (split frames, saved without `dockingVersion`)
|
||||
// gives way to the default, its hidden panels with it.
|
||||
let mut fields = workspace.clone();
|
||||
let (docking, version) = match fields.as_object_mut() {
|
||||
Some(fields) => (fields.remove("docking"), fields.remove("dockingVersion")),
|
||||
None => (None, None),
|
||||
};
|
||||
let current = version.and_then(|version| version.as_u64()).is_some_and(|version| version >= u64::from(cadcraft_ui_egui::docking::LAYOUT_VERSION));
|
||||
let mut ui: UiState = serde_json::from_value(fields).map_err(|error| format!("{}: invalid workspace: {error}", path.display()))?;
|
||||
if let Some(docking) = docking.filter(|_| current)
|
||||
&& let Ok(docking) = serde_json::from_value::<cadcraft_ui_egui::docking::Workspace>(docking)
|
||||
&& cadcraft_ui_egui::docking::validate(&docking).is_ok()
|
||||
{
|
||||
ui.docking = docking;
|
||||
}
|
||||
// Old or hand-edited files cannot reopen a dialog or replace the active drawing view.
|
||||
ui.dialog = None;
|
||||
ui.start_tab = false;
|
||||
snapshot(&ui).map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
Ok(Some(ui))
|
||||
}
|
||||
|
||||
fn write(path: &Path, workspace: &Value) -> Result<(), String> {
|
||||
let bytes = serde_json::to_vec_pretty(&json!({"version": 1, "workspace": workspace})).map_err(|error| error.to_string())?;
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return Err("workspace exceeds 64 KiB".into());
|
||||
}
|
||||
let parent = path.parent().ok_or("workspace path has no parent")?;
|
||||
fs::create_dir_all(parent).map_err(|error| format!("{}: {error}", parent.display()))?;
|
||||
let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let temporary = parent.join(format!(".workspace-{}-{sequence}.tmp", std::process::id()));
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(&temporary).map_err(|error| format!("{}: {error}", temporary.display()))?;
|
||||
let result = (|| {
|
||||
file.write_all(&bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
fs::rename(&temporary, path)
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
return Err(format!("{}: could not save workspace: {error}", path.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub fn load() -> (Self, Option<UiState>, Option<String>) {
|
||||
Self::at(config_dir_from(std::env::consts::OS, |key| std::env::var_os(key)).map(|root| root.join("workspace.json")))
|
||||
}
|
||||
|
||||
fn at(path: Option<PathBuf>) -> (Self, Option<UiState>, Option<String>) {
|
||||
let result = path.as_deref().map(read).transpose().map(Option::flatten);
|
||||
match result {
|
||||
Ok(ui) => {
|
||||
let initial = ui.as_ref().cloned().unwrap_or_default();
|
||||
(Self { path, last_attempt: snapshot(&initial).ok(), read_failed: false, pending_write_error: None, last_write: None }, ui, None)
|
||||
}
|
||||
Err(error) => (
|
||||
Self { path, last_attempt: None, read_failed: true, pending_write_error: None, last_write: None },
|
||||
None,
|
||||
Some(format!("Workspace could not be restored; its file was left unchanged. {error}")),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `ui` if it differs from the last state written. `Ok(Some(wait))` means a change
|
||||
/// is held back by [`MIN_WRITE_INTERVAL`]; call again after `wait` to write it.
|
||||
pub fn save_if_changed(&mut self, ui: &UiState, now: Instant) -> Result<Option<Duration>, String> {
|
||||
let Some(path) = &self.path else { return Ok(None) };
|
||||
if self.read_failed {
|
||||
// Preserve a corrupt, oversized or newer-version file until the user repairs it.
|
||||
return Ok(None);
|
||||
}
|
||||
let value = snapshot(ui)?;
|
||||
if self.last_attempt.as_ref() == Some(&value) {
|
||||
return self.pending_write_error.clone().map_or(Ok(None), Err);
|
||||
}
|
||||
if let Some(wait) = self.last_write.and_then(|last| MIN_WRITE_INTERVAL.checked_sub(now.saturating_duration_since(last)))
|
||||
&& !wait.is_zero()
|
||||
{
|
||||
return Ok(Some(wait));
|
||||
}
|
||||
// Keep a failed state's warning without retrying disk I/O every rendered frame.
|
||||
self.last_attempt = Some(value.clone());
|
||||
self.last_write = Some(now);
|
||||
let result = write(path, &value);
|
||||
self.pending_write_error = result.as_ref().err().cloned();
|
||||
result.map(|()| None)
|
||||
}
|
||||
|
||||
pub fn save_on_exit(&mut self, ui: &UiState) -> Result<(), String> {
|
||||
if self.pending_write_error.is_some() {
|
||||
self.last_attempt = None;
|
||||
}
|
||||
self.last_write = None;
|
||||
self.save_if_changed(ui, Instant::now()).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-workspace-test-{}-{sequence}", std::process::id()));
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_override_isolated_or_explicitly_disabled() {
|
||||
let get = |key: &str| match key {
|
||||
"CADCRAFT_CONFIG_DIR" => Some(OsString::from("/private/test-state")),
|
||||
"HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some(OsString::from("/unrelated-user-profile")),
|
||||
_ => None,
|
||||
};
|
||||
for platform in ["macos", "windows", "linux", "freebsd"] {
|
||||
assert_eq!(config_dir_from(platform, get), Some(PathBuf::from("/private/test-state")));
|
||||
assert_eq!(config_dir_from(platform, |key| if key == "CADCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { get(key) }), None);
|
||||
}
|
||||
assert_eq!(
|
||||
config_dir_from("linux", |key| (key == "XDG_CONFIG_HOME").then(|| OsString::from("/config"))),
|
||||
Some(PathBuf::from("/config/cadcraft"))
|
||||
);
|
||||
assert_eq!(config_dir_from("macos", |_| None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_survives_new_store_without_transient_or_document_state() {
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut first, restored, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(restored.is_none() && error.is_none());
|
||||
let ui = UiState {
|
||||
show_palettes: false,
|
||||
show_command_line: false,
|
||||
toolset_tab: "Modeling".into(),
|
||||
collapsed_groups: vec!["Solid".into()],
|
||||
history_lines: 5,
|
||||
dialog: Some("layers".into()),
|
||||
start_tab: true,
|
||||
..Default::default()
|
||||
};
|
||||
first.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
let value: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert!(value["workspace"].get("dialog").is_none());
|
||||
assert!(value["workspace"].get("startTab").is_none());
|
||||
let (_, restored, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(error.is_none());
|
||||
let restored = restored.unwrap();
|
||||
assert_eq!(snapshot(&restored).unwrap(), snapshot(&ui).unwrap());
|
||||
assert!(restored.dialog.is_none() && !restored.start_tab);
|
||||
let mut transient_only = ui.clone();
|
||||
transient_only.dialog = None;
|
||||
transient_only.start_tab = false;
|
||||
first.save_if_changed(&transient_only, Instant::now()).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), bytes);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_columns_floating_and_hidden_panels_survive_native_workspace_file_reload() {
|
||||
use cadcraft_ui_egui::docking::{LAYOUT_VERSION, Panel, permissions, reveal_panel};
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut store, _, _) = Workspace::at(Some(path.clone()));
|
||||
let mut ui = UiState::default();
|
||||
let mut app = cadcraft_ui_egui::CadApp::new(cadcraft_engine::Session::default(), Default::default());
|
||||
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
|
||||
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
|
||||
ui.docking = app.ui.docking;
|
||||
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
|
||||
ui.show_toolsets = false;
|
||||
store.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(saved["workspace"]["dockingVersion"], json!(LAYOUT_VERSION));
|
||||
let (_, reloaded, error) = Workspace::at(Some(path));
|
||||
assert!(error.is_none());
|
||||
let mut reloaded = reloaded.unwrap();
|
||||
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
|
||||
assert!(!reloaded.show_toolsets);
|
||||
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
|
||||
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
|
||||
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
|
||||
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_frame_layout_file_loads_as_the_dock_default_with_its_other_settings() {
|
||||
use cadcraft_ui_egui::docking::default_workspace;
|
||||
// Written as CADCraft 0.7 writes it: craft-ui's v1 layout with no docking version, a
|
||||
// floating window as one `{panels, active, rect}` group, Tool Sets closed.
|
||||
let file = r#"{"version":1,"workspace":{
|
||||
"docking":{
|
||||
"layout":{
|
||||
"root":{"Split":{"axis":"Horizontal","size":{"FixedSecond":300.0},
|
||||
"first":{"Tabs":{"panels":["canvas"],"active":0}},
|
||||
"second":{"Stack":{"entries":[{"panel":"properties","open":false,"height":null}]}}}},
|
||||
"floating":[{"panels":["layers","externalReferences"],"active":1,"rect":[120.0,90.0,340.0,410.0]}]},
|
||||
"hidden":[["toolSets",{"floating":null,"anchor":"canvas","placement":{"Split":"Left"},
|
||||
"size":{"FixedFirst":220.0},"stack":null,"sibling":["canvas","properties"]}]]},
|
||||
"showToolsets":false,"showPalettes":true,"showToolbar":false,"toolsetTab":"Modeling","historyLines":4}}"#;
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
fs::write(&path, file).unwrap();
|
||||
let (_, restored, error) = Workspace::at(Some(path));
|
||||
assert!(error.is_none(), "{error:?}");
|
||||
let ui = restored.unwrap();
|
||||
assert_eq!(ui.toolset_tab, "Modeling");
|
||||
assert_eq!(ui.history_lines, 4);
|
||||
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
|
||||
assert_eq!(ui.docking.layout, default_workspace().layout);
|
||||
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_oversized_and_newer_state_are_reported_and_preserved() {
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
for bytes in [
|
||||
b"{invalid".to_vec(),
|
||||
vec![b' '; MAX_BYTES as usize + 1],
|
||||
br#"{"version":2,"workspace":{}}"#.to_vec(),
|
||||
br#"{"version":1,"workspace":{"toolsetTab":"unknown"}}"#.to_vec(),
|
||||
br#"{"version":1,"workspace":{"historyLines":18446744073709551615}}"#.to_vec(),
|
||||
] {
|
||||
fs::write(&path, &bytes).unwrap();
|
||||
let (mut store, ui, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(ui.is_none());
|
||||
assert!(error.as_deref().is_some_and(|error| error.contains("left unchanged")));
|
||||
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }, Instant::now()).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), bytes);
|
||||
}
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_docking_preserves_other_workspace_preferences() {
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
for docking in [
|
||||
json!({"layout":{"root":{"FuturePanelGroup":{}}},"hidden":[]}),
|
||||
json!({"layout":false,"hidden":[]}),
|
||||
json!({"layout":{"root":null,"floating":[]},"hidden":[["futurePanel",{}]]}),
|
||||
] {
|
||||
let workspace = json!({"showToolbar":false,"showPalettes":false,"toolsetTab":"Modeling", "collapsedGroups":["Draw"], "historyLines":7,"docking":docking,
|
||||
"dockingVersion":cadcraft_ui_egui::docking::LAYOUT_VERSION});
|
||||
assert!(serde_json::from_value::<UiState>(workspace.clone()).is_err(), "runtime state must stay strict");
|
||||
fs::write(&path, serde_json::to_vec(&json!({"version":1,"workspace":workspace})).unwrap()).unwrap();
|
||||
let (_, restored, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(error.is_none());
|
||||
let restored = restored.unwrap();
|
||||
assert!(!restored.show_toolbar);
|
||||
assert!(!restored.show_palettes);
|
||||
assert_eq!(restored.toolset_tab, "Modeling");
|
||||
assert_eq!(restored.collapsed_groups, ["Draw"]);
|
||||
assert_eq!(restored.history_lines, 7);
|
||||
assert_eq!(serde_json::to_value(restored.docking).unwrap(), serde_json::to_value(UiState::default().docking).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rapid_changes_are_written_once_per_interval_with_the_newest_state() {
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut store, _, _) = Workspace::at(Some(path.clone()));
|
||||
let start = Instant::now();
|
||||
let mut ui = UiState { history_lines: 1, ..Default::default() };
|
||||
assert_eq!(store.save_if_changed(&ui, start).unwrap(), None);
|
||||
// A drag: a new state every frame, none of them written until the interval ends.
|
||||
for (frame, lines) in (2..=5).enumerate() {
|
||||
ui.history_lines = lines;
|
||||
let now = start + Duration::from_millis(16 * (frame as u64 + 1));
|
||||
let wait = store.save_if_changed(&ui, now).unwrap();
|
||||
assert_eq!(wait, Some(MIN_WRITE_INTERVAL - (now - start)));
|
||||
}
|
||||
assert_eq!(read(&path).unwrap().unwrap().history_lines, 1);
|
||||
assert_eq!(store.save_if_changed(&ui, start + MIN_WRITE_INTERVAL).unwrap(), None);
|
||||
assert_eq!(read(&path).unwrap().unwrap().history_lines, 5);
|
||||
ui.history_lines = 6;
|
||||
assert!(store.save_if_changed(&ui, start + MIN_WRITE_INTERVAL).unwrap().is_some());
|
||||
store.save_on_exit(&ui).unwrap();
|
||||
assert_eq!(read(&path).unwrap().unwrap().history_lines, 6);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_update_cannot_replace_last_good_workspace() {
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut store, _, _) = Workspace::at(Some(path.clone()));
|
||||
let mut ui = UiState { show_palettes: false, ..Default::default() };
|
||||
store.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
let good = fs::read(&path).unwrap();
|
||||
ui.collapsed_groups = vec!["x".repeat(257)];
|
||||
assert!(store.save_if_changed(&ui, Instant::now()).is_err());
|
||||
assert_eq!(fs::read(&path).unwrap(), good);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_write_keeps_warning_and_retries_once_on_exit() {
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut store, _, _) = Workspace::at(Some(path.clone()));
|
||||
// Simulate a destination becoming unavailable after startup.
|
||||
fs::create_dir(&path).unwrap();
|
||||
let ui = UiState { show_palettes: false, ..Default::default() };
|
||||
let first_error = store.save_if_changed(&ui, Instant::now()).unwrap_err();
|
||||
fs::remove_dir(&path).unwrap();
|
||||
assert_eq!(store.save_if_changed(&ui, Instant::now()).unwrap_err(), first_error);
|
||||
assert!(!path.exists(), "ordinary frames must not retry disk writes");
|
||||
store.save_on_exit(&ui).unwrap();
|
||||
assert!(!read(&path).unwrap().unwrap().show_palettes);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -22,9 +22,72 @@ real_name = "Brandon Thomas"
|
||||
display_name = "Brandon Thomas"
|
||||
sync_github_name = false
|
||||
|
||||
[people.switch87]
|
||||
real_name = "Gert Pellin"
|
||||
display_name = "Gert Pellin"
|
||||
sync_github_name = false
|
||||
|
||||
[people.rangoDJ]
|
||||
sync_github_name = true
|
||||
|
||||
[people.Tru10]
|
||||
display_name = "by Truitt"
|
||||
sync_github_name = false
|
||||
|
||||
[people.tsangiotis]
|
||||
real_name = "Tasos Sangiotis"
|
||||
display_name = "Tasos Sangiotis"
|
||||
sync_github_name = false
|
||||
|
||||
[people.vangel76]
|
||||
sync_github_name = true
|
||||
|
||||
[people.WladmirJunior]
|
||||
real_name = "Wladmir Júnior"
|
||||
sync_github_name = true
|
||||
|
||||
[people.Losminek]
|
||||
sync_github_name = true
|
||||
|
||||
[people.GJoe2]
|
||||
sync_github_name = true
|
||||
|
||||
[people.holmbom]
|
||||
real_name = "Erik Holmbom"
|
||||
display_name = "Erik Holmbom"
|
||||
sync_github_name = false
|
||||
|
||||
[people.cyfung1031]
|
||||
real_name = "Chester Fung"
|
||||
display_name = "Chester Fung"
|
||||
sync_github_name = true
|
||||
|
||||
[people.C00kieMonsta]
|
||||
real_name = "Antoine Boxho"
|
||||
display_name = "Antoine Boxho"
|
||||
sync_github_name = true
|
||||
|
||||
[people.Silvertree2010]
|
||||
display_name = "Netter"
|
||||
sync_github_name = false
|
||||
|
||||
[people.gurparvez]
|
||||
real_name = "Gurparvez"
|
||||
|
||||
[people.nicholasgower]
|
||||
sync_github_name = true
|
||||
|
||||
[people.ffishman]
|
||||
real_name = "Rodrigo Gressler"
|
||||
display_name = "Rodrigo"
|
||||
sync_github_name = false
|
||||
|
||||
[people.aussieboer61]
|
||||
real_name = "Richard Sauer"
|
||||
display_name = "Richard Sauer"
|
||||
sync_github_name = false
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
|
||||
+52
-9
@@ -21,8 +21,9 @@ impl Rgb {
|
||||
format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
|
||||
}
|
||||
pub fn parse_hex(s: &str) -> Option<Rgb> {
|
||||
let s = s.trim().trim_start_matches('#');
|
||||
if s.len() != 6 || !s.is_ascii() {
|
||||
let s = s.trim();
|
||||
let s = s.strip_prefix('#').unwrap_or(s);
|
||||
if s.len() != 6 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
u32::from_str_radix(s, 16).ok().map(Rgb::from_u32)
|
||||
@@ -110,9 +111,9 @@ impl Color {
|
||||
_ => {}
|
||||
}
|
||||
if let Some(rest) = t.strip_prefix("color ") {
|
||||
return rest.trim().parse::<u8>().ok().filter(|i| *i >= 1).map(Color::Index);
|
||||
return parse_digits::<u8>(rest.trim()).filter(|i| *i >= 1).map(Color::Index);
|
||||
}
|
||||
if let Ok(i) = t.parse::<u16>() {
|
||||
if let Some(i) = parse_digits::<u16>(&t) {
|
||||
return match i {
|
||||
0 => Some(Color::ByBlock),
|
||||
256 => Some(Color::ByLayer),
|
||||
@@ -123,14 +124,22 @@ impl Color {
|
||||
if t.starts_with('#') {
|
||||
return Rgb::parse_hex(&t).map(Color::True);
|
||||
}
|
||||
let parts: Vec<_> = t.split(',').map(|p| p.trim().parse::<u8>()).collect();
|
||||
if let [Ok(r), Ok(g), Ok(b)] = parts.as_slice() {
|
||||
let parts: Vec<_> = t.split(',').map(|p| parse_digits::<u8>(p.trim())).collect();
|
||||
if let [Some(r), Some(g), Some(b)] = parts.as_slice() {
|
||||
return Some(Color::True(Rgb(*r, *g, *b)));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an unsigned integer made of ASCII digits only (no sign, unlike `str::parse`).
|
||||
fn parse_digits<T: std::str::FromStr>(s: &str) -> Option<T> {
|
||||
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
s.parse().ok()
|
||||
}
|
||||
|
||||
/// The RGB of ACI `i` (0 and out-of-range map to white/7).
|
||||
pub fn aci_rgb(i: u8) -> Rgb {
|
||||
PALETTE.get(usize::from(i)).copied().unwrap_or(Rgb(255, 255, 255))
|
||||
@@ -156,7 +165,7 @@ fn build_palette() -> [Rgb; 256] {
|
||||
for (slot, c) in p.iter_mut().zip(base) {
|
||||
*slot = c;
|
||||
}
|
||||
let values = [255.0, 165.0, 127.0, 76.0, 38.0];
|
||||
let values = [255.0, 204.0, 153.0, 127.0, 76.0];
|
||||
for i in 10..250usize {
|
||||
let hue = (i - 10) / 10; // 0..24, 15° each
|
||||
let sub = i % 10;
|
||||
@@ -225,13 +234,47 @@ pub fn display_rgb(c: Rgb, aci7: bool, background: Rgb) -> Rgb {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_hex_rejects_non_hex_digits() {
|
||||
assert_eq!(Rgb::parse_hex("+12345"), None);
|
||||
assert_eq!(Rgb::parse_hex("-12345"), None);
|
||||
assert_eq!(Color::parse("#+12345"), None);
|
||||
assert_eq!(Rgb::parse_hex("#012345"), Some(Rgb(1, 35, 69)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_rejects_plus_sign() {
|
||||
assert_eq!(Color::parse("+5"), None);
|
||||
assert_eq!(Color::parse(" +256"), None);
|
||||
assert_eq!(Color::parse("color +5"), None);
|
||||
assert_eq!(Color::parse("+1,+2,+3"), None);
|
||||
assert_eq!(Color::parse("1,+2,3"), None);
|
||||
assert_eq!(Color::parse("5"), Some(Color::Index(5)));
|
||||
assert_eq!(Color::parse("256"), Some(Color::ByLayer));
|
||||
assert_eq!(Color::parse("color 5"), Some(Color::Index(5)));
|
||||
assert_eq!(Color::parse("1, 2, 3"), Some(Color::True(Rgb(1, 2, 3))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_hex_rejects_repeated_hash() {
|
||||
assert_eq!(Rgb::parse_hex("##ff0000"), None);
|
||||
assert_eq!(Rgb::parse_hex("###ff0000"), None);
|
||||
assert_eq!(Color::parse("##ff0000"), None);
|
||||
assert_eq!(Rgb::parse_hex("#ff0000"), Some(Rgb(255, 0, 0)));
|
||||
assert_eq!(Rgb::parse_hex("ff0000"), Some(Rgb(255, 0, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_known_entries() {
|
||||
assert_eq!(aci_rgb(1), Rgb(255, 0, 0));
|
||||
assert_eq!(aci_rgb(10), Rgb(255, 0, 0));
|
||||
assert_eq!(aci_rgb(11), Rgb(255, 127, 127));
|
||||
assert_eq!(aci_rgb(12), Rgb(165, 0, 0));
|
||||
assert_eq!(aci_rgb(13), Rgb(165, 82, 82));
|
||||
assert_eq!(aci_rgb(12), Rgb(204, 0, 0));
|
||||
assert_eq!(aci_rgb(13), Rgb(204, 102, 102));
|
||||
assert_eq!(aci_rgb(14), Rgb(153, 0, 0));
|
||||
assert_eq!(aci_rgb(15), Rgb(153, 76, 76));
|
||||
assert_eq!(aci_rgb(16), Rgb(127, 0, 0));
|
||||
assert_eq!(aci_rgb(18), Rgb(76, 0, 0));
|
||||
assert_eq!(aci_rgb(20), Rgb(255, 63, 0));
|
||||
assert_eq!(aci_rgb(30), Rgb(255, 127, 0));
|
||||
assert_eq!(aci_rgb(50), Rgb(255, 255, 0));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! AUTOCONSTRAIN: infer constraints from geometry that already nearly satisfies them.
|
||||
//! AUTOCONSTRAIN: infer constraints from geometry that already nearly satisfies them; and
|
||||
//! CONSTRAINTINFER's inference for what a command just placed ([`infer_placed`]).
|
||||
|
||||
use cadcraft_doc::{Constraint, ConstraintKind, Drawing, EntityKind, GeomRef, Handle, Sub};
|
||||
use cadcraft_geom::{Line, Vec2};
|
||||
@@ -101,7 +102,11 @@ fn ang_between(d1: Vec2, d2: Vec2) -> f64 {
|
||||
pub fn infer(d: &Drawing, handles: &[Handle], o: &InferOptions) -> Vec<Constraint> {
|
||||
let tol = if o.distance_tolerance.is_finite() { o.distance_tolerance.clamp(0.0, 1e9) } else { 0.05 };
|
||||
let atol = if o.angle_tolerance.is_finite() { o.angle_tolerance.clamp(0.0, 45.0).to_radians() } else { 1f64.to_radians() };
|
||||
let allow = |k: ConstraintKind| o.types.is_empty() || o.types.iter().any(|t| t.eq_ignore_ascii_case(k.name()));
|
||||
// Resolve the allowed type names into a set once, so membership is O(1) per candidate instead
|
||||
// of re-scanning the whole (attacker-controllable) `o.types` list for every geometric match
|
||||
// (CWE-407). Empty `o.types` means "all types".
|
||||
let allowed: std::collections::HashSet<String> = o.types.iter().map(|t| t.to_ascii_lowercase()).collect();
|
||||
let allow = |k: ConstraintKind| allowed.is_empty() || allowed.contains(&k.name().to_ascii_lowercase());
|
||||
let g = collect(d, handles);
|
||||
let mut out: Vec<Constraint> = Vec::new();
|
||||
let mut push = |kind: ConstraintKind, refs: Vec<GeomRef>| {
|
||||
@@ -191,6 +196,114 @@ pub fn infer(d: &Drawing, handles: &[Handle], o: &InferOptions) -> Vec<Constrain
|
||||
out
|
||||
}
|
||||
|
||||
/// Constraint types CONSTRAINTINFER applies.
|
||||
pub const INFER_TYPES: [ConstraintKind; 6] = [
|
||||
ConstraintKind::Coincident,
|
||||
ConstraintKind::Tangent,
|
||||
ConstraintKind::Perpendicular,
|
||||
ConstraintKind::Parallel,
|
||||
ConstraintKind::Horizontal,
|
||||
ConstraintKind::Vertical,
|
||||
];
|
||||
|
||||
/// CONSTRAINTINFER: the constraints that the exact placement of `placed` (objects a command just
|
||||
/// drew or edited) implies against each other and `others`: end points snapped onto end points,
|
||||
/// midpoints, centres or onto objects (Coincident), tangent and perpendicular snaps, parallel
|
||||
/// lines, and horizontal/vertical lines (ortho, polar). Snapped geometry is exact, so the
|
||||
/// tolerances in `o` are expected to be tight. Only [`INFER_TYPES`] (and `o.types`, when set)
|
||||
/// are returned, each involving a placed object.
|
||||
pub fn infer_placed(d: &Drawing, placed: &[Handle], others: &[Handle], o: &InferOptions) -> Vec<Constraint> {
|
||||
let tol = if o.distance_tolerance.is_finite() { o.distance_tolerance.clamp(0.0, 1e9) } else { 0.0 };
|
||||
let mut all: Vec<Handle> = placed.iter().take(MAX_OBJECTS).copied().collect();
|
||||
for h in others {
|
||||
if all.len() >= MAX_OBJECTS {
|
||||
break;
|
||||
}
|
||||
if !all.contains(h) {
|
||||
all.push(*h);
|
||||
}
|
||||
}
|
||||
let mine = |c: &Constraint| c.refs.iter().any(|r| placed.contains(&r.handle));
|
||||
let mut out: Vec<Constraint> = infer(d, &all, o).into_iter().filter(|c| INFER_TYPES.contains(&c.kind) && mine(c)).collect();
|
||||
// Placed end points on other objects' midpoints, centres, or on the objects themselves.
|
||||
let allow = o.types.is_empty() || o.types.iter().any(|t| t.eq_ignore_ascii_case(ConstraintKind::Coincident.name()));
|
||||
if !allow {
|
||||
return out;
|
||||
}
|
||||
let g = collect(d, &all);
|
||||
// Point to point (midpoint, centre) first; point on an object last, so a tangent or
|
||||
// perpendicular snap keeps its tangency (an end on the curve it touches adds nothing then).
|
||||
let mut extra = Vec::new();
|
||||
let mut on = Vec::new();
|
||||
for (rp, p) in g.points.iter().filter(|(r, _)| placed.contains(&r.handle)) {
|
||||
if out.iter().any(|c| c.kind == ConstraintKind::Coincident && c.refs.contains(rp)) {
|
||||
continue;
|
||||
}
|
||||
let target = g
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|(r, _, _)| r.handle != rp.handle)
|
||||
.find_map(|(r, a, b)| {
|
||||
let ln = Line::new(*a, *b);
|
||||
if a.mid(*b).dist(*p) <= tol && r.sub == Sub::Whole {
|
||||
Some(GeomRef::new(r.handle, Sub::Mid))
|
||||
} else {
|
||||
let t = ln.param_of(*p);
|
||||
(ln.dist(*p) <= tol && (0.0..=1.0).contains(&t) && ln.len() > tol).then_some(*r)
|
||||
}
|
||||
})
|
||||
.or_else(|| {
|
||||
g.curves.iter().filter(|(r, _, _)| r.handle != rp.handle).find_map(|(r, c, rad)| {
|
||||
if c.dist(*p) <= tol {
|
||||
Some(GeomRef::new(r.handle, Sub::Center))
|
||||
} else {
|
||||
((c.dist(*p) - rad).abs() <= tol && on_arc(d, r.handle, *c, *p)).then_some(*r)
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(t) = target
|
||||
&& extra.len() + on.len() + out.len() < MAX_CANDIDATES
|
||||
{
|
||||
let c = Constraint { id: 0, kind: ConstraintKind::Coincident, refs: vec![*rp, t], name: String::new(), expr: String::new() };
|
||||
if t.sub == Sub::Whole { on.push(c) } else { extra.push(c) }
|
||||
}
|
||||
}
|
||||
// Perpendicular lines meeting in a T (a perpendicular snap onto the middle of a line).
|
||||
let atol = if o.angle_tolerance.is_finite() { o.angle_tolerance.clamp(0.0, 45.0).to_radians() } else { 0.0 };
|
||||
let allow_per = o.types.is_empty() || o.types.iter().any(|t| t.eq_ignore_ascii_case(ConstraintKind::Perpendicular.name()));
|
||||
for (r1, a1, b1) in g.lines.iter().filter(|(r, _, _)| placed.contains(&r.handle)) {
|
||||
for (r2, a2, b2) in g.lines.iter().filter(|(r, _, _)| r.handle != r1.handle) {
|
||||
let (l1, l2) = (Line::new(*a1, *b1), Line::new(*a2, *b2));
|
||||
let touches = |l: &Line, p: Vec2| l.dist(p) <= tol && (0.0..=1.0).contains(&l.param_of(p));
|
||||
let tee = [*a1, *b1].iter().any(|p| touches(&l2, *p)) || [*a2, *b2].iter().any(|p| touches(&l1, *p));
|
||||
let ang = ang_between(*b1 - *a1, *b2 - *a2);
|
||||
let dup = out.iter().any(|c| c.kind == ConstraintKind::Perpendicular && c.refs.contains(r1) && c.refs.contains(r2));
|
||||
if allow_per
|
||||
&& tee
|
||||
&& !dup
|
||||
&& (std::f64::consts::FRAC_PI_2 - ang).abs() <= atol
|
||||
&& l1.len() > tol
|
||||
&& l2.len() > tol
|
||||
&& out.len() < MAX_CANDIDATES
|
||||
{
|
||||
out.push(Constraint { id: 0, kind: ConstraintKind::Perpendicular, refs: vec![*r1, *r2], name: String::new(), expr: String::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = out.iter().take_while(|c| c.kind == ConstraintKind::Coincident).count();
|
||||
out.splice(n..n, extra);
|
||||
out.extend(on);
|
||||
out
|
||||
}
|
||||
|
||||
/// Does `p` (on the circle) lie within the arc's sweep (always for a circle)?
|
||||
fn on_arc(d: &Drawing, h: Handle, c: Vec2, p: Vec2) -> bool {
|
||||
match d.entity(h).map(|e| &e.kind) {
|
||||
Some(EntityKind::Arc(a)) => cadcraft_geom::angle_in_sweep((p - c).angle(), a.start, a.end),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Infer and apply constraints over `handles`; returns the ids added. Redundant or conflicting
|
||||
/// candidates are skipped.
|
||||
pub fn autoconstrain(d: &mut Drawing, handles: &[Handle], o: &InferOptions) -> Vec<u32> {
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Curve math for the residuals: ellipse points and derivatives, B-spline end derivatives and
|
||||
//! curve end frames (point, tangent, curvature) for tangent and smooth (G2) joins.
|
||||
//!
|
||||
//! Textbook formulas only: the derivative of a clamped B-spline at its ends follows from the
|
||||
//! derivative control points (Piegl & Tiller, *The NURBS Book*, ch. 3–4), rational curves through
|
||||
//! the quotient rule on homogeneous coordinates.
|
||||
|
||||
use cadcraft_geom::{Spline as GSpline, Vec2};
|
||||
|
||||
/// `v <= lim`, or NaN.
|
||||
pub(crate) fn not_above(v: f64, lim: f64) -> bool {
|
||||
v.is_nan() || v <= lim
|
||||
}
|
||||
|
||||
/// A curve end: point, unit tangent in the curve's own direction, signed curvature (positive
|
||||
/// when the curve turns left).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Frame {
|
||||
pub p: Vec2,
|
||||
pub t: Vec2,
|
||||
pub k: f64,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
/// From a point and the first and second derivatives with respect to any parameter.
|
||||
pub fn from_derivs(p: Vec2, d1: Vec2, d2: Vec2) -> Option<Frame> {
|
||||
let l = d1.len();
|
||||
if !l.is_finite() || not_above(l, 1e-300) {
|
||||
return None;
|
||||
}
|
||||
let k = d1.cross(d2) / (l * l * l);
|
||||
let f = Frame { p, t: d1 * (1.0 / l), k };
|
||||
(f.p.is_finite() && f.t.is_finite() && f.k.is_finite()).then_some(f)
|
||||
}
|
||||
|
||||
/// The same end traversed the other way.
|
||||
pub fn reversed(self) -> Frame {
|
||||
Frame { p: self.p, t: -self.t, k: -self.k }
|
||||
}
|
||||
}
|
||||
|
||||
/// An ellipse or elliptical arc in solver parameters.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Ell {
|
||||
pub c: Vec2,
|
||||
/// Major axis vector (centre to the end of the major axis).
|
||||
pub mj: Vec2,
|
||||
pub ratio: f64,
|
||||
pub t0: f64,
|
||||
pub t1: f64,
|
||||
pub arc: bool,
|
||||
}
|
||||
|
||||
impl Ell {
|
||||
pub fn minor(&self) -> Vec2 {
|
||||
self.mj.perp() * self.ratio
|
||||
}
|
||||
pub fn at(&self, t: f64) -> Vec2 {
|
||||
self.c + self.mj * t.cos() + self.minor() * t.sin()
|
||||
}
|
||||
pub fn d1(&self, t: f64) -> Vec2 {
|
||||
self.mj * -t.sin() + self.minor() * t.cos()
|
||||
}
|
||||
pub fn d2(&self, t: f64) -> Vec2 {
|
||||
self.mj * -t.cos() - self.minor() * t.sin()
|
||||
}
|
||||
pub fn frame(&self, t: f64) -> Option<Frame> {
|
||||
Frame::from_derivs(self.at(t), self.d1(t), self.d2(t))
|
||||
}
|
||||
/// Semi-axes `(a, b)`.
|
||||
fn axes(&self) -> (f64, f64) {
|
||||
let a = self.mj.len();
|
||||
(a, a * self.ratio.abs())
|
||||
}
|
||||
/// Local coordinates of `p` along the major and minor axes.
|
||||
fn local(&self, p: Vec2) -> Option<(f64, f64, Vec2, Vec2)> {
|
||||
let (a, _) = self.axes();
|
||||
if not_above(a, 1e-300) {
|
||||
return None;
|
||||
}
|
||||
let u_dir = self.mj * (1.0 / a);
|
||||
let v_dir = u_dir.perp();
|
||||
let q = p - self.c;
|
||||
Some((q.dot(u_dir), q.dot(v_dir), u_dir, v_dir))
|
||||
}
|
||||
/// A distance-like residual of `p` from the ellipse: zero exactly on it, about the distance
|
||||
/// near it.
|
||||
pub fn on(&self, p: Vec2) -> f64 {
|
||||
let (a, b) = self.axes();
|
||||
match self.local(p) {
|
||||
Some((u, v, _, _)) if b > 1e-300 => {
|
||||
let s = a / b;
|
||||
(u * u + v * v * s * s).sqrt() - a
|
||||
}
|
||||
_ => p.dist(self.c) - a,
|
||||
}
|
||||
}
|
||||
/// Unit outward normal of the ellipse's implicit form at (or near) `p`.
|
||||
pub fn normal(&self, p: Vec2) -> Vec2 {
|
||||
let (a, b) = self.axes();
|
||||
match self.local(p) {
|
||||
Some((u, v, ud, vd)) if b > 1e-300 => (ud * (u / (a * a)) + vd * (v / (b * b))).normalized(),
|
||||
_ => (p - self.c).normalized(),
|
||||
}
|
||||
}
|
||||
/// Largest `n·(P − c)` over the ellipse for a unit direction `n` (its support distance).
|
||||
pub fn support(&self, n: Vec2) -> f64 {
|
||||
let (x, y) = (n.dot(self.mj), n.dot(self.minor()));
|
||||
(x * x + y * y).sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
/// A circle (or the circle of an arc) as a parametric curve.
|
||||
pub(crate) fn circle_at(c: Vec2, r: f64, t: f64) -> (Vec2, Vec2) {
|
||||
let (s, co) = t.sin_cos();
|
||||
(c + Vec2::new(co, s) * r, Vec2::new(-s, co) * r)
|
||||
}
|
||||
|
||||
/// Homogeneous control point.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct H {
|
||||
x: f64,
|
||||
y: f64,
|
||||
w: f64,
|
||||
}
|
||||
|
||||
impl H {
|
||||
fn sub(self, o: H) -> H {
|
||||
H { x: self.x - o.x, y: self.y - o.y, w: self.w - o.w }
|
||||
}
|
||||
fn scale(self, f: f64) -> H {
|
||||
H { x: self.x * f, y: self.y * f, w: self.w * f }
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the knot vector clamped (end knot repeated `degree + 1` times) at the start or end?
|
||||
pub(crate) fn clamped(s: &GSpline, at_end: bool) -> bool {
|
||||
let p = s.degree;
|
||||
let k = &s.knots;
|
||||
if !s.is_valid() || k.len() < 2 * (p + 1) {
|
||||
return false;
|
||||
}
|
||||
let scale = k.iter().fold(1.0f64, |m, v| m.max(v.abs()));
|
||||
let tol = 1e-12 * scale;
|
||||
let window = if at_end { k.get(k.len() - p - 1..) } else { k.get(..=p) };
|
||||
match window {
|
||||
Some(w) => w.iter().all(|v| w.first().is_some_and(|f| (v - f).abs() <= tol)),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// End frame of a clamped spline at its start (`at_end` false) or end, in the curve's own
|
||||
/// direction. `None` for an unclamped end or degenerate data.
|
||||
pub(crate) fn spline_end(s: &GSpline, at_end: bool) -> Option<Frame> {
|
||||
if !clamped(s, at_end) {
|
||||
return None;
|
||||
}
|
||||
let p = s.degree;
|
||||
let n = s.control.len();
|
||||
let wt = |i: usize| if s.weights.is_empty() { Some(1.0) } else { s.weights.get(i).copied() };
|
||||
let hp = |i: usize| -> Option<H> {
|
||||
let c = s.control.get(i)?;
|
||||
let w = wt(i)?;
|
||||
Some(H { x: c.x * w, y: c.y * w, w })
|
||||
};
|
||||
// Work on the start of the curve; for the end, reverse the control points and knots.
|
||||
let (q, u): (Vec<H>, Vec<f64>) = if at_end {
|
||||
let q = (0..n.min(3)).map(|i| hp(n - 1 - i)).collect::<Option<Vec<_>>>()?;
|
||||
let last = s.knots.len() - 1;
|
||||
let u = (0..s.knots.len().min(p + 3)).map(|i| s.knots.get(last - i).map(|v| -v)).collect::<Option<Vec<_>>>()?;
|
||||
(q, u)
|
||||
} else {
|
||||
let q = (0..n.min(3)).map(hp).collect::<Option<Vec<_>>>()?;
|
||||
let u = s.knots.get(..(p + 3).min(s.knots.len()))?.to_vec();
|
||||
(q, u)
|
||||
};
|
||||
let pf = p as f64;
|
||||
let (q0, q1) = (*q.first()?, *q.get(1)?);
|
||||
let den1 = u.get(p + 1)? - u.get(1)?;
|
||||
if not_above(den1.abs(), 1e-300) {
|
||||
return None;
|
||||
}
|
||||
let a1 = q1.sub(q0).scale(pf / den1);
|
||||
let a2 = if p >= 2 {
|
||||
let q2 = *q.get(2)?;
|
||||
let den2 = u.get(p + 2)? - u.get(2)?;
|
||||
let den0 = u.get(p + 1)? - u.get(2)?;
|
||||
if !(den2.abs() > 1e-300 && den0.abs() > 1e-300) {
|
||||
return None;
|
||||
}
|
||||
q2.sub(q1).scale(1.0 / den2).sub(q1.sub(q0).scale(1.0 / den1)).scale(pf * (pf - 1.0) / den0)
|
||||
} else {
|
||||
H { x: 0.0, y: 0.0, w: 0.0 }
|
||||
};
|
||||
// Quotient rule: C = A / w.
|
||||
if not_above(q0.w.abs(), 1e-300) {
|
||||
return None;
|
||||
}
|
||||
let c = Vec2::new(q0.x / q0.w, q0.y / q0.w);
|
||||
let c1 = (Vec2::new(a1.x, a1.y) - c * a1.w) / q0.w;
|
||||
let c2 = (Vec2::new(a2.x, a2.y) - c1 * (2.0 * a1.w) - c * a2.w) / q0.w;
|
||||
let f = Frame::from_derivs(c, c1, c2)?;
|
||||
// The reversed curve's start is the end traversed backwards.
|
||||
Some(if at_end { f.reversed() } else { f })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ellipse_residuals() {
|
||||
let e = Ell { c: Vec2::new(1.0, 2.0), mj: Vec2::new(4.0, 0.0), ratio: 0.5, t0: 0.0, t1: 1.0, arc: false };
|
||||
assert!(e.on(Vec2::new(5.0, 2.0)).abs() < 1e-12);
|
||||
assert!(e.on(Vec2::new(1.0, 4.0)).abs() < 1e-12);
|
||||
assert!(e.on(Vec2::new(6.0, 2.0)) > 0.0);
|
||||
assert!((e.support(Vec2::new(0.0, 1.0)) - 2.0).abs() < 1e-12);
|
||||
assert!((e.support(Vec2::new(1.0, 0.0)) - 4.0).abs() < 1e-12);
|
||||
assert!(e.normal(Vec2::new(1.0, 4.0)).near(Vec2::new(0.0, 1.0), 1e-12));
|
||||
// Curvature at the end of the major axis: a / b².
|
||||
let f = e.frame(0.0).unwrap();
|
||||
assert!((f.k - 4.0 / 4.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_end_derivatives_match_sampling() {
|
||||
let s = GSpline::from_control(vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0), Vec2::new(3.0, 3.0), Vec2::new(6.0, 1.0)], 3);
|
||||
for at_end in [false, true] {
|
||||
let f = spline_end(&s, at_end).unwrap();
|
||||
let (lo, hi) = s.domain();
|
||||
let (t, h) = if at_end { (hi, -1e-4) } else { (lo, 1e-4) };
|
||||
let (p0, p1, p2) = (s.eval(t), s.eval(t + h), s.eval(t + 2.0 * h));
|
||||
assert!(f.p.near(p0, 1e-12));
|
||||
// One-sided differences (a negative step at the end still gives d/dt).
|
||||
let d1 = (p1 - p0) * (1.0 / h);
|
||||
let d2 = (p2 - p1 * 2.0 + p0) * (1.0 / (h * h));
|
||||
let g = Frame::from_derivs(p0, d1, d2).unwrap();
|
||||
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
|
||||
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
|
||||
}
|
||||
// An unclamped (periodic) spline has no ends.
|
||||
let closed = GSpline::from_fit_points_closed(&[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(2.0, 3.0)]);
|
||||
assert!(spline_end(&closed, false).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Degrees of freedom: how much the constraints leave the geometry free to move.
|
||||
//!
|
||||
//! Per connected component, the remaining DOF is the number of free parameters minus the rank
|
||||
//! of the constraint Jacobian at the current geometry; equations beyond the rank are redundant
|
||||
//! (over-constraint). Per object, the DOF is the dimension of the null-space motion restricted
|
||||
//! to the object's own parameters: how many independent ways the object can still move while
|
||||
//! every constraint keeps holding (the rest of its component moving along as needed).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use cadcraft_doc::{Constraint, Drawing, Handle};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::model::Model;
|
||||
use crate::{Comp, MAX_CONSTRAINTS, SolveError, SolveOptions, build_budgeted, lm};
|
||||
|
||||
/// Most free parameters for which per-object freedom is analysed (null-space basis size).
|
||||
const MAX_NULL_COLS: usize = 600;
|
||||
/// Largest Jacobian (rows × columns × min) whose rank is computed.
|
||||
const MAX_RANK_WORK: f64 = 4e8;
|
||||
/// Largest residual-evaluation work (rows × free × per-residual cost, including spline
|
||||
/// reconstruction) allowed before building the Jacobian during numerical differentiation.
|
||||
const MAX_EVAL_WORK: f64 = 2e9;
|
||||
/// Most objects listed in one report.
|
||||
const MAX_OBJECTS: usize = 10_000;
|
||||
|
||||
/// Constraint state of an object or a selection.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DofStatus {
|
||||
/// No constraints.
|
||||
Unconstrained,
|
||||
/// Some freedom left.
|
||||
Under,
|
||||
/// No freedom left, no redundant constraints.
|
||||
Fully,
|
||||
/// Redundant constraints.
|
||||
Over,
|
||||
/// Too large to analyse.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl DofStatus {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
DofStatus::Unconstrained => "Not constrained",
|
||||
DofStatus::Under => "Under-constrained",
|
||||
DofStatus::Fully => "Fully constrained",
|
||||
DofStatus::Over => "Over-constrained",
|
||||
DofStatus::Unknown => "Unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Degrees of freedom of one object.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ObjectDof {
|
||||
pub handle: String,
|
||||
#[serde(rename = "type")]
|
||||
pub kind: &'static str,
|
||||
/// Parameters of the object: its degrees of freedom without constraints.
|
||||
pub params: usize,
|
||||
/// Remaining degrees of freedom (`None` when the system is too large to analyse).
|
||||
pub dof: Option<usize>,
|
||||
pub status: DofStatus,
|
||||
}
|
||||
|
||||
/// Degrees of freedom of the drawing's constrained geometry, or of a selection.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DofReport {
|
||||
/// Remaining degrees of freedom: the constraint components touching the analysed objects,
|
||||
/// plus unconstrained objects' own parameters (`None` when too large to analyse).
|
||||
pub dof: Option<usize>,
|
||||
pub status: DofStatus,
|
||||
/// Equations that duplicate others.
|
||||
pub redundant: usize,
|
||||
/// Constraints taking part.
|
||||
pub constraints: usize,
|
||||
pub objects: Vec<ObjectDof>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
struct CompDof {
|
||||
dof: Option<usize>,
|
||||
redundant: usize,
|
||||
/// Per slot (model order).
|
||||
objects: Vec<Option<usize>>,
|
||||
}
|
||||
|
||||
/// Compute component and object freedom only when rank and residual-evaluation work fit their budgets.
|
||||
/// Return unknown freedom before building the Jacobian when either work limit is exceeded.
|
||||
fn analyse(comp: &Comp) -> CompDof {
|
||||
let free = comp.free(None);
|
||||
let rows = comp.rows(None);
|
||||
let nf = free.len();
|
||||
let unknown = CompDof { dof: None, redundant: 0, objects: vec![None; comp.model.slots.len()] };
|
||||
if rows > lm::MAX_ROWS || (rows as f64) * (nf as f64) * (rows.min(nf) as f64) > MAX_RANK_WORK {
|
||||
return unknown;
|
||||
}
|
||||
// Numerical differentiation evaluates every residual about `rows × free` times, and each
|
||||
// spline-end residual reconstructs its spline through a dense solve. Account for that
|
||||
// reconstruction cost before building the Jacobian so a component with few equations but large
|
||||
// splines cannot pass the rank-work check yet still require billions of operations (row 43).
|
||||
let eval_work = (rows as f64) * (nf as f64) * (1.0 + comp.built.iter().map(|b| b.spline_reconstruct_cost(&comp.model)).sum::<f64>());
|
||||
if eval_work > MAX_EVAL_WORK {
|
||||
return unknown;
|
||||
}
|
||||
let f = |x: &[f64], out: &mut Vec<f64>| comp.eval(x, out, None);
|
||||
let jac = lm::jacobian(&f, &comp.model.x0, &free, rows);
|
||||
if nf > MAX_NULL_COLS {
|
||||
let rank = lm::rank_qr(&jac, rows, nf);
|
||||
return CompDof { dof: Some(nf - rank.min(nf)), redundant: rows.saturating_sub(rank), objects: vec![None; comp.model.slots.len()] };
|
||||
}
|
||||
let (rank, basis) = lm::null_space(&jac, rows, nf);
|
||||
let objects = comp
|
||||
.model
|
||||
.slots
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let cols: Vec<usize> = free.iter().enumerate().filter(|(_, j)| (s.off..s.off + s.len).contains(*j)).map(|(k, _)| k).collect();
|
||||
if cols.is_empty() || basis.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
// Null vectors restricted to the object's columns; their rank is its freedom.
|
||||
let restricted: Vec<Vec<f64>> = basis.iter().map(|v| cols.iter().map(|&k| v.get(k).copied().unwrap_or(0.0)).collect()).collect();
|
||||
Some(lm::qr(restricted, 0.0, 1e-6).0)
|
||||
})
|
||||
.collect();
|
||||
CompDof { dof: Some(nf - rank.min(nf)), redundant: rows.saturating_sub(rank), objects }
|
||||
}
|
||||
|
||||
fn plural(n: usize, one: &str, many: &str) -> String {
|
||||
format!("{n} {}", if n == 1 { one } else { many })
|
||||
}
|
||||
|
||||
/// Degrees of freedom of the constrained geometry (`handles` empty), or of the given objects
|
||||
/// (constrained or not) and the constraint components they belong to.
|
||||
pub fn dof(d: &Drawing, handles: &[Handle]) -> Result<DofReport, SolveError> {
|
||||
let cons: Vec<&Constraint> = d.constraints.iter().take(MAX_CONSTRAINTS).collect();
|
||||
let mut members_left = crate::model::MAX_RIGID_WORK;
|
||||
let (comps, _) = build_budgeted(d, &cons, &SolveOptions::default(), &mut members_left)?;
|
||||
let want = |h: Handle| handles.is_empty() || handles.contains(&h);
|
||||
let mut objects = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut total = Some(0usize);
|
||||
let mut redundant = 0;
|
||||
let mut constraints = 0;
|
||||
let mut any_constrained = false;
|
||||
for comp in &comps {
|
||||
if !comp.model.slots.iter().any(|s| want(s.handle)) {
|
||||
continue;
|
||||
}
|
||||
any_constrained = true;
|
||||
let a = analyse(comp);
|
||||
constraints += comp.built.len();
|
||||
redundant += a.redundant;
|
||||
total = match (total, a.dof) {
|
||||
(Some(t), Some(v)) => Some(t.saturating_add(v)),
|
||||
_ => None,
|
||||
};
|
||||
for (s, od) in comp.model.slots.iter().zip(&a.objects) {
|
||||
if !want(s.handle) || !seen.insert(s.handle) || objects.len() >= MAX_OBJECTS {
|
||||
continue;
|
||||
}
|
||||
let status = match od {
|
||||
_ if a.redundant > 0 => DofStatus::Over,
|
||||
Some(0) => DofStatus::Fully,
|
||||
Some(_) => DofStatus::Under,
|
||||
None => DofStatus::Unknown,
|
||||
};
|
||||
let kind = d.entity(s.handle).map_or("", |e| e.kind.type_name());
|
||||
objects.push(ObjectDof { handle: s.handle.hex(), kind, params: s.len, dof: *od, status });
|
||||
}
|
||||
}
|
||||
let mut free_objects = false;
|
||||
for &h in handles.iter().take(MAX_OBJECTS) {
|
||||
if seen.contains(&h) {
|
||||
continue;
|
||||
}
|
||||
let m = Model::build_budgeted(d, &[h], &mut members_left);
|
||||
let Some(s) = m.slots.first() else { continue };
|
||||
seen.insert(h);
|
||||
free_objects = true;
|
||||
total = total.map(|t| t.saturating_add(s.len));
|
||||
let kind = d.entity(h).map_or("", |e| e.kind.type_name());
|
||||
objects.push(ObjectDof { handle: h.hex(), kind, params: s.len, dof: Some(s.len), status: DofStatus::Unconstrained });
|
||||
}
|
||||
let status = if redundant > 0 {
|
||||
DofStatus::Over
|
||||
} else if !any_constrained {
|
||||
DofStatus::Unconstrained
|
||||
} else {
|
||||
match total {
|
||||
Some(0) => DofStatus::Fully,
|
||||
Some(_) => DofStatus::Under,
|
||||
None => DofStatus::Unknown,
|
||||
}
|
||||
};
|
||||
let message = match (status, total) {
|
||||
(DofStatus::Unconstrained, _) if !free_objects => "No constraints".to_string(),
|
||||
(DofStatus::Over, _) => format!("Over-constrained: {}", plural(redundant, "redundant equation", "redundant equations")),
|
||||
(DofStatus::Fully, _) => "Fully constrained".to_string(),
|
||||
(_, Some(n)) => format!("{} remaining", plural(n, "degree of freedom", "degrees of freedom")),
|
||||
(_, None) => "Too large to analyse".to_string(),
|
||||
};
|
||||
Ok(DofReport { dof: total, status, redundant, constraints, objects, message })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
use crate::residual::{Built, Form};
|
||||
use cadcraft_doc::{Common, ConstraintKind, EntityKind, GeomRef, Space};
|
||||
use cadcraft_geom::{Spline, Vec2};
|
||||
|
||||
/// An expensive fit-spline endpoint residual produces unknown freedom before numerical differentiation.
|
||||
#[test]
|
||||
fn endpoint_analysis_rejects_cubic_fit_work_before_differentiation() {
|
||||
let mut d = Drawing::default();
|
||||
let pts: Vec<_> = (0..500).map(|i| Vec2::new(i as f64, (i % 3) as f64)).collect();
|
||||
let mut spline = Spline::from_control(pts.clone(), 3);
|
||||
spline.fit = pts;
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Spline(spline)).unwrap();
|
||||
let model = Model::build(&d, &[h]);
|
||||
let endpoint = Built {
|
||||
id: 1,
|
||||
kind: ConstraintKind::Tangent,
|
||||
refs: vec![GeomRef::whole(h)],
|
||||
form: Form::EndOn { spline: 0, at_end: false },
|
||||
target: 0.0,
|
||||
sign: 1.0,
|
||||
rows: 2,
|
||||
aux_init: Vec::new(),
|
||||
aux: 0,
|
||||
};
|
||||
let comp = Comp { model, built: vec![endpoint], weights: vec![1.0; 2], held: Vec::new(), tol: 1e-9 };
|
||||
assert!(analyse(&comp).dof.is_none());
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
/// Longest expression accepted (characters).
|
||||
pub const MAX_LEN: usize = 1024;
|
||||
/// Deepest nesting (parentheses, unary minus) and parameter reference chain.
|
||||
/// Deepest syntax tree and combined expression/parameter evaluation path.
|
||||
pub const MAX_DEPTH: usize = 64;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
@@ -49,7 +49,7 @@ struct Parser<'a> {
|
||||
|
||||
impl Parser<'_> {
|
||||
fn ws(&mut self) {
|
||||
while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
while self.s.get(self.i).is_some_and(u8::is_ascii_whitespace) {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,20 @@ pub fn parse(text: &str) -> Result<Expr, ExprError> {
|
||||
if p.peek().is_some() {
|
||||
return Err(ExprError::Syntax(format!("unexpected `{}`", text.get(p.i..).unwrap_or("").trim())));
|
||||
}
|
||||
let mut pending = vec![(&e, 1)];
|
||||
while let Some((node, depth)) = pending.pop() {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(ExprError::TooDeep);
|
||||
}
|
||||
match node {
|
||||
Expr::Neg(a) => pending.push((a, depth + 1)),
|
||||
Expr::Bin(_, a, b) => {
|
||||
pending.push((a, depth + 1));
|
||||
pending.push((b, depth + 1));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
|
||||
@@ -185,14 +199,58 @@ pub fn names(e: &Expr, out: &mut Vec<String>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` with every whole-name use of `old` replaced by `new`; numbers (`1e3`), other names
|
||||
/// (`d10` for `d1`) and spacing are left as written.
|
||||
pub fn rename(text: &str, old: &str, new: &str) -> String {
|
||||
let b = text.as_bytes();
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut i = 0;
|
||||
while let Some(&c) = b.get(i) {
|
||||
let start = i;
|
||||
if c.is_ascii_digit() || c == b'.' {
|
||||
while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'.') {
|
||||
i += 1;
|
||||
}
|
||||
if b.get(i).is_some_and(|c| *c == b'e' || *c == b'E') {
|
||||
let mut j = i + 1;
|
||||
if b.get(j).is_some_and(|c| *c == b'+' || *c == b'-') {
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j).is_some_and(u8::is_ascii_digit) {
|
||||
i = j;
|
||||
while b.get(i).is_some_and(u8::is_ascii_digit) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if c.is_ascii_alphabetic() || c == b'_' {
|
||||
while b.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_') {
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
i += text.get(i..).and_then(|r| r.chars().next()).map_or(1, char::len_utf8);
|
||||
}
|
||||
let token = text.get(start..i).unwrap_or_default();
|
||||
out.push_str(if token == old { new } else { token });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Evaluate with a variable lookup.
|
||||
pub fn eval_with(e: &Expr, lookup: &mut dyn FnMut(&str) -> Result<f64, ExprError>) -> Result<f64, ExprError> {
|
||||
eval_at_depth(e, &mut |n, _| lookup(n), 0)
|
||||
}
|
||||
|
||||
fn eval_at_depth(e: &Expr, lookup: &mut dyn FnMut(&str, usize) -> Result<f64, ExprError>, depth: usize) -> Result<f64, ExprError> {
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err(ExprError::TooDeep);
|
||||
}
|
||||
let v = match e {
|
||||
Expr::Num(v) => *v,
|
||||
Expr::Var(n) => lookup(n)?,
|
||||
Expr::Neg(a) => -eval_with(a, lookup)?,
|
||||
Expr::Var(n) => lookup(n, depth + 1)?,
|
||||
Expr::Neg(a) => -eval_at_depth(a, lookup, depth + 1)?,
|
||||
Expr::Bin(op, a, b) => {
|
||||
let (x, y) = (eval_with(a, lookup)?, eval_with(b, lookup)?);
|
||||
let (x, y) = (eval_at_depth(a, lookup, depth + 1)?, eval_at_depth(b, lookup, depth + 1)?);
|
||||
match op {
|
||||
'+' => x + y,
|
||||
'-' => x - y,
|
||||
@@ -236,9 +294,12 @@ impl Env {
|
||||
/// Value of a named parameter.
|
||||
pub fn value(&mut self, name: &str) -> Result<f64, ExprError> {
|
||||
let mut stack = Vec::new();
|
||||
self.value_inner(name, &mut stack)
|
||||
self.value_inner(name, &mut stack, 0)
|
||||
}
|
||||
fn value_inner(&mut self, name: &str, stack: &mut Vec<String>) -> Result<f64, ExprError> {
|
||||
fn value_inner(&mut self, name: &str, stack: &mut Vec<String>, depth: usize) -> Result<f64, ExprError> {
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err(ExprError::TooDeep);
|
||||
}
|
||||
if let Some(v) = self.cache.get(name) {
|
||||
return Ok(*v);
|
||||
}
|
||||
@@ -251,7 +312,7 @@ impl Env {
|
||||
let text = self.exprs.get(name).cloned().ok_or_else(|| ExprError::Unknown(name.to_string()))?;
|
||||
let e = parse(&text)?;
|
||||
stack.push(name.to_string());
|
||||
let r = eval_with(&e, &mut |n| self.value_inner(n, stack));
|
||||
let r = eval_at_depth(&e, &mut |n, depth| self.value_inner(n, stack, depth), depth);
|
||||
stack.pop();
|
||||
let v = r?;
|
||||
self.cache.insert(name.to_string(), v);
|
||||
@@ -261,7 +322,7 @@ impl Env {
|
||||
pub fn eval(&mut self, text: &str) -> Result<f64, ExprError> {
|
||||
let e = parse(text)?;
|
||||
let mut stack = Vec::new();
|
||||
eval_with(&e, &mut |n| self.value_inner(n, &mut stack))
|
||||
eval_at_depth(&e, &mut |n, depth| self.value_inner(n, &mut stack, depth), 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,6 +375,38 @@ mod tests {
|
||||
assert!(chain.value("p0").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expression_and_parameter_depth_share_a_limit_on_a_small_stack() {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(1024 * 1024)
|
||||
.spawn(|| {
|
||||
for op in ["+", "-", "*", "/"] {
|
||||
let within = vec!["1"; MAX_DEPTH].join(op);
|
||||
assert!(eval_const(&within).is_ok());
|
||||
assert_eq!(parse(&format!("{within}{op}1")), Err(ExprError::TooDeep));
|
||||
}
|
||||
let mut env = Env::new();
|
||||
for i in 0..MAX_DEPTH {
|
||||
env.insert(&format!("p{i}"), &format!("p{}+{}", i + 1, vec!["0"; 30].join("+")));
|
||||
}
|
||||
env.insert(&format!("p{MAX_DEPTH}"), "1");
|
||||
assert_eq!(env.value("p0"), Err(ExprError::TooDeep));
|
||||
assert_eq!(env.eval("p0+1"), Err(ExprError::TooDeep));
|
||||
env.insert("safe", "2*3");
|
||||
assert_eq!(env.eval("safe+1"), Ok(7.0));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_replaces_whole_names_only() {
|
||||
assert_eq!(rename("d1+d10*d1 / (d1_x+2e1)", "d1", "w"), "w+d10*w / (d1_x+2e1)");
|
||||
assert_eq!(rename("1e2+e", "e", "x"), "1e2+x");
|
||||
assert_eq!(rename("é+a", "a", "b"), "é+b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_valid() {
|
||||
assert!(valid_name("d1") && valid_name("_w") && !valid_name("1d") && !valid_name("a-b") && !valid_name("") && !valid_name("pi"));
|
||||
|
||||
+396
-51
@@ -1,6 +1,7 @@
|
||||
//! CADCraft parametric solver.
|
||||
//!
|
||||
//! Maps constrained lines, arcs, circles, points and polyline vertices to a parameter vector
|
||||
//! Maps constrained lines, arcs, circles, points, polyline vertices, ellipses, splines and block
|
||||
//! references to a parameter vector
|
||||
//! ([`model`]), turns each [`Constraint`] into residual equations ([`residual`]), and drives the
|
||||
//! residuals to zero with a weighted minimum-norm damped Gauss–Newton solver ([`lm`]), so
|
||||
//! geometry moves as little as possible and geometry the caller wants kept (just edited, or picked
|
||||
@@ -9,7 +10,11 @@
|
||||
//! Inconsistent systems are not "solved" by moving things wildly: the solve fails, nothing is
|
||||
//! written back, and the error names the conflicting constraints (each one whose removal makes
|
||||
//! the rest solvable). New constraints that add no independent equation are reported as
|
||||
//! redundant (over-constraining), as AutoCAD does.
|
||||
//! redundant (over-constraining), as AutoCAD does, naming the constraints they duplicate.
|
||||
//!
|
||||
//! [`dof()`] reports the remaining degrees of freedom: the rank of the constraint Jacobian per
|
||||
//! connected component (Householder QR with column pivoting), and per object the dimension of
|
||||
//! the null-space motion its own parameters still have.
|
||||
//!
|
||||
//! Own implementation (clean-room): the KittyCAD `ezpz` crate (MIT) was evaluated; it pulls in
|
||||
//! the `faer` linear-algebra stack and models KCL's geometry, so a small solver tailored to the
|
||||
@@ -18,6 +23,8 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod auto;
|
||||
mod curves;
|
||||
mod dof;
|
||||
pub mod expr;
|
||||
mod lm;
|
||||
mod model;
|
||||
@@ -29,9 +36,10 @@ use cadcraft_doc::{Constraint, ConstraintKind, Drawing, GeomRef, Handle};
|
||||
use cadcraft_geom::Vec2;
|
||||
use serde::Serialize;
|
||||
|
||||
pub use auto::{InferOptions, autoconstrain, infer};
|
||||
pub use auto::{INFER_TYPES, InferOptions, autoconstrain, infer, infer_placed};
|
||||
pub use dof::{DofReport, DofStatus, ObjectDof, dof};
|
||||
pub use expr::{Env, ExprError};
|
||||
pub use model::supported;
|
||||
pub use model::{ref_points, rigid_points, supported};
|
||||
|
||||
use model::Model;
|
||||
use residual::{Built, Form};
|
||||
@@ -73,6 +81,12 @@ pub struct SolveOptions {
|
||||
pub keep: Vec<Handle>,
|
||||
/// Entities that should take up the change.
|
||||
pub prefer_move: Vec<Handle>,
|
||||
/// Points held where they are for this solve, as a Fix would hold them (the grip an edit
|
||||
/// just put down): see [`edited_points`].
|
||||
pub hold: Vec<GeomRef>,
|
||||
/// Where a Fix on a derived point (by constraint id) holds it, instead of where the point is
|
||||
/// now: see [`moved_anchors`].
|
||||
pub anchors: Vec<(u32, Vec2)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
@@ -168,17 +182,48 @@ pub fn next_id(d: &Drawing) -> u32 {
|
||||
|
||||
// ---------------- systems ----------------
|
||||
|
||||
/// Interpret a constraint against the model's current parameters, appending its auxiliary
|
||||
/// unknowns (contact parameters) to the model, settled with the geometry held still.
|
||||
pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result<Built, String> {
|
||||
let x = model.x0.clone();
|
||||
let mut b = Built::new(c, model, &x, target)?;
|
||||
if b.aux_init.is_empty() {
|
||||
return Ok(b);
|
||||
}
|
||||
if model.x0.len() + b.aux_init.len() > model::MAX_PARAMS + 1000 {
|
||||
return Err("constraint system too large".into());
|
||||
}
|
||||
b.aux = model.x0.len();
|
||||
model.x0.extend(b.aux_init.iter().copied());
|
||||
let free: Vec<usize> = (b.aux..model.x0.len()).collect();
|
||||
let weights = vec![1.0; model.x0.len()];
|
||||
let o = {
|
||||
let m: &Model = model;
|
||||
let f = |x: &[f64], out: &mut Vec<f64>| b.eval(m, x, out);
|
||||
lm::solve(&f, &m.x0, &free, &weights, 1e-14, 60)
|
||||
};
|
||||
model.x0 = o.x;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// One connected component of the constraint graph.
|
||||
struct Comp {
|
||||
model: Model,
|
||||
built: Vec<Built>,
|
||||
pub(crate) struct Comp {
|
||||
pub(crate) model: Model,
|
||||
pub(crate) built: Vec<Built>,
|
||||
weights: Vec<f64>,
|
||||
/// Parameters of the points held by [`SolveOptions::hold`].
|
||||
held: Vec<usize>,
|
||||
tol: f64,
|
||||
}
|
||||
|
||||
impl Comp {
|
||||
fn locks(&self, skip: Option<usize>) -> Vec<bool> {
|
||||
let mut locked = vec![false; self.model.x0.len()];
|
||||
for &j in &self.held {
|
||||
if let Some(l) = locked.get_mut(j) {
|
||||
*l = true;
|
||||
}
|
||||
}
|
||||
for (i, b) in self.built.iter().enumerate() {
|
||||
if Some(i) == skip || b.form != Form::Lock {
|
||||
continue;
|
||||
@@ -193,17 +238,17 @@ impl Comp {
|
||||
}
|
||||
locked
|
||||
}
|
||||
fn free(&self, skip: Option<usize>) -> Vec<usize> {
|
||||
pub(crate) fn free(&self, skip: Option<usize>) -> Vec<usize> {
|
||||
self.locks(skip).iter().enumerate().filter(|(_, l)| !**l).map(|(i, _)| i).collect()
|
||||
}
|
||||
fn eval(&self, x: &[f64], out: &mut Vec<f64>, skip: Option<usize>) {
|
||||
pub(crate) fn eval(&self, x: &[f64], out: &mut Vec<f64>, skip: Option<usize>) {
|
||||
for (i, b) in self.built.iter().enumerate() {
|
||||
if Some(i) != skip {
|
||||
b.eval(&self.model, x, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn rows(&self, skip: Option<usize>) -> usize {
|
||||
pub(crate) fn rows(&self, skip: Option<usize>) -> usize {
|
||||
self.built.iter().enumerate().filter(|(i, _)| Some(*i) != skip).map(|(_, b)| b.rows).sum()
|
||||
}
|
||||
fn run(&self, skip: Option<usize>) -> Result<lm::Outcome, SolveError> {
|
||||
@@ -213,7 +258,30 @@ impl Comp {
|
||||
return Err(SolveError::TooLarge);
|
||||
}
|
||||
let f = |x: &[f64], out: &mut Vec<f64>| self.eval(x, out, skip);
|
||||
Ok(lm::solve(&f, &self.model.x0, &free, &self.weights, self.tol, MAX_ITER))
|
||||
let mut o = lm::solve(&f, &self.model.x0, &free, &self.weights, self.tol, MAX_ITER);
|
||||
// A solution the ellipses would be stored differently from (axes swapped, minor axis
|
||||
// mirrored) holds only if the constraints still hold on the stored form: a constraint on
|
||||
// an axis end by index does not.
|
||||
if o.converged && !self.model.storable(&o.x) {
|
||||
let mut out = Vec::new();
|
||||
match self.model.stored_form(&o.x) {
|
||||
Some(mut xc) => {
|
||||
// Contact parameters are positions along the curves: they follow the stored form.
|
||||
for b in self.built.iter().filter(|b| b.form == Form::Contact) {
|
||||
for (k, r) in b.refs.iter().enumerate() {
|
||||
if let (Some(&t), Some(slot)) = (o.x.get(b.aux + k), xc.get_mut(b.aux + k)) {
|
||||
*slot = self.model.stored_t(&o.x, r.handle, t);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.eval(&xc, &mut out, skip);
|
||||
o.converged = lm::max_abs(&out) <= self.tol;
|
||||
o.x = xc;
|
||||
}
|
||||
None => o.converged = false,
|
||||
}
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
/// Constraint ids in conflict (each one whose removal makes the rest solvable).
|
||||
fn conflicts(&self, x_failed: &[f64]) -> Vec<u32> {
|
||||
@@ -290,51 +358,98 @@ fn components<'a>(cons: &[&'a Constraint]) -> Vec<Vec<&'a Constraint>> {
|
||||
groups.into_values().collect()
|
||||
}
|
||||
|
||||
/// The solver weight of each unknown of `model`: kept handles weigh more, preferred-to-move ones
|
||||
/// less, angles and ratios by size², and contact parameters move freely.
|
||||
fn solver_weights(model: &Model, opts: &SolveOptions) -> Vec<f64> {
|
||||
let mut weights = vec![1.0; model.x0.len()];
|
||||
for s in &model.slots {
|
||||
let w = if opts.keep.contains(&s.handle) {
|
||||
1e4
|
||||
} else if opts.prefer_move.contains(&s.handle) {
|
||||
1e-2
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
for j in s.off..s.off + s.len {
|
||||
if let Some(slot) = weights.get_mut(j) {
|
||||
*slot = w;
|
||||
}
|
||||
}
|
||||
for (j, f) in slot_scales(model, s) {
|
||||
if let Some(slot) = weights.get_mut(j) {
|
||||
*slot *= f;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Contact parameters move freely.
|
||||
let geo = model.slots.iter().map(|s| s.off + s.len).max().unwrap_or(0);
|
||||
for w in weights.iter_mut().skip(geo) {
|
||||
*w = 1e-3;
|
||||
}
|
||||
weights
|
||||
}
|
||||
|
||||
/// Per-unknown factors for the angles and ratios of one slot: size², so that the movement of
|
||||
/// points is what is minimised.
|
||||
fn slot_scales(model: &Model, s: &model::Slot) -> Vec<(usize, f64)> {
|
||||
let sq = |j: usize| model.x0.get(j).map_or(1.0, |r| (r * r).max(1e-6));
|
||||
match s.shape {
|
||||
model::Shape::Arc => vec![(s.off + 3, sq(s.off + 2)), (s.off + 4, sq(s.off + 2))],
|
||||
model::Shape::Ellipse { arc } => {
|
||||
let a2 = (sq(s.off + 2) + sq(s.off + 3)).max(1e-6);
|
||||
let mut v = vec![(s.off + 4, a2)];
|
||||
if arc {
|
||||
v.extend([(s.off + 5, a2), (s.off + 6, a2)]);
|
||||
}
|
||||
v
|
||||
}
|
||||
model::Shape::Insert { .. } => vec![(s.off + 2, model.rigid_extent2(s.handle).max(1.0))],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the component systems. Constraints that cannot be interpreted are returned as skipped.
|
||||
fn build(d: &Drawing, cons: &[&Constraint], opts: &SolveOptions) -> Result<(Vec<Comp>, Vec<(u32, String)>), SolveError> {
|
||||
pub(crate) fn build(d: &Drawing, cons: &[&Constraint], opts: &SolveOptions) -> Result<(Vec<Comp>, Vec<(u32, String)>), SolveError> {
|
||||
let mut members_left = model::MAX_RIGID_WORK;
|
||||
build_budgeted(d, cons, opts, &mut members_left)
|
||||
}
|
||||
|
||||
/// Build constraint components with one caller-owned rigid-member sampling budget shared by every model.
|
||||
/// Return constraints that cannot be interpreted as skipped entries.
|
||||
pub(crate) fn build_budgeted(
|
||||
d: &Drawing,
|
||||
cons: &[&Constraint],
|
||||
opts: &SolveOptions,
|
||||
members_left: &mut usize,
|
||||
) -> Result<(Vec<Comp>, Vec<(u32, String)>), SolveError> {
|
||||
let mut e = env(d);
|
||||
let mut skipped = Vec::new();
|
||||
let mut comps = Vec::new();
|
||||
for group in components(cons) {
|
||||
let handles: Vec<Handle> = group.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
|
||||
let model = Model::build(d, &handles);
|
||||
let mut model = Model::build_budgeted(d, &handles, members_left);
|
||||
let mut built = Vec::new();
|
||||
for c in group {
|
||||
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c)? } else { 0.0 };
|
||||
match Built::new(c, &model, &model.x0, target) {
|
||||
Ok(b) => built.push(b),
|
||||
match interpret(c, &mut model, target) {
|
||||
Ok(mut b) => {
|
||||
if let Form::Anchor(_) = b.form
|
||||
&& let Some(&(_, a)) = opts.anchors.iter().find(|(id, _)| *id == c.id)
|
||||
{
|
||||
b.form = Form::Anchor(a);
|
||||
}
|
||||
built.push(b);
|
||||
}
|
||||
Err(msg) => skipped.push((c.id, msg)),
|
||||
}
|
||||
}
|
||||
if built.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut weights = vec![1.0; model.x0.len()];
|
||||
for s in &model.slots {
|
||||
let w = if opts.keep.contains(&s.handle) {
|
||||
1e4
|
||||
} else if opts.prefer_move.contains(&s.handle) {
|
||||
1e-2
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
for j in s.off..s.off + s.len {
|
||||
if let Some(slot) = weights.get_mut(j) {
|
||||
*slot = w;
|
||||
}
|
||||
}
|
||||
if s.shape == model::Shape::Arc {
|
||||
// Angles: weight by r² so the endpoints' movement is what is minimised.
|
||||
let r2 = model.x0.get(s.off + 2).map_or(1.0, |r| (r * r).max(1e-6));
|
||||
for j in [s.off + 3, s.off + 4] {
|
||||
if let Some(slot) = weights.get_mut(j) {
|
||||
*slot *= r2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let weights = solver_weights(&model, opts);
|
||||
let held = opts.hold.iter().filter_map(|r| model.lock_indices(r)).flatten().collect();
|
||||
let tol = scale_tol(&model.x0);
|
||||
comps.push(Comp { model, built, weights, tol });
|
||||
comps.push(Comp { model, built, weights, held, tol });
|
||||
}
|
||||
Ok((comps, skipped))
|
||||
}
|
||||
@@ -364,13 +479,13 @@ pub fn solve(d: &mut Drawing, opts: &SolveOptions) -> Result<SolveReport, SolveE
|
||||
pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
|
||||
let mut e = env(d);
|
||||
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
|
||||
let model = Model::build(d, &handles);
|
||||
let mut model = Model::build(d, &handles);
|
||||
d.constraints
|
||||
.iter()
|
||||
.take(MAX_CONSTRAINTS)
|
||||
.map(|c| {
|
||||
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
|
||||
let r = target.and_then(|t| Built::new(c, &model, &model.x0, t).ok()).map(|b| {
|
||||
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
|
||||
let mut out = Vec::new();
|
||||
b.eval(&model, &model.x0, &mut out);
|
||||
lm::max_abs(&out)
|
||||
@@ -380,6 +495,142 @@ pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Put back what each Fix locks where `before` had it, and report whether anything moved.
|
||||
///
|
||||
/// A Fix keeps no position of its own: the solver locks the parameters at their current values.
|
||||
/// Without this, an edit that moves a fixed point (a grip drag) would carry the lock along with
|
||||
/// it. Only Fixes that already existed in `before`, on objects of the same shape, are restored.
|
||||
/// An object held by a Fix on a derived point (a line's midpoint, an arc's end) has nothing to
|
||||
/// lock: when the edit only moved it (MOVE), it is put back whole, so it is not reshaped to bring
|
||||
/// the point back.
|
||||
pub fn restore_fixed(d: &mut Drawing, before: &Drawing) -> bool {
|
||||
let refs: Vec<GeomRef> = d
|
||||
.constraints
|
||||
.iter()
|
||||
.filter(|c| c.kind == ConstraintKind::Fix && before.constraints.contains(c))
|
||||
.flat_map(|c| c.refs.iter().copied())
|
||||
.collect();
|
||||
if refs.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let handles: Vec<Handle> = refs.iter().map(|r| r.handle).collect();
|
||||
let (now, old) = (Model::build(d, &handles), Model::build(before, &handles));
|
||||
let mut x = now.x0.clone();
|
||||
let mut changed = false;
|
||||
for r in &refs {
|
||||
let same_shape = matches!((now.slot(r.handle), old.slot(r.handle)), (Some(a), Some(b)) if a.shape == b.shape);
|
||||
if !same_shape {
|
||||
continue;
|
||||
}
|
||||
let (Some(i), Some(j)) = (now.lock_indices(r), old.lock_indices(r)) else {
|
||||
if let (Some(a), Some(b)) = (now.slot(r.handle), old.slot(r.handle))
|
||||
&& translated(&now, &old, r.handle)
|
||||
&& let (Some(dst), Some(src)) = (x.get_mut(a.off..a.off + a.len), old.x0.get(b.off..b.off + b.len))
|
||||
{
|
||||
for (v, &w) in dst.iter_mut().zip(src) {
|
||||
*v = w;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
for (i, j) in i.into_iter().zip(j) {
|
||||
if let (Some(slot), Some(&v)) = (x.get_mut(i), old.x0.get(j))
|
||||
&& *slot != v
|
||||
{
|
||||
*slot = v;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
now.write_back(d, &x);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The parameters of `h`'s points (see [`Model::point_refs`]) in `m`, as (x, y) pairs.
|
||||
fn point_params(m: &Model, h: Handle) -> Vec<(usize, usize)> {
|
||||
m.point_refs(h)
|
||||
.iter()
|
||||
.filter_map(|r| m.lock_indices(r))
|
||||
.flat_map(|ix| ix.as_chunks::<2>().0.iter().map(|&[x, y]| (x, y)).collect::<Vec<_>>())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Is `h` in `now` its shape in `old` moved by one vector, and nothing else?
|
||||
fn translated(now: &Model, old: &Model, h: Handle) -> bool {
|
||||
let (Some(a), Some(b)) = (now.slot(h), old.slot(h)) else { return false };
|
||||
let (Some(xa), Some(xb)) = (now.x0.get(a.off..a.off + a.len), old.x0.get(b.off..b.off + b.len)) else { return false };
|
||||
let tol = scale_tol(xb) * 10.0;
|
||||
let pts: Vec<(usize, usize)> =
|
||||
point_params(old, h).into_iter().filter_map(|(i, j)| Some((i.checked_sub(b.off)?, j.checked_sub(b.off)?))).collect();
|
||||
let delta = |(i, j): (usize, usize)| Some(Vec2::new(xa.get(i)? - xb.get(i)?, xa.get(j)? - xb.get(j)?));
|
||||
let Some(v) = pts.first().and_then(|&p| delta(p)) else { return false };
|
||||
if v.len() <= tol || !pts.iter().all(|&p| delta(p).is_some_and(|d| d.near(v, tol))) {
|
||||
return false;
|
||||
}
|
||||
(0..xb.len())
|
||||
.filter(|k| !pts.iter().any(|&(i, j)| *k == i || *k == j))
|
||||
.all(|k| matches!((xa.get(k), xb.get(k)), (Some(p), Some(q)) if (p - q).abs() <= tol))
|
||||
}
|
||||
|
||||
/// The points of `h` (its ends, centre or vertices) the edit from `before` to `d` moved, when it
|
||||
/// moved some of them but not all: the grip that was dragged, to pass as [`SolveOptions::hold`] so
|
||||
/// it stays where it was put and the rest of the object takes up the constraints. Empty when the
|
||||
/// object kept its points or moved them all.
|
||||
pub fn edited_points(d: &Drawing, before: &Drawing, h: Handle) -> Vec<GeomRef> {
|
||||
let (now, old) = (Model::build(d, &[h]), Model::build(before, &[h]));
|
||||
if !matches!((now.slot(h), old.slot(h)), (Some(a), Some(b)) if a.shape == b.shape) {
|
||||
return Vec::new();
|
||||
}
|
||||
let tol = scale_tol(&old.x0) * 10.0;
|
||||
let refs = now.point_refs(h);
|
||||
let moved: Vec<GeomRef> = refs
|
||||
.iter()
|
||||
.filter(|r| matches!((now.lock_indices(r), old.lock_indices(r)), (Some(i), Some(j)) if i.iter().zip(&j).any(|(&i, &j)| matches!((now.x0.get(i), old.x0.get(j)), (Some(p), Some(q)) if (p - q).abs() > tol))))
|
||||
.copied()
|
||||
.collect();
|
||||
if moved.len() == refs.len() { Vec::new() } else { moved }
|
||||
}
|
||||
|
||||
/// Where `before` had each derived point held by a Fix (a line's midpoint, an arc's end), for the
|
||||
/// Fixes whose point has moved since, to pass as [`SolveOptions::anchors`].
|
||||
///
|
||||
/// A Fix on a derived point anchors it where it is when the system is built, and
|
||||
/// [`restore_fixed`] has no parameters to put back: without this, an edit that moves the point
|
||||
/// would leave the Fix satisfied at the new place.
|
||||
pub fn moved_anchors(d: &Drawing, before: &Drawing) -> Vec<(u32, Vec2)> {
|
||||
let fixes: Vec<(u32, GeomRef)> = d
|
||||
.constraints
|
||||
.iter()
|
||||
.filter(|c| c.kind == ConstraintKind::Fix && before.constraints.contains(c))
|
||||
.filter_map(|c| match c.refs.as_slice() {
|
||||
[r] => Some((c.id, *r)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if fixes.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let handles: Vec<Handle> = fixes.iter().map(|(_, r)| r.handle).collect();
|
||||
let (now, old) = (Model::build(d, &handles), Model::build(before, &handles));
|
||||
let tol = scale_tol(&old.x0);
|
||||
let mut out = Vec::new();
|
||||
for (id, r) in fixes {
|
||||
let same_shape = matches!((now.slot(r.handle), old.slot(r.handle)), (Some(a), Some(b)) if a.shape == b.shape);
|
||||
if !same_shape || now.lock_indices(&r).is_some() {
|
||||
continue;
|
||||
}
|
||||
if let (Some(p), Some(a)) = (now.point(&now.x0, &r), old.point(&old.x0, &r))
|
||||
&& !p.near(a, tol)
|
||||
{
|
||||
out.push((id, a));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// True when every interpretable constraint holds at the current geometry.
|
||||
pub fn all_satisfied(d: &Drawing) -> bool {
|
||||
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
|
||||
@@ -397,16 +648,16 @@ pub fn validate(d: &Drawing, c: &Constraint) -> Result<(), String> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let model = Model::build(d, &handles);
|
||||
Built::new(c, &model, &model.x0, 1.0).map(|_| ())
|
||||
let mut model = Model::build(d, &handles);
|
||||
interpret(c, &mut model, 1.0).map(|_| ())
|
||||
}
|
||||
|
||||
/// The current measured value of a dimensional constraint over `refs` (degrees for angular).
|
||||
pub fn measure(d: &Drawing, kind: ConstraintKind, refs: &[GeomRef]) -> Result<f64, String> {
|
||||
let c = Constraint { id: 0, kind, refs: refs.to_vec(), name: String::new(), expr: String::new() };
|
||||
let handles: Vec<Handle> = refs.iter().map(|r| r.handle).collect();
|
||||
let model = Model::build(d, &handles);
|
||||
let b = Built::new(&c, &model, &model.x0, 1.0)?;
|
||||
let mut model = Model::build(d, &handles);
|
||||
let b = interpret(&c, &mut model, 1.0)?;
|
||||
Ok(b.measure(&model, &model.x0))
|
||||
}
|
||||
|
||||
@@ -475,8 +726,7 @@ pub fn add(d: &mut Drawing, mut c: Constraint, opts: &SolveOptions) -> Result<u3
|
||||
return Err(SolveError::Conflict { ids });
|
||||
}
|
||||
// Redundancy: the new rows must raise the rank.
|
||||
if let Some(pos) = comp.built.iter().position(|b| b.id == id)
|
||||
&& let Some(nb) = comp.built.get(pos)
|
||||
if let Some(nb) = comp.built.iter().find(|b| b.id == id)
|
||||
&& nb.rows > 0
|
||||
{
|
||||
let free = comp.free(None);
|
||||
@@ -489,11 +739,31 @@ pub fn add(d: &mut Drawing, mut c: Constraint, opts: &SolveOptions) -> Result<u3
|
||||
};
|
||||
let rows_all: usize = ordered.iter().map(|b| b.rows).sum();
|
||||
let rows_old = rows_all - nb.rows;
|
||||
let nf = free.len();
|
||||
let jac = lm::jacobian(&f, &o.x, &free, rows_all);
|
||||
let r_all = lm::rank(&jac, rows_all, free.len());
|
||||
let r_old = lm::rank(jac.get(..rows_old * free.len()).unwrap_or_default(), rows_old, free.len());
|
||||
let r_all = lm::rank_qr(&jac, rows_all, nf);
|
||||
let r_old = lm::rank_qr(jac.get(..rows_old * nf).unwrap_or_default(), rows_old, nf);
|
||||
if r_all < r_old + nb.rows {
|
||||
let mine: Vec<Handle> = nb.refs.iter().map(|r| r.handle).collect();
|
||||
return Err(SolveError::Redundant { ids: redundant_with(&comp, &ordered, &jac, nf, id) });
|
||||
}
|
||||
}
|
||||
// A Fix that locks parameters adds one equation per parameter it locks.
|
||||
if let Some(pos) = comp.built.iter().position(|b| b.id == id)
|
||||
&& comp.built.get(pos).is_some_and(|b| b.form == Form::Lock)
|
||||
{
|
||||
let before = comp.free(Some(pos));
|
||||
let after = comp.free(None);
|
||||
let locked: Vec<usize> = before.iter().enumerate().filter(|(_, j)| !after.contains(j)).map(|(k, _)| k).collect();
|
||||
let rows_old = comp.rows(Some(pos));
|
||||
let nf = before.len();
|
||||
let f = |x: &[f64], out: &mut Vec<f64>| comp.eval(x, out, Some(pos));
|
||||
let mut jac = lm::jacobian(&f, &o.x, &before, rows_old);
|
||||
let r_old = lm::rank_qr(&jac, rows_old, nf);
|
||||
for k in &locked {
|
||||
jac.extend((0..nf).map(|c| if c == *k { 1.0 } else { 0.0 }));
|
||||
}
|
||||
if locked.is_empty() || lm::rank_qr(&jac, rows_old + locked.len(), nf) < r_old + locked.len() {
|
||||
let mine: Vec<Handle> = comp.built.get(pos).map(|b| b.refs.iter().map(|r| r.handle).collect()).unwrap_or_default();
|
||||
let ids = comp.built.iter().filter(|b| b.id != id && b.refs.iter().any(|r| mine.contains(&r.handle))).map(|b| b.id).collect();
|
||||
return Err(SolveError::Redundant { ids });
|
||||
}
|
||||
@@ -503,6 +773,53 @@ pub fn add(d: &mut Drawing, mut c: Constraint, opts: &SolveOptions) -> Result<u3
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// The existing constraints a redundant new one (last in `ordered`) duplicates: each one whose
|
||||
/// removal would let the new one add independent equations. Falls back to the constraints on
|
||||
/// the same objects.
|
||||
fn redundant_with(comp: &Comp, ordered: &[&Built], jac: &[f64], nf: usize, id: u32) -> Vec<u32> {
|
||||
let mut starts = Vec::with_capacity(ordered.len());
|
||||
let mut at = 0;
|
||||
for b in ordered {
|
||||
starts.push(at);
|
||||
at += b.rows;
|
||||
}
|
||||
let pick = |skip: usize, with_new: bool| -> (Vec<f64>, usize) {
|
||||
let mut m = Vec::new();
|
||||
let mut rows = 0;
|
||||
let last = ordered.len().saturating_sub(1);
|
||||
for (i, b) in ordered.iter().enumerate() {
|
||||
if i == skip || (i == last && !with_new) {
|
||||
continue;
|
||||
}
|
||||
let s = starts.get(i).copied().unwrap_or(0);
|
||||
if let Some(part) = jac.get(s * nf..(s + b.rows) * nf) {
|
||||
m.extend_from_slice(part);
|
||||
rows += b.rows;
|
||||
}
|
||||
}
|
||||
(m, rows)
|
||||
};
|
||||
let new_rows = ordered.last().map_or(0, |b| b.rows);
|
||||
let mut ids = Vec::new();
|
||||
if ordered.len() <= MAX_CONFLICT_PROBES + 1 {
|
||||
for (i, b) in ordered.iter().enumerate().take(ordered.len().saturating_sub(1)) {
|
||||
if b.rows == 0 {
|
||||
continue;
|
||||
}
|
||||
let (old, ro) = pick(i, false);
|
||||
let (all, ra) = pick(i, true);
|
||||
if lm::rank_qr(&all, ra, nf) == lm::rank_qr(&old, ro, nf) + new_rows {
|
||||
ids.push(b.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ids.is_empty() {
|
||||
let mine: Vec<Handle> = ordered.last().map(|b| b.refs.iter().map(|r| r.handle).collect()).unwrap_or_default();
|
||||
ids = comp.built.iter().filter(|b| b.id != id && b.refs.iter().any(|r| mine.contains(&r.handle))).map(|b| b.id).collect();
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// Format a value for an expression (up to 6 decimals, trailing zeros trimmed).
|
||||
pub fn format_value(v: f64) -> String {
|
||||
let s = format!("{v:.6}");
|
||||
@@ -545,6 +862,33 @@ pub fn set_parameter(d: &mut Drawing, name: &str, expr_text: &str, opts: &SolveO
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Rename a parameter (dimensional constraint name or user parameter) and every expression that
|
||||
/// uses it. Geometry doesn't change. On error the drawing is unchanged.
|
||||
pub fn rename_parameter(d: &mut Drawing, old: &str, new: &str) -> Result<(), SolveError> {
|
||||
if !name_in_use(d, old) {
|
||||
return Err(SolveError::Other(format!("no parameter `{old}`")));
|
||||
}
|
||||
if !expr::valid_name(new) {
|
||||
return Err(SolveError::Other(format!("invalid parameter name `{new}`")));
|
||||
}
|
||||
if new != old && name_in_use(d, new) {
|
||||
return Err(SolveError::Other(format!("`{new}` is already in use")));
|
||||
}
|
||||
for c in d.constraints.iter_mut().filter(|c| c.kind.is_dimensional()) {
|
||||
if c.name == old {
|
||||
c.name = new.to_string();
|
||||
}
|
||||
c.expr = expr::rename(&c.expr, old, new);
|
||||
}
|
||||
for p in &mut d.parametric.parameters {
|
||||
if p.name == old {
|
||||
p.name = new.to_string();
|
||||
}
|
||||
p.expr = expr::rename(&p.expr, old, new);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where to draw a constraint's glyphs (one anchor per reference).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -580,6 +924,7 @@ pub fn glyphs(d: &Drawing) -> Vec<Glyph> {
|
||||
.point(x, r)
|
||||
.or_else(|| model.line(x, r).map(|(a, b)| a.mid(b)))
|
||||
.or_else(|| model.circle(x, r).map(|(c, rad)| c + Vec2::new(0.0, rad)))
|
||||
.or_else(|| model.anchor(x, r))
|
||||
})
|
||||
.collect();
|
||||
Glyph {
|
||||
|
||||
+132
-43
@@ -102,50 +102,124 @@ fn solve_dense(mut a: Vec<f64>, mut b: Vec<f64>, n: usize) -> Option<Vec<f64>> {
|
||||
y.iter().all(|v| v.is_finite()).then_some(y)
|
||||
}
|
||||
|
||||
/// Numerical rank of a row-major `rows × cols` matrix (rows normalised first).
|
||||
pub(crate) fn rank(m: &[f64], rows: usize, cols: usize) -> usize {
|
||||
let mut a: Vec<Vec<f64>> = (0..rows)
|
||||
.map(|i| {
|
||||
let r: Vec<f64> = m.get(i * cols..(i + 1) * cols).map(<[f64]>::to_vec).unwrap_or_default();
|
||||
let n = norm2(&r).sqrt();
|
||||
if n > 1e-12 { r.iter().map(|v| v / n).collect() } else { vec![0.0; cols] }
|
||||
})
|
||||
.collect();
|
||||
let mut rank = 0;
|
||||
let mut used = vec![false; rows];
|
||||
/// Householder QR with column pivoting of the columns `cols` (each of the same length). Stops
|
||||
/// when the largest remaining column norm drops to `rel` times the first pivot's (or below
|
||||
/// `abs`). Returns the numerical rank and the Householder vectors (full length, zero above the
|
||||
/// diagonal; each reflector is `I − 2vvᵀ/(vᵀv)`).
|
||||
pub(crate) fn qr(mut cols: Vec<Vec<f64>>, rel: f64, abs: f64) -> (usize, Vec<Vec<f64>>) {
|
||||
let m = cols.first().map_or(0, Vec::len);
|
||||
let n = cols.len();
|
||||
let mut refl = Vec::new();
|
||||
let mut first = None;
|
||||
for k in 0..m.min(n) {
|
||||
// Pivot: the column with the largest remaining norm.
|
||||
let mut best = (k, -1.0f64);
|
||||
for (j, c) in cols.iter().enumerate().skip(k) {
|
||||
let v = c.get(k..).map_or(0.0, norm2);
|
||||
if v.is_finite() && v > best.1 {
|
||||
best = (j, v);
|
||||
}
|
||||
}
|
||||
let norm = best.1.max(0.0).sqrt();
|
||||
let lim = first.map_or(abs, |f: f64| (f * rel).max(abs));
|
||||
if crate::curves::not_above(norm, lim) {
|
||||
break;
|
||||
}
|
||||
first.get_or_insert(norm);
|
||||
cols.swap(k, best.0);
|
||||
let Some(col) = cols.get(k) else { break };
|
||||
let mut v = vec![0.0; m];
|
||||
for i in k..m {
|
||||
if let (Some(d), Some(s)) = (v.get_mut(i), col.get(i)) {
|
||||
*d = *s;
|
||||
}
|
||||
}
|
||||
let x0 = v.get(k).copied().unwrap_or(0.0);
|
||||
let alpha = if x0 >= 0.0 { -norm } else { norm };
|
||||
if let Some(d) = v.get_mut(k) {
|
||||
*d -= alpha;
|
||||
}
|
||||
let vv = norm2(&v);
|
||||
if crate::curves::not_above(vv, 0.0) {
|
||||
break;
|
||||
}
|
||||
for c in cols.iter_mut().skip(k) {
|
||||
reflect(&v, vv, c);
|
||||
}
|
||||
refl.push(v);
|
||||
}
|
||||
(refl.len(), refl)
|
||||
}
|
||||
|
||||
fn reflect(v: &[f64], vv: f64, c: &mut [f64]) {
|
||||
let d: f64 = v.iter().zip(c.iter()).map(|(a, b)| a * b).sum();
|
||||
let f = 2.0 * d / vv;
|
||||
if f != 0.0 {
|
||||
for (ci, vi) in c.iter_mut().zip(v) {
|
||||
*ci -= f * vi;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows and columns scaled to unit norm (zero ones left alone), as columns of the transpose:
|
||||
/// `out[i]` is row `i` of the row-major `rows × cols` matrix `m`.
|
||||
fn balanced_rows(m: &[f64], rows: usize, cols: usize) -> Vec<Vec<f64>> {
|
||||
let mut r: Vec<Vec<f64>> = (0..rows).map(|i| m.get(i * cols..(i + 1) * cols).map(<[f64]>::to_vec).unwrap_or_else(|| vec![0.0; cols])).collect();
|
||||
for row in &mut r {
|
||||
let n = norm2(row).sqrt();
|
||||
let f = if n > 1e-12 && n.is_finite() { 1.0 / n } else { 0.0 };
|
||||
row.iter_mut().for_each(|v| *v *= f);
|
||||
}
|
||||
// Columns: unit norm, except numerical noise (an exactly zero derivative evaluated by
|
||||
// differences), which scaling would turn into a spurious independent direction.
|
||||
for c in 0..cols {
|
||||
let mut piv = None;
|
||||
let mut best = 1e-7;
|
||||
for (i, row) in a.iter().enumerate() {
|
||||
if used.get(i).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let v = row.get(c).copied().unwrap_or(0.0).abs();
|
||||
if v > best {
|
||||
best = v;
|
||||
piv = Some(i);
|
||||
}
|
||||
}
|
||||
let Some(p) = piv else { continue };
|
||||
if let Some(u) = used.get_mut(p) {
|
||||
*u = true;
|
||||
}
|
||||
rank += 1;
|
||||
let prow = a.get(p).cloned().unwrap_or_default();
|
||||
let pv = prow.get(c).copied().unwrap_or(1.0);
|
||||
for (i, row) in a.iter_mut().enumerate() {
|
||||
if i == p || used.get(i).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
let f = row.get(c).copied().unwrap_or(0.0) / pv;
|
||||
if f != 0.0 {
|
||||
for (v, pr) in row.iter_mut().zip(&prow) {
|
||||
*v -= f * pr;
|
||||
}
|
||||
let n = r.iter().map(|row| row.get(c).map_or(0.0, |v| v * v)).sum::<f64>().sqrt();
|
||||
let f = if n > COL_NOISE && n.is_finite() { 1.0 / n } else { 0.0 };
|
||||
for row in &mut r {
|
||||
if let Some(v) = row.get_mut(c) {
|
||||
*v *= f;
|
||||
}
|
||||
}
|
||||
}
|
||||
rank
|
||||
r
|
||||
}
|
||||
|
||||
/// Column norm (after row balancing) below which a column is difference noise.
|
||||
const COL_NOISE: f64 = 1e-6;
|
||||
/// Relative threshold below which a pivot counts as zero (the Jacobian is numerical).
|
||||
const RANK_TOL: f64 = 1e-7;
|
||||
|
||||
/// Numerical rank of a row-major `rows × cols` Jacobian (rows and columns balanced first,
|
||||
/// Householder QR with column pivoting).
|
||||
pub(crate) fn rank_qr(m: &[f64], rows: usize, cols: usize) -> usize {
|
||||
if rows == 0 || cols == 0 {
|
||||
return 0;
|
||||
}
|
||||
// QR of the transpose: its columns are the Jacobian's rows.
|
||||
qr(balanced_rows(m, rows, cols), RANK_TOL, 1e-12).0
|
||||
}
|
||||
|
||||
/// Rank and an orthonormal basis of the null space (each vector of length `cols`) of a
|
||||
/// row-major `rows × cols` Jacobian, in balanced column coordinates (a diagonal scaling, so
|
||||
/// which parameters a null vector moves is preserved).
|
||||
pub(crate) fn null_space(m: &[f64], rows: usize, cols: usize) -> (usize, Vec<Vec<f64>>) {
|
||||
let (rank, refl) = if rows == 0 { (0, Vec::new()) } else { qr(balanced_rows(m, rows, cols), RANK_TOL, 1e-12) };
|
||||
let mut basis = Vec::with_capacity(cols.saturating_sub(rank));
|
||||
for j in rank..cols {
|
||||
let mut e = vec![0.0; cols];
|
||||
if let Some(v) = e.get_mut(j) {
|
||||
*v = 1.0;
|
||||
}
|
||||
// Q e_j with Q = H_0 H_1 … H_{r−1}.
|
||||
for v in refl.iter().rev() {
|
||||
let vv = norm2(v);
|
||||
if vv > 0.0 {
|
||||
reflect(v, vv, &mut e);
|
||||
}
|
||||
}
|
||||
basis.push(e);
|
||||
}
|
||||
(rank, basis)
|
||||
}
|
||||
|
||||
/// Run the solver from `x0`. Only `free` parameters change.
|
||||
@@ -241,9 +315,24 @@ mod tests {
|
||||
let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap();
|
||||
assert!((y[0] - 0.8).abs() < 1e-12 && (y[1] - 1.4).abs() < 1e-12);
|
||||
assert!(solve_dense(vec![1.0, 2.0, 2.0, 4.0], vec![1.0, 1.0], 2).is_none());
|
||||
assert_eq!(rank(&[1.0, 0.0, 0.0, 1.0, 1.0, 1.0], 3, 2), 2);
|
||||
assert_eq!(rank(&[1.0, 2.0, 2.0, 4.0], 2, 2), 1);
|
||||
assert_eq!(rank(&[0.0; 4], 2, 2), 0);
|
||||
assert_eq!(rank_qr(&[1.0, 0.0, 0.0, 1.0, 1.0, 1.0], 3, 2), 2);
|
||||
assert_eq!(rank_qr(&[1.0, 2.0, 2.0, 4.0], 2, 2), 1);
|
||||
assert_eq!(rank_qr(&[0.0; 4], 2, 2), 0);
|
||||
assert_eq!(rank_qr(&[1e-9, 0.0, 0.0, 1e6], 2, 2), 2, "balanced: scale does not hide rank");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_space_spans_free_motion() {
|
||||
// x0 + x1 = c fixes one combination; x2 is untouched.
|
||||
let (r, n) = null_space(&[1.0, 1.0, 0.0], 1, 3);
|
||||
assert_eq!((r, n.len()), (1, 2));
|
||||
for v in &n {
|
||||
assert!((v[0] + v[1]).abs() < 1e-12);
|
||||
}
|
||||
// x2's own motion survives in the null space; x0 alone does not.
|
||||
assert!(n.iter().any(|v| v[2].abs() > 0.5));
|
||||
let (r, n) = null_space(&[], 0, 2);
|
||||
assert_eq!((r, n.len()), (0, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+521
-34
@@ -5,22 +5,61 @@
|
||||
//! - Arc: `cx cy r start end` (angles in radians)
|
||||
//! - LwPolyline: `x0 y0 x1 y1 …` (bulges are kept; segments are treated as straight lines)
|
||||
//! - Point: `x y`
|
||||
//! - Ellipse: `cx cy mx my ratio` plus `start end` (parameters, radians) for an elliptical arc;
|
||||
//! `(mx, my)` is the major axis vector
|
||||
//! - Spline: its defining points `x0 y0 x1 y1 …`: the fit points of an interpolating spline
|
||||
//! (rebuilt through them on write-back), else the control points
|
||||
//! - Block reference: `x y rotation`; the block's characteristic points ride along rigidly
|
||||
//!
|
||||
//! Constraints may append auxiliary unknowns after the entity parameters (contact parameters of
|
||||
//! a tangency between curves); they are never written back.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cadcraft_doc::{Drawing, EntityKind, GeomRef, Handle, Sub};
|
||||
use cadcraft_geom::{Vec2, ccw_sweep};
|
||||
use cadcraft_doc::{Drawing, EntityKind, GeomRef, Handle, Insert, Sub};
|
||||
use cadcraft_geom::{Spline as GSpline, Vec2, ccw_sweep};
|
||||
|
||||
use crate::curves::{Ell, Frame, clamped, spline_end};
|
||||
|
||||
/// Most parameters one solve may have.
|
||||
pub const MAX_PARAMS: usize = 4000;
|
||||
/// Most defining points of a spline taking part in constraints.
|
||||
pub const MAX_SPLINE_POINTS: usize = 500;
|
||||
/// Most characteristic points of a block reference used as rigid constraint points.
|
||||
pub const MAX_RIGID_POINTS: usize = 256;
|
||||
/// Block members examined when sampling rigid points, counting those that contribute none, so a
|
||||
/// block padded with point-less entities cannot make sampling (repeated per Insert) unbounded.
|
||||
const MAX_RIGID_MEMBERS: usize = 100_000;
|
||||
/// Shared across every model built for one analysis request.
|
||||
pub(crate) const MAX_RIGID_WORK: usize = 1_000_000;
|
||||
/// How far past 1 a solved ellipse ratio may land by rounding and still be stored as 1.
|
||||
const RATIO_TOL: f64 = 1e-9;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Shape {
|
||||
Line,
|
||||
Circle,
|
||||
Arc,
|
||||
Poly { n: usize, closed: bool },
|
||||
Poly {
|
||||
n: usize,
|
||||
closed: bool,
|
||||
},
|
||||
Point,
|
||||
/// `arc`: elliptical arc (has start/end parameters).
|
||||
Ellipse {
|
||||
arc: bool,
|
||||
},
|
||||
/// `n` defining points; `fit`: they are fit points; `ends`: the curve has a start and an end
|
||||
/// (open and clamped) that are its first and last defining points.
|
||||
Spline {
|
||||
n: usize,
|
||||
fit: bool,
|
||||
ends: bool,
|
||||
},
|
||||
/// Block reference with `n` rigid points.
|
||||
Insert {
|
||||
n: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -36,20 +75,195 @@ pub(crate) struct Model {
|
||||
pub slots: Vec<Slot>,
|
||||
pub x0: Vec<f64>,
|
||||
index: HashMap<Handle, usize>,
|
||||
/// Spline templates (degree, knots, weights, fit options) the defining points plug into.
|
||||
splines: HashMap<Handle, GSpline>,
|
||||
/// Block reference rigid points relative to the insertion point at rotation 0.
|
||||
rigid: HashMap<Handle, Vec<Vec2>>,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
/// Work for a spline that an endpoint residual actually reconstructs. Fit interpolation
|
||||
/// uses dense Gaussian elimination (cubic); control splines clone and evaluate their template.
|
||||
pub(crate) fn spline_reconstruct_cost(&self, handle: Handle) -> f64 {
|
||||
let Some(s) = self.splines.get(&handle) else { return 0.0 };
|
||||
let n = s.fit.len() as f64;
|
||||
if fit_mode(s) {
|
||||
n * n * n
|
||||
} else {
|
||||
let n = s.control.len() as f64;
|
||||
n * n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Can this entity take part in constraints?
|
||||
pub fn supported(kind: &EntityKind) -> bool {
|
||||
matches!(kind, EntityKind::Line(_) | EntityKind::Circle(_) | EntityKind::Arc(_) | EntityKind::LwPolyline(_) | EntityKind::Point(_))
|
||||
matches!(
|
||||
kind,
|
||||
EntityKind::Line(_)
|
||||
| EntityKind::Circle(_)
|
||||
| EntityKind::Arc(_)
|
||||
| EntityKind::LwPolyline(_)
|
||||
| EntityKind::Point(_)
|
||||
| EntityKind::Ellipse(_)
|
||||
| EntityKind::Spline(_)
|
||||
| EntityKind::Insert(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// World positions of a block reference's rigid points: the characteristic points (end points,
|
||||
/// centres, vertices, nested insertion points) of the block's own objects, at most
|
||||
/// [`MAX_RIGID_POINTS`]. Nested blocks are not entered.
|
||||
pub fn rigid_points(d: &Drawing, ins: &Insert) -> Vec<Vec2> {
|
||||
let mut members_left = MAX_RIGID_MEMBERS;
|
||||
rigid_points_budgeted(d, ins, &mut members_left)
|
||||
}
|
||||
|
||||
/// Sample finite block points within per-insert and caller-shared member limits.
|
||||
/// Members that contribute no points still consume traversal work; nested blocks are not entered.
|
||||
fn rigid_points_budgeted(d: &Drawing, ins: &Insert, members_left: &mut usize) -> Vec<Vec2> {
|
||||
let Some(block) = d.block(&ins.block) else { return Vec::new() };
|
||||
let m = ins.transform(block.base.xy());
|
||||
let mut out = Vec::new();
|
||||
// Bound the members examined, not only the points collected: entities that contribute no
|
||||
// points (Text, Ray, …) still cost traversal, so a block full of them — scanned again for
|
||||
// every Insert — would otherwise be unbounded (CWE-407).
|
||||
let mut examined = 0usize;
|
||||
for e in block.entities.iter() {
|
||||
examined += 1;
|
||||
if out.len() >= MAX_RIGID_POINTS || examined > MAX_RIGID_MEMBERS || *members_left == 0 {
|
||||
break;
|
||||
}
|
||||
*members_left -= 1;
|
||||
let pts: Vec<Vec2> = match &e.kind {
|
||||
EntityKind::Line(l) => vec![l.a.xy(), l.b.xy()],
|
||||
EntityKind::Arc(a) => {
|
||||
let g = cadcraft_geom::Arc::new(a.center.xy(), a.radius, a.start, a.end);
|
||||
vec![g.start_point(), g.end_point(), g.center]
|
||||
}
|
||||
EntityKind::Circle(c) => vec![c.center.xy()],
|
||||
EntityKind::Point(p) => vec![p.p.xy()],
|
||||
EntityKind::Ellipse(el) => vec![el.center.xy()],
|
||||
EntityKind::Insert(i) => vec![i.insert.xy()],
|
||||
EntityKind::LwPolyline(p) => p.vertices.iter().take(MAX_RIGID_POINTS).map(|v| v.p).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
out.extend(pts.into_iter().map(|p| m.apply(p)).filter(|p| p.is_finite()));
|
||||
}
|
||||
out.truncate(MAX_RIGID_POINTS);
|
||||
out
|
||||
}
|
||||
|
||||
/// Constraint points of an object as the solver sees them (`Sub`, position): end points,
|
||||
/// centres, axis ends, defining points, rigid points. Points at the same place are listed once.
|
||||
pub fn ref_points(d: &Drawing, h: Handle) -> Vec<(Sub, Vec2)> {
|
||||
let m = Model::build(d, &[h]);
|
||||
let Some(s) = m.slots.first() else { return Vec::new() };
|
||||
let n = match s.shape {
|
||||
Shape::Ellipse { .. } => 4,
|
||||
Shape::Spline { n, .. } | Shape::Insert { n } | Shape::Poly { n, .. } => n,
|
||||
_ => 0,
|
||||
};
|
||||
let mut out: Vec<(Sub, Vec2)> = Vec::new();
|
||||
for sub in [Sub::Whole, Sub::Center, Sub::Start, Sub::End, Sub::Mid].into_iter().chain((0..n).map(|i| Sub::Vertex(i as u32))) {
|
||||
if let Some(p) = m.point(&m.x0, &GeomRef::new(h, sub))
|
||||
&& !out.iter().any(|(_, q)| *q == p)
|
||||
{
|
||||
out.push((sub, p));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn p2(x: &[f64], i: usize) -> Option<Vec2> {
|
||||
Some(Vec2::new(*x.get(i)?, *x.get(i + 1)?))
|
||||
}
|
||||
|
||||
/// Does a spline interpolate its fit points (so they can be its parameters)?
|
||||
fn fit_mode(s: &GSpline) -> bool {
|
||||
s.fit.len() >= 2 && s.fit_opts.tolerance == 0.0
|
||||
}
|
||||
|
||||
impl Model {
|
||||
/// Build a model for the given entities. Unsupported or missing entities are skipped.
|
||||
pub fn build(d: &Drawing, handles: &[Handle]) -> Model {
|
||||
let mut members_left = MAX_RIGID_WORK;
|
||||
Self::build_budgeted(d, handles, &mut members_left)
|
||||
}
|
||||
|
||||
/// Add the parameters of one supported entity to `m`, and return its shape; `None` when it is
|
||||
/// left out (too large, degenerate or unsupported).
|
||||
fn add_params(m: &mut Model, d: &Drawing, h: Handle, kind: &EntityKind, off: usize, members_left: &mut usize) -> Option<Shape> {
|
||||
let shape = match kind {
|
||||
EntityKind::Line(l) => {
|
||||
m.x0.extend([l.a.x, l.a.y, l.b.x, l.b.y]);
|
||||
Shape::Line
|
||||
}
|
||||
EntityKind::Circle(c) => {
|
||||
m.x0.extend([c.center.x, c.center.y, c.radius]);
|
||||
Shape::Circle
|
||||
}
|
||||
EntityKind::Arc(a) => {
|
||||
m.x0.extend([a.center.x, a.center.y, a.radius, a.start, a.end]);
|
||||
Shape::Arc
|
||||
}
|
||||
EntityKind::LwPolyline(p) => {
|
||||
if p.vertices.len() < 2 || off + p.vertices.len() * 2 > MAX_PARAMS {
|
||||
return None;
|
||||
}
|
||||
for v in &p.vertices {
|
||||
m.x0.extend([v.p.x, v.p.y]);
|
||||
}
|
||||
Shape::Poly { n: p.vertices.len(), closed: p.closed }
|
||||
}
|
||||
EntityKind::Point(p) => {
|
||||
m.x0.extend([p.p.x, p.p.y]);
|
||||
Shape::Point
|
||||
}
|
||||
EntityKind::Ellipse(el) => {
|
||||
let ell = cadcraft_geom::Ellipse { center: el.center.xy(), major: el.major.xy(), ratio: el.ratio, start: el.start, end: el.end };
|
||||
let arc = !ell.is_full();
|
||||
m.x0.extend([el.center.x, el.center.y, el.major.x, el.major.y, el.ratio]);
|
||||
if arc {
|
||||
m.x0.extend([el.start, el.end]);
|
||||
}
|
||||
Shape::Ellipse { arc }
|
||||
}
|
||||
EntityKind::Spline(sp) => {
|
||||
let fit = fit_mode(sp);
|
||||
let pts = if fit { &sp.fit } else { &sp.control };
|
||||
let n = pts.len();
|
||||
if !(2..=MAX_SPLINE_POINTS).contains(&n) || off + n * 2 > MAX_PARAMS || (!fit && !sp.is_valid()) {
|
||||
return None;
|
||||
}
|
||||
for p in pts {
|
||||
m.x0.extend([p.x, p.y]);
|
||||
}
|
||||
// Fit points interpolate exactly, so the curve's ends are the first and last
|
||||
// fit point; a control polygon's ends are its first and last points when the
|
||||
// knots are clamped.
|
||||
let ends = !sp.closed && (fit || (clamped(sp, false) && clamped(sp, true)));
|
||||
// Missing weights default to 1 in eval; only excess weights are unused.
|
||||
let mut kept = sp.clone();
|
||||
kept.weights.truncate(kept.control.len());
|
||||
m.splines.insert(h, kept);
|
||||
Shape::Spline { n, fit, ends }
|
||||
}
|
||||
EntityKind::Insert(ins) => {
|
||||
let base = Vec2::new(ins.insert.x, ins.insert.y);
|
||||
let pts: Vec<Vec2> = rigid_points_budgeted(d, ins, members_left).into_iter().map(|p| (p - base).rotate(-ins.rotation)).collect();
|
||||
m.x0.extend([ins.insert.x, ins.insert.y, ins.rotation]);
|
||||
let n = pts.len();
|
||||
m.rigid.insert(h, pts);
|
||||
Shape::Insert { n }
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(shape)
|
||||
}
|
||||
|
||||
/// Build solver parameters for supported entities while sharing rigid-member sampling work with other models.
|
||||
pub(crate) fn build_budgeted(d: &Drawing, handles: &[Handle], members_left: &mut usize) -> Model {
|
||||
let mut m = Model::default();
|
||||
for &h in handles {
|
||||
if m.index.contains_key(&h) {
|
||||
@@ -57,34 +271,7 @@ impl Model {
|
||||
}
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let off = m.x0.len();
|
||||
let shape = match &e.kind {
|
||||
EntityKind::Line(l) => {
|
||||
m.x0.extend([l.a.x, l.a.y, l.b.x, l.b.y]);
|
||||
Shape::Line
|
||||
}
|
||||
EntityKind::Circle(c) => {
|
||||
m.x0.extend([c.center.x, c.center.y, c.radius]);
|
||||
Shape::Circle
|
||||
}
|
||||
EntityKind::Arc(a) => {
|
||||
m.x0.extend([a.center.x, a.center.y, a.radius, a.start, a.end]);
|
||||
Shape::Arc
|
||||
}
|
||||
EntityKind::LwPolyline(p) => {
|
||||
if p.vertices.len() < 2 || off + p.vertices.len() * 2 > MAX_PARAMS {
|
||||
continue;
|
||||
}
|
||||
for v in &p.vertices {
|
||||
m.x0.extend([v.p.x, v.p.y]);
|
||||
}
|
||||
Shape::Poly { n: p.vertices.len(), closed: p.closed }
|
||||
}
|
||||
EntityKind::Point(p) => {
|
||||
m.x0.extend([p.p.x, p.p.y]);
|
||||
Shape::Point
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let Some(shape) = Self::add_params(&mut m, d, h, &e.kind, off, members_left) else { continue };
|
||||
if m.x0.len() > MAX_PARAMS || m.x0.get(off..).unwrap_or(&[]).iter().any(|v| !v.is_finite()) {
|
||||
m.x0.truncate(off);
|
||||
continue;
|
||||
@@ -128,6 +315,129 @@ impl Model {
|
||||
(Shape::Poly { n, .. }, Sub::End) => p2(x, o + 2 * n.checked_sub(1)?),
|
||||
(Shape::Poly { .. }, Sub::Mid) => None,
|
||||
(Shape::Point, Sub::Whole | Sub::Start | Sub::Center) => p2(x, o),
|
||||
(Shape::Ellipse { .. }, Sub::Center) => p2(x, o),
|
||||
(Shape::Ellipse { .. }, Sub::Vertex(i)) => {
|
||||
// Axis end points: +major, +minor, −major, −minor.
|
||||
let e = self.ell_at(x, o, false)?;
|
||||
Some(match i {
|
||||
0 => e.c + e.mj,
|
||||
1 => e.c + e.minor(),
|
||||
2 => e.c - e.mj,
|
||||
3 => e.c - e.minor(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
(Shape::Ellipse { arc: true }, Sub::Start | Sub::End | Sub::Mid) => {
|
||||
let e = self.ell_at(x, o, true)?;
|
||||
Some(e.at(match r.sub {
|
||||
Sub::Start => e.t0,
|
||||
Sub::End => e.t1,
|
||||
_ => e.t0 + ccw_sweep(e.t0, e.t1) / 2.0,
|
||||
}))
|
||||
}
|
||||
(Shape::Spline { n, .. }, Sub::Vertex(i)) => {
|
||||
let i = i as usize;
|
||||
if i < n { p2(x, o + 2 * i) } else { None }
|
||||
}
|
||||
(Shape::Spline { ends: true, .. }, Sub::Start) => p2(x, o),
|
||||
(Shape::Spline { n, ends: true, .. }, Sub::End) => p2(x, o + 2 * n.checked_sub(1)?),
|
||||
(Shape::Insert { .. }, Sub::Whole | Sub::Start | Sub::Center) => p2(x, o),
|
||||
(Shape::Insert { n }, Sub::Vertex(i)) => {
|
||||
let i = i as usize;
|
||||
if i >= n {
|
||||
return None;
|
||||
}
|
||||
let q = *self.rigid.get(&s.handle)?.get(i)?;
|
||||
Some(p2(x, o)? + q.rotate(*x.get(o + 2)?))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ell_at(&self, x: &[f64], o: usize, arc: bool) -> Option<Ell> {
|
||||
let (t0, t1) = if arc { (*x.get(o + 5)?, *x.get(o + 6)?) } else { (0.0, std::f64::consts::TAU) };
|
||||
Some(Ell { c: p2(x, o)?, mj: p2(x, o + 2)?, ratio: *x.get(o + 4)?, t0, t1, arc })
|
||||
}
|
||||
|
||||
/// An ellipse-like reference (ellipse or elliptical arc).
|
||||
pub fn ellipse(&self, x: &[f64], r: &GeomRef) -> Option<Ell> {
|
||||
let s = self.slot(r.handle)?;
|
||||
match (s.shape, r.sub) {
|
||||
(Shape::Ellipse { arc }, Sub::Whole) => self.ell_at(x, s.off, arc),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this reference (any part of) a spline?
|
||||
pub fn is_spline(&self, r: &GeomRef) -> bool {
|
||||
self.slot(r.handle).is_some_and(|s| matches!(s.shape, Shape::Spline { .. }))
|
||||
}
|
||||
|
||||
/// The spline of a reference with the defining points taken from `x`.
|
||||
fn spline(&self, x: &[f64], s: &Slot) -> Option<GSpline> {
|
||||
let Shape::Spline { n, fit, .. } = s.shape else { return None };
|
||||
let t = self.splines.get(&s.handle)?;
|
||||
let pts = (0..n).map(|i| p2(x, s.off + 2 * i)).collect::<Option<Vec<_>>>()?;
|
||||
Some(if fit {
|
||||
t.refit(&pts, t.closed)
|
||||
} else {
|
||||
let mut sp = t.clone();
|
||||
sp.control = pts;
|
||||
sp
|
||||
})
|
||||
}
|
||||
|
||||
/// The start (`at_end` false) or end of a curve reference, in the curve's own direction:
|
||||
/// lines and polyline segments, arcs, elliptical arcs and open splines. A polyline's
|
||||
/// `start`/`end` are its first and last segments' outer ends.
|
||||
pub fn end_frame(&self, x: &[f64], r: &GeomRef, at_end: bool) -> Option<Frame> {
|
||||
let s = self.slot(r.handle)?;
|
||||
let o = s.off;
|
||||
let seg = match (s.shape, r.sub) {
|
||||
(Shape::Poly { .. }, Sub::Start) => Some(GeomRef::new(r.handle, Sub::Segment(0))),
|
||||
(Shape::Poly { n, closed: false }, Sub::End) => Some(GeomRef::new(r.handle, Sub::Segment(n.checked_sub(2)? as u32))),
|
||||
(Shape::Line, Sub::Start | Sub::End) => Some(GeomRef::whole(r.handle)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((a, b)) = self.line(x, &seg.unwrap_or(*r)) {
|
||||
let d = b - a;
|
||||
let l = d.len();
|
||||
if crate::curves::not_above(l, 1e-300) {
|
||||
return None;
|
||||
}
|
||||
return Some(Frame { p: if at_end { b } else { a }, t: d * (1.0 / l), k: 0.0 });
|
||||
}
|
||||
match (s.shape, r.sub) {
|
||||
(Shape::Arc, Sub::Whole | Sub::Start | Sub::End) => {
|
||||
let (c, rad) = (p2(x, o)?, *x.get(o + 2)?);
|
||||
let a = *x.get(if at_end { o + 4 } else { o + 3 })?;
|
||||
if crate::curves::not_above(rad.abs(), 1e-300) {
|
||||
return None;
|
||||
}
|
||||
let (p, d1) = crate::curves::circle_at(c, rad, a);
|
||||
Some(Frame { p, t: d1.normalized(), k: 1.0 / rad })
|
||||
}
|
||||
(Shape::Ellipse { arc: true }, Sub::Whole | Sub::Start | Sub::End) => {
|
||||
let e = self.ell_at(x, o, true)?;
|
||||
e.frame(if at_end { e.t1 } else { e.t0 })
|
||||
}
|
||||
(Shape::Spline { ends: true, .. }, Sub::Whole | Sub::Start | Sub::End) => spline_end(&self.spline(x, s)?, at_end),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Squared distance of a block reference's farthest rigid point from its insertion point.
|
||||
pub fn rigid_extent2(&self, h: Handle) -> f64 {
|
||||
self.rigid.get(&h).map_or(0.0, |v| v.iter().map(|q| q.len2()).fold(0.0, f64::max))
|
||||
}
|
||||
|
||||
/// Where to draw a glyph for a reference that is not a point, line or circle.
|
||||
pub fn anchor(&self, x: &[f64], r: &GeomRef) -> Option<Vec2> {
|
||||
let s = self.slot(r.handle)?;
|
||||
match s.shape {
|
||||
Shape::Ellipse { .. } => self.ell_at(x, s.off, false).map(|e| e.c + e.minor()),
|
||||
Shape::Spline { n, .. } => p2(x, s.off + 2 * (n / 2)),
|
||||
Shape::Insert { .. } => p2(x, s.off),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -176,6 +486,18 @@ impl Model {
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of an object a Fix locks directly (ends, centre, vertices, insertion point).
|
||||
pub fn point_refs(&self, h: Handle) -> Vec<GeomRef> {
|
||||
let Some(s) = self.slot(h) else { return Vec::new() };
|
||||
let at = |sub: Sub| GeomRef { handle: h, sub };
|
||||
match s.shape {
|
||||
Shape::Line => vec![at(Sub::Start), at(Sub::End)],
|
||||
Shape::Point => vec![at(Sub::Whole)],
|
||||
Shape::Circle | Shape::Arc | Shape::Ellipse { .. } | Shape::Insert { .. } => vec![at(Sub::Center)],
|
||||
Shape::Poly { n, .. } | Shape::Spline { n, .. } => (0..n).filter_map(|i| u32::try_from(i).ok()).map(|i| at(Sub::Vertex(i))).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters a Fix on this reference locks directly. `None` when the reference is a derived
|
||||
/// point (fixed through a residual instead).
|
||||
pub fn lock_indices(&self, r: &GeomRef) -> Option<Vec<usize>> {
|
||||
@@ -193,11 +515,67 @@ impl Model {
|
||||
let (a, b) = Self::seg(n, closed, i as usize)?;
|
||||
vec![o + 2 * a, o + 2 * a + 1, o + 2 * b, o + 2 * b + 1]
|
||||
}
|
||||
(Shape::Ellipse { .. } | Shape::Insert { .. }, Sub::Center) => vec![o, o + 1],
|
||||
(Shape::Insert { .. }, Sub::Start) => vec![o, o + 1],
|
||||
(Shape::Spline { n, .. }, Sub::Vertex(i)) if (i as usize) < n => vec![o + 2 * i as usize, o + 2 * i as usize + 1],
|
||||
(Shape::Spline { ends: true, .. }, Sub::Start) => vec![o, o + 1],
|
||||
(Shape::Spline { n, ends: true, .. }, Sub::End) if n > 0 => vec![o + 2 * (n - 1), o + 2 * (n - 1) + 1],
|
||||
_ => return None,
|
||||
};
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// Can `write_back` store `x` as it is? An ellipse keeps 0 < ratio <= 1, its major axis the
|
||||
/// longer one: a solution past that is stored with its axes swapped or its minor axis
|
||||
/// mirrored (see [`Model::stored_form`]), which renumbers the axis ends.
|
||||
pub fn storable(&self, x: &[f64]) -> bool {
|
||||
self.slots.iter().all(|s| match s.shape {
|
||||
Shape::Ellipse { .. } => x.get(s.off + 4).is_some_and(|r| *r > 0.0 && *r <= 1.0 + RATIO_TOL),
|
||||
_ => true,
|
||||
})
|
||||
}
|
||||
|
||||
/// `x` with every ellipse re-expressed as [`Model::write_back`] stores it (the same curve with
|
||||
/// the major axis the longer one, a full ellipse's negative ratio made positive), so the
|
||||
/// constraints can be checked against what would be stored. `None` when an elliptical arc has
|
||||
/// a negative ratio or an ellipse a zero one.
|
||||
pub fn stored_form(&self, x: &[f64]) -> Option<Vec<f64>> {
|
||||
let mut xc = x.to_vec();
|
||||
for s in &self.slots {
|
||||
let Shape::Ellipse { arc } = s.shape else { continue };
|
||||
let o = s.off;
|
||||
let mut ratio = *x.get(o + 4)?;
|
||||
if ratio < 0.0 && !arc {
|
||||
ratio = -ratio;
|
||||
}
|
||||
if ratio <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
if ratio > 1.0 + RATIO_TOL {
|
||||
let major = p2(x, o + 2)?.perp() * ratio;
|
||||
*xc.get_mut(o + 2)? = major.x;
|
||||
*xc.get_mut(o + 3)? = major.y;
|
||||
ratio = 1.0 / ratio;
|
||||
if arc {
|
||||
*xc.get_mut(o + 5)? -= std::f64::consts::FRAC_PI_2;
|
||||
*xc.get_mut(o + 6)? -= std::f64::consts::FRAC_PI_2;
|
||||
}
|
||||
}
|
||||
*xc.get_mut(o + 4)? = ratio;
|
||||
}
|
||||
Some(xc)
|
||||
}
|
||||
|
||||
/// The parameter `stored_form` gives the point at parameter `t` on ellipse `h` (unchanged for
|
||||
/// any other object): `-t` where a negative ratio was made positive, a quarter turn back where
|
||||
/// the axes were swapped.
|
||||
pub fn stored_t(&self, x: &[f64], h: Handle, t: f64) -> f64 {
|
||||
let Some(s) = self.slot(h) else { return t };
|
||||
let (Shape::Ellipse { .. }, Some(&ratio)) = (s.shape, x.get(s.off + 4)) else { return t };
|
||||
let (t, ratio) = if ratio < 0.0 { (-t, -ratio) } else { (t, ratio) };
|
||||
if ratio > 1.0 + RATIO_TOL { t - std::f64::consts::FRAC_PI_2 } else { t }
|
||||
}
|
||||
|
||||
/// Write solved parameters back. Returns the handles that moved.
|
||||
pub fn write_back(&self, d: &mut Drawing, x: &[f64]) -> Vec<Handle> {
|
||||
let mut moved = Vec::new();
|
||||
@@ -211,6 +589,13 @@ impl Model {
|
||||
continue;
|
||||
}
|
||||
let shape = s.shape;
|
||||
// A control-point spline loses its fit data once its control points move.
|
||||
let spline = self.spline(x, s).map(|mut sp| {
|
||||
if matches!(shape, Shape::Spline { fit: false, .. }) {
|
||||
sp.fit.clear();
|
||||
}
|
||||
sp
|
||||
});
|
||||
let ok = d.modify_entity(s.handle, |e| match (&mut e.kind, shape) {
|
||||
(EntityKind::Line(l), Shape::Line) => {
|
||||
if let [ax, ay, bx, by] = new {
|
||||
@@ -229,11 +614,14 @@ impl Model {
|
||||
}
|
||||
(EntityKind::Arc(a), Shape::Arc) => {
|
||||
if let [cx, cy, r, s0, s1] = new {
|
||||
// A negative radius puts every point opposite its angle: turning both
|
||||
// ends half a turn keeps the same points with a positive radius.
|
||||
let turn = if *r < 0.0 { std::f64::consts::PI } else { 0.0 };
|
||||
a.center.x = *cx;
|
||||
a.center.y = *cy;
|
||||
a.radius = r.abs().max(1e-12);
|
||||
a.start = cadcraft_geom::norm_angle(*s0);
|
||||
a.end = cadcraft_geom::norm_angle(*s1);
|
||||
a.start = cadcraft_geom::norm_angle(*s0 + turn);
|
||||
a.end = cadcraft_geom::norm_angle(*s1 + turn);
|
||||
}
|
||||
}
|
||||
(EntityKind::LwPolyline(p), Shape::Poly { n, .. }) if p.vertices.len() == n => {
|
||||
@@ -249,6 +637,48 @@ impl Model {
|
||||
p.p.y = *py;
|
||||
}
|
||||
}
|
||||
(EntityKind::Ellipse(el), Shape::Ellipse { arc }) => {
|
||||
if let [cx, cy, mx, my, ratio, rest @ ..] = new {
|
||||
let (mut major, mut ratio) = (Vec2::new(*mx, *my), ratio.abs());
|
||||
let (mut t0, mut t1) = match rest {
|
||||
[a, b] if arc => (*a, *b),
|
||||
_ => (el.start, el.end),
|
||||
};
|
||||
// Keep the stored form: the major axis is the longer one. `storable` lets a
|
||||
// solved ratio exceed 1 only by rounding: that is a circle, not a swap.
|
||||
if ratio > 1.0 + RATIO_TOL {
|
||||
major = major.perp() * ratio;
|
||||
ratio = 1.0 / ratio;
|
||||
if arc {
|
||||
t0 -= std::f64::consts::FRAC_PI_2;
|
||||
t1 -= std::f64::consts::FRAC_PI_2;
|
||||
}
|
||||
}
|
||||
if major.len() > 1e-12 {
|
||||
el.center.x = *cx;
|
||||
el.center.y = *cy;
|
||||
el.major.x = major.x;
|
||||
el.major.y = major.y;
|
||||
el.ratio = ratio.clamp(1e-9, 1.0);
|
||||
if arc {
|
||||
el.start = cadcraft_geom::norm_angle(t0);
|
||||
el.end = cadcraft_geom::norm_angle(t1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(EntityKind::Spline(sp), Shape::Spline { .. }) => {
|
||||
if let Some(rebuilt) = spline.as_ref() {
|
||||
*sp = rebuilt.clone();
|
||||
}
|
||||
}
|
||||
(EntityKind::Insert(ins), Shape::Insert { .. }) => {
|
||||
if let [ix, iy, rot] = new {
|
||||
ins.insert.x = *ix;
|
||||
ins.insert.y = *iy;
|
||||
ins.rotation = cadcraft_geom::norm_angle(*rot);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
if ok.is_ok() {
|
||||
@@ -258,3 +688,60 @@ impl Model {
|
||||
moved
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
use cadcraft_doc::{Block, Common, Entity, Line, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Writing an unchanged model back leaves partial rational weights and the original spline geometry intact.
|
||||
#[test]
|
||||
fn write_back_keeps_partial_rational_weights() {
|
||||
let mut drawing = Drawing::default();
|
||||
let mut spline = GSpline::from_control(vec![Vec2::ZERO, Vec2::new(1.0, 2.0), Vec2::new(3.0, 0.0)], 2);
|
||||
spline.weights = vec![2.0, 0.5];
|
||||
let h = drawing.add(&Space::Model, Common::default(), EntityKind::Spline(spline.clone())).unwrap();
|
||||
let model = Model::build(&drawing, &[h]);
|
||||
model.write_back(&mut drawing, &model.x0);
|
||||
let EntityKind::Spline(after) = &drawing.entity(h).unwrap().kind else { panic!("spline") };
|
||||
assert_eq!(after.weights, spline.weights);
|
||||
for i in 0..=10 {
|
||||
assert!(after.eval(i as f64 / 10.0).near(spline.eval(i as f64 / 10.0), 1e-12));
|
||||
}
|
||||
}
|
||||
|
||||
/// A second model receives no sampled block points after the first model spends the shared member budget.
|
||||
#[test]
|
||||
fn rigid_sampling_budget_is_shared_between_models() {
|
||||
let mut d = Drawing::default();
|
||||
let mut block = Block::new("BAR");
|
||||
for _ in 0..3 {
|
||||
block.entities.push(Entity {
|
||||
handle: d.new_handle(),
|
||||
common: Common::default(),
|
||||
kind: EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }),
|
||||
});
|
||||
}
|
||||
d.blocks.insert("BAR".into(), Arc::new(block));
|
||||
let ins = Insert {
|
||||
block: "BAR".into(),
|
||||
insert: Vec3::ZERO,
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
};
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let mut budget = 2;
|
||||
let first = Model::build_budgeted(&d, &[h], &mut budget);
|
||||
assert_eq!(first.rigid[&h].len(), 4);
|
||||
assert_eq!(budget, 0);
|
||||
let next = Model::build_budgeted(&d, &[h], &mut budget);
|
||||
assert!(next.rigid[&h].is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,12 @@
|
||||
use cadcraft_doc::{Constraint, ConstraintKind, DistAxis, GeomRef};
|
||||
use cadcraft_geom::Vec2;
|
||||
|
||||
use crate::curves::circle_at;
|
||||
use crate::model::Model;
|
||||
|
||||
/// Contact parameter samples per curve when guessing where two curves touch.
|
||||
const CONTACT_SAMPLES: usize = 72;
|
||||
|
||||
/// How a constraint's references were interpreted (decided once from the starting geometry).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum Form {
|
||||
@@ -36,10 +40,38 @@ pub(crate) enum Form {
|
||||
C1,
|
||||
/// Arc sweep (angular on an arc).
|
||||
ArcSweep,
|
||||
/// Two lines measured along the rays from their intersection to each line's far end, the
|
||||
/// angle the dimension draws; `rev` marks a line whose far end is its start point.
|
||||
Rays {
|
||||
rev: [bool; 2],
|
||||
},
|
||||
/// Fix of a derived point (residual to an anchor).
|
||||
Anchor(Vec2),
|
||||
/// Fix handled by locking parameters (no rows).
|
||||
Lock,
|
||||
/// Point on an ellipse (refs: point, ellipse).
|
||||
PE {
|
||||
swap: bool,
|
||||
},
|
||||
/// Line tangent to an ellipse.
|
||||
LE {
|
||||
swap: bool,
|
||||
},
|
||||
/// Two curves (circles, arcs, ellipses; at least one ellipse) touching at a contact point
|
||||
/// given by one auxiliary parameter per curve.
|
||||
Contact,
|
||||
/// A spline end on a line, circle, arc or ellipse and tangent to it (`spline`: which
|
||||
/// reference is the spline).
|
||||
EndOn {
|
||||
spline: usize,
|
||||
at_end: bool,
|
||||
},
|
||||
/// Two curve ends joined with a common tangent (G1), and common curvature when `g2`.
|
||||
Join {
|
||||
a_end: bool,
|
||||
b_end: bool,
|
||||
g2: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -53,6 +85,10 @@ pub(crate) struct Built {
|
||||
/// Orientation chosen from the starting geometry (±1).
|
||||
pub sign: f64,
|
||||
pub rows: usize,
|
||||
/// Starting values of auxiliary unknowns (contact parameters), appended to the parameter
|
||||
/// vector at `aux` by [`crate::interpret`].
|
||||
pub aux_init: Vec<f64>,
|
||||
pub aux: usize,
|
||||
}
|
||||
|
||||
fn dir_n(a: Vec2, b: Vec2) -> Vec2 {
|
||||
@@ -61,6 +97,10 @@ fn dir_n(a: Vec2, b: Vec2) -> Vec2 {
|
||||
if l > 1e-12 { d * (1.0 / l) } else { d }
|
||||
}
|
||||
|
||||
fn ray(a: Vec2, b: Vec2, rev: bool) -> Vec2 {
|
||||
if rev { dir_n(b, a) } else { dir_n(a, b) }
|
||||
}
|
||||
|
||||
fn sgn(v: f64) -> f64 {
|
||||
if v < 0.0 { -1.0 } else { 1.0 }
|
||||
}
|
||||
@@ -76,6 +116,16 @@ fn r_at(c: &Constraint, i: usize) -> Option<&GeomRef> {
|
||||
}
|
||||
|
||||
impl Built {
|
||||
/// Estimate spline reconstruction work for endpoint and join residuals; other residual forms add no such cost.
|
||||
pub(crate) fn spline_reconstruct_cost(&self, m: &Model) -> f64 {
|
||||
let cost = |i: usize| self.refs.get(i).map_or(0.0, |r| m.spline_reconstruct_cost(r.handle));
|
||||
match self.form {
|
||||
Form::EndOn { spline, .. } => cost(spline),
|
||||
Form::Join { .. } => cost(0) + cost(1),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpret a constraint against the model at `x`. `target` is the evaluated value for
|
||||
/// dimensional constraints (degrees for angular). Errors explain what references are needed.
|
||||
pub fn new(c: &Constraint, m: &Model, x: &[f64], target: f64) -> Result<Built, String> {
|
||||
@@ -85,7 +135,9 @@ impl Built {
|
||||
let ln = |i: usize| r_at(c, i).and_then(|r| m.line(x, r));
|
||||
let ci = |i: usize| r_at(c, i).and_then(|r| m.circle(x, r));
|
||||
let n = c.refs.len();
|
||||
let mut b = Built { id: c.id, kind: c.kind, refs, form: Form::PP, target, sign: 1.0, rows: 0 };
|
||||
let el = |i: usize| r_at(c, i).and_then(|r| m.ellipse(x, r));
|
||||
let lnx = |i: usize| ln(i).or_else(|| el(i).map(|e| (e.c - e.mj, e.c + e.mj)));
|
||||
let mut b = Built { id: c.id, kind: c.kind, refs, form: Form::PP, target, sign: 1.0, rows: 0, aux_init: Vec::new(), aux: 0 };
|
||||
let need = |what: &str| Err(format!("{} needs {what}", c.kind.name()));
|
||||
match c.kind {
|
||||
K::Coincident => {
|
||||
@@ -103,20 +155,24 @@ impl Built {
|
||||
Form::PC { swap: false }
|
||||
} else if pt(1).is_some() && ci(0).is_some() {
|
||||
Form::PC { swap: true }
|
||||
} else if pt(0).is_some() && el(1).is_some() {
|
||||
Form::PE { swap: false }
|
||||
} else if pt(1).is_some() && el(0).is_some() {
|
||||
Form::PE { swap: true }
|
||||
} else {
|
||||
return need("two points, or a point and a line/circle/arc");
|
||||
return need("two points, or a point and a line/circle/arc/ellipse");
|
||||
};
|
||||
if b.rows == 0 {
|
||||
b.rows = 1;
|
||||
}
|
||||
}
|
||||
K::Horizontal | K::Vertical => {
|
||||
if n == 1 && ln(0).is_some() {
|
||||
if n == 1 && lnx(0).is_some() {
|
||||
b.form = Form::L1;
|
||||
} else if n == 2 && pt(0).is_some() && pt(1).is_some() {
|
||||
b.form = Form::P2;
|
||||
} else {
|
||||
return need("a line or two points");
|
||||
return need("a line, an ellipse or two points");
|
||||
}
|
||||
b.rows = 1;
|
||||
}
|
||||
@@ -128,9 +184,10 @@ impl Built {
|
||||
b.rows = if c.kind == K::Collinear { 2 } else { 1 };
|
||||
}
|
||||
K::Concentric => {
|
||||
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| pt(i));
|
||||
if !(n == 2 && center(0).is_some() && center(1).is_some() && (ci(0).is_some() || ci(1).is_some())) {
|
||||
return need("two circles or arcs");
|
||||
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| el(i).map(|e| e.c)).or_else(|| pt(i));
|
||||
let curve = |i: usize| ci(i).is_some() || el(i).is_some();
|
||||
if !(n == 2 && center(0).is_some() && center(1).is_some() && (curve(0) || curve(1))) {
|
||||
return need("two circles, arcs or ellipses");
|
||||
}
|
||||
b.form = Form::CC;
|
||||
b.rows = 2;
|
||||
@@ -152,6 +209,9 @@ impl Built {
|
||||
if n != 2 {
|
||||
return need("two objects");
|
||||
}
|
||||
if c.refs.iter().any(|r| m.is_spline(r)) {
|
||||
return Self::spline_form(b, m, x);
|
||||
}
|
||||
b.rows = 1;
|
||||
if let (Some((a, bb)), Some((cc, _))) = (ln(0), ci(1)) {
|
||||
b.form = Form::LC { swap: false };
|
||||
@@ -165,10 +225,20 @@ impl Built {
|
||||
let d = c1.dist(c2);
|
||||
b.sign = if d >= r1.abs().max(r2.abs()) { 1.0 } else { -1.0 };
|
||||
b.target = sgn(r1 - r2);
|
||||
} else if let (Some((a, bb)), Some(e)) = (ln(0), el(1)) {
|
||||
b.form = Form::LE { swap: false };
|
||||
b.sign = sgn(dir_n(a, bb).cross(e.c - a));
|
||||
} else if let (Some((a, bb)), Some(e)) = (ln(1), el(0)) {
|
||||
b.form = Form::LE { swap: true };
|
||||
b.sign = sgn(dir_n(a, bb).cross(e.c - a));
|
||||
} else if (ci(0).is_some() || el(0).is_some()) && (ci(1).is_some() || el(1).is_some()) {
|
||||
b.form = Form::Contact;
|
||||
b.rows = 3;
|
||||
b.aux_init = b.contact_guess(m, x).ok_or_else(|| format!("{} could not find where the curves touch", c.kind.name()))?;
|
||||
} else if ln(0).is_some() && ln(1).is_some() && c.kind == K::Smooth {
|
||||
b.form = Form::LL;
|
||||
} else {
|
||||
return need("a line and a circle/arc, or two circles/arcs");
|
||||
return need("a line and a circle/arc/ellipse, two curves, or a spline end and a curve");
|
||||
}
|
||||
}
|
||||
K::Symmetric => {
|
||||
@@ -233,10 +303,15 @@ impl Built {
|
||||
}
|
||||
K::Angular => {
|
||||
b.rows = 1;
|
||||
if n == 2 && ln(0).is_some() && ln(1).is_some() {
|
||||
b.form = Form::LL;
|
||||
let (Some((a1, b1)), Some((a2, b2))) = (ln(0), ln(1)) else { return need("two lines") };
|
||||
let (d1, d2) = (dir_n(a1, b1), dir_n(a2, b2));
|
||||
if let (2, Some((a1, b1)), Some((a2, b2))) = (n, ln(0), ln(1)) {
|
||||
// Start-to-end directions would measure the supplement when a line is drawn
|
||||
// towards the vertex, so use the rays the dimension draws.
|
||||
let rev = match cadcraft_geom::line_line_infinite(a1, b1, a2, b2) {
|
||||
Some((_, t, u)) => [t > 0.5, u > 0.5],
|
||||
None => [false, false],
|
||||
};
|
||||
b.form = Form::Rays { rev };
|
||||
let (d1, d2) = (ray(a1, b1, rev[0]), ray(a2, b2, rev[1]));
|
||||
b.sign = sgn(d1.cross(d2).atan2(d1.dot(d2)));
|
||||
} else if n == 1 && m.arc_sweep(x, r_at(c, 0).ok_or_else(|| "Angular needs references".to_string())?).is_some() {
|
||||
b.form = Form::ArcSweep;
|
||||
@@ -246,7 +321,7 @@ impl Built {
|
||||
b.target = target.to_radians();
|
||||
// Two lines measure a signed angle in [-180, 180] and the sign is re-read from the geometry, so a larger
|
||||
// target would flip the sign once solved and never be satisfied; only an arc sweep can reach a full turn.
|
||||
let max = if b.form == Form::LL { std::f64::consts::PI } else { std::f64::consts::TAU };
|
||||
let max = if matches!(b.form, Form::Rays { .. }) { std::f64::consts::PI } else { std::f64::consts::TAU };
|
||||
if !b.target.is_finite() || b.target.abs() > max {
|
||||
return Err("angle out of range".into());
|
||||
}
|
||||
@@ -257,7 +332,7 @@ impl Built {
|
||||
}
|
||||
b.form = Form::C1;
|
||||
b.rows = 1;
|
||||
if !(target.is_finite() && target > 0.0) {
|
||||
if !target.is_finite() || crate::curves::not_above(target, 0.0) {
|
||||
return Err(format!("{} value must be positive", c.kind.name()));
|
||||
}
|
||||
}
|
||||
@@ -278,8 +353,47 @@ impl Built {
|
||||
let pt = |i: usize| m.point(x, r(i)?);
|
||||
let ln = |i: usize| m.line(x, r(i)?);
|
||||
let ci = |i: usize| m.circle(x, r(i)?);
|
||||
let el = |i: usize| m.ellipse(x, r(i)?);
|
||||
match (self.kind, self.form) {
|
||||
(_, Form::Lock) => {}
|
||||
(_, Form::PE { swap }) => {
|
||||
let (p, e) = if swap { (pt(1)?, el(0)?) } else { (pt(0)?, el(1)?) };
|
||||
out.push(e.on(p));
|
||||
}
|
||||
(_, Form::LE { swap }) => {
|
||||
let ((a, b), e) = if swap { (ln(1)?, el(0)?) } else { (ln(0)?, el(1)?) };
|
||||
let d = dir_n(a, b);
|
||||
out.push(self.sign * d.cross(e.c - a) - e.support(d.perp()));
|
||||
}
|
||||
(_, Form::Contact) => {
|
||||
let (p0, d0) = self.curve_at(m, x, 0, *x.get(self.aux)?)?;
|
||||
let (p1, d1) = self.curve_at(m, x, 1, *x.get(self.aux + 1)?)?;
|
||||
out.extend([p0.x - p1.x, p0.y - p1.y, d0.normalized().cross(d1.normalized())]);
|
||||
}
|
||||
(_, Form::EndOn { spline, at_end }) => {
|
||||
let f = m.end_frame(x, r(spline)?, at_end)?;
|
||||
let o = 1 - spline.min(1);
|
||||
if let Some((a, b)) = ln(o) {
|
||||
let d = dir_n(a, b);
|
||||
out.extend([d.cross(f.p - a), f.t.cross(d)]);
|
||||
} else if let Some((c, rad)) = ci(o) {
|
||||
out.extend([f.p.dist(c) - rad, f.t.dot(dir_n(c, f.p))]);
|
||||
} else {
|
||||
let e = el(o)?;
|
||||
out.extend([e.on(f.p), f.t.dot(e.normal(f.p))]);
|
||||
}
|
||||
}
|
||||
(_, Form::Join { a_end, b_end, g2 }) => {
|
||||
// Orient both so the first curve runs into the joint and the second out of it.
|
||||
let fa = m.end_frame(x, r(0)?, a_end)?;
|
||||
let fb = m.end_frame(x, r(1)?, b_end)?;
|
||||
let fa = if a_end { fa } else { fa.reversed() };
|
||||
let fb = if b_end { fb.reversed() } else { fb };
|
||||
out.extend([fa.p.x - fb.p.x, fa.p.y - fb.p.y, fa.t.cross(fb.t)]);
|
||||
if g2 {
|
||||
out.push(fa.k - fb.k);
|
||||
}
|
||||
}
|
||||
(_, Form::Anchor(a)) => {
|
||||
let p = pt(0)?;
|
||||
out.extend([p.x - a.x, p.y - a.y]);
|
||||
@@ -297,7 +411,7 @@ impl Built {
|
||||
out.push(p.dist(c) - rad);
|
||||
}
|
||||
(K::Horizontal | K::Vertical, f) => {
|
||||
let (a, b) = if f == Form::L1 { ln(0)? } else { (pt(0)?, pt(1)?) };
|
||||
let (a, b) = if f == Form::L1 { ln(0).or_else(|| el(0).map(|e| (e.c - e.mj, e.c + e.mj)))? } else { (pt(0)?, pt(1)?) };
|
||||
out.push(if self.kind == K::Horizontal { a.y - b.y } else { a.x - b.x });
|
||||
}
|
||||
(K::Parallel | K::Smooth, Form::LL) => {
|
||||
@@ -314,7 +428,7 @@ impl Built {
|
||||
out.extend([d.cross(a2 - a1), d.cross(b2 - a1)]);
|
||||
}
|
||||
(K::Concentric, _) => {
|
||||
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| pt(i));
|
||||
let center = |i: usize| ci(i).map(|(c, _)| c).or_else(|| el(i).map(|e| e.c)).or_else(|| pt(i));
|
||||
let (p, q) = (center(0)?, center(1)?);
|
||||
out.extend([p.x - q.x, p.y - q.y]);
|
||||
}
|
||||
@@ -371,9 +485,9 @@ impl Built {
|
||||
(K::Angular, Form::ArcSweep) => {
|
||||
out.push(m.arc_sweep(x, r(0)?)? - self.target);
|
||||
}
|
||||
(K::Angular, _) => {
|
||||
(K::Angular, Form::Rays { rev }) => {
|
||||
let ((a1, b1), (a2, b2)) = (ln(0)?, ln(1)?);
|
||||
let (d1, d2) = (dir_n(a1, b1), dir_n(a2, b2));
|
||||
let (d1, d2) = (ray(a1, b1, rev[0]), ray(a2, b2, rev[1]));
|
||||
out.push(wrap(d1.cross(d2).atan2(d1.dot(d2)) - self.sign * self.target));
|
||||
}
|
||||
(K::Radius, _) => out.push(ci(0)?.1 - self.target),
|
||||
@@ -383,6 +497,95 @@ impl Built {
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Point and derivative of curve reference `i` (circle, arc or ellipse) at parameter `t`.
|
||||
fn curve_at(&self, m: &Model, x: &[f64], i: usize, t: f64) -> Option<(Vec2, Vec2)> {
|
||||
let r = self.refs.get(i)?;
|
||||
if let Some((c, rad)) = m.circle(x, r) {
|
||||
return Some(circle_at(c, rad, t));
|
||||
}
|
||||
let e = m.ellipse(x, r)?;
|
||||
Some((e.at(t), e.d1(t)))
|
||||
}
|
||||
|
||||
/// Contact parameters where two curves come closest (sampled), for [`Form::Contact`].
|
||||
fn contact_guess(&self, m: &Model, x: &[f64]) -> Option<Vec<f64>> {
|
||||
let step = std::f64::consts::TAU / CONTACT_SAMPLES as f64;
|
||||
let s0: Vec<(f64, Vec2)> = (0..CONTACT_SAMPLES).filter_map(|k| Some((k as f64 * step, self.curve_at(m, x, 0, k as f64 * step)?.0))).collect();
|
||||
let s1: Vec<(f64, Vec2)> = (0..CONTACT_SAMPLES).filter_map(|k| Some((k as f64 * step, self.curve_at(m, x, 1, k as f64 * step)?.0))).collect();
|
||||
let mut best: Option<(f64, f64, f64)> = None;
|
||||
for (t0, p0) in &s0 {
|
||||
for (t1, p1) in &s1 {
|
||||
let d = p0.dist(*p1);
|
||||
if d.is_finite() && best.is_none_or(|b| d < b.0) {
|
||||
best = Some((d, *t0, *t1));
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, a, b)| vec![a, b])
|
||||
}
|
||||
|
||||
/// Tangent or Smooth with a spline: the spline end and the other curve's nearest end are
|
||||
/// joined (Smooth: G2; Tangent between splines: G1), or the spline's end touches a line,
|
||||
/// circle, arc or ellipse tangentially. A `start`/`end` reference picks the end.
|
||||
fn spline_form(mut b: Built, m: &Model, x: &[f64]) -> Result<Built, String> {
|
||||
let (Some(r0), Some(r1)) = (b.refs.first().copied(), b.refs.get(1).copied()) else {
|
||||
return Err(format!("{} needs two objects", b.kind.name()));
|
||||
};
|
||||
let ends = |r: &GeomRef| -> &'static [bool] {
|
||||
match r.sub {
|
||||
cadcraft_doc::Sub::Start => &[false],
|
||||
cadcraft_doc::Sub::End => &[true],
|
||||
_ => &[false, true],
|
||||
}
|
||||
};
|
||||
let join = b.kind == ConstraintKind::Smooth || (m.is_spline(&r0) && m.is_spline(&r1));
|
||||
if join {
|
||||
let mut best: Option<(f64, bool, bool)> = None;
|
||||
for &ea in ends(&r0) {
|
||||
for &eb in ends(&r1) {
|
||||
if let (Some(fa), Some(fb)) = (m.end_frame(x, &r0, ea), m.end_frame(x, &r1, eb)) {
|
||||
let d = fa.p.dist(fb.p);
|
||||
if d.is_finite() && best.is_none_or(|bb| d < bb.0) {
|
||||
best = Some((d, ea, eb));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, a_end, b_end)) = best else {
|
||||
return Err(format!("{} needs an open spline and a line, arc, elliptical arc, polyline segment or open spline", b.kind.name()));
|
||||
};
|
||||
let g2 = b.kind == ConstraintKind::Smooth;
|
||||
b.form = Form::Join { a_end, b_end, g2 };
|
||||
b.rows = if g2 { 4 } else { 3 };
|
||||
return Ok(b);
|
||||
}
|
||||
let (si, rs, ro) = if m.is_spline(&r0) { (0, r0, r1) } else { (1, r1, r0) };
|
||||
let dist = |p: Vec2| -> Option<f64> {
|
||||
if let Some((a, bb)) = m.line(x, &ro) {
|
||||
Some(dir_n(a, bb).cross(p - a).abs())
|
||||
} else if let Some((c, rad)) = m.circle(x, &ro) {
|
||||
Some((p.dist(c) - rad).abs())
|
||||
} else {
|
||||
m.ellipse(x, &ro).map(|e| e.on(p).abs())
|
||||
}
|
||||
};
|
||||
let mut best: Option<(f64, bool)> = None;
|
||||
for &e in ends(&rs) {
|
||||
if let Some(d) = m.end_frame(x, &rs, e).and_then(|f| dist(f.p))
|
||||
&& d.is_finite()
|
||||
&& best.is_none_or(|bb| d < bb.0)
|
||||
{
|
||||
best = Some((d, e));
|
||||
}
|
||||
}
|
||||
let Some((_, at_end)) = best else {
|
||||
return Err("Tangent needs an open spline and a line, circle, arc, ellipse or spline".into());
|
||||
};
|
||||
b.form = Form::EndOn { spline: si, at_end };
|
||||
b.rows = 2;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// The current measured value (degrees for angular), for dimensional constraints.
|
||||
pub fn measure(&self, m: &Model, x: &[f64]) -> f64 {
|
||||
let mut b = self.clone();
|
||||
|
||||
@@ -305,7 +305,7 @@ fn keep_option_moves_the_other_entity() {
|
||||
let mut d = Drawing::default();
|
||||
let a = line(&mut d, (0.0, 0.0), (10.0, 0.0));
|
||||
let b = line(&mut d, (0.0, 2.0), (10.0, 4.0));
|
||||
add(&mut d, con(ConstraintKind::Parallel, &[w(a), w(b)]), &SolveOptions { keep: vec![a], prefer_move: vec![b] }).unwrap();
|
||||
add(&mut d, con(ConstraintKind::Parallel, &[w(a), w(b)]), &SolveOptions { keep: vec![a], prefer_move: vec![b], ..Default::default() }).unwrap();
|
||||
let (a0, a1) = ln(&d, a);
|
||||
assert!(a0.near(Vec2::new(0.0, 0.0), 1e-3) && a1.near(Vec2::new(10.0, 0.0), 1e-3), "{a0:?} {a1:?}");
|
||||
}
|
||||
@@ -412,7 +412,7 @@ fn glyphs_and_residuals() {
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!all_satisfied(&d));
|
||||
let r = solve(&mut d, &SolveOptions { keep: vec![], prefer_move: vec![] }).unwrap();
|
||||
let r = solve(&mut d, &SolveOptions::default()).unwrap();
|
||||
assert_eq!(r.moved, vec![a]);
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
@@ -463,3 +463,29 @@ fn set_parameter_rejects_out_of_domain_dimension() {
|
||||
set_parameter(&mut d, "rad1", "2", &opts).unwrap();
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
|
||||
/// The solver may meet a coincidence with a negative arc radius; the stored arc must still put
|
||||
/// the referenced point where the solver did (issue #703), through `add` and through `solve`.
|
||||
#[test]
|
||||
fn arc_solved_with_a_negative_radius_keeps_its_points() {
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
// (arc centre, radius, start, end, point): a semicircle with the point behind it, and the
|
||||
// asymmetric case from the issue.
|
||||
let cases = [((0.0, 0.0), 1.0, -FRAC_PI_2, FRAC_PI_2, (-5.0, 0.0)), ((6.694, -0.686), 0.62075, 3.4824, 1.1766, (-7.562, 4.946))];
|
||||
for (c, r, a0, a1, p) in cases {
|
||||
for through_solve in [false, true] {
|
||||
let mut d = Drawing::default();
|
||||
let a = arc(&mut d, c, r, a0, a1);
|
||||
let q = add_e(&mut d, EntityKind::Point(DPoint { p: v(p.0, p.1), angle: 0.0 }));
|
||||
let k = con(ConstraintKind::Coincident, &[s(a, Sub::Mid), w(q)]);
|
||||
if through_solve {
|
||||
d.constraints.push(Constraint { id: 1, ..k });
|
||||
solve(&mut d, &SolveOptions::default()).unwrap();
|
||||
} else {
|
||||
ok(&mut d, k);
|
||||
}
|
||||
assert!(all_satisfied(&d), "{c:?} solve {through_solve}: {:?}", residuals(&d));
|
||||
assert!(circ(&d, a).1 > 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
//! Degrees of freedom, redundancy hints, ellipse/spline/block geometry and Smooth (G2).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_constraints::{DofStatus, SolveError, SolveOptions, add, all_satisfied, dof, solve};
|
||||
use cadcraft_doc::{
|
||||
Arc as DArc, Block, Circle as DCircle, Common, Constraint, ConstraintKind as K, DistAxis, Drawing, Ellipse as DEllipse, Entity, EntityKind,
|
||||
GeomRef, Handle, Insert, Line as DLine, Point as DPoint, Space, Sub,
|
||||
};
|
||||
use cadcraft_geom::{Spline as GSpline, Vec2, Vec3};
|
||||
|
||||
fn v(x: f64, y: f64) -> Vec3 {
|
||||
Vec3::new(x, y, 0.0)
|
||||
}
|
||||
fn put(d: &mut Drawing, k: EntityKind) -> Handle {
|
||||
d.add(&Space::Model, Common::default(), k).unwrap()
|
||||
}
|
||||
fn line(d: &mut Drawing, a: (f64, f64), b: (f64, f64)) -> Handle {
|
||||
put(d, EntityKind::Line(DLine { a: v(a.0, a.1), b: v(b.0, b.1) }))
|
||||
}
|
||||
fn circle(d: &mut Drawing, c: (f64, f64), r: f64) -> Handle {
|
||||
put(d, EntityKind::Circle(DCircle { center: v(c.0, c.1), radius: r }))
|
||||
}
|
||||
fn point(d: &mut Drawing, p: (f64, f64)) -> Handle {
|
||||
put(d, EntityKind::Point(DPoint { p: v(p.0, p.1), angle: 0.0 }))
|
||||
}
|
||||
fn ellipse(d: &mut Drawing, c: (f64, f64), major: (f64, f64), ratio: f64, start: f64, end: f64) -> Handle {
|
||||
put(d, EntityKind::Ellipse(DEllipse { center: v(c.0, c.1), major: v(major.0, major.1), ratio, start, end }))
|
||||
}
|
||||
fn spline(d: &mut Drawing, pts: &[(f64, f64)]) -> Handle {
|
||||
let s = GSpline::from_control(pts.iter().map(|p| Vec2::new(p.0, p.1)).collect(), 3);
|
||||
put(d, EntityKind::Spline(s))
|
||||
}
|
||||
fn con(kind: K, refs: &[GeomRef]) -> Constraint {
|
||||
Constraint { id: 0, kind, refs: refs.to_vec(), name: String::new(), expr: String::new() }
|
||||
}
|
||||
fn dim(kind: K, refs: &[GeomRef], expr: &str) -> Constraint {
|
||||
Constraint { id: 0, kind, refs: refs.to_vec(), name: String::new(), expr: expr.into() }
|
||||
}
|
||||
fn w(h: Handle) -> GeomRef {
|
||||
GeomRef::whole(h)
|
||||
}
|
||||
fn s(h: Handle, sub: Sub) -> GeomRef {
|
||||
GeomRef::new(h, sub)
|
||||
}
|
||||
fn ok(d: &mut Drawing, c: Constraint) -> u32 {
|
||||
let k = c.kind;
|
||||
add(d, c, &SolveOptions::default()).unwrap_or_else(|e| panic!("{k:?}: {e}"))
|
||||
}
|
||||
fn ends(d: &Drawing, h: Handle) -> (Vec2, Vec2) {
|
||||
match &d.entity(h).unwrap().kind {
|
||||
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
|
||||
_ => panic!("not a line"),
|
||||
}
|
||||
}
|
||||
fn ell(d: &Drawing, h: Handle) -> cadcraft_geom::Ellipse {
|
||||
match &d.entity(h).unwrap().kind {
|
||||
EntityKind::Ellipse(e) => cadcraft_geom::Ellipse { center: e.center.xy(), major: e.major.xy(), ratio: e.ratio, start: e.start, end: e.end },
|
||||
_ => panic!("not an ellipse"),
|
||||
}
|
||||
}
|
||||
fn spl(d: &Drawing, h: Handle) -> GSpline {
|
||||
match &d.entity(h).unwrap().kind {
|
||||
EntityKind::Spline(s) => s.clone(),
|
||||
_ => panic!("not a spline"),
|
||||
}
|
||||
}
|
||||
fn obj_dof(d: &Drawing, h: Handle) -> Option<usize> {
|
||||
let r = dof(d, &[h]).unwrap();
|
||||
r.objects.iter().find(|o| o.handle == h.hex()).and_then(|o| o.dof)
|
||||
}
|
||||
|
||||
/// Signed curvature by sampling a curve near a parameter (central differences).
|
||||
fn curvature(f: impl Fn(f64) -> Vec2, t: f64, h: f64) -> f64 {
|
||||
let (a, b, c) = (f(t - h), f(t), f(t + h));
|
||||
let d1 = (c - a) * (0.5 / h);
|
||||
let d2 = (c - b * 2.0 + a) * (1.0 / (h * h));
|
||||
d1.cross(d2) / d1.len().powi(3)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangle_dof_counts_down_to_fully_constrained() {
|
||||
let mut d = Drawing::default();
|
||||
let l = [
|
||||
line(&mut d, (0.0, 0.0), (10.0, 0.2)),
|
||||
line(&mut d, (10.0, 0.2), (10.1, 5.0)),
|
||||
line(&mut d, (10.1, 5.0), (0.0, 5.0)),
|
||||
line(&mut d, (0.0, 5.0), (0.0, 0.0)),
|
||||
];
|
||||
let r = dof(&d, &[]).unwrap();
|
||||
assert_eq!((r.status, r.dof, r.message.as_str()), (DofStatus::Unconstrained, Some(0), "No constraints"));
|
||||
// An unconstrained line has its four parameters.
|
||||
assert_eq!(obj_dof(&d, l[0]), Some(4));
|
||||
for i in 0..4 {
|
||||
ok(&mut d, con(K::Coincident, &[s(l[i], Sub::End), s(l[(i + 1) % 4], Sub::Start)]));
|
||||
}
|
||||
ok(&mut d, con(K::Horizontal, &[w(l[0])]));
|
||||
ok(&mut d, con(K::Horizontal, &[w(l[2])]));
|
||||
ok(&mut d, con(K::Vertical, &[w(l[1])]));
|
||||
ok(&mut d, con(K::Vertical, &[w(l[3])]));
|
||||
// 16 parameters − 12 equations: translation, width, height.
|
||||
let r = dof(&d, &[]).unwrap();
|
||||
assert_eq!((r.dof, r.status, r.redundant), (Some(4), DofStatus::Under, 0));
|
||||
assert_eq!(r.objects.len(), 4);
|
||||
assert!(r.objects.iter().all(|o| o.params == 4 && o.dof == Some(3) && o.status == DofStatus::Under), "{r:?}");
|
||||
ok(&mut d, con(K::Fix, &[s(l[0], Sub::Start)]));
|
||||
assert_eq!(dof(&d, &[]).unwrap().dof, Some(2));
|
||||
ok(&mut d, dim(K::Distance(DistAxis::Aligned), &[w(l[0])], "12"));
|
||||
// The bottom edge is now fixed; the others still stretch with the height.
|
||||
assert_eq!(obj_dof(&d, l[0]), Some(0));
|
||||
assert_eq!(obj_dof(&d, l[2]), Some(1));
|
||||
ok(&mut d, dim(K::Distance(DistAxis::Aligned), &[w(l[1])], "4"));
|
||||
let r = dof(&d, &[]).unwrap();
|
||||
assert_eq!((r.dof, r.status, r.message.as_str()), (Some(0), DofStatus::Fully, "Fully constrained"));
|
||||
assert!(r.objects.iter().all(|o| o.status == DofStatus::Fully));
|
||||
// A fully constrained rectangle refuses one more dimension, naming the constraints it repeats.
|
||||
let e = add(&mut d, dim(K::Distance(DistAxis::Aligned), &[w(l[3])], "4"), &SolveOptions::default()).unwrap_err();
|
||||
let SolveError::Redundant { ids } = e else { panic!("{e:?}") };
|
||||
assert!(!ids.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redundant_hint_names_the_duplicated_constraints() {
|
||||
let mut d = Drawing::default();
|
||||
let a = line(&mut d, (0.0, 0.0), (10.0, 0.1));
|
||||
let b = line(&mut d, (0.0, 5.0), (10.0, 5.2));
|
||||
let c = line(&mut d, (20.0, 0.0), (20.0, 9.0));
|
||||
let ha = ok(&mut d, con(K::Horizontal, &[w(a)]));
|
||||
let hb = ok(&mut d, con(K::Horizontal, &[w(b)]));
|
||||
let vc = ok(&mut d, con(K::Vertical, &[w(c)]));
|
||||
ok(&mut d, con(K::Coincident, &[s(b, Sub::End), s(c, Sub::Start)]));
|
||||
let before = d.clone();
|
||||
let e = add(&mut d, con(K::Parallel, &[w(a), w(b)]), &SolveOptions::default()).unwrap_err();
|
||||
let SolveError::Redundant { ids } = &e else { panic!("{e:?}") };
|
||||
assert!(ids.contains(&ha) && ids.contains(&hb), "{ids:?}");
|
||||
assert!(!ids.contains(&vc), "{ids:?}");
|
||||
assert!(e.to_string().contains(&format!("#{ha}")), "{e}");
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_constrained_drawing_is_reported() {
|
||||
let mut d = Drawing::default();
|
||||
let a = line(&mut d, (0.0, 0.0), (10.0, 0.0));
|
||||
ok(&mut d, con(K::Horizontal, &[w(a)]));
|
||||
// A file can hold a duplicate the command would have refused.
|
||||
d.constraints.push(Constraint { id: 99, ..con(K::Horizontal, &[w(a)]) });
|
||||
let r = dof(&d, &[]).unwrap();
|
||||
assert_eq!((r.status, r.redundant), (DofStatus::Over, 1));
|
||||
assert!(r.message.starts_with("Over-constrained"), "{}", r.message);
|
||||
assert_eq!(r.objects[0].status, DofStatus::Over);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_constraints() {
|
||||
let mut d = Drawing::default();
|
||||
let e = ellipse(&mut d, (0.0, 0.0), (6.0, 0.5), 0.5, 0.0, std::f64::consts::TAU);
|
||||
assert_eq!(obj_dof(&d, e), Some(5));
|
||||
// Horizontal applies to the major axis.
|
||||
ok(&mut d, con(K::Horizontal, &[w(e)]));
|
||||
assert!(ell(&d, e).major.y.abs() < 1e-9);
|
||||
// A point on the ellipse.
|
||||
let p = point(&mut d, (0.3, 3.4));
|
||||
ok(&mut d, con(K::Coincident, &[w(p), w(e)]));
|
||||
let g = ell(&d, e);
|
||||
let pp = match &d.entity(p).unwrap().kind {
|
||||
EntityKind::Point(q) => q.p.xy(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let (a, b) = (g.major.len(), g.major.len() * g.ratio);
|
||||
let q = pp - g.center;
|
||||
assert!(((q.x / a).powi(2) + (q.y / b).powi(2) - 1.0).abs() < 1e-7);
|
||||
// Concentric with a circle.
|
||||
let c = circle(&mut d, (0.5, -0.4), 1.0);
|
||||
ok(&mut d, con(K::Concentric, &[w(e), w(c)]));
|
||||
let cc = match &d.entity(c).unwrap().kind {
|
||||
EntityKind::Circle(k) => k.center.xy(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert!(cc.near(ell(&d, e).center, 1e-7));
|
||||
// A line tangent to the ellipse.
|
||||
let l = line(&mut d, (-10.0, 3.6), (10.0, 3.2));
|
||||
ok(&mut d, con(K::Tangent, &[w(l), w(e)]));
|
||||
let (la, lb) = ends(&d, l);
|
||||
let g = ell(&d, e);
|
||||
let n = (lb - la).normalized().perp();
|
||||
let support = (n.dot(g.major).powi(2) + n.dot(g.minor()).powi(2)).sqrt();
|
||||
assert!(((g.center - la).dot(n).abs() - support).abs() < 1e-7);
|
||||
// An axis end point coincides with a line end.
|
||||
let m = line(&mut d, (6.2, 0.3), (9.0, 5.0));
|
||||
ok(&mut d, con(K::Coincident, &[s(e, Sub::Vertex(0)), s(m, Sub::Start)]));
|
||||
let g = ell(&d, e);
|
||||
assert!(ends(&d, m).0.near(g.center + g.major, 1e-7));
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circle_tangent_to_ellipse_and_elliptical_arc_ends() {
|
||||
let mut d = Drawing::default();
|
||||
let e = ellipse(&mut d, (0.0, 0.0), (5.0, 0.0), 0.6, 0.0, std::f64::consts::TAU);
|
||||
ok(&mut d, con(K::Fix, &[w(e)]));
|
||||
let c = circle(&mut d, (7.5, 0.4), 2.0);
|
||||
ok(&mut d, con(K::Tangent, &[w(c), w(e)]));
|
||||
let (cc, r) = match &d.entity(c).unwrap().kind {
|
||||
EntityKind::Circle(k) => (k.center.xy(), k.radius),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
// Closest distance from the circle's centre to the ellipse equals the radius.
|
||||
let g = ell(&d, e);
|
||||
let near = (0..20000).map(|i| g.at_param(i as f64 * std::f64::consts::TAU / 20000.0).dist(cc)).fold(f64::INFINITY, f64::min);
|
||||
assert!((near - r).abs() < 1e-3, "{near} vs {r}");
|
||||
assert!(all_satisfied(&d));
|
||||
// Elliptical arc ends are points.
|
||||
let arc = ellipse(&mut d, (20.0, 0.0), (4.0, 0.0), 0.5, 0.0, std::f64::consts::PI);
|
||||
assert_eq!(obj_dof(&d, arc), Some(7));
|
||||
let l = line(&mut d, (24.3, 0.2), (30.0, 0.0));
|
||||
ok(&mut d, con(K::Coincident, &[s(arc, Sub::Start), s(l, Sub::Start)]));
|
||||
let g = ell(&d, arc);
|
||||
assert!(ends(&d, l).0.near(g.at_param(g.start), 1e-7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_points_tangent_and_smooth_g2() {
|
||||
let mut d = Drawing::default();
|
||||
// Arc to the left of the spline's start.
|
||||
let a = put(&mut d, EntityKind::Arc(DArc { center: v(0.0, 3.0), radius: 3.0, start: std::f64::consts::PI, end: 1.5 * std::f64::consts::PI }));
|
||||
ok(&mut d, con(K::Fix, &[w(a)]));
|
||||
let sp = spline(&mut d, &[(0.1, 0.1), (3.0, 0.4), (6.0, 2.0), (9.0, 2.0)]);
|
||||
assert_eq!(obj_dof(&d, sp), Some(8));
|
||||
ok(&mut d, con(K::Smooth, &[w(sp), w(a)]));
|
||||
let g = spl(&d, sp);
|
||||
let (lo, _) = g.domain();
|
||||
// Joined at the arc's end (0, 0), tangent along +x, curvature 1/3 like the arc.
|
||||
assert!(g.eval(lo).near(Vec2::new(0.0, 0.0), 1e-7), "{:?}", g.eval(lo));
|
||||
let t = (g.eval(lo + 1e-6) - g.eval(lo)).normalized();
|
||||
assert!(t.near(Vec2::new(1.0, 0.0), 1e-4), "{t:?}");
|
||||
let k = curvature(|u| g.eval(u), lo + 1e-3, 1e-4);
|
||||
assert!((k - 1.0 / 3.0).abs() < 2e-2, "curvature {k}");
|
||||
assert!(all_satisfied(&d));
|
||||
// The spline's control points are constraint points.
|
||||
let p = point(&mut d, (9.5, 2.5));
|
||||
ok(&mut d, con(K::Coincident, &[s(sp, Sub::Vertex(3)), w(p)]));
|
||||
let pp = match &d.entity(p).unwrap().kind {
|
||||
EntityKind::Point(q) => q.p.xy(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert!(spl(&d, sp).control[3].near(pp, 1e-7));
|
||||
// Smooth to a line: the far end ends straight.
|
||||
let l = line(&mut d, (9.2, 2.1), (15.0, 3.0));
|
||||
ok(&mut d, con(K::Smooth, &[w(sp), w(l)]));
|
||||
let g = spl(&d, sp);
|
||||
let (_, hi) = g.domain();
|
||||
assert!(g.eval(hi).near(ends(&d, l).0, 1e-7));
|
||||
let k = curvature(|u| g.eval(u), hi - 1e-3, 1e-4);
|
||||
assert!(k.abs() < 2e-2, "curvature at the line {k}");
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_tangent_to_circle_and_fit_spline_smooth() {
|
||||
let mut d = Drawing::default();
|
||||
let c = circle(&mut d, (0.0, 0.0), 2.0);
|
||||
ok(&mut d, con(K::Fix, &[w(c)]));
|
||||
let sp = spline(&mut d, &[(2.1, 0.3), (2.5, 3.0), (5.0, 4.0), (8.0, 4.0)]);
|
||||
ok(&mut d, con(K::Tangent, &[w(sp), w(c)]));
|
||||
let g = spl(&d, sp);
|
||||
let (lo, _) = g.domain();
|
||||
let p = g.eval(lo);
|
||||
assert!((p.len() - 2.0).abs() < 1e-7);
|
||||
let t = (g.eval(lo + 1e-7) - p).normalized();
|
||||
assert!(t.dot(p.normalized()).abs() < 1e-4);
|
||||
// A fit-point spline keeps its fit points and is rebuilt through them.
|
||||
let fit: Vec<Vec2> = [(20.0, 0.0), (23.0, 2.0), (27.0, 1.0), (30.0, 3.0)].iter().map(|p| Vec2::new(p.0, p.1)).collect();
|
||||
let fs = put(&mut d, EntityKind::Spline(GSpline::from_fit_points(&fit)));
|
||||
let l = line(&mut d, (10.0, -1.0), (19.8, 0.2));
|
||||
ok(&mut d, con(K::Fix, &[w(l)]));
|
||||
ok(&mut d, con(K::Smooth, &[w(fs), w(l)]));
|
||||
let g = spl(&d, fs);
|
||||
assert_eq!(g.fit.len(), 4);
|
||||
assert!(g.fit[0].near(Vec2::new(19.8, 0.2), 1e-7));
|
||||
let (lo, _) = g.domain();
|
||||
assert!(g.eval(lo).near(g.fit[0], 1e-9));
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_reference_moves_rigidly() {
|
||||
let mut d = Drawing::default();
|
||||
let mut b = Block::new("BAR");
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity { handle: h, common: Common::default(), kind: EntityKind::Line(DLine { a: v(0.0, 0.0), b: v(4.0, 0.0) }) });
|
||||
d.blocks.insert("BAR".into(), Arc::new(b));
|
||||
let ins = put(
|
||||
&mut d,
|
||||
EntityKind::Insert(Insert {
|
||||
block: "BAR".into(),
|
||||
insert: v(1.0, 1.0),
|
||||
scale: v(1.0, 1.0),
|
||||
rotation: 1.2,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
}),
|
||||
);
|
||||
assert_eq!(obj_dof(&d, ins), Some(3));
|
||||
let p0 = point(&mut d, (10.0, 10.0));
|
||||
let wall = line(&mut d, (10.0, 0.0), (10.0, 20.0));
|
||||
ok(&mut d, con(K::Fix, &[w(p0)]));
|
||||
ok(&mut d, con(K::Fix, &[w(wall)]));
|
||||
// The insertion point onto p0 leaves the turn; the block's far end (rigid point 1) onto the
|
||||
// wall takes it.
|
||||
ok(&mut d, con(K::Coincident, &[w(ins), w(p0)]));
|
||||
assert_eq!(obj_dof(&d, ins), Some(1));
|
||||
ok(&mut d, con(K::Coincident, &[s(ins, Sub::Vertex(1)), w(wall)]));
|
||||
let EntityKind::Insert(i) = &d.entity(ins).unwrap().kind else { panic!() };
|
||||
assert!(i.insert.xy().near(Vec2::new(10.0, 10.0), 1e-7));
|
||||
assert!((i.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-7, "{}", i.rotation);
|
||||
// Both points again would be one equation too many.
|
||||
let p1 = point(&mut d, (10.0, 14.0));
|
||||
ok(&mut d, con(K::Fix, &[w(p1)]));
|
||||
assert!(matches!(add(&mut d, con(K::Coincident, &[s(ins, Sub::Vertex(1)), w(p1)]), &SolveOptions::default()), Err(SolveError::Redundant { .. })));
|
||||
assert_eq!(dof(&d, &[]).unwrap().status, DofStatus::Fully);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_new_geometry_never_panics() {
|
||||
let mut d = Drawing::default();
|
||||
let bad_e = ellipse(&mut d, (0.0, 0.0), (0.0, 0.0), f64::NAN, 0.0, 1.0);
|
||||
let flat_e = ellipse(&mut d, (0.0, 0.0), (1e300, 0.0), 0.0, 0.0, 1.0);
|
||||
let broken = put(&mut d, EntityKind::Spline(GSpline { degree: 7, knots: vec![f64::NAN; 3], control: vec![Vec2::ZERO; 2], ..Default::default() }));
|
||||
let one = put(&mut d, EntityKind::Spline(GSpline::from_control(vec![Vec2::new(1.0, 1.0); 3], 2)));
|
||||
let missing = put(
|
||||
&mut d,
|
||||
EntityKind::Insert(Insert {
|
||||
block: "NOPE".into(),
|
||||
insert: v(0.0, 0.0),
|
||||
scale: v(0.0, f64::INFINITY),
|
||||
rotation: f64::NAN,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
}),
|
||||
);
|
||||
let l = line(&mut d, (0.0, 0.0), (0.0, 0.0));
|
||||
let hs = [bad_e, flat_e, broken, one, missing, l];
|
||||
let kinds = [K::Coincident, K::Concentric, K::Tangent, K::Smooth, K::Horizontal, K::Fix, K::Equal, K::Symmetric, K::Radius];
|
||||
let subs = [Sub::Whole, Sub::Start, Sub::End, Sub::Center, Sub::Vertex(0), Sub::Vertex(3), Sub::Vertex(u32::MAX)];
|
||||
for k in kinds {
|
||||
for (i, h) in hs.iter().enumerate() {
|
||||
for sub in subs {
|
||||
let refs = [s(*h, sub), w(hs[(i + 1) % hs.len()]), w(hs[(i + 2) % hs.len()])];
|
||||
for n in 0..=3 {
|
||||
let _ = add(&mut d, dim(k, &refs[..n], "1"), &SolveOptions::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = solve(&mut d, &SolveOptions::default());
|
||||
let _ = dof(&d, &hs);
|
||||
let _ = dof(&d, &[Handle(0), Handle(u64::MAX)]);
|
||||
}
|
||||
|
||||
/// Fit-point vertex constraints retain a known freedom count because they do not reconstruct the spline.
|
||||
#[test]
|
||||
fn vertex_constraints_on_large_fit_spline_do_not_charge_reconstruction() {
|
||||
let mut d = Drawing::default();
|
||||
let pts: Vec<_> = (0..500).map(|i| Vec2::new(i as f64, (i % 3) as f64)).collect();
|
||||
let mut sp = GSpline::from_control(pts.clone(), 3);
|
||||
sp.fit = pts;
|
||||
let h = put(&mut d, EntityKind::Spline(sp));
|
||||
for i in 0..5 {
|
||||
let p = point(&mut d, (i as f64, (i % 3) as f64));
|
||||
let mut c = con(K::Coincident, &[s(h, Sub::Vertex(i)), w(p)]);
|
||||
c.id = i + 1;
|
||||
d.constraints.push(c);
|
||||
}
|
||||
let report = dof(&d, &[]).unwrap();
|
||||
assert_eq!(report.status, DofStatus::Under);
|
||||
assert_eq!(report.dof, Some(1000));
|
||||
}
|
||||
|
||||
/// Adds a constraint that the stored ellipse can only hold with its axes renumbered: refused,
|
||||
/// with the drawing unchanged.
|
||||
fn refused_on_minor_axis_end(p: (f64, f64)) {
|
||||
let mut d = Drawing::default();
|
||||
let e = ellipse(&mut d, (0.0, 0.0), (4.0, 0.0), 0.5, 0.0, std::f64::consts::TAU);
|
||||
ok(&mut d, con(K::Fix, &[s(e, Sub::Center)]));
|
||||
let p = point(&mut d, p);
|
||||
ok(&mut d, con(K::Fix, &[w(p)]));
|
||||
let before = d.clone();
|
||||
let r = add(&mut d, con(K::Coincident, &[s(e, Sub::Vertex(1)), w(p)]), &SolveOptions::default());
|
||||
assert!(matches!(r, Err(SolveError::Conflict { .. })), "{r:?}, ellipse {:?}", ell(&d, e));
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
/// Pulling a minor axis end past the major axis length would need a ratio above 1, which the
|
||||
/// stored ellipse holds only by swapping its axes (and so renumbering their ends).
|
||||
#[test]
|
||||
fn minor_axis_end_pulled_past_the_major_axis_is_refused() {
|
||||
refused_on_minor_axis_end((0.0, 6.0));
|
||||
}
|
||||
|
||||
/// Pulling a minor axis end through the centre would need a negative ratio, which the stored
|
||||
/// ellipse cannot hold: storing its absolute value would mirror the minor axis end.
|
||||
#[test]
|
||||
fn minor_axis_end_pulled_through_the_centre_is_refused() {
|
||||
refused_on_minor_axis_end((0.0, -1.0));
|
||||
}
|
||||
|
||||
/// A circle-like ellipse whose solution makes the minor axis the longer one: stored with its axes
|
||||
/// swapped, which constraints that name no axis end by index do not notice.
|
||||
fn round_ellipse(d: &mut Drawing, start: f64, end: f64) -> Handle {
|
||||
let e = ellipse(d, (0.0, 0.0), (4.0, 0.0), 1.0, start, end);
|
||||
ok(d, con(K::Fix, &[s(e, Sub::Center)]));
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_that_swaps_a_round_ellipse_axes_is_kept() {
|
||||
let mut d = Drawing::default();
|
||||
let e = round_ellipse(&mut d, 0.0, std::f64::consts::TAU);
|
||||
let l = line(&mut d, (-10.0, 4.5), (10.0, 4.5));
|
||||
ok(&mut d, con(K::Fix, &[w(l)]));
|
||||
ok(&mut d, con(K::Tangent, &[w(l), w(e)]));
|
||||
assert!(ell(&d, e).ratio <= 1.0);
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_on_curve_that_swaps_a_round_ellipse_axes_is_kept() {
|
||||
let mut d = Drawing::default();
|
||||
let e = round_ellipse(&mut d, 0.0, std::f64::consts::TAU);
|
||||
let p = point(&mut d, (0.0, 4.5));
|
||||
ok(&mut d, con(K::Fix, &[w(p)]));
|
||||
ok(&mut d, con(K::Coincident, &[w(p), w(e)]));
|
||||
assert!(ell(&d, e).ratio <= 1.0);
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elliptical_arc_start_that_swaps_its_axes_is_kept() {
|
||||
let mut d = Drawing::default();
|
||||
let e = round_ellipse(&mut d, std::f64::consts::FRAC_PI_2, std::f64::consts::PI);
|
||||
let p = point(&mut d, (0.0, 4.5));
|
||||
ok(&mut d, con(K::Fix, &[w(p)]));
|
||||
ok(&mut d, con(K::Coincident, &[s(e, Sub::Start), w(p)]));
|
||||
assert!(ell(&d, e).ratio <= 1.0);
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_circle_that_swaps_a_round_ellipse_axes_is_kept() {
|
||||
let mut d = Drawing::default();
|
||||
let e = round_ellipse(&mut d, 0.0, std::f64::consts::TAU);
|
||||
let c = circle(&mut d, (0.0, 6.0), 1.5);
|
||||
ok(&mut d, con(K::Fix, &[w(c)]));
|
||||
ok(&mut d, con(K::Tangent, &[w(c), w(e)]));
|
||||
assert!(ell(&d, e).ratio <= 1.0);
|
||||
assert!(all_satisfied(&d));
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
//! Annotative scaling.
|
||||
//!
|
||||
//! An annotation scale ("1:50") says how many drawing units one paper unit stands for. The
|
||||
//! drawing keeps a list of them (SCALELISTEDIT) and a current one (`CANNOSCALE`). An annotative
|
||||
//! object (text, MText, dimension, multileader, hatch, block reference) stores its size as it
|
||||
//! should measure on paper and the set of scales it supports ([`Common::anno_scales`]); in a view
|
||||
//! it draws at paper size × that view's annotation scale, and only in views whose scale it
|
||||
//! supports unless `ANNOALLVISIBLE` is 1. Model space is seen at `CANNOSCALE`, a layout viewport
|
||||
//! at its viewport scale, and paper space itself at 1:1.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Common, Drawing, Entity, EntityKind};
|
||||
|
||||
/// A named annotation scale: `paper_units` on paper show `drawing_units` of the drawing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AnnoScale {
|
||||
pub name: String,
|
||||
pub paper_units: f64,
|
||||
pub drawing_units: f64,
|
||||
}
|
||||
|
||||
/// The most scales a drawing's list or one object holds (hostile files and parameters).
|
||||
pub const MAX_SCALES: usize = 1000;
|
||||
|
||||
impl AnnoScale {
|
||||
pub fn new(name: &str, paper_units: f64, drawing_units: f64) -> Self {
|
||||
AnnoScale { name: name.to_string(), paper_units, drawing_units }
|
||||
}
|
||||
/// The 1:1 scale.
|
||||
pub fn unit() -> Self {
|
||||
AnnoScale::new("1:1", 1.0, 1.0)
|
||||
}
|
||||
/// Both units finite and positive (and their ratio usable).
|
||||
pub fn is_valid(&self) -> bool {
|
||||
let ok = |v: f64| v.is_finite() && v > 0.0;
|
||||
ok(self.paper_units) && ok(self.drawing_units) && ok(self.drawing_units / self.paper_units)
|
||||
}
|
||||
/// Drawing units per paper unit (1:50 → 50): what an annotative object's paper size is
|
||||
/// multiplied by. 1 for an invalid scale.
|
||||
pub fn factor(&self) -> f64 {
|
||||
if self.is_valid() { self.drawing_units / self.paper_units } else { 1.0 }
|
||||
}
|
||||
/// Whether this scale has the ratio `factor` (drawing units per paper unit).
|
||||
pub fn has_factor(&self, factor: f64) -> bool {
|
||||
same_factor(self.factor(), factor)
|
||||
}
|
||||
}
|
||||
|
||||
/// Two scale factors are the same ratio (relative tolerance).
|
||||
pub fn same_factor(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1e-12)
|
||||
}
|
||||
|
||||
/// The default metric scale list.
|
||||
pub fn metric_scales() -> Vec<AnnoScale> {
|
||||
let mut v: Vec<AnnoScale> =
|
||||
[1.0, 2.0, 4.0, 5.0, 8.0, 10.0, 16.0, 20.0, 30.0, 40.0, 50.0, 100.0].iter().map(|n| AnnoScale::new(&format!("1:{n}"), 1.0, *n)).collect();
|
||||
v.extend([2.0, 4.0, 8.0, 10.0, 100.0].iter().map(|n| AnnoScale::new(&format!("{n}:1"), *n, 1.0)));
|
||||
v
|
||||
}
|
||||
|
||||
/// The default imperial scale list: the metric ratios, then the architectural inch-to-foot
|
||||
/// scales.
|
||||
pub fn imperial_scales() -> Vec<AnnoScale> {
|
||||
let mut v = metric_scales();
|
||||
let arch: [(&str, f64); 15] = [
|
||||
("1/128\" = 1'-0\"", 1.0 / 128.0),
|
||||
("1/64\" = 1'-0\"", 1.0 / 64.0),
|
||||
("1/32\" = 1'-0\"", 1.0 / 32.0),
|
||||
("1/16\" = 1'-0\"", 1.0 / 16.0),
|
||||
("3/32\" = 1'-0\"", 3.0 / 32.0),
|
||||
("1/8\" = 1'-0\"", 1.0 / 8.0),
|
||||
("3/16\" = 1'-0\"", 3.0 / 16.0),
|
||||
("1/4\" = 1'-0\"", 0.25),
|
||||
("3/8\" = 1'-0\"", 0.375),
|
||||
("1/2\" = 1'-0\"", 0.5),
|
||||
("3/4\" = 1'-0\"", 0.75),
|
||||
("1\" = 1'-0\"", 1.0),
|
||||
("1-1/2\" = 1'-0\"", 1.5),
|
||||
("3\" = 1'-0\"", 3.0),
|
||||
("6\" = 1'-0\"", 6.0),
|
||||
];
|
||||
v.extend(arch.iter().map(|(n, p)| AnnoScale::new(n, *p, 12.0)));
|
||||
v.push(AnnoScale::new("1'-0\" = 1'-0\"", 12.0, 12.0));
|
||||
v
|
||||
}
|
||||
|
||||
/// Kinds that can be annotative.
|
||||
pub fn can_be_annotative(k: &EntityKind) -> bool {
|
||||
matches!(
|
||||
k,
|
||||
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_) | EntityKind::Hatch(_) | EntityKind::Insert(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// An annotative object: a kind that can be annotative, with at least one supported scale.
|
||||
pub fn is_annotative(e: &Entity) -> bool {
|
||||
!e.common.anno_scales.is_empty() && can_be_annotative(&e.kind)
|
||||
}
|
||||
|
||||
/// Make `e` annotative (supporting `current` when it supports no scale yet) or not. Kinds that
|
||||
/// can't be annotative are left alone.
|
||||
pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
|
||||
if !on {
|
||||
e.common.anno_scales.clear();
|
||||
} else if can_be_annotative(&e.kind) && e.common.anno_scales.is_empty() {
|
||||
e.common.anno_scales.push(current.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// How an object draws in a view.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum AnnoDraw {
|
||||
/// Not annotative: as stored.
|
||||
Plain,
|
||||
/// Annotative, at this factor (drawing units per paper unit).
|
||||
Scaled(f64),
|
||||
/// Annotative and not supporting the view's scale, with `ANNOALLVISIBLE` 0.
|
||||
Hidden,
|
||||
}
|
||||
|
||||
impl Common {
|
||||
/// Whether these properties list a scale with the ratio `factor`.
|
||||
pub fn supports_factor(&self, factor: f64) -> bool {
|
||||
self.anno_scales.iter().any(|s| s.has_factor(factor))
|
||||
}
|
||||
/// Whether these properties list the scale named `name`.
|
||||
pub fn supports_scale(&self, name: &str) -> bool {
|
||||
self.anno_scales.iter().any(|s| s.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
}
|
||||
|
||||
/// How `e` draws in a view whose annotation scale is `view` (drawing units per paper unit). An
|
||||
/// object that doesn't support the view's scale shows at its first scale when `all_visible`.
|
||||
pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
|
||||
if !is_annotative(e) {
|
||||
return AnnoDraw::Plain;
|
||||
}
|
||||
if e.common.supports_factor(view) {
|
||||
return AnnoDraw::Scaled(if view.is_finite() && view > 0.0 { view } else { 1.0 });
|
||||
}
|
||||
match e.common.anno_scales.first() {
|
||||
Some(s) if all_visible => AnnoDraw::Scaled(s.factor()),
|
||||
_ => AnnoDraw::Hidden,
|
||||
}
|
||||
}
|
||||
|
||||
/// `e` as it draws at annotation scale `f`: its paper sizes (text height and width, dimension
|
||||
/// overall scale, multileader arrow, landing and content, hatch pattern scale, block scale and
|
||||
/// attributes) multiplied by `f`. A dimension is drawn from its definition at that scale, not
|
||||
/// from a stored geometry block. Other kinds come back unchanged.
|
||||
pub fn anno_scaled(e: &Entity, f: f64) -> Entity {
|
||||
let f = if f.is_finite() && f > 0.0 { f } else { 1.0 };
|
||||
let mut out = e.clone();
|
||||
match &mut out.kind {
|
||||
EntityKind::Text(t) => t.height *= f,
|
||||
EntityKind::MText(t) => {
|
||||
t.height *= f;
|
||||
t.width *= f;
|
||||
if let Some(c) = &mut t.columns {
|
||||
c.scale(f);
|
||||
}
|
||||
}
|
||||
EntityKind::Dimension(dm) => {
|
||||
dm.overrides.insert("scale".into(), serde_json::json!(f));
|
||||
dm.block = None;
|
||||
}
|
||||
EntityKind::MLeader(m) => {
|
||||
let land = m.landing;
|
||||
m.arrow_size *= f;
|
||||
m.dogleg *= f;
|
||||
if let Some(t) = &mut m.text {
|
||||
t.insert = land + (t.insert - land) * f;
|
||||
t.height *= f;
|
||||
t.width *= f;
|
||||
if let Some(c) = &mut t.columns {
|
||||
c.scale(f);
|
||||
}
|
||||
}
|
||||
if let Some(ins) = &mut m.block {
|
||||
ins.insert = land + (ins.insert - land) * f;
|
||||
ins.scale = ins.scale * f;
|
||||
}
|
||||
}
|
||||
EntityKind::Hatch(h) if !h.solid => h.scale *= f,
|
||||
EntityKind::Insert(ins) => {
|
||||
let o = ins.insert;
|
||||
ins.scale = ins.scale * f;
|
||||
ins.col_spacing *= f;
|
||||
ins.row_spacing *= f;
|
||||
for a in &mut ins.attribs {
|
||||
a.text.insert = o + (a.text.insert - o) * f;
|
||||
a.text.align_pt = a.text.align_pt.map(|p| o + (p - o) * f);
|
||||
a.text.height *= f;
|
||||
if let Some(ml) = &mut a.multiline {
|
||||
ml.mtext.insert = o + (ml.mtext.insert - o) * f;
|
||||
ml.mtext.height *= f;
|
||||
ml.mtext.width *= f;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Drawing {
|
||||
/// The scale named `name` in the drawing's scale list (case-insensitive).
|
||||
pub fn anno_scale(&self, name: &str) -> Option<&AnnoScale> {
|
||||
let n = name.trim();
|
||||
self.scales.iter().find(|s| s.name.eq_ignore_ascii_case(n))
|
||||
}
|
||||
/// The current annotation scale (`CANNOSCALE`); 1:1 when it names no scale of the list.
|
||||
pub fn current_anno_scale(&self) -> AnnoScale {
|
||||
let name = self.header.str("CANNOSCALE", "1:1");
|
||||
self.anno_scale(&name).filter(|s| s.is_valid()).cloned().unwrap_or_else(AnnoScale::unit)
|
||||
}
|
||||
/// Whether annotative objects that don't support the view's scale show (`ANNOALLVISIBLE`).
|
||||
pub fn anno_all_visible(&self) -> bool {
|
||||
self.header.i64("ANNOALLVISIBLE", 1) != 0
|
||||
}
|
||||
/// How top-level object `e` draws outside a viewport: in a layout's paper space at 1:1
|
||||
/// (paper space shows every annotative object), elsewhere (model space, or an object not in
|
||||
/// the drawing yet) as [`anno_draw`] at the current annotation scale.
|
||||
pub fn anno_draw(&self, e: &Entity) -> AnnoDraw {
|
||||
if !is_annotative(e) {
|
||||
return AnnoDraw::Plain;
|
||||
}
|
||||
if !self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle)) {
|
||||
return AnnoDraw::Scaled(1.0);
|
||||
}
|
||||
anno_draw(e, self.current_anno_scale().factor(), self.anno_all_visible())
|
||||
}
|
||||
/// Whether new objects of this kind are annotative: text and MText with an annotative text
|
||||
/// style, dimensions with an annotative dimension style, multileaders with an annotative
|
||||
/// multileader style, hatches while `HPANNOTATIVE` is 1, references to annotative blocks.
|
||||
pub fn annotative_by_style(&self, k: &EntityKind) -> bool {
|
||||
match k {
|
||||
EntityKind::Text(t) => self.text_style(&t.style).is_some_and(|s| s.annotative),
|
||||
EntityKind::MText(t) => self.text_style(&t.style).is_some_and(|s| s.annotative),
|
||||
EntityKind::Dimension(dm) => self.dim_style(&dm.style).is_some_and(|s| s.annotative),
|
||||
EntityKind::MLeader(m) => self.mleader_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&m.style)).is_some_and(|s| s.annotative),
|
||||
EntityKind::Hatch(_) => self.header.i64("HPANNOTATIVE", 0) != 0,
|
||||
EntityKind::Insert(ins) => self.block(&ins.block).is_some_and(|b| b.annotative),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
//! Associative arrays: the parameters an array keeps, and where they place its items.
|
||||
//!
|
||||
//! An associative array is a block reference to an anonymous block (`*U…`, the *array block*)
|
||||
//! that holds one block reference per item. Each item refers to the array's *source block*
|
||||
//! (another anonymous block holding the source objects) or, for items replaced with ARRAYEDIT,
|
||||
//! to another block. Other programs see an ordinary block reference; CADCraft keeps the
|
||||
//! parameters below on the array block ([`Block::array`](crate::Block)) so the items can be
|
||||
//! regenerated when the array is edited.
|
||||
//!
|
||||
//! All positions are in the array block's coordinates: its origin is the array's base point,
|
||||
//! which is where the array's block reference is inserted.
|
||||
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Common, Drawing, Entity, EntityKind, Insert, Lineweight};
|
||||
|
||||
/// Most items one array may have (items × rows × levels), whatever MAXARRAY says.
|
||||
pub const MAX_ARRAY_ITEMS: u64 = 10_000_000;
|
||||
|
||||
fn one() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// The parameters of an associative array.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ArrayParams {
|
||||
/// The source block the items refer to.
|
||||
pub source: String,
|
||||
pub kind: ArrayKind,
|
||||
/// Levels: copies of the whole array along Z.
|
||||
#[serde(default = "one")]
|
||||
pub levels: u32,
|
||||
#[serde(default)]
|
||||
pub level_spacing: f64,
|
||||
/// Items that refer to another block than the source (ARRAYEDIT REPlace).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub replaced: Vec<ReplacedItem>,
|
||||
/// The source objects are out for editing (ARRAYEDIT Source, until ARRAYCLOSE). Not saved:
|
||||
/// a drawing saved meanwhile keeps the objects as separate objects.
|
||||
#[serde(skip)]
|
||||
pub editing: Option<SourceEdit>,
|
||||
}
|
||||
|
||||
/// ARRAYEDIT Source in progress: the array's source objects placed in the drawing for editing.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SourceEdit {
|
||||
/// The array (block reference) being edited.
|
||||
pub array: crate::Handle,
|
||||
/// The item the objects were placed at: (i, j, level).
|
||||
pub item: (u32, u32, u32),
|
||||
/// The objects placed for editing.
|
||||
pub objects: Vec<crate::Handle>,
|
||||
/// Objects with this handle or above were drawn while editing; they join the source too.
|
||||
pub first_new: u64,
|
||||
}
|
||||
|
||||
/// Rectangular or polar placement.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum ArrayKind {
|
||||
Rect(RectArray),
|
||||
Polar(PolarArray),
|
||||
}
|
||||
|
||||
/// A rectangular array: columns along the axis angle, rows across it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RectArray {
|
||||
pub cols: u32,
|
||||
pub rows: u32,
|
||||
pub col_spacing: f64,
|
||||
pub row_spacing: f64,
|
||||
/// Direction of the rows (the column axis), radians.
|
||||
#[serde(default)]
|
||||
pub axis_angle: f64,
|
||||
/// Elevation added per row.
|
||||
#[serde(default)]
|
||||
pub row_elevation: f64,
|
||||
}
|
||||
|
||||
/// A polar array: items around a centre, rows as rings further out.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PolarArray {
|
||||
pub center: Vec2,
|
||||
pub items: u32,
|
||||
/// Angle to fill, degrees (positive = counterclockwise, ±360 = a full circle).
|
||||
pub fill: f64,
|
||||
/// Items are rotated as they go around (else they keep their orientation).
|
||||
pub rotate: bool,
|
||||
#[serde(default = "one")]
|
||||
pub rows: u32,
|
||||
/// Distance between rings, outwards from the centre.
|
||||
#[serde(default)]
|
||||
pub row_spacing: f64,
|
||||
#[serde(default)]
|
||||
pub row_elevation: f64,
|
||||
}
|
||||
|
||||
/// An item that refers to another block. `i` is the column (rectangular) or the item around the
|
||||
/// circle (polar), `j` the row.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReplacedItem {
|
||||
pub i: u32,
|
||||
pub j: u32,
|
||||
#[serde(default)]
|
||||
pub level: u32,
|
||||
pub block: String,
|
||||
}
|
||||
|
||||
/// Where one item goes: its block reference's insertion point (the image of the array's base
|
||||
/// point) and rotation (radians).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ArrayItem {
|
||||
pub i: u32,
|
||||
pub j: u32,
|
||||
pub level: u32,
|
||||
pub insert: Vec3,
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl ArrayParams {
|
||||
/// Items along the first direction (columns or items around) and rows.
|
||||
pub fn grid(&self) -> (u32, u32) {
|
||||
match &self.kind {
|
||||
ArrayKind::Rect(r) => (r.cols, r.rows),
|
||||
ArrayKind::Polar(p) => (p.items, p.rows),
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of items, saturating.
|
||||
pub fn item_count(&self) -> u64 {
|
||||
let (a, b) = self.grid();
|
||||
u64::from(a).saturating_mul(u64::from(b)).saturating_mul(u64::from(self.levels))
|
||||
}
|
||||
|
||||
/// Whether the parameters are usable: at least one item in every direction, at most
|
||||
/// [`MAX_ARRAY_ITEMS`] in all, and finite numbers. Parameters read from files are checked
|
||||
/// with this before they are kept.
|
||||
pub fn is_valid(&self) -> bool {
|
||||
let (a, b) = self.grid();
|
||||
let nums = match &self.kind {
|
||||
ArrayKind::Rect(r) => [r.col_spacing, r.row_spacing, r.axis_angle, r.row_elevation, 0.0, 0.0],
|
||||
ArrayKind::Polar(p) => [p.center.x, p.center.y, p.fill, p.row_spacing, p.row_elevation, 0.0],
|
||||
};
|
||||
a >= 1
|
||||
&& b >= 1
|
||||
&& self.levels >= 1
|
||||
&& self.item_count() <= MAX_ARRAY_ITEMS
|
||||
&& !self.source.trim().is_empty()
|
||||
&& nums.iter().chain(std::iter::once(&self.level_spacing)).all(|v| v.is_finite())
|
||||
&& self.replaced.len() as u64 <= MAX_ARRAY_ITEMS
|
||||
}
|
||||
|
||||
/// Where every item goes, row by row and level by level; `None` when the parameters are not
|
||||
/// [valid](Self::is_valid).
|
||||
pub fn items(&self) -> Option<Vec<ArrayItem>> {
|
||||
if !self.is_valid() {
|
||||
return None;
|
||||
}
|
||||
let n = usize::try_from(self.item_count()).ok()?;
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for level in 0..self.levels {
|
||||
let lz = self.level_spacing * f64::from(level);
|
||||
match &self.kind {
|
||||
ArrayKind::Rect(r) => {
|
||||
let (ux, uy) = (Vec2::from_angle(r.axis_angle), Vec2::from_angle(r.axis_angle).perp());
|
||||
for j in 0..r.rows {
|
||||
for i in 0..r.cols {
|
||||
let p = ux * (r.col_spacing * f64::from(i)) + uy * (r.row_spacing * f64::from(j));
|
||||
out.push(ArrayItem { i, j, level, insert: p.to3(lz + r.row_elevation * f64::from(j)), rotation: 0.0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
ArrayKind::Polar(p) => {
|
||||
let total = p.fill.to_radians();
|
||||
let full = (total.abs() - std::f64::consts::TAU).abs() < 1e-9;
|
||||
let step = if full { total / f64::from(p.items.max(1)) } else { total / f64::from(p.items.saturating_sub(1).max(1)) };
|
||||
// Rows move the items outwards: along the line from the centre to the base point.
|
||||
let out_dir = {
|
||||
let d = (Vec2::ZERO - p.center).normalized();
|
||||
if d == Vec2::ZERO { Vec2::X } else { d }
|
||||
};
|
||||
for j in 0..p.rows {
|
||||
let o = out_dir * (p.row_spacing * f64::from(j));
|
||||
for i in 0..p.items {
|
||||
let a = step * f64::from(i);
|
||||
let at = o.rotate_about(p.center, a);
|
||||
let rotation = if p.rotate { a } else { 0.0 };
|
||||
out.push(ArrayItem { i, j, level, insert: at.to3(lz + p.row_elevation * f64::from(j)), rotation });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The block an item refers to: a replacement, else the source.
|
||||
pub fn block_for(&self, i: u32, j: u32, level: u32) -> &str {
|
||||
self.replaced.iter().rev().find(|r| (r.i, r.j, r.level) == (i, j, level)).map_or(self.source.as_str(), |r| r.block.as_str())
|
||||
}
|
||||
|
||||
/// The block references that make up the array block: one per item, on layer 0 with ByBlock
|
||||
/// properties so they take the array's. Handles are allocated from `d`. `None` when the
|
||||
/// parameters are not [valid](Self::is_valid).
|
||||
pub fn item_entities(&self, d: &mut Drawing) -> Option<Vec<Entity>> {
|
||||
let items = self.items()?;
|
||||
let common = Common {
|
||||
layer: "0".into(),
|
||||
color: cadcraft_color::Color::ByBlock,
|
||||
linetype: "ByBlock".into(),
|
||||
lineweight: Lineweight::ByBlock,
|
||||
..Common::default()
|
||||
};
|
||||
let mut out = Vec::with_capacity(items.len());
|
||||
for it in items {
|
||||
let ins = Insert {
|
||||
block: self.block_for(it.i, it.j, it.level).to_string(),
|
||||
insert: it.insert,
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: it.rotation,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
};
|
||||
out.push(Entity { handle: d.new_handle(), common: common.clone(), kind: EntityKind::Insert(ins) });
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Take the block names from the array block's items `ents` (in the order [`items`]
|
||||
/// lists them): the source block is whatever the items that are not replaced refer to, so
|
||||
/// the parameters follow blocks renamed on paste, on INSERT of a file or by other programs
|
||||
/// (which may rename anonymous blocks). `false` when the items don't match the parameters
|
||||
/// (another program changed the block), so the array should be treated as a plain block.
|
||||
///
|
||||
/// [`items`]: Self::items
|
||||
pub fn sync_names<'a>(&mut self, ents: impl Iterator<Item = &'a Entity>) -> bool {
|
||||
let n = self.item_count();
|
||||
let ents: Vec<&Entity> = ents.take(usize::try_from(n).unwrap_or(usize::MAX).saturating_add(1)).collect();
|
||||
if ents.len() as u64 != n {
|
||||
return false;
|
||||
}
|
||||
let Some(items) = self.items() else { return false };
|
||||
// Index the replacement entries by placement so each item is matched in O(1) instead of
|
||||
// scanning the whole `replaced` vector per item, which is quadratic when both the items
|
||||
// and the replacements are large (CWE-407). Last entry wins, as `.rev().find` did.
|
||||
let mut last_replaced: std::collections::HashMap<(u32, u32, u32), usize> = std::collections::HashMap::with_capacity(self.replaced.len());
|
||||
for (idx, r) in self.replaced.iter().enumerate() {
|
||||
last_replaced.insert((r.i, r.j, r.level), idx);
|
||||
}
|
||||
let mut source: Option<&str> = None;
|
||||
for (it, e) in items.iter().zip(&ents) {
|
||||
let EntityKind::Insert(ins) = &e.kind else { return false };
|
||||
match last_replaced.get(&(it.i, it.j, it.level)).and_then(|&idx| self.replaced.get_mut(idx)) {
|
||||
Some(r) => r.block.clone_from(&ins.block),
|
||||
None => match source {
|
||||
None => source = Some(&ins.block),
|
||||
Some(s) if s.eq_ignore_ascii_case(&ins.block) => {}
|
||||
Some(_) => return false,
|
||||
},
|
||||
}
|
||||
}
|
||||
if let Some(s) = source {
|
||||
self.source = s.to_string();
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drawing {
|
||||
/// The parameters of `e` when it is an associative array (a block reference to an array
|
||||
/// block whose items match its parameters), with the block names its items use.
|
||||
pub fn array_params(&self, e: &Entity) -> Option<ArrayParams> {
|
||||
let EntityKind::Insert(i) = &e.kind else { return None };
|
||||
let b = self.block(&i.block)?;
|
||||
let mut p = b.array.clone()?;
|
||||
p.sync_names(b.entities.iter().map(|e| e.as_ref())).then_some(p)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rect(cols: u32, rows: u32) -> ArrayParams {
|
||||
ArrayParams {
|
||||
source: "*U1".into(),
|
||||
kind: ArrayKind::Rect(RectArray { cols, rows, col_spacing: 2.0, row_spacing: 3.0, axis_angle: 0.0, row_elevation: 0.0 }),
|
||||
levels: 2,
|
||||
level_spacing: 5.0,
|
||||
replaced: Vec::new(),
|
||||
editing: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_items_go_column_row_level() {
|
||||
let items = rect(3, 2).items().unwrap_or_default();
|
||||
assert_eq!(items.len(), 12);
|
||||
let last = items.last().copied().map(|i| (i.i, i.j, i.level, i.insert));
|
||||
assert_eq!(last, Some((2, 1, 1, Vec3::new(4.0, 3.0, 5.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_rows_go_outwards() {
|
||||
let p = ArrayParams {
|
||||
source: "*U1".into(),
|
||||
kind: ArrayKind::Polar(PolarArray {
|
||||
center: Vec2::new(-10.0, 0.0),
|
||||
items: 4,
|
||||
fill: 360.0,
|
||||
rotate: true,
|
||||
rows: 2,
|
||||
row_spacing: 1.0,
|
||||
row_elevation: 0.0,
|
||||
}),
|
||||
levels: 1,
|
||||
level_spacing: 0.0,
|
||||
replaced: Vec::new(),
|
||||
editing: None,
|
||||
};
|
||||
let items = p.items().unwrap_or_default();
|
||||
assert_eq!(items.len(), 8);
|
||||
// Item 1 of row 0 is a quarter turn round: base (0,0) → (-10,10).
|
||||
assert!(items[1].insert.xy().near(Vec2::new(-10.0, 10.0), 1e-9));
|
||||
// Row 1 starts one unit further out.
|
||||
assert!(items[4].insert.xy().near(Vec2::new(1.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_params_are_invalid() {
|
||||
let mut p = rect(u32::MAX, u32::MAX);
|
||||
assert!(!p.is_valid() && p.items().is_none());
|
||||
p = rect(0, 1);
|
||||
assert!(!p.is_valid());
|
||||
p = rect(2, 2);
|
||||
p.level_spacing = f64::NAN;
|
||||
assert!(!p.is_valid());
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ impl Sub {
|
||||
"mid" | "midpoint" | "m" => Sub::Mid,
|
||||
"center" | "centre" | "c" => Sub::Center,
|
||||
_ => {
|
||||
for (p, vertex) in [("vertex", true), ("segment", false), ("seg", false), ("v", true)] {
|
||||
for (p, vertex) in [("vertex", true), ("segment", false), ("seg", false), ("s", false), ("v", true)] {
|
||||
if let Some(n) = l.strip_prefix(p) {
|
||||
let i: u32 = n.trim().parse().ok()?;
|
||||
return Some(if vertex { Sub::Vertex(i) } else { Sub::Segment(i) });
|
||||
@@ -99,7 +99,8 @@ pub enum ConstraintKind {
|
||||
Horizontal,
|
||||
Vertical,
|
||||
Tangent,
|
||||
/// G2 continuity; solved as tangency for now.
|
||||
/// G2 continuity (common point, tangent and curvature) with a spline; tangency between
|
||||
/// other curves.
|
||||
Smooth,
|
||||
Symmetric,
|
||||
Equal,
|
||||
@@ -207,7 +208,7 @@ impl Default for ParametricSettings {
|
||||
angle_tolerance: 1.0,
|
||||
auto_types: ["Coincident", "Collinear", "Parallel", "Perpendicular", "Horizontal", "Vertical", "Tangent", "Concentric", "Equal"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.map(ToString::to_string)
|
||||
.collect(),
|
||||
bars_visible: true,
|
||||
bar_exceptions: Vec::new(),
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
//! Dynamic blocks made in another program, read from the data CADCraft keeps for them.
|
||||
//!
|
||||
//! A dynamic block's behaviour lives in objects CADCraft does not write itself and keeps as
|
||||
//! [`Foreign`](crate::foreign::Foreign) data: the block's BLOCK_RECORD has an extension dictionary
|
||||
//! whose `ACAD_ENHANCEDBLOCK` entry is an evaluation graph (`ACAD_EVALUATION_GRAPH`), and the
|
||||
//! graph lists the block's *parameters* (a distance, a point, visibility states, a lookup…) and
|
||||
//! *actions* (what changing a parameter does to the block's objects: stretch, move, look up…).
|
||||
//! [`dynamic_block`] reads them into the model below without changing the kept data, so a drawing
|
||||
//! saved again still carries them exactly as read.
|
||||
//!
|
||||
//! Every count and index here comes from the file: they are capped by the data actually present
|
||||
//! and unknown or damaged objects are skipped, never trusted.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::foreign::ForeignObject;
|
||||
use crate::{Drawing, Handle, RawTag};
|
||||
|
||||
mod apply;
|
||||
mod grips;
|
||||
mod reference;
|
||||
pub use apply::{drag_grip, set_property};
|
||||
pub use grips::{DynGrip, GripPart, GripShape, grips};
|
||||
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
|
||||
|
||||
/// Most objects one evaluation graph is read with.
|
||||
const MAX_NODES: usize = 10_000;
|
||||
|
||||
/// Handles as hex strings in JSON, as commands report them.
|
||||
fn hex<S: serde::Serializer>(h: &Handle, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&h.hex())
|
||||
}
|
||||
fn hexes<S: serde::Serializer>(hs: &[Handle], s: S) -> Result<S::Ok, S::Error> {
|
||||
s.collect_seq(hs.iter().map(|h| h.hex()))
|
||||
}
|
||||
fn hex_vertices<S: serde::Serializer>(v: &[(Handle, Vec<i32>)], s: S) -> Result<S::Ok, S::Error> {
|
||||
s.collect_seq(v.iter().map(|(h, i)| (h.hex(), i)))
|
||||
}
|
||||
|
||||
/// A dynamic block's parameters and actions.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DynamicBlock {
|
||||
pub parameters: Vec<Parameter>,
|
||||
pub actions: Vec<Action>,
|
||||
/// Graph members of types not modelled here (grips, constraints…), by DXF type.
|
||||
pub other: Vec<String>,
|
||||
/// The grip objects by graph id (parameters name their grips by id; visibility states list
|
||||
/// the grips shown in them by object).
|
||||
#[serde(skip)]
|
||||
pub grip_objects: Vec<(i32, Handle)>,
|
||||
}
|
||||
|
||||
/// One parameter: a property a reference to the block can change.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Parameter {
|
||||
/// Its id in the evaluation graph (actions and lookups refer to parameters by it).
|
||||
pub node: i32,
|
||||
#[serde(serialize_with = "hex")]
|
||||
pub handle: Handle,
|
||||
/// The name the block editor shows ("Linear", "Visibility State").
|
||||
pub element: String,
|
||||
/// The parameter's properties appear in a reference's Properties palette.
|
||||
pub show_properties: bool,
|
||||
pub kind: ParameterKind,
|
||||
/// Graph ids of its grips: a two-point parameter's base and end grips (0 for none), a
|
||||
/// one-point parameter's grip. A reference's history records grip drags by these.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub grips: Vec<i32>,
|
||||
}
|
||||
|
||||
/// What a parameter is, with its definition geometry in block coordinates.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum ParameterKind {
|
||||
/// A distance between two points (Distance1).
|
||||
Linear {
|
||||
base: Vec3,
|
||||
end: Vec3,
|
||||
label: String,
|
||||
description: String,
|
||||
values: ValueSet,
|
||||
/// The value changes the end point (`false`) or both points from the midpoint (`true`).
|
||||
from_midpoint: bool,
|
||||
},
|
||||
/// A distance and an angle from a base point.
|
||||
Polar { base: Vec3, end: Vec3 },
|
||||
/// Horizontal and vertical distances from a base point.
|
||||
Xy { base: Vec3, end: Vec3 },
|
||||
/// An angle about a base point.
|
||||
Rotation { base: Vec3, end: Vec3 },
|
||||
/// Aligns the reference with nearby geometry.
|
||||
Alignment { base: Vec3, end: Vec3 },
|
||||
/// Mirrors the objects about a reflection line.
|
||||
Flip { base: Vec3, end: Vec3 },
|
||||
/// A position (Position1).
|
||||
Point { at: Vec3, label: String, description: String },
|
||||
/// Named sets of visible objects.
|
||||
Visibility {
|
||||
at: Vec3,
|
||||
label: String,
|
||||
description: String,
|
||||
#[serde(serialize_with = "hexes")]
|
||||
controlled: Vec<Handle>,
|
||||
states: Vec<VisibilityState>,
|
||||
},
|
||||
/// A named value chosen from a lookup table.
|
||||
Lookup { at: Vec3, label: String, description: String },
|
||||
/// Moves the block's base point.
|
||||
BasePoint { at: Vec3 },
|
||||
/// A parameter type not modelled yet.
|
||||
Other { dxf_type: String },
|
||||
}
|
||||
|
||||
impl ParameterKind {
|
||||
/// The property name a reference shows ("Distance1", "Visibility1"), when it has one.
|
||||
pub fn label(&self) -> Option<&str> {
|
||||
match self {
|
||||
ParameterKind::Linear { label, .. }
|
||||
| ParameterKind::Point { label, .. }
|
||||
| ParameterKind::Visibility { label, .. }
|
||||
| ParameterKind::Lookup { label, .. } => Some(label),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
|
||||
/// objects are hidden).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VisibilityState {
|
||||
pub name: String,
|
||||
#[serde(serialize_with = "hexes")]
|
||||
pub visible: Vec<Handle>,
|
||||
/// The parameters and actions active in this state (their objects).
|
||||
#[serde(serialize_with = "hexes")]
|
||||
pub active: Vec<Handle>,
|
||||
}
|
||||
|
||||
/// The values a distance or angle may take.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ValueSet {
|
||||
/// Which of the limits below apply (see the methods).
|
||||
pub flags: i32,
|
||||
pub minimum: f64,
|
||||
pub maximum: f64,
|
||||
pub increment: f64,
|
||||
/// The allowed values, for a list.
|
||||
pub list: Vec<f64>,
|
||||
}
|
||||
|
||||
impl ValueSet {
|
||||
pub fn has_minimum(&self) -> bool {
|
||||
self.flags & 1 != 0
|
||||
}
|
||||
pub fn has_maximum(&self) -> bool {
|
||||
self.flags & 2 != 0
|
||||
}
|
||||
pub fn has_increment(&self) -> bool {
|
||||
self.flags & 4 != 0
|
||||
}
|
||||
pub fn is_list(&self) -> bool {
|
||||
self.flags & 8 != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// One action: what changing parameters does to the block's objects.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Action {
|
||||
pub node: i32,
|
||||
#[serde(serialize_with = "hex")]
|
||||
pub handle: Handle,
|
||||
/// Its name in the block editor ("Stretch", "Lookup1").
|
||||
pub name: String,
|
||||
/// Where the block editor shows it.
|
||||
pub at: Vec3,
|
||||
/// The objects it acts on.
|
||||
#[serde(serialize_with = "hexes")]
|
||||
pub selection: Vec<Handle>,
|
||||
/// Graph ids of the parameters it follows, with the parameter value each connection reads
|
||||
/// ("EndXDelta").
|
||||
pub connections: Vec<(i32, String)>,
|
||||
pub kind: ActionKind,
|
||||
}
|
||||
|
||||
/// What an action does.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum ActionKind {
|
||||
/// Moves the vertices inside `frame` of the objects listed (all of an object not listed).
|
||||
Stretch {
|
||||
frame: Vec<Vec2>,
|
||||
#[serde(serialize_with = "hex_vertices")]
|
||||
vertices: Vec<(Handle, Vec<i32>)>,
|
||||
multiplier: f64,
|
||||
angle_offset: f64,
|
||||
},
|
||||
/// A table: each row sets the listed parameter values together.
|
||||
Lookup {
|
||||
columns: Vec<LookupColumn>,
|
||||
rows: Vec<Vec<String>>,
|
||||
},
|
||||
/// Moves the objects by the change of the parameter values it follows.
|
||||
Move {
|
||||
multiplier: f64,
|
||||
angle_offset: f64,
|
||||
},
|
||||
Scale,
|
||||
Rotate,
|
||||
Flip,
|
||||
Array,
|
||||
PolarStretch,
|
||||
/// An action type not modelled yet.
|
||||
Other {
|
||||
dxf_type: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// A lookup table column: the parameter value it reads or sets.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LookupColumn {
|
||||
/// The parameter's graph id.
|
||||
pub node: i32,
|
||||
/// The value it stands for ("VisibilityState", "lookupString").
|
||||
pub property: String,
|
||||
/// A lookup property (shown on the reference) rather than an input.
|
||||
pub lookup: bool,
|
||||
/// What the reference shows when no row matches ("Custom").
|
||||
pub unmatched: String,
|
||||
}
|
||||
|
||||
/// The groups of an object split at its subclass markers (100): `(marker, groups after it)`.
|
||||
fn sections(tags: &[RawTag]) -> Vec<(&str, &[RawTag])> {
|
||||
let mut out: Vec<(&str, &[RawTag])> = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut name = "";
|
||||
for (i, t) in tags.iter().enumerate() {
|
||||
if t.code == 100 {
|
||||
out.push((name, tags.get(start..i).unwrap_or_default()));
|
||||
name = t.value.as_str();
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
out.push((name, tags.get(start..).unwrap_or_default()));
|
||||
out
|
||||
}
|
||||
|
||||
/// The groups after subclass marker `marker`, empty when the object has none.
|
||||
fn section<'a>(secs: &[(&str, &'a [RawTag])], marker: &str) -> &'a [RawTag] {
|
||||
secs.iter().find(|(n, _)| n.eq_ignore_ascii_case(marker)).map_or(&[], |(_, t)| t)
|
||||
}
|
||||
|
||||
/// Reads groups in order, as an object writes them.
|
||||
struct Cursor<'a> {
|
||||
tags: &'a [RawTag],
|
||||
at: usize,
|
||||
/// Groups scanned so far. A missing group neither moves the cursor nor ends the loops that
|
||||
/// ask for it, so a hostile record could make nested counts rescan it again and again; past
|
||||
/// `budget` every lookup fails at once and every count is zero.
|
||||
work: usize,
|
||||
budget: usize,
|
||||
}
|
||||
|
||||
impl<'a> Cursor<'a> {
|
||||
fn new(tags: &'a [RawTag]) -> Self {
|
||||
Cursor { tags, at: 0, work: 0, budget: tags.len().saturating_mul(16).saturating_add(1024) }
|
||||
}
|
||||
/// The next group with `code` from here on (the cursor moves past it).
|
||||
fn next(&mut self, code: i32) -> Option<&'a str> {
|
||||
if self.work >= self.budget {
|
||||
return None;
|
||||
}
|
||||
let rest = self.tags.get(self.at..)?;
|
||||
let Some(rel) = rest.iter().position(|t| t.code == code) else {
|
||||
self.work = self.work.saturating_add(rest.len().max(1));
|
||||
return None;
|
||||
};
|
||||
self.work = self.work.saturating_add(rel + 1);
|
||||
self.at += rel + 1;
|
||||
self.tags.get(self.at - 1).map(|t| t.value.as_str())
|
||||
}
|
||||
fn string(&mut self, code: i32) -> String {
|
||||
self.next(code).unwrap_or_default().to_string()
|
||||
}
|
||||
fn int(&mut self, code: i32) -> i32 {
|
||||
self.next(code).and_then(|v| v.trim().parse().ok()).unwrap_or(0)
|
||||
}
|
||||
fn real(&mut self, code: i32) -> f64 {
|
||||
self.next(code).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite()).unwrap_or(0.0)
|
||||
}
|
||||
/// A count read from the file, capped by the groups left (each item needs at least one).
|
||||
fn count(&mut self, code: i32) -> usize {
|
||||
let n = usize::try_from(self.int(code)).unwrap_or(0).min(self.tags.len().saturating_sub(self.at));
|
||||
if self.work >= self.budget { 0 } else { n }
|
||||
}
|
||||
fn handle(&mut self, code: i32) -> Option<Handle> {
|
||||
self.next(code).and_then(Handle::parse_hex)
|
||||
}
|
||||
fn handles(&mut self, code: i32, n: usize) -> Vec<Handle> {
|
||||
(0..n).filter_map(|_| self.handle(code)).collect()
|
||||
}
|
||||
/// A point written with codes `x`, `x + 10`, `x + 20`.
|
||||
fn point(&mut self, x: i32) -> Vec3 {
|
||||
let px = self.real(x);
|
||||
let py = self.real(x + 10);
|
||||
let at = self.at;
|
||||
// Z is optional: only take it when it is the very next group.
|
||||
let pz = match self.tags.get(at) {
|
||||
Some(t) if t.code == x + 20 => self.real(x + 20),
|
||||
_ => 0.0,
|
||||
};
|
||||
Vec3::new(px, py, pz)
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects `xdict`'s `ACAD_ENHANCEDBLOCK` evaluation graph lists, when the dictionary has one.
|
||||
fn graph_members<'a>(objects: &HashMap<Handle, &'a ForeignObject>, xdict: Handle) -> Option<Vec<&'a ForeignObject>> {
|
||||
let dict = objects.get(&xdict)?;
|
||||
let mut graph = None;
|
||||
let mut tags = dict.tags.iter();
|
||||
while let Some(t) = tags.next() {
|
||||
if t.code == 3 && t.value.eq_ignore_ascii_case("ACAD_ENHANCEDBLOCK") {
|
||||
graph = tags.next().filter(|t| t.code == 350 || t.code == 360).and_then(|t| Handle::parse_hex(&t.value));
|
||||
break;
|
||||
}
|
||||
}
|
||||
let graph = objects.get(&graph?).filter(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH"))?;
|
||||
let members = section(§ions(&graph.tags), "AcDbEvalGraph").iter().filter(|t| t.code == 360).filter_map(|t| Handle::parse_hex(&t.value));
|
||||
// Deduplicate member handles before resolving them: a graph can list the same member many
|
||||
// times, and parsing each occurrence into its own owned parameter multiplies a single large
|
||||
// record into gigabytes of retained allocations (CWE-400).
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
Some(members.take(MAX_NODES).filter(|h| seen.insert(*h)).filter_map(|h| objects.get(&h).copied()).collect())
|
||||
}
|
||||
|
||||
/// The dynamic block data of block `name` (any case; `*Model_Space` for a drawing that is a
|
||||
/// block's own drawing), or `None` when it has none.
|
||||
pub fn dynamic_block(d: &Drawing, name: &str) -> Option<DynamicBlock> {
|
||||
let xdict = d.foreign.records.get(&("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()))?.xdict?;
|
||||
let objects: HashMap<Handle, &ForeignObject> = d.foreign.objects.iter().map(|o| (o.handle, o)).collect();
|
||||
let mut out = DynamicBlock::default();
|
||||
for o in graph_members(&objects, xdict)? {
|
||||
let secs = sections(&o.tags);
|
||||
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
|
||||
let element = Cursor::new(section(&secs, "AcDbBlockElement")).string(300);
|
||||
let kind = o.kind.to_ascii_uppercase();
|
||||
if kind.ends_with("PARAMETER") {
|
||||
let show_properties = Cursor::new(section(&secs, "AcDbBlockParameter")).int(280) != 0;
|
||||
let grips = grip_ids(&secs);
|
||||
out.parameters.push(Parameter { node, handle: o.handle, element, show_properties, kind: parameter(&kind, &secs), grips });
|
||||
} else if kind.ends_with("ACTION") {
|
||||
out.actions.push(action(o.handle, node, element, &kind, &secs));
|
||||
} else {
|
||||
if kind.ends_with("GRIP") {
|
||||
out.grip_objects.push((node, o.handle));
|
||||
}
|
||||
out.other.push(o.kind.clone());
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
|
||||
/// base and end grips (91); after a one-point parameter's point, its grip (93).
|
||||
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
|
||||
let two = section(secs, "AcDbBlock2PtParameter");
|
||||
if !two.is_empty() {
|
||||
let mut c = Cursor::new(two);
|
||||
c.point(1010);
|
||||
c.point(1011);
|
||||
let n = c.count(170).min(2);
|
||||
return (0..n).map(|_| c.int(91)).collect();
|
||||
}
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
|
||||
c.point(1010);
|
||||
c.next(93).and_then(|v| v.trim().parse().ok()).into_iter().collect()
|
||||
}
|
||||
|
||||
fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
|
||||
let two = || {
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlock2PtParameter"));
|
||||
(c.point(1010), c.point(1011))
|
||||
};
|
||||
let one = || Cursor::new(section(secs, "AcDbBlock1PtParameter")).point(1010);
|
||||
match kind {
|
||||
"BLOCKLINEARPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockLinearParameter"));
|
||||
let label = c.string(305);
|
||||
let description = c.string(306);
|
||||
let from_midpoint = Cursor::new(section(secs, "AcDbBlock2PtParameter")).int(177) == 1;
|
||||
ParameterKind::Linear { base, end, label, description, values: value_set(&mut c), from_midpoint }
|
||||
}
|
||||
"BLOCKPOINTPARAMETER" => {
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockPointParameter"));
|
||||
ParameterKind::Point { at: one(), label: c.string(303), description: c.string(304) }
|
||||
}
|
||||
"BLOCKVISIBILITYPARAMETER" => visibility(one(), section(secs, "AcDbBlockVisibilityParameter")),
|
||||
"BLOCKLOOKUPPARAMETER" => {
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockLookupParameter"));
|
||||
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
|
||||
}
|
||||
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
|
||||
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
match kind {
|
||||
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
|
||||
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
|
||||
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
|
||||
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
|
||||
_ => ParameterKind::Flip { base, end },
|
||||
}
|
||||
}
|
||||
other => ParameterKind::Other { dxf_type: other.to_string() },
|
||||
}
|
||||
}
|
||||
|
||||
/// A value set after a parameter's name and description: description (307), flags (96),
|
||||
/// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each).
|
||||
fn value_set(c: &mut Cursor) -> ValueSet {
|
||||
c.next(307);
|
||||
let flags = c.int(96);
|
||||
let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143));
|
||||
let n = c.count(175);
|
||||
let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
|
||||
ValueSet { flags, minimum, maximum, increment, list }
|
||||
}
|
||||
|
||||
/// A visibility parameter: its name and description (301, 302), the objects it controls (93
|
||||
/// count, 331 each), then each state (92 count): name (303), visible objects (94, 332) and the
|
||||
/// parameters and actions active in it (95, 333).
|
||||
fn visibility(at: Vec3, tags: &[RawTag]) -> ParameterKind {
|
||||
let mut c = Cursor::new(tags);
|
||||
let label = c.string(301);
|
||||
let description = c.string(302);
|
||||
let n = c.count(93);
|
||||
let controlled = c.handles(331, n);
|
||||
let states = (0..c.count(92))
|
||||
.map(|_| {
|
||||
let name = c.string(303);
|
||||
let n = c.count(94);
|
||||
let visible = c.handles(332, n);
|
||||
let n = c.count(95);
|
||||
VisibilityState { name, visible, active: c.handles(333, n) }
|
||||
})
|
||||
.collect();
|
||||
ParameterKind::Visibility { at, label, description, controlled, states }
|
||||
}
|
||||
|
||||
fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[RawTag])]) -> Action {
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockAction"));
|
||||
c.next(70);
|
||||
let n = c.count(71);
|
||||
let selection = c.handles(330, n);
|
||||
let at = c.point(1010);
|
||||
let (connections, kind) = match kind {
|
||||
"BLOCKSTRETCHACTION" => stretch(section(secs, "AcDbBlockStretchAction")),
|
||||
"BLOCKLOOKUPACTION" => (Vec::new(), lookup(section(secs, "AcDbBlockLookupAction"))),
|
||||
"BLOCKMOVEACTION" => {
|
||||
let tags = section(secs, "AcDbBlockMoveAction");
|
||||
let mut c = Cursor::new(tags);
|
||||
let (multiplier, angle_offset) = (c.real(140), c.real(141));
|
||||
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
|
||||
}
|
||||
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
|
||||
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
|
||||
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
|
||||
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
|
||||
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
|
||||
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
|
||||
};
|
||||
Action { node, handle, name, at, selection, connections, kind }
|
||||
}
|
||||
|
||||
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
|
||||
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
|
||||
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
let int = |code: i32| first(code).trim().parse().unwrap_or(0);
|
||||
vec![(int(92), first(301)), (int(93), first(302))]
|
||||
}
|
||||
|
||||
/// A stretch action: its two connections, the frame (72 count, 1011/1021 points), the objects
|
||||
/// whose vertices it moves (73 count; each a 331 handle, a 74 count and 94 vertex indices), then
|
||||
/// the distance multiplier (140) and angle offset (141).
|
||||
fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
|
||||
let connections = two_connections(tags);
|
||||
let mut c = Cursor::new(tags);
|
||||
let n = c.count(72);
|
||||
let frame = (0..n)
|
||||
.map(|_| {
|
||||
let x = c.real(1011);
|
||||
Vec2::new(x, c.real(1021))
|
||||
})
|
||||
.collect();
|
||||
let objects = c.count(73);
|
||||
let vertices = (0..objects)
|
||||
.filter_map(|_| {
|
||||
let h = c.handle(331)?;
|
||||
let n = c.count(74);
|
||||
Some((h, (0..n).map(|_| c.int(94)).collect()))
|
||||
})
|
||||
.collect();
|
||||
c.next(75);
|
||||
let (multiplier, angle_offset) = (c.real(140), c.real(141));
|
||||
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
|
||||
}
|
||||
|
||||
/// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header),
|
||||
/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the
|
||||
/// parameter value it stands for (304).
|
||||
fn lookup(tags: &[RawTag]) -> ActionKind {
|
||||
let mut c = Cursor::new(tags);
|
||||
let rows = c.count(92);
|
||||
let cols = c.count(93);
|
||||
c.next(301);
|
||||
let cells = rows.saturating_mul(cols).min(tags.len());
|
||||
let flat: Vec<String> = (0..cells).map(|_| c.string(302)).collect();
|
||||
let rows = flat.chunks(cols.max(1)).map(<[String]>::to_vec).collect();
|
||||
let columns = (0..cols)
|
||||
.map(|_| {
|
||||
c.next(303);
|
||||
let node = c.int(94);
|
||||
let lookup = c.int(282) != 0;
|
||||
let unmatched = c.string(305);
|
||||
let property = c.string(304);
|
||||
LookupColumn { node, property, lookup, unmatched }
|
||||
})
|
||||
.collect();
|
||||
ActionKind::Lookup { columns, rows }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tag(code: i32, value: &str) -> RawTag {
|
||||
RawTag { code, value: value.to_string() }
|
||||
}
|
||||
|
||||
/// Counts that promise groups the record doesn't have: each nested loop would rescan the
|
||||
/// record for them. The work budget keeps this linear in the record's size.
|
||||
#[test]
|
||||
fn hostile_counts_with_missing_groups_stay_linear() {
|
||||
let n = 20_000;
|
||||
let mut tags = vec![tag(93, "0"), tag(92, &n.to_string())];
|
||||
tags.extend((0..n).map(|_| tag(94, &n.to_string())));
|
||||
let ParameterKind::Visibility { states, .. } = visibility(Vec3::default(), &tags) else { panic!("a visibility parameter") };
|
||||
assert!(states.len() <= n && states.iter().all(|s| s.visible.is_empty()));
|
||||
|
||||
let mut tags = vec![tag(73, &n.to_string())];
|
||||
tags.extend((0..n).flat_map(|_| [tag(331, "1F"), tag(74, &n.to_string())]));
|
||||
let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") };
|
||||
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
|
||||
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,215 @@
|
||||
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
|
||||
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
|
||||
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
|
||||
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
|
||||
//!
|
||||
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{DynamicBlock, ParameterKind, Value, custom_properties, dynamic_block, reference};
|
||||
use crate::{Drawing, EntityKind, Handle};
|
||||
|
||||
/// Most grips listed for one reference.
|
||||
const MAX_GRIPS: usize = 200;
|
||||
|
||||
/// Which of a parameter's points a grip is at.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GripPart {
|
||||
/// A distance's base point.
|
||||
Base,
|
||||
/// A distance's end point.
|
||||
End,
|
||||
/// A one-point parameter's point (a position, a visibility or lookup grip).
|
||||
At,
|
||||
}
|
||||
|
||||
impl GripPart {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
GripPart::Base => "base",
|
||||
GripPart::End => "end",
|
||||
GripPart::At => "at",
|
||||
}
|
||||
}
|
||||
pub fn from_name(s: &str) -> Option<GripPart> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"base" => Some(GripPart::Base),
|
||||
"end" => Some(GripPart::End),
|
||||
"at" => Some(GripPart::At),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a grip looks and what it does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GripShape {
|
||||
/// An arrow pointing away from the distance: drag it to change the distance.
|
||||
Linear,
|
||||
/// A square: drag it to move the position.
|
||||
Point,
|
||||
/// A down-pointing triangle: click it for the property's choices.
|
||||
List,
|
||||
}
|
||||
|
||||
/// One grip of a dynamic block reference.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DynGrip {
|
||||
/// The parameter's graph id.
|
||||
pub node: i32,
|
||||
pub part: GripPart,
|
||||
pub shape: GripShape,
|
||||
/// Where it is, in drawing coordinates.
|
||||
#[serde(serialize_with = "point")]
|
||||
pub at: Vec2,
|
||||
/// The way an arrow points (a unit vector in drawing coordinates; zero for the others).
|
||||
#[serde(serialize_with = "point")]
|
||||
pub dir: Vec2,
|
||||
/// The property it changes, as Properties names it.
|
||||
pub property: String,
|
||||
/// A list grip's choices.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub choices: Vec<String>,
|
||||
}
|
||||
|
||||
/// Which ends of two-point parameter `node` the block's actions follow, as (base, end): a
|
||||
/// connection to one point's change (BaseXDelta, EndYDelta, UpdatedEnd…) follows that end, one to
|
||||
/// the value itself (a distance, an angle) follows both. None when no action is attached to the
|
||||
/// parameter: its grips are all kept, as the block has them.
|
||||
fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
|
||||
let mut used: Option<(bool, bool)> = None;
|
||||
for (n, name) in m.actions.iter().flat_map(|a| a.connections.iter()) {
|
||||
if *n != node {
|
||||
continue;
|
||||
}
|
||||
let c = name.to_ascii_lowercase();
|
||||
let (base, end) = used.unwrap_or((false, false));
|
||||
used = Some(if c.starts_with("base") || c.starts_with("updatedbase") {
|
||||
(true, end)
|
||||
} else if c.starts_with("end") || c.starts_with("updatedend") {
|
||||
(base, true)
|
||||
} else {
|
||||
(true, true)
|
||||
});
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
|
||||
[p.x, p.y].serialize(s)
|
||||
}
|
||||
|
||||
/// The grips of dynamic block reference `insert` (none when it is not one).
|
||||
pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
let Some(r) = reference(d, insert) else { return Vec::new() };
|
||||
let Some(m) = dynamic_block(d, &r.definition) else { return Vec::new() };
|
||||
let Some(EntityKind::Insert(ins)) = d.entity(insert).map(|e| &e.kind) else { return Vec::new() };
|
||||
let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default();
|
||||
let xf = ins.transform(base);
|
||||
let world = |p: Vec3| xf.apply(p.xy());
|
||||
let toward = |p: Vec3, u: Vec3| {
|
||||
let v = xf.apply(p.xy() + u.xy()) - xf.apply(p.xy());
|
||||
if v.len() > 1e-12 { v * (1.0 / v.len()) } else { Vec2::ZERO }
|
||||
};
|
||||
// The grips the current visibility state shows (all of them without visibility states).
|
||||
let objects: HashMap<i32, Handle> = m.grip_objects.iter().copied().collect();
|
||||
let mut shown_in_state: Option<HashSet<Handle>> = None;
|
||||
let mut visibility_node = None;
|
||||
for p in &m.parameters {
|
||||
if let ParameterKind::Visibility { states, .. } = &p.kind {
|
||||
let current = match r.values.get(&p.node) {
|
||||
Some(Value::Text { value }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
|
||||
_ => states.first(),
|
||||
};
|
||||
if let Some(s) = current {
|
||||
shown_in_state = Some(s.active.iter().copied().collect());
|
||||
}
|
||||
visibility_node = Some(p.node);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// A grip shows in the current visibility state when the state lists it, or lists its
|
||||
// parameter (AutoCAD shows a listed parameter's grips though the grips aren't listed).
|
||||
let param_handle: HashMap<i32, Handle> = m.parameters.iter().map(|p| (p.node, p.handle)).collect();
|
||||
let shown = |node: i32, id: i32| {
|
||||
id != 0
|
||||
&& (Some(node) == visibility_node
|
||||
|| shown_in_state
|
||||
.as_ref()
|
||||
.is_none_or(|a| objects.get(&id).is_some_and(|h| a.contains(h)) || param_handle.get(&node).is_some_and(|h| a.contains(h))))
|
||||
};
|
||||
let choices: HashMap<String, Vec<String>> =
|
||||
custom_properties(d, insert).map(|(_, ps)| ps.into_iter().map(|p| (p.name.to_ascii_uppercase(), p.choices)).collect()).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
for p in &m.parameters {
|
||||
let grip = |i: usize| p.grips.get(i).copied().unwrap_or(0);
|
||||
match &p.kind {
|
||||
ParameterKind::Linear { base, end, label, from_midpoint, .. } => {
|
||||
let (b, e) = match r.values.get(&p.node) {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
let u = e - b;
|
||||
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
|
||||
// An end no action follows has no grip (dragging it would change nothing); a
|
||||
// distance from its midpoint moves both ends.
|
||||
let used = match ends_used(&m, p.node) {
|
||||
Some((base, end)) if !*from_midpoint => [base, end],
|
||||
_ => [true, true],
|
||||
};
|
||||
for (i, part, at, way) in [(0, GripPart::Base, b, u * -1.0), (1, GripPart::End, e, u)] {
|
||||
if used[i] && shown(p.node, grip(i)) {
|
||||
let (at, dir) = (world(at), toward(at, way));
|
||||
out.push(DynGrip { node: p.node, part, shape: GripShape::Linear, at, dir, property: label.clone(), choices: Vec::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
ParameterKind::Point { at, label, .. } => {
|
||||
let at = match r.values.get(&p.node) {
|
||||
Some(Value::Point { at }) => *at,
|
||||
_ => *at,
|
||||
};
|
||||
if shown(p.node, grip(0)) {
|
||||
let at = world(at);
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::At,
|
||||
shape: GripShape::Point,
|
||||
at,
|
||||
dir: Vec2::ZERO,
|
||||
property: label.clone(),
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
|
||||
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
|
||||
if shown(p.node, grip(0)) {
|
||||
let at = world(*at);
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::At,
|
||||
shape: GripShape::List,
|
||||
at,
|
||||
dir: Vec2::ZERO,
|
||||
property: label.clone(),
|
||||
choices: list.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if out.len() >= MAX_GRIPS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.retain(|g| g.at.is_finite());
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! Dynamic block references: which dynamic block a block reference shows, the values it was given
|
||||
//! and the custom properties those make.
|
||||
//!
|
||||
//! A reference whose values differ from the block's own refers to an anonymous block (`*U12`)
|
||||
//! holding the result, and its extension dictionary says what it is: `AcDbBlockRepresentation`
|
||||
//! has `AcDbRepData` (pointing at the dynamic block's BLOCK_RECORD) and an `AppDataCache` whose
|
||||
//! `ACAD_ENHANCEDBLOCKDATA` dictionary holds one XRECORD per parameter, keyed by its graph id, with
|
||||
//! the value in block coordinates. A reference to the dynamic block itself has the block's values.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{ActionKind, DynamicBlock, ParameterKind, dynamic_block};
|
||||
use crate::foreign::ForeignObject;
|
||||
use crate::{Drawing, EntityKind, Handle};
|
||||
|
||||
/// Most values one reference is read with.
|
||||
const MAX_VALUES: usize = 10_000;
|
||||
|
||||
/// A parameter's value on one reference, in block coordinates.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum Value {
|
||||
/// A visibility state's name or a lookup value.
|
||||
Text { value: String },
|
||||
/// A point parameter's position.
|
||||
Point { at: Vec3 },
|
||||
/// A two-point parameter's points.
|
||||
Points { base: Vec3, end: Vec3 },
|
||||
}
|
||||
|
||||
/// A dynamic block reference.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Reference {
|
||||
/// The dynamic block it shows (its name in the drawing).
|
||||
pub definition: String,
|
||||
/// The values it was given, by parameter graph id; parameters missing here have the block's
|
||||
/// own values.
|
||||
pub values: BTreeMap<i32, Value>,
|
||||
}
|
||||
|
||||
/// One custom property of a reference, as the Properties palette shows it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CustomProperty {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
/// The values it may be set to, when it is a choice (visibility states, lookup values, a
|
||||
/// distance's list).
|
||||
pub choices: Vec<String>,
|
||||
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a
|
||||
/// position, or a lookup whose tables set only those.
|
||||
pub editable: bool,
|
||||
}
|
||||
|
||||
fn objects(d: &Drawing) -> HashMap<Handle, &ForeignObject> {
|
||||
d.foreign.objects.iter().map(|o| (o.handle, o)).collect()
|
||||
}
|
||||
|
||||
/// The object entry `key` of dictionary `dict` refers to.
|
||||
fn entry(objects: &HashMap<Handle, &ForeignObject>, dict: Handle, key: &str) -> Option<Handle> {
|
||||
let o = objects.get(&dict)?;
|
||||
let mut tags = o.tags.iter();
|
||||
while let Some(t) = tags.next() {
|
||||
if t.code == 3 && t.value.eq_ignore_ascii_case(key) {
|
||||
return tags.next().filter(|t| t.code == 350 || t.code == 360).and_then(|t| Handle::parse_hex(&t.value));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Every entry of dictionary `dict`: (key, object).
|
||||
fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(String, Handle)> {
|
||||
let Some(o) = objects.get(&dict) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut key: Option<&str> = None;
|
||||
for t in &o.tags {
|
||||
match t.code {
|
||||
3 => key = Some(t.value.as_str()),
|
||||
350 | 360 => {
|
||||
if let (Some(k), Some(h)) = (key.take(), Handle::parse_hex(&t.value)) {
|
||||
out.push((k.to_string(), h));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
|
||||
fn value(o: &ForeignObject) -> Option<Value> {
|
||||
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
|
||||
return Some(Value::Text { value: t.value.clone() });
|
||||
}
|
||||
let num = |code: i32, i: usize| {
|
||||
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
|
||||
};
|
||||
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
|
||||
match (point(0), point(1)) {
|
||||
(Some(base), Some(end)) => Some(Value::Points { base, end }),
|
||||
(Some(at), None) => Some(Value::Point { at }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The dynamic block reference `insert` is, or `None` when it isn't one.
|
||||
pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
|
||||
let EntityKind::Insert(ins) = &d.entity(insert)?.kind else { return None };
|
||||
let objects = objects(d);
|
||||
let rep = d.foreign.entities.get(&insert).and_then(|x| x.xdict).and_then(|x| entry(&objects, x, "AcDbBlockRepresentation"));
|
||||
let Some(rep) = rep else {
|
||||
// No representation: a reference to a dynamic block with its own values.
|
||||
return dynamic_block(d, &ins.block)
|
||||
.is_some()
|
||||
.then(|| Reference { definition: d.block(&ins.block).map_or_else(|| ins.block.clone(), |b| b.name.clone()), values: BTreeMap::new() });
|
||||
};
|
||||
let data = entry(&objects, rep, "AcDbRepData").and_then(|h| objects.get(&h).copied())?;
|
||||
let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?;
|
||||
let (kind, name) = d.foreign.targets.get(&target)?;
|
||||
let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone();
|
||||
dynamic_block(d, &definition)?;
|
||||
let mut values = BTreeMap::new();
|
||||
let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA"));
|
||||
for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) {
|
||||
if let (Ok(node), Some(v)) = (key.trim().parse::<i32>(), objects.get(&h).and_then(|o| value(o))) {
|
||||
values.insert(node, v);
|
||||
}
|
||||
}
|
||||
Some(Reference { definition, values })
|
||||
}
|
||||
|
||||
/// A number as the drawing shows lengths (LUPREC decimals).
|
||||
fn number(d: &Drawing, v: f64) -> String {
|
||||
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
|
||||
format!("{v:.prec$}")
|
||||
}
|
||||
|
||||
/// Whether table cell `cell` reads as `value` (numbers compare as numbers).
|
||||
fn same(cell: &str, value: &str) -> bool {
|
||||
match (cell.trim().parse::<f64>(), value.trim().parse::<f64>()) {
|
||||
(Ok(a), Ok(b)) => (a - b).abs() <= 1e-6 * a.abs().max(b.abs()).max(1.0),
|
||||
_ => cell.trim().eq_ignore_ascii_case(value.trim()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current values of a reference's parameters, for evaluating its lookup tables.
|
||||
struct Current<'a> {
|
||||
m: &'a DynamicBlock,
|
||||
values: &'a BTreeMap<i32, Value>,
|
||||
}
|
||||
|
||||
impl Current<'_> {
|
||||
/// Parameter `node`'s value of property `property`, as table cells write it.
|
||||
fn property(&self, node: i32, property: &str) -> Option<String> {
|
||||
let p = self.m.parameters.iter().find(|p| p.node == node)?;
|
||||
let v = self.values.get(&node);
|
||||
match (&p.kind, property.to_ascii_lowercase().as_str()) {
|
||||
(ParameterKind::Visibility { states, .. }, "visibilitystate") => match v {
|
||||
Some(Value::Text { value }) => Some(value.clone()),
|
||||
_ => states.first().map(|s| s.name.clone()),
|
||||
},
|
||||
(ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
Some(format!("{}", (e - b).len()))
|
||||
}
|
||||
(ParameterKind::Lookup { .. }, "lookupstring") => match v {
|
||||
Some(Value::Text { value }) => Some(value.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
|
||||
/// current inputs, or the tables' "no match" name ("Custom") when they don't agree or a table
|
||||
/// has no matching row. Also the values it may be set to.
|
||||
fn lookup(&self, node: i32) -> (String, Vec<String>) {
|
||||
let mut found: Option<Option<String>> = None;
|
||||
let mut unmatched = String::from("Custom");
|
||||
let mut choices: Vec<String> = Vec::new();
|
||||
for a in &self.m.actions {
|
||||
let ActionKind::Lookup { columns, rows } = &a.kind else { continue };
|
||||
let Some(out) = columns.iter().position(|c| c.lookup && c.node == node) else { continue };
|
||||
if rows.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(c) = columns.get(out) {
|
||||
unmatched = c.unmatched.clone();
|
||||
}
|
||||
for r in rows {
|
||||
if let Some(v) = r.get(out).filter(|v| !choices.contains(v)) {
|
||||
choices.push(v.clone());
|
||||
}
|
||||
}
|
||||
let hit = rows.iter().find(|r| {
|
||||
columns.iter().enumerate().filter(|(_, c)| !c.lookup).all(|(i, c)| match (r.get(i), self.property(c.node, &c.property)) {
|
||||
(Some(cell), Some(v)) => same(cell, &v),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
let v = hit.and_then(|r| r.get(out).cloned());
|
||||
found = Some(match found {
|
||||
None => v,
|
||||
Some(prev) if prev == v => prev,
|
||||
Some(_) => None,
|
||||
});
|
||||
}
|
||||
(found.flatten().unwrap_or(unmatched), choices)
|
||||
}
|
||||
}
|
||||
|
||||
/// The custom properties block reference `insert` shows (the Properties palette's Custom
|
||||
/// section): its dynamic block's name and, in parameter order, each parameter shown in Properties
|
||||
/// with its value. Lengths and positions are in drawing units (block units × the reference's
|
||||
/// scale); positions are relative to the block's base point.
|
||||
pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<CustomProperty>)> {
|
||||
let r = reference(d, insert)?;
|
||||
let EntityKind::Insert(ins) = &d.entity(insert)?.kind else { return None };
|
||||
let m = dynamic_block(d, &r.definition)?;
|
||||
let base = d.block(&r.definition).map(|b| b.base).unwrap_or_default();
|
||||
let (sx, sy) = (ins.scale.x.abs(), ins.scale.y.abs());
|
||||
let cur = Current { m: &m, values: &r.values };
|
||||
let mut out = Vec::new();
|
||||
for p in m.parameters.iter().filter(|p| p.show_properties) {
|
||||
let v = r.values.get(&p.node);
|
||||
match &p.kind {
|
||||
ParameterKind::Linear { base: b, end: e, label, values, .. } => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*b, *e),
|
||||
};
|
||||
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
|
||||
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
|
||||
}
|
||||
ParameterKind::Point { at, label, .. } => {
|
||||
let at = match v {
|
||||
Some(Value::Point { at }) => *at,
|
||||
_ => *at,
|
||||
};
|
||||
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
|
||||
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
|
||||
}
|
||||
ParameterKind::Visibility { label, states, .. } => {
|
||||
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
|
||||
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });
|
||||
}
|
||||
ParameterKind::Lookup { label, .. } => {
|
||||
let (value, choices) = cur.lookup(p.node);
|
||||
let editable = lookup_sets_what_changes(&m, p.node);
|
||||
out.push(CustomProperty { name: label.clone(), value, choices, editable });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some((r.definition, out))
|
||||
}
|
||||
|
||||
/// Whether every lookup table that sets lookup parameter `node` sets only what
|
||||
/// [`super::set_property`] can apply with it: visibility states and distances.
|
||||
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
|
||||
let mut any = false;
|
||||
for a in &m.actions {
|
||||
let ActionKind::Lookup { columns, rows } = &a.kind else { continue };
|
||||
if rows.is_empty() || !columns.iter().any(|c| c.lookup && c.node == node) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
if !columns
|
||||
.iter()
|
||||
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
+135
-619
@@ -6,111 +6,8 @@ use cadcraft_geom::{
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A database handle (DXF group 5), unique per drawing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct Handle(pub u64);
|
||||
|
||||
impl Handle {
|
||||
pub fn hex(self) -> String {
|
||||
format!("{:X}", self.0)
|
||||
}
|
||||
pub fn parse_hex(s: &str) -> Option<Handle> {
|
||||
u64::from_str_radix(s.trim(), 16).ok().map(Handle)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lineweight in hundredths of a millimetre, or a logical value.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Lineweight {
|
||||
#[default]
|
||||
ByLayer,
|
||||
ByBlock,
|
||||
Default,
|
||||
/// 0..=211 (hundredths of mm).
|
||||
Mm100(u16),
|
||||
}
|
||||
|
||||
impl Lineweight {
|
||||
/// The standard lineweight values (mm × 100).
|
||||
pub const STANDARD: [u16; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211];
|
||||
pub fn to_dxf(self) -> i16 {
|
||||
match self {
|
||||
Lineweight::ByLayer => -1,
|
||||
Lineweight::ByBlock => -2,
|
||||
Lineweight::Default => -3,
|
||||
Lineweight::Mm100(v) => v.min(211) as i16,
|
||||
}
|
||||
}
|
||||
pub fn from_dxf(v: i16) -> Lineweight {
|
||||
match v {
|
||||
-2 => Lineweight::ByBlock,
|
||||
-3 => Lineweight::Default,
|
||||
0..=211 => Lineweight::Mm100(v as u16),
|
||||
_ => Lineweight::ByLayer,
|
||||
}
|
||||
}
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
Lineweight::ByLayer => "ByLayer".into(),
|
||||
Lineweight::ByBlock => "ByBlock".into(),
|
||||
Lineweight::Default => "Default".into(),
|
||||
Lineweight::Mm100(v) => format!("{:.2} mm", f64::from(v) / 100.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transparency: ByLayer, ByBlock, or 0..=90 percent.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Transparency {
|
||||
#[default]
|
||||
ByLayer,
|
||||
ByBlock,
|
||||
Percent(u8),
|
||||
}
|
||||
|
||||
impl Transparency {
|
||||
/// "ByLayer", "ByBlock" or the percentage ("50").
|
||||
pub fn name(&self) -> String {
|
||||
match self {
|
||||
Transparency::ByLayer => "ByLayer".into(),
|
||||
Transparency::ByBlock => "ByBlock".into(),
|
||||
Transparency::Percent(p) => p.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Properties every entity has.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Common {
|
||||
pub layer: String,
|
||||
pub color: Color,
|
||||
pub linetype: String,
|
||||
pub lineweight: Lineweight,
|
||||
pub ltscale: f64,
|
||||
pub transparency: Transparency,
|
||||
pub visible: bool,
|
||||
pub thickness: f64,
|
||||
pub extrusion: Vec3,
|
||||
}
|
||||
|
||||
impl Default for Common {
|
||||
fn default() -> Self {
|
||||
Common {
|
||||
layer: "0".into(),
|
||||
color: Color::ByLayer,
|
||||
linetype: "ByLayer".into(),
|
||||
lineweight: Lineweight::ByLayer,
|
||||
ltscale: 1.0,
|
||||
transparency: Transparency::ByLayer,
|
||||
visible: true,
|
||||
thickness: 0.0,
|
||||
extrusion: Vec3::Z,
|
||||
}
|
||||
}
|
||||
}
|
||||
mod mline;
|
||||
pub use mline::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Entity {
|
||||
@@ -125,524 +22,36 @@ impl Entity {
|
||||
Entity { handle, common: Common::default(), kind }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Line {
|
||||
pub a: Vec3,
|
||||
pub b: Vec3,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Point {
|
||||
pub p: Vec3,
|
||||
#[serde(default)]
|
||||
pub angle: f64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Circle {
|
||||
pub center: Vec3,
|
||||
pub radius: f64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Arc {
|
||||
pub center: Vec3,
|
||||
pub radius: f64,
|
||||
/// Radians, CCW.
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Ellipse {
|
||||
pub center: Vec3,
|
||||
pub major: Vec3,
|
||||
pub ratio: f64,
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct LwPolyline {
|
||||
pub vertices: Vec<PolyVertex>,
|
||||
pub closed: bool,
|
||||
#[serde(default)]
|
||||
pub const_width: f64,
|
||||
#[serde(default)]
|
||||
pub elevation: f64,
|
||||
/// Polyline linetype generation (PLINEGEN).
|
||||
#[serde(default)]
|
||||
pub plinegen: bool,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Polyline3d {
|
||||
pub points: Vec<Vec3>,
|
||||
pub closed: bool,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HAlign {
|
||||
#[default]
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
Aligned,
|
||||
Middle,
|
||||
Fit,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VAlign {
|
||||
#[default]
|
||||
Baseline,
|
||||
Bottom,
|
||||
Middle,
|
||||
Top,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Text {
|
||||
pub insert: Vec3,
|
||||
#[serde(default)]
|
||||
pub align_pt: Option<Vec3>,
|
||||
pub height: f64,
|
||||
pub value: String,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
#[serde(default = "one")]
|
||||
pub width_factor: f64,
|
||||
#[serde(default)]
|
||||
pub oblique: f64,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default)]
|
||||
pub halign: HAlign,
|
||||
#[serde(default)]
|
||||
pub valign: VAlign,
|
||||
}
|
||||
impl Text {
|
||||
/// The point the text is placed by, as the Insertion snap and the grip show it: the alignment
|
||||
/// point (DXF group 11) of justified text, the start point (group 10) of left-baseline,
|
||||
/// aligned and fit text.
|
||||
pub fn justify_point(&self) -> Vec2 {
|
||||
match (self.halign, self.valign) {
|
||||
(HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _) => self.insert.xy(),
|
||||
_ => self.align_pt.unwrap_or(self.insert).xy(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn one() -> f64 {
|
||||
1.0
|
||||
}
|
||||
fn standard() -> String {
|
||||
"Standard".into()
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MText {
|
||||
pub insert: Vec3,
|
||||
pub height: f64,
|
||||
/// Reference rectangle width (0 = no wrapping).
|
||||
#[serde(default)]
|
||||
pub width: f64,
|
||||
/// 1..=9: TL TC TR ML MC MR BL BC BR.
|
||||
#[serde(default = "attach_tl")]
|
||||
pub attach: u8,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
/// Raw MTEXT contents with inline codes (\P, {\fArial|b1;...}, \S1/2; …).
|
||||
pub contents: String,
|
||||
#[serde(default = "one")]
|
||||
pub line_spacing: f64,
|
||||
}
|
||||
fn attach_tl() -> u8 {
|
||||
1
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Attrib {
|
||||
pub tag: String,
|
||||
pub text: Text,
|
||||
#[serde(default)]
|
||||
pub invisible: bool,
|
||||
#[serde(default)]
|
||||
pub constant: bool,
|
||||
#[serde(default)]
|
||||
pub prompt: String,
|
||||
/// An attribute's own properties; each one left unset follows the attribute definition.
|
||||
#[serde(default, skip_serializing_if = "AttribProps::is_empty")]
|
||||
pub props: AttribProps,
|
||||
}
|
||||
|
||||
/// Properties set on one attribute of a block reference (an ATTRIB's layer, colour, linetype and
|
||||
/// lineweight), overriding those of its definition.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AttribProps {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub layer: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<Color>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linetype: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub lineweight: Option<Lineweight>,
|
||||
}
|
||||
|
||||
impl AttribProps {
|
||||
/// Nothing set: the attribute is drawn with its definition's properties.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == AttribProps::default()
|
||||
}
|
||||
/// `base` (the definition's properties) with the ones set here in place.
|
||||
pub fn over(&self, base: &Common) -> Common {
|
||||
Common {
|
||||
layer: self.layer.clone().unwrap_or_else(|| base.layer.clone()),
|
||||
color: self.color.unwrap_or(base.color),
|
||||
linetype: self.linetype.clone().unwrap_or_else(|| base.linetype.clone()),
|
||||
lineweight: self.lineweight.unwrap_or(base.lineweight),
|
||||
..base.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Insert {
|
||||
pub block: String,
|
||||
pub insert: Vec3,
|
||||
#[serde(default = "unit_scale")]
|
||||
pub scale: Vec3,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
#[serde(default)]
|
||||
pub attribs: Vec<Attrib>,
|
||||
#[serde(default = "one_u")]
|
||||
pub cols: u32,
|
||||
#[serde(default = "one_u")]
|
||||
pub rows: u32,
|
||||
#[serde(default)]
|
||||
pub col_spacing: f64,
|
||||
#[serde(default)]
|
||||
pub row_spacing: f64,
|
||||
}
|
||||
fn unit_scale() -> Vec3 {
|
||||
Vec3::new(1.0, 1.0, 1.0)
|
||||
}
|
||||
fn one_u() -> u32 {
|
||||
1
|
||||
}
|
||||
impl Insert {
|
||||
/// Block-to-world transform (2D part).
|
||||
pub fn transform(&self, base: Vec2) -> Mat3 {
|
||||
Mat3::translate(self.insert.xy())
|
||||
.then_before(Mat3::rotate(self.rotation))
|
||||
.then_before(Mat3::scale(self.scale.x, self.scale.y))
|
||||
.then_before(Mat3::translate(-base))
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DimKind {
|
||||
/// Rotated linear dimension (horizontal = 0, vertical = 90°).
|
||||
Linear {
|
||||
rotation: f64,
|
||||
},
|
||||
Aligned,
|
||||
Angular,
|
||||
Angular3P,
|
||||
Diameter,
|
||||
Radius,
|
||||
Ordinate {
|
||||
x_type: bool,
|
||||
},
|
||||
ArcLength,
|
||||
}
|
||||
/// A dimension. Definition points follow DXF: `defpt` (10: dimension line point),
|
||||
/// `p13`/`p14` (extension origins), `p15`/`p16` (arc/angle points), `text_mid` (11).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Dimension {
|
||||
pub kind: DimKind,
|
||||
pub defpt: Vec3,
|
||||
pub text_mid: Vec3,
|
||||
#[serde(default)]
|
||||
pub p13: Vec3,
|
||||
#[serde(default)]
|
||||
pub p14: Vec3,
|
||||
#[serde(default)]
|
||||
pub p15: Vec3,
|
||||
#[serde(default)]
|
||||
pub p16: Vec3,
|
||||
/// "" = measured value, "<>" inside = measurement placeholder, " " = suppressed.
|
||||
#[serde(default)]
|
||||
pub text: String,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default)]
|
||||
pub measurement: f64,
|
||||
#[serde(default)]
|
||||
pub text_rotation: f64,
|
||||
/// User moved the text (text_mid is authoritative).
|
||||
#[serde(default)]
|
||||
pub user_text_pos: bool,
|
||||
/// Anonymous block with the rendered geometry (from files); regenerated when edited.
|
||||
#[serde(default)]
|
||||
pub block: Option<String>,
|
||||
/// Per-dimension style overrides (DIMOVERRIDE): DimStyle field names (camelCase) → values,
|
||||
/// merged over the named style.
|
||||
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
|
||||
pub overrides: serde_json::Map<String, serde_json::Value>,
|
||||
/// Associativity: which definition points follow which objects.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub assoc: Vec<DimAssoc>,
|
||||
}
|
||||
|
||||
/// A dimension definition point that follows an object (associative dimensions).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DimAssoc {
|
||||
/// Definition point: "defpt", "p13", "p14", "p15" or "p16".
|
||||
pub point: String,
|
||||
/// The object it is attached to.
|
||||
pub handle: Handle,
|
||||
pub snap: AssocSnap,
|
||||
}
|
||||
|
||||
/// Where on the object an associative definition point sits.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AssocSnap {
|
||||
/// Start point of a line/arc (or polyline vertex 0).
|
||||
Start,
|
||||
/// End point of a line/arc.
|
||||
End,
|
||||
Mid,
|
||||
/// Centre of a circle/arc.
|
||||
Center,
|
||||
/// On a circle/arc at a fixed angle (radians) from its centre.
|
||||
OnCircle {
|
||||
angle: f64,
|
||||
},
|
||||
/// Intersection of this (line) object with another line.
|
||||
Intersection {
|
||||
other: Handle,
|
||||
},
|
||||
/// Vertex `index` of a polyline.
|
||||
Vertex {
|
||||
index: usize,
|
||||
},
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Leader {
|
||||
pub vertices: Vec<Vec3>,
|
||||
#[serde(default = "yes")]
|
||||
pub arrow: bool,
|
||||
#[serde(default)]
|
||||
pub spline: bool,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
}
|
||||
mod helix;
|
||||
pub use helix::*;
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MLeader {
|
||||
pub leaders: Vec<Vec<Vec3>>,
|
||||
pub landing: Vec3,
|
||||
pub dogleg: f64,
|
||||
pub text: Option<MText>,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default = "one")]
|
||||
pub arrow_size: f64,
|
||||
}
|
||||
/// A hatch boundary loop: closed polyline with bulges.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct HatchLoop {
|
||||
pub vertices: Vec<PolyVertex>,
|
||||
#[serde(default)]
|
||||
pub outer: bool,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Hatch {
|
||||
pub pattern: String,
|
||||
pub solid: bool,
|
||||
pub loops: Vec<HatchLoop>,
|
||||
#[serde(default = "one")]
|
||||
pub scale: f64,
|
||||
#[serde(default)]
|
||||
pub angle: f64,
|
||||
#[serde(default)]
|
||||
pub associative: bool,
|
||||
/// 0 normal (odd parity), 1 outer, 2 ignore.
|
||||
#[serde(default)]
|
||||
pub style: u8,
|
||||
#[serde(default)]
|
||||
pub elevation: f64,
|
||||
/// Gradient fill: name + second colour.
|
||||
#[serde(default)]
|
||||
pub gradient: Option<Gradient>,
|
||||
#[serde(default)]
|
||||
pub origin: Vec2,
|
||||
#[serde(default)]
|
||||
pub background: Option<Color>,
|
||||
/// The pattern's line families as a file defined them, for a pattern that isn't in the
|
||||
/// standard library (unit scale and angle, like the library's; empty otherwise).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub pattern_lines: Vec<crate::library::PatternLine>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Gradient {
|
||||
pub name: String,
|
||||
pub color1: Color,
|
||||
pub color2: Color,
|
||||
#[serde(default)]
|
||||
pub angle: f64,
|
||||
#[serde(default)]
|
||||
pub centered: bool,
|
||||
}
|
||||
/// SOLID / TRACE: up to four corners (DXF order 1,2,4,3 when drawn).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Solid {
|
||||
pub corners: [Vec3; 4],
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Face3d {
|
||||
pub corners: [Vec3; 4],
|
||||
#[serde(default)]
|
||||
pub hidden_edges: u8,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RayLine {
|
||||
pub base: Vec3,
|
||||
pub dir: Vec3,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Viewport {
|
||||
pub center: Vec3,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
pub view_center: Vec2,
|
||||
pub view_height: f64,
|
||||
#[serde(default)]
|
||||
pub id: u32,
|
||||
#[serde(default)]
|
||||
pub locked: bool,
|
||||
#[serde(default)]
|
||||
pub frozen_layers: Vec<String>,
|
||||
/// Per-viewport layer colour overrides (VP Color in the Layer Properties Manager).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub layer_colors: Vec<(String, Color)>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Image {
|
||||
pub insert: Vec3,
|
||||
/// One pixel's width (U) and height (V) vectors in drawing units.
|
||||
pub u: Vec3,
|
||||
pub v: Vec3,
|
||||
/// Image size in pixels.
|
||||
pub size: Vec2,
|
||||
/// The image file (its IMAGEDEF object's path).
|
||||
pub path: String,
|
||||
/// The image definition's name (its key in the drawing's image dictionary).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub name: String,
|
||||
/// Clip boundary in pixel coordinates (origin at the top-left corner of the image, y down):
|
||||
/// two opposite corners of a rectangle, or a polygon's vertices. Empty: the whole image.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub clip: Vec<Vec2>,
|
||||
/// The clip boundary is applied.
|
||||
#[serde(default)]
|
||||
pub clipping: bool,
|
||||
/// Display flags: 1 show the image, 2 show it when not aligned with the screen, 4 use the
|
||||
/// clip boundary, 8 transparency on.
|
||||
#[serde(default = "image_display")]
|
||||
pub display: u16,
|
||||
/// Brightness, contrast and fade, 0..=100.
|
||||
#[serde(default = "image_fifty")]
|
||||
pub brightness: u8,
|
||||
#[serde(default = "image_fifty")]
|
||||
pub contrast: u8,
|
||||
#[serde(default)]
|
||||
pub fade: u8,
|
||||
/// The definition's default size of one pixel and its resolution unit (0 none, 2 cm, 5 inch).
|
||||
#[serde(default = "image_pixel")]
|
||||
pub pixel_size: Vec2,
|
||||
#[serde(default)]
|
||||
pub resolution_units: u8,
|
||||
}
|
||||
fn image_display() -> u16 {
|
||||
7
|
||||
}
|
||||
fn image_fifty() -> u8 {
|
||||
50
|
||||
}
|
||||
fn image_pixel() -> Vec2 {
|
||||
Vec2::new(1.0, 1.0)
|
||||
}
|
||||
impl Default for Image {
|
||||
fn default() -> Self {
|
||||
Image {
|
||||
insert: Vec3::ZERO,
|
||||
u: Vec3::new(1.0, 0.0, 0.0),
|
||||
v: Vec3::new(0.0, 1.0, 0.0),
|
||||
size: Vec2::new(1.0, 1.0),
|
||||
path: String::new(),
|
||||
name: String::new(),
|
||||
clip: Vec::new(),
|
||||
clipping: false,
|
||||
display: image_display(),
|
||||
brightness: image_fifty(),
|
||||
contrast: image_fifty(),
|
||||
fade: 0,
|
||||
pixel_size: image_pixel(),
|
||||
resolution_units: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Wipeout {
|
||||
pub boundary: Vec<Vec2>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableCell {
|
||||
pub text: String,
|
||||
#[serde(default)]
|
||||
pub merged: Option<(u32, u32)>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Table {
|
||||
pub insert: Vec3,
|
||||
pub col_widths: Vec<f64>,
|
||||
pub row_heights: Vec<f64>,
|
||||
pub cells: Vec<Vec<TableCell>>,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default = "default_text_h")]
|
||||
pub text_height: f64,
|
||||
/// First row is a title (merged across, larger text).
|
||||
#[serde(default)]
|
||||
pub title: bool,
|
||||
/// The row after the title holds column headers.
|
||||
#[serde(default)]
|
||||
pub header: bool,
|
||||
}
|
||||
fn default_text_h() -> f64 {
|
||||
0.18
|
||||
}
|
||||
/// A raw DXF group: kept for round-tripping entities we do not model.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RawTag {
|
||||
pub code: i32,
|
||||
pub value: String,
|
||||
}
|
||||
mod region;
|
||||
pub use region::*;
|
||||
|
||||
mod block;
|
||||
mod common;
|
||||
mod curves;
|
||||
mod dim;
|
||||
mod fill;
|
||||
mod layout;
|
||||
mod text;
|
||||
|
||||
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
|
||||
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
|
||||
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyline3d, RayLine, Solid};
|
||||
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
||||
pub use fill::{Gradient, Hatch, HatchLoop, Wipeout};
|
||||
pub use layout::{Image, Table, TableCell, Viewport};
|
||||
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Unknown {
|
||||
pub dxf_type: String,
|
||||
@@ -660,6 +69,7 @@ pub enum EntityKind {
|
||||
LwPolyline(LwPolyline),
|
||||
Polyline3d(Polyline3d),
|
||||
Spline(GSpline),
|
||||
Helix(Helix),
|
||||
Ray(RayLine),
|
||||
XLine(RayLine),
|
||||
Text(Text),
|
||||
@@ -667,16 +77,19 @@ pub enum EntityKind {
|
||||
AttDef(Attrib),
|
||||
Insert(Insert),
|
||||
Dimension(Dimension),
|
||||
MLine(MLine),
|
||||
Leader(Leader),
|
||||
MLeader(MLeader),
|
||||
Hatch(Hatch),
|
||||
Solid(Solid),
|
||||
Trace(Solid),
|
||||
Face3d(Face3d),
|
||||
Region(Region),
|
||||
Viewport(Viewport),
|
||||
Image(Image),
|
||||
Wipeout(Wipeout),
|
||||
Table(Table),
|
||||
Tolerance(crate::Tolerance),
|
||||
Unknown(Unknown),
|
||||
}
|
||||
|
||||
@@ -710,6 +123,7 @@ impl EntityKind {
|
||||
EntityKind::LwPolyline(_) => "Polyline",
|
||||
EntityKind::Polyline3d(_) => "3D Polyline",
|
||||
EntityKind::Spline(_) => "Spline",
|
||||
EntityKind::Helix(_) => "Helix",
|
||||
EntityKind::Ray(_) => "Ray",
|
||||
EntityKind::XLine(_) => "Xline",
|
||||
EntityKind::Text(_) => "Text",
|
||||
@@ -717,16 +131,19 @@ impl EntityKind {
|
||||
EntityKind::AttDef(_) => "Attribute Definition",
|
||||
EntityKind::Insert(_) => "Block Reference",
|
||||
EntityKind::Dimension(_) => "Dimension",
|
||||
EntityKind::MLine(_) => "MLine",
|
||||
EntityKind::Leader(_) => "Leader",
|
||||
EntityKind::MLeader(_) => "Multileader",
|
||||
EntityKind::Hatch(_) => "Hatch",
|
||||
EntityKind::Solid(_) => "2D Solid",
|
||||
EntityKind::Trace(_) => "Trace",
|
||||
EntityKind::Face3d(_) => "3D Face",
|
||||
EntityKind::Region(_) => "Region",
|
||||
EntityKind::Viewport(_) => "Viewport",
|
||||
EntityKind::Image(_) => "Raster Image",
|
||||
EntityKind::Wipeout(_) => "Wipeout",
|
||||
EntityKind::Table(_) => "Table",
|
||||
EntityKind::Tolerance(_) => "Tolerance",
|
||||
EntityKind::Unknown(_) => "Proxy",
|
||||
}
|
||||
}
|
||||
@@ -741,6 +158,7 @@ impl EntityKind {
|
||||
EntityKind::LwPolyline(_) => "LWPOLYLINE",
|
||||
EntityKind::Polyline3d(_) => "POLYLINE",
|
||||
EntityKind::Spline(_) => "SPLINE",
|
||||
EntityKind::Helix(_) => "HELIX",
|
||||
EntityKind::Ray(_) => "RAY",
|
||||
EntityKind::XLine(_) => "XLINE",
|
||||
EntityKind::Text(_) => "TEXT",
|
||||
@@ -748,16 +166,19 @@ impl EntityKind {
|
||||
EntityKind::AttDef(_) => "ATTDEF",
|
||||
EntityKind::Insert(_) => "INSERT",
|
||||
EntityKind::Dimension(_) => "DIMENSION",
|
||||
EntityKind::MLine(_) => "MLINE",
|
||||
EntityKind::Leader(_) => "LEADER",
|
||||
EntityKind::MLeader(_) => "MULTILEADER",
|
||||
EntityKind::Hatch(_) => "HATCH",
|
||||
EntityKind::Solid(_) => "SOLID",
|
||||
EntityKind::Trace(_) => "TRACE",
|
||||
EntityKind::Face3d(_) => "3DFACE",
|
||||
EntityKind::Region(_) => "REGION",
|
||||
EntityKind::Viewport(_) => "VIEWPORT",
|
||||
EntityKind::Image(_) => "IMAGE",
|
||||
EntityKind::Wipeout(_) => "WIPEOUT",
|
||||
EntityKind::Table(_) => "ACAD_TABLE",
|
||||
EntityKind::Tolerance(_) => "TOLERANCE",
|
||||
EntityKind::Unknown(u) => u.dxf_type.as_str(),
|
||||
}
|
||||
}
|
||||
@@ -788,6 +209,7 @@ impl EntityKind {
|
||||
v
|
||||
}
|
||||
EntityKind::Spline(s) => vec![Prim::Spline(s.clone())],
|
||||
EntityKind::Helix(h) => vec![Prim::Spline(h.spline())],
|
||||
EntityKind::Ray(r) => vec![Prim::Infinite { base: r.base.xy(), dir: r.dir.xy().normalized(), ray: true }],
|
||||
EntityKind::XLine(r) => vec![Prim::Infinite { base: r.base.xy(), dir: r.dir.xy().normalized(), ray: false }],
|
||||
EntityKind::Solid(s) | EntityKind::Trace(s) => {
|
||||
@@ -799,6 +221,7 @@ impl EntityKind {
|
||||
let pts = [c[0].xy(), c[1].xy(), c[2].xy(), c[3].xy(), c[0].xy()];
|
||||
pts.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect()
|
||||
}
|
||||
EntityKind::Region(r) => r.segments().into_iter().map(Prim::Seg).collect(),
|
||||
EntityKind::Hatch(h) => {
|
||||
h.loops.iter().flat_map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.segments()).map(Prim::Seg).collect()
|
||||
}
|
||||
@@ -823,13 +246,16 @@ impl EntityKind {
|
||||
EntityKind::AttDef(a) => vec![Prim::Point(a.text.insert.xy())],
|
||||
EntityKind::Insert(i) => vec![Prim::Point(i.insert.xy())],
|
||||
EntityKind::Dimension(d) => vec![Prim::Point(d.defpt.xy())],
|
||||
EntityKind::MLine(m) => m.segments().into_iter().map(Prim::Seg).collect(),
|
||||
EntityKind::MLeader(m) => m
|
||||
.leaders
|
||||
.iter()
|
||||
.flat_map(|l| l.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(w.first()?.xy(), w.get(1)?.xy()))))))
|
||||
.chain(m.block.iter().map(|b| Prim::Point(b.insert.xy())))
|
||||
.collect(),
|
||||
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
|
||||
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
|
||||
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
|
||||
EntityKind::Unknown(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -900,21 +326,33 @@ impl EntityKind {
|
||||
p.const_width *= s;
|
||||
}
|
||||
EntityKind::Polyline3d(p) => p.points.iter_mut().for_each(t3),
|
||||
EntityKind::Spline(sp) => {
|
||||
for c in sp.control.iter_mut().chain(sp.fit.iter_mut()) {
|
||||
*c = m.apply(*c);
|
||||
}
|
||||
EntityKind::Spline(sp) => sp.transform(m),
|
||||
EntityKind::Helix(h) => {
|
||||
let sp = m.apply(h.start_point().xy());
|
||||
t3(&mut h.center);
|
||||
h.base_radius *= s;
|
||||
h.top_radius *= s;
|
||||
h.height *= s;
|
||||
h.start_angle = h.center.xy().angle_to(sp);
|
||||
// Mirrored, the twist turns the other way.
|
||||
h.ccw ^= mirror;
|
||||
}
|
||||
EntityKind::Ray(r) | EntityKind::XLine(r) => {
|
||||
t3(&mut r.base);
|
||||
r.dir = m.apply_vec(r.dir.xy()).normalized().to3(0.0);
|
||||
}
|
||||
EntityKind::Text(t) => transform_text(t, m, s, rot, mirror),
|
||||
EntityKind::AttDef(a) => transform_text(&mut a.text, m, s, rot, mirror),
|
||||
EntityKind::AttDef(a) => {
|
||||
transform_text(&mut a.text, m, s, rot, mirror);
|
||||
a.transform_multiline(m);
|
||||
}
|
||||
EntityKind::MText(t) => {
|
||||
t3(&mut t.insert);
|
||||
t.height *= s;
|
||||
t.width *= s;
|
||||
if let Some(c) = &mut t.columns {
|
||||
c.scale(s);
|
||||
}
|
||||
t.rotation = cadcraft_geom::norm_angle(t.rotation + rot);
|
||||
}
|
||||
EntityKind::Insert(i) => {
|
||||
@@ -929,6 +367,7 @@ impl EntityKind {
|
||||
}
|
||||
for a in &mut i.attribs {
|
||||
transform_text(&mut a.text, m, s, rot, false);
|
||||
a.transform_multiline(m);
|
||||
}
|
||||
i.col_spacing *= s;
|
||||
i.row_spacing *= s;
|
||||
@@ -940,8 +379,15 @@ impl EntityKind {
|
||||
if let DimKind::Linear { rotation } = &mut d.kind {
|
||||
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
|
||||
}
|
||||
d.marks.transform(&t3, rot, s, mirror);
|
||||
d.block = None;
|
||||
}
|
||||
EntityKind::MLine(ml) => {
|
||||
ml.vertices.iter_mut().for_each(|v| t3(&mut v.p));
|
||||
ml.vertices.iter_mut().flat_map(|v| v.cuts.iter_mut()).for_each(|c| (c.start, c.end) = (c.start * s, c.end * s));
|
||||
// Mirrored, the elements change sides.
|
||||
ml.scale *= if mirror { -s } else { s };
|
||||
}
|
||||
EntityKind::Leader(l) => l.vertices.iter_mut().for_each(t3),
|
||||
EntityKind::MLeader(ml) => {
|
||||
for l in &mut ml.leaders {
|
||||
@@ -951,6 +397,18 @@ impl EntityKind {
|
||||
if let Some(t) = &mut ml.text {
|
||||
t3(&mut t.insert);
|
||||
t.height *= s;
|
||||
t.width *= s;
|
||||
if let Some(c) = &mut t.columns {
|
||||
c.scale(s);
|
||||
}
|
||||
}
|
||||
if let Some(b) = &mut ml.block {
|
||||
// Transformed exactly like a block reference.
|
||||
let mut k = EntityKind::Insert(b.clone());
|
||||
k.transform(m);
|
||||
if let EntityKind::Insert(nb) = k {
|
||||
*b = nb;
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::Hatch(h) => {
|
||||
@@ -968,6 +426,14 @@ impl EntityKind {
|
||||
}
|
||||
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(t3),
|
||||
EntityKind::Face3d(f) => f.corners.iter_mut().for_each(t3),
|
||||
EntityKind::Region(r) => {
|
||||
for v in r.loops.iter_mut().flat_map(|l| l.vertices.iter_mut()) {
|
||||
v.p = m.apply(v.p);
|
||||
if mirror {
|
||||
v.bulge = -v.bulge;
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::Viewport(v) => {
|
||||
t3(&mut v.center);
|
||||
v.width *= s;
|
||||
@@ -980,17 +446,33 @@ impl EntityKind {
|
||||
}
|
||||
EntityKind::Wipeout(w) => w.boundary.iter_mut().for_each(|p| *p = m.apply(*p)),
|
||||
EntityKind::Table(t) => {
|
||||
if let Some(b) = &mut t.breaks {
|
||||
b.height *= s;
|
||||
b.spacing *= s;
|
||||
b.heights.iter_mut().for_each(|h| *h *= s);
|
||||
b.offsets.iter_mut().for_each(|o| *o = m.apply_vec(*o));
|
||||
}
|
||||
t3(&mut t.insert);
|
||||
t.col_widths.iter_mut().for_each(|w| *w *= s);
|
||||
t.row_heights.iter_mut().for_each(|h| *h *= s);
|
||||
t.text_height *= s;
|
||||
}
|
||||
EntityKind::Tolerance(t) => {
|
||||
t3(&mut t.insert);
|
||||
// Like text with MIRRTEXT = 0: a mirrored frame keeps reading left to right.
|
||||
let a = if mirror { t.rotation() } else { t.rotation() + rot };
|
||||
t.dir = Vec2::from_angle(cadcraft_geom::norm_angle(a)).to3(0.0);
|
||||
}
|
||||
EntityKind::Unknown(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Grip points (editable defining points), in display order.
|
||||
pub fn grips(&self) -> Vec<Vec2> {
|
||||
// A broken table has a grip for each part.
|
||||
if let EntityKind::Table(t) = self {
|
||||
return t.grip_points();
|
||||
}
|
||||
match self {
|
||||
EntityKind::Line(l) => vec![l.a.xy(), l.a.xy().mid(l.b.xy()), l.b.xy()],
|
||||
EntityKind::Point(p) => vec![p.p.xy()],
|
||||
@@ -1011,9 +493,12 @@ impl EntityKind {
|
||||
EntityKind::LwPolyline(p) => {
|
||||
let mut g: Vec<Vec2> = Vec::new();
|
||||
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
|
||||
// Compute the segments once, not once per vertex: rebuilding the whole segment
|
||||
// vector inside the loop is quadratic in the vertex count (CWE-407).
|
||||
let segs = pl.segments();
|
||||
for (i, v) in p.vertices.iter().enumerate() {
|
||||
g.push(v.p);
|
||||
if let Some(s) = pl.segments().get(i) {
|
||||
if let Some(s) = segs.get(i) {
|
||||
g.push(s.mid());
|
||||
}
|
||||
}
|
||||
@@ -1027,12 +512,14 @@ impl EntityKind {
|
||||
s.fit.clone()
|
||||
}
|
||||
}
|
||||
EntityKind::Helix(h) => vec![h.center.xy(), h.start_point().xy(), h.end_point().xy()],
|
||||
EntityKind::Ray(r) | EntityKind::XLine(r) => vec![r.base.xy(), r.base.xy() + r.dir.xy()],
|
||||
EntityKind::Text(t) => vec![t.justify_point()],
|
||||
EntityKind::MText(t) => vec![t.insert.xy()],
|
||||
EntityKind::AttDef(a) => vec![a.text.justify_point()],
|
||||
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(),
|
||||
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
|
||||
EntityKind::MLine(m) => m.points(),
|
||||
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
|
||||
EntityKind::MLeader(m) => m.leaders.iter().flat_map(|l| l.iter().map(|v| v.xy())).chain(std::iter::once(m.landing.xy())).collect(),
|
||||
EntityKind::Hatch(h) => {
|
||||
@@ -1041,6 +528,7 @@ impl EntityKind {
|
||||
}
|
||||
EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.iter().map(|c| c.xy()).collect(),
|
||||
EntityKind::Face3d(f) => f.corners.iter().map(|c| c.xy()).collect(),
|
||||
EntityKind::Region(r) => vec![r.bounds().center()],
|
||||
EntityKind::Viewport(v) => {
|
||||
let c = v.center.xy();
|
||||
let h = Vec2::new(v.width / 2.0, v.height / 2.0);
|
||||
@@ -1049,6 +537,7 @@ impl EntityKind {
|
||||
EntityKind::Image(i) => vec![i.insert.xy()],
|
||||
EntityKind::Wipeout(w) => w.boundary.clone(),
|
||||
EntityKind::Table(t) => vec![t.insert.xy()],
|
||||
EntityKind::Tolerance(t) => vec![t.insert.xy()],
|
||||
EntityKind::Unknown(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -1067,3 +556,30 @@ fn transform_text(t: &mut Text, m: &Mat3, s: f64, rot: f64, mirror: bool) {
|
||||
// MIRRTEXT = 0 (the default): mirrored text keeps reading left to right.
|
||||
t.rotation = cadcraft_geom::norm_angle(t.rotation + if mirror { 0.0 } else { rot });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod grip_tests {
|
||||
use super::*;
|
||||
use cadcraft_geom::PolyVertex;
|
||||
|
||||
#[test]
|
||||
fn handle_parse_hex_accepts_only_hex_digits() {
|
||||
assert_eq!(Handle::parse_hex("1a"), Some(Handle(0x1A)));
|
||||
assert_eq!(Handle::parse_hex(" 1A "), Some(Handle(0x1A)));
|
||||
for bad in ["+1A", "-1A", "", "+", "1 A"] {
|
||||
assert_eq!(Handle::parse_hex(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyline_grips_are_vertices_and_midpoints() {
|
||||
// Grips are each vertex plus the midpoint of each segment; the segment vector is computed
|
||||
// once rather than rebuilt per vertex (CWE-407, row 35).
|
||||
let verts: Vec<PolyVertex> = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
|
||||
let e = EntityKind::LwPolyline(LwPolyline { vertices: verts, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false });
|
||||
let g = e.grips();
|
||||
// 3 vertices + 2 segment midpoints.
|
||||
assert_eq!(g.len(), 5, "{g:?}");
|
||||
assert!(g.contains(&Vec2::new(0.0, 0.0)) && g.contains(&Vec2::new(5.0, 0.0)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
use super::common::{Common, Lineweight};
|
||||
use super::text::{MText, Text};
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Attrib {
|
||||
pub tag: String,
|
||||
pub text: Text,
|
||||
#[serde(default)]
|
||||
pub invisible: bool,
|
||||
#[serde(default)]
|
||||
pub constant: bool,
|
||||
#[serde(default)]
|
||||
pub prompt: String,
|
||||
/// An attribute's own properties; each one left unset follows the attribute definition.
|
||||
#[serde(default, skip_serializing_if = "AttribProps::is_empty")]
|
||||
pub props: AttribProps,
|
||||
/// A multiline attribute (DXF attribute type 2, or 4 for a definition): its text as
|
||||
/// multiline text. `text.value` holds the plain text, which value edits change.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub multiline: Option<MultilineAttrib>,
|
||||
/// Its other modes: Verify, Preset and Lock position.
|
||||
#[serde(default, skip_serializing_if = "AttribModes::is_default")]
|
||||
pub modes: AttribModes,
|
||||
}
|
||||
|
||||
/// An attribute's modes beyond invisible and constant.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AttribModes {
|
||||
/// Verify: the value is asked for twice when the block is inserted (DXF flag 4).
|
||||
#[serde(default)]
|
||||
pub verify: bool,
|
||||
/// Preset: the default value is used without asking (DXF flag 8).
|
||||
#[serde(default)]
|
||||
pub preset: bool,
|
||||
/// Lock position: the attribute can't be moved on its own within a reference (DXF group
|
||||
/// 280 after the flags). A reference's attributes take it from their definitions.
|
||||
#[serde(default)]
|
||||
pub lock_position: bool,
|
||||
}
|
||||
|
||||
impl AttribModes {
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
/// The modes of a reference's attribute made from a definition with these: AutoCAD keeps
|
||||
/// only Lock position there.
|
||||
pub fn for_reference(self) -> Self {
|
||||
AttribModes { lock_position: self.lock_position, ..Self::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The multiline text of a multiline attribute.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MultilineAttrib {
|
||||
pub mtext: MText,
|
||||
/// The plain text `mtext`'s contents read as: an attribute whose value differs was edited
|
||||
/// since, and its value replaces the contents.
|
||||
pub read_as: String,
|
||||
}
|
||||
|
||||
impl MultilineAttrib {
|
||||
/// This text placed by `m` (a block reference's transform, for its attribute made from a
|
||||
/// definition).
|
||||
pub fn transformed(&self, m: &Mat3) -> MultilineAttrib {
|
||||
let mut k = EntityKind::MText(self.mtext.clone());
|
||||
k.transform(m);
|
||||
let mtext = if let EntityKind::MText(t) = k { t } else { self.mtext.clone() };
|
||||
MultilineAttrib { mtext, read_as: self.read_as.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Attrib {
|
||||
/// Move a multiline attribute's text by `m` along with the attribute (nothing for others).
|
||||
pub fn transform_multiline(&mut self, m: &Mat3) {
|
||||
if let Some(ml) = &mut self.multiline {
|
||||
*ml = ml.transformed(m);
|
||||
}
|
||||
}
|
||||
|
||||
/// A multiline attribute's text as drawn and saved: its multiline text, with the contents
|
||||
/// replaced by the value when the value was edited since it was read.
|
||||
pub fn multiline_text(&self) -> Option<MText> {
|
||||
let m = self.multiline.as_ref()?;
|
||||
let mut t = m.mtext.clone();
|
||||
if self.text.value != m.read_as {
|
||||
t.contents = mtext_literal(&self.text.value);
|
||||
}
|
||||
Some(t)
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` as MTEXT contents that read back as `s`: backslashes and braces escaped, line breaks as
|
||||
/// paragraph breaks.
|
||||
pub fn mtext_literal(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'{' => out.push_str("\\{"),
|
||||
'}' => out.push_str("\\}"),
|
||||
'\n' => out.push_str("\\P"),
|
||||
'\r' => {}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Properties set on one attribute of a block reference (an ATTRIB's layer, colour, linetype and
|
||||
/// lineweight), overriding those of its definition.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AttribProps {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub layer: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<Color>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linetype: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub lineweight: Option<Lineweight>,
|
||||
}
|
||||
|
||||
impl AttribProps {
|
||||
/// Nothing set: the attribute is drawn with its definition's properties.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == AttribProps::default()
|
||||
}
|
||||
/// `base` (the definition's properties) with the ones set here in place.
|
||||
pub fn over(&self, base: &Common) -> Common {
|
||||
Common {
|
||||
layer: self.layer.clone().unwrap_or_else(|| base.layer.clone()),
|
||||
color: self.color.unwrap_or(base.color),
|
||||
linetype: self.linetype.clone().unwrap_or_else(|| base.linetype.clone()),
|
||||
lineweight: self.lineweight.unwrap_or(base.lineweight),
|
||||
..base.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Insert {
|
||||
pub block: String,
|
||||
pub insert: Vec3,
|
||||
#[serde(default = "unit_scale")]
|
||||
pub scale: Vec3,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
#[serde(default)]
|
||||
pub attribs: Vec<Attrib>,
|
||||
#[serde(default = "one_u")]
|
||||
pub cols: u32,
|
||||
#[serde(default = "one_u")]
|
||||
pub rows: u32,
|
||||
#[serde(default)]
|
||||
pub col_spacing: f64,
|
||||
#[serde(default)]
|
||||
pub row_spacing: f64,
|
||||
}
|
||||
|
||||
fn unit_scale() -> Vec3 {
|
||||
Vec3::new(1.0, 1.0, 1.0)
|
||||
}
|
||||
|
||||
fn one_u() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
impl Insert {
|
||||
/// Block-to-world transform (2D part).
|
||||
pub fn transform(&self, base: Vec2) -> Mat3 {
|
||||
Mat3::translate(self.insert.xy())
|
||||
.then_before(Mat3::rotate(self.rotation))
|
||||
.then_before(Mat3::scale(self.scale.x, self.scale.y))
|
||||
.then_before(Mat3::translate(-base))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use super::*;
|
||||
|
||||
/// A database handle (DXF group 5), unique per drawing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct Handle(pub u64);
|
||||
|
||||
impl Handle {
|
||||
pub fn hex(self) -> String {
|
||||
format!("{:X}", self.0)
|
||||
}
|
||||
pub fn parse_hex(s: &str) -> Option<Handle> {
|
||||
let s = s.trim();
|
||||
if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
u64::from_str_radix(s, 16).ok().map(Handle)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lineweight in hundredths of a millimetre, or a logical value.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Lineweight {
|
||||
#[default]
|
||||
ByLayer,
|
||||
ByBlock,
|
||||
Default,
|
||||
/// 0..=211 (hundredths of mm).
|
||||
Mm100(u16),
|
||||
}
|
||||
|
||||
impl Lineweight {
|
||||
/// The standard lineweight values (mm × 100).
|
||||
pub const STANDARD: [u16; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211];
|
||||
pub fn to_dxf(self) -> i16 {
|
||||
match self {
|
||||
Lineweight::ByLayer => -1,
|
||||
Lineweight::ByBlock => -2,
|
||||
Lineweight::Default => -3,
|
||||
Lineweight::Mm100(v) => v.min(211) as i16,
|
||||
}
|
||||
}
|
||||
pub fn from_dxf(v: i16) -> Lineweight {
|
||||
match v {
|
||||
-2 => Lineweight::ByBlock,
|
||||
-3 => Lineweight::Default,
|
||||
0..=211 => Lineweight::Mm100(v as u16),
|
||||
_ => Lineweight::ByLayer,
|
||||
}
|
||||
}
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
Lineweight::ByLayer => "ByLayer".into(),
|
||||
Lineweight::ByBlock => "ByBlock".into(),
|
||||
Lineweight::Default => "Default".into(),
|
||||
Lineweight::Mm100(v) => format!("{:.2} mm", f64::from(v) / 100.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transparency: ByLayer, ByBlock, or 0..=90 percent.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Transparency {
|
||||
#[default]
|
||||
ByLayer,
|
||||
ByBlock,
|
||||
Percent(u8),
|
||||
}
|
||||
|
||||
impl Transparency {
|
||||
/// "ByLayer", "ByBlock" or the percentage ("50").
|
||||
pub fn name(&self) -> String {
|
||||
match self {
|
||||
Transparency::ByLayer => "ByLayer".into(),
|
||||
Transparency::ByBlock => "ByBlock".into(),
|
||||
Transparency::Percent(p) => p.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Properties every entity has.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Common {
|
||||
pub layer: String,
|
||||
pub color: Color,
|
||||
pub linetype: String,
|
||||
pub lineweight: Lineweight,
|
||||
pub ltscale: f64,
|
||||
pub transparency: Transparency,
|
||||
pub visible: bool,
|
||||
pub thickness: f64,
|
||||
pub extrusion: Vec3,
|
||||
/// Named plot style: `ByLayer`, `ByBlock` or a style of the layout's named (`.stb`) plot
|
||||
/// style table.
|
||||
pub plot_style: String,
|
||||
/// The annotation scales an annotative object supports (empty: not annotative).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub anno_scales: Vec<crate::AnnoScale>,
|
||||
/// Other applications' extended data (xdata) as read from the drawing file: whole
|
||||
/// applications, each from its `1001` group on. It is part of the object, so a copy of the
|
||||
/// object (COPY, MIRROR, ARRAY, paste) carries it, as in AutoCAD.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub xdata: Vec<RawTag>,
|
||||
}
|
||||
|
||||
impl Default for Common {
|
||||
fn default() -> Self {
|
||||
Common {
|
||||
layer: "0".into(),
|
||||
color: Color::ByLayer,
|
||||
linetype: "ByLayer".into(),
|
||||
lineweight: Lineweight::ByLayer,
|
||||
ltscale: 1.0,
|
||||
transparency: Transparency::ByLayer,
|
||||
visible: true,
|
||||
thickness: 0.0,
|
||||
extrusion: Vec3::Z,
|
||||
plot_style: "ByLayer".into(),
|
||||
anno_scales: Vec::new(),
|
||||
xdata: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A raw DXF group: kept for round-tripping entities we do not model.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RawTag {
|
||||
pub code: i32,
|
||||
pub value: String,
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Line {
|
||||
pub a: Vec3,
|
||||
pub b: Vec3,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Point {
|
||||
pub p: Vec3,
|
||||
#[serde(default)]
|
||||
pub angle: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Circle {
|
||||
pub center: Vec3,
|
||||
pub radius: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Arc {
|
||||
pub center: Vec3,
|
||||
pub radius: f64,
|
||||
/// Radians, CCW.
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Ellipse {
|
||||
pub center: Vec3,
|
||||
pub major: Vec3,
|
||||
pub ratio: f64,
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct LwPolyline {
|
||||
pub vertices: Vec<PolyVertex>,
|
||||
pub closed: bool,
|
||||
#[serde(default)]
|
||||
pub const_width: f64,
|
||||
#[serde(default)]
|
||||
pub elevation: f64,
|
||||
/// Polyline linetype generation (PLINEGEN).
|
||||
#[serde(default)]
|
||||
pub plinegen: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Polyline3d {
|
||||
pub points: Vec<Vec3>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// SOLID / TRACE: up to four corners (DXF order 1,2,4,3 when drawn).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Solid {
|
||||
pub corners: [Vec3; 4],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Face3d {
|
||||
pub corners: [Vec3; 4],
|
||||
#[serde(default)]
|
||||
pub hidden_edges: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RayLine {
|
||||
pub base: Vec3,
|
||||
pub dir: Vec3,
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
use super::block::Insert;
|
||||
use super::common::Handle;
|
||||
use super::text::MText;
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DimKind {
|
||||
/// Rotated linear dimension (horizontal = 0, vertical = 90°).
|
||||
Linear {
|
||||
rotation: f64,
|
||||
},
|
||||
Aligned,
|
||||
Angular,
|
||||
Angular3P,
|
||||
Diameter,
|
||||
Radius,
|
||||
Ordinate {
|
||||
x_type: bool,
|
||||
},
|
||||
ArcLength,
|
||||
}
|
||||
|
||||
/// A dimension. Definition points follow DXF: `defpt` (10: dimension line point),
|
||||
/// `p13`/`p14` (extension origins), `p15`/`p16` (arc/angle points), `text_mid` (11).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Dimension {
|
||||
pub kind: DimKind,
|
||||
pub defpt: Vec3,
|
||||
pub text_mid: Vec3,
|
||||
#[serde(default)]
|
||||
pub p13: Vec3,
|
||||
#[serde(default)]
|
||||
pub p14: Vec3,
|
||||
#[serde(default)]
|
||||
pub p15: Vec3,
|
||||
#[serde(default)]
|
||||
pub p16: Vec3,
|
||||
/// "" = measured value, "<>" inside = measurement placeholder, " " = suppressed.
|
||||
#[serde(default)]
|
||||
pub text: String,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default)]
|
||||
pub measurement: f64,
|
||||
#[serde(default)]
|
||||
pub text_rotation: f64,
|
||||
/// User moved the text (text_mid is authoritative).
|
||||
#[serde(default)]
|
||||
pub user_text_pos: bool,
|
||||
/// Anonymous block with the rendered geometry (from files); regenerated when edited.
|
||||
#[serde(default)]
|
||||
pub block: Option<String>,
|
||||
/// Per-dimension style overrides (DIMOVERRIDE): DimStyle field names (camelCase) → values,
|
||||
/// merged over the named style.
|
||||
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
|
||||
pub overrides: serde_json::Map<String, serde_json::Value>,
|
||||
/// Associativity: which definition points follow which objects.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub assoc: Vec<DimAssoc>,
|
||||
/// Oblique extension lines, jogs, breaks and inspection frames.
|
||||
#[serde(default, skip_serializing_if = "DimMarks::is_empty")]
|
||||
pub marks: DimMarks,
|
||||
}
|
||||
|
||||
/// What dimension edits add to a dimension's drawing: DIMEDIT Oblique, DIMJOGLINE, DIMJOGGED,
|
||||
/// DIMBREAK and DIMINSPECT.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DimMarks {
|
||||
/// Angle (radians) of the extension lines of a linear or aligned dimension; None =
|
||||
/// perpendicular to the dimension line.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub oblique: Option<f64>,
|
||||
/// A jog on the dimension line of a linear or aligned dimension, at this point (DIMJOGLINE).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub jog_line: Option<Vec3>,
|
||||
/// A jogged radius dimension (DIMJOGGED).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub jogged: Option<JoggedRadius>,
|
||||
/// Gaps in the dimension and extension lines (DIMBREAK).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub breaks: Vec<DimBreak>,
|
||||
/// Inspection frame, label and rate (DIMINSPECT).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub inspect: Option<Inspection>,
|
||||
}
|
||||
|
||||
impl DimMarks {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == DimMarks::default()
|
||||
}
|
||||
|
||||
/// Transform the points and angles (part of [`EntityKind::transform`]).
|
||||
pub(super) fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
|
||||
if let Some(a) = &mut self.oblique {
|
||||
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
|
||||
}
|
||||
if let Some(j) = &mut self.jog_line {
|
||||
t3(j);
|
||||
}
|
||||
if let Some(j) = &mut self.jogged {
|
||||
t3(&mut j.center);
|
||||
t3(&mut j.jog);
|
||||
}
|
||||
for b in &mut self.breaks {
|
||||
t3(&mut b.at);
|
||||
b.size *= s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The definition of a jogged radius dimension: the dimension line starts at an overriding
|
||||
/// centre and jogs on its way to the arc.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JoggedRadius {
|
||||
/// Where the dimension line starts instead of the true centre.
|
||||
pub center: Vec3,
|
||||
/// The middle of the jog.
|
||||
pub jog: Vec3,
|
||||
}
|
||||
|
||||
/// A gap in a dimension's lines: everything within `size / 2` of `at` is left out.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DimBreak {
|
||||
pub at: Vec3,
|
||||
pub size: f64,
|
||||
/// Made by DIMBREAK Auto (recomputed by the next Auto) rather than picked by hand.
|
||||
pub auto: bool,
|
||||
}
|
||||
|
||||
/// An inspection dimension (DIMINSPECT).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Inspection {
|
||||
/// Frame shape: 0 round ends, 1 angular ends, 2 none.
|
||||
pub shape: u8,
|
||||
/// Text left of the value ("" = none).
|
||||
pub label: String,
|
||||
/// Inspection rate right of the value ("" = none).
|
||||
pub rate: String,
|
||||
}
|
||||
|
||||
/// A dimension definition point that follows an object (associative dimensions).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DimAssoc {
|
||||
/// Definition point: "defpt", "p13", "p14", "p15" or "p16".
|
||||
pub point: String,
|
||||
/// The object it is attached to.
|
||||
pub handle: Handle,
|
||||
pub snap: AssocSnap,
|
||||
}
|
||||
|
||||
/// Where on the object an associative definition point sits.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AssocSnap {
|
||||
/// Start point of a line/arc (or polyline vertex 0).
|
||||
Start,
|
||||
/// End point of a line/arc.
|
||||
End,
|
||||
Mid,
|
||||
/// Centre of a circle/arc.
|
||||
Center,
|
||||
/// On a circle/arc at a fixed angle (radians) from its centre.
|
||||
OnCircle {
|
||||
angle: f64,
|
||||
},
|
||||
/// Intersection of this (line) object with another line.
|
||||
Intersection {
|
||||
other: Handle,
|
||||
},
|
||||
/// Vertex `index` of a polyline.
|
||||
Vertex {
|
||||
index: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Leader {
|
||||
pub vertices: Vec<Vec3>,
|
||||
#[serde(default = "yes")]
|
||||
pub arrow: bool,
|
||||
#[serde(default)]
|
||||
pub spline: bool,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MLeader {
|
||||
pub leaders: Vec<Vec<Vec3>>,
|
||||
pub landing: Vec3,
|
||||
pub dogleg: f64,
|
||||
pub text: Option<MText>,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default = "one")]
|
||||
pub arrow_size: f64,
|
||||
/// Leader lines are smooth curves through their points (leader type Spline). An empty
|
||||
/// `leaders` is a multileader without a leader line (leader type None).
|
||||
#[serde(default)]
|
||||
pub spline: bool,
|
||||
/// Block content in place of the text: a block reference placed at the landing.
|
||||
#[serde(default)]
|
||||
pub block: Option<Insert>,
|
||||
}
|
||||
|
||||
impl MLeader {
|
||||
/// Each leader line as drawn: through its points to the landing, smoothed for spline leaders.
|
||||
pub fn leader_paths(&self) -> Vec<Vec<Vec2>> {
|
||||
self.leaders
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let pts: Vec<Vec2> = l.iter().map(|v| v.xy()).chain(std::iter::once(self.landing.xy())).collect();
|
||||
if self.spline && pts.len() > 2 { GSpline::from_fit_points(&pts).tessellate(1e-3) } else { pts }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use super::common::Handle;
|
||||
use super::*;
|
||||
|
||||
/// A hatch boundary loop: closed polyline with bulges.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct HatchLoop {
|
||||
pub vertices: Vec<PolyVertex>,
|
||||
#[serde(default)]
|
||||
pub outer: bool,
|
||||
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
|
||||
/// hatch re-fills the loop from them when they change.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub sources: Vec<Handle>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Hatch {
|
||||
pub pattern: String,
|
||||
pub solid: bool,
|
||||
pub loops: Vec<HatchLoop>,
|
||||
#[serde(default = "one")]
|
||||
pub scale: f64,
|
||||
#[serde(default)]
|
||||
pub angle: f64,
|
||||
#[serde(default)]
|
||||
pub associative: bool,
|
||||
/// 0 normal (odd parity), 1 outer, 2 ignore.
|
||||
#[serde(default)]
|
||||
pub style: u8,
|
||||
#[serde(default)]
|
||||
pub elevation: f64,
|
||||
/// Gradient fill: name + second colour.
|
||||
#[serde(default)]
|
||||
pub gradient: Option<Gradient>,
|
||||
#[serde(default)]
|
||||
pub origin: Vec2,
|
||||
#[serde(default)]
|
||||
pub background: Option<Color>,
|
||||
/// The pattern's line families as a file defined them, for a pattern that isn't in the
|
||||
/// standard library (unit scale and angle, like the library's; empty otherwise).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub pattern_lines: Vec<crate::library::PatternLine>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Gradient {
|
||||
pub name: String,
|
||||
pub color1: Color,
|
||||
pub color2: Color,
|
||||
#[serde(default)]
|
||||
pub angle: f64,
|
||||
#[serde(default)]
|
||||
pub centered: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Wipeout {
|
||||
pub boundary: Vec<Vec2>,
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Helices (HELIX): a spiral round a vertical axis from a base radius to a top radius, drawn as
|
||||
//! the cubic spline through points on it (DXF Reference: HELIX, a SPLINE with AcDbHelix data).
|
||||
|
||||
use cadcraft_geom::{FitOptions, KnotParam, Spline as GSpline, TAU, Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Most turns a helix has (as the reference program allows).
|
||||
pub const MAX_HELIX_TURNS: f64 = 500.0;
|
||||
/// Points on the helix per turn that its spline runs through.
|
||||
const POINTS_PER_TURN: f64 = 8.0;
|
||||
|
||||
/// What stays fixed when the helix is edited (DXF group 280).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HelixConstrain {
|
||||
TurnHeight,
|
||||
Turns,
|
||||
#[default]
|
||||
Height,
|
||||
}
|
||||
|
||||
impl HelixConstrain {
|
||||
pub fn to_dxf(self) -> i64 {
|
||||
match self {
|
||||
HelixConstrain::TurnHeight => 0,
|
||||
HelixConstrain::Turns => 1,
|
||||
HelixConstrain::Height => 2,
|
||||
}
|
||||
}
|
||||
pub fn from_dxf(v: i64) -> HelixConstrain {
|
||||
match v {
|
||||
0 => HelixConstrain::TurnHeight,
|
||||
1 => HelixConstrain::Turns,
|
||||
_ => HelixConstrain::Height,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Helix {
|
||||
/// Centre of the base (the axis base point).
|
||||
pub center: Vec3,
|
||||
pub base_radius: f64,
|
||||
pub top_radius: f64,
|
||||
/// Along the axis (+Z); negative goes down.
|
||||
pub height: f64,
|
||||
pub turns: f64,
|
||||
/// Angle of the start point from the centre, radians.
|
||||
#[serde(default)]
|
||||
pub start_angle: f64,
|
||||
/// Twist: counter-clockwise seen from above (right-handed).
|
||||
#[serde(default = "yes")]
|
||||
pub ccw: bool,
|
||||
#[serde(default)]
|
||||
pub constrain: HelixConstrain,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Helix {
|
||||
/// The values made safe: finite, radii >= 0, turns within (0, 500].
|
||||
pub fn sanitized(mut self) -> Helix {
|
||||
let fin = |v: f64, d: f64| if v.is_finite() { v } else { d };
|
||||
self.center = Vec3::new(fin(self.center.x, 0.0), fin(self.center.y, 0.0), fin(self.center.z, 0.0));
|
||||
self.base_radius = fin(self.base_radius, 1.0).abs().min(1e12);
|
||||
self.top_radius = fin(self.top_radius, self.base_radius).abs().min(1e12);
|
||||
self.height = fin(self.height, 0.0).clamp(-1e12, 1e12);
|
||||
self.turns = fin(self.turns, 3.0).clamp(1e-3, MAX_HELIX_TURNS);
|
||||
self.start_angle = fin(self.start_angle, 0.0);
|
||||
self
|
||||
}
|
||||
|
||||
/// Distance between turns.
|
||||
pub fn turn_height(&self) -> f64 {
|
||||
if self.turns > 0.0 { self.height / self.turns } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The point at `t` (0 = start, 1 = end) along the helix.
|
||||
pub fn point_at(&self, t: f64) -> Vec3 {
|
||||
let sign = if self.ccw { 1.0 } else { -1.0 };
|
||||
let a = self.start_angle + sign * TAU * self.turns * t;
|
||||
let r = self.base_radius + (self.top_radius - self.base_radius) * t;
|
||||
let p = Vec2::polar(self.center.xy(), r, a);
|
||||
Vec3::new(p.x, p.y, self.center.z + self.height * t)
|
||||
}
|
||||
|
||||
pub fn start_point(&self) -> Vec3 {
|
||||
self.point_at(0.0)
|
||||
}
|
||||
pub fn end_point(&self) -> Vec3 {
|
||||
self.point_at(1.0)
|
||||
}
|
||||
|
||||
/// The points the spline runs through, evenly spaced in angle.
|
||||
pub fn fit_points(&self) -> Vec<Vec3> {
|
||||
let turns = if self.turns.is_finite() { self.turns.clamp(1e-3, MAX_HELIX_TURNS) } else { 1.0 };
|
||||
let n = ((turns * POINTS_PER_TURN).ceil() as usize).max(4);
|
||||
(0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect()
|
||||
}
|
||||
|
||||
/// The helix as a cubic spline seen from above, and the height of each control point: the
|
||||
/// spline through [`Helix::fit_points`] with evenly spaced knots, so the height, linear in
|
||||
/// the parameter, is exact at each control point's Greville abscissa.
|
||||
pub fn spline3(&self) -> (GSpline, Vec<f64>) {
|
||||
let fit = self.fit_points();
|
||||
let xy: Vec<Vec2> = fit.iter().map(|p| p.xy()).collect();
|
||||
let sp = GSpline::fit_with(&xy, false, FitOptions { knots: KnotParam::Uniform, ..FitOptions::default() });
|
||||
let (lo, hi) = sp.domain();
|
||||
let span = if hi - lo > 1e-12 { hi - lo } else { 1.0 };
|
||||
let p = sp.degree.max(1);
|
||||
let z = (0..sp.control.len())
|
||||
.map(|j| {
|
||||
let g = (1..=p).map(|k| sp.knots.get(j + k).copied().unwrap_or(hi)).sum::<f64>() / p as f64;
|
||||
self.center.z + self.height * ((g - lo) / span).clamp(0.0, 1.0)
|
||||
})
|
||||
.collect();
|
||||
(sp, z)
|
||||
}
|
||||
|
||||
/// The helix seen from above.
|
||||
pub fn spline(&self) -> GSpline {
|
||||
self.spline3().0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
use super::common::Handle;
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Viewport {
|
||||
pub center: Vec3,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
pub view_center: Vec2,
|
||||
pub view_height: f64,
|
||||
#[serde(default)]
|
||||
pub id: u32,
|
||||
#[serde(default)]
|
||||
pub locked: bool,
|
||||
#[serde(default)]
|
||||
pub frozen_layers: Vec<String>,
|
||||
/// Per-viewport layer colour overrides (VP Color in the Layer Properties Manager).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub layer_colors: Vec<(String, Color)>,
|
||||
/// The paper-space entity whose outline clips the viewport (a closed polyline, circle,
|
||||
/// ellipse or spline; DXF group 340). `None`: the rectangle `center`/`width`/`height`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub clip: Option<Handle>,
|
||||
/// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space.
|
||||
#[serde(default = "yes")]
|
||||
pub on: bool,
|
||||
}
|
||||
|
||||
impl Default for Viewport {
|
||||
fn default() -> Self {
|
||||
Viewport {
|
||||
center: Vec3::ZERO,
|
||||
width: 1.0,
|
||||
height: 1.0,
|
||||
view_center: Vec2::ZERO,
|
||||
view_height: 1.0,
|
||||
id: 0,
|
||||
locked: false,
|
||||
frozen_layers: Vec::new(),
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Image {
|
||||
pub insert: Vec3,
|
||||
/// One pixel's width (U) and height (V) vectors in drawing units.
|
||||
pub u: Vec3,
|
||||
pub v: Vec3,
|
||||
/// Image size in pixels.
|
||||
pub size: Vec2,
|
||||
/// The image file (its IMAGEDEF object's path).
|
||||
pub path: String,
|
||||
/// The image definition's name (its key in the drawing's image dictionary).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub name: String,
|
||||
/// Clip boundary in pixel coordinates (origin at the top-left corner of the image, y down):
|
||||
/// two opposite corners of a rectangle, or a polygon's vertices. Empty: the whole image.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub clip: Vec<Vec2>,
|
||||
/// The clip boundary is applied.
|
||||
#[serde(default)]
|
||||
pub clipping: bool,
|
||||
/// Display flags: 1 show the image, 2 show it when not aligned with the screen, 4 use the
|
||||
/// clip boundary, 8 transparency on.
|
||||
#[serde(default = "image_display")]
|
||||
pub display: u16,
|
||||
/// Brightness, contrast and fade, 0..=100.
|
||||
#[serde(default = "image_fifty")]
|
||||
pub brightness: u8,
|
||||
#[serde(default = "image_fifty")]
|
||||
pub contrast: u8,
|
||||
#[serde(default)]
|
||||
pub fade: u8,
|
||||
/// The definition's default size of one pixel and its resolution unit (0 none, 2 cm, 5 inch).
|
||||
#[serde(default = "image_pixel")]
|
||||
pub pixel_size: Vec2,
|
||||
#[serde(default)]
|
||||
pub resolution_units: u8,
|
||||
}
|
||||
|
||||
fn image_display() -> u16 {
|
||||
7
|
||||
}
|
||||
|
||||
fn image_fifty() -> u8 {
|
||||
50
|
||||
}
|
||||
|
||||
fn image_pixel() -> Vec2 {
|
||||
Vec2::new(1.0, 1.0)
|
||||
}
|
||||
|
||||
impl Default for Image {
|
||||
fn default() -> Self {
|
||||
Image {
|
||||
insert: Vec3::ZERO,
|
||||
u: Vec3::new(1.0, 0.0, 0.0),
|
||||
v: Vec3::new(0.0, 1.0, 0.0),
|
||||
size: Vec2::new(1.0, 1.0),
|
||||
path: String::new(),
|
||||
name: String::new(),
|
||||
clip: Vec::new(),
|
||||
clipping: false,
|
||||
display: image_display(),
|
||||
brightness: image_fifty(),
|
||||
contrast: image_fifty(),
|
||||
fade: 0,
|
||||
pixel_size: image_pixel(),
|
||||
resolution_units: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableCell {
|
||||
pub text: String,
|
||||
#[serde(default)]
|
||||
pub merged: Option<(u32, u32)>,
|
||||
/// The cell's own cell style; empty: its row's.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub style: String,
|
||||
/// A formula (`=Sum(A1:B3)`); `text` holds its value.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub formula: Option<String>,
|
||||
/// The cell's own text height (DXF 140 in the cell record), before the table's scale;
|
||||
/// `None`: its cell style's.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub text_height: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Table {
|
||||
pub insert: Vec3,
|
||||
pub col_widths: Vec<f64>,
|
||||
pub row_heights: Vec<f64>,
|
||||
pub cells: Vec<Vec<TableCell>>,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default = "default_text_h")]
|
||||
pub text_height: f64,
|
||||
/// First row is a title (merged across, larger text).
|
||||
#[serde(default)]
|
||||
pub title: bool,
|
||||
/// The row after the title holds column headers.
|
||||
#[serde(default)]
|
||||
pub header: bool,
|
||||
/// The cell style of each row; missing or empty: by position (Title, Header, Data).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub row_styles: Vec<String>,
|
||||
/// Table breaking (TABLEBREAK): the table drawn in several parts.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub breaks: Option<crate::TableBreak>,
|
||||
/// The CSV file the cells come from (DATALINK).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub data_link: Option<crate::DataLink>,
|
||||
}
|
||||
|
||||
fn default_text_h() -> f64 {
|
||||
0.18
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Multilines (MLINE) and multiline styles (MLINESTYLE): parallel lines — the style's
|
||||
//! elements — run at fixed offsets along a path of vertices, with optional caps, joints and a
|
||||
//! fill between the outermost elements (DXF Reference: MLINE entity, MLINESTYLE object).
|
||||
//!
|
||||
//! An [`MLine`] carries a copy of its style ([`MLine::def`]), so its geometry needs nothing
|
||||
//! else from the drawing: snapping, selection and trimming work from the entity alone.
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_geom::{Arc as GArc, Line as GLine, PI, Segment, Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Most elements a multiline style has (as in the style dialog of the reference program).
|
||||
pub const MAX_MLINE_ELEMENTS: usize = 16;
|
||||
/// Most vertices of one multiline (hostile files).
|
||||
pub const MAX_MLINE_VERTICES: usize = 100_000;
|
||||
/// Most breaks per vertex (all elements together).
|
||||
pub const MAX_MLINE_CUTS: usize = 1_000;
|
||||
/// The style every drawing has.
|
||||
pub const STANDARD_MLINE_STYLE: &str = "STANDARD";
|
||||
|
||||
/// One line of a multiline style: its offset from the style's zero line (+ = left of the
|
||||
/// drawing direction), colour and linetype.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MLineElement {
|
||||
pub offset: f64,
|
||||
pub color: Color,
|
||||
pub linetype: String,
|
||||
}
|
||||
|
||||
impl Default for MLineElement {
|
||||
fn default() -> Self {
|
||||
MLineElement { offset: 0.0, color: Color::ByLayer, linetype: "ByLayer".into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The caps at one end of a multiline.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MLineCaps {
|
||||
/// A line across all elements.
|
||||
pub line: bool,
|
||||
/// A half circle joining the outermost elements.
|
||||
pub outer_arc: bool,
|
||||
/// Half circles joining pairs of inner elements.
|
||||
pub inner_arcs: bool,
|
||||
/// Angle of the end against the drawing direction, radians (π/2 = square).
|
||||
pub angle: f64,
|
||||
}
|
||||
|
||||
impl Default for MLineCaps {
|
||||
fn default() -> Self {
|
||||
MLineCaps { line: false, outer_arc: false, inner_arcs: false, angle: PI / 2.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// A multiline style (MLSTYLE).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MLineStyle {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Elements from the largest offset down.
|
||||
pub elements: Vec<MLineElement>,
|
||||
pub start_caps: MLineCaps,
|
||||
pub end_caps: MLineCaps,
|
||||
/// Lines across all elements at every vertex ("display joints").
|
||||
pub joints: bool,
|
||||
/// Fill colour between the outermost elements; `None` = no fill.
|
||||
pub fill: Option<Color>,
|
||||
}
|
||||
|
||||
impl Default for MLineStyle {
|
||||
/// The STANDARD style: two lines one unit apart, no caps, no fill.
|
||||
fn default() -> Self {
|
||||
MLineStyle {
|
||||
name: STANDARD_MLINE_STYLE.into(),
|
||||
description: String::new(),
|
||||
elements: vec![MLineElement { offset: 0.5, ..Default::default() }, MLineElement { offset: -0.5, ..Default::default() }],
|
||||
start_caps: MLineCaps::default(),
|
||||
end_caps: MLineCaps::default(),
|
||||
joints: false,
|
||||
fill: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MLineStyle {
|
||||
/// The style with hostile values made safe: 1..=16 finite elements sorted by offset (largest
|
||||
/// first), cap angles within 10°..170°.
|
||||
pub fn sanitized(mut self) -> MLineStyle {
|
||||
self.elements.retain(|e| e.offset.is_finite() && e.offset.abs() < 1e12);
|
||||
self.elements.truncate(MAX_MLINE_ELEMENTS);
|
||||
if self.elements.is_empty() {
|
||||
self.elements.push(MLineElement::default());
|
||||
}
|
||||
self.elements.sort_by(|a, b| b.offset.total_cmp(&a.offset));
|
||||
for c in [&mut self.start_caps, &mut self.end_caps] {
|
||||
c.angle = if c.angle.is_finite() { c.angle.clamp(10f64.to_radians(), 170f64.to_radians()) } else { PI / 2.0 };
|
||||
}
|
||||
self
|
||||
}
|
||||
pub fn max_offset(&self) -> f64 {
|
||||
self.elements.iter().map(|e| e.offset).fold(f64::NEG_INFINITY, f64::max).max(-1e12)
|
||||
}
|
||||
pub fn min_offset(&self) -> f64 {
|
||||
self.elements.iter().map(|e| e.offset).fold(f64::INFINITY, f64::min).min(1e12)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which line of the style runs through the picked points.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MLineJust {
|
||||
/// The element with the largest offset.
|
||||
#[default]
|
||||
Top,
|
||||
/// The style's zero line.
|
||||
Zero,
|
||||
/// The element with the smallest offset.
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl MLineJust {
|
||||
/// DXF group 70 of MLINE (and CMLJUST).
|
||||
pub fn to_dxf(self) -> i64 {
|
||||
match self {
|
||||
MLineJust::Top => 0,
|
||||
MLineJust::Zero => 1,
|
||||
MLineJust::Bottom => 2,
|
||||
}
|
||||
}
|
||||
pub fn from_dxf(v: i64) -> MLineJust {
|
||||
match v {
|
||||
1 => MLineJust::Zero,
|
||||
2 => MLineJust::Bottom,
|
||||
_ => MLineJust::Top,
|
||||
}
|
||||
}
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
MLineJust::Top => "Top",
|
||||
MLineJust::Zero => "Zero",
|
||||
MLineJust::Bottom => "Bottom",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A break in one element along the segment that starts at a vertex: distances from the
|
||||
/// element's start on that segment (MLEDIT Cut).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MLineCut {
|
||||
pub element: usize,
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MLineVertex {
|
||||
pub p: Vec3,
|
||||
/// Breaks in the segment that starts here.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub cuts: Vec<MLineCut>,
|
||||
}
|
||||
|
||||
impl MLineVertex {
|
||||
pub fn new(p: Vec3) -> Self {
|
||||
MLineVertex { p, cuts: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A multiline.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MLine {
|
||||
/// Style name (the MLINESTYLE it was drawn with).
|
||||
pub style: String,
|
||||
/// The style's elements, caps, joints and fill as this multiline uses them.
|
||||
#[serde(default)]
|
||||
pub def: MLineStyle,
|
||||
/// Element offsets are multiplied by this; negative flips the elements to the other side.
|
||||
#[serde(default = "one")]
|
||||
pub scale: f64,
|
||||
#[serde(default)]
|
||||
pub justification: MLineJust,
|
||||
#[serde(default)]
|
||||
pub closed: bool,
|
||||
#[serde(default)]
|
||||
pub no_start_caps: bool,
|
||||
#[serde(default)]
|
||||
pub no_end_caps: bool,
|
||||
pub vertices: Vec<MLineVertex>,
|
||||
}
|
||||
|
||||
fn one() -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
/// A multiline's drawn geometry.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MLineGeometry {
|
||||
/// Element pieces: (element index into `def.elements`, from, to).
|
||||
pub lines: Vec<(usize, Vec2, Vec2)>,
|
||||
/// Caps and joints, drawn with the multiline's own properties.
|
||||
pub caps: Vec<Segment>,
|
||||
/// The fill between the outermost elements (even-odd loops); empty without fill.
|
||||
pub fill: Vec<Vec<Vec2>>,
|
||||
}
|
||||
|
||||
impl MLine {
|
||||
/// A multiline through `pts` in style `def`.
|
||||
pub fn new(def: &MLineStyle, pts: &[Vec2], closed: bool, just: MLineJust, scale: f64) -> MLine {
|
||||
MLine {
|
||||
style: def.name.clone(),
|
||||
def: def.clone(),
|
||||
scale,
|
||||
justification: just,
|
||||
closed,
|
||||
no_start_caps: false,
|
||||
no_end_caps: false,
|
||||
vertices: pts.iter().map(|p| MLineVertex::new(p.to3(0.0))).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The offset the vertex path sits at, in style units.
|
||||
pub fn ref_offset(&self) -> f64 {
|
||||
match self.justification {
|
||||
MLineJust::Top => self.def.max_offset(),
|
||||
MLineJust::Zero => 0.0,
|
||||
MLineJust::Bottom => self.def.min_offset(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Each element's distance from the vertex path (+ = left of the drawing direction).
|
||||
pub fn offsets(&self) -> Vec<f64> {
|
||||
let r = self.ref_offset();
|
||||
let s = if self.scale.is_finite() { self.scale } else { 1.0 };
|
||||
self.def.elements.iter().map(|e| (e.offset - r) * s).collect()
|
||||
}
|
||||
|
||||
pub fn points(&self) -> Vec<Vec2> {
|
||||
self.vertices.iter().map(|v| v.p.xy()).collect()
|
||||
}
|
||||
|
||||
/// Number of segments (the closing one included).
|
||||
pub fn segment_count(&self) -> usize {
|
||||
let n = self.vertices.len();
|
||||
if n < 2 {
|
||||
0
|
||||
} else if self.closed {
|
||||
n
|
||||
} else {
|
||||
n - 1
|
||||
}
|
||||
}
|
||||
|
||||
/// Unit direction of each segment (zero for a degenerate one).
|
||||
pub fn directions(&self) -> Vec<Vec2> {
|
||||
let pts = self.points();
|
||||
let n = pts.len();
|
||||
(0..self.segment_count())
|
||||
.map(|i| (pts.get((i + 1) % n.max(1)).copied().unwrap_or_default() - pts.get(i).copied().unwrap_or_default()).normalized())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The miter vector at each vertex: the element at offset `d` passes through `v + m * d`.
|
||||
pub fn miters(&self) -> Vec<Vec2> {
|
||||
let dirs = self.directions();
|
||||
let n = self.vertices.len();
|
||||
let nseg = dirs.len();
|
||||
// A degenerate segment takes its neighbour's direction.
|
||||
let dir = |i: usize| -> Vec2 {
|
||||
(0..nseg).map(|k| dirs.get((i + k) % nseg.max(1)).copied().unwrap_or_default()).find(|d| *d != Vec2::ZERO).unwrap_or(Vec2::X)
|
||||
};
|
||||
let dir_back = |i: usize| -> Vec2 {
|
||||
(0..nseg)
|
||||
.map(|k| dirs.get((i + nseg - k % nseg) % nseg.max(1)).copied().unwrap_or_default())
|
||||
.find(|d| *d != Vec2::ZERO)
|
||||
.unwrap_or(Vec2::X)
|
||||
};
|
||||
let end = |d: Vec2, angle: f64| {
|
||||
let u = d.rotate(angle);
|
||||
let s = angle.sin();
|
||||
if s.abs() < 1e-6 { d.perp() } else { u / s }
|
||||
};
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
if nseg == 0 {
|
||||
return Vec2::Y;
|
||||
}
|
||||
let open_end = !self.closed && (i == 0 || i + 1 == n);
|
||||
if open_end {
|
||||
return if i == 0 { end(dir(0), self.def.start_caps.angle) } else { end(dir_back(n - 2), PI - self.def.end_caps.angle) };
|
||||
}
|
||||
let d_in = dir_back((i + nseg - 1) % nseg);
|
||||
let d_out = dir(i % nseg);
|
||||
let (n1, n2) = (d_in.perp(), d_out.perp());
|
||||
let b = (n1 + n2).normalized();
|
||||
if b == Vec2::ZERO {
|
||||
return n1;
|
||||
}
|
||||
// Keep sharp corners finite.
|
||||
b / b.dot(n1).max(0.05)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The drawn geometry: element pieces (breaks taken out), caps, joints and fill.
|
||||
pub fn geometry(&self) -> MLineGeometry {
|
||||
let mut g = MLineGeometry::default();
|
||||
let pts = self.points();
|
||||
let n = pts.len();
|
||||
let nseg = self.segment_count();
|
||||
if nseg == 0 || pts.iter().any(|p| !p.is_finite()) {
|
||||
return g;
|
||||
}
|
||||
let miters = self.miters();
|
||||
let offs = self.offsets();
|
||||
let at = |k: usize, d: f64| pts.get(k % n).copied().unwrap_or_default() + miters.get(k % n).copied().unwrap_or_default() * d;
|
||||
for k in 0..nseg {
|
||||
let cuts = self.vertices.get(k).map(|v| v.cuts.as_slice()).unwrap_or(&[]);
|
||||
for (e, d) in offs.iter().enumerate() {
|
||||
let (a, b) = (at(k, *d), at(k + 1, *d));
|
||||
let len = a.dist(b);
|
||||
if len <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
let dir = (b - a) / len;
|
||||
for (s, t) in pieces(len, cuts.iter().filter(|c| c.element == e).map(|c| (c.start, c.end))) {
|
||||
g.lines.push((e, a + dir * s, a + dir * t));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Elements by offset, largest (leftmost) first.
|
||||
let mut order: Vec<usize> = (0..offs.len()).collect();
|
||||
order.sort_by(|a, b| offs.get(*b).copied().unwrap_or(0.0).total_cmp(&offs.get(*a).copied().unwrap_or(0.0)));
|
||||
let (Some(&top), Some(&bottom)) = (order.first(), order.last()) else { return g };
|
||||
let off = |e: usize| offs.get(e).copied().unwrap_or(0.0);
|
||||
let across = |k: usize| Segment::Line(GLine::new(at(k, off(top)), at(k, off(bottom))));
|
||||
if !self.closed {
|
||||
for (k, caps, skip, start) in [(0, self.def.start_caps, self.no_start_caps, true), (n - 1, self.def.end_caps, self.no_end_caps, false)] {
|
||||
if skip {
|
||||
continue;
|
||||
}
|
||||
if caps.line && order.len() > 1 {
|
||||
g.caps.push(across(k));
|
||||
}
|
||||
let pairs = order.len() / 2;
|
||||
for i in 0..pairs {
|
||||
if (i == 0 && !caps.outer_arc) || (i > 0 && !caps.inner_arcs) {
|
||||
continue;
|
||||
}
|
||||
let (Some(&ea), Some(&eb)) = (order.get(i), order.get(order.len() - 1 - i)) else { continue };
|
||||
let (a, b) = (at(k, off(ea)), at(k, off(eb)));
|
||||
if let Some(arc) = half_circle(a, b, start) {
|
||||
g.caps.push(arc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.def.joints && order.len() > 1 {
|
||||
let inner = if self.closed { 0..n } else { 1..n.saturating_sub(1) };
|
||||
for k in inner {
|
||||
g.caps.push(across(k));
|
||||
}
|
||||
}
|
||||
if self.def.fill.is_some() {
|
||||
let side = |e: usize| (0..n).map(|k| at(k, off(e))).collect::<Vec<Vec2>>();
|
||||
if self.closed {
|
||||
g.fill = vec![side(top), side(bottom)];
|
||||
} else {
|
||||
let mut poly = side(top);
|
||||
poly.extend(side(bottom).into_iter().rev());
|
||||
g.fill = vec![poly];
|
||||
}
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// Segments of every element piece, cap and joint.
|
||||
pub fn segments(&self) -> Vec<Segment> {
|
||||
let g = self.geometry();
|
||||
g.lines.iter().map(|(_, a, b)| Segment::Line(GLine::new(*a, *b))).chain(g.caps).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of `[0, len]` left after taking out the `gaps` (each `(start, end)`, any order).
|
||||
fn pieces(len: f64, gaps: impl Iterator<Item = (f64, f64)>) -> Vec<(f64, f64)> {
|
||||
let mut gaps: Vec<(f64, f64)> =
|
||||
gaps.filter(|(a, b)| a.is_finite() && b.is_finite()).map(|(a, b)| (a.min(b).max(0.0), a.max(b).min(len))).filter(|(a, b)| b > a).collect();
|
||||
gaps.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut out = Vec::new();
|
||||
let mut from = 0.0;
|
||||
for (a, b) in gaps {
|
||||
if a > from + 1e-12 {
|
||||
out.push((from, a));
|
||||
}
|
||||
from = f64::max(from, b);
|
||||
}
|
||||
if len > from + 1e-12 {
|
||||
out.push((from, len));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A half circle from `a` to `b` bulging backwards (`start`) or forwards along the multiline.
|
||||
fn half_circle(a: Vec2, b: Vec2, start: bool) -> Option<Segment> {
|
||||
let r = a.dist(b) / 2.0;
|
||||
if r <= 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let c = a.mid(b);
|
||||
let (sa, sb) = (c.angle_to(a), c.angle_to(b));
|
||||
// From the left element to the right one: counter-clockwise passes behind the start.
|
||||
Some(if start { Segment::Arc { arc: GArc::new(c, r, sa, sb), ccw: true } } else { Segment::Arc { arc: GArc::new(c, r, sb, sa), ccw: false } })
|
||||
}
|
||||
|
||||
impl crate::Drawing {
|
||||
/// The multiline style named `name` (any case).
|
||||
pub fn mline_style(&self, name: &str) -> Option<&MLineStyle> {
|
||||
self.mline_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name.trim()))
|
||||
}
|
||||
/// The current multiline style (CMLSTYLE), STANDARD when it is missing.
|
||||
pub fn current_mline_style(&self) -> MLineStyle {
|
||||
let name = self.header.str("CMLSTYLE", STANDARD_MLINE_STYLE);
|
||||
self.mline_style(&name).or_else(|| self.mline_style(STANDARD_MLINE_STYLE)).cloned().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Regions (REGION): a closed planar area bounded by loops of lines and arcs. Outer loops add
|
||||
//! area, island loops (holes) take it away; loops don't cross.
|
||||
|
||||
use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Segment, Vec2, point_in_polygon};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::HatchLoop;
|
||||
|
||||
/// Most loops one region has (hostile files and edits).
|
||||
pub const MAX_REGION_LOOPS: usize = 10_000;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Region {
|
||||
/// Closed loops with bulges; `outer` false for islands.
|
||||
pub loops: Vec<HatchLoop>,
|
||||
}
|
||||
|
||||
/// Area properties of a region (MASSPROP), in drawing units.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct RegionProps {
|
||||
pub area: f64,
|
||||
pub perimeter: f64,
|
||||
pub bounds: Bounds2,
|
||||
pub centroid: Vec2,
|
||||
/// ∫y² dA and ∫x² dA about the origin.
|
||||
pub ixx: f64,
|
||||
pub iyy: f64,
|
||||
/// ∫xy dA about the origin.
|
||||
pub ixy: f64,
|
||||
/// The same three about the centroid.
|
||||
pub centroid_moments: [f64; 3],
|
||||
}
|
||||
|
||||
impl Region {
|
||||
/// A region bounded by one closed loop.
|
||||
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
|
||||
}
|
||||
|
||||
pub fn polylines(&self) -> Vec<Polyline> {
|
||||
self.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect()
|
||||
}
|
||||
|
||||
/// The boundary: every loop's lines and arcs.
|
||||
pub fn segments(&self) -> Vec<Segment> {
|
||||
self.polylines().iter().flat_map(Polyline::segments).collect()
|
||||
}
|
||||
|
||||
/// Each loop as points, arcs within `tol`.
|
||||
pub fn tessellate(&self, tol: f64) -> Vec<Vec<Vec2>> {
|
||||
self.polylines().iter().map(|p| p.tessellate(tol)).collect()
|
||||
}
|
||||
|
||||
pub fn bounds(&self) -> Bounds2 {
|
||||
self.polylines().iter().fold(Bounds2::EMPTY, |b, p| b.union(&p.bounds()))
|
||||
}
|
||||
|
||||
/// Outer loops' area less the islands'.
|
||||
pub fn area(&self) -> f64 {
|
||||
self.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.area().abs() * if l.outer { 1.0 } else { -1.0 }).sum()
|
||||
}
|
||||
|
||||
pub fn perimeter(&self) -> f64 {
|
||||
self.polylines().iter().map(Polyline::len).sum()
|
||||
}
|
||||
|
||||
/// A chord tolerance fine enough for measuring: 1e-5 of the region's size.
|
||||
fn fine_tol(&self) -> f64 {
|
||||
let b = self.bounds();
|
||||
if b.is_empty() { 1e-6 } else { ((b.width() + b.height()) * 1e-5).max(1e-12) }
|
||||
}
|
||||
|
||||
/// Whether `p` lies inside the region (odd parity over its loops).
|
||||
pub fn contains(&self, p: Vec2) -> bool {
|
||||
self.tessellate(self.fine_tol()).iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1
|
||||
}
|
||||
|
||||
/// Set each loop's `outer` flag from how deeply other loops enclose it: an even depth is
|
||||
/// an outer loop, odd an island.
|
||||
pub fn renest(&mut self) {
|
||||
let polys = self.tessellate(self.fine_tol());
|
||||
let depth: Vec<usize> = polys
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| {
|
||||
let Some(p) = probe(l) else { return 0 };
|
||||
polys.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count()
|
||||
})
|
||||
.collect();
|
||||
for (l, d) in self.loops.iter_mut().zip(depth) {
|
||||
l.outer = d % 2 == 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Area, perimeter, bounding box, centroid and second moments (outer loops counted
|
||||
/// counter-clockwise, islands clockwise).
|
||||
pub fn props(&self) -> RegionProps {
|
||||
let tol = self.fine_tol();
|
||||
let (mut a, mut cx, mut cy, mut ixx, mut iyy, mut ixy) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
|
||||
for (l, pts) in self.loops.iter().zip(self.tessellate(tol)) {
|
||||
let signed = cadcraft_geom::shoelace(&pts);
|
||||
// Outer loops add, islands subtract, whatever way they run.
|
||||
let flip = if (signed >= 0.0) == l.outer { 1.0 } else { -1.0 };
|
||||
let n = pts.len();
|
||||
for i in 0..n {
|
||||
let (Some(p), Some(q)) = (pts.get(i), pts.get((i + 1) % n)) else { continue };
|
||||
let c = (p.x * q.y - q.x * p.y) * flip;
|
||||
a += c / 2.0;
|
||||
cx += (p.x + q.x) * c / 6.0;
|
||||
cy += (p.y + q.y) * c / 6.0;
|
||||
ixx += (p.y * p.y + p.y * q.y + q.y * q.y) * c / 12.0;
|
||||
iyy += (p.x * p.x + p.x * q.x + q.x * q.x) * c / 12.0;
|
||||
ixy += (p.x * q.y + 2.0 * p.x * p.y + 2.0 * q.x * q.y + q.x * p.y) * c / 24.0;
|
||||
}
|
||||
}
|
||||
let c = if a.abs() > 1e-300 { Vec2::new(cx / a, cy / a) } else { Vec2::ZERO };
|
||||
// Shifted with the area of the same outline the moments were taken from.
|
||||
let centroid_moments = [ixx - a * c.y * c.y, iyy - a * c.x * c.x, ixy - a * c.x * c.y];
|
||||
RegionProps { area: self.area(), perimeter: self.perimeter(), bounds: self.bounds(), centroid: c, ixx, iyy, ixy, centroid_moments }
|
||||
}
|
||||
}
|
||||
|
||||
/// A point of a loop to test its nesting with: the middle of its first non-degenerate edge.
|
||||
fn probe(l: &[Vec2]) -> Option<Vec2> {
|
||||
let n = l.len();
|
||||
(0..n).find_map(|i| {
|
||||
let (a, b) = (*l.get(i)?, *l.get((i + 1) % n)?);
|
||||
(a.dist(b) > 1e-12).then(|| (a + b) * 0.5).filter(|m| m.is_finite())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HAlign {
|
||||
#[default]
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
Aligned,
|
||||
Middle,
|
||||
Fit,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VAlign {
|
||||
#[default]
|
||||
Baseline,
|
||||
Bottom,
|
||||
Middle,
|
||||
Top,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Text {
|
||||
pub insert: Vec3,
|
||||
#[serde(default)]
|
||||
pub align_pt: Option<Vec3>,
|
||||
pub height: f64,
|
||||
pub value: String,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
#[serde(default = "one")]
|
||||
pub width_factor: f64,
|
||||
#[serde(default)]
|
||||
pub oblique: f64,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
#[serde(default)]
|
||||
pub halign: HAlign,
|
||||
#[serde(default)]
|
||||
pub valign: VAlign,
|
||||
}
|
||||
|
||||
impl Text {
|
||||
/// The point the text is placed by, as the Insertion snap and the grip show it: the alignment
|
||||
/// point (DXF group 11) of justified text, the start point (group 10) of left-baseline,
|
||||
/// aligned and fit text.
|
||||
pub fn justify_point(&self) -> Vec2 {
|
||||
match (self.halign, self.valign) {
|
||||
(HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _) => self.insert.xy(),
|
||||
_ => self.align_pt.unwrap_or(self.insert).xy(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MText {
|
||||
pub insert: Vec3,
|
||||
pub height: f64,
|
||||
/// Reference rectangle width (0 = no wrapping).
|
||||
#[serde(default)]
|
||||
pub width: f64,
|
||||
/// 1..=9: TL TC TR ML MC MR BL BC BR.
|
||||
#[serde(default = "attach_tl")]
|
||||
pub attach: u8,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
/// Raw MTEXT contents with inline codes (\P, {\fArial|b1;...}, \S1/2; …).
|
||||
pub contents: String,
|
||||
#[serde(default = "one")]
|
||||
pub line_spacing: f64,
|
||||
/// Line spacing style (DXF 73): Exactly (`true`) keeps `line_spacing` whatever the character
|
||||
/// heights; At least (`false`, the default) lets taller characters push lines apart.
|
||||
#[serde(default)]
|
||||
pub line_spacing_exact: bool,
|
||||
/// Columns the text flows through, each `width` wide (DXF 75/76/78/79/48/49/50); `None`:
|
||||
/// one column.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub columns: Option<MTextColumns>,
|
||||
}
|
||||
|
||||
fn attach_tl() -> u8 {
|
||||
1
|
||||
}
|
||||
|
||||
/// Static columns: a fixed number of columns of one height. Dynamic columns: as many columns
|
||||
/// as the text needs, of one height (auto height) or each its own (manual heights).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MTextColumnType {
|
||||
#[default]
|
||||
Static,
|
||||
Dynamic,
|
||||
}
|
||||
|
||||
/// MTEXT columns (MTEXT Columns option, DXF Reference MTEXT groups 75–79, 48–50).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MTextColumns {
|
||||
#[serde(rename = "type")]
|
||||
pub kind: MTextColumnType,
|
||||
/// Number of columns (static columns: the columns there are).
|
||||
pub count: u16,
|
||||
/// Space between two columns.
|
||||
pub gutter: f64,
|
||||
/// Height of every column (static, and dynamic with auto height).
|
||||
pub height: f64,
|
||||
/// Dynamic columns: one height for all columns (`height`) instead of `heights`.
|
||||
pub auto_height: bool,
|
||||
/// Dynamic columns with manual heights: the height of each column.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub heights: Vec<f64>,
|
||||
/// Columns run right to left.
|
||||
pub flow_reversed: bool,
|
||||
}
|
||||
|
||||
impl MTextColumns {
|
||||
/// The width of `count` columns of `column_width` and their gutters.
|
||||
pub fn total_width(&self, column_width: f64) -> f64 {
|
||||
let n = f64::from(self.count.max(1));
|
||||
column_width * n + self.gutter.max(0.0) * (n - 1.0)
|
||||
}
|
||||
|
||||
/// The tallest column.
|
||||
pub fn max_height(&self) -> f64 {
|
||||
self.heights.iter().copied().fold(self.height, f64::max).max(0.0)
|
||||
}
|
||||
|
||||
/// Scale every length (SCALE, block insertion).
|
||||
pub fn scale(&mut self, s: f64) {
|
||||
self.gutter *= s;
|
||||
self.height *= s;
|
||||
self.heights.iter_mut().for_each(|h| *h *= s);
|
||||
}
|
||||
}
|
||||
+132
-45
@@ -48,40 +48,59 @@ fn blank(s: &str) -> bool {
|
||||
s.replace("\\~", " ").chars().all(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// Approximate box of an MTEXT, from its attachment point, width and line count.
|
||||
fn mtext_box(t: &crate::MText) -> Bounds2 {
|
||||
let lines = t.contents.split("\\P").count().max(1);
|
||||
let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1);
|
||||
let mut w = if t.width > 0.0 { t.width } else { t.height * 0.8 * longest as f64 };
|
||||
let mut h = t.height * 1.66 * lines as f64;
|
||||
if let Some(c) = t.columns.as_ref().filter(|_| t.width > 0.0) {
|
||||
// Columns side by side, the text flowing down each in turn.
|
||||
w = c.total_width(t.width);
|
||||
h = if c.max_height() > 0.0 { c.max_height() } else { h };
|
||||
}
|
||||
let (dx, dy) = match t.attach {
|
||||
2 | 5 | 8 => (-w / 2.0, 0.0),
|
||||
3 | 6 | 9 => (-w, 0.0),
|
||||
_ => (0.0, 0.0),
|
||||
};
|
||||
let top = match t.attach {
|
||||
4..=6 => h / 2.0,
|
||||
7..=9 => h,
|
||||
_ => 0.0,
|
||||
};
|
||||
let o = t.insert.xy();
|
||||
let pts = [Vec2::new(dx, top + dy), Vec2::new(dx + w, top + dy), Vec2::new(dx + w, top - h + dy), Vec2::new(dx, top - h + dy)]
|
||||
.map(|p| o + p.rotate(t.rotation));
|
||||
Bounds2::from_points(pts)
|
||||
}
|
||||
|
||||
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
|
||||
// A top-level annotative object measures as it draws at the current annotation scale.
|
||||
if depth == 0 {
|
||||
match d.anno_draw(e) {
|
||||
crate::AnnoDraw::Plain => {}
|
||||
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
|
||||
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, &mut HashMap::new()),
|
||||
}
|
||||
}
|
||||
bounds_in(d, e, depth, &mut HashMap::new())
|
||||
}
|
||||
|
||||
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
|
||||
/// by block name: every further reference to a block reuses them instead of expanding the block
|
||||
/// again, so nested or self-referencing blocks cost one pass over each definition instead of one
|
||||
/// per reference (which grows exponentially with the nesting depth).
|
||||
fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String, Bounds2>) -> Bounds2 {
|
||||
/// by block name and depth: every further reference to a block at that depth reuses them instead of
|
||||
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
|
||||
/// definition per depth instead of one per reference (which grows exponentially with the nesting
|
||||
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
|
||||
/// bounds must not stand in for a shallower reference to the same block (#706).
|
||||
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 {
|
||||
match &e.kind {
|
||||
EntityKind::Table(t) if t.is_broken() => t.bounds(),
|
||||
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
|
||||
EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY,
|
||||
EntityKind::Text(t) => text_box(t, t.value.chars().count()),
|
||||
EntityKind::AttDef(a) => text_box(&a.text, a.tag.chars().count()),
|
||||
EntityKind::MText(t) => {
|
||||
let lines = t.contents.split("\\P").count().max(1);
|
||||
let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1);
|
||||
let w = if t.width > 0.0 { t.width } else { t.height * 0.8 * longest as f64 };
|
||||
let h = t.height * 1.66 * lines as f64;
|
||||
let (dx, dy) = match t.attach {
|
||||
2 | 5 | 8 => (-w / 2.0, 0.0),
|
||||
3 | 6 | 9 => (-w, 0.0),
|
||||
_ => (0.0, 0.0),
|
||||
};
|
||||
let top = match t.attach {
|
||||
4..=6 => h / 2.0,
|
||||
7..=9 => h,
|
||||
_ => 0.0,
|
||||
};
|
||||
let o = t.insert.xy();
|
||||
let pts = [Vec2::new(dx, top + dy), Vec2::new(dx + w, top + dy), Vec2::new(dx + w, top - h + dy), Vec2::new(dx, top - h + dy)]
|
||||
.map(|p| o + p.rotate(t.rotation));
|
||||
Bounds2::from_points(pts)
|
||||
}
|
||||
EntityKind::MText(t) => mtext_box(t),
|
||||
EntityKind::Insert(ins) => {
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
return Bounds2::EMPTY;
|
||||
@@ -89,28 +108,34 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
|
||||
// A reference to a missing block (an unloaded xref, a purged definition) or to an empty
|
||||
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
|
||||
// insertion point. Attributes below still count.
|
||||
let Some(blk) = d.block(&ins.block) else { return Bounds2::EMPTY };
|
||||
let m = ins.transform(blk.base.xy());
|
||||
let inner = match blocks.get(&blk.name) {
|
||||
Some(b) => *b,
|
||||
None => {
|
||||
let mut inner = Bounds2::EMPTY;
|
||||
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
|
||||
inner = inner.union(&bounds_in(d, be, depth + 1, blocks));
|
||||
let mut b = Bounds2::EMPTY;
|
||||
if let Some(blk) = d.block(&ins.block) {
|
||||
let m = ins.transform(blk.base.xy());
|
||||
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
|
||||
Some(b) => *b,
|
||||
None => {
|
||||
let mut inner = Bounds2::EMPTY;
|
||||
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
|
||||
inner = inner.union(&bounds_in(d, be, depth + 1, blocks));
|
||||
}
|
||||
blocks.insert((blk.name.as_str(), depth), inner);
|
||||
inner
|
||||
}
|
||||
blocks.insert(blk.name.clone(), inner);
|
||||
inner
|
||||
};
|
||||
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
|
||||
if ins.cols > 1 || ins.rows > 1 {
|
||||
let off =
|
||||
Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1)))
|
||||
.rotate(ins.rotation);
|
||||
b = b.union(&Bounds2::from_points(b.corners().map(|c| c + off)));
|
||||
}
|
||||
};
|
||||
let mut b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
|
||||
if ins.cols > 1 || ins.rows > 1 {
|
||||
let off = Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1)))
|
||||
.rotate(ins.rotation);
|
||||
b = b.union(&Bounds2::from_points(b.corners().map(|c| c + off)));
|
||||
}
|
||||
for a in &ins.attribs {
|
||||
if !a.invisible {
|
||||
b = b.union(&text_box(&a.text, a.text.value.chars().count()));
|
||||
b = b.union(&match a.multiline_text() {
|
||||
Some(m) => mtext_box(&m),
|
||||
None => text_box(&a.text, a.text.value.chars().count()),
|
||||
});
|
||||
}
|
||||
}
|
||||
b
|
||||
@@ -140,9 +165,21 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
|
||||
if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n))
|
||||
&& depth < MAX_BLOCK_DEPTH
|
||||
{
|
||||
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
|
||||
b = b.union(&bounds_in(d, be, depth + 1, blocks));
|
||||
}
|
||||
// Reuse the shared block-bounds cache (as the Insert branch does) so a dimension
|
||||
// block with branching or self-referencing children costs one pass per definition
|
||||
// per depth, not one per reference (which grows exponentially) (CWE-400).
|
||||
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
|
||||
Some(cached) => *cached,
|
||||
None => {
|
||||
let mut inner = Bounds2::EMPTY;
|
||||
for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) {
|
||||
inner = inner.union(&bounds_in(d, be, depth + 1, blocks));
|
||||
}
|
||||
blocks.insert((blk.name.as_str(), depth), inner);
|
||||
inner
|
||||
}
|
||||
};
|
||||
b = b.union(&inner);
|
||||
}
|
||||
b
|
||||
}
|
||||
@@ -150,6 +187,13 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
|
||||
let mut b = Bounds2::from_points(m.leaders.iter().flatten().map(|v| v.xy()).chain(std::iter::once(m.landing.xy())));
|
||||
if let Some(t) = &m.text {
|
||||
b.add(t.insert.xy());
|
||||
if !blank(&t.contents) {
|
||||
b = b.union(&mtext_box(t));
|
||||
}
|
||||
}
|
||||
if let Some(ins) = &m.block {
|
||||
let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) };
|
||||
b = b.union(&bounds_in(d, &be, depth, blocks));
|
||||
}
|
||||
b
|
||||
}
|
||||
@@ -158,6 +202,8 @@ fn bounds_in(d: &Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<String,
|
||||
let h: f64 = t.row_heights.iter().sum();
|
||||
Bounds2::new(t.insert.xy(), t.insert.xy() + Vec2::new(w, -h))
|
||||
}
|
||||
// Text widths estimated like `text_box`; the renderer measures the font.
|
||||
EntityKind::Tolerance(t) => t.layout(d, &|s, h| h * 0.9 * s.chars().count() as f64).bounds,
|
||||
EntityKind::Image(i) => {
|
||||
let o = i.insert.xy();
|
||||
let u = i.u.xy() * i.size.x;
|
||||
@@ -283,8 +329,49 @@ mod tests {
|
||||
#[test]
|
||||
fn right_justified_attdef_is_left_of_alignment_point() {
|
||||
let text = text(HAlign::Right, VAlign::Baseline);
|
||||
let a = crate::Attrib { tag: "HELLO".into(), text, invisible: false, constant: false, prompt: String::new(), props: Default::default() };
|
||||
let a = crate::Attrib {
|
||||
tag: "HELLO".into(),
|
||||
text,
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: Default::default(),
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
};
|
||||
let b = bounds(EntityKind::AttDef(a));
|
||||
assert!(b.min.x <= -4.4 && b.max.x < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multileader_text_is_inside_its_bounds() {
|
||||
let mtext = crate::MText {
|
||||
insert: Vec3::new(25.45, 0.0, 0.0),
|
||||
height: 5.0,
|
||||
width: 0.0,
|
||||
attach: 4,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: "N".into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
let ml = crate::MLeader {
|
||||
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]],
|
||||
landing: Vec3::new(25.0, 0.0, 0.0),
|
||||
dogleg: 0.45,
|
||||
text: Some(mtext.clone()),
|
||||
style: "Standard".into(),
|
||||
arrow_size: 1.0,
|
||||
spline: false,
|
||||
block: None,
|
||||
};
|
||||
let b = bounds(EntityKind::MLeader(ml.clone()));
|
||||
// The glyph spans x 25.45..28.78, y -2.5..2.5.
|
||||
assert!(b.min.x <= 0.0 && b.max.x >= 28.79 && b.min.y <= -2.5 && b.max.y >= 2.5);
|
||||
let mut empty = ml;
|
||||
empty.text = Some(crate::MText { contents: " ".into(), ..mtext });
|
||||
assert!(bounds(EntityKind::MLeader(empty)).max.x < 26.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Data from a drawing file that CADCraft does not model, kept so that saving the drawing writes
|
||||
//! it back: other programs' objects, extension dictionaries, xdata and properties (#528).
|
||||
//!
|
||||
//! It is kept as the file's own DXF groups, with the file's handles. The file reader fills it and
|
||||
//! the writer puts it back, pointing references at whatever now has the referenced role (the
|
||||
//! named object dictionary, a table record, a block, an entity); references to objects that are
|
||||
//! gone are dropped. Commands don't edit it.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::{Handle, RawTag};
|
||||
|
||||
/// What a file handle stood for when the object it named is one CADCraft writes itself (under a
|
||||
/// new handle on save): a kind and an upper-case name, e.g. `("LAYER", "WALLS")`,
|
||||
/// `("TABLE", "LAYER")`, `("BLOCK", "DOOR")`, `("NOD", "")` for the named object dictionary and
|
||||
/// `("NOD", "ACAD_GROUP")` for one of its entries.
|
||||
pub type ForeignKey = (String, String);
|
||||
|
||||
/// A non-graphical object of a type or role CADCraft does not model.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ForeignObject {
|
||||
/// Its handle in the file it came from (kept on save).
|
||||
pub handle: Handle,
|
||||
/// Its DXF type (group 0), e.g. `XRECORD`.
|
||||
pub kind: String,
|
||||
/// Its groups after the type, as read.
|
||||
pub tags: Vec<RawTag>,
|
||||
}
|
||||
|
||||
/// What an entity, table record or block carries beyond what CADCraft models.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ForeignExtra {
|
||||
/// Its extension dictionary (one of [`Foreign::objects`]).
|
||||
pub xdict: Option<Handle>,
|
||||
/// Objects of [`Foreign::objects`] that react to it (persistent reactors).
|
||||
pub reactors: Vec<Handle>,
|
||||
/// Other applications' extended data of a table record or block: groups from `1001` on. An
|
||||
/// entity's is part of the entity ([`crate::Common::xdata`]), so it follows the entity's copies.
|
||||
pub xdata: Vec<RawTag>,
|
||||
/// The colour book colour (group 430) and the true colour (group 420) it was read with: it is
|
||||
/// written back while the colour is unchanged.
|
||||
pub color_book: Option<(String, String)>,
|
||||
/// Other unmodelled property groups (material 347, shadow mode 284).
|
||||
pub props: Vec<RawTag>,
|
||||
}
|
||||
|
||||
impl ForeignExtra {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything of a file CADCraft keeps without modelling it.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Foreign {
|
||||
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
|
||||
pub classes: Vec<Vec<RawTag>>,
|
||||
/// Kept objects, in file order.
|
||||
pub objects: Vec<ForeignObject>,
|
||||
/// Entries of the named object dictionary that CADCraft doesn't write itself: (key, object).
|
||||
pub dictionary: Vec<(String, Handle)>,
|
||||
/// Extras of entities, by handle.
|
||||
pub entities: BTreeMap<Handle, ForeignExtra>,
|
||||
/// Extras of table records (`("LAYER", "WALLS")`), tables (`("TABLE", "LAYER")`) and blocks
|
||||
/// (`("BLOCK", "DOOR")`), by [`ForeignKey`].
|
||||
pub records: BTreeMap<ForeignKey, ForeignExtra>,
|
||||
/// The roles of the file handles the kept data refers to, for objects CADCraft rewrites.
|
||||
pub targets: BTreeMap<Handle, ForeignKey>,
|
||||
/// The upper-case names of the file's classes in its CLASSES order, kept when the file has
|
||||
/// proxy objects or entities: a proxy's class number (group 91) is 500 plus its class's place
|
||||
/// here, and saving renumbers it to the written CLASSES (#1812).
|
||||
pub class_order: Vec<String>,
|
||||
/// The file's data store section (ACDSDATA, AutoCAD 2013 and later), as read: its groups
|
||||
/// after the section name. It holds the ACIS geometry of 3D solids, regions, bodies and
|
||||
/// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD`
|
||||
/// names its entity with a 320 handle (see [`Foreign::data_store_entities`]).
|
||||
pub data_store: Vec<RawTag>,
|
||||
}
|
||||
|
||||
impl Foreign {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.objects.is_empty()
|
||||
&& self.dictionary.is_empty()
|
||||
&& self.entities.is_empty()
|
||||
&& self.records.is_empty()
|
||||
&& self.classes.is_empty()
|
||||
&& self.targets.is_empty()
|
||||
&& self.class_order.is_empty()
|
||||
&& self.data_store.is_empty()
|
||||
}
|
||||
|
||||
/// The entities the data store has records for (their 320 handles).
|
||||
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
|
||||
self.data_store.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim())).collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
//! Geometric tolerancing (GD&T): the TOLERANCE entity (feature control frames) and its layout.
|
||||
//!
|
||||
//! The frame is stored as the DXF Reference's "visual representation string" (TOLERANCE group 1):
|
||||
//! frame lines separated by `^J`, compartments separated by `%%v`, and the geometric symbols as
|
||||
//! characters of the `gdt` font inside `{\Fgdt;…}` runs. CADCraft never uses that font: every
|
||||
//! symbol is drawn by [`symbol_prims`] from our own geometry (standard ISO/ASME symbol shapes).
|
||||
|
||||
use cadcraft_geom::{Bounds2, Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Caps for hostile frame strings (files, command parameters).
|
||||
pub const MAX_FRAME_CHARS: usize = 4096;
|
||||
pub const MAX_FRAME_ROWS: usize = 8;
|
||||
pub const MAX_FRAME_CELLS: usize = 12;
|
||||
|
||||
/// A TOLERANCE entity: a feature control frame.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Tolerance {
|
||||
/// Insertion point: the middle of the left edge of the first frame line.
|
||||
pub insert: Vec3,
|
||||
/// The frame's X-axis direction (DXF group 11).
|
||||
#[serde(default = "x_axis")]
|
||||
pub dir: Vec3,
|
||||
/// Dimension style: text height (DIMTXT × DIMSCALE), gap, colours, text style.
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
/// The frame contents (DXF group 1).
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
fn x_axis() -> Vec3 {
|
||||
Vec3::new(1.0, 0.0, 0.0)
|
||||
}
|
||||
fn standard() -> String {
|
||||
"Standard".into()
|
||||
}
|
||||
|
||||
impl Tolerance {
|
||||
/// The frame's rotation (radians from +X); 0 when the direction is unusable.
|
||||
pub fn rotation(&self) -> f64 {
|
||||
let d = self.dir.xy();
|
||||
if d.is_finite() && d.len() > 1e-12 { d.angle() } else { 0.0 }
|
||||
}
|
||||
/// Text height and padding from the dimension style: DIMTXT and DIMGAP times the style's
|
||||
/// DIMSCALE (the drawing's when 0), or the text style's fixed height.
|
||||
pub fn text_size(&self, d: &crate::Drawing) -> (f64, f64) {
|
||||
let st = d.dim_style(&self.style).cloned().unwrap_or_default();
|
||||
let k = st.effective_scale(d.header.f64("DIMSCALE", 1.0));
|
||||
let fixed = d.text_style(&st.text_style).map(|t| t.height).filter(|h| h.is_finite() && *h > 0.0);
|
||||
let h = fixed.unwrap_or(st.text_height * k);
|
||||
(if h.is_finite() && h > 0.0 { h } else { 0.18 }, st.text_gap * k)
|
||||
}
|
||||
/// The frame laid out with `measure(text, height)` as the width of plain text.
|
||||
pub fn layout(&self, d: &crate::Drawing, measure: &dyn Fn(&str, f64) -> f64) -> GdtLayout {
|
||||
let (h, gap) = self.text_size(d);
|
||||
layout_frame(&self.text, self.insert.xy(), self.rotation(), h, gap, measure)
|
||||
}
|
||||
}
|
||||
|
||||
/// A geometric characteristic, material condition or zone symbol.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GdtSymbol {
|
||||
Position,
|
||||
Concentricity,
|
||||
Symmetry,
|
||||
Parallelism,
|
||||
Perpendicularity,
|
||||
Angularity,
|
||||
Cylindricity,
|
||||
Flatness,
|
||||
Circularity,
|
||||
Straightness,
|
||||
SurfaceProfile,
|
||||
LineProfile,
|
||||
CircularRunout,
|
||||
TotalRunout,
|
||||
Diameter,
|
||||
/// Maximum material condition (circled M).
|
||||
Mmc,
|
||||
/// Least material condition (circled L).
|
||||
Lmc,
|
||||
/// Regardless of feature size (circled S).
|
||||
Rfs,
|
||||
/// Projected tolerance zone (circled P).
|
||||
Projected,
|
||||
}
|
||||
|
||||
/// Every symbol with its `gdt` font character and its name.
|
||||
const SYMBOLS: [(GdtSymbol, char, &str); 19] = [
|
||||
(GdtSymbol::Position, 'j', "position"),
|
||||
(GdtSymbol::Concentricity, 'r', "concentricity"),
|
||||
(GdtSymbol::Symmetry, 'i', "symmetry"),
|
||||
(GdtSymbol::Parallelism, 'f', "parallelism"),
|
||||
(GdtSymbol::Perpendicularity, 'b', "perpendicularity"),
|
||||
(GdtSymbol::Angularity, 'a', "angularity"),
|
||||
(GdtSymbol::Cylindricity, 'g', "cylindricity"),
|
||||
(GdtSymbol::Flatness, 'c', "flatness"),
|
||||
(GdtSymbol::Circularity, 'e', "circularity"),
|
||||
(GdtSymbol::Straightness, 'u', "straightness"),
|
||||
(GdtSymbol::SurfaceProfile, 'd', "surfaceprofile"),
|
||||
(GdtSymbol::LineProfile, 'k', "lineprofile"),
|
||||
(GdtSymbol::CircularRunout, 'h', "circularrunout"),
|
||||
(GdtSymbol::TotalRunout, 't', "totalrunout"),
|
||||
(GdtSymbol::Diameter, 'n', "diameter"),
|
||||
(GdtSymbol::Mmc, 'm', "mmc"),
|
||||
(GdtSymbol::Lmc, 'l', "lmc"),
|
||||
(GdtSymbol::Rfs, 's', "rfs"),
|
||||
(GdtSymbol::Projected, 'p', "projected"),
|
||||
];
|
||||
|
||||
impl GdtSymbol {
|
||||
/// The symbol's character in the frame string's `{\Fgdt;…}` runs.
|
||||
pub fn code(self) -> char {
|
||||
SYMBOLS.iter().find(|(s, _, _)| *s == self).map(|(_, c, _)| *c).unwrap_or('j')
|
||||
}
|
||||
pub fn from_code(c: char) -> Option<GdtSymbol> {
|
||||
SYMBOLS.iter().find(|(_, k, _)| *k == c).map(|(s, _, _)| *s)
|
||||
}
|
||||
/// Lower-case name ("position", "mmc", …).
|
||||
pub fn name(self) -> &'static str {
|
||||
SYMBOLS.iter().find(|(s, _, _)| *s == self).map(|(_, _, n)| *n).unwrap_or("position")
|
||||
}
|
||||
/// A symbol by name (case, spaces, dashes and underscores ignored) or by a few common
|
||||
/// alternatives ("true position", "runout", "profile", "M", "L", "S").
|
||||
pub fn parse(s: &str) -> Option<GdtSymbol> {
|
||||
let k: String = s.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).flat_map(char::to_lowercase).collect();
|
||||
let alias = match k.as_str() {
|
||||
"trueposition" | "pos" => Some(GdtSymbol::Position),
|
||||
"coaxiality" => Some(GdtSymbol::Concentricity),
|
||||
"roundness" => Some(GdtSymbol::Circularity),
|
||||
"profile" | "surface" | "profileofasurface" => Some(GdtSymbol::SurfaceProfile),
|
||||
"line" | "profileofaline" => Some(GdtSymbol::LineProfile),
|
||||
"runout" => Some(GdtSymbol::CircularRunout),
|
||||
"total" => Some(GdtSymbol::TotalRunout),
|
||||
"m" => Some(GdtSymbol::Mmc),
|
||||
"l" => Some(GdtSymbol::Lmc),
|
||||
"s" => Some(GdtSymbol::Rfs),
|
||||
"dia" | "ø" | "⌀" | "%%c" => Some(GdtSymbol::Diameter),
|
||||
_ => None,
|
||||
};
|
||||
alias.or_else(|| SYMBOLS.iter().find(|(_, _, n)| *n == k).map(|(s, _, _)| *s))
|
||||
}
|
||||
/// A geometric characteristic (the first compartment of a frame line).
|
||||
pub fn is_characteristic(self) -> bool {
|
||||
!matches!(self, GdtSymbol::Diameter | GdtSymbol::Mmc | GdtSymbol::Lmc | GdtSymbol::Rfs | GdtSymbol::Projected)
|
||||
}
|
||||
/// A material condition modifier.
|
||||
pub fn is_material(self) -> bool {
|
||||
matches!(self, GdtSymbol::Mmc | GdtSymbol::Lmc | GdtSymbol::Rfs)
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece of a compartment: plain text or a symbol.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GdtRun {
|
||||
Text(String),
|
||||
Symbol(GdtSymbol),
|
||||
}
|
||||
|
||||
/// One compartment's runs.
|
||||
pub type Compartment = Vec<GdtRun>;
|
||||
|
||||
/// Parse a frame string into lines of compartments. Unknown formatting codes are skipped, an
|
||||
/// unterminated code ends the string, and the sizes are capped ([`MAX_FRAME_CHARS`],
|
||||
/// [`MAX_FRAME_ROWS`], [`MAX_FRAME_CELLS`]).
|
||||
pub fn parse_frame(text: &str) -> Vec<Vec<Compartment>> {
|
||||
let cs: Vec<char> = text.chars().take(MAX_FRAME_CHARS).collect();
|
||||
let at = |i: usize| cs.get(i).copied();
|
||||
let mut rows: Vec<Vec<Compartment>> = vec![vec![Vec::new()]];
|
||||
// Font stack: whether the `gdt` font is current, per brace level.
|
||||
let mut gdt = false;
|
||||
let mut stack: Vec<bool> = Vec::new();
|
||||
let push = |rows: &mut Vec<Vec<Compartment>>, run: GdtRun| {
|
||||
let Some(cell) = rows.last_mut().and_then(|r| r.last_mut()) else { return };
|
||||
match (cell.last_mut(), run) {
|
||||
(Some(GdtRun::Text(t)), GdtRun::Text(s)) => t.push_str(&s),
|
||||
(_, run) => cell.push(run),
|
||||
}
|
||||
};
|
||||
let mut i = 0;
|
||||
while let Some(c) = at(i) {
|
||||
let next = at(i + 1);
|
||||
let lower = |k: usize| at(k).map(|c| c.to_ascii_lowercase());
|
||||
// Line break: `^J`, `\P` or a raw newline.
|
||||
if (c == '^' && matches!(next, Some('J' | 'j'))) || (c == '\\' && next == Some('P')) || c == '\n' {
|
||||
if rows.len() >= MAX_FRAME_ROWS {
|
||||
break;
|
||||
}
|
||||
rows.push(vec![Vec::new()]);
|
||||
i += if c == '\n' { 1 } else { 2 };
|
||||
continue;
|
||||
}
|
||||
if c == '\r' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if c == '%' && next == Some('%') {
|
||||
match lower(i + 2) {
|
||||
Some('v') => {
|
||||
if let Some(r) = rows.last_mut()
|
||||
&& r.len() < MAX_FRAME_CELLS
|
||||
{
|
||||
r.push(Vec::new());
|
||||
}
|
||||
}
|
||||
Some('c') => push(&mut rows, GdtRun::Symbol(GdtSymbol::Diameter)),
|
||||
Some('d') => push(&mut rows, GdtRun::Text("°".into())),
|
||||
Some('p') => push(&mut rows, GdtRun::Text("±".into())),
|
||||
Some('%') => push(&mut rows, GdtRun::Text("%".into())),
|
||||
Some(o) => push(&mut rows, GdtRun::Text(format!("%%{o}"))),
|
||||
None => break,
|
||||
}
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'{' => {
|
||||
if stack.len() < 64 {
|
||||
stack.push(gdt);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
'}' => {
|
||||
gdt = stack.pop().unwrap_or(false);
|
||||
i += 1;
|
||||
}
|
||||
'\\' => match next {
|
||||
Some('\\' | '{' | '}') => {
|
||||
if let Some(n) = next {
|
||||
push(&mut rows, GdtRun::Text(n.to_string()));
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
// Font switch `\Fname;` / `\fname|b0|i0;`: the gdt font draws symbols.
|
||||
Some('F' | 'f') => {
|
||||
let Some(end) = (i + 2..cs.len()).find(|k| at(*k) == Some(';')) else { break };
|
||||
let name: String = cs.get(i + 2..end).unwrap_or(&[]).iter().take_while(|c| **c != '|').collect();
|
||||
gdt = name.trim().to_ascii_lowercase().starts_with("gdt");
|
||||
i = end + 1;
|
||||
}
|
||||
// Codes with a value up to `;` (height, colour, tracking, width, oblique, alignment…).
|
||||
Some('A' | 'C' | 'c' | 'H' | 'Q' | 'T' | 'W' | 'S') => {
|
||||
let Some(end) = (i + 2..cs.len()).find(|k| at(*k) == Some(';')) else { break };
|
||||
i = end + 1;
|
||||
}
|
||||
// On/off toggles (underline, overline, strike-through) and the non-breaking space.
|
||||
Some('L' | 'l' | 'O' | 'o' | 'K' | 'k') => i += 2,
|
||||
Some('~') => {
|
||||
push(&mut rows, GdtRun::Text(" ".into()));
|
||||
i += 2;
|
||||
}
|
||||
Some(_) => {
|
||||
push(&mut rows, GdtRun::Text("\\".into()));
|
||||
i += 1;
|
||||
}
|
||||
None => break,
|
||||
},
|
||||
c if gdt => {
|
||||
push(&mut rows, GdtSymbol::from_code(c).map(GdtRun::Symbol).unwrap_or_else(|| GdtRun::Text(c.to_string())));
|
||||
i += 1;
|
||||
}
|
||||
c => {
|
||||
push(&mut rows, GdtRun::Text(c.to_string()));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// A compartment with nothing to show.
|
||||
pub fn compartment_is_empty(c: &Compartment) -> bool {
|
||||
c.iter().all(|r| matches!(r, GdtRun::Text(t) if t.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// A tolerance value: optional diameter symbol, the value, optional material condition.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GdtTol {
|
||||
#[serde(default)]
|
||||
pub diameter: bool,
|
||||
#[serde(default)]
|
||||
pub value: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub material: Option<String>,
|
||||
}
|
||||
|
||||
/// A datum reference: the letter(s) and an optional material condition.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GdtDatum {
|
||||
#[serde(default)]
|
||||
pub letter: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub material: Option<String>,
|
||||
}
|
||||
|
||||
/// One frame line as the Geometric Tolerance dialog fills it.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct GdtLine {
|
||||
pub symbol: Option<GdtSymbol>,
|
||||
pub tol1: Option<GdtTol>,
|
||||
pub tol2: Option<GdtTol>,
|
||||
pub datums: Vec<GdtDatum>,
|
||||
}
|
||||
|
||||
/// A whole feature control frame: up to two tolerance lines, the projected tolerance zone and
|
||||
/// the datum identifier.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct GdtFrame {
|
||||
pub lines: Vec<GdtLine>,
|
||||
/// Projected tolerance zone height ("" = none).
|
||||
pub height: String,
|
||||
pub projected: bool,
|
||||
/// Datum identifier ("" = none).
|
||||
pub datum_id: String,
|
||||
}
|
||||
|
||||
/// Escape free text for a frame string (no line or compartment breaks, no formatting codes).
|
||||
fn escape(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for c in s.chars().take(256) {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'{' => out.push_str("\\{"),
|
||||
'}' => out.push_str("\\}"),
|
||||
// `%%%` is a literal percent sign (a lone `%` could start a `%%` code).
|
||||
'%' => out.push_str("%%%"),
|
||||
'\n' | '\r' | '^' => out.push(' '),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn sym(s: GdtSymbol) -> String {
|
||||
format!("{{\\Fgdt;{}}}", s.code())
|
||||
}
|
||||
|
||||
/// The material condition symbol named by `m` ("M", "L", "S", "mmc"…).
|
||||
fn material(m: &Option<String>) -> Option<GdtSymbol> {
|
||||
m.as_deref().and_then(GdtSymbol::parse).filter(|s| s.is_material())
|
||||
}
|
||||
|
||||
/// The frame string for `f` (DXF group 1 of a TOLERANCE).
|
||||
pub fn compose_frame(f: &GdtFrame) -> String {
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
let tol = |t: &Option<GdtTol>| -> String {
|
||||
let Some(t) = t else { return String::new() };
|
||||
let mut s = String::new();
|
||||
if t.diameter {
|
||||
s.push_str(&sym(GdtSymbol::Diameter));
|
||||
}
|
||||
s.push_str(&escape(t.value.trim()));
|
||||
if let Some(m) = material(&t.material) {
|
||||
s.push_str(&sym(m));
|
||||
}
|
||||
if t.value.trim().is_empty() && !t.diameter && material(&t.material).is_none() { String::new() } else { s }
|
||||
};
|
||||
for l in f.lines.iter().take(MAX_FRAME_ROWS) {
|
||||
let mut cells = vec![l.symbol.map(sym).unwrap_or_default(), tol(&l.tol1), tol(&l.tol2)];
|
||||
for d in l.datums.iter().take(3) {
|
||||
let mut s = escape(d.letter.trim());
|
||||
if let Some(m) = material(&d.material) {
|
||||
s.push_str(&sym(m));
|
||||
}
|
||||
cells.push(s);
|
||||
}
|
||||
while cells.last().is_some_and(String::is_empty) {
|
||||
cells.pop();
|
||||
}
|
||||
if !cells.is_empty() {
|
||||
lines.push(cells.join("%%v"));
|
||||
}
|
||||
}
|
||||
if !f.height.trim().is_empty() || f.projected {
|
||||
let mut s = escape(f.height.trim());
|
||||
if f.projected {
|
||||
s.push_str(&sym(GdtSymbol::Projected));
|
||||
}
|
||||
lines.push(s);
|
||||
}
|
||||
if !f.datum_id.trim().is_empty() {
|
||||
lines.push(escape(f.datum_id.trim()));
|
||||
}
|
||||
lines.join("^J")
|
||||
}
|
||||
|
||||
/// A primitive of a laid-out frame, in WCS.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GdtPrim {
|
||||
Line(Vec<Vec2>),
|
||||
Circle {
|
||||
center: Vec2,
|
||||
radius: f64,
|
||||
},
|
||||
/// Counter-clockwise from `start` to `end` (radians).
|
||||
Arc {
|
||||
center: Vec2,
|
||||
radius: f64,
|
||||
start: f64,
|
||||
end: f64,
|
||||
},
|
||||
/// A filled triangle (arrowheads).
|
||||
Fill([Vec2; 3]),
|
||||
}
|
||||
|
||||
/// A text run of a laid-out frame: left baseline point (WCS), height and rotation.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GdtText {
|
||||
pub pos: Vec2,
|
||||
pub height: f64,
|
||||
pub rotation: f64,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// A laid-out feature control frame.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct GdtLayout {
|
||||
/// The frame's boxes (drawn with the dimension line colour).
|
||||
pub frame: Vec<GdtPrim>,
|
||||
/// The symbols (drawn with the text colour).
|
||||
pub symbols: Vec<GdtPrim>,
|
||||
pub texts: Vec<GdtText>,
|
||||
pub bounds: Bounds2,
|
||||
}
|
||||
|
||||
/// Lay out the frame `text` at `insert`, rotated by `rotation`, with text height `h` and
|
||||
/// horizontal padding `gap`. `measure(s, h)` is the width of plain text `s` at height `h`.
|
||||
pub fn layout_frame(text: &str, insert: Vec2, rotation: f64, h: f64, gap: f64, measure: &dyn Fn(&str, f64) -> f64) -> GdtLayout {
|
||||
let h = if h.is_finite() && h > 0.0 { h.min(1e12) } else { 0.18 };
|
||||
let gap = if gap.is_finite() { gap.abs().clamp(h * 0.25, h * 2.0) } else { h * 0.5 };
|
||||
let rotation = if rotation.is_finite() { rotation } else { 0.0 };
|
||||
let (insert, row_h) = (if insert.is_finite() { insert } else { Vec2::ZERO }, 2.0 * h);
|
||||
let to_w = |p: Vec2| insert + p.rotate(rotation);
|
||||
let mut out = GdtLayout::default();
|
||||
let mut prev_width = 0.0;
|
||||
let rows: Vec<Vec<Compartment>> = parse_frame(text)
|
||||
.into_iter()
|
||||
.map(|r| r.into_iter().filter(|c| !compartment_is_empty(c)).collect::<Vec<_>>())
|
||||
.filter(|r| !r.is_empty())
|
||||
.collect();
|
||||
let run_w = |r: &GdtRun| match r {
|
||||
GdtRun::Symbol(_) => h,
|
||||
GdtRun::Text(t) => {
|
||||
let w = measure(t, h);
|
||||
if w.is_finite() { w.clamp(0.0, h * 4096.0) } else { 0.0 }
|
||||
}
|
||||
};
|
||||
for (k, row) in rows.iter().enumerate() {
|
||||
let top = h - k as f64 * row_h;
|
||||
let (bot, mid) = (top - row_h, top - h);
|
||||
let mut x = 0.0;
|
||||
for cell in row {
|
||||
// Runs a little apart, so a modifier doesn't touch the value before it.
|
||||
let sep = 0.25 * h;
|
||||
let w: f64 = cell.iter().map(run_w).sum::<f64>() + sep * cell.len().saturating_sub(1) as f64;
|
||||
let cw = (w + 2.0 * gap).max(row_h);
|
||||
// The separator on the cell's left (the frame's left edge for the first cell).
|
||||
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(x, top)), to_w(Vec2::new(x, bot))]));
|
||||
let mut cx = x + (cw - w) / 2.0;
|
||||
for r in cell {
|
||||
match r {
|
||||
GdtRun::Symbol(s) => {
|
||||
let o = Vec2::new(cx, mid - h / 2.0);
|
||||
out.symbols.extend(symbol_prims(*s).into_iter().map(|p| map_prim(p, |q| to_w(o + q * h), h, rotation)));
|
||||
}
|
||||
GdtRun::Text(t) => {
|
||||
out.texts.push(GdtText { pos: to_w(Vec2::new(cx, mid - h / 2.0)), height: h, rotation, value: t.clone() });
|
||||
}
|
||||
}
|
||||
cx += run_w(r) + sep;
|
||||
}
|
||||
x += cw;
|
||||
}
|
||||
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(x, top)), to_w(Vec2::new(x, bot))]));
|
||||
// Top edge: the first line's, or the part sticking out past the line above.
|
||||
if k == 0 {
|
||||
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(0.0, top)), to_w(Vec2::new(x, top))]));
|
||||
} else if x > prev_width {
|
||||
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(prev_width, top)), to_w(Vec2::new(x, top))]));
|
||||
}
|
||||
out.frame.push(GdtPrim::Line(vec![to_w(Vec2::new(0.0, bot)), to_w(Vec2::new(x, bot))]));
|
||||
out.bounds = out.bounds.union(&Bounds2::from_points([
|
||||
to_w(Vec2::new(0.0, top)),
|
||||
to_w(Vec2::new(x, bot)),
|
||||
to_w(Vec2::new(0.0, bot)),
|
||||
to_w(Vec2::new(x, top)),
|
||||
]));
|
||||
prev_width = x;
|
||||
}
|
||||
if rows.is_empty() {
|
||||
out.bounds = Bounds2::from_points([insert]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Map a unit-box primitive through `f` (scale `s`, rotation `rot`).
|
||||
fn map_prim(p: GdtPrim, f: impl Fn(Vec2) -> Vec2, s: f64, rot: f64) -> GdtPrim {
|
||||
match p {
|
||||
GdtPrim::Line(v) => GdtPrim::Line(v.into_iter().map(f).collect()),
|
||||
GdtPrim::Circle { center, radius } => GdtPrim::Circle { center: f(center), radius: radius * s },
|
||||
GdtPrim::Arc { center, radius, start, end } => GdtPrim::Arc { center: f(center), radius: radius * s, start: start + rot, end: end + rot },
|
||||
GdtPrim::Fill(t) => GdtPrim::Fill(t.map(f)),
|
||||
}
|
||||
}
|
||||
|
||||
/// An arrowhead at `tip` pointing along `d` (unit box units).
|
||||
fn arrow(tip: Vec2, d: Vec2) -> GdtPrim {
|
||||
let d = d.normalized();
|
||||
let back = tip - d * 0.3;
|
||||
GdtPrim::Fill([tip, back + d.perp() * 0.1, back - d.perp() * 0.1])
|
||||
}
|
||||
|
||||
/// A symbol drawn in a unit box (x and y in 0..1, the baseline at y = 0).
|
||||
pub fn symbol_prims(s: GdtSymbol) -> Vec<GdtPrim> {
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
let v = Vec2::new;
|
||||
let line = |pts: &[(f64, f64)]| GdtPrim::Line(pts.iter().map(|(x, y)| v(*x, *y)).collect());
|
||||
let circle = |x: f64, y: f64, r: f64| GdtPrim::Circle { center: v(x, y), radius: r };
|
||||
// Circled letters: the circle plus the letter's strokes.
|
||||
let circled = |mut letter: Vec<GdtPrim>| {
|
||||
letter.insert(0, circle(0.5, 0.5, 0.5));
|
||||
letter
|
||||
};
|
||||
match s {
|
||||
GdtSymbol::Position => vec![circle(0.5, 0.5, 0.3), line(&[(0.0, 0.5), (1.0, 0.5)]), line(&[(0.5, 0.0), (0.5, 1.0)])],
|
||||
GdtSymbol::Concentricity => vec![circle(0.5, 0.5, 0.45), circle(0.5, 0.5, 0.25)],
|
||||
GdtSymbol::Symmetry => vec![line(&[(0.0, 0.5), (1.0, 0.5)]), line(&[(0.2, 0.2), (0.8, 0.2)]), line(&[(0.2, 0.8), (0.8, 0.8)])],
|
||||
GdtSymbol::Parallelism => vec![line(&[(0.1, 0.05), (0.5, 0.95)]), line(&[(0.5, 0.05), (0.9, 0.95)])],
|
||||
GdtSymbol::Perpendicularity => vec![line(&[(0.05, 0.05), (0.95, 0.05)]), line(&[(0.5, 0.05), (0.5, 0.95)])],
|
||||
GdtSymbol::Angularity => vec![line(&[(0.95, 0.05), (0.05, 0.05), (0.85, 0.75)])],
|
||||
GdtSymbol::Cylindricity => {
|
||||
let (c, r) = (v(0.5, 0.5), 0.3);
|
||||
let d = Vec2::from_angle(65f64.to_radians());
|
||||
let n = d.perp() * r;
|
||||
vec![circle(0.5, 0.5, r), GdtPrim::Line(vec![c + n - d * 0.5, c + n + d * 0.5]), GdtPrim::Line(vec![c - n - d * 0.5, c - n + d * 0.5])]
|
||||
}
|
||||
GdtSymbol::Flatness => vec![line(&[(0.0, 0.25), (0.7, 0.25), (1.0, 0.75), (0.3, 0.75), (0.0, 0.25)])],
|
||||
GdtSymbol::Circularity => vec![circle(0.5, 0.5, 0.45)],
|
||||
GdtSymbol::Straightness => vec![line(&[(0.0, 0.5), (1.0, 0.5)])],
|
||||
GdtSymbol::SurfaceProfile => {
|
||||
vec![GdtPrim::Arc { center: v(0.5, 0.2), radius: 0.45, start: 0.0, end: PI }, line(&[(0.05, 0.2), (0.95, 0.2)])]
|
||||
}
|
||||
GdtSymbol::LineProfile => vec![GdtPrim::Arc { center: v(0.5, 0.2), radius: 0.45, start: 0.0, end: PI }],
|
||||
GdtSymbol::CircularRunout => vec![line(&[(0.2, 0.05), (0.7, 0.95)]), arrow(v(0.7, 0.95), v(0.5, 0.9))],
|
||||
GdtSymbol::TotalRunout => vec![
|
||||
line(&[(0.05, 0.05), (0.5, 0.05)]),
|
||||
line(&[(0.05, 0.05), (0.45, 0.95)]),
|
||||
line(&[(0.5, 0.05), (0.9, 0.95)]),
|
||||
arrow(v(0.45, 0.95), v(0.4, 0.9)),
|
||||
arrow(v(0.9, 0.95), v(0.4, 0.9)),
|
||||
],
|
||||
GdtSymbol::Diameter => vec![circle(0.5, 0.5, 0.35), line(&[(0.1, 0.0), (0.9, 1.0)])],
|
||||
GdtSymbol::Mmc => circled(vec![line(&[(0.3, 0.25), (0.3, 0.75), (0.5, 0.45), (0.7, 0.75), (0.7, 0.25)])]),
|
||||
GdtSymbol::Lmc => circled(vec![line(&[(0.38, 0.75), (0.38, 0.25), (0.65, 0.25)])]),
|
||||
GdtSymbol::Rfs => circled(vec![
|
||||
GdtPrim::Arc { center: v(0.5, 0.625), radius: 0.125, start: 20f64.to_radians(), end: 3.0 * FRAC_PI_2 },
|
||||
GdtPrim::Arc { center: v(0.5, 0.375), radius: 0.125, start: 200f64.to_radians(), end: FRAC_PI_2 },
|
||||
]),
|
||||
GdtSymbol::Projected => circled(vec![
|
||||
line(&[(0.5, 0.5), (0.38, 0.5), (0.38, 0.75), (0.5, 0.75)]),
|
||||
GdtPrim::Arc { center: v(0.5, 0.625), radius: 0.125, start: -FRAC_PI_2, end: FRAC_PI_2 },
|
||||
line(&[(0.38, 0.5), (0.38, 0.25)]),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_symbols_compartments_and_lines() {
|
||||
let rows = parse_frame("{\\Fgdt;j}%%v{\\Fgdt;n}0.1{\\Fgdt;m}%%vA%%vB^J2.5{\\Fgdt;p}");
|
||||
assert_eq!(rows.len(), 2);
|
||||
let r0 = &rows[0];
|
||||
assert_eq!(r0.len(), 4);
|
||||
assert_eq!(r0[0], vec![GdtRun::Symbol(GdtSymbol::Position)]);
|
||||
assert_eq!(r0[1], vec![GdtRun::Symbol(GdtSymbol::Diameter), GdtRun::Text("0.1".into()), GdtRun::Symbol(GdtSymbol::Mmc)]);
|
||||
assert_eq!(r0[3], vec![GdtRun::Text("B".into())]);
|
||||
assert_eq!(rows[1][0], vec![GdtRun::Text("2.5".into()), GdtRun::Symbol(GdtSymbol::Projected)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_then_parse() {
|
||||
let f = GdtFrame {
|
||||
lines: vec![GdtLine {
|
||||
symbol: Some(GdtSymbol::Flatness),
|
||||
tol1: Some(GdtTol { diameter: false, value: "0.05".into(), material: None }),
|
||||
tol2: None,
|
||||
datums: vec![GdtDatum { letter: "A".into(), material: Some("L".into()) }],
|
||||
}],
|
||||
height: String::new(),
|
||||
projected: false,
|
||||
datum_id: "B".into(),
|
||||
};
|
||||
let s = compose_frame(&f);
|
||||
assert_eq!(s, "{\\Fgdt;c}%%v0.05%%v%%vA{\\Fgdt;l}^JB");
|
||||
let rows = parse_frame(&s);
|
||||
assert_eq!(rows[0][3], vec![GdtRun::Text("A".into()), GdtRun::Symbol(GdtSymbol::Lmc)]);
|
||||
assert_eq!(rows[1][0], vec![GdtRun::Text("B".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_strings_do_not_panic() {
|
||||
let huge = "%%v{\\Fgdt;j}".repeat(100_000);
|
||||
for s in ["{\\Fgdt;", "{\\Fgdt", "\\", "%%", "%", "{{{{", "}}}}", "^", "\\P\\P\\P", "{\\H", &huge, "\u{0}%%v\u{ffff}"] {
|
||||
let rows = parse_frame(s);
|
||||
assert!(rows.len() <= MAX_FRAME_ROWS && rows.iter().all(|r| r.len() <= MAX_FRAME_CELLS));
|
||||
let l = layout_frame(s, Vec2::new(f64::NAN, 1.0), f64::INFINITY, f64::NAN, -1.0, &|t, h| t.len() as f64 * h);
|
||||
assert!(l.frame.iter().all(|p| matches!(p, GdtPrim::Line(v) if v.iter().all(|q| q.is_finite()))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_boxes_each_compartment() {
|
||||
let l = layout_frame("{\\Fgdt;j}%%v0.1%%vA", Vec2::ZERO, 0.0, 1.0, 0.5, &|t, h| t.chars().count() as f64 * h);
|
||||
// Three cells: four separators, top and bottom.
|
||||
assert_eq!(l.frame.len(), 6);
|
||||
assert_eq!(l.texts.len(), 2);
|
||||
assert!((l.bounds.min.y + 1.0).abs() < 1e-9 && (l.bounds.max.y - 1.0).abs() < 1e-9);
|
||||
assert!(l.bounds.min.x.abs() < 1e-9 && l.bounds.max.x > 6.0);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use cadcraft_geom::Vec3;
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A header variable value.
|
||||
@@ -76,6 +76,20 @@ impl Header {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Drawing snap spacing; malformed or missing values use the drafting default.
|
||||
pub fn snap_unit(&self) -> Vec2 {
|
||||
self.spacing("SNAPUNIT", false)
|
||||
}
|
||||
/// Drawing grid spacing. A zero component follows the corresponding snap spacing.
|
||||
pub fn grid_unit(&self) -> Vec2 {
|
||||
self.spacing("GRIDUNIT", true)
|
||||
}
|
||||
fn spacing(&self, name: &str, allow_zero: bool) -> Vec2 {
|
||||
self.point(name)
|
||||
.map(|p| p.xy())
|
||||
.filter(|p| p.is_finite() && if allow_zero { p.x >= 0.0 && p.y >= 0.0 } else { p.x > 0.0 && p.y > 0.0 })
|
||||
.unwrap_or(Vec2::new(0.5, 0.5))
|
||||
}
|
||||
pub fn set_f64(&mut self, name: &str, v: f64) {
|
||||
self.set(name, HVal::Real(v));
|
||||
}
|
||||
@@ -118,6 +132,11 @@ impl Header {
|
||||
// Snap grid origin and rotation (SNAPANG in degrees).
|
||||
h.set("SNAPBASE", HVal::Point(Vec3::ZERO));
|
||||
h.set_f64("SNAPANG", 0.0);
|
||||
h.set("SNAPUNIT", HVal::Point(Vec3::new(0.5, 0.5, 0.0)));
|
||||
h.set("GRIDUNIT", HVal::Point(Vec3::new(0.5, 0.5, 0.0)));
|
||||
// Annotation scale of model space; annotative objects of other scales show (1) or not.
|
||||
h.set_str("CANNOSCALE", "1:1");
|
||||
h.set_i64("ANNOALLVISIBLE", 1);
|
||||
h
|
||||
}
|
||||
|
||||
|
||||
+109
-5
@@ -6,25 +6,39 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod array;
|
||||
mod constraint;
|
||||
mod entity;
|
||||
mod extents;
|
||||
mod gdt;
|
||||
mod header;
|
||||
pub mod library;
|
||||
mod plotstyle;
|
||||
mod plotter;
|
||||
mod refedit;
|
||||
mod store;
|
||||
mod tables;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub use array::*;
|
||||
pub use cadcraft_color as color;
|
||||
pub use cadcraft_geom as geom;
|
||||
pub use constraint::*;
|
||||
pub use entity::*;
|
||||
pub use extents::{MAX_BLOCK_DEPTH, entity_bounds};
|
||||
pub use gdt::*;
|
||||
pub use header::{HVal, Header};
|
||||
pub use plotstyle::*;
|
||||
pub use plotter::*;
|
||||
pub use refedit::{RefEdit, WorkItem};
|
||||
pub use store::EntityStore;
|
||||
pub use tables::*;
|
||||
|
||||
/// File data CADCraft doesn't model, kept for saving (#528).
|
||||
pub mod dynblock;
|
||||
pub mod foreign;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DocError {
|
||||
#[error("no such layer `{0}`")]
|
||||
@@ -48,28 +62,74 @@ pub enum Space {
|
||||
Paper(String),
|
||||
}
|
||||
|
||||
impl Space {
|
||||
/// Whether this is a layout's paper space.
|
||||
pub fn is_paper(&self) -> bool {
|
||||
matches!(self, Space::Paper(_))
|
||||
}
|
||||
|
||||
/// The layout whose paper space this is; `None` for model space.
|
||||
pub fn layout(&self) -> Option<&str> {
|
||||
match self {
|
||||
Space::Paper(n) => Some(n),
|
||||
Space::Model => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tab name (CTAB): `Model`, or the layout's name.
|
||||
pub fn tab_name(&self) -> &str {
|
||||
self.layout().unwrap_or("Model")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Drawing {
|
||||
pub header: Header,
|
||||
/// File data CADCraft does not model, written back on save.
|
||||
pub foreign: std::sync::Arc<foreign::Foreign>,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<Linetype>,
|
||||
pub text_styles: Vec<TextStyle>,
|
||||
pub dim_styles: Vec<DimStyle>,
|
||||
pub mleader_styles: Vec<MLeaderStyle>,
|
||||
pub table_styles: Vec<TableStyle>,
|
||||
/// Multiline styles (MLSTYLE); STANDARD is always there.
|
||||
pub mline_styles: Vec<MLineStyle>,
|
||||
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
|
||||
pub model: EntityStore,
|
||||
pub layouts: Vec<Layout>,
|
||||
/// The layout a file marks active (its block is `*Paper_Space`, the others `*Paper_SpaceN`),
|
||||
/// written active again. `None`, or a layout that no longer exists: the first by tab order.
|
||||
pub active_layout: Option<String>,
|
||||
pub views: Vec<NamedView>,
|
||||
/// Model space viewport configurations (VPORTS): the tiles shown and named ones.
|
||||
pub vports: Vec<VportConfig>,
|
||||
pub ucss: Vec<Ucs>,
|
||||
pub layer_states: Vec<LayerState>,
|
||||
pub groups: Vec<Group>,
|
||||
/// Plot style tables kept with the drawing (STYLESMANAGER); they shadow built-in tables of
|
||||
/// the same name.
|
||||
pub plot_style_tables: Vec<PlotStyleTable>,
|
||||
/// Parametric constraints (GEOMCONSTRAINT / DIMCONSTRAINT).
|
||||
pub constraints: Vec<Constraint>,
|
||||
/// User parameters and parametric settings.
|
||||
pub parametric: Parametric,
|
||||
/// The annotation scale list (SCALELISTEDIT).
|
||||
pub scales: Vec<AnnoScale>,
|
||||
/// Next free handle.
|
||||
pub handseed: u64,
|
||||
/// Objects hidden for this session by ISOLATEOBJECTS / HIDEOBJECTS. Never written to a file:
|
||||
/// a drawing opens with everything shown again.
|
||||
pub hidden_objects: BTreeSet<Handle>,
|
||||
/// What reading the file left out (a DWG's object records the reader couldn't decode), told
|
||||
/// to the user when the drawing opens. Never written to a file.
|
||||
pub read_notes: Vec<String>,
|
||||
/// The in-place block reference edit in progress (REFEDIT). Never written to a file; files are
|
||||
/// written from [`Drawing::committed`].
|
||||
pub refedit: Option<RefEdit>,
|
||||
/// Records of the file this drawing was read from that the reader could not place (a damaged
|
||||
/// file), counted by the section they came from. Never written to a file.
|
||||
pub skipped_records: BTreeMap<String, usize>,
|
||||
}
|
||||
|
||||
impl Default for Drawing {
|
||||
@@ -85,17 +145,21 @@ impl Drawing {
|
||||
d.header = Header::imperial();
|
||||
d
|
||||
}
|
||||
/// An empty metric drawing (millimetres, ISO-25 dimensions).
|
||||
/// An empty metric drawing (millimetres, ISO-25 dimensions, multileaders and tables to match).
|
||||
pub fn new_metric() -> Self {
|
||||
let mut d = Drawing::bare();
|
||||
d.header = Header::metric();
|
||||
d.scales = metric_scales();
|
||||
d.dim_styles.push(DimStyle::iso25());
|
||||
d.mleader_styles = vec![MLeaderStyle::metric()];
|
||||
d.table_styles = vec![TableStyle::metric()];
|
||||
d.header.set_str("DIMSTYLE", "ISO-25");
|
||||
d
|
||||
}
|
||||
fn bare() -> Self {
|
||||
Drawing {
|
||||
header: Header::default(),
|
||||
foreign: std::sync::Arc::default(),
|
||||
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
|
||||
linetypes: vec![
|
||||
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
|
||||
@@ -106,16 +170,25 @@ impl Drawing {
|
||||
dim_styles: vec![DimStyle::default()],
|
||||
mleader_styles: vec![MLeaderStyle::default()],
|
||||
table_styles: vec![TableStyle::default()],
|
||||
mline_styles: vec![MLineStyle::default()],
|
||||
blocks: BTreeMap::new(),
|
||||
model: EntityStore::new(),
|
||||
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
|
||||
active_layout: None,
|
||||
views: Vec::new(),
|
||||
vports: Vec::new(),
|
||||
ucss: Vec::new(),
|
||||
layer_states: Vec::new(),
|
||||
groups: Vec::new(),
|
||||
plot_style_tables: Vec::new(),
|
||||
constraints: Vec::new(),
|
||||
parametric: Parametric::default(),
|
||||
scales: imperial_scales(),
|
||||
handseed: 0x100,
|
||||
hidden_objects: BTreeSet::new(),
|
||||
read_notes: Vec::new(),
|
||||
refedit: None,
|
||||
skipped_records: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +238,17 @@ impl Drawing {
|
||||
let same = match (base.get(*field), &cv) {
|
||||
// Text style and arrow block names compare without case.
|
||||
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
|
||||
if matches!(*field, "textStyle" | "arrowBlock" | "arrowBlock1" | "arrowBlock2") =>
|
||||
if matches!(
|
||||
*field,
|
||||
"textStyle"
|
||||
| "arrowBlock"
|
||||
| "arrowBlock1"
|
||||
| "arrowBlock2"
|
||||
| "leaderArrowBlock"
|
||||
| "dimLinetype"
|
||||
| "extLinetype1"
|
||||
| "extLinetype2"
|
||||
) =>
|
||||
{
|
||||
a.eq_ignore_ascii_case(b)
|
||||
}
|
||||
@@ -219,6 +302,18 @@ impl Drawing {
|
||||
true
|
||||
}
|
||||
|
||||
/// The layouts in the order their paper space blocks are named in a file: the active one
|
||||
/// (`*Paper_Space`) first, then the others by tab order (`*Paper_Space0`, `*Paper_Space1`, …).
|
||||
pub fn paper_space_layouts(&self) -> Vec<&Layout> {
|
||||
let mut ls: Vec<&Layout> = self.layouts.iter().collect();
|
||||
ls.sort_by_key(|l| l.tab_order);
|
||||
if let Some(i) = self.active_layout.as_ref().and_then(|a| ls.iter().position(|l| l.name.eq_ignore_ascii_case(a))) {
|
||||
let active = ls.remove(i);
|
||||
ls.insert(0, active);
|
||||
}
|
||||
ls
|
||||
}
|
||||
|
||||
pub fn space(&self, space: &Space) -> Option<&EntityStore> {
|
||||
match space {
|
||||
Space::Model => Some(&self.model),
|
||||
@@ -261,9 +356,15 @@ impl Drawing {
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
/// Effective visibility of an entity (its own flag, its layer on/thawed).
|
||||
/// Effective visibility of an entity (its own flag, its layer on/thawed, not hidden by object
|
||||
/// isolation).
|
||||
pub fn is_visible(&self, e: &Entity) -> bool {
|
||||
e.common.visible && self.layer(&e.common.layer).is_none_or(Layer::visible)
|
||||
e.common.visible && self.layer(&e.common.layer).is_none_or(Layer::visible) && !self.is_hidden_object(e.handle)
|
||||
}
|
||||
|
||||
/// Whether ISOLATEOBJECTS / HIDEOBJECTS hid `h` for this session.
|
||||
pub fn is_hidden_object(&self, h: Handle) -> bool {
|
||||
!self.hidden_objects.is_empty() && self.hidden_objects.contains(&h)
|
||||
}
|
||||
|
||||
/// Bounds of all visible entities in a space.
|
||||
@@ -297,5 +398,8 @@ impl Drawing {
|
||||
}
|
||||
}
|
||||
|
||||
mod anno;
|
||||
pub use anno::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
+70
-21
@@ -6,6 +6,8 @@
|
||||
|
||||
use crate::{DashElement, Drawing, Linetype};
|
||||
|
||||
pub mod files;
|
||||
|
||||
/// The standard linetype library, defined in inches. Load it into a drawing with
|
||||
/// [`standard_linetypes_for`], which scales it for metric drawings.
|
||||
pub fn standard_linetypes() -> Vec<Linetype> {
|
||||
@@ -151,9 +153,11 @@ pub fn standard_patterns() -> Vec<HatchPattern> {
|
||||
name: "BRICK",
|
||||
description: "Brick or masonry-type surface",
|
||||
lines: vec![
|
||||
// Running bond: courses 0.25 high, bricks 0.5 long. Each vertical family draws the
|
||||
// joints of every other course, 0.5 apart; the second is offset half a brick.
|
||||
pl(0.0, (0.0, 0.0), (0.0, 0.25), &[]),
|
||||
pl(90.0, (0.0, 0.0), (0.25, 0.25), &[0.25, -0.25]),
|
||||
pl(90.0, (0.25, 0.0), (0.25, 0.25), &[-0.25, 0.25]),
|
||||
pl(90.0, (0.0, 0.0), (0.0, 0.5), &[0.25, -0.25]),
|
||||
pl(90.0, (0.25, 0.0), (0.0, 0.5), &[-0.25, 0.25]),
|
||||
],
|
||||
},
|
||||
HatchPattern {
|
||||
@@ -201,28 +205,73 @@ pub fn standard_patterns() -> Vec<HatchPattern> {
|
||||
description: "Staircase effect",
|
||||
lines: vec![pl(0.0, (0.0, 0.0), (0.125, 0.125), &[0.125, -0.125]), pl(90.0, (0.125, 0.0), (0.125, 0.125), &[0.125, -0.125])],
|
||||
},
|
||||
HatchPattern {
|
||||
name: "AR-CONC",
|
||||
description: "Random dot and stone pattern",
|
||||
lines: vec![
|
||||
pl(50.0, (0.0, 0.0), (0.4, 0.25), &[0.15, -0.6]),
|
||||
pl(355.0, (0.0, 0.0), (0.27, 0.3), &[0.12, -0.5]),
|
||||
pl(100.0, (0.12, 0.05), (0.35, 0.33), &[0.1, -0.55]),
|
||||
pl(0.0, (0.07, 0.02), (0.21, 0.17), &[0.0, -0.4]),
|
||||
],
|
||||
},
|
||||
HatchPattern {
|
||||
name: "AR-SAND",
|
||||
description: "Random dot pattern",
|
||||
lines: vec![
|
||||
pl(37.5, (0.0, 0.0), (0.112, 0.0912), &[0.0, -0.22, 0.0, -0.14]),
|
||||
pl(7.5, (0.0, 0.0), (0.157, 0.0724), &[0.0, -0.19, 0.0, -0.31]),
|
||||
pl(-32.5, (0.0, 0.0), (0.091, 0.1312), &[0.0, -0.27, 0.0, -0.11]),
|
||||
],
|
||||
},
|
||||
// Drawn at the scale of the pattern CAD programs ship under this name (about 16x
|
||||
// coarser than first drawn here: AR-CONC hatches came out hundreds of times too dense).
|
||||
scaled_pattern(
|
||||
HatchPattern {
|
||||
name: "AR-CONC",
|
||||
description: "Random dot and stone pattern",
|
||||
lines: vec![
|
||||
pl(50.0, (0.0, 0.0), (0.4, 0.25), &[0.15, -0.6]),
|
||||
pl(355.0, (0.0, 0.0), (0.27, 0.3), &[0.12, -0.5]),
|
||||
pl(100.0, (0.12, 0.05), (0.35, 0.33), &[0.1, -0.55]),
|
||||
pl(0.0, (0.07, 0.02), (0.21, 0.17), &[0.0, -0.4]),
|
||||
],
|
||||
},
|
||||
16.0,
|
||||
),
|
||||
// Drawn at the scale of the pattern CAD programs ship under this name (about 16x
|
||||
// coarser than first drawn here: AR-CONC hatches came out hundreds of times too dense).
|
||||
scaled_pattern(
|
||||
HatchPattern {
|
||||
name: "AR-SAND",
|
||||
description: "Random dot pattern",
|
||||
lines: vec![
|
||||
pl(37.5, (0.0, 0.0), (0.112, 0.0912), &[0.0, -0.22, 0.0, -0.14]),
|
||||
pl(7.5, (0.0, 0.0), (0.157, 0.0724), &[0.0, -0.19, 0.0, -0.31]),
|
||||
pl(-32.5, (0.0, 0.0), (0.091, 0.1312), &[0.0, -0.27, 0.0, -0.11]),
|
||||
],
|
||||
},
|
||||
16.0,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn pattern(name: &str) -> Option<HatchPattern> {
|
||||
standard_patterns().into_iter().find(|p| p.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The library pattern `name` as drawn in `d`. In a metric drawing (`MEASUREMENT` 1) every
|
||||
/// length is multiplied by 25.4, as CAD programs use ISO-scaled pattern definitions there (as
|
||||
/// for linetypes, see [`standard_linetypes_for`]): a hatch at scale 1 measures in millimetres
|
||||
/// what it measures in inches in an imperial drawing.
|
||||
pub fn pattern_for(d: &Drawing, name: &str) -> Option<HatchPattern> {
|
||||
let p = pattern(name)?;
|
||||
Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p })
|
||||
}
|
||||
|
||||
/// `p` with every length (origins, offsets, dashes) multiplied by `k`.
|
||||
fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern {
|
||||
for l in &mut p.lines {
|
||||
l.origin = (l.origin.0 * k, l.origin.1 * k);
|
||||
l.delta = (l.delta.0 * k, l.delta.1 * k);
|
||||
for d in &mut l.dashes {
|
||||
*d *= k;
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn metric_drawings_draw_iso_scaled_patterns() {
|
||||
let imp = pattern_for(&Drawing::new_imperial(), "ANSI31").map(|p| p.lines[0].delta.1);
|
||||
let met = pattern_for(&Drawing::new_metric(), "ansi31").map(|p| p.lines[0].delta.1);
|
||||
assert_eq!(imp, Some(0.125));
|
||||
assert!(met.is_some_and(|m| (m - 0.125 * 25.4).abs() < 1e-12), "{met:?}");
|
||||
assert!(pattern_for(&Drawing::new_metric(), "NOPE").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
//! Readers for the user's own linetype (`.lin`) and hatch pattern (`.pat`) files.
|
||||
//!
|
||||
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
|
||||
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
|
||||
//! a pattern), with `;` starting a comment line. CADCraft ships no such file; these read the
|
||||
//! files users bring. Everything here treats the text as hostile: lines, definitions, dashes,
|
||||
//! families and warnings are capped, numbers must be finite and reasonable, and nothing panics.
|
||||
//! Problems become warnings and the definitions that can be read are kept.
|
||||
|
||||
use super::PatternLine;
|
||||
use crate::{DashElement, Linetype};
|
||||
|
||||
/// Longest line read; longer lines are skipped with a warning.
|
||||
pub const MAX_LINE_CHARS: usize = 4096;
|
||||
/// Most definitions (linetypes or patterns) read from one file.
|
||||
pub const MAX_DEFINITIONS: usize = 4096;
|
||||
/// Most elements in one linetype.
|
||||
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
|
||||
/// Most line families in one hatch pattern (what the renderer draws, too).
|
||||
pub const MAX_PATTERN_FAMILIES: usize = 1024;
|
||||
/// Most dashes in one pattern line family (as for a pattern definition read from DXF).
|
||||
pub const MAX_PATTERN_DASHES: usize = 256;
|
||||
/// Largest magnitude accepted for a length, offset or scale.
|
||||
pub const MAX_VALUE: f64 = 1.0e6;
|
||||
/// Longest name or description kept.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
/// Most warnings collected; the rest are counted in a last line.
|
||||
const MAX_WARNINGS: usize = 100;
|
||||
|
||||
/// A hatch pattern read from a user's `.pat` file.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct UserPattern {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub lines: Vec<PatternLine>,
|
||||
}
|
||||
|
||||
/// What a file held: the definitions that could be read, and why anything else was skipped.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Parsed<T> {
|
||||
pub items: Vec<T>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T> Default for Parsed<T> {
|
||||
fn default() -> Self {
|
||||
Parsed { items: Vec::new(), warnings: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Parsed<T> {
|
||||
fn warn(&mut self, line: usize, msg: impl Into<String>) {
|
||||
match self.warnings.len() {
|
||||
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
|
||||
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
|
||||
fn header(rest: &str) -> std::result::Result<(String, String), String> {
|
||||
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("a definition without a name".into());
|
||||
}
|
||||
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
|
||||
return Err("a definition name that is too long or has control characters".into());
|
||||
}
|
||||
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
|
||||
Ok((name.to_string(), desc))
|
||||
}
|
||||
|
||||
/// A finite number within ±[`MAX_VALUE`].
|
||||
fn number(t: &str) -> Option<f64> {
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
|
||||
}
|
||||
|
||||
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
|
||||
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
|
||||
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
|
||||
}
|
||||
|
||||
// ---------- LIN ----------
|
||||
|
||||
/// Read the linetypes of a `.lin` file. Simple linetypes and complex ones with embedded text
|
||||
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
|
||||
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
|
||||
/// Lengths are in drawing units as written: a user's file is never rescaled.
|
||||
pub fn parse_lin(text: &str) -> Parsed<Linetype> {
|
||||
let mut out = Parsed::default();
|
||||
// The definition being read: name, description, header line.
|
||||
let mut pending: Option<(String, String, usize)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
if line.is_empty() || line.starts_with(';') {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
if let Some((name, _, at)) = pending.take() {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
match header(rest) {
|
||||
Ok((name, desc)) => pending = Some((name, desc, no)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((name, description, _)) = pending.take() else {
|
||||
out.warn(no, "pattern line without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
|
||||
break;
|
||||
}
|
||||
if out.items.iter().any(|l: &Linetype| l.name.eq_ignore_ascii_case(&name)) {
|
||||
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
|
||||
continue;
|
||||
}
|
||||
match lin_pattern(line, no, &name, &mut out) {
|
||||
Ok(pattern) => out.items.push(Linetype { name, description, pattern }),
|
||||
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
|
||||
}
|
||||
}
|
||||
if let Some((name, _, at)) = pending {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a pattern line at commas outside `[…]` and `"…"`.
|
||||
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
|
||||
let mut out = Vec::new();
|
||||
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
|
||||
for (i, c) in line.char_indices() {
|
||||
match c {
|
||||
'"' => quoted = !quoted,
|
||||
'[' if !quoted => depth = depth.saturating_add(1),
|
||||
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
|
||||
',' if !quoted && depth == 0 => {
|
||||
out.push(line.get(start..i).unwrap_or("").trim());
|
||||
start = i.saturating_add(1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
}
|
||||
if quoted || depth != 0 {
|
||||
return Err("an unclosed [ or \"".into());
|
||||
}
|
||||
out.push(line.get(start..).unwrap_or("").trim());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The elements of a pattern line `A,dash,gap,[…],…`.
|
||||
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<Linetype>) -> std::result::Result<Vec<DashElement>, String> {
|
||||
let mut fields = lin_fields(line)?;
|
||||
// The alignment field ("A") comes first; a line of plain numbers is read as well.
|
||||
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
|
||||
fields.remove(0);
|
||||
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
|
||||
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
|
||||
}
|
||||
let mut pattern: Vec<DashElement> = Vec::new();
|
||||
for f in fields.into_iter().filter(|f| !f.is_empty()) {
|
||||
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
let Some(inner) = f.strip_prefix('[') else {
|
||||
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
|
||||
pattern.push(DashElement::dash(len));
|
||||
continue;
|
||||
};
|
||||
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
|
||||
match lin_text(inner)? {
|
||||
Some(text) => {
|
||||
// The text sits at the end of the element before it (a zero-length one if none).
|
||||
if pattern.last().is_none_or(|e| e.text.is_some()) {
|
||||
pattern.push(DashElement::dash(0.0));
|
||||
}
|
||||
if let Some(last) = pattern.last_mut() {
|
||||
*last = DashElement { length: last.length, ..text };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let shape = inner.split(',').next().unwrap_or("").trim();
|
||||
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which CADCraft can't read; left out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Err("no dashes".into());
|
||||
}
|
||||
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
|
||||
return Err("every element has zero length".into());
|
||||
}
|
||||
Ok(pattern)
|
||||
}
|
||||
|
||||
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
|
||||
fn lin_text(inner: &str) -> std::result::Result<Option<DashElement>, String> {
|
||||
let inner = inner.trim();
|
||||
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
|
||||
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
|
||||
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
|
||||
return Err("embedded text that is too long or has control characters".into());
|
||||
}
|
||||
let mut parts = rest.split(',').map(str::trim);
|
||||
if !parts.next().unwrap_or("").is_empty() {
|
||||
return Err("text element: expected a comma after the text".into());
|
||||
}
|
||||
let style = parts.next().unwrap_or("").trim();
|
||||
if style.is_empty() || style.contains('=') {
|
||||
return Err("text element: the text style is missing".into());
|
||||
}
|
||||
let mut e = DashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..DashElement::dash(0.0) };
|
||||
for kv in parts.filter(|p| !p.is_empty()) {
|
||||
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
|
||||
match k.trim().to_ascii_uppercase().as_str() {
|
||||
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
|
||||
"X" => e.offset.x = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
|
||||
"Y" => e.offset.y = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
|
||||
// Upright text keeps a rotation relative to the line, like R.
|
||||
k @ ("R" | "A" | "U") => {
|
||||
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
|
||||
e.absolute = k == "A";
|
||||
}
|
||||
other => return Err(format!("text element: unknown option `{other}`")),
|
||||
}
|
||||
}
|
||||
Ok(Some(e))
|
||||
}
|
||||
|
||||
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
|
||||
fn angle(t: &str) -> Option<f64> {
|
||||
let t = t.trim().to_ascii_lowercase();
|
||||
let (num, unit) = match t.char_indices().last() {
|
||||
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
|
||||
_ => (t.as_str(), 'd'),
|
||||
};
|
||||
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
|
||||
Some(match unit {
|
||||
'r' => v,
|
||||
'g' => v * std::f64::consts::PI / 200.0,
|
||||
_ => v.to_radians(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- PAT ----------
|
||||
|
||||
/// Read the hatch patterns of a `.pat` file. Values are used as written (an inch file for inch
|
||||
/// drawings, a millimetre file for metric ones).
|
||||
pub fn parse_pat(text: &str) -> Parsed<UserPattern> {
|
||||
let mut out: Parsed<UserPattern> = Parsed::default();
|
||||
// The pattern being read, its header line, and whether it already failed.
|
||||
let mut cur: Option<(UserPattern, usize, bool)> = None;
|
||||
let finish = |cur: Option<(UserPattern, usize, bool)>, out: &mut Parsed<UserPattern>| {
|
||||
let Some((p, at, failed)) = cur else { return };
|
||||
if failed {
|
||||
return;
|
||||
}
|
||||
if p.lines.is_empty() {
|
||||
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
|
||||
} else if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
|
||||
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
|
||||
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
|
||||
} else {
|
||||
out.items.push(p);
|
||||
}
|
||||
};
|
||||
for (no, line) in lines(text) {
|
||||
// A comment runs to the end of the line.
|
||||
let line = line.split(';').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
finish(cur.take(), &mut out);
|
||||
match header(rest) {
|
||||
Ok((name, description)) => cur = Some((UserPattern { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((p, _, failed)) = cur.as_mut() else {
|
||||
out.warn(no, "line family without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if *failed {
|
||||
continue;
|
||||
}
|
||||
if p.lines.len() >= MAX_PATTERN_FAMILIES {
|
||||
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
|
||||
*failed = true;
|
||||
continue;
|
||||
}
|
||||
match pat_family(line) {
|
||||
Ok(l) => p.lines.push(l),
|
||||
Err(e) => {
|
||||
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
|
||||
*failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
finish(cur, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
|
||||
fn pat_family(line: &str) -> std::result::Result<PatternLine, String> {
|
||||
let mut v = Vec::new();
|
||||
for f in line.split(',') {
|
||||
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
|
||||
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
|
||||
}
|
||||
let f = f.trim();
|
||||
if f.is_empty() && v.len() >= 5 {
|
||||
continue;
|
||||
}
|
||||
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
|
||||
}
|
||||
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
|
||||
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
|
||||
};
|
||||
if dy.abs() < 1e-9 {
|
||||
return Err("a line family with zero spacing (delta-y)".into());
|
||||
}
|
||||
Ok(PatternLine { angle, origin: (x, y), delta: (dx, dy), dashes: v.get(5..).unwrap_or(&[]).to_vec() })
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
//! Plot style tables: how objects print.
|
||||
//!
|
||||
//! A colour-dependent table (`.ctb`) has one plot style per index colour 1..=255: an object
|
||||
//! prints with the style of its colour. A named table (`.stb`) holds styles that layers and
|
||||
//! objects name directly. Each style can replace the object's colour, fade it (screening), turn
|
||||
//! it grey, and replace its linetype and lineweight.
|
||||
//!
|
||||
//! CADCraft's built-in tables are our own definitions, not copies of any vendor's files:
|
||||
//! [`DEFAULT_CTB`] keeps the object's properties, [`MONOCHROME_CTB`] prints everything black
|
||||
//! and [`GRAYSCALE_CTB`] prints every colour as the grey of its luminance; the named
|
||||
//! [`DEFAULT_STB`] offers `Normal`, `Black`, `Screened 50%` and `Thick`, and
|
||||
//! [`MONOCHROME_STB`] prints `Normal` black.
|
||||
//!
|
||||
//! Tables are saved as files in our own JSON format (see `docs/plot-styles.md`):
|
||||
//! [`PlotStyleTable::to_file_text`] and [`PlotStyleTable::from_file_text`].
|
||||
|
||||
use cadcraft_color::Rgb;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Built-in colour-dependent table that prints objects with their own properties.
|
||||
pub const DEFAULT_CTB: &str = "default.ctb";
|
||||
/// Built-in colour-dependent table that prints everything black.
|
||||
pub const MONOCHROME_CTB: &str = "monochrome.ctb";
|
||||
/// Built-in colour-dependent table that prints every colour as a grey of its luminance.
|
||||
pub const GRAYSCALE_CTB: &str = "grayscale.ctb";
|
||||
|
||||
/// Built-in named table: `Normal` (object properties), `Black`, `Screened 50%` and `Thick`.
|
||||
pub const DEFAULT_STB: &str = "default.stb";
|
||||
/// Built-in named table whose `Normal` style prints black.
|
||||
pub const MONOCHROME_STB: &str = "monochrome.stb";
|
||||
|
||||
/// The names of the built-in tables.
|
||||
pub const BUILTIN_PLOT_STYLE_TABLES: &[&str] = &[DEFAULT_CTB, MONOCHROME_CTB, GRAYSCALE_CTB, DEFAULT_STB, MONOCHROME_STB];
|
||||
|
||||
/// The style every named table has, which keeps the object's properties unless redefined.
|
||||
pub const NORMAL_STYLE: &str = "Normal";
|
||||
|
||||
/// Most styles a named table may hold.
|
||||
pub const MAX_NAMED_STYLES: usize = 1024;
|
||||
/// Largest table file we read, in bytes.
|
||||
pub const MAX_TABLE_FILE: usize = 4 << 20;
|
||||
/// Format marker and version of our table files.
|
||||
const FILE_MARKER: &str = "cadcraftPlotStyleTable";
|
||||
const FILE_VERSION: u64 = 1;
|
||||
|
||||
/// Number of styles in a colour-dependent table (one per index colour 1..=255).
|
||||
pub const CTB_STYLES: usize = 255;
|
||||
|
||||
/// Line end style of a plot style.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum EndStyle {
|
||||
#[default]
|
||||
Object,
|
||||
Butt,
|
||||
Square,
|
||||
Round,
|
||||
Diamond,
|
||||
}
|
||||
|
||||
/// Line join style of a plot style.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum JoinStyle {
|
||||
#[default]
|
||||
Object,
|
||||
Miter,
|
||||
Bevel,
|
||||
Round,
|
||||
Diamond,
|
||||
}
|
||||
|
||||
/// Fill style of a plot style (for filled areas).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FillStyle {
|
||||
#[default]
|
||||
Object,
|
||||
Solid,
|
||||
Checkerboard,
|
||||
Crosshatch,
|
||||
Diamonds,
|
||||
HorizontalBars,
|
||||
SlantLeft,
|
||||
SlantRight,
|
||||
SquareDots,
|
||||
VerticalBars,
|
||||
}
|
||||
|
||||
/// One plot style. Serialized fields left at "use the object's" are omitted.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PlotStyle {
|
||||
pub name: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub description: String,
|
||||
/// Output colour (`"#rrggbb"` in JSON); `None` uses the object's colour.
|
||||
#[serde(with = "rgb_hex", skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<Rgb>,
|
||||
/// Print the colour as the grey of its luminance.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub grayscale: bool,
|
||||
/// Ink intensity in percent, 0 (white) to 100 (full colour).
|
||||
#[serde(skip_serializing_if = "is_full")]
|
||||
pub screening: u8,
|
||||
/// Linetype name; `None` uses the object's linetype.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linetype: Option<String>,
|
||||
/// Lineweight in hundredths of a millimetre (0..=211); `None` uses the object's lineweight.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub lineweight: Option<u16>,
|
||||
#[serde(skip_serializing_if = "is_default")]
|
||||
pub end: EndStyle,
|
||||
#[serde(skip_serializing_if = "is_default")]
|
||||
pub join: JoinStyle,
|
||||
#[serde(skip_serializing_if = "is_default")]
|
||||
pub fill: FillStyle,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
fn is_full(s: &u8) -> bool {
|
||||
*s >= 100
|
||||
}
|
||||
fn is_default<T: Default + PartialEq>(v: &T) -> bool {
|
||||
*v == T::default()
|
||||
}
|
||||
|
||||
/// `Option<Rgb>` as `"#rrggbb"` (also read from `[r, g, b]`).
|
||||
mod rgb_hex {
|
||||
use cadcraft_color::Rgb;
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(c: &Option<Rgb>, s: S) -> Result<S::Ok, S::Error> {
|
||||
match c {
|
||||
Some(c) => s.serialize_str(&c.hex()),
|
||||
None => s.serialize_none(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Any {
|
||||
Hex(String),
|
||||
Triple(u8, u8, u8),
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Rgb>, D::Error> {
|
||||
Ok(match Option::<Any>::deserialize(d)? {
|
||||
None => None,
|
||||
Some(Any::Triple(r, g, b)) => Some(Rgb(r, g, b)),
|
||||
Some(Any::Hex(h)) => {
|
||||
Some(Rgb::parse_hex(h.trim().trim_start_matches('#')).ok_or_else(|| serde::de::Error::custom("colour must be \"#rrggbb\""))?)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PlotStyle {
|
||||
fn default() -> Self {
|
||||
PlotStyle::object("")
|
||||
}
|
||||
}
|
||||
|
||||
impl PlotStyle {
|
||||
/// A style that keeps every object property.
|
||||
pub fn object(name: &str) -> PlotStyle {
|
||||
PlotStyle {
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
color: None,
|
||||
grayscale: false,
|
||||
screening: 100,
|
||||
linetype: None,
|
||||
lineweight: None,
|
||||
end: EndStyle::Object,
|
||||
join: JoinStyle::Object,
|
||||
fill: FillStyle::Object,
|
||||
}
|
||||
}
|
||||
/// Whether the style leaves the colour alone.
|
||||
pub fn keeps_color(&self) -> bool {
|
||||
self.color.is_none() && !self.grayscale && self.screening >= 100
|
||||
}
|
||||
/// The printed colour of an object drawn in `rgb`: the style's colour (else `rgb`), turned
|
||||
/// grey when asked, then screened toward white.
|
||||
pub fn apply_color(&self, rgb: Rgb) -> Rgb {
|
||||
let c = self.color.unwrap_or(rgb);
|
||||
let c = if self.grayscale {
|
||||
let g = (c.luma().clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Rgb(g, g, g)
|
||||
} else {
|
||||
c
|
||||
};
|
||||
let s = u16::from(self.screening.min(100));
|
||||
// Screening mixes the ink with the white paper: 100 % = full ink, 0 % = white.
|
||||
let screen = |v: u8| (255 - (255 - u16::from(v)) * s / 100) as u8;
|
||||
Rgb(screen(c.0), screen(c.1), screen(c.2))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a table maps colours or names to styles.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PlotStyleKind {
|
||||
/// Colour-dependent (`.ctb`): style `i - 1` applies to index colour `i`.
|
||||
#[default]
|
||||
ColorDependent,
|
||||
/// Named (`.stb`): styles are picked by name.
|
||||
Named,
|
||||
}
|
||||
|
||||
/// A plot style table.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PlotStyleTable {
|
||||
/// File name, such as `monochrome.ctb`.
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: PlotStyleKind,
|
||||
pub styles: Vec<PlotStyle>,
|
||||
}
|
||||
|
||||
impl PlotStyleTable {
|
||||
/// A colour-dependent table whose style for index colour `i` is `f(i)` (else object
|
||||
/// properties), named `Color_i`.
|
||||
pub fn color_dependent(name: &str, description: &str, f: impl Fn(u8) -> Option<PlotStyle>) -> PlotStyleTable {
|
||||
let styles = (1..=255u8)
|
||||
.map(|i| {
|
||||
let label = format!("Color_{i}");
|
||||
let mut s = f(i).unwrap_or_else(|| PlotStyle::object(&label));
|
||||
s.name = label;
|
||||
s
|
||||
})
|
||||
.collect();
|
||||
PlotStyleTable { name: name.into(), description: description.into(), kind: PlotStyleKind::ColorDependent, styles }
|
||||
}
|
||||
|
||||
/// A named table holding `Normal` (object properties) followed by `styles`.
|
||||
pub fn named(name: &str, description: &str, styles: Vec<PlotStyle>) -> PlotStyleTable {
|
||||
let mut all = vec![PlotStyle::object(NORMAL_STYLE)];
|
||||
all.extend(styles);
|
||||
PlotStyleTable { name: name.into(), description: description.into(), kind: PlotStyleKind::Named, styles: all }.sanitized()
|
||||
}
|
||||
|
||||
/// A built-in table by name (case-insensitive; a `.ctb` extension may be left out).
|
||||
pub fn builtin(name: &str) -> Option<PlotStyleTable> {
|
||||
let n = name.trim().to_ascii_lowercase();
|
||||
let n = if n.ends_with(".ctb") || n.ends_with(".stb") { n } else { format!("{n}.ctb") };
|
||||
let black = Some(Rgb(0, 0, 0));
|
||||
match n.as_str() {
|
||||
DEFAULT_STB => Some(PlotStyleTable::named(
|
||||
DEFAULT_STB,
|
||||
"Normal keeps object properties; Black, Screened 50% and Thick",
|
||||
vec![
|
||||
PlotStyle { name: "Black".into(), color: black, ..PlotStyle::default() },
|
||||
PlotStyle { name: "Screened 50%".into(), screening: 50, ..PlotStyle::default() },
|
||||
PlotStyle { name: "Thick".into(), lineweight: Some(50), ..PlotStyle::default() },
|
||||
],
|
||||
)),
|
||||
MONOCHROME_STB => {
|
||||
let mut t = PlotStyleTable::named(
|
||||
MONOCHROME_STB,
|
||||
"Normal prints black; Screened 50% prints grey",
|
||||
vec![PlotStyle { name: "Screened 50%".into(), color: black, screening: 50, ..PlotStyle::default() }],
|
||||
);
|
||||
if let Some(n) = t.styles.first_mut() {
|
||||
n.color = black;
|
||||
}
|
||||
Some(t)
|
||||
}
|
||||
DEFAULT_CTB => Some(PlotStyleTable::color_dependent(DEFAULT_CTB, "Object colours, linetypes and lineweights", |_| None)),
|
||||
MONOCHROME_CTB => Some(PlotStyleTable::color_dependent(MONOCHROME_CTB, "Every colour prints black", |_| {
|
||||
Some(PlotStyle { color: Some(Rgb(0, 0, 0)), ..PlotStyle::default() })
|
||||
})),
|
||||
GRAYSCALE_CTB => Some(PlotStyleTable::color_dependent(GRAYSCALE_CTB, "Every colour prints as the grey of its luminance", |_| {
|
||||
Some(PlotStyle { grayscale: true, ..PlotStyle::default() })
|
||||
})),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this table is colour-dependent.
|
||||
pub fn is_color_dependent(&self) -> bool {
|
||||
self.kind == PlotStyleKind::ColorDependent
|
||||
}
|
||||
|
||||
/// The style for index colour `aci` (1..=255) of a colour-dependent table.
|
||||
pub fn by_color(&self, aci: u8) -> Option<&PlotStyle> {
|
||||
if !self.is_color_dependent() || aci == 0 {
|
||||
return None;
|
||||
}
|
||||
self.styles.get(usize::from(aci) - 1)
|
||||
}
|
||||
|
||||
/// The style called `name` (case-insensitive).
|
||||
pub fn by_name(&self, name: &str) -> Option<&PlotStyle> {
|
||||
self.styles.iter().find(|s| s.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The table with hostile or inconsistent values fixed: screening at most 100 %,
|
||||
/// lineweights at most 2.11 mm, names at most 255 characters; a colour-dependent table has
|
||||
/// exactly 255 styles named `Color_1`..`Color_255`; a named table has unique, non-empty
|
||||
/// style names (at most [`MAX_NAMED_STYLES`]) starting with `Normal`.
|
||||
pub fn sanitized(mut self) -> PlotStyleTable {
|
||||
let cut = |s: &str| s.chars().take(255).collect::<String>();
|
||||
self.name = cut(self.name.trim());
|
||||
self.description = cut(&self.description);
|
||||
for s in &mut self.styles {
|
||||
s.name = cut(s.name.trim());
|
||||
s.description = cut(&s.description);
|
||||
s.screening = s.screening.min(100);
|
||||
s.lineweight = s.lineweight.map(|w| w.min(211));
|
||||
s.linetype = s.linetype.take().map(|l| cut(l.trim())).filter(|l| !l.is_empty());
|
||||
}
|
||||
match self.kind {
|
||||
PlotStyleKind::ColorDependent => {
|
||||
self.styles.truncate(CTB_STYLES);
|
||||
while self.styles.len() < CTB_STYLES {
|
||||
self.styles.push(PlotStyle::object(""));
|
||||
}
|
||||
for (i, s) in self.styles.iter_mut().enumerate() {
|
||||
s.name = format!("Color_{}", i + 1);
|
||||
}
|
||||
}
|
||||
PlotStyleKind::Named => {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.styles.retain(|s| !s.name.is_empty() && seen.insert(s.name.to_lowercase()));
|
||||
self.styles.truncate(MAX_NAMED_STYLES);
|
||||
match self.styles.iter().position(|s| s.name.eq_ignore_ascii_case(NORMAL_STYLE)) {
|
||||
Some(0) => {}
|
||||
Some(i) => {
|
||||
let n = self.styles.remove(i);
|
||||
self.styles.insert(0, n);
|
||||
}
|
||||
None => {
|
||||
self.styles.insert(0, PlotStyle::object(NORMAL_STYLE));
|
||||
self.styles.truncate(MAX_NAMED_STYLES);
|
||||
}
|
||||
}
|
||||
if let Some(n) = self.styles.first_mut() {
|
||||
n.name = NORMAL_STYLE.into();
|
||||
}
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The table as a file in our own format: pretty-printed JSON with a format marker.
|
||||
pub fn to_file_text(&self) -> String {
|
||||
let mut v = serde_json::to_value(self).unwrap_or(serde_json::Value::Null);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert(FILE_MARKER.into(), FILE_VERSION.into());
|
||||
}
|
||||
serde_json::to_string_pretty(&v).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Read a table file written by [`PlotStyleTable::to_file_text`] (sanitized).
|
||||
pub fn from_file_text(text: &str) -> std::result::Result<PlotStyleTable, String> {
|
||||
if text.len() > MAX_TABLE_FILE {
|
||||
return Err("the plot style table file is too large".into());
|
||||
}
|
||||
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("not a CADCraft plot style table: {e}"))?;
|
||||
match v.get(FILE_MARKER).and_then(serde_json::Value::as_u64) {
|
||||
Some(FILE_VERSION) => {}
|
||||
Some(n) => return Err(format!("plot style table format version {n} is newer than this CADCraft reads")),
|
||||
None => return Err(format!("not a CADCraft plot style table (no `{FILE_MARKER}`)")),
|
||||
}
|
||||
let t: PlotStyleTable = serde_json::from_value(v).map_err(|e| format!("bad plot style table: {e}"))?;
|
||||
Ok(t.sanitized())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a page setup's table name means "no plot style table".
|
||||
pub fn no_plot_style_table(name: &str) -> bool {
|
||||
let n = name.trim();
|
||||
n.is_empty() || n.eq_ignore_ascii_case("none")
|
||||
}
|
||||
|
||||
/// The plot style table a page setup names, if it is one we know: the drawing's own tables
|
||||
/// first, then the built-in ones. `None` for no table (empty or "None") and for tables we don't
|
||||
/// have.
|
||||
pub fn plot_style_table(d: &crate::Drawing, name: &str) -> Option<PlotStyleTable> {
|
||||
if no_plot_style_table(name) {
|
||||
return None;
|
||||
}
|
||||
let n = name.trim();
|
||||
d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned().or_else(|| PlotStyleTable::builtin(n))
|
||||
}
|
||||
|
||||
/// The names of every table a drawing can use: its own, then the built-in ones it doesn't
|
||||
/// shadow.
|
||||
pub fn plot_style_table_names(d: &crate::Drawing) -> Vec<String> {
|
||||
let mut v: Vec<String> = d.plot_style_tables.iter().map(|t| t.name.clone()).collect();
|
||||
for b in BUILTIN_PLOT_STYLE_TABLES {
|
||||
if !v.iter().any(|n| n.eq_ignore_ascii_case(b)) {
|
||||
v.push((*b).to_string());
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn builtins_are_complete_color_dependent_tables() {
|
||||
for n in [DEFAULT_CTB, MONOCHROME_CTB, GRAYSCALE_CTB] {
|
||||
let t = PlotStyleTable::builtin(n).unwrap();
|
||||
assert_eq!(t.name, n);
|
||||
assert!(t.is_color_dependent());
|
||||
assert_eq!(t.styles.len(), CTB_STYLES);
|
||||
assert_eq!(t.by_color(1).unwrap().name, "Color_1");
|
||||
assert_eq!(t.by_color(255).unwrap().name, "Color_255");
|
||||
assert!(t.by_color(0).is_none());
|
||||
}
|
||||
assert!(PlotStyleTable::builtin("Monochrome").is_some());
|
||||
assert!(PlotStyleTable::builtin("nope.ctb").is_none());
|
||||
assert!(no_plot_style_table("") && no_plot_style_table(" None ") && !no_plot_style_table("monochrome.ctb"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_transforms() {
|
||||
let mono = PlotStyleTable::builtin(MONOCHROME_CTB).unwrap();
|
||||
assert_eq!(mono.by_color(1).unwrap().apply_color(Rgb(255, 0, 0)), Rgb(0, 0, 0));
|
||||
let gray = PlotStyleTable::builtin(GRAYSCALE_CTB).unwrap();
|
||||
let g = gray.by_color(3).unwrap().apply_color(Rgb(0, 255, 0));
|
||||
assert!(g.0 == g.1 && g.1 == g.2 && g.0 > 128, "{g:?}");
|
||||
let half = PlotStyle { color: Some(Rgb(0, 0, 0)), screening: 50, ..PlotStyle::default() };
|
||||
assert_eq!(half.apply_color(Rgb(9, 9, 9)), Rgb(128, 128, 128));
|
||||
let none = PlotStyle { screening: 0, ..PlotStyle::default() };
|
||||
assert_eq!(none.apply_color(Rgb(10, 20, 30)), Rgb(255, 255, 255));
|
||||
assert!(PlotStyle::default().keeps_color() && !half.keeps_color());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_builtins_and_sanitizing() {
|
||||
let t = PlotStyleTable::builtin("default.stb").unwrap();
|
||||
assert!(!t.is_color_dependent());
|
||||
assert_eq!(t.styles.first().unwrap().name, NORMAL_STYLE);
|
||||
assert!(t.by_name("black").is_some() && t.by_color(1).is_none());
|
||||
assert_eq!(PlotStyleTable::builtin(MONOCHROME_STB).unwrap().by_name("Normal").unwrap().color, Some(Rgb(0, 0, 0)));
|
||||
// Hostile values are clamped; names fixed.
|
||||
let bad = PlotStyleTable {
|
||||
name: " x.stb ".into(),
|
||||
kind: PlotStyleKind::Named,
|
||||
styles: vec![
|
||||
PlotStyle { name: "A".into(), screening: 250, lineweight: Some(9999), ..PlotStyle::default() },
|
||||
PlotStyle { name: "a".into(), ..PlotStyle::default() },
|
||||
PlotStyle { name: " ".into(), ..PlotStyle::default() },
|
||||
],
|
||||
..PlotStyleTable::default()
|
||||
}
|
||||
.sanitized();
|
||||
assert_eq!(bad.name, "x.stb");
|
||||
assert_eq!(bad.styles.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Normal", "A"]);
|
||||
assert_eq!((bad.styles[1].screening, bad.styles[1].lineweight), (100, Some(211)));
|
||||
let short = PlotStyleTable { styles: vec![PlotStyle::object("zz")], ..PlotStyleTable::default() }.sanitized();
|
||||
assert_eq!(short.styles.len(), CTB_STYLES);
|
||||
assert_eq!(short.styles[0].name, "Color_1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_format_round_trip() {
|
||||
for name in BUILTIN_PLOT_STYLE_TABLES {
|
||||
let t = PlotStyleTable::builtin(name).unwrap();
|
||||
let text = t.to_file_text();
|
||||
assert!(text.contains("\"cadcraftPlotStyleTable\": 1"));
|
||||
assert_eq!(PlotStyleTable::from_file_text(&text).unwrap(), t, "{name}");
|
||||
}
|
||||
let mono = PlotStyleTable::builtin(MONOCHROME_CTB).unwrap().to_file_text();
|
||||
assert!(mono.contains("\"color\": \"#000000\""), "colours as hex");
|
||||
assert!(!mono.contains("screening"), "defaults are left out");
|
||||
assert!(PlotStyleTable::from_file_text("{}").is_err());
|
||||
assert!(PlotStyleTable::from_file_text("{\"cadcraftPlotStyleTable\": 9}").is_err());
|
||||
assert!(PlotStyleTable::from_file_text("not json").is_err());
|
||||
let rgb: PlotStyle = serde_json::from_value(serde_json::json!({"name": "x", "color": [1, 2, 3]})).unwrap();
|
||||
assert_eq!(rgb.color, Some(Rgb(1, 2, 3)));
|
||||
assert!(serde_json::from_value::<PlotStyle>(serde_json::json!({"color": "#zz0000"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_tables_shadow_builtins() {
|
||||
let mut d = crate::Drawing::new_metric();
|
||||
assert!(plot_style_table(&d, "monochrome.ctb").unwrap().by_color(1).unwrap().color.is_some());
|
||||
d.plot_style_tables.push(PlotStyleTable::color_dependent("Monochrome.ctb", "", |_| None));
|
||||
assert!(plot_style_table(&d, "monochrome.ctb").unwrap().by_color(1).unwrap().color.is_none());
|
||||
let names = plot_style_table_names(&d);
|
||||
assert_eq!(names.iter().filter(|n| n.eq_ignore_ascii_case("monochrome.ctb")).count(), 1);
|
||||
assert!(names.contains(&"default.stb".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_round_trip_with_defaults() {
|
||||
let t = PlotStyleTable::builtin(GRAYSCALE_CTB).unwrap();
|
||||
let back: PlotStyleTable = serde_json::from_value(serde_json::to_value(&t).unwrap()).unwrap();
|
||||
assert_eq!(back, t);
|
||||
let s: PlotStyle = serde_json::from_value(serde_json::json!({"name": "Thick", "lineweight": 50})).unwrap();
|
||||
assert_eq!((s.screening, s.lineweight, s.color), (100, Some(50), None));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
//! Plotter configurations: output devices with their paper sizes and printable areas.
|
||||
//!
|
||||
//! A configuration is a file in our own format (`*.plotter.json`, UTF-8 JSON with a format
|
||||
//! marker, see `docs/plotters.md`). It names the output (PDF, PNG or SVG), the paper sizes the
|
||||
//! device offers (each with the margins that bound its printable area), the raster resolution
|
||||
//! and the default orientation. Binary `.pc3` files are not read.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// File-name suffix of plotter configuration files.
|
||||
pub const PLOTTER_FILE_EXT: &str = ".plotter.json";
|
||||
/// Largest plotter configuration file read (bytes).
|
||||
pub const MAX_PLOTTER_FILE: usize = 1 << 20;
|
||||
/// Most paper sizes one device keeps.
|
||||
pub const MAX_DEVICE_PAPERS: usize = 512;
|
||||
/// Longest device or paper name (characters).
|
||||
pub const MAX_PLOTTER_NAME: usize = 100;
|
||||
/// Largest paper side (mm), as for page setups.
|
||||
pub const MAX_PAPER_MM: f64 = 5080.0;
|
||||
|
||||
const FILE_MARKER: &str = "cadcraftPlotter";
|
||||
const FILE_VERSION: u64 = 1;
|
||||
|
||||
/// What a device writes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PlotOutput {
|
||||
#[default]
|
||||
Pdf,
|
||||
Png,
|
||||
Svg,
|
||||
}
|
||||
|
||||
impl PlotOutput {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
PlotOutput::Pdf => "pdf",
|
||||
PlotOutput::Png => "png",
|
||||
PlotOutput::Svg => "svg",
|
||||
}
|
||||
}
|
||||
/// Parse `pdf`, `png` or `svg` (any case).
|
||||
pub fn parse(s: &str) -> Option<PlotOutput> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"pdf" => Some(PlotOutput::Pdf),
|
||||
"png" => Some(PlotOutput::Png),
|
||||
"svg" => Some(PlotOutput::Svg),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Default sheet orientation of a device.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Orientation {
|
||||
Portrait,
|
||||
#[default]
|
||||
Landscape,
|
||||
}
|
||||
|
||||
/// A paper size a device offers: size in millimetres (portrait: width <= height after
|
||||
/// sanitizing) and margins (left, bottom, right, top; mm) bounding the printable area.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DevicePaper {
|
||||
pub name: String,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
pub margins: [f64; 4],
|
||||
}
|
||||
|
||||
impl Default for DevicePaper {
|
||||
fn default() -> Self {
|
||||
DevicePaper { name: String::new(), width: 210.0, height: 297.0, margins: [0.0; 4] }
|
||||
}
|
||||
}
|
||||
|
||||
impl DevicePaper {
|
||||
/// The paper with hostile values fixed: finite sizes within 1..=[`MAX_PAPER_MM`] mm
|
||||
/// (portrait), margins 0..=1000 mm that leave a printable area (else none), a name of at
|
||||
/// most [`MAX_PLOTTER_NAME`] characters.
|
||||
pub fn sanitized(mut self) -> DevicePaper {
|
||||
let side = |v: f64| if v.is_finite() { v.clamp(1.0, MAX_PAPER_MM) } else { 1.0 };
|
||||
let (w, h) = (side(self.width), side(self.height));
|
||||
self.width = w.min(h);
|
||||
self.height = w.max(h);
|
||||
for m in &mut self.margins {
|
||||
*m = if m.is_finite() { m.clamp(0.0, 1000.0) } else { 0.0 };
|
||||
}
|
||||
let [l, b, r, t] = self.margins;
|
||||
if l + r >= self.width || b + t >= self.height {
|
||||
self.margins = [0.0; 4];
|
||||
}
|
||||
self.name = clean_name(&self.name);
|
||||
if self.name.is_empty() {
|
||||
self.name = format!("User ({:.2} x {:.2} MM)", self.width, self.height);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A plotter configuration.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PlotterConfig {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub output: PlotOutput,
|
||||
/// Raster resolution (dots per inch) for PNG output.
|
||||
pub resolution: u32,
|
||||
pub orientation: Orientation,
|
||||
/// Name of the paper chosen when a page setup switches to this device.
|
||||
pub default_paper: String,
|
||||
pub papers: Vec<DevicePaper>,
|
||||
}
|
||||
|
||||
impl Default for PlotterConfig {
|
||||
fn default() -> Self {
|
||||
PlotterConfig {
|
||||
name: String::new(),
|
||||
description: String::new(),
|
||||
output: PlotOutput::Pdf,
|
||||
resolution: 300,
|
||||
orientation: Orientation::Landscape,
|
||||
default_paper: String::new(),
|
||||
papers: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A name trimmed, without control characters, at most [`MAX_PLOTTER_NAME`] characters.
|
||||
fn clean_name(s: &str) -> String {
|
||||
s.trim().chars().filter(|c| !c.is_control()).take(MAX_PLOTTER_NAME).collect::<String>().trim().to_string()
|
||||
}
|
||||
|
||||
/// Names compare ignoring case, spaces, `_` and `-`.
|
||||
fn key(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_whitespace() && *c != '_' && *c != '-').collect::<String>().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
impl PlotterConfig {
|
||||
/// The configuration with hostile values fixed: a clean name and description, resolution
|
||||
/// 50..=2400 dpi, at most [`MAX_DEVICE_PAPERS`] sanitized papers with unique names, and a
|
||||
/// default paper the device has (the first one when it names none of them).
|
||||
pub fn sanitized(mut self) -> PlotterConfig {
|
||||
self.name = clean_name(&self.name);
|
||||
self.description = self.description.chars().filter(|c| !c.is_control() || *c == '\n').take(1000).collect();
|
||||
self.resolution = self.resolution.clamp(50, 2400);
|
||||
let mut papers: Vec<DevicePaper> = Vec::new();
|
||||
for p in std::mem::take(&mut self.papers).into_iter().take(MAX_DEVICE_PAPERS) {
|
||||
let p = p.sanitized();
|
||||
if !papers.iter().any(|q| key(&q.name) == key(&p.name)) {
|
||||
papers.push(p);
|
||||
}
|
||||
}
|
||||
self.papers = papers;
|
||||
self.default_paper = match self.paper(&self.default_paper) {
|
||||
Some(p) => p.name.clone(),
|
||||
None => self.papers.first().map(|p| p.name.clone()).unwrap_or_default(),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
/// The paper called `name` (ignoring case, spaces, `_` and `-`).
|
||||
pub fn paper(&self, name: &str) -> Option<&DevicePaper> {
|
||||
let k = key(name);
|
||||
if k.is_empty() {
|
||||
return None;
|
||||
}
|
||||
self.papers.iter().find(|p| key(&p.name) == k)
|
||||
}
|
||||
|
||||
/// The paper a page setup gets when it switches to this device.
|
||||
pub fn default_paper(&self) -> Option<&DevicePaper> {
|
||||
self.paper(&self.default_paper).or_else(|| self.papers.first())
|
||||
}
|
||||
|
||||
/// The configuration (sanitized) as a file in our own format: pretty-printed JSON with a
|
||||
/// format marker.
|
||||
pub fn to_file_text(&self) -> String {
|
||||
let mut v = serde_json::to_value(self.clone().sanitized()).unwrap_or(serde_json::Value::Null);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert(FILE_MARKER.into(), FILE_VERSION.into());
|
||||
}
|
||||
serde_json::to_string_pretty(&v).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Read a file written by [`PlotterConfig::to_file_text`] (sanitized; a name is required).
|
||||
pub fn from_file_text(text: &str) -> std::result::Result<PlotterConfig, String> {
|
||||
if text.len() > MAX_PLOTTER_FILE {
|
||||
return Err("the plotter configuration file is too large".into());
|
||||
}
|
||||
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("not a CADCraft plotter configuration: {e}"))?;
|
||||
match v.get(FILE_MARKER).and_then(serde_json::Value::as_u64) {
|
||||
Some(FILE_VERSION) => {}
|
||||
Some(n) => return Err(format!("plotter configuration format version {n} is newer than this CADCraft reads")),
|
||||
None => return Err(format!("not a CADCraft plotter configuration (no `{FILE_MARKER}`)")),
|
||||
}
|
||||
let c: PlotterConfig = serde_json::from_value(v).map_err(|e| format!("bad plotter configuration: {e}"))?;
|
||||
let c = c.sanitized();
|
||||
if c.name.is_empty() {
|
||||
return Err("the plotter configuration has no name".into());
|
||||
}
|
||||
Ok(c)
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name a device is kept under: its name with characters that can't appear in file
|
||||
/// names replaced by `_`, plus [`PLOTTER_FILE_EXT`]. `None` for an empty name.
|
||||
pub fn plotter_file_name(name: &str) -> Option<String> {
|
||||
let base: String =
|
||||
clean_name(name).chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '(' | ')' | '+' | ',') { c } else { '_' }).collect();
|
||||
let base = base.trim().trim_start_matches('.');
|
||||
(!base.is_empty()).then(|| format!("{base}{PLOTTER_FILE_EXT}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trip_and_hostile_values() {
|
||||
let c = PlotterConfig {
|
||||
name: "Office A3".into(),
|
||||
output: PlotOutput::Png,
|
||||
resolution: 1_000_000,
|
||||
default_paper: "nope".into(),
|
||||
papers: vec![
|
||||
DevicePaper { name: "A3 borderless".into(), width: 420.0, height: 297.0, margins: [0.0; 4] },
|
||||
DevicePaper { name: "a3-BORDERLESS".into(), ..DevicePaper::default() },
|
||||
DevicePaper { name: String::new(), width: f64::NAN, height: 1e12, margins: [f64::INFINITY, 9e9, -1.0, 5.0] },
|
||||
],
|
||||
..PlotterConfig::default()
|
||||
};
|
||||
let back = PlotterConfig::from_file_text(&c.to_file_text()).unwrap();
|
||||
assert_eq!(back.resolution, 2400);
|
||||
assert_eq!(back.papers.len(), 2, "duplicate names dropped");
|
||||
assert_eq!((back.papers[0].width, back.papers[0].height), (297.0, 420.0), "portrait");
|
||||
assert_eq!(back.default_paper, "A3 borderless");
|
||||
assert_eq!(back.papers[1].width, 1.0);
|
||||
assert_eq!(back.papers[1].height, MAX_PAPER_MM);
|
||||
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
|
||||
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
|
||||
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
|
||||
assert!(back.paper("a3 BORDERLESS").is_some());
|
||||
assert!(PlotterConfig::from_file_text("{}").is_err());
|
||||
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 1}"#).is_err(), "needs a name");
|
||||
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 9, "name": "x"}"#).is_err());
|
||||
assert_eq!(plotter_file_name("../a/b:c").as_deref(), Some("___a_b_c.plotter.json"));
|
||||
assert_eq!(plotter_file_name(" "), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! In-place editing of a block reference (REFEDIT / REFSET / REFCLOSE): the state kept with the
|
||||
//! drawing while it lasts.
|
||||
//!
|
||||
//! The reference being edited is hidden and the block's objects stand in the drawing as ordinary
|
||||
//! objects (the *working set*, transformed to where the reference shows them), the rest of the
|
||||
//! block as faded copies (*ghosts*) that cannot be edited. REFCLOSE writes the working set back
|
||||
//! into the block definition. The state lives in the [`Drawing`] itself, so undo and redo move
|
||||
//! the working copies and the state together and can never leave one without the other.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use cadcraft_geom::Mat3;
|
||||
|
||||
use crate::{Drawing, Entity, Handle, Space};
|
||||
|
||||
/// One object of the working set.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WorkItem {
|
||||
/// The object in the drawing (a copy of the block object, or a drawing object added to the set).
|
||||
pub copy: Handle,
|
||||
/// The block object it was copied from; `None` for an object added from the drawing.
|
||||
pub source: Option<Handle>,
|
||||
}
|
||||
|
||||
/// An active in-place edit of a block reference. Never written to a file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RefEdit {
|
||||
/// The block being edited.
|
||||
pub block: String,
|
||||
/// The reference that was picked (hidden while editing).
|
||||
pub insert: Handle,
|
||||
/// Whether the reference was visible before it was hidden.
|
||||
pub insert_was_visible: bool,
|
||||
/// The space the reference is in.
|
||||
pub space: Space,
|
||||
/// Block coordinates to drawing coordinates, through the picked reference.
|
||||
pub to_world: Mat3,
|
||||
/// The working set.
|
||||
pub items: Vec<WorkItem>,
|
||||
/// The rest of the block as faded copies: (copy, block object).
|
||||
pub ghosts: Vec<(Handle, Handle)>,
|
||||
/// Block objects taken out of the working set with their edits (block coordinates, the block
|
||||
/// object's handle).
|
||||
pub released: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl RefEdit {
|
||||
/// Whether `h` is a working set object.
|
||||
pub fn is_working(&self, h: Handle) -> bool {
|
||||
self.items.iter().any(|i| i.copy == h)
|
||||
}
|
||||
/// Whether `h` is something the edit manages (working set, ghost, the hidden reference).
|
||||
pub fn owns(&self, h: Handle) -> bool {
|
||||
h == self.insert || self.is_working(h) || self.ghosts.iter().any(|(g, _)| *g == h)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drawing {
|
||||
/// The drawing as REFCLOSE Discard would leave it: the working copies and ghosts gone, the
|
||||
/// reference shown, the block untouched. Borrowed when no edit is active. Files are written
|
||||
/// from this, so a saved or autosaved drawing never holds half an edit.
|
||||
pub fn committed(&self) -> Cow<'_, Drawing> {
|
||||
let Some(r) = &self.refedit else { return Cow::Borrowed(self) };
|
||||
let mut d = self.clone();
|
||||
d.end_refedit_discard(r);
|
||||
Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// Remove the edit's working copies and ghosts, show the reference again and clear the state.
|
||||
pub fn end_refedit_discard(&mut self, r: &RefEdit) {
|
||||
for i in &r.items {
|
||||
if i.source.is_some() {
|
||||
self.remove_entity(i.copy);
|
||||
}
|
||||
}
|
||||
for (g, _) in &r.ghosts {
|
||||
self.remove_entity(*g);
|
||||
}
|
||||
let vis = r.insert_was_visible;
|
||||
let _ = self.modify_entity(r.insert, |e| e.common.visible = vis);
|
||||
self.refedit = None;
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,70 @@ impl EntityStore {
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
/// Move `h` directly above (`above`) or under `anchor` in the draw order. False (and nothing
|
||||
/// moves) when either is absent or they are the same object.
|
||||
pub fn move_next_to(&mut self, h: Handle, anchor: Handle, above: bool) -> bool {
|
||||
if h == anchor || !self.contains(anchor) {
|
||||
return false;
|
||||
}
|
||||
let Some(e) = self.remove(h) else { return false };
|
||||
let at = self.chunk_id(anchor).and_then(|id| Some((id, self.chunk_pos(id)?)));
|
||||
let Some((id, pos)) = at else {
|
||||
// Unreachable in practice (the anchor was present); keep the object on top.
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
return false;
|
||||
};
|
||||
let Some(c) = self.chunks.get_mut(pos) else {
|
||||
// Unreachable in practice too; never lose the object.
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
return false;
|
||||
};
|
||||
let chunk = Arc::make_mut(c);
|
||||
let i = chunk.items.iter().position(|x| x.handle == anchor).unwrap_or(chunk.items.len());
|
||||
let i = if above { (i + 1).min(chunk.items.len()) } else { i };
|
||||
chunk.items.insert(i, e);
|
||||
let split = chunk.items.len() > 2 * CHUNK_MAX;
|
||||
self.set_index(h, Some(id));
|
||||
self.len += 1;
|
||||
if split {
|
||||
self.split_chunk(pos);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Split an oversized chunk in two, keeping the order.
|
||||
fn split_chunk(&mut self, pos: usize) {
|
||||
let mut fresh = self.new_chunk();
|
||||
let Some(c) = self.chunks.get_mut(pos) else { return };
|
||||
let chunk = Arc::make_mut(c);
|
||||
let tail = chunk.items.split_off(chunk.items.len() / 2);
|
||||
let new = Arc::make_mut(&mut fresh);
|
||||
new.items = tail;
|
||||
let (id, moved): (u32, Vec<Handle>) = (new.id, new.items.iter().map(|e| e.handle).collect());
|
||||
self.chunks.insert(pos + 1, fresh);
|
||||
for h in moved {
|
||||
self.set_index(h, Some(id));
|
||||
}
|
||||
}
|
||||
/// Reorder the whole store by a key (stable: equal keys keep their order).
|
||||
pub fn sort_by_key<K: Ord>(&mut self, mut key: impl FnMut(&Entity) -> K) {
|
||||
let mut items: Vec<Arc<Entity>> = self.iter().cloned().collect();
|
||||
items.sort_by_cached_key(|e| key(e));
|
||||
*self = EntityStore::default();
|
||||
for e in items {
|
||||
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
|
||||
if needs_new {
|
||||
let c = self.new_chunk();
|
||||
self.chunks.push(c);
|
||||
}
|
||||
let h = e.handle;
|
||||
let Some(last) = self.chunks.last_mut() else { return };
|
||||
let chunk = Arc::make_mut(last);
|
||||
chunk.items.push(e);
|
||||
let id = chunk.id;
|
||||
self.set_index(h, Some(id));
|
||||
self.len += 1;
|
||||
}
|
||||
}
|
||||
/// True when `other` shares every chunk with `self` (same draw order, same entities). Holding
|
||||
/// a clone of a store makes this exact: any edit to the original copies the touched chunk.
|
||||
pub fn same_as(&self, other: &EntityStore) -> bool {
|
||||
@@ -256,4 +320,48 @@ mod tests {
|
||||
assert_eq!(s.iter().next().map(|e| e.handle), Some(Handle(5)));
|
||||
assert_eq!(s.len(), 5);
|
||||
}
|
||||
|
||||
fn order(s: &EntityStore) -> Vec<u64> {
|
||||
s.iter().map(|e| e.handle.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_next_to_and_sort() {
|
||||
let mut s = EntityStore::new();
|
||||
for h in 1..=5 {
|
||||
s.push(ent(h));
|
||||
}
|
||||
assert!(s.move_next_to(Handle(1), Handle(3), true));
|
||||
assert_eq!(order(&s), [2, 3, 1, 4, 5]);
|
||||
assert!(s.move_next_to(Handle(5), Handle(2), false));
|
||||
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
|
||||
assert!(!s.move_next_to(Handle(5), Handle(5), true));
|
||||
assert!(!s.move_next_to(Handle(5), Handle(99), true));
|
||||
assert!(!s.move_next_to(Handle(99), Handle(5), true));
|
||||
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
|
||||
assert_eq!(s.len(), 5);
|
||||
s.sort_by_key(|e| e.handle.0 % 2);
|
||||
assert_eq!(order(&s), [2, 4, 5, 3, 1]);
|
||||
assert!(s.get(Handle(3)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_next_to_splits_big_chunks() {
|
||||
let mut s = EntityStore::new();
|
||||
for h in 1..=3000 {
|
||||
s.push(ent(h));
|
||||
}
|
||||
// Pile everything into the first chunk, under handle 1.
|
||||
for h in 1500..=3000 {
|
||||
assert!(s.move_next_to(Handle(h), Handle(1), true));
|
||||
}
|
||||
assert_eq!(s.len(), 3000);
|
||||
assert!(s.chunks.iter().all(|c| c.items.len() <= 2 * CHUNK_MAX));
|
||||
let o = order(&s);
|
||||
assert_eq!(o.first(), Some(&1));
|
||||
assert_eq!(o.get(1), Some(&3000));
|
||||
for h in 1..=3000 {
|
||||
assert_eq!(s.get(Handle(h)).map(|e| e.handle.0), Some(h));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+330
-26
@@ -177,6 +177,11 @@ pub struct DimStyle {
|
||||
pub dim_line_color: Color,
|
||||
pub ext_line_color: Color,
|
||||
pub text_color: Color,
|
||||
/// DIMTFILL, the background of the text: 0 none, 1 the drawing's background color,
|
||||
/// 2 `text_fill_color`.
|
||||
pub text_fill: u8,
|
||||
/// DIMTFILLCLR: the text background color when `text_fill` is 2.
|
||||
pub text_fill_color: Color,
|
||||
pub text_style: String,
|
||||
/// DIMPOST prefix/suffix "<>" template.
|
||||
pub post: String,
|
||||
@@ -230,6 +235,49 @@ pub struct DimStyle {
|
||||
/// DIMSE1 / DIMSE2 suppress extension lines.
|
||||
pub suppress_ext1: bool,
|
||||
pub suppress_ext2: bool,
|
||||
/// DIMSD1 / DIMSD2 suppress the first / second half of the dimension line and its arrow.
|
||||
pub suppress_dim1: bool,
|
||||
pub suppress_dim2: bool,
|
||||
/// DIMATFIT, what moves outside the extension lines when text and arrows don't both fit:
|
||||
/// 0 both, 1 arrows first, 2 text first, 3 whichever fits best.
|
||||
pub fit: u8,
|
||||
/// DIMTIX: text always between the extension lines.
|
||||
pub text_inside: bool,
|
||||
/// DIMSOXD: suppress arrowheads that don't fit between the extension lines.
|
||||
pub suppress_outside_arrows: bool,
|
||||
/// DIMTOFL: a dimension line between the extension lines even when the arrows are outside
|
||||
/// (through the circle for radius and diameter dimensions with the text outside).
|
||||
pub force_line_inside: bool,
|
||||
/// DIMTMOVE, when the text is moved away from its default place: 0 the dimension line
|
||||
/// moves with it, 1 a leader joins them, 2 neither.
|
||||
pub text_move: u8,
|
||||
/// DIMTVP: text above (+) or below (-) the dimension line by this many text heights when
|
||||
/// DIMTAD is 0.
|
||||
pub text_vertical_pos: f64,
|
||||
/// DIMTOLJ, vertical place of tolerance values next to the measurement: 0 bottom,
|
||||
/// 1 middle, 2 top.
|
||||
pub tol_just: u8,
|
||||
/// DIMAZIN zero suppression of angular dimensions: 1 leading, 2 trailing.
|
||||
pub angular_zero_suppression: u8,
|
||||
/// DIMARCSYM, arc length symbol: 0 before the text, 1 above it, 2 none.
|
||||
pub arc_symbol: u8,
|
||||
/// DIMLDRBLK leader arrowhead ("" = closed filled).
|
||||
pub leader_arrow_block: String,
|
||||
/// DIMLTYPE / DIMLTEX1 / DIMLTEX2: linetypes of the dimension line and the extension
|
||||
/// lines ("" = ByBlock).
|
||||
pub dim_linetype: String,
|
||||
pub ext_linetype1: String,
|
||||
pub ext_linetype2: String,
|
||||
/// DIMLWD / DIMLWE: lineweights of the dimension line and the extension lines in 1/100 mm
|
||||
/// (-1 ByLayer, -2 ByBlock, -3 default).
|
||||
pub dim_lineweight: i16,
|
||||
pub ext_lineweight: i16,
|
||||
/// DIMFXLON / DIMFXL: extension lines of a fixed length, measured from the dimension line
|
||||
/// toward the origin.
|
||||
pub fixed_ext: bool,
|
||||
pub fixed_ext_length: f64,
|
||||
/// DIMJOGANG: angle (degrees) of the jog's middle segment in jogged radius dimensions.
|
||||
pub jog_angle: f64,
|
||||
}
|
||||
|
||||
/// DIMSTYLE system variable names and the [`DimStyle`] fields they set.
|
||||
@@ -253,6 +301,8 @@ pub const DIMVARS: &[(&str, &str)] = &[
|
||||
("DIMCLRD", "dimLineColor"),
|
||||
("DIMCLRE", "extLineColor"),
|
||||
("DIMCLRT", "textColor"),
|
||||
("DIMTFILL", "textFill"),
|
||||
("DIMTFILLCLR", "textFillColor"),
|
||||
("DIMTXSTY", "textStyle"),
|
||||
("DIMPOST", "post"),
|
||||
("DIMCEN", "centerMark"),
|
||||
@@ -281,6 +331,26 @@ pub const DIMVARS: &[(&str, &str)] = &[
|
||||
("DIMAUNIT", "angularUnit"),
|
||||
("DIMSE1", "suppressExt1"),
|
||||
("DIMSE2", "suppressExt2"),
|
||||
("DIMSD1", "suppressDim1"),
|
||||
("DIMSD2", "suppressDim2"),
|
||||
("DIMATFIT", "fit"),
|
||||
("DIMTIX", "textInside"),
|
||||
("DIMSOXD", "suppressOutsideArrows"),
|
||||
("DIMTOFL", "forceLineInside"),
|
||||
("DIMTMOVE", "textMove"),
|
||||
("DIMTVP", "textVerticalPos"),
|
||||
("DIMTOLJ", "tolJust"),
|
||||
("DIMAZIN", "angularZeroSuppression"),
|
||||
("DIMARCSYM", "arcSymbol"),
|
||||
("DIMLDRBLK", "leaderArrowBlock"),
|
||||
("DIMLTYPE", "dimLinetype"),
|
||||
("DIMLTEX1", "extLinetype1"),
|
||||
("DIMLTEX2", "extLinetype2"),
|
||||
("DIMLWD", "dimLineweight"),
|
||||
("DIMLWE", "extLineweight"),
|
||||
("DIMFXLON", "fixedExt"),
|
||||
("DIMFXL", "fixedExtLength"),
|
||||
("DIMJOGANG", "jogAngle"),
|
||||
];
|
||||
|
||||
impl Default for DimStyle {
|
||||
@@ -304,6 +374,8 @@ impl Default for DimStyle {
|
||||
dim_line_color: Color::ByBlock,
|
||||
ext_line_color: Color::ByBlock,
|
||||
text_color: Color::ByBlock,
|
||||
text_fill: 0,
|
||||
text_fill_color: Color::ByBlock,
|
||||
text_style: "Standard".into(),
|
||||
post: String::new(),
|
||||
center_mark: 0.09,
|
||||
@@ -335,6 +407,26 @@ impl Default for DimStyle {
|
||||
angular_unit: 0,
|
||||
suppress_ext1: false,
|
||||
suppress_ext2: false,
|
||||
suppress_dim1: false,
|
||||
suppress_dim2: false,
|
||||
fit: 3,
|
||||
text_inside: false,
|
||||
suppress_outside_arrows: false,
|
||||
force_line_inside: false,
|
||||
text_move: 0,
|
||||
text_vertical_pos: 0.0,
|
||||
tol_just: 1,
|
||||
angular_zero_suppression: 0,
|
||||
arc_symbol: 0,
|
||||
leader_arrow_block: String::new(),
|
||||
dim_linetype: String::new(),
|
||||
ext_linetype1: String::new(),
|
||||
ext_linetype2: String::new(),
|
||||
dim_lineweight: -2,
|
||||
ext_lineweight: -2,
|
||||
fixed_ext: false,
|
||||
fixed_ext_length: 1.0,
|
||||
jog_angle: 45.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -349,6 +441,49 @@ impl DimStyle {
|
||||
.or_else(|| ["name", "annotative"].into_iter().find(|f| f.eq_ignore_ascii_case(name)))
|
||||
}
|
||||
|
||||
/// The value `v` takes for a field whose current value is `old`: coerced to the field's type where
|
||||
/// the text or number can be read as it.
|
||||
fn coerce_value(old: &serde_json::Value, v: &serde_json::Value, field: &str) -> serde_json::Value {
|
||||
use serde_json::Value;
|
||||
match (old, v) {
|
||||
(Value::Bool(_), Value::Number(n)) => Value::Bool(n.as_f64().is_some_and(|x| x != 0.0)),
|
||||
(Value::Bool(_), Value::String(t)) => Value::Bool(matches!(t.to_ascii_lowercase().as_str(), "1" | "on" | "true" | "yes")),
|
||||
(Value::Number(_), Value::String(t)) => match t.trim().parse::<f64>() {
|
||||
Ok(x) => serde_json::json!(x),
|
||||
// Lineweight names.
|
||||
Err(_) if matches!(field, "dimLineweight" | "extLineweight") => match t.trim().to_ascii_lowercase().as_str() {
|
||||
"bylayer" => serde_json::json!(-1),
|
||||
"byblock" => serde_json::json!(-2),
|
||||
"default" => serde_json::json!(-3),
|
||||
_ => v.clone(),
|
||||
},
|
||||
Err(_) => v.clone(),
|
||||
},
|
||||
(Value::Number(_), Value::Bool(b)) => serde_json::json!(u8::from(*b)),
|
||||
(Value::String(_), Value::Number(n)) => Value::String(n.to_string()),
|
||||
(Value::Object(_), Value::Number(n)) => {
|
||||
let c = n.as_i64().and_then(|i| i16::try_from(i).ok()).map(Color::from_aci);
|
||||
c.and_then(|c| serde_json::to_value(c).ok()).unwrap_or_else(|| v.clone())
|
||||
}
|
||||
(Value::Object(_), Value::String(t)) => Color::parse(t).and_then(|c| serde_json::to_value(c).ok()).unwrap_or_else(|| v.clone()),
|
||||
_ => v.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `coerced` is outside the range its `field` can take.
|
||||
fn out_of_range(field: &str, coerced: &serde_json::Value) -> bool {
|
||||
let x = coerced.as_f64();
|
||||
match field {
|
||||
"textHeight" | "tolScale" => x.is_some_and(|x| x <= 0.0),
|
||||
"scale" | "arrowSize" | "tickSize" | "fixedExtLength" => x.is_some_and(|x| x < 0.0),
|
||||
"fit" | "angularZeroSuppression" => x.is_some_and(|x| x > 3.0),
|
||||
"textMove" | "tolJust" | "arcSymbol" | "textFill" => x.is_some_and(|x| x > 2.0),
|
||||
"dimLineweight" | "extLineweight" => x.is_some_and(|x| !(-3.0..=211.0).contains(&x)),
|
||||
"jogAngle" => x.is_some_and(|x| !(5.0..=90.0).contains(&x)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set fields from a JSON object of field or DIM* variable names (numbers, booleans as
|
||||
/// 0/1, colours as ACI numbers or names). Returns the names that were not recognised or
|
||||
/// had unusable values.
|
||||
@@ -366,36 +501,29 @@ impl DimStyle {
|
||||
rejected.push(k.clone());
|
||||
continue;
|
||||
};
|
||||
let coerced = match (&old, v) {
|
||||
(Value::Bool(_), Value::Number(n)) => Value::Bool(n.as_f64().is_some_and(|x| x != 0.0)),
|
||||
(Value::Bool(_), Value::String(t)) => Value::Bool(matches!(t.to_ascii_lowercase().as_str(), "1" | "on" | "true" | "yes")),
|
||||
(Value::Number(_), Value::String(t)) => match t.trim().parse::<f64>() {
|
||||
Ok(x) => serde_json::json!(x),
|
||||
Err(_) => v.clone(),
|
||||
},
|
||||
(Value::Number(_), Value::Bool(b)) => serde_json::json!(u8::from(*b)),
|
||||
(Value::String(_), Value::Number(n)) => Value::String(n.to_string()),
|
||||
(Value::Object(_), Value::Number(n)) => {
|
||||
let c = n.as_i64().and_then(|i| i16::try_from(i).ok()).map(Color::from_aci);
|
||||
c.and_then(|c| serde_json::to_value(c).ok()).unwrap_or_else(|| v.clone())
|
||||
}
|
||||
(Value::Object(_), Value::String(t)) => Color::parse(t).and_then(|c| serde_json::to_value(c).ok()).unwrap_or_else(|| v.clone()),
|
||||
_ => v.clone(),
|
||||
};
|
||||
let coerced = Self::coerce_value(&old, v, field);
|
||||
// Integers stored in u8 fields: round floats.
|
||||
let coerced = match (&old, &coerced) {
|
||||
// Lineweights (i16): whole hundredths of a mm or -1/-2/-3.
|
||||
(Value::Number(_), Value::Number(n)) if matches!(field, "dimLineweight" | "extLineweight") && !n.is_i64() => {
|
||||
serde_json::json!(n.as_f64().filter(|x| x.is_finite()).unwrap_or(0.0).round() as i64)
|
||||
}
|
||||
(Value::Number(_), Value::Number(_)) if matches!(field, "dimLineweight" | "extLineweight") => coerced,
|
||||
// A value below 0 or one that rounds above 255 is refused; DIMADEC -1 reads as 0.
|
||||
(Value::Number(o), Value::Number(n)) if o.is_u64() && !n.is_u64() => {
|
||||
serde_json::json!(n.as_f64().filter(|x| x.is_finite()).unwrap_or(0.0).round().clamp(0.0, 255.0) as u64)
|
||||
let min = if field == "angularDecimals" { -1.0 } else { 0.0 };
|
||||
match n.as_f64().filter(|x| x.is_finite() && *x >= min).map(f64::round).filter(|x| *x <= 255.0) {
|
||||
Some(x) => serde_json::json!(x.max(0.0) as u64),
|
||||
None => {
|
||||
rejected.push(k.clone());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => coerced,
|
||||
};
|
||||
// Sizes that can't be negative (text height and tolerance scale: not zero either).
|
||||
let x = coerced.as_f64();
|
||||
let out_of_range = match field {
|
||||
"textHeight" | "tolScale" => x.is_some_and(|x| x <= 0.0),
|
||||
"scale" | "arrowSize" | "tickSize" => x.is_some_and(|x| x < 0.0),
|
||||
_ => false,
|
||||
};
|
||||
let out_of_range = Self::out_of_range(field, &coerced);
|
||||
if out_of_range {
|
||||
rejected.push(k.clone());
|
||||
continue;
|
||||
@@ -429,6 +557,45 @@ impl DimStyle {
|
||||
st
|
||||
}
|
||||
|
||||
/// DIMTMOVE 0: the dimension line of a linear or aligned dimension follows text the user
|
||||
/// placed (`text_mid`), keeping the DIMTAD / DIMTVP offset. Other kinds, text in its
|
||||
/// default place and other DIMTMOVE values are left alone.
|
||||
pub fn follow_text(&self, d: &mut crate::Dimension, dimscale: f64) {
|
||||
if self.text_move != 0 || !d.user_text_pos {
|
||||
return;
|
||||
}
|
||||
let dir = match d.kind {
|
||||
crate::DimKind::Linear { rotation } => Vec2::from_angle(rotation),
|
||||
crate::DimKind::Aligned => (d.p14.xy() - d.p13.xy()).normalized(),
|
||||
_ => return,
|
||||
};
|
||||
if dir == Vec2::ZERO || !dir.is_finite() {
|
||||
return;
|
||||
}
|
||||
let n = dir.perp();
|
||||
let k = self.effective_scale(dimscale);
|
||||
let (th, gap) = (self.text_height * k, self.text_gap.abs() * k);
|
||||
let above = if n.y.abs() > 1e-9 {
|
||||
if n.y > 0.0 { n } else { -n }
|
||||
} else if n.x < 0.0 {
|
||||
n
|
||||
} else {
|
||||
-n
|
||||
};
|
||||
let away = if (d.defpt.xy() - d.p13.xy()).dot(n) >= 0.0 { n } else { -n };
|
||||
let off = match self.text_above {
|
||||
0 => above * (self.text_vertical_pos * th),
|
||||
2 => away * (gap + th / 2.0),
|
||||
4 => -above * (gap + th / 2.0),
|
||||
_ => above * (gap + th / 2.0),
|
||||
};
|
||||
let shift = n * (d.text_mid.xy() - off - d.defpt.xy()).dot(n);
|
||||
if shift.is_finite() {
|
||||
d.defpt.x += shift.x;
|
||||
d.defpt.y += shift.y;
|
||||
}
|
||||
}
|
||||
|
||||
/// The ISO-25 style for metric drawings.
|
||||
pub fn iso25() -> Self {
|
||||
DimStyle {
|
||||
@@ -445,6 +612,8 @@ impl DimStyle {
|
||||
center_mark: 2.5,
|
||||
zero_suppression: 8,
|
||||
baseline_spacing: 3.75,
|
||||
force_line_inside: true,
|
||||
tol_just: 0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -459,11 +628,28 @@ pub struct MLeaderStyle {
|
||||
pub landing_gap: f64,
|
||||
pub dogleg: f64,
|
||||
pub text_style: String,
|
||||
/// New multileaders of this style are annotative.
|
||||
pub annotative: bool,
|
||||
}
|
||||
|
||||
impl Default for MLeaderStyle {
|
||||
fn default() -> Self {
|
||||
MLeaderStyle { name: "Standard".into(), arrow_size: 0.18, text_height: 0.18, landing_gap: 0.09, dogleg: 0.36, text_style: "Standard".into() }
|
||||
MLeaderStyle {
|
||||
name: "Standard".into(),
|
||||
arrow_size: 0.18,
|
||||
text_height: 0.18,
|
||||
landing_gap: 0.09,
|
||||
dogleg: 0.36,
|
||||
text_style: "Standard".into(),
|
||||
annotative: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MLeaderStyle {
|
||||
/// The Standard style for metric drawings: text and arrows as high as ISO-25's.
|
||||
pub fn metric() -> Self {
|
||||
MLeaderStyle { arrow_size: 2.5, text_height: 2.5, landing_gap: 0.625, dogleg: 5.0, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,24 +661,52 @@ pub struct TableStyle {
|
||||
pub margin: f64,
|
||||
pub title: bool,
|
||||
pub header: bool,
|
||||
/// Cell styles: custom ones, and Title/Header/Data where they differ from what the text
|
||||
/// height and margin imply ([`TableStyle::cell_style`]).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub cell_styles: Vec<crate::CellStyle>,
|
||||
}
|
||||
|
||||
impl Default for TableStyle {
|
||||
fn default() -> Self {
|
||||
TableStyle { name: "Standard".into(), text_height: 0.18, margin: 0.06, title: true, header: true }
|
||||
TableStyle { name: "Standard".into(), text_height: 0.18, margin: 0.06, title: true, header: true, cell_styles: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl TableStyle {
|
||||
/// The Standard style for metric drawings: text as high as ISO-25's.
|
||||
pub fn metric() -> Self {
|
||||
TableStyle { text_height: 2.5, margin: 1.0, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
mod cellstyle;
|
||||
mod tablebreak;
|
||||
pub use cellstyle::*;
|
||||
pub use tablebreak::*;
|
||||
|
||||
/// A block definition.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Block {
|
||||
pub name: String,
|
||||
/// References to this block are annotative.
|
||||
#[serde(default)]
|
||||
pub annotative: bool,
|
||||
pub base: Vec3,
|
||||
#[serde(skip)]
|
||||
pub entities: EntityStore,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
/// An xref (`xref_path`: the referenced drawing's path as the user gave it, absolute,
|
||||
/// relative to the host drawing's folder or a bare file name) attached as an overlay (DXF
|
||||
/// BLOCK flag 8): not loaded when the host drawing is itself referenced by another drawing.
|
||||
/// An xref's objects come from that file and are never saved with the host.
|
||||
#[serde(default)]
|
||||
pub xref_overlay: bool,
|
||||
/// Whether an xref's objects are loaded, and why not (session state; not saved).
|
||||
#[serde(default)]
|
||||
pub xref_status: XrefStatus,
|
||||
/// Anonymous (`*D12`, `*U3`…) blocks are generated geometry.
|
||||
#[serde(default)]
|
||||
pub anonymous: bool,
|
||||
@@ -502,19 +716,55 @@ pub struct Block {
|
||||
pub explodable: bool,
|
||||
#[serde(default)]
|
||||
pub units: u8,
|
||||
/// The parameters of an associative array when this is an array block.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub array: Option<crate::ArrayParams>,
|
||||
}
|
||||
|
||||
/// The load state of an external reference.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum XrefStatus {
|
||||
/// Not loaded yet (read from a file, not resolved).
|
||||
#[default]
|
||||
NotLoaded,
|
||||
Loaded,
|
||||
/// Unloaded by the user (XREF Unload): kept, not drawn.
|
||||
Unloaded,
|
||||
/// The referenced file was not found.
|
||||
NotFound,
|
||||
/// The file was found but could not be loaded (unreadable, too large, a circular reference).
|
||||
Unresolved,
|
||||
}
|
||||
|
||||
impl XrefStatus {
|
||||
/// The status as the External References palette shows it.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
XrefStatus::NotLoaded => "Not loaded",
|
||||
XrefStatus::Loaded => "Loaded",
|
||||
XrefStatus::Unloaded => "Unloaded",
|
||||
XrefStatus::NotFound => "Not Found",
|
||||
XrefStatus::Unresolved => "Unresolved",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Block {
|
||||
pub fn new(name: &str) -> Self {
|
||||
Block {
|
||||
name: name.into(),
|
||||
annotative: false,
|
||||
base: Vec3::ZERO,
|
||||
entities: EntityStore::new(),
|
||||
xref_overlay: false,
|
||||
xref_status: XrefStatus::NotLoaded,
|
||||
description: String::new(),
|
||||
anonymous: name.starts_with('*'),
|
||||
xref_path: None,
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -532,12 +782,23 @@ pub struct PageSetup {
|
||||
pub landscape: bool,
|
||||
/// "layout" | "extents" | "display" | "window" | "limits".
|
||||
pub plot_area: String,
|
||||
/// Plot window corners `[x1, y1, x2, y2]` (DXF plot layout groups 48, 49, 140, 141); used when `plot_area` is "window".
|
||||
pub plot_window: [f64; 4],
|
||||
pub scale_to_fit: bool,
|
||||
/// Paper units per drawing unit.
|
||||
pub scale: f64,
|
||||
pub plot_style_table: String,
|
||||
pub center: bool,
|
||||
pub lineweights: bool,
|
||||
/// Draw the layout on screen (and in its PNG/SVG exports) with its plot style table
|
||||
/// applied ("Display plot styles"; DXF plot layout flag 2).
|
||||
pub show_plot_styles: bool,
|
||||
/// Plot objects with their transparency ("Plot transparency"; PLOTTRANSPARENCYOVERRIDE can
|
||||
/// override it). The DXF plot layout flags have no bit for it, so it is not saved in DXF.
|
||||
pub plot_transparency: bool,
|
||||
/// The layout's paper units are millimetres (plot paper units 1 in DXF) whatever the
|
||||
/// drawing's MEASUREMENT says; otherwise paper units follow MEASUREMENT (#1058).
|
||||
pub paper_mm: bool,
|
||||
}
|
||||
|
||||
impl Default for PageSetup {
|
||||
@@ -550,11 +811,15 @@ impl Default for PageSetup {
|
||||
margins_mm: [6.35, 6.35, 6.35, 6.35],
|
||||
landscape: true,
|
||||
plot_area: "layout".into(),
|
||||
plot_window: [0.0; 4],
|
||||
scale_to_fit: false,
|
||||
scale: 1.0,
|
||||
plot_style_table: String::new(),
|
||||
center: false,
|
||||
lineweights: true,
|
||||
show_plot_styles: false,
|
||||
plot_transparency: false,
|
||||
paper_mm: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -578,15 +843,54 @@ impl Layout {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
/// A named view (VIEW table): the centre and size of the area shown, in model space or a layout.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NamedView {
|
||||
pub name: String,
|
||||
pub center: Vec2,
|
||||
pub height: f64,
|
||||
pub width: f64,
|
||||
/// The layer state restored with the view (its layer snapshot).
|
||||
#[serde(default)]
|
||||
pub layer_state: Option<String>,
|
||||
/// View twist (radians, counterclockwise); kept for files, not applied to the 2D display.
|
||||
#[serde(default)]
|
||||
pub twist: f64,
|
||||
/// The layout a paper space view belongs to (`None`: a model space view; an empty name: a
|
||||
/// paper space view whose layout is not known).
|
||||
#[serde(default)]
|
||||
pub layout: Option<String>,
|
||||
}
|
||||
|
||||
/// One tiled model space viewport of a [`VportConfig`] (a VPORT table record): its corners as
|
||||
/// fractions of the drawing area (0,0 lower left to 1,1 upper right) and its view.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VportTile {
|
||||
pub min: Vec2,
|
||||
pub max: Vec2,
|
||||
pub center: Vec2,
|
||||
pub height: f64,
|
||||
/// Width / height of the tile on screen when it was saved (0: unknown).
|
||||
#[serde(default)]
|
||||
pub aspect: f64,
|
||||
}
|
||||
|
||||
/// A model space viewport configuration (VPORTS): `*Active` is the one shown, other names are
|
||||
/// saved configurations. The first tile is the current one.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct VportConfig {
|
||||
pub name: String,
|
||||
pub tiles: Vec<VportTile>,
|
||||
}
|
||||
|
||||
impl VportConfig {
|
||||
/// The name of the configuration shown.
|
||||
pub const ACTIVE: &str = "*Active";
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.name.eq_ignore_ascii_case(Self::ACTIVE)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
//! Table cell styles: the Title, Header and Data styles every table style has, plus named custom
|
||||
//! ones. A cell style sets the text (style, height, colour, alignment), the cell (fill, margins,
|
||||
//! borders) and how numbers are shown.
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Lineweight, Table, TableStyle};
|
||||
|
||||
/// The most cell styles a table style keeps (hostile input).
|
||||
pub const MAX_CELL_STYLES: usize = 64;
|
||||
|
||||
/// One border of a cell style.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CellBorder {
|
||||
pub visible: bool,
|
||||
pub color: Color,
|
||||
pub lineweight: Lineweight,
|
||||
}
|
||||
|
||||
impl Default for CellBorder {
|
||||
fn default() -> Self {
|
||||
CellBorder { visible: true, color: Color::ByBlock, lineweight: Lineweight::ByBlock }
|
||||
}
|
||||
}
|
||||
|
||||
/// The borders of a cell style, in the order of the DXF Reference's TABLESTYLE groups: top,
|
||||
/// inside horizontal, bottom, left, inside vertical, right. "Inside" borders separate cells that
|
||||
/// share the style.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CellBorders {
|
||||
pub top: CellBorder,
|
||||
pub inside_h: CellBorder,
|
||||
pub bottom: CellBorder,
|
||||
pub left: CellBorder,
|
||||
pub inside_v: CellBorder,
|
||||
pub right: CellBorder,
|
||||
}
|
||||
|
||||
impl CellBorders {
|
||||
/// The borders in DXF order (top, inside horizontal, bottom, left, inside vertical, right).
|
||||
pub fn as_array(&self) -> [CellBorder; 6] {
|
||||
[self.top, self.inside_h, self.bottom, self.left, self.inside_v, self.right]
|
||||
}
|
||||
/// Mutable borders in DXF order.
|
||||
pub fn as_array_mut(&mut self) -> [&mut CellBorder; 6] {
|
||||
[&mut self.top, &mut self.inside_h, &mut self.bottom, &mut self.left, &mut self.inside_v, &mut self.right]
|
||||
}
|
||||
}
|
||||
|
||||
/// How a cell shows a number (a formula result).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum CellFormat {
|
||||
/// As short as possible (up to the precision when it has decimals).
|
||||
#[default]
|
||||
General,
|
||||
/// Fixed decimals.
|
||||
Decimal,
|
||||
/// × 100 with a percent sign.
|
||||
Percent,
|
||||
/// Shown as typed: formulas keep their text.
|
||||
Text,
|
||||
}
|
||||
|
||||
/// A cell style.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CellStyle {
|
||||
pub name: String,
|
||||
/// Text style name.
|
||||
pub text_style: String,
|
||||
pub text_height: f64,
|
||||
pub text_color: Color,
|
||||
/// Background fill; `None` for no fill.
|
||||
pub fill: Option<Color>,
|
||||
/// Text alignment in the cell, as MTEXT attachment: 1 top left … 9 bottom right.
|
||||
pub align: u8,
|
||||
/// Horizontal and vertical margin between the cell edge and its text.
|
||||
pub margin_h: f64,
|
||||
pub margin_v: f64,
|
||||
pub borders: CellBorders,
|
||||
pub format: CellFormat,
|
||||
/// Decimal places for numbers (0..=8).
|
||||
pub precision: u8,
|
||||
/// New rows in this style merge across the table (titles).
|
||||
pub merge: bool,
|
||||
}
|
||||
|
||||
impl Default for CellStyle {
|
||||
fn default() -> Self {
|
||||
CellStyle {
|
||||
name: CellStyle::DATA.into(),
|
||||
text_style: "Standard".into(),
|
||||
text_height: 0.18,
|
||||
text_color: Color::ByBlock,
|
||||
fill: None,
|
||||
align: 4,
|
||||
margin_h: 0.06,
|
||||
margin_v: 0.06,
|
||||
borders: CellBorders::default(),
|
||||
format: CellFormat::General,
|
||||
precision: 2,
|
||||
merge: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CellStyle {
|
||||
pub const TITLE: &str = "Title";
|
||||
pub const HEADER: &str = "Header";
|
||||
pub const DATA: &str = "Data";
|
||||
|
||||
/// Whether `name` is one of the three styles every table style has.
|
||||
pub fn is_builtin(name: &str) -> bool {
|
||||
[Self::TITLE, Self::HEADER, Self::DATA].iter().any(|n| n.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// A copy with every value in range (hostile input from files and JSON).
|
||||
pub fn sanitized(mut self) -> CellStyle {
|
||||
let pos = |v: f64, d: f64| if v.is_finite() && v > 0.0 { v.min(1e9) } else { d };
|
||||
let nonneg = |v: f64| if v.is_finite() && v >= 0.0 { v.min(1e9) } else { 0.0 };
|
||||
self.text_height = pos(self.text_height, 0.18);
|
||||
self.margin_h = nonneg(self.margin_h);
|
||||
self.margin_v = nonneg(self.margin_v);
|
||||
if !(1..=9).contains(&self.align) {
|
||||
self.align = 4;
|
||||
}
|
||||
self.precision = self.precision.min(8);
|
||||
self.name = self.name.trim().chars().take(255).collect();
|
||||
if self.text_style.trim().is_empty() {
|
||||
self.text_style = "Standard".into();
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// `v` as this style shows numbers.
|
||||
pub fn format_number(&self, v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "#NUM".into();
|
||||
}
|
||||
let p = usize::from(self.precision.min(8));
|
||||
match self.format {
|
||||
CellFormat::Decimal => format!("{:.*}", p, v),
|
||||
CellFormat::Percent => format!("{:.*}%", p, v * 100.0),
|
||||
CellFormat::General | CellFormat::Text => {
|
||||
let s = format!("{:.*}", p, v);
|
||||
let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s };
|
||||
if s == "-0" { "0".into() } else { s }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TableStyle {
|
||||
/// The Title, Header or Data style this table style implies from its text height and margin
|
||||
/// (data middle left; header and title middle centre, the title 1.4 × as high and merged).
|
||||
pub fn base_cell_style(&self, name: &str) -> Option<CellStyle> {
|
||||
let base = CellStyle { text_height: self.text_height, margin_h: self.margin, margin_v: self.margin, ..CellStyle::default() };
|
||||
if name.eq_ignore_ascii_case(CellStyle::TITLE) {
|
||||
Some(CellStyle { name: CellStyle::TITLE.into(), text_height: self.text_height * 1.4, align: 5, merge: true, ..base })
|
||||
} else if name.eq_ignore_ascii_case(CellStyle::HEADER) {
|
||||
Some(CellStyle { name: CellStyle::HEADER.into(), align: 5, ..base })
|
||||
} else if name.eq_ignore_ascii_case(CellStyle::DATA) {
|
||||
Some(base)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The cell style `name`: the style's own definition, else the implied Title/Header/Data
|
||||
/// style, else Data.
|
||||
pub fn cell_style(&self, name: &str) -> CellStyle {
|
||||
self.cell_styles
|
||||
.iter()
|
||||
.find(|c| c.name.eq_ignore_ascii_case(name))
|
||||
.cloned()
|
||||
.or_else(|| self.base_cell_style(name))
|
||||
.or_else(|| self.cell_styles.iter().find(|c| c.name.eq_ignore_ascii_case(CellStyle::DATA)).cloned())
|
||||
.or_else(|| self.base_cell_style(CellStyle::DATA))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the style has a cell style `name` (built-in or custom).
|
||||
pub fn has_cell_style(&self, name: &str) -> bool {
|
||||
CellStyle::is_builtin(name) || self.cell_styles.iter().any(|c| c.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The names of its cell styles: Title, Header, Data, then the custom ones.
|
||||
pub fn cell_style_names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = [CellStyle::TITLE, CellStyle::HEADER, CellStyle::DATA].iter().map(ToString::to_string).collect();
|
||||
out.extend(self.cell_styles.iter().filter(|c| !CellStyle::is_builtin(&c.name)).map(|c| c.name.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
/// Store `cs` (replacing a cell style of the same name). A built-in style equal to its implied
|
||||
/// form is not stored, so plain styles stay plain.
|
||||
pub fn set_cell_style(&mut self, cs: CellStyle) {
|
||||
let cs = cs.sanitized();
|
||||
self.cell_styles.retain(|c| !c.name.eq_ignore_ascii_case(&cs.name));
|
||||
if self.base_cell_style(&cs.name).is_some_and(|b| b == CellStyle { name: b.name.clone(), ..cs.clone() }) {
|
||||
return;
|
||||
}
|
||||
if self.cell_styles.len() < MAX_CELL_STYLES {
|
||||
self.cell_styles.push(cs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cell style of row `row` by its position: Title for the first row of a titled table,
|
||||
/// Header for the header row, else Data.
|
||||
pub fn positional_cell_style(row: usize, title: bool, header: bool) -> &'static str {
|
||||
if title && row == 0 {
|
||||
CellStyle::TITLE
|
||||
} else if header && row == usize::from(title) {
|
||||
CellStyle::HEADER
|
||||
} else {
|
||||
CellStyle::DATA
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Table {
|
||||
fn default() -> Self {
|
||||
Table {
|
||||
insert: cadcraft_geom::Vec3::new(0.0, 0.0, 0.0),
|
||||
col_widths: Vec::new(),
|
||||
row_heights: Vec::new(),
|
||||
cells: Vec::new(),
|
||||
style: "Standard".into(),
|
||||
text_height: 0.18,
|
||||
title: false,
|
||||
header: false,
|
||||
row_styles: Vec::new(),
|
||||
breaks: None,
|
||||
data_link: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Table {
|
||||
/// The cell style name of row `row`.
|
||||
pub fn row_style(&self, row: usize) -> &str {
|
||||
match self.row_styles.get(row).map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
Some(s) => s,
|
||||
None => positional_cell_style(row, self.title, self.header),
|
||||
}
|
||||
}
|
||||
/// The cell style name of cell (`row`, `col`): its own, else its row's.
|
||||
pub fn cell_style_name(&self, row: usize, col: usize) -> &str {
|
||||
match self.cells.get(row).and_then(|r| r.get(col)).map(|c| c.style.trim()).filter(|s| !s.is_empty()) {
|
||||
Some(s) => s,
|
||||
None => self.row_style(row),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn implied_styles_follow_the_table_style() {
|
||||
let st = TableStyle { text_height: 0.25, margin: 0.1, ..TableStyle::default() };
|
||||
let t = st.cell_style("title");
|
||||
assert_eq!((t.name.as_str(), t.align, t.merge), ("Title", 5, true));
|
||||
assert!((t.text_height - 0.35).abs() < 1e-12);
|
||||
assert_eq!(st.cell_style("nope").name, "Data");
|
||||
assert_eq!(st.cell_style_names(), ["Title", "Header", "Data"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storing_an_implied_style_keeps_the_style_plain() {
|
||||
let mut st = TableStyle::default();
|
||||
st.set_cell_style(st.cell_style("Header"));
|
||||
assert!(st.cell_styles.is_empty());
|
||||
st.set_cell_style(CellStyle { name: "Totals".into(), fill: Some(Color::Index(3)), ..CellStyle::default() });
|
||||
assert!(st.has_cell_style("TOTALS"));
|
||||
assert_eq!(st.cell_style_names().last().map(String::as_str), Some("Totals"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_format() {
|
||||
let c = CellStyle::default();
|
||||
assert_eq!(c.format_number(2.5), "2.5");
|
||||
assert_eq!(c.format_number(3.0), "3");
|
||||
assert_eq!(c.format_number(-0.0001), "0");
|
||||
let d = CellStyle { format: CellFormat::Decimal, precision: 3, ..c.clone() };
|
||||
assert_eq!(d.format_number(1.0), "1.000");
|
||||
let p = CellStyle { format: CellFormat::Percent, precision: 0, ..c };
|
||||
assert_eq!(p.format_number(0.25), "25%");
|
||||
assert_eq!(p.format_number(f64::NAN), "#NUM");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_are_sanitized() {
|
||||
let c = CellStyle { text_height: f64::NAN, margin_h: -1.0, align: 42, precision: 200, ..CellStyle::default() }.sanitized();
|
||||
assert_eq!((c.text_height, c.margin_h, c.align, c.precision), (0.18, 0.0, 4, 8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
//! Table breaking: a long table drawn in several parts side by side or one below the other, with
|
||||
//! the label rows repeated, and data links (the table's cells filled from a CSV file).
|
||||
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Table;
|
||||
|
||||
/// The most parts a table is broken into.
|
||||
pub const MAX_TABLE_PARTS: usize = 1000;
|
||||
|
||||
/// Where the next part of a broken table goes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BreakDirection {
|
||||
#[default]
|
||||
Right,
|
||||
Left,
|
||||
Down,
|
||||
}
|
||||
|
||||
/// TABLEBREAK settings.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct TableBreak {
|
||||
pub enabled: bool,
|
||||
pub direction: BreakDirection,
|
||||
/// Repeat the title and header rows at the top of every part.
|
||||
pub repeat_top: bool,
|
||||
/// Repeat the last row (bottom labels) at the bottom of every part.
|
||||
pub repeat_bottom: bool,
|
||||
/// Largest part height (labels included).
|
||||
pub height: f64,
|
||||
/// Manual heights of the first parts; later parts use `height`.
|
||||
pub heights: Vec<f64>,
|
||||
/// Space between parts.
|
||||
pub spacing: f64,
|
||||
/// Moves of parts 2, 3, … from their automatic place (part grips).
|
||||
pub offsets: Vec<Vec2>,
|
||||
}
|
||||
|
||||
impl Default for TableBreak {
|
||||
fn default() -> Self {
|
||||
TableBreak {
|
||||
enabled: false,
|
||||
direction: BreakDirection::Right,
|
||||
repeat_top: true,
|
||||
repeat_bottom: false,
|
||||
height: 0.0,
|
||||
heights: Vec::new(),
|
||||
spacing: 0.5,
|
||||
offsets: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A CSV file the table's cells come from (DATALINK).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DataLink {
|
||||
pub path: String,
|
||||
/// The first table row the file's rows fill.
|
||||
pub start_row: usize,
|
||||
}
|
||||
|
||||
/// One part of a (broken) table: the rows it shows, top to bottom, and its insertion point.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TablePart {
|
||||
pub rows: Vec<usize>,
|
||||
pub origin: Vec2,
|
||||
}
|
||||
|
||||
fn size(v: f64) -> f64 {
|
||||
if v.is_finite() && v > 0.0 { v } else { 0.0 }
|
||||
}
|
||||
|
||||
impl Table {
|
||||
/// Number of label rows at the top (title and header).
|
||||
pub fn top_label_rows(&self) -> usize {
|
||||
(usize::from(self.title) + usize::from(self.header)).min(self.row_heights.len())
|
||||
}
|
||||
|
||||
/// Whether the table is drawn in several parts.
|
||||
pub fn is_broken(&self) -> bool {
|
||||
self.breaks.as_ref().is_some_and(|b| b.enabled && (size(b.height) > 0.0 || b.heights.iter().any(|h| size(*h) > 0.0)))
|
||||
}
|
||||
|
||||
/// The parts the table is drawn in (one part when it isn't broken).
|
||||
pub fn parts(&self) -> Vec<TablePart> {
|
||||
let rows = self.row_heights.len().min(10_000);
|
||||
let o = self.insert.xy();
|
||||
let all = || TablePart { rows: (0..rows).collect(), origin: o };
|
||||
let Some(b) = self.breaks.as_ref().filter(|_| self.is_broken()) else { return vec![all()] };
|
||||
let h = |r: usize| size(self.row_heights.get(r).copied().unwrap_or(0.0));
|
||||
let top: Vec<usize> = (0..self.top_label_rows()).collect();
|
||||
let bottom: Option<usize> = (b.repeat_bottom && rows > top.len() + 1).then(|| rows - 1);
|
||||
let data_end = bottom.unwrap_or(rows);
|
||||
let bottom_h = bottom.map(h).unwrap_or(0.0);
|
||||
let mut parts: Vec<Vec<usize>> = Vec::new();
|
||||
let mut r = top.len();
|
||||
while r < data_end && parts.len() < MAX_TABLE_PARTS {
|
||||
let i = parts.len();
|
||||
let limit = b.heights.get(i).copied().map(size).filter(|v| *v > 0.0).unwrap_or(size(b.height));
|
||||
let mut rows_here: Vec<usize> = if i == 0 || b.repeat_top { top.clone() } else { Vec::new() };
|
||||
let mut used: f64 = rows_here.iter().map(|r| h(*r)).sum::<f64>() + if b.repeat_bottom { bottom_h } else { 0.0 };
|
||||
// At least one data row per part.
|
||||
while r < data_end {
|
||||
let next = r;
|
||||
let fits = limit <= 0.0 || used + h(next) <= limit + 1e-9;
|
||||
if !fits && rows_here.len() > if i == 0 || b.repeat_top { top.len() } else { 0 } {
|
||||
break;
|
||||
}
|
||||
used += h(next);
|
||||
rows_here.push(next);
|
||||
r += 1;
|
||||
}
|
||||
parts.push(rows_here);
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return vec![all()];
|
||||
}
|
||||
// The rest when the part limit is reached; the bottom labels.
|
||||
let n = parts.len();
|
||||
if let Some(last) = parts.last_mut() {
|
||||
last.extend(r..data_end);
|
||||
}
|
||||
for p in &mut parts {
|
||||
if let Some(br) = bottom {
|
||||
p.push(br);
|
||||
}
|
||||
}
|
||||
// Place them.
|
||||
let width: f64 = self.col_widths.iter().map(|w| size(*w)).sum();
|
||||
let spacing = size(b.spacing);
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut at = o;
|
||||
for (i, rows) in parts.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
let prev_h: f64 = out.last().map(|p: &TablePart| p.rows.iter().map(|r| h(*r)).sum()).unwrap_or(0.0);
|
||||
at = match b.direction {
|
||||
BreakDirection::Right => at + Vec2::new(width + spacing, 0.0),
|
||||
BreakDirection::Left => at - Vec2::new(width + spacing, 0.0),
|
||||
BreakDirection::Down => at - Vec2::new(0.0, prev_h + spacing),
|
||||
};
|
||||
}
|
||||
let off = if i > 0 { b.offsets.get(i - 1).copied().filter(|v| v.is_finite()).unwrap_or(Vec2::ZERO) } else { Vec2::ZERO };
|
||||
// Automatic places follow the automatic chain; manual moves apply to the part only.
|
||||
out.push(TablePart { rows, origin: at + off });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The area the table covers, all parts included.
|
||||
pub fn bounds(&self) -> Bounds2 {
|
||||
let w: f64 = self.col_widths.iter().map(|w| size(*w)).sum();
|
||||
let mut b = Bounds2::EMPTY;
|
||||
for p in self.parts() {
|
||||
let h: f64 = p.rows.iter().map(|r| size(self.row_heights.get(*r).copied().unwrap_or(0.0))).sum();
|
||||
b.add(p.origin);
|
||||
b.add(p.origin + Vec2::new(w, -h));
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The cell (row, col) under `p`, in any part.
|
||||
pub fn cell_at_point(&self, p: Vec2) -> Option<(usize, usize)> {
|
||||
for part in self.parts() {
|
||||
let (x, y) = (p.x - part.origin.x, part.origin.y - p.y);
|
||||
if !(x.is_finite() && y.is_finite()) || x < 0.0 || y < 0.0 {
|
||||
continue;
|
||||
}
|
||||
let mut acc = 0.0;
|
||||
let mut row = None;
|
||||
for r in &part.rows {
|
||||
acc += size(self.row_heights.get(*r).copied().unwrap_or(0.0));
|
||||
if y <= acc {
|
||||
row = Some(*r);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(row) = row else { continue };
|
||||
let mut acc = 0.0;
|
||||
for (c, w) in self.col_widths.iter().enumerate() {
|
||||
acc += size(*w);
|
||||
if x <= acc {
|
||||
return Some((row, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Grip points: the insertion point, then the origin of every further part.
|
||||
pub fn grip_points(&self) -> Vec<Vec2> {
|
||||
let mut g = vec![self.insert.xy()];
|
||||
if self.is_broken() {
|
||||
g.extend(self.parts().into_iter().skip(1).map(|p| p.origin));
|
||||
}
|
||||
g
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::TableCell;
|
||||
|
||||
fn table(rows: usize) -> Table {
|
||||
Table {
|
||||
col_widths: vec![2.0, 3.0],
|
||||
row_heights: vec![1.0; rows],
|
||||
cells: vec![vec![TableCell::default(); 2]; rows],
|
||||
title: true,
|
||||
header: true,
|
||||
..Table::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbroken_is_one_part() {
|
||||
let t = table(5);
|
||||
assert_eq!(t.parts(), vec![TablePart { rows: vec![0, 1, 2, 3, 4], origin: Vec2::ZERO }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breaks_repeat_labels_and_go_right() {
|
||||
let mut t = table(8);
|
||||
t.breaks = Some(TableBreak { enabled: true, height: 4.0, spacing: 1.0, ..TableBreak::default() });
|
||||
let p = t.parts();
|
||||
let rows: Vec<Vec<usize>> = p.iter().map(|x| x.rows.clone()).collect();
|
||||
assert_eq!(rows, vec![vec![0, 1, 2, 3], vec![0, 1, 4, 5], vec![0, 1, 6, 7]]);
|
||||
assert_eq!(p[1].origin, Vec2::new(6.0, 0.0));
|
||||
assert_eq!(t.grip_points().len(), 3);
|
||||
assert_eq!(t.cell_at_point(Vec2::new(7.0, -2.5)), Some((4, 0)));
|
||||
let b = t.bounds();
|
||||
assert_eq!((b.min, b.max), (Vec2::new(0.0, -4.0), Vec2::new(17.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn down_without_repeats_and_manual_heights() {
|
||||
let mut t = table(8);
|
||||
t.breaks = Some(TableBreak {
|
||||
enabled: true,
|
||||
direction: BreakDirection::Down,
|
||||
repeat_top: false,
|
||||
repeat_bottom: true,
|
||||
height: 3.0,
|
||||
heights: vec![5.0],
|
||||
offsets: vec![Vec2::new(1.0, 0.0)],
|
||||
..TableBreak::default()
|
||||
});
|
||||
let p = t.parts();
|
||||
let rows: Vec<Vec<usize>> = p.iter().map(|x| x.rows.clone()).collect();
|
||||
assert_eq!(rows, vec![vec![0, 1, 2, 3, 7], vec![4, 5, 7], vec![6, 7]]);
|
||||
assert_eq!(p[1].origin, Vec2::new(1.0, -5.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_break_settings() {
|
||||
let mut t = table(3000);
|
||||
t.breaks = Some(TableBreak { enabled: true, height: 1e-9, spacing: f64::NAN, ..TableBreak::default() });
|
||||
let p = t.parts();
|
||||
assert!(p.len() <= MAX_TABLE_PARTS);
|
||||
assert_eq!(p.iter().map(|x| x.rows.iter().filter(|r| **r >= 2).count()).sum::<usize>(), 2998);
|
||||
t.breaks = Some(TableBreak { enabled: true, height: f64::INFINITY, ..TableBreak::default() });
|
||||
assert_eq!(t.parts().len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,23 @@ fn new_drawing_has_standard_tables() {
|
||||
assert!(m.dim_style("ISO-25").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_metric_drawing_has_metric_multileader_and_table_styles() {
|
||||
let m = Drawing::new_metric();
|
||||
let iso = m.dim_style("ISO-25").unwrap();
|
||||
let ml = m.mleader_styles.iter().find(|s| s.name == "Standard").unwrap();
|
||||
assert_eq!((ml.text_height, ml.arrow_size), (iso.text_height, iso.arrow_size));
|
||||
assert_eq!(ml.dogleg, 5.0);
|
||||
let ts = m.table_styles.iter().find(|s| s.name == "Standard").unwrap();
|
||||
assert_eq!(ts.text_height, iso.text_height);
|
||||
assert_eq!(iso.text_height, 2.5);
|
||||
|
||||
let i = Drawing::new_imperial();
|
||||
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
|
||||
assert_eq!(i.table_styles, vec![TableStyle::default()]);
|
||||
assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_and_extents() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
@@ -79,6 +96,59 @@ fn inserts_of_missing_or_empty_blocks_do_not_stretch_extents() {
|
||||
assert_eq!(d.extents(&Space::Model).max, Vec2::new(12.0, 12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_attributes_of_a_missing_block_still_count() {
|
||||
// The renderer draws the attributes of a reference whose definition is missing, so they are
|
||||
// extents and selection targets, as with an empty definition. The insertion point still isn't.
|
||||
let attrib = |invisible: bool| Attrib {
|
||||
tag: "TAG".into(),
|
||||
text: Text {
|
||||
insert: Vec3::new(1000.0, 1000.0, 0.0),
|
||||
align_pt: None,
|
||||
height: 10.0,
|
||||
value: "hello".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: HAlign::Left,
|
||||
valign: VAlign::Baseline,
|
||||
},
|
||||
invisible,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: Default::default(),
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
};
|
||||
let ins = |block: &str, attribs: Vec<Attrib>| {
|
||||
Entity::new(
|
||||
Handle(1),
|
||||
EntityKind::Insert(Insert {
|
||||
block: block.into(),
|
||||
insert: Vec3::ZERO,
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs,
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
}),
|
||||
)
|
||||
};
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.blocks.insert("Empty".into(), std::sync::Arc::new(Block::new("Empty")));
|
||||
let missing = entity_bounds(&d, &ins("Missing", vec![attrib(false)]), 0);
|
||||
let empty = entity_bounds(&d, &ins("Empty", vec![attrib(false)]), 0);
|
||||
assert!(!missing.is_empty());
|
||||
assert_eq!((missing.min, missing.max), (empty.min, empty.max));
|
||||
assert_eq!(missing.min, Vec2::new(1000.0, 1000.0));
|
||||
// Without a visible attribute there is nothing to measure.
|
||||
assert!(entity_bounds(&d, &ins("Missing", vec![]), 0).is_empty());
|
||||
assert!(entity_bounds(&d, &ins("Missing", vec![attrib(true)]), 0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_arc_mirror_keeps_shape() {
|
||||
let mut k = EntityKind::Arc(Arc { center: Vec3::ZERO, radius: 1.0, start: 0.0, end: std::f64::consts::FRAC_PI_2 });
|
||||
@@ -269,6 +339,38 @@ fn extents_pair(d: &Drawing) -> (Vec2, Vec2) {
|
||||
(b.min, b.max)
|
||||
}
|
||||
|
||||
/// #706: block A reaches B once through a chain of 14 blocks (B at depth 15, its line's block E at
|
||||
/// 16, past the limit) and once directly (B at depth 1). `children` picks which of the two A holds.
|
||||
fn deep_and_shallow(children: &[&str]) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut add = |name: &str, kids: Vec<EntityKind>| {
|
||||
let mut blk = Block::new(name);
|
||||
for (i, k) in kids.into_iter().enumerate() {
|
||||
blk.entities.push(Entity::new(Handle(i as u64 + 1), k));
|
||||
}
|
||||
d.blocks.insert(name.into(), std::sync::Arc::new(blk));
|
||||
};
|
||||
add("E", vec![line((1000.0, 1000.0), (2000.0, 1000.0))]);
|
||||
add("B", vec![plain_insert("E")]);
|
||||
for i in 1..=14 {
|
||||
let next = if i == 14 { "B".to_string() } else { format!("C{}", i + 1) };
|
||||
add(&format!("C{i}"), vec![plain_insert(&next)]);
|
||||
}
|
||||
add("A", children.iter().map(|c| plain_insert(c)).collect());
|
||||
d.add(&Space::Model, Common::default(), plain_insert("A")).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_block_visit_does_not_hide_a_shallow_reference() {
|
||||
let line = (Vec2::new(1000.0, 1000.0), Vec2::new(2000.0, 1000.0));
|
||||
// Control: past the limit, the deep path alone contributes nothing.
|
||||
assert!(deep_and_shallow(&["C1"]).extents(&Space::Model).is_empty());
|
||||
assert_eq!(extents_pair(&deep_and_shallow(&["B"])), line);
|
||||
assert_eq!(extents_pair(&deep_and_shallow(&["B", "C1"])), line);
|
||||
assert_eq!(extents_pair(&deep_and_shallow(&["C1", "B"])), line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_entity_with_invisible_flag_is_ignored_in_insert_extents() {
|
||||
let mut far = far_line("0");
|
||||
@@ -354,6 +456,8 @@ fn attdef_in_block_is_ignored_in_insert_extents() {
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: Default::default(),
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
}),
|
||||
);
|
||||
let d = drawing_with_block(attdef);
|
||||
@@ -385,6 +489,8 @@ fn mtext_kind(contents: &str) -> EntityKind {
|
||||
style: "Standard".into(),
|
||||
contents: contents.into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -441,6 +547,7 @@ fn invisible_dimblock_entity_is_ignored_in_dimension_extents() {
|
||||
block: Some("*D1".into()),
|
||||
overrides: Default::default(),
|
||||
assoc: vec![],
|
||||
marks: Default::default(),
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -463,3 +570,14 @@ fn invisible_dimblock_entity_is_ignored_in_dimension_extents() {
|
||||
dim(&mut d, far_line("0"));
|
||||
assert_eq!(d.extents(&Space::Model).max, Vec2::new(6000.0, 6000.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_names_its_tab() {
|
||||
assert!(!Space::Model.is_paper());
|
||||
assert_eq!(Space::Model.layout(), None);
|
||||
assert_eq!(Space::Model.tab_name(), "Model");
|
||||
let p = Space::Paper("Sheet A".into());
|
||||
assert!(p.is_paper());
|
||||
assert_eq!(p.layout(), Some("Sheet A"));
|
||||
assert_eq!(p.tab_name(), "Sheet A");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
//! Reading the user's own `.lin` and `.pat` files (#552). Every file here is a tiny synthetic one
|
||||
//! written for these tests, with our own names.
|
||||
|
||||
use cadcraft_doc::library::files::{MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, parse_lin, parse_pat};
|
||||
|
||||
const LIN: &str = "\
|
||||
;; my own linetypes
|
||||
*MYDASH,My dash __ __ __
|
||||
A,.5,-.25
|
||||
|
||||
*MYDOTS
|
||||
A,0,-.1,0,-.2
|
||||
*MYTEXT,Text line --MY--MY--
|
||||
A,.5,-.2,[\"MY\",STANDARD,S=.1,R=0.0,X=-0.1,Y=-.05],-.2
|
||||
*MYSHAPE,Shape line
|
||||
A,.25,-.1,[MYBOX,myshapes.shx,S=.1],-.1,1
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn simple_and_text_linetypes_are_read() {
|
||||
let r = parse_lin(LIN);
|
||||
let names: Vec<&str> = r.items.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["MYDASH", "MYDOTS", "MYTEXT", "MYSHAPE"]);
|
||||
let dash = &r.items[0];
|
||||
assert_eq!(dash.description, "My dash __ __ __");
|
||||
assert_eq!(dash.pattern.iter().map(|e| e.length).collect::<Vec<_>>(), [0.5, -0.25]);
|
||||
assert_eq!(r.items[1].description, "");
|
||||
assert_eq!(r.items[1].pattern.len(), 4);
|
||||
|
||||
// The text belongs to the gap before it: drawn at that gap's end.
|
||||
let text = &r.items[2].pattern;
|
||||
assert_eq!(text.len(), 3);
|
||||
assert_eq!(text[1].length, -0.2);
|
||||
assert_eq!(text[1].text.as_deref(), Some("MY"));
|
||||
assert_eq!(text[1].style.as_deref(), Some("STANDARD"));
|
||||
assert!((text[1].scale - 0.1).abs() < 1e-12);
|
||||
assert!((text[1].offset.x + 0.1).abs() < 1e-12 && (text[1].offset.y + 0.05).abs() < 1e-12);
|
||||
assert!(!text[1].absolute);
|
||||
assert!(text[2].text.is_none());
|
||||
|
||||
// Shapes need SHX files: left out with a note, the dashes kept.
|
||||
let shape = &r.items[3].pattern;
|
||||
assert_eq!(shape.iter().map(|e| e.length).collect::<Vec<_>>(), [0.25, -0.1, -0.1, 1.0]);
|
||||
assert!(shape.iter().all(|e| e.text.is_none() && e.shape.is_none()));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("MYBOX")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rotation_units_and_absolute_angles() {
|
||||
let r = parse_lin("*R1\nA,1,[\"x\",S1,A=90,S=1],-1\n*R2\nA,1,[\"x\",S1,R=1.5r],-1\n*R3\nA,1,[\"a,b]\",S1,U=100g],-1\n");
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let rot = |i: usize| r.items[i].pattern[0].rotation;
|
||||
assert!((rot(0) - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && r.items[0].pattern[0].absolute);
|
||||
assert!((rot(1) - 1.5).abs() < 1e-12);
|
||||
assert!((rot(2) - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
|
||||
// Commas and brackets inside the quoted text are text.
|
||||
assert_eq!(r.items[2].pattern[0].text.as_deref(), Some("a,b]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_linetypes_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
*NOPATTERN
|
||||
*BADNUM
|
||||
A,.5,abc
|
||||
*BADALIGN
|
||||
B,.5,-.5
|
||||
*UNCLOSED
|
||||
A,.5,[\"x\",S1
|
||||
*
|
||||
A,1,-1
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,2,-2
|
||||
*ZERO
|
||||
A,0,0
|
||||
*NOSTYLE
|
||||
A,1,[\"x\"],-1
|
||||
";
|
||||
let r = parse_lin(text);
|
||||
assert_eq!(r.items.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["GOOD"]);
|
||||
assert_eq!(r.items[0].pattern[0].length, 1.0, "the first definition is kept");
|
||||
for what in ["NOPATTERN", "BADNUM", "BADALIGN", "UNCLOSED", "without a name", "without a *NAME", "defined twice", "ZERO", "NOSTYLE"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_linetype_files_never_panic_and_stay_capped() {
|
||||
let long_line = format!("*LONG\nA,{}", vec!["1"; 5000].join(","));
|
||||
let many = format!("*MANY\nA,{}", vec!["1,-1"; MAX_LINETYPE_ELEMENTS].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*L{i}\nA,1,-1\n")).collect();
|
||||
let huge = "*HUGE\nA,1e300,-1\n*NAN\nA,NaN,-1\n*INF\nA,inf,-1\n";
|
||||
for text in [long_line.as_str(), many.as_str(), defs.as_str(), huge, "", "\u{feff}", "]]][[[\"", "*\u{0}\nA,1", "A,1,-1\n*X,", "*X\nA,[[[[\"]]]"]
|
||||
{
|
||||
let r = parse_lin(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|l| l.pattern.len() <= MAX_LINETYPE_ELEMENTS && l.pattern.iter().all(|e| e.length.is_finite())));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_lin(huge).items.is_empty());
|
||||
assert_eq!(parse_lin(&defs).items.len(), 4096);
|
||||
}
|
||||
|
||||
const PAT: &str = "\
|
||||
; my own patterns
|
||||
*MYGRID, My grid
|
||||
0, 0,0, 0,.5
|
||||
90, 0,0, 0,.5
|
||||
*MYBRICK,My brick ; trailing comment
|
||||
0, 0,0, 0,.25
|
||||
90, 0,0, .25,.25, .25,-.25
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn hatch_patterns_are_read() {
|
||||
let r = parse_pat(PAT);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(r.items.len(), 2);
|
||||
let grid = &r.items[0];
|
||||
assert_eq!((grid.name.as_str(), grid.description.as_str()), ("MYGRID", "My grid"));
|
||||
assert_eq!(grid.lines.len(), 2);
|
||||
assert_eq!(grid.lines[1].angle, 90.0);
|
||||
assert_eq!(grid.lines[1].delta, (0.0, 0.5));
|
||||
let brick = &r.items[1];
|
||||
assert_eq!(brick.description, "My brick");
|
||||
assert_eq!(brick.lines[1].origin, (0.0, 0.0));
|
||||
assert_eq!(brick.lines[1].dashes, [0.25, -0.25]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowercase_pattern_names_are_upper_cased() {
|
||||
let r = parse_pat("*mypat\n45,0,0,0,.125\n");
|
||||
assert_eq!(r.items[0].name, "MYPAT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_patterns_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
0,0,0,0,1
|
||||
*EMPTY
|
||||
*SHORT
|
||||
0,0,0
|
||||
*ZEROGAP
|
||||
0,0,0,1,0
|
||||
*BADNUM
|
||||
0,0,0,0,x
|
||||
*OK
|
||||
0,0,0,0,1
|
||||
*OK
|
||||
45,0,0,0,1
|
||||
";
|
||||
let r = parse_pat(text);
|
||||
assert_eq!(r.items.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["OK"]);
|
||||
assert_eq!(r.items[0].lines[0].angle, 0.0, "the first definition is kept");
|
||||
for what in ["without a *NAME", "EMPTY", "SHORT", "ZEROGAP", "BADNUM", "defined twice"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_pattern_files_never_panic_and_stay_capped() {
|
||||
let families = format!("*FAM\n{}", "0,0,0,0,1\n".repeat(MAX_PATTERN_FAMILIES + 5));
|
||||
let dashes = format!("*DASH\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES + 1].join(","));
|
||||
let ok_dashes = format!("*DASHOK\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*P{i}\n0,0,0,0,1\n")).collect();
|
||||
let big = "*BIG\n1e300,0,0,0,1\n*NAN\nNaN,0,0,0,1\n";
|
||||
for text in [families.as_str(), dashes.as_str(), ok_dashes.as_str(), defs.as_str(), big, "", "*", "***\n,,,,,", "*X\n,,,,,,,,,,"] {
|
||||
let r = parse_pat(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|p| p.lines.len() <= MAX_PATTERN_FAMILIES && p.lines.iter().all(|l| l.dashes.len() <= MAX_PATTERN_DASHES)));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_pat(&families).items.is_empty());
|
||||
assert!(parse_pat(&dashes).items.is_empty());
|
||||
assert_eq!(parse_pat(&ok_dashes).items.len(), 1);
|
||||
assert!(parse_pat(big).items.is_empty());
|
||||
assert_eq!(parse_pat(&defs).items.len(), 4096);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
mod lin_pat_parse;
|
||||
mod sub_segment_alias;
|
||||
@@ -0,0 +1,14 @@
|
||||
//! `Sub::parse` accepts every spelling its documentation lists (#710).
|
||||
|
||||
use cadcraft_doc::Sub;
|
||||
|
||||
#[test]
|
||||
fn short_segment_name_matches_the_documented_forms() {
|
||||
for spelling in ["seg2", "segment2", "s2"] {
|
||||
assert_eq!(Sub::parse(spelling), Some(Sub::Segment(2)), "spelling: {spelling}");
|
||||
}
|
||||
for spelling in ["s", "start"] {
|
||||
assert_eq!(Sub::parse(spelling), Some(Sub::Start), "spelling: {spelling}");
|
||||
}
|
||||
assert_eq!(Sub::parse("unknown"), None);
|
||||
}
|
||||
@@ -10,4 +10,4 @@ workspace = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# MPL-2.0: used as an unmodified dependency only (see plan/adr/0001 and NOTICE).
|
||||
acadrust = "0.6.3"
|
||||
acadrust = "0.6.5"
|
||||
|
||||
+731
-12
@@ -4,6 +4,25 @@
|
||||
//! converted to DXF bytes, which CADCraft's own DXF reader maps to its document model; saving
|
||||
//! goes the other way. Keeping the dependency behind this byte-level API isolates it: nothing
|
||||
//! else in CADCraft depends on its types. Native targets only (it memory-maps files).
|
||||
//!
|
||||
//! # Guardrails around the third-party decoder
|
||||
//!
|
||||
//! The decoder allocates tables and section buffers from sizes a (possibly damaged or hostile)
|
||||
//! file declares, and once it starts it cannot be interrupted (an allocation failure aborts the
|
||||
//! process, which `catch_unwind` cannot recover). Because the dependency is used unmodified, this
|
||||
//! crate guards it from the outside:
|
||||
//!
|
||||
//! - Both directions reject oversized input *before* the decoder runs ([`Limits::max_dwg_bytes`]
|
||||
//! for DWG→DXF, [`Limits::max_dxf_bytes`] for DXF→DWG), and the DWG→DXF output is capped while
|
||||
//! it is written (`CappedWriter`).
|
||||
//! - The reader and writer run inside `catch_unwind`, so a decode failure is reported instead of
|
||||
//! crashing.
|
||||
//!
|
||||
//! These bound the input- and output-size variants. A small file that declares a huge internal
|
||||
//! table or section can still make the dependency allocate before any size is known; fully fixing
|
||||
//! that requires an upstream fix in `acadrust` (validate declared sizes against a decoded-memory
|
||||
//! budget) or running the decode in a separate worker with an OS memory limit. The limits here
|
||||
//! keep the blast radius bounded in the meantime.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
@@ -61,12 +80,38 @@ mod native {
|
||||
/// guard: the input size before the DWG reader runs, the DXF size while it is written, so a
|
||||
/// runaway conversion stops at the limit instead of filling memory first.
|
||||
pub fn dwg_to_dxf_with(bytes: &[u8], limits: Limits) -> Result<Vec<u8>, String> {
|
||||
dwg_to_dxf_noted(bytes, limits).map(|(dxf, _)| dxf)
|
||||
}
|
||||
|
||||
/// [`dwg_to_dxf_with`], also returning notes on what the read left out. The reader runs in
|
||||
/// failsafe mode: an object record it can't decode is skipped instead of failing the whole
|
||||
/// file, and the notes say how many were skipped and of which types, so a partial read never
|
||||
/// passes for a complete one.
|
||||
pub fn dwg_to_dxf_noted(bytes: &[u8], limits: Limits) -> Result<(Vec<u8>, Vec<String>), String> {
|
||||
if bytes.len() > limits.max_dwg_bytes {
|
||||
return Err(format!("DWG: the file is {}, larger than the {} CADCraft opens", mb(bytes.len() as u64), mb(limits.max_dwg_bytes as u64)));
|
||||
}
|
||||
let doc = std::panic::catch_unwind(|| acadrust::DwgReader::from_stream(Cursor::new(bytes)).read())
|
||||
.map_err(|_| "the DWG reader failed on this file".to_string())?
|
||||
.map_err(|e| format!("DWG: {e}"))?;
|
||||
let outcome = std::panic::catch_unwind(|| {
|
||||
acadrust::DwgReader::from_stream_with_options(Cursor::new(bytes), acadrust::DwgReadOptions::failsafe()).read_with_stats()
|
||||
})
|
||||
.map_err(|_| "the DWG reader failed on this file".to_string())?
|
||||
.map_err(|e| format!("DWG: {e}"))?;
|
||||
// Failsafe skips records, not whole files: when the objects stream itself couldn't be
|
||||
// read (a damaged header or section map, or not a DWG at all), nothing was read.
|
||||
if !outcome.stats.record_stream_read {
|
||||
let why = outcome.stats.diagnostics.first().map(|d| d.message.trim_start_matches("Failsafe: ").to_string());
|
||||
return Err(format!("DWG: {}", why.unwrap_or_else(|| "the file's objects couldn't be read".to_string())));
|
||||
}
|
||||
let mut notes = read_notes(&outcome.stats);
|
||||
let mut doc = outcome.document;
|
||||
current_style_names(&mut doc);
|
||||
table_merges(&mut doc);
|
||||
table_style_rows(&mut doc, false);
|
||||
let orphans = drop_orphaned_dgn_components(&mut doc);
|
||||
if orphans > 0 {
|
||||
let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") };
|
||||
notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out"));
|
||||
}
|
||||
let mut out = CappedWriter { buf: Vec::new(), limit: limits.max_dxf_bytes, exceeded: false };
|
||||
let written = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DxfWriter::new(&doc).write_to_writer(&mut out)))
|
||||
.map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?;
|
||||
@@ -79,14 +124,283 @@ mod native {
|
||||
));
|
||||
}
|
||||
written.map_err(|e| format!("DWG→DXF: {e}"))?;
|
||||
Ok(add_header_vars(out.buf, &doc.header))
|
||||
Ok((add_header_vars(out.buf, &doc.header), notes))
|
||||
}
|
||||
|
||||
/// Most record types named in the skipped-records note.
|
||||
const NOTE_TYPES: usize = 6;
|
||||
|
||||
/// The note on object records a failsafe read skipped: how many, and how many of each type
|
||||
/// (most first), or nothing when the read was complete.
|
||||
pub(crate) fn read_notes(stats: &acadrust::ReadStats) -> Vec<String> {
|
||||
let skipped = stats.skipped_source_records;
|
||||
if skipped == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let label = |t: Option<&str>| match t.map(str::parse::<i16>) {
|
||||
Some(Ok(code)) => type_name(code).map_or_else(|| format!("type {code}"), str::to_string),
|
||||
Some(Err(_)) => t.unwrap_or_default().to_string(),
|
||||
None => "unknown".to_string(),
|
||||
};
|
||||
let mut by_type: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
|
||||
for d in stats.diagnostics.iter().filter(|d| d.record_handle.is_some()) {
|
||||
*by_type.entry(label(d.record_type.as_deref())).or_default() += 1;
|
||||
}
|
||||
let mut types: Vec<(String, usize)> = by_type.into_iter().collect();
|
||||
types.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
let mut list: Vec<String> = types.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t} × {n}")).collect();
|
||||
if types.len() > NOTE_TYPES {
|
||||
list.push(format!("{} more types", types.len() - NOTE_TYPES));
|
||||
}
|
||||
let of = if stats.source_records > 0 { format!(" of {}", stats.source_records) } else { String::new() };
|
||||
let records = if skipped == 1 && of.is_empty() { "object record" } else { "object records" };
|
||||
let (were, them) = if skipped == 1 { ("was", "it") } else { ("were", "them") };
|
||||
let which = if list.is_empty() { String::new() } else { format!(" ({})", list.join(", ")) };
|
||||
vec![format!(
|
||||
"DWG: {skipped}{of} {records} couldn't be read and {were} left out{which}; \
|
||||
saving over the original file would lose {them}"
|
||||
)]
|
||||
}
|
||||
|
||||
/// The DXF name of a DWG object type code with a fixed number (classes, 500 and up, are
|
||||
/// numbered per file).
|
||||
fn type_name(code: i16) -> Option<&'static str> {
|
||||
Some(match code {
|
||||
1 => "TEXT",
|
||||
2 => "ATTRIB",
|
||||
3 => "ATTDEF",
|
||||
4 => "BLOCK",
|
||||
5 => "ENDBLK",
|
||||
6 => "SEQEND",
|
||||
7 => "INSERT",
|
||||
8 => "MINSERT",
|
||||
10..=14 => "VERTEX",
|
||||
15 | 16 | 29 | 30 => "POLYLINE",
|
||||
17 => "ARC",
|
||||
18 => "CIRCLE",
|
||||
19 => "LINE",
|
||||
20..=26 => "DIMENSION",
|
||||
27 => "POINT",
|
||||
28 => "3DFACE",
|
||||
31 => "SOLID",
|
||||
32 => "TRACE",
|
||||
33 => "SHAPE",
|
||||
34 => "VIEWPORT",
|
||||
35 => "ELLIPSE",
|
||||
36 => "SPLINE",
|
||||
37 => "REGION",
|
||||
38 => "3DSOLID",
|
||||
39 => "BODY",
|
||||
40 => "RAY",
|
||||
41 => "XLINE",
|
||||
42 => "DICTIONARY",
|
||||
43 => "OLEFRAME",
|
||||
44 => "MTEXT",
|
||||
45 => "LEADER",
|
||||
46 => "TOLERANCE",
|
||||
47 => "MLINE",
|
||||
48 => "BLOCK_CONTROL",
|
||||
49 => "BLOCK_RECORD",
|
||||
50 => "LAYER_CONTROL",
|
||||
51 => "LAYER",
|
||||
52 => "STYLE_CONTROL",
|
||||
53 => "STYLE",
|
||||
56 => "LTYPE_CONTROL",
|
||||
57 => "LTYPE",
|
||||
60 => "VIEW_CONTROL",
|
||||
61 => "VIEW",
|
||||
62 => "UCS_CONTROL",
|
||||
63 => "UCS",
|
||||
64 => "VPORT_CONTROL",
|
||||
65 => "VPORT",
|
||||
66 => "APPID_CONTROL",
|
||||
67 => "APPID",
|
||||
68 => "DIMSTYLE_CONTROL",
|
||||
69 => "DIMSTYLE",
|
||||
70 => "VX_CONTROL",
|
||||
71 => "VX_TABLE_RECORD",
|
||||
72 => "GROUP",
|
||||
73 => "MLINESTYLE",
|
||||
74 => "OLE2FRAME",
|
||||
77 => "LWPOLYLINE",
|
||||
78 => "HATCH",
|
||||
79 => "XRECORD",
|
||||
80 => "ACDBPLACEHOLDER",
|
||||
82 => "LAYOUT",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Merged table cells onto the cells. acadrust 0.6.3 reads a 2010+ (AC1024+) DWG table's
|
||||
/// merged cells into the table's `merged_ranges` only, while its DXF writer writes each cell's
|
||||
/// own merge groups (173, 175, 176), so without this the merges would be lost. Tables whose
|
||||
/// cells already carry merges are left alone. Each range's first cell gets the span; the
|
||||
/// cells it covers are marked merged with no span of their own, as CADCraft's DXF writer does.
|
||||
fn table_merges(doc: &mut acadrust::CadDocument) {
|
||||
for e in doc.entities_mut() {
|
||||
let acadrust::entities::EntityType::Table(t) = e else { continue };
|
||||
if t.merged_ranges.is_empty() || t.rows.iter().flat_map(|r| &r.cells).any(|c| c.merge_width > 1 || c.merge_height > 1) {
|
||||
continue;
|
||||
}
|
||||
let (rows, cols) = (t.rows.len(), t.columns.len());
|
||||
// A real table has at most one merge per cell; more ranges than that come from a
|
||||
// damaged file and would only make this rows × cols × ranges.
|
||||
let max_ranges = rows.saturating_mul(cols).min(1 << 16);
|
||||
for r in t.merged_ranges.iter().take(max_ranges).cloned().collect::<Vec<_>>() {
|
||||
// Clamp to the table: the ranges come from the file.
|
||||
let (bottom, right) = (r.bottom_row.min(rows.saturating_sub(1)), r.right_col.min(cols.saturating_sub(1)));
|
||||
if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) {
|
||||
continue;
|
||||
}
|
||||
let span = |n: usize| i32::try_from(n + 1).unwrap_or(i32::MAX);
|
||||
for (ri, row) in t.rows.iter_mut().enumerate().take(bottom + 1).skip(r.top_row) {
|
||||
for (ci, cell) in row.cells.iter_mut().enumerate().take(right + 1).skip(r.left_col) {
|
||||
cell.merged = 1;
|
||||
let first = (ri, ci) == (r.top_row, r.left_col);
|
||||
cell.merge_width = if first { span(right - r.left_col) } else { 0 };
|
||||
cell.merge_height = if first { span(bottom - r.top_row) } else { 0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Table styles' title and header suppression between the two places acadrust 0.6.3 keeps
|
||||
/// it. 2010+ (AC1024+) DWG stores it only in the style's flags (title 1, header 2), while
|
||||
/// acadrust's DXF reader and writer use the `title_suppressed`/`header_suppressed` fields
|
||||
/// (groups 280, 281). `to_flags` copies the fields into the flags before a DWG is written;
|
||||
/// otherwise the flags are copied into the fields after one is read. Older versions store
|
||||
/// both and are left alone.
|
||||
fn table_style_rows(doc: &mut acadrust::CadDocument, to_flags: bool) {
|
||||
use acadrust::objects::{ObjectType, TableStyleFlags};
|
||||
if doc.version < acadrust::DxfVersion::AC1024 {
|
||||
return;
|
||||
}
|
||||
for o in doc.objects.values_mut() {
|
||||
let ObjectType::TableStyle(s) = o else { continue };
|
||||
for (bit, suppressed) in
|
||||
[(TableStyleFlags::TITLE_SUPPRESSED, &mut s.title_suppressed), (TableStyleFlags::HEADER_SUPPRESSED, &mut s.header_suppressed)]
|
||||
{
|
||||
if to_flags {
|
||||
s.flags.set(bit, *suppressed);
|
||||
} else {
|
||||
*suppressed = s.flags.contains(bit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification,
|
||||
/// common dimension data), which acadrust keeps no copy of from DXF: it is set here as
|
||||
/// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128,
|
||||
/// acadrust 0.6.5 reads and writes itself.
|
||||
fn dimension_flags(doc: &mut acadrust::CadDocument) {
|
||||
for e in doc.entities_mut() {
|
||||
let acadrust::entities::EntityType::Dimension(d) = e else { continue };
|
||||
d.base_mut().dwg_flags_byte |= 0x02;
|
||||
}
|
||||
}
|
||||
|
||||
/// Leave out DGN line style components (`LS*COMPONENT`) that no line style definition uses
|
||||
/// (#1482). A drawing that once came from MicroStation can carry hundreds of thousands of
|
||||
/// them, orphaned copies piled up by earlier DGN imports and copy-pastes (AutoCAD's PURGE
|
||||
/// removes them as orphaned data): in a real 83 MB site plan they were 888,483 of 889,053
|
||||
/// components and made its DXF rendition 1.2 GB, over [`Limits::DEFAULT`], so the file
|
||||
/// didn't open at all. No definition that was read refers to them (a definition the reader
|
||||
/// skipped can't use them either) and CADCraft doesn't draw DGN line styles, so nothing
|
||||
/// visible is lost.
|
||||
/// Every component a definition reaches (directly, or through compound and point
|
||||
/// components) is kept, as are the definitions; dictionary entries that named a dropped
|
||||
/// component go with it. Returns how many were left out.
|
||||
fn drop_orphaned_dgn_components(doc: &mut acadrust::CadDocument) -> usize {
|
||||
use acadrust::objects::{DgnLineStyleData, ObjectType};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
// Each component's references, and the definitions' root components to start from.
|
||||
let mut refs: HashMap<acadrust::Handle, Vec<acadrust::Handle>> = HashMap::new();
|
||||
let mut stack: Vec<acadrust::Handle> = Vec::new();
|
||||
for (h, o) in &doc.objects {
|
||||
let ObjectType::DgnLineStyle(ls) = o else { continue };
|
||||
match &ls.data {
|
||||
DgnLineStyleData::Definition { root_component, .. } => stack.push(*root_component),
|
||||
DgnLineStyleData::Component { component, .. } => {
|
||||
refs.insert(*h, component.references());
|
||||
}
|
||||
DgnLineStyleData::Registered { .. } => {}
|
||||
}
|
||||
}
|
||||
if refs.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
// Each component is visited once, so cycles and shared subtrees end.
|
||||
let mut used: HashSet<acadrust::Handle> = HashSet::new();
|
||||
while let Some(h) = stack.pop() {
|
||||
if let Some(r) = refs.get(&h)
|
||||
&& used.insert(h)
|
||||
{
|
||||
stack.extend(r.iter().copied());
|
||||
}
|
||||
}
|
||||
let orphans: HashSet<acadrust::Handle> = refs.into_keys().filter(|h| !used.contains(h)).collect();
|
||||
if orphans.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
doc.objects.retain(|h, _| !orphans.contains(h));
|
||||
doc.dgn_ls_components.retain(|h, _| !orphans.contains(h));
|
||||
for o in doc.objects.values_mut() {
|
||||
let ObjectType::Dictionary(d) = o else { continue };
|
||||
if d.entries.iter().any(|(_, e)| orphans.contains(e)) {
|
||||
d.entries.retain(|(_, e)| !orphans.contains(e));
|
||||
let keys: HashSet<&str> = d.entries.iter().map(|(k, _)| k.as_str()).collect();
|
||||
d.hard_owner_entries.retain(|k| keys.contains(k.as_str()));
|
||||
}
|
||||
}
|
||||
orphans.len()
|
||||
}
|
||||
|
||||
/// Leave out what acadrust can't write as this DWG version: other programs' custom entities
|
||||
/// and objects without raw DWG data of that version. acadrust 0.6.4 refuses the whole file
|
||||
/// for one of them (0.6.3 left them out); CADCraft already tells the user which entity types
|
||||
/// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many.
|
||||
fn drop_unwritable(doc: &mut acadrust::CadDocument) -> usize {
|
||||
let version = doc.version;
|
||||
let unwritable: Vec<acadrust::Handle> = doc
|
||||
.entities()
|
||||
.filter_map(|e| match e {
|
||||
acadrust::entities::EntityType::Unknown(u)
|
||||
if u.raw_dwg_data.is_none() || u.dwg_source_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 =>
|
||||
{
|
||||
Some(u.common.handle)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for h in &unwritable {
|
||||
doc.remove_entity(*h);
|
||||
}
|
||||
let objects: Vec<acadrust::Handle> = doc
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|(h, o)| match o {
|
||||
acadrust::objects::ObjectType::Unknown { raw_dwg_data, raw_dwg_version, .. }
|
||||
if raw_dwg_data.is_none() || raw_dwg_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 =>
|
||||
{
|
||||
Some(*h)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for h in &objects {
|
||||
doc.objects.remove(h);
|
||||
}
|
||||
unwritable.len() + objects.len()
|
||||
}
|
||||
|
||||
/// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of
|
||||
/// the HEADER section: (name, group code, value).
|
||||
fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 7] {
|
||||
[
|
||||
("$ANGBASE", 50, h.angle_base.to_string()),
|
||||
// DWG holds radians; `$ANGBASE` is in degrees.
|
||||
("$ANGBASE", 50, h.angle_base.to_degrees().to_string()),
|
||||
("$ANGDIR", 70, h.angle_direction.to_string()),
|
||||
("$FILLETRAD", 40, h.fillet_radius.to_string()),
|
||||
("$CHAMFERA", 40, h.chamfer_distance_a.to_string()),
|
||||
@@ -146,28 +460,206 @@ mod native {
|
||||
/// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004
|
||||
/// (AC1018).
|
||||
pub fn dxf_to_dwg(dxf: &[u8]) -> Result<Vec<u8>, String> {
|
||||
convert(dxf, None)
|
||||
}
|
||||
|
||||
/// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"),
|
||||
/// whatever version the DXF declares.
|
||||
pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result<Vec<u8>, String> {
|
||||
let v = match version.trim().to_ascii_uppercase().as_str() {
|
||||
"AC1015" => acadrust::DxfVersion::AC1015,
|
||||
"AC1018" => acadrust::DxfVersion::AC1018,
|
||||
"AC1021" => acadrust::DxfVersion::AC1021,
|
||||
"AC1024" => acadrust::DxfVersion::AC1024,
|
||||
"AC1027" => acadrust::DxfVersion::AC1027,
|
||||
"AC1032" => acadrust::DxfVersion::AC1032,
|
||||
_ => return Err(super::unsupported(version)),
|
||||
};
|
||||
convert(dxf, Some(v))
|
||||
}
|
||||
|
||||
/// The current dimension and text styles' names from their handles: a DWG stores the
|
||||
/// handles, and the reader leaves the names at "Standard", so a drawing reopened from DWG
|
||||
/// lost its current dimension style (#1051).
|
||||
fn current_style_names(doc: &mut acadrust::CadDocument) {
|
||||
let h = doc.header.current_dimstyle_handle;
|
||||
if let Some(n) = doc.dim_styles.iter().find(|ds| ds.handle == h && !h.is_null()).map(|ds| ds.name.clone()) {
|
||||
doc.header.current_dimstyle_name = n;
|
||||
}
|
||||
let h = doc.header.current_text_style_handle;
|
||||
if let Some(n) = doc.text_styles.iter().find(|ts| ts.handle == h && !h.is_null()).map(|ts| ts.name.clone()) {
|
||||
doc.header.current_text_style_name = n;
|
||||
}
|
||||
}
|
||||
|
||||
/// The current dimension style (`$DIMSTYLE`) by its name: the DXF gives the name, and the
|
||||
/// handle read with it needn't be the style's in the document, in which case the DWG writer
|
||||
/// fell back to Standard and AutoCAD opened the drawing with Standard current (#1051).
|
||||
fn current_dimstyle(doc: &mut acadrust::CadDocument) {
|
||||
let name = doc.header.current_dimstyle_name.clone();
|
||||
if let Some(h) = doc.dim_styles.iter().find(|ds| ds.name.eq_ignore_ascii_case(&name)).map(|ds| ds.handle) {
|
||||
doc.header.current_dimstyle_handle = h;
|
||||
}
|
||||
}
|
||||
|
||||
/// The current text style (`$TEXTSTYLE`) by its name, the same way as [`current_dimstyle`]:
|
||||
/// the handle read with the DXF needn't be the style's in the document, in which case the DWG
|
||||
/// writer fell back to Standard and AutoCAD opened the drawing with Standard current (#1650).
|
||||
fn current_text_style(doc: &mut acadrust::CadDocument) {
|
||||
let name = doc.header.current_text_style_name.clone();
|
||||
if let Some(h) = doc.text_styles.iter().find(|ts| ts.name.eq_ignore_ascii_case(&name)).map(|ts| ts.handle) {
|
||||
doc.header.current_text_style_handle = h;
|
||||
}
|
||||
}
|
||||
|
||||
fn convert(dxf: &[u8], version: Option<acadrust::DxfVersion>) -> Result<Vec<u8>, String> {
|
||||
// Reject a pathologically large DXF before handing it to the third-party decoder, which
|
||||
// allocates tables and section buffers from the input's declared sizes and cannot be
|
||||
// interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder
|
||||
// runs inside `catch_unwind` so a decode failure is reported rather than crashing.
|
||||
if dxf.len() > Limits::DEFAULT.max_dxf_bytes {
|
||||
return Err(format!(
|
||||
"DXF: the input is {}, larger than the {} CADCraft converts to DWG",
|
||||
mb(dxf.len() as u64),
|
||||
mb(Limits::DEFAULT.max_dxf_bytes as u64)
|
||||
));
|
||||
}
|
||||
let data = dxf.to_vec();
|
||||
let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read()))
|
||||
.map_err(|_| "the DXF→DWG conversion failed".to_string())?
|
||||
.map_err(|e| format!("DXF: {e}"))?;
|
||||
// Write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG has no true colours, transparency,
|
||||
// table styles or gradients, and readers can't tell its layouts apart reliably. The DXF
|
||||
// stays R2000; only the DWG is newer.
|
||||
if doc.version < MIN_DWG_VERSION {
|
||||
doc.version = MIN_DWG_VERSION;
|
||||
match version {
|
||||
Some(v) => doc.version = v,
|
||||
// Without a version asked for, write at least AutoCAD 2004 (AC1018) DWG: R2000 DWG
|
||||
// has no true colours, transparency, table styles or gradients. The DXF stays R2000;
|
||||
// only the DWG is newer.
|
||||
None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION,
|
||||
None => {}
|
||||
}
|
||||
other_layout_owners(&mut doc);
|
||||
table_style_rows(&mut doc, true);
|
||||
dimension_flags(&mut doc);
|
||||
drop_unwritable(&mut doc);
|
||||
current_dimstyle(&mut doc);
|
||||
add_variable_dictionary(&mut doc);
|
||||
current_text_style(&mut doc);
|
||||
std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc)))
|
||||
.map_err(|_| "the DWG writer failed on this drawing".to_string())?
|
||||
.map_err(|e| format!("DWG write: {e}"))
|
||||
}
|
||||
|
||||
/// AutoCAD's entry name for the drawing variables dictionary (the DXF Reference calls it the
|
||||
/// ACDBVARIABLEDICTIONARY; dictionary keys are case-insensitive).
|
||||
const VARIABLE_DICTIONARY: &str = "AcDbVariableDictionary";
|
||||
|
||||
/// A style or scale name, or `default` when the drawing has none.
|
||||
fn name_or_default(name: &str, default: &str) -> String {
|
||||
let name = name.trim();
|
||||
if name.is_empty() { default.to_string() } else { name.to_string() }
|
||||
}
|
||||
|
||||
/// A drawing variable's value as text, or `default` when the header holds a value the
|
||||
/// variable doesn't accept (a hostile file can put any integer in it).
|
||||
fn variable_value(value: i16, valid: &[i16], default: i16) -> String {
|
||||
if valid.contains(&value) { value.to_string() } else { default.to_string() }
|
||||
}
|
||||
|
||||
/// Add the drawing variables dictionary AutoCAD always writes into the named object
|
||||
/// dictionary, with the variables it keeps there, when the drawing has none (#1813).
|
||||
/// Vectric Aspire 10.5 reads a 2004 (AC1018) DWG without it as empty ("No data was imported
|
||||
/// from the DXF / DWG file"), though it reads the same drawing as DXF — which has no such
|
||||
/// dictionary either, as CADCraft's and ezdxf's writers don't make one. AutoCAD's AC1032 DWGs
|
||||
/// read there without it, so newer output is left as it was, and a dictionary the drawing
|
||||
/// does have keeps its own entries and values.
|
||||
fn add_variable_dictionary(doc: &mut acadrust::CadDocument) {
|
||||
use acadrust::objects::{Dictionary, DictionaryVariable, ObjectType};
|
||||
if doc.version >= acadrust::DxfVersion::AC1032 {
|
||||
return;
|
||||
}
|
||||
let root_handle = doc.header.named_objects_dict_handle;
|
||||
match doc.objects.get(&root_handle) {
|
||||
Some(ObjectType::Dictionary(root)) => {
|
||||
if root.get(VARIABLE_DICTIONARY).is_some() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
// The variables AutoCAD writes for a drawing with default styles and a 1:1 annotation
|
||||
// scale. DIMASSOC and HIDETEXT keep the drawing's own header values; LAYEREVAL and
|
||||
// LAYERNOTIFY have no DXF header variable.
|
||||
let variables = [
|
||||
("CMLEADERSTYLE", name_or_default(&doc.header.current_mleader_style_name, "Standard")),
|
||||
("CTABLESTYLE", name_or_default(&doc.header.current_table_style_name, "Standard")),
|
||||
("CANNOSCALE", name_or_default(&doc.header.current_annotation_scale, "1:1")),
|
||||
("DIMASSOC", variable_value(doc.header.dimension_associativity, &[0, 1, 2], 2)),
|
||||
("HIDETEXT", variable_value(doc.header.hide_text, &[0, 1], 1)),
|
||||
("LAYEREVAL", "0".to_string()),
|
||||
("LAYERNOTIFY", "0".to_string()),
|
||||
];
|
||||
let dictionary_handle = doc.allocate_handle();
|
||||
let mut dictionary = Dictionary::new();
|
||||
dictionary.handle = dictionary_handle;
|
||||
dictionary.owner = root_handle;
|
||||
for (name, value) in variables {
|
||||
let handle = doc.allocate_handle();
|
||||
let mut variable = DictionaryVariable::new(name, &value);
|
||||
variable.handle = handle;
|
||||
variable.owner_handle = dictionary_handle;
|
||||
dictionary.add_entry(name, handle);
|
||||
doc.objects.insert(handle, ObjectType::DictionaryVariable(variable));
|
||||
}
|
||||
doc.objects.insert(dictionary_handle, ObjectType::Dictionary(dictionary));
|
||||
if let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&root_handle) {
|
||||
root.add_entry(VARIABLE_DICTIONARY, dictionary_handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entities of a layout other than the one in `*Paper_Space` are written owned by their block
|
||||
/// (entity mode 0, with its handle). acadrust writes every paper-space entity with mode 1,
|
||||
/// "paper space", which AutoCAD reads as the `*Paper_Space` block's: everything drawn on a
|
||||
/// second layout landed on the first one, and the second stayed empty (#1057).
|
||||
fn other_layout_owners(doc: &mut acadrust::CadDocument) {
|
||||
let others: std::collections::HashSet<acadrust::Handle> = doc
|
||||
.block_records
|
||||
.iter()
|
||||
.filter(|br| {
|
||||
let n = br.name.to_ascii_uppercase();
|
||||
n.len() > 12 && n.starts_with("*PAPER_SPACE") && n[12..].bytes().all(|b| b.is_ascii_digit())
|
||||
})
|
||||
.map(|br| br.handle)
|
||||
.collect();
|
||||
if others.is_empty() {
|
||||
return;
|
||||
}
|
||||
for e in doc.entities_mut() {
|
||||
let c = e.common_mut();
|
||||
if others.contains(&c.owner_handle) {
|
||||
c.entity_mode = Some(0);
|
||||
}
|
||||
}
|
||||
acadrust::DwgWriter::write_to_vec(&doc).map_err(|e| format!("DWG write: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{dwg_to_dxf, dwg_to_dxf_with, dxf_to_dwg};
|
||||
pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as};
|
||||
|
||||
/// The error for a DWG version CADCraft can't write.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
fn unsupported(version: &str) -> String {
|
||||
let list: Vec<&str> = VERSIONS.iter().map(|(_, year)| *year).collect();
|
||||
format!("DWG version `{version}` can't be written (CADCraft writes {})", list.join(", "))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn dwg_to_dxf(_bytes: &[u8]) -> Result<Vec<u8>, String> {
|
||||
Err("DWG files can't be opened in the web build yet; save as DXF".into())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn dwg_to_dxf_noted(_bytes: &[u8], _limits: Limits) -> Result<(Vec<u8>, Vec<String>), String> {
|
||||
Err("DWG files can't be opened in the web build yet; save as DXF".into())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result<Vec<u8>, String> {
|
||||
Err("DWG files can't be opened in the web build yet; save as DXF".into())
|
||||
}
|
||||
@@ -175,6 +667,10 @@ pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result<Vec<u8>, String
|
||||
pub fn dxf_to_dwg(_dxf: &[u8]) -> Result<Vec<u8>, String> {
|
||||
Err("DWG files can't be written in the web build yet; save as DXF".into())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result<Vec<u8>, String> {
|
||||
Err("DWG files can't be written in the web build yet; save as DXF".into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -187,9 +683,232 @@ mod tests {
|
||||
assert_eq!(version(b"AC1018xxxx").as_deref(), Some("AC1018"));
|
||||
}
|
||||
|
||||
/// A DXF with ROMANS as `$TEXTSTYLE` gives a DWG whose current text style is ROMANS, not
|
||||
/// Standard: the DXF names the style, and the handle read with it was Standard's (#1650).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn current_text_style_reaches_the_dwg() {
|
||||
let header = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 9\n$TEXTSTYLE\n 7\nROMANS\n 0\nENDSEC\n";
|
||||
let style = " 0\nSTYLE\n 5\n1F0\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nROMANS\n 70\n0\n";
|
||||
let style = format!("{style} 40\n0\n 41\n1\n 50\n0\n 71\n0\n 42\n2.5\n 3\nromans.shx\n 4\n\n");
|
||||
let dxf = format!("{header} 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nSTYLE\n 70\n1\n{style} 0\nENDTAB\n 0\nENDSEC\n 0\nEOF\n");
|
||||
let dwg = dxf_to_dwg(dxf.as_bytes()).unwrap();
|
||||
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap();
|
||||
let romans = doc.text_styles.iter().find(|ts| ts.name == "ROMANS").map(|ts| ts.handle);
|
||||
assert!(romans.is_some(), "ROMANS is missing from the DWG");
|
||||
assert_eq!(Some(doc.header.current_text_style_handle), romans);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_is_an_error_not_a_crash() {
|
||||
assert!(dwg_to_dxf(b"AC1032 this is not a dwg file at all").is_err());
|
||||
assert!(dwg_to_dxf(b"").is_err());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn dxf_to_dwg_rejects_garbage_without_crashing() {
|
||||
// The DXF→DWG path runs the third-party reader inside catch_unwind and reports failures
|
||||
// rather than crashing (and rejects oversized input before decoding).
|
||||
assert!(dxf_to_dwg(b"not a dxf file").is_err());
|
||||
assert!(dxf_to_dwg(b"").is_err());
|
||||
}
|
||||
|
||||
/// A DXF with one DIMENSION per (text, group 70, subclass, points) row.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn dims_dxf(dims: &[(&str, i64, &str, &[(i32, [f64; 2])])]) -> String {
|
||||
let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n");
|
||||
for (text, flags, sub, pts) in dims {
|
||||
s += " 0\nDIMENSION\n 8\n0\n100\nAcDbEntity\n100\nAcDbDimension\n 10\n0\n 20\n0\n 30\n0\n";
|
||||
s += &format!(" 11\n50\n 21\n-20\n 31\n0\n 70\n{flags}\n 1\n{text}\n 3\nStandard\n100\n{sub}\n");
|
||||
for (code, [x, y]) in pts.iter() {
|
||||
s += &format!("{code:>3}\n{x}\n{:>3}\n{y}\n{:>3}\n0\n", code + 10, code + 20);
|
||||
}
|
||||
}
|
||||
s + " 0\nENDSEC\n 0\nEOF\n"
|
||||
}
|
||||
|
||||
/// DWG stores DXF group 70's bit 128 inverted, in bit 0 of the dimension flags byte (set:
|
||||
/// the text is at its default position), and bit 32 in bit 1 (ODA DWG specification, common
|
||||
/// dimension data). The bytes are read back raw, so a reader that inverts bit 0 the same way
|
||||
/// as the writer can't hide a wrong byte.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn dimension_text_position_flags_reach_the_dwg_as_autocad_reads_them() {
|
||||
let linear: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [100.0, 0.0])];
|
||||
let radius: &[(i32, [f64; 2])] = &[(15, [10.0, 0.0])];
|
||||
let angular: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [10.0, 0.0]), (15, [0.0, 0.0]), (16, [0.0, 10.0])];
|
||||
let kinds = [
|
||||
(0, "AcDbAlignedDimension", linear),
|
||||
(1, "AcDbAlignedDimension", linear),
|
||||
(4, "AcDbRadialDimension", radius),
|
||||
(2, "AcDb2LineAngularDimension", angular),
|
||||
];
|
||||
let mut dims = Vec::new();
|
||||
for (ty, sub, pts) in kinds {
|
||||
dims.push(("HOME", ty | 32, sub, pts));
|
||||
dims.push(("MOVED", ty | 32 | 128, sub, pts));
|
||||
}
|
||||
let dwg = dxf_to_dwg(dims_dxf(&dims).as_bytes()).unwrap();
|
||||
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap();
|
||||
let mut seen = Vec::new();
|
||||
for e in doc.entities() {
|
||||
let acadrust::entities::EntityType::Dimension(d) = e else { continue };
|
||||
let (text, byte) = (d.base().text_override().unwrap_or_default(), d.base().dwg_flags_byte);
|
||||
seen.push((text.to_string(), byte & 0x03));
|
||||
assert_eq!(byte & 0x02, 0x02, "{text} {:?}: bit 32 of group 70 is lost (flags byte {byte:#04x})", d.base().dimension_type);
|
||||
let default_pos = text == "HOME";
|
||||
assert_eq!(byte & 0x01 != 0, default_pos, "{text} {:?}: flags byte {byte:#04x}", d.base().dimension_type);
|
||||
}
|
||||
for text in ["HOME", "MOVED"] {
|
||||
assert_eq!(seen.iter().filter(|(t, _)| t == text).count(), 4, "{seen:?}");
|
||||
}
|
||||
|
||||
// And CADCraft reads its own DWG back as it wrote it: 128 only on the moved texts.
|
||||
let dxf = String::from_utf8(dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
let mut flags = Vec::new();
|
||||
for rec in lines.chunks(2).collect::<Vec<_>>().split(|p| p.first() == Some(&"0")) {
|
||||
let value = |code: &str| rec.iter().find(|p| p.first() == Some(&code)).and_then(|p| p.get(1).copied());
|
||||
if let (Some(text @ ("HOME" | "MOVED")), Some(v)) = (value("1"), value("70")) {
|
||||
flags.push((text, v.parse::<i64>().unwrap_or(-1) & 128));
|
||||
}
|
||||
}
|
||||
assert_eq!(flags.len(), 8, "{flags:?}");
|
||||
assert!(flags.iter().all(|(l, f)| (*f == 128) == (*l == "MOVED")), "{flags:?}");
|
||||
}
|
||||
|
||||
/// The handles a DXF text refers to or gives its records (groups 5, 105 and 330–369).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn dxf_handles(dxf: &str) -> std::collections::HashSet<u64> {
|
||||
let lines: Vec<&str> = dxf.lines().collect();
|
||||
lines
|
||||
.chunks(2)
|
||||
.filter_map(|p| match p {
|
||||
[c, v] if matches!(c.trim().parse::<i32>(), Ok(5 | 105 | 330..=369)) => u64::from_str_radix(v.trim(), 16).ok(),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Issue #1482: a DWG that once came from MicroStation can carry hundreds of thousands of DGN
|
||||
/// line style components no definition uses (a real 83 MB site plan: 888,483 of 889,053, a
|
||||
/// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and
|
||||
/// their dictionary entries with them; the definition and every component it reaches —
|
||||
/// through compound and point components, around a cycle — are kept.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn orphaned_dgn_line_style_components_are_left_out() {
|
||||
use acadrust::objects::*;
|
||||
let mut doc = acadrust::CadDocument::new();
|
||||
let container = doc.allocate_handle();
|
||||
let nod = doc.header.named_objects_dict_handle;
|
||||
let Some(ObjectType::Dictionary(root)) = doc.objects.get_mut(&nod) else { panic!("no named object dictionary") };
|
||||
root.entries.push(("ACAD_DGNLINESTYLECOMP".into(), container));
|
||||
let pattern = || DgnLsStrokePattern {
|
||||
has_iteration_limit: false,
|
||||
is_single_segment: false,
|
||||
iteration_limit: 0,
|
||||
auto_phase: 0.0,
|
||||
phase: 0.0,
|
||||
phase_mode: DgnLsPhaseMode::Distance,
|
||||
strokes: vec![DgnLsStroke {
|
||||
is_dash: true,
|
||||
bypass_corner: false,
|
||||
can_be_scaled: true,
|
||||
invert_at_origin: false,
|
||||
invert_at_end: false,
|
||||
length: 2.5,
|
||||
start_width: 0.0,
|
||||
end_width: 0.0,
|
||||
width_mode: 0,
|
||||
cap_mode: 0,
|
||||
}],
|
||||
};
|
||||
let kind = |c: &DgnLsComponentData| match c {
|
||||
DgnLsComponentData::Symbol(_) => DgnLsComponentType::Symbol,
|
||||
DgnLsComponentData::Compound(_) => DgnLsComponentType::Compound,
|
||||
DgnLsComponentData::Stroke(_) => DgnLsComponentType::Stroke,
|
||||
DgnLsComponentData::Point(_) => DgnLsComponentType::Point,
|
||||
DgnLsComponentData::Internal(_) => DgnLsComponentType::Internal,
|
||||
};
|
||||
let compound = |of: &[acadrust::Handle]| {
|
||||
DgnLsComponentData::Compound(DgnLsCompoundComponent {
|
||||
entries: of.iter().map(|&component| DgnLsCompoundEntry { component, offset: 0.0 }).collect(),
|
||||
})
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
let mut put = |doc: &mut acadrust::CadDocument, h: acadrust::Handle, data: DgnLineStyleData| {
|
||||
entries.push((format!("{:X}", h.value()), h));
|
||||
let reactors = vec![container];
|
||||
doc.objects
|
||||
.insert(h, ObjectType::DgnLineStyle(DgnLineStyleObject { handle: h, owner: container, reactors, xdictionary_handle: None, data }));
|
||||
};
|
||||
let component = |c: DgnLsComponentData| DgnLineStyleData::Component {
|
||||
kind: kind(&c),
|
||||
description: "dash".into(),
|
||||
version: 1,
|
||||
component_uid: [7; 16],
|
||||
scale: 1.0,
|
||||
property_flags: 0,
|
||||
component: c,
|
||||
properties: vec![],
|
||||
};
|
||||
let h: Vec<acadrust::Handle> = (0..9).map(|_| doc.allocate_handle()).collect();
|
||||
let [def, root, stroke, point, back, orphan, orphan_cycle, internal, shared] = h[..] else { panic!("nine handles") };
|
||||
put(
|
||||
&mut doc,
|
||||
def,
|
||||
DgnLineStyleData::Definition {
|
||||
description: "{ dash }".into(),
|
||||
version: 1,
|
||||
style_number: 1,
|
||||
component_uid: [1; 16],
|
||||
is_continuous: false,
|
||||
unit_definition: 1.0,
|
||||
unit_scale: 1.0,
|
||||
units_type: 0,
|
||||
is_element: false,
|
||||
is_physical: false,
|
||||
is_scale_independent: false,
|
||||
is_snappable: false,
|
||||
root_component: root,
|
||||
properties: vec![],
|
||||
},
|
||||
);
|
||||
// Used: def → root → {stroke, point → shared, back → root (a cycle)}.
|
||||
put(&mut doc, root, component(compound(&[stroke, point, back])));
|
||||
put(&mut doc, stroke, component(DgnLsComponentData::Stroke(pattern())));
|
||||
put(&mut doc, point, component(DgnLsComponentData::Point(DgnLsPointComponent { stroke_component: shared, symbols: vec![] })));
|
||||
put(&mut doc, back, component(compound(&[root])));
|
||||
put(&mut doc, shared, component(DgnLsComponentData::Stroke(pattern())));
|
||||
// Orphans: an internal component, and two compounds that refer to each other and to a
|
||||
// used component (which stays).
|
||||
let pattern_internal =
|
||||
DgnLsInternalComponent { pattern: pattern(), internal_version: 0, hardware_style: 0, is_hardware_style: false, line_code: 0 };
|
||||
put(&mut doc, internal, component(DgnLsComponentData::Internal(pattern_internal)));
|
||||
put(&mut doc, orphan, component(compound(&[orphan_cycle, shared])));
|
||||
put(&mut doc, orphan_cycle, component(compound(&[orphan])));
|
||||
let mut dict = Dictionary::new();
|
||||
dict.handle = container;
|
||||
dict.owner = nod;
|
||||
dict.entries = entries;
|
||||
doc.objects.insert(container, ObjectType::Dictionary(dict));
|
||||
let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap();
|
||||
|
||||
let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap();
|
||||
let dxf = String::from_utf8(dxf).unwrap();
|
||||
let handles = dxf_handles(&dxf);
|
||||
for kept in [def, root, stroke, point, back, shared] {
|
||||
assert!(handles.contains(&kept.value()), "{:X} was left out", kept.value());
|
||||
}
|
||||
for gone in [internal, orphan, orphan_cycle] {
|
||||
assert!(!handles.contains(&gone.value()), "{:X} was kept or is still referred to", gone.value());
|
||||
}
|
||||
let lines: Vec<&str> = dxf.lines().collect();
|
||||
let ls: Vec<&str> = lines.chunks(2).filter_map(|p| p.get(1).filter(|_| p[0].trim() == "0" && p[1].starts_with("LS")).copied()).collect();
|
||||
assert_eq!(ls.iter().filter(|t| t.ends_with("COMPONENT")).count(), 5, "{ls:?}");
|
||||
assert!(ls.contains(&"LSDEFINITION") && !ls.contains(&"LSINTERNALCOMPONENT"), "{ls:?}");
|
||||
assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cadcraft-dxf"
|
||||
description = "Standalone DXF tag reader/writer (ASCII and binary), from the published DXF reference"
|
||||
description = "Standalone DXF tag reader/writer (ASCII and binary, pre-2007 code pages), from the published DXF reference"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -10,3 +10,5 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
encoding_rs = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Text decoding for DXF files.
|
||||
//!
|
||||
//! R2007 (AC1021) and later DXF files are UTF-8. Older ones store text in the code page named by
|
||||
//! the `$DWGCODEPAGE` header variable (`ANSI_1252`, `ANSI_932`, `DOS850`, …); characters outside
|
||||
//! it are written as `\U+XXXX` (any character) or `\M+nXXXX` (a double-byte character of an East
|
||||
//! Asian code page) escapes, which [`crate::parse`] decodes after the bytes.
|
||||
//!
|
||||
//! The Windows, ISO and East Asian code pages are decoded with `encoding_rs`; DOS 437, 850 and
|
||||
//! 852 with the tables below (the upper halves of the IBM PC code pages; the lower halves are
|
||||
//! ASCII). Decoding never fails: a byte sequence that is invalid in the code page (a truncated
|
||||
//! double-byte character, an unassigned byte) becomes U+FFFD and the bytes after it decode
|
||||
//! normally, so line ends and the group structure survive.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use encoding_rs::Encoding;
|
||||
|
||||
/// How the bytes of a code page become text.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum Decoder {
|
||||
Utf8,
|
||||
Encoding(&'static Encoding),
|
||||
/// Single-byte DOS code page: ASCII, then these 128 characters for bytes 0x80–0xFF.
|
||||
Table(&'static [char; 128]),
|
||||
}
|
||||
|
||||
/// The decoder for a `$DWGCODEPAGE` value (case-insensitive), or `None` when CADCraft doesn't
|
||||
/// know the code page.
|
||||
pub(crate) fn decoder(code_page: &str) -> Option<Decoder> {
|
||||
use encoding_rs as e;
|
||||
let name = code_page.trim().to_ascii_uppercase().replace(['-', ' '], "_");
|
||||
let enc = match name.as_str() {
|
||||
"UTF8" | "UTF_8" | "UNICODE" => return Some(Decoder::Utf8),
|
||||
"ASCII" | "ANSI_1252" | "ISO8859_1" | "ISO_8859_1" => e::WINDOWS_1252,
|
||||
"ANSI_874" => e::WINDOWS_874,
|
||||
"ANSI_932" | "DOS932" | "SHIFT_JIS" => e::SHIFT_JIS,
|
||||
"ANSI_936" | "GB2312" | "GBK" => e::GBK,
|
||||
"ANSI_949" | "KSC5601" | "KOREAN" => e::EUC_KR,
|
||||
"ANSI_950" | "BIG5" => e::BIG5,
|
||||
"ANSI_1250" => e::WINDOWS_1250,
|
||||
"ANSI_1251" => e::WINDOWS_1251,
|
||||
"ANSI_1253" => e::WINDOWS_1253,
|
||||
"ANSI_1254" | "ISO8859_9" | "ISO_8859_9" => e::WINDOWS_1254,
|
||||
"ANSI_1255" => e::WINDOWS_1255,
|
||||
"ANSI_1256" => e::WINDOWS_1256,
|
||||
"ANSI_1257" => e::WINDOWS_1257,
|
||||
"ANSI_1258" => e::WINDOWS_1258,
|
||||
"ISO8859_2" | "ISO_8859_2" => e::ISO_8859_2,
|
||||
"ISO8859_3" | "ISO_8859_3" => e::ISO_8859_3,
|
||||
"ISO8859_4" | "ISO_8859_4" => e::ISO_8859_4,
|
||||
"ISO8859_5" | "ISO_8859_5" => e::ISO_8859_5,
|
||||
"ISO8859_6" | "ISO_8859_6" => e::ISO_8859_6,
|
||||
"ISO8859_7" | "ISO_8859_7" => e::ISO_8859_7,
|
||||
"ISO8859_8" | "ISO_8859_8" => e::ISO_8859_8,
|
||||
"DOS866" => e::IBM866,
|
||||
"MACINTOSH" | "MAC_ROMAN" => e::MACINTOSH,
|
||||
"DOS437" => return Some(Decoder::Table(&DOS437)),
|
||||
"DOS850" => return Some(Decoder::Table(&DOS850)),
|
||||
"DOS852" => return Some(Decoder::Table(&DOS852)),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Decoder::Encoding(enc))
|
||||
}
|
||||
|
||||
/// Decode `bytes` from the code page `code_page` names (a `$DWGCODEPAGE` value such as
|
||||
/// `ANSI_1251`), or `None` when CADCraft doesn't know that code page. Invalid sequences become
|
||||
/// U+FFFD; escapes (`\U+XXXX`, `\M+nXXXX`) are left as they are.
|
||||
pub fn decode_code_page(bytes: &[u8], code_page: &str) -> Option<String> {
|
||||
decoder(code_page).map(|d| decode(bytes, d).into_owned())
|
||||
}
|
||||
|
||||
/// Decode bytes with a decoder. UTF-8 that isn't valid falls back to Windows-1252.
|
||||
pub(crate) fn decode(bytes: &[u8], d: Decoder) -> Cow<'_, str> {
|
||||
match d {
|
||||
Decoder::Utf8 => match std::str::from_utf8(bytes) {
|
||||
Ok(s) => Cow::Borrowed(s),
|
||||
Err(_) => encoding_rs::WINDOWS_1252.decode_without_bom_handling(bytes).0,
|
||||
},
|
||||
Decoder::Encoding(e) => e.decode_without_bom_handling(bytes).0,
|
||||
Decoder::Table(t) => match std::str::from_utf8(bytes) {
|
||||
Ok(s) if s.is_ascii() => Cow::Borrowed(s),
|
||||
_ => Cow::Owned(
|
||||
bytes
|
||||
.iter()
|
||||
.map(|&b| if b.is_ascii() { char::from(b) } else { t.get(usize::from(b & 0x7F)).copied().unwrap_or('\u{FFFD}') })
|
||||
.collect(),
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `$DWGCODEPAGE` value of an ASCII DXF file: the line two lines after a `$DWGCODEPAGE`
|
||||
/// line (the group code `3` between them), looked for in the HEADER section only (the scan stops
|
||||
/// at the first `ENDSEC`). Works on the raw bytes, before they are decoded.
|
||||
fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> {
|
||||
let mut lines = bytes.split(|&b| b == b'\n').map(<[u8]>::trim_ascii);
|
||||
while let Some(line) = lines.next() {
|
||||
if line == b"ENDSEC" {
|
||||
return None;
|
||||
}
|
||||
if line.eq_ignore_ascii_case(b"$DWGCODEPAGE") {
|
||||
return match (lines.next(), lines.next()) {
|
||||
(Some(b"3"), Some(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Decode a whole ASCII DXF file. Valid UTF-8 is read as UTF-8: R2007+ files, pure-ASCII files,
|
||||
/// and older files from writers that ignored the code page. Anything else is decoded from the
|
||||
/// file's `$DWGCODEPAGE`, or from Windows-1252 (the usual `ANSI_1252`) when the header has none
|
||||
/// or names a code page CADCraft doesn't know, which is logged as a warning.
|
||||
pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> {
|
||||
if let Ok(s) = std::str::from_utf8(bytes) {
|
||||
return Cow::Borrowed(s);
|
||||
}
|
||||
let d = match ascii_code_page(bytes) {
|
||||
Some(name) => {
|
||||
let name = String::from_utf8_lossy(name);
|
||||
decoder(&name).unwrap_or_else(|| {
|
||||
log::warn!("DXF: unknown code page `{name}`; reading the text as ANSI_1252");
|
||||
Decoder::Utf8
|
||||
})
|
||||
}
|
||||
None => Decoder::Utf8,
|
||||
};
|
||||
decode(bytes, d)
|
||||
}
|
||||
|
||||
/// The text state of a binary DXF file, learnt from its header as the tags go by: `$ACADVER`
|
||||
/// (R2007+ strings are UTF-8) and `$DWGCODEPAGE` (the code page of older files). Both come
|
||||
/// first in the HEADER section and are ASCII, so every later string is decoded right.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct BinaryText {
|
||||
/// The header variable whose value comes next (after a group 9).
|
||||
var: Option<HeaderVar>,
|
||||
utf8: bool,
|
||||
code_page: Option<Decoder>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum HeaderVar {
|
||||
AcadVer,
|
||||
CodePage,
|
||||
}
|
||||
|
||||
impl BinaryText {
|
||||
/// Decode one string value of group `code` and update the state from it. Strings of R2007+
|
||||
/// files, and of files without a code page, are UTF-8 when valid (else Windows-1252); older
|
||||
/// files' strings are in their code page.
|
||||
pub(crate) fn string(&mut self, code: i32, raw: &[u8]) -> String {
|
||||
let d = if self.utf8 { Decoder::Utf8 } else { self.code_page.unwrap_or(Decoder::Utf8) };
|
||||
let s = decode(raw, d).into_owned();
|
||||
match (code, self.var.take()) {
|
||||
(9, _) => {
|
||||
self.var = match s.trim() {
|
||||
"$ACADVER" => Some(HeaderVar::AcadVer),
|
||||
"$DWGCODEPAGE" => Some(HeaderVar::CodePage),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
(1, Some(HeaderVar::AcadVer)) => self.utf8 = is_utf8_version(&s),
|
||||
(3, Some(HeaderVar::CodePage)) => {
|
||||
self.code_page = decoder(&s);
|
||||
if self.code_page.is_none() {
|
||||
log::warn!("DXF: unknown code page `{}`; reading the text as ANSI_1252", s.trim());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// True for an `$ACADVER` of R2007 (AC1021) or later, whose text is UTF-8.
|
||||
fn is_utf8_version(acadver: &str) -> bool {
|
||||
acadver.trim().strip_prefix("AC").and_then(|n| n.parse::<u32>().ok()).is_some_and(|n| n >= 1021)
|
||||
}
|
||||
|
||||
/// The double-byte code page of a `\M+n` escape: 1 Japanese (Shift-JIS), 2 Traditional Chinese
|
||||
/// (Big5), 3 Korean (Wansung), 5 Simplified Chinese (GB 2312). 4 (Korean Johab) is not
|
||||
/// supported, so its escapes stay literal.
|
||||
pub(crate) fn mif_encoding(n: char) -> Option<&'static Encoding> {
|
||||
match n {
|
||||
'1' => Some(encoding_rs::SHIFT_JIS),
|
||||
'2' => Some(encoding_rs::BIG5),
|
||||
'3' => Some(encoding_rs::EUC_KR),
|
||||
'5' => Some(encoding_rs::GBK),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// Generated from the IBM PC code page definitions (bytes 0x80–0xFF in order).
|
||||
const DOS437: [char; 128] = [
|
||||
'\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{00E0}', '\u{00E5}', '\u{00E7}', '\u{00EA}', '\u{00EB}', '\u{00E8}', '\u{00EF}',
|
||||
'\u{00EE}', '\u{00EC}', '\u{00C4}', '\u{00C5}', '\u{00C9}', '\u{00E6}', '\u{00C6}', '\u{00F4}', '\u{00F6}', '\u{00F2}', '\u{00FB}', '\u{00F9}',
|
||||
'\u{00FF}', '\u{00D6}', '\u{00DC}', '\u{00A2}', '\u{00A3}', '\u{00A5}', '\u{20A7}', '\u{0192}', '\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}',
|
||||
'\u{00F1}', '\u{00D1}', '\u{00AA}', '\u{00BA}', '\u{00BF}', '\u{2310}', '\u{00AC}', '\u{00BD}', '\u{00BC}', '\u{00A1}', '\u{00AB}', '\u{00BB}',
|
||||
'\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{2561}', '\u{2562}', '\u{2556}', '\u{2555}', '\u{2563}', '\u{2551}', '\u{2557}',
|
||||
'\u{255D}', '\u{255C}', '\u{255B}', '\u{2510}', '\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{255E}', '\u{255F}',
|
||||
'\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}', '\u{2567}', '\u{2568}', '\u{2564}', '\u{2565}', '\u{2559}',
|
||||
'\u{2558}', '\u{2552}', '\u{2553}', '\u{256B}', '\u{256A}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{258C}', '\u{2590}', '\u{2580}',
|
||||
'\u{03B1}', '\u{00DF}', '\u{0393}', '\u{03C0}', '\u{03A3}', '\u{03C3}', '\u{00B5}', '\u{03C4}', '\u{03A6}', '\u{0398}', '\u{03A9}', '\u{03B4}',
|
||||
'\u{221E}', '\u{03C6}', '\u{03B5}', '\u{2229}', '\u{2261}', '\u{00B1}', '\u{2265}', '\u{2264}', '\u{2320}', '\u{2321}', '\u{00F7}', '\u{2248}',
|
||||
'\u{00B0}', '\u{2219}', '\u{00B7}', '\u{221A}', '\u{207F}', '\u{00B2}', '\u{25A0}', '\u{00A0}',
|
||||
];
|
||||
const DOS850: [char; 128] = [
|
||||
'\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{00E0}', '\u{00E5}', '\u{00E7}', '\u{00EA}', '\u{00EB}', '\u{00E8}', '\u{00EF}',
|
||||
'\u{00EE}', '\u{00EC}', '\u{00C4}', '\u{00C5}', '\u{00C9}', '\u{00E6}', '\u{00C6}', '\u{00F4}', '\u{00F6}', '\u{00F2}', '\u{00FB}', '\u{00F9}',
|
||||
'\u{00FF}', '\u{00D6}', '\u{00DC}', '\u{00F8}', '\u{00A3}', '\u{00D8}', '\u{00D7}', '\u{0192}', '\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}',
|
||||
'\u{00F1}', '\u{00D1}', '\u{00AA}', '\u{00BA}', '\u{00BF}', '\u{00AE}', '\u{00AC}', '\u{00BD}', '\u{00BC}', '\u{00A1}', '\u{00AB}', '\u{00BB}',
|
||||
'\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{00C1}', '\u{00C2}', '\u{00C0}', '\u{00A9}', '\u{2563}', '\u{2551}', '\u{2557}',
|
||||
'\u{255D}', '\u{00A2}', '\u{00A5}', '\u{2510}', '\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{00E3}', '\u{00C3}',
|
||||
'\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}', '\u{00A4}', '\u{00F0}', '\u{00D0}', '\u{00CA}', '\u{00CB}',
|
||||
'\u{00C8}', '\u{0131}', '\u{00CD}', '\u{00CE}', '\u{00CF}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{00A6}', '\u{00CC}', '\u{2580}',
|
||||
'\u{00D3}', '\u{00DF}', '\u{00D4}', '\u{00D2}', '\u{00F5}', '\u{00D5}', '\u{00B5}', '\u{00FE}', '\u{00DE}', '\u{00DA}', '\u{00DB}', '\u{00D9}',
|
||||
'\u{00FD}', '\u{00DD}', '\u{00AF}', '\u{00B4}', '\u{00AD}', '\u{00B1}', '\u{2017}', '\u{00BE}', '\u{00B6}', '\u{00A7}', '\u{00F7}', '\u{00B8}',
|
||||
'\u{00B0}', '\u{00A8}', '\u{00B7}', '\u{00B9}', '\u{00B3}', '\u{00B2}', '\u{25A0}', '\u{00A0}',
|
||||
];
|
||||
const DOS852: [char; 128] = [
|
||||
'\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{016F}', '\u{0107}', '\u{00E7}', '\u{0142}', '\u{00EB}', '\u{0150}', '\u{0151}',
|
||||
'\u{00EE}', '\u{0179}', '\u{00C4}', '\u{0106}', '\u{00C9}', '\u{0139}', '\u{013A}', '\u{00F4}', '\u{00F6}', '\u{013D}', '\u{013E}', '\u{015A}',
|
||||
'\u{015B}', '\u{00D6}', '\u{00DC}', '\u{0164}', '\u{0165}', '\u{0141}', '\u{00D7}', '\u{010D}', '\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}',
|
||||
'\u{0104}', '\u{0105}', '\u{017D}', '\u{017E}', '\u{0118}', '\u{0119}', '\u{00AC}', '\u{017A}', '\u{010C}', '\u{015F}', '\u{00AB}', '\u{00BB}',
|
||||
'\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{00C1}', '\u{00C2}', '\u{011A}', '\u{015E}', '\u{2563}', '\u{2551}', '\u{2557}',
|
||||
'\u{255D}', '\u{017B}', '\u{017C}', '\u{2510}', '\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{0102}', '\u{0103}',
|
||||
'\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}', '\u{00A4}', '\u{0111}', '\u{0110}', '\u{010E}', '\u{00CB}',
|
||||
'\u{010F}', '\u{0147}', '\u{00CD}', '\u{00CE}', '\u{011B}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{0162}', '\u{016E}', '\u{2580}',
|
||||
'\u{00D3}', '\u{00DF}', '\u{00D4}', '\u{0143}', '\u{0144}', '\u{0148}', '\u{0160}', '\u{0161}', '\u{0154}', '\u{00DA}', '\u{0155}', '\u{0170}',
|
||||
'\u{00FD}', '\u{00DD}', '\u{0163}', '\u{00B4}', '\u{00AD}', '\u{02DD}', '\u{02DB}', '\u{02C7}', '\u{02D8}', '\u{00A7}', '\u{00F7}', '\u{00B8}',
|
||||
'\u{00B0}', '\u{00A8}', '\u{02D9}', '\u{0171}', '\u{0158}', '\u{0159}', '\u{25A0}', '\u{00A0}',
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn code_page_names() {
|
||||
let d = |bytes: &[u8], cp: &str| decode_code_page(bytes, cp);
|
||||
assert_eq!(d(b"\xCF\xF0\xE8\xE2\xE5\xF2", "ANSI_1251").as_deref(), Some("Привет"));
|
||||
assert_eq!(d(b"\xCF\xF0\xE8\xE2\xE5\xF2", " ansi_1251 ").as_deref(), Some("Привет"));
|
||||
assert_eq!(d(b"\x90\x7D\x96\xCA", "ANSI_932").as_deref(), Some("図面"));
|
||||
assert_eq!(d(b"\xCD\xBC\xB2\xE3", "GB2312").as_deref(), Some("图层"));
|
||||
assert_eq!(d(b"\xB9\xCF\xBC\x68", "BIG5").as_deref(), Some("圖層"));
|
||||
assert_eq!(d(b"\xB5\xB5\xB8\xE9", "ANSI_949").as_deref(), Some("도면"));
|
||||
assert_eq!(d(b"\xD3\xF7\xDD\xE4\xE9\xEF", "ANSI_1253").as_deref(), Some("Σχέδιο"));
|
||||
assert_eq!(d(b"\xC0\xD2\xBE", "ANSI_874").as_deref(), Some("ภาพ"));
|
||||
assert_eq!(d(b"\x80", "ANSI_1252").as_deref(), Some("€"));
|
||||
// DOS 437 and 850 agree on letters but differ on 0x9B (¢ / ø).
|
||||
assert_eq!(d(b"Gr\x94\xE1e \x9B", "DOS437").as_deref(), Some("Größe ¢"));
|
||||
assert_eq!(d(b"Gr\x94\xE1e \x9B", "dos850").as_deref(), Some("Größe ø"));
|
||||
assert_eq!(d(b"\xBD\xA2\x88w", "DOS852").as_deref(), Some("Żółw"));
|
||||
assert_eq!(d(b"\x91\xAB\xAE\xA9", "DOS866").as_deref(), Some("Слой"));
|
||||
assert_eq!(d("é".as_bytes(), "UTF8").as_deref(), Some("é"));
|
||||
assert_eq!(d(b"x", "ANSI_1361"), None);
|
||||
assert_eq!(d(b"x", "EBCDIC"), None);
|
||||
assert_eq!(d(b"x", ""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_sequences_become_replacement_characters() {
|
||||
// A Shift-JIS lead byte cut off by the line end keeps the line end.
|
||||
assert_eq!(decode_code_page(b"\x90\n1\n", "ANSI_932").as_deref(), Some("\u{FFFD}\n1\n"));
|
||||
assert_eq!(decode_code_page(b"\x90", "ANSI_932").as_deref(), Some("\u{FFFD}"));
|
||||
assert_eq!(decode_code_page(b"\xFF\xFF", "ANSI_936").as_deref(), Some("\u{FFFD}\u{FFFD}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_scan() {
|
||||
let head = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DWGCODEPAGE\n3\nANSI_1251\r\n0\nENDSEC\n";
|
||||
assert_eq!(ascii_code_page(head), Some(&b"ANSI_1251"[..]));
|
||||
// Only the HEADER section counts.
|
||||
assert_eq!(ascii_code_page(b"0\nSECTION\n2\nHEADER\n0\nENDSEC\n9\n$DWGCODEPAGE\n3\nANSI_1251\n"), None);
|
||||
// Wrong group code, or the file ends early.
|
||||
assert_eq!(ascii_code_page(b"9\n$DWGCODEPAGE\n1\nANSI_1251\n"), None);
|
||||
assert_eq!(ascii_code_page(b"9\n$DWGCODEPAGE\n3"), None);
|
||||
assert!(is_utf8_version("AC1021") && is_utf8_version(" AC1032 "));
|
||||
assert!(!is_utf8_version("AC1018") && !is_utf8_version("AC1009") && !is_utf8_version("garbage"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mif_escapes() {
|
||||
let one = |s: &str| crate::parse(format!("1\n{s}\n0\nEOF\n").as_bytes()).unwrap()[0].str();
|
||||
assert_eq!(one("\\M+5BCFE\\M+1907D\\M+2B9CF\\M+3B5B5!"), "件図圖도!");
|
||||
assert_eq!(one("\\M+5BCFE\\U+0021"), "件!");
|
||||
// Johab, unknown code pages, bad hex, short escapes and unassigned codes stay literal.
|
||||
for s in ["\\M+4ABCD", "\\M+9BCFE", "\\M+5GGGG", "\\M+5BC", "\\M+", "\\M+50041", "\\M+5FFFF"] {
|
||||
assert_eq!(one(s), s);
|
||||
}
|
||||
}
|
||||
}
|
||||
+146
-20
@@ -9,6 +9,9 @@
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
mod version;
|
||||
pub use version::Version;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DxfError {
|
||||
#[error("not a DXF file")]
|
||||
@@ -163,14 +166,8 @@ const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0";
|
||||
/// tag list to a few GB; real drawings stay far below (a 10 MB DWG is typically a few million).
|
||||
pub const MAX_TAGS: usize = 50_000_000;
|
||||
|
||||
/// Decode bytes as text: UTF-8 when valid (borrowed, no copy), otherwise Latin-1 (old ANSI_1252
|
||||
/// files).
|
||||
fn decode_text(b: &[u8]) -> std::borrow::Cow<'_, str> {
|
||||
match std::str::from_utf8(b) {
|
||||
Ok(s) => std::borrow::Cow::Borrowed(s),
|
||||
Err(_) => std::borrow::Cow::Owned(b.iter().map(|&c| char::from(c)).collect()),
|
||||
}
|
||||
}
|
||||
mod codepage;
|
||||
pub use codepage::decode_code_page;
|
||||
|
||||
/// Parse a DXF file (ASCII or binary).
|
||||
pub fn parse(bytes: &[u8]) -> Result<Vec<Tag>> {
|
||||
@@ -189,7 +186,7 @@ pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
|
||||
if tags > max_tags {
|
||||
return Err(DxfError::TooLarge { tags, limit: max_tags });
|
||||
}
|
||||
parse_ascii_with_limit(&decode_text(bytes), max_tags)
|
||||
parse_ascii_with_limit(&codepage::decode_ascii_file(bytes), max_tags)
|
||||
}
|
||||
|
||||
/// The four hex digits of a `\U+XXXX` escape starting at `chars[i]`, if there is one.
|
||||
@@ -204,17 +201,41 @@ fn escape_at(chars: &[char], i: usize) -> Option<u32> {
|
||||
hex.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?))
|
||||
}
|
||||
|
||||
/// The character of a `\M+nXXXX` escape starting at `chars[i]`, if there is one: `n` names a
|
||||
/// double-byte code page and `XXXX` is the character's two bytes in hex.
|
||||
fn mif_escape_at(chars: &[char], i: usize) -> Option<char> {
|
||||
if chars.get(i) != Some(&'\\') || chars.get(i + 1) != Some(&'M') || chars.get(i + 2) != Some(&'+') {
|
||||
return None;
|
||||
}
|
||||
let enc = codepage::mif_encoding(*chars.get(i + 3)?)?;
|
||||
let hex = chars.get(i + 4..i + 8)?;
|
||||
if !hex.iter().all(char::is_ascii_hexdigit) {
|
||||
return None;
|
||||
}
|
||||
let code = hex.iter().try_fold(0u16, |acc, c| Some(acc * 16 + u16::try_from(c.to_digit(16)?).ok()?))?;
|
||||
let bytes = code.to_be_bytes();
|
||||
let text = enc.decode_without_bom_handling_and_without_replacement(&bytes)?;
|
||||
let mut it = text.chars();
|
||||
it.next().filter(|_| it.next().is_none())
|
||||
}
|
||||
|
||||
/// Unescape the `\U+XXXX` sequences pre-R2007 DXF uses for characters outside the file's code
|
||||
/// page (four hex digits, one UTF-16 code unit; characters above U+FFFF are a surrogate pair of
|
||||
/// escapes). Malformed escapes and unpaired surrogates are kept as literal text.
|
||||
/// escapes), and the `\M+nXXXX` sequences for double-byte East Asian characters. Malformed
|
||||
/// escapes, unpaired surrogates and unknown `\M+` code pages are kept as literal text.
|
||||
fn unescape_unicode(s: &str) -> String {
|
||||
if !s.contains("\\U+") {
|
||||
if !s.contains("\\U+") && !s.contains("\\M+") {
|
||||
return s.to_string();
|
||||
}
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
if let Some(ch) = mif_escape_at(&chars, i) {
|
||||
out.push(ch);
|
||||
i += 8;
|
||||
continue;
|
||||
}
|
||||
if let Some(unit) = escape_at(&chars, i) {
|
||||
if let Some(ch) = char::from_u32(unit) {
|
||||
out.push(ch);
|
||||
@@ -276,7 +297,7 @@ struct Cur<'a> {
|
||||
p: usize,
|
||||
}
|
||||
|
||||
impl Cur<'_> {
|
||||
impl<'a> Cur<'a> {
|
||||
fn take(&mut self, n: usize) -> Result<&[u8]> {
|
||||
let end = self.p.checked_add(n).ok_or(DxfError::Eof)?;
|
||||
let s = self.b.get(self.p..end).ok_or(DxfError::Eof)?;
|
||||
@@ -306,12 +327,13 @@ impl Cur<'_> {
|
||||
a.copy_from_slice(s);
|
||||
Ok(f64::from_le_bytes(a))
|
||||
}
|
||||
fn cstr(&mut self) -> Result<String> {
|
||||
/// The bytes of a zero-terminated string (without the zero), decoded by the caller.
|
||||
fn cstr(&mut self) -> Result<&'a [u8]> {
|
||||
let start = self.p;
|
||||
while self.p < self.b.len() && self.b.get(self.p) != Some(&0) {
|
||||
self.p += 1;
|
||||
}
|
||||
let s = decode_text(self.b.get(start..self.p).unwrap_or(&[])).into_owned();
|
||||
let s = self.b.get(start..self.p).unwrap_or(&[]);
|
||||
if self.p >= self.b.len() {
|
||||
return Err(DxfError::Eof);
|
||||
}
|
||||
@@ -327,6 +349,7 @@ pub fn parse_binary(b: &[u8]) -> Result<Vec<Tag>> {
|
||||
|
||||
fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
|
||||
let mut c = Cur { b, p: 0 };
|
||||
let mut text = codepage::BinaryText::default();
|
||||
let mut tags = Vec::new();
|
||||
while c.p < b.len() {
|
||||
let mut code = i32::from(c.i16()?);
|
||||
@@ -334,7 +357,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
|
||||
code = i32::from(c.i16()?);
|
||||
}
|
||||
let v = match kind_of(code) {
|
||||
Kind::Str => Value::Str(unescape_unicode(&c.cstr()?)),
|
||||
Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))),
|
||||
Kind::Real => Value::Real(c.f64()?),
|
||||
Kind::Int16 => Value::Int(i64::from(c.i16()?)),
|
||||
Kind::Int32 => Value::Int(i64::from(c.i32()?)),
|
||||
@@ -359,6 +382,9 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if tags.is_empty() {
|
||||
return Err(DxfError::NotDxf);
|
||||
}
|
||||
Ok(tags)
|
||||
}
|
||||
|
||||
@@ -376,11 +402,18 @@ pub fn format_real(v: f64) -> String {
|
||||
/// The output is pure ASCII: non-ASCII characters in strings are written as `\U+XXXX` escapes,
|
||||
/// the pre-R2007 convention, so it is correct whatever `$DWGCODEPAGE` the header declares.
|
||||
pub fn write_ascii(tags: &[Tag]) -> String {
|
||||
write_ascii_as(tags, false)
|
||||
}
|
||||
|
||||
/// Write tags as ASCII DXF with text in UTF-8 (`utf8`, the R2007+ convention: non-ASCII
|
||||
/// characters as they are) or escaped as `\U+XXXX` (older versions, see [`write_ascii`]). Line
|
||||
/// breaks inside strings become spaces either way.
|
||||
pub fn write_ascii_as(tags: &[Tag], utf8: bool) -> String {
|
||||
let mut out = String::with_capacity(tags.len() * 16);
|
||||
for t in tags {
|
||||
let _ = write!(out, "{:>3}\r\n", t.code);
|
||||
match &t.value {
|
||||
Value::Str(s) => escape_unicode(s, &mut out),
|
||||
Value::Str(s) => escape_unicode(s, utf8, &mut out),
|
||||
Value::Real(r) => out.push_str(&format_real(*r)),
|
||||
Value::Int(i) => out.push_str(&i.to_string()),
|
||||
Value::Bool(b) => out.push_str(&i64::from(*b).to_string()),
|
||||
@@ -391,14 +424,94 @@ pub fn write_ascii(tags: &[Tag]) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Write tags as binary DXF (DXF Reference, "Binary DXF Files", R13+ layout): the sentinel,
|
||||
/// then per tag a 2-byte little-endian group code and the value in the binary form of the code's
|
||||
/// [`Kind`]: a zero-terminated string, an 8-byte real, a 2-, 4- or 8-byte integer, a 1-byte
|
||||
/// boolean, or a binary chunk (one length byte, then up to 255 bytes; longer data is split into
|
||||
/// several groups of the same code). Strings are UTF-8 when `utf8` (R2007+), otherwise escaped as
|
||||
/// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text
|
||||
/// is stored as a number; a code outside the 16-bit range is skipped.
|
||||
pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(BINARY_SENTINEL.len() + tags.len() * 12);
|
||||
out.extend_from_slice(BINARY_SENTINEL);
|
||||
for t in tags {
|
||||
let Ok(code) = i16::try_from(t.code) else { continue };
|
||||
let code_bytes = code.to_le_bytes();
|
||||
match kind_of(t.code) {
|
||||
Kind::Str => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
let s = match &t.value {
|
||||
Value::Str(s) => s.clone(),
|
||||
v => v.as_str(),
|
||||
};
|
||||
let mut text = String::with_capacity(s.len());
|
||||
escape_unicode(&s, utf8, &mut text);
|
||||
out.extend(text.bytes().filter(|&b| b != 0));
|
||||
out.push(0);
|
||||
}
|
||||
Kind::Real => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.extend_from_slice(&t.value.as_f64().to_le_bytes());
|
||||
}
|
||||
Kind::Int16 => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
let v = t.value.as_i64().clamp(i64::from(i16::MIN), i64::from(i16::MAX));
|
||||
out.extend_from_slice(&i16::try_from(v).unwrap_or_default().to_le_bytes());
|
||||
}
|
||||
Kind::Int32 => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
let v = t.value.as_i64().clamp(i64::from(i32::MIN), i64::from(i32::MAX));
|
||||
out.extend_from_slice(&i32::try_from(v).unwrap_or_default().to_le_bytes());
|
||||
}
|
||||
Kind::Int64 => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.extend_from_slice(&t.value.as_i64().to_le_bytes());
|
||||
}
|
||||
Kind::Bool => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.push(u8::from(t.value.as_i64() != 0));
|
||||
}
|
||||
Kind::Hex => {
|
||||
let bytes = hex_bytes(&t.value.as_str());
|
||||
// An empty chunk is still one group, as in ASCII.
|
||||
let mut chunks: Vec<&[u8]> = bytes.chunks(255).collect();
|
||||
if chunks.is_empty() {
|
||||
chunks.push(&[]);
|
||||
}
|
||||
for chunk in chunks {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.push(u8::try_from(chunk.len()).unwrap_or(u8::MAX));
|
||||
out.extend_from_slice(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The bytes of hex text, two digits each; anything that isn't a pair of hex digits is skipped.
|
||||
fn hex_bytes(s: &str) -> Vec<u8> {
|
||||
let digits: Vec<u8> = s.bytes().filter_map(|b| char::from(b).to_digit(16).and_then(|d| u8::try_from(d).ok())).collect();
|
||||
digits.as_chunks::<2>().0.iter().map(|[hi, lo]| (hi << 4) | lo).collect()
|
||||
}
|
||||
|
||||
/// Whether `bytes` are a binary DXF file (they start with the binary sentinel).
|
||||
pub fn is_binary(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(BINARY_SENTINEL)
|
||||
}
|
||||
|
||||
/// Escape a string for a pre-R2007 DXF, whose text is in the `$DWGCODEPAGE` code page: ASCII
|
||||
/// stays as it is and every other character becomes `\U+XXXX` (a surrogate pair of escapes
|
||||
/// above U+FFFF), so the bytes are valid in any code page. Line breaks become spaces.
|
||||
fn escape_unicode(s: &str, out: &mut String) {
|
||||
for c in s.chars() {
|
||||
/// above U+FFFF), so the bytes are valid in any code page; with `utf8` they stay as they are.
|
||||
/// A backslash that would start a `\U+` or `\M+` sequence is written as `\U+005C` so the reader
|
||||
/// gives back the literal text. Line breaks become spaces.
|
||||
fn escape_unicode(s: &str, utf8: bool, out: &mut String) {
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
match c {
|
||||
'\r' | '\n' => out.push(' '),
|
||||
c if c.is_ascii() => out.push(c),
|
||||
'\\' if matches!(chars.get(i + 1), Some('U' | 'M')) && chars.get(i + 2) == Some(&'+') => out.push_str("\\U+005C"),
|
||||
c if utf8 || c.is_ascii() => out.push(c),
|
||||
c => {
|
||||
let mut units = [0u16; 2];
|
||||
for u in c.encode_utf16(&mut units) {
|
||||
@@ -455,6 +568,19 @@ pub fn records(tags: &[Tag]) -> Vec<(String, Vec<Tag>)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn literal_escape_text_roundtrips() {
|
||||
for utf8 in [false, true] {
|
||||
for text in ["\\U+00E9", "\\M+183A4F", "a\\nb \\P", "\\\\U+00E9", "\\U+005C"] {
|
||||
let tags = vec![Tag::s(8, text)];
|
||||
let back = parse_ascii(&write_ascii_as(&tags, utf8)).unwrap();
|
||||
assert_eq!(back, tags, "utf8={utf8} {text}");
|
||||
let back = parse_binary(&write_binary(&tags, utf8)).unwrap();
|
||||
assert_eq!(back[1..], tags[..], "binary utf8={utf8} {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii_roundtrip() {
|
||||
let tags = vec![
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//! The DXF/DWG file versions CADCraft writes (DXF Reference, HEADER `$ACADVER`).
|
||||
|
||||
/// A file version CADCraft can save: the AutoCAD release that introduced the format. Each format
|
||||
/// also serves the releases after it (2018 is still AutoCAD's current format).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Version {
|
||||
/// AutoCAD 2000/2002 (AC1015).
|
||||
R2000,
|
||||
/// AutoCAD 2004–2006 (AC1018).
|
||||
R2004,
|
||||
/// AutoCAD 2007–2009 (AC1021): the first version whose DXF text is UTF-8.
|
||||
R2007,
|
||||
/// AutoCAD 2010–2012 (AC1024).
|
||||
R2010,
|
||||
/// AutoCAD 2013–2017 (AC1027).
|
||||
R2013,
|
||||
/// AutoCAD 2018 and later (AC1032), the default.
|
||||
#[default]
|
||||
R2018,
|
||||
}
|
||||
|
||||
impl Version {
|
||||
/// Every version, oldest first.
|
||||
pub const ALL: [Version; 6] = [Version::R2000, Version::R2004, Version::R2007, Version::R2010, Version::R2013, Version::R2018];
|
||||
|
||||
/// The `$ACADVER` code ("AC1032").
|
||||
pub fn code(self) -> &'static str {
|
||||
match self {
|
||||
Version::R2000 => "AC1015",
|
||||
Version::R2004 => "AC1018",
|
||||
Version::R2007 => "AC1021",
|
||||
Version::R2010 => "AC1024",
|
||||
Version::R2013 => "AC1027",
|
||||
Version::R2018 => "AC1032",
|
||||
}
|
||||
}
|
||||
|
||||
/// The release year that names the version ("2018").
|
||||
pub fn year(self) -> &'static str {
|
||||
match self {
|
||||
Version::R2000 => "2000",
|
||||
Version::R2004 => "2004",
|
||||
Version::R2007 => "2007",
|
||||
Version::R2010 => "2010",
|
||||
Version::R2013 => "2013",
|
||||
Version::R2018 => "2018",
|
||||
}
|
||||
}
|
||||
|
||||
/// A version named by its year ("2018", "R2018") or its `$ACADVER` code ("AC1032"), any case.
|
||||
pub fn parse(s: &str) -> Option<Version> {
|
||||
let s = s.trim();
|
||||
let year = s.strip_prefix(['R', 'r']).unwrap_or(s);
|
||||
Version::ALL.into_iter().find(|v| v.year() == year || v.code().eq_ignore_ascii_case(s))
|
||||
}
|
||||
|
||||
/// The version to save a file of `$ACADVER` `code` in: the same version when CADCraft writes
|
||||
/// it, else the nearest one it does (R2000 for older files, 2018 for newer ones); `None` when
|
||||
/// the code isn't a version code at all.
|
||||
pub fn for_acadver(code: &str) -> Option<Version> {
|
||||
let code = code.trim();
|
||||
if let Some(v) = Version::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(code)) {
|
||||
return Some(v);
|
||||
}
|
||||
code.get(..2).filter(|p| p.eq_ignore_ascii_case("AC"))?;
|
||||
let n = code.get(2..).filter(|d| d.bytes().all(|b| b.is_ascii_digit())).and_then(|d| d.parse::<u32>().ok())?;
|
||||
Some(match n {
|
||||
..1018 => Version::R2000,
|
||||
1018..1021 => Version::R2004,
|
||||
1021..1024 => Version::R2007,
|
||||
1024..1027 => Version::R2010,
|
||||
1027..1032 => Version::R2013,
|
||||
_ => Version::R2018,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether text in this version's DXF is UTF-8 (2007 and later). Older versions keep text in
|
||||
/// the `$DWGCODEPAGE` code page, which CADCraft avoids by escaping non-ASCII as `\U+XXXX`.
|
||||
pub fn utf8(self) -> bool {
|
||||
self >= Version::R2007
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Version {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.year())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_years_and_codes() {
|
||||
assert_eq!(Version::parse("2018"), Some(Version::R2018));
|
||||
assert_eq!(Version::parse(" r2004 "), Some(Version::R2004));
|
||||
assert_eq!(Version::parse("ac1021"), Some(Version::R2007));
|
||||
assert_eq!(Version::parse("2005"), None);
|
||||
assert_eq!(Version::parse(""), None);
|
||||
for v in Version::ALL {
|
||||
assert_eq!(Version::parse(v.code()), Some(v));
|
||||
assert_eq!(Version::parse(v.year()), Some(v));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_versions_map_to_the_nearest_writable_one() {
|
||||
assert_eq!(Version::for_acadver("AC1009"), Some(Version::R2000));
|
||||
assert_eq!(Version::for_acadver("AC1014"), Some(Version::R2000));
|
||||
assert_eq!(Version::for_acadver("AC1024"), Some(Version::R2010));
|
||||
assert_eq!(Version::for_acadver("AC1035"), Some(Version::R2018));
|
||||
assert_eq!(Version::for_acadver("MC0.0"), None);
|
||||
assert_eq!(Version::for_acadver("AC"), None);
|
||||
assert_eq!(Version::for_acadver("AC99999999999999999999"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Binary DXF writing (#421): every value kind round-trips through `write_binary` and `parse`,
|
||||
//! and hostile binary input never panics.
|
||||
|
||||
use cadcraft_dxf::{Tag, Value, is_binary, parse, write_ascii_as, write_binary};
|
||||
|
||||
fn sample() -> Vec<Tag> {
|
||||
vec![
|
||||
Tag::s(0, "SECTION"),
|
||||
Tag::s(2, "ENTITIES"),
|
||||
Tag::s(0, "TEXT"),
|
||||
Tag::s(5, "1F"),
|
||||
Tag::f(10, -3.25),
|
||||
Tag::i(62, 5),
|
||||
Tag::i(90, 70_000),
|
||||
Tag::i(160, 1 << 40),
|
||||
Tag::new(290, Value::Bool(true)),
|
||||
Tag::new(310, Value::Hex("00FFA5".into())),
|
||||
Tag::s(1, "图号 Café 😀"),
|
||||
Tag::i(1071, -2),
|
||||
Tag::s(0, "ENDSEC"),
|
||||
Tag::s(0, "EOF"),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_roundtrips_every_value_kind() {
|
||||
for utf8 in [false, true] {
|
||||
let bytes = write_binary(&sample(), utf8);
|
||||
assert!(is_binary(&bytes));
|
||||
assert_eq!(parse(&bytes).unwrap(), sample(), "utf8 = {utf8}");
|
||||
}
|
||||
// Pre-2007 strings are escaped to ASCII, 2007+ ones are UTF-8.
|
||||
let old = write_binary(&sample(), false);
|
||||
assert!(old.windows(7).any(|w| w == b"\\U+56FE"));
|
||||
let new = write_binary(&sample(), true);
|
||||
assert!(new.windows("图号".len()).any(|w| w == "图号".as_bytes()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_converts_values_to_their_codes_kind() {
|
||||
// A number held as text at a numeric code, an out-of-range 16-bit value, a long chunk.
|
||||
let long = "AB".repeat(300);
|
||||
let tags = vec![Tag::s(70, "12"), Tag::i(62, 1 << 20), Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")];
|
||||
let back = parse(&write_binary(&tags, true)).unwrap();
|
||||
assert_eq!(back[0], Tag::i(70, 12));
|
||||
assert_eq!(back[1], Tag::i(62, i64::from(i16::MAX)));
|
||||
assert_eq!(back[2].code, 310);
|
||||
assert_eq!(back[3].code, 310, "300 bytes are split into chunks of at most 255");
|
||||
assert_eq!(back[2].str().len() + back[3].str().len(), 600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_ascii_keeps_text_and_drops_line_breaks() {
|
||||
let text = write_ascii_as(&[Tag::s(1, "图号\r\nÄ"), Tag::s(0, "EOF")], true);
|
||||
assert!(text.contains("图号 Ä\r\n"));
|
||||
assert_eq!(parse(text.as_bytes()).unwrap()[0].str(), "图号 Ä");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_binary_input_never_panics() {
|
||||
let good = write_binary(&sample(), true);
|
||||
// Every truncation, and every single-byte corruption of the body.
|
||||
for n in 0..good.len() {
|
||||
let _ = parse(good.get(..n).unwrap());
|
||||
}
|
||||
for i in 22..good.len() {
|
||||
for b in [0u8, 0x7f, 0xff] {
|
||||
let mut bad = good.clone();
|
||||
bad[i] = b;
|
||||
let _ = parse(&bad);
|
||||
}
|
||||
}
|
||||
// A sentinel and nothing else is not a drawing.
|
||||
assert!(parse(b"AutoCAD Binary DXF\r\n\x1a\0").is_err());
|
||||
}
|
||||
@@ -12,12 +12,21 @@ workspace = true
|
||||
cadcraft-geom = { workspace = true }
|
||||
cadcraft-color = { workspace = true }
|
||||
cadcraft-doc = { workspace = true }
|
||||
cadcraft-dxf = { workspace = true }
|
||||
cadcraft-constraints = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
cadcraft-render = { workspace = true }
|
||||
craft-docpath = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# R-tree spatial index for picking, window selection and object snaps (MIT OR Apache-2.0).
|
||||
rstar = { version = "0.12", default-features = false }
|
||||
rstar = { version = "0.13", default-features = false }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
# Real DXF files for the external reference tests (io is a lower layer).
|
||||
cadcraft-io = { workspace = true }
|
||||
|
||||
@@ -274,8 +274,7 @@ pub fn recompute(dm: &Dimension, prev: Option<&Dimension>, before: &Drawing, aft
|
||||
// An ordinate's `defpt` is its fixed datum (the drawing origin); it must not follow the feature.
|
||||
let ordinate = matches!(nd.kind, DimKind::Ordinate { .. });
|
||||
for name in POINTS {
|
||||
if !moved.iter().any(|m| m == name)
|
||||
&& !(ordinate && name == "defpt")
|
||||
if !(moved.iter().any(|m| m == name) || ordinate && name == "defpt")
|
||||
&& !(linear && (name == "p13" || name == "p14"))
|
||||
&& let Some(slot) = def_point_mut(&mut nd, name)
|
||||
{
|
||||
@@ -337,10 +336,13 @@ pub fn update(after: &mut Arc<Drawing>, before: &Drawing) -> usize {
|
||||
/// finishes. `uid` (when known) is the document the command started in.
|
||||
pub fn after_command(s: &mut crate::Session, before: Option<&Arc<Drawing>>, uid: Option<u64>) {
|
||||
let Some(before) = before else { return };
|
||||
let mut notes = Vec::new();
|
||||
if let Ok(st) = s.state_mut()
|
||||
&& uid.is_none_or(|u| u == st.uid)
|
||||
&& !Arc::ptr_eq(before, &st.doc)
|
||||
{
|
||||
update(&mut st.doc, before);
|
||||
notes = crate::cmd::hatch::refill_associative(&mut st.doc, before);
|
||||
}
|
||||
notes.into_iter().for_each(|n| s.echo(n));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Safe, atomic file replacement.
|
||||
//!
|
||||
//! Save, export, plot, autosave and the audit log all write a file by first putting the bytes in
|
||||
//! a sibling temporary file and then renaming it over the destination, so a failed or partial
|
||||
//! write never truncates the real file. The temporary file must be created *exclusively*: opening
|
||||
//! a predictable, pre-existing temporary path for a truncating write lets another local user plant
|
||||
//! a symlink there and redirect the write onto a file the victim can write but the attacker chose
|
||||
//! (CWE-59). [`write_atomic`] creates a fresh temporary file with `create_new` (`O_CREAT|O_EXCL`),
|
||||
//! so an existing entry at that path — symlink or not — makes the create fail rather than follow
|
||||
//! it. The handle is retained for the whole write, and only its own fresh file is renamed into
|
||||
//! place.
|
||||
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use std::fs::{File, OpenOptions, Permissions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Monotonic counter making temporary names unique within this process without a RNG dependency.
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// How many fresh temporary names to try before giving up (each collision is another local race).
|
||||
const MAX_TRIES: u32 = 32;
|
||||
|
||||
/// Write `bytes` to `path`, replacing it atomically and without ever following a pre-existing
|
||||
/// temporary symlink.
|
||||
///
|
||||
/// A fresh temporary file is created with exclusive semantics in `path`'s own directory, the bytes
|
||||
/// are written through the retained handle and flushed, and the temporary is then renamed over
|
||||
/// `path`. On any failure the temporary is removed and the original `path` is left untouched.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let permissions = match std::fs::symlink_metadata(path) {
|
||||
Ok(meta) if meta.is_file() => Some(meta.permissions()),
|
||||
Ok(_) => None,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf);
|
||||
let (mut file, tmp) = create_temp(&dir, permissions.as_ref())?;
|
||||
let write = (|| {
|
||||
if let Some(permissions) = permissions {
|
||||
file.set_permissions(permissions)?;
|
||||
}
|
||||
file.write_all(bytes)?;
|
||||
file.flush()?;
|
||||
file.sync_all()
|
||||
})();
|
||||
if let Err(e) = write {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
drop(file);
|
||||
if let Err(e) = std::fs::rename(&tmp, path) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create a fresh, exclusively-owned temporary file inside `dir`, returning its handle and path.
|
||||
///
|
||||
/// `create_new(true)` opens with `O_CREAT | O_EXCL`, which refuses to follow or reuse an existing
|
||||
/// entry (including a symlink), closing the plant-a-symlink race. Names are unpredictable enough to
|
||||
/// avoid collisions in practice, and genuine collisions are retried with a new name.
|
||||
fn create_temp(dir: &Path, permissions: Option<&Permissions>) -> io::Result<(File, PathBuf)> {
|
||||
let pid = std::process::id();
|
||||
let mut last_err = None;
|
||||
for _ in 0..MAX_TRIES {
|
||||
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
|
||||
let tmp = dir.join(format!(".cadcraft-tmp-{pid}-{seq}-{nanos}"));
|
||||
match create_exclusive(&tmp, permissions) {
|
||||
Ok(file) => return Ok((file, tmp)),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
|
||||
last_err = Some(e);
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Err(last_err.unwrap_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, "could not create a unique temporary file")))
|
||||
}
|
||||
|
||||
fn create_exclusive(path: &Path, permissions: Option<&Permissions>) -> io::Result<File> {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if let Some(permissions) = permissions {
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
// Restrict access in the create syscall: chmod afterwards leaves a window in which a
|
||||
// different user can open the inode and retain read access to bytes written later.
|
||||
options.mode(permissions.mode() & 0o777);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = permissions;
|
||||
options.open(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replaces_contents_atomically() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-aw-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dest = dir.join("out.bin");
|
||||
std::fs::write(&dest, b"old").unwrap();
|
||||
write_atomic(&dest, b"new bytes").unwrap();
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), b"new bytes");
|
||||
// No temporary files left behind.
|
||||
let leftovers: Vec<_> =
|
||||
std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).filter(|n| n.to_string_lossy().starts_with(".cadcraft-tmp")).collect();
|
||||
assert!(leftovers.is_empty(), "left temp files: {leftovers:?}");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn does_not_follow_a_planted_temp_symlink() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-aw-sym-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let victim = dir.join("victim");
|
||||
std::fs::write(&victim, b"precious").unwrap();
|
||||
let planted = dir.join(".cadcraft-tmp-plant");
|
||||
symlink(&victim, &planted).unwrap();
|
||||
assert_eq!(create_exclusive(&planted, None).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
|
||||
let dest = dir.join("drawing.dxf");
|
||||
write_atomic(&dest, b"drawing bytes").unwrap();
|
||||
assert_eq!(std::fs::read(&victim).unwrap(), b"precious", "victim file was overwritten");
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), b"drawing bytes");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn replacement_preserves_private_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-aw-mode-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dest = dir.join("private.adt");
|
||||
std::fs::write(&dest, b"old").unwrap();
|
||||
std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
write_atomic(&dest, b"private report").unwrap();
|
||||
assert_eq!(std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), b"private report");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn private_temp_is_restricted_from_creation() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-aw-create-mode-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("private-temp");
|
||||
let permissions = Permissions::from_mode(0o600);
|
||||
let file = create_exclusive(&path, Some(&permissions)).unwrap();
|
||||
assert_eq!(file.metadata().unwrap().permissions().mode() & 0o077, 0);
|
||||
drop(file);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user