mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-24 21:09:50 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9d09f0baa | ||
|
|
84acf6293b | ||
|
|
4c70a46377 | ||
|
|
f4bd752bdc | ||
|
|
589b59defc | ||
|
|
fefe3a0c27 | ||
|
|
3753d7cf08 | ||
|
|
a8cd6f4b63 | ||
|
|
ebe0138d30 | ||
|
|
11838c58c6 | ||
|
|
f353ec7fa4 | ||
|
|
be003d44af | ||
|
|
a4ca87ab2a | ||
|
|
72e7590c8c | ||
|
|
884585a344 | ||
|
|
08cbb69585 | ||
|
|
80d282e7a5 | ||
|
|
5144bd5b17 | ||
|
|
8108dbccc6 | ||
|
|
8272c991b9 | ||
|
|
a2bf1b3ad5 | ||
|
|
e2a6aacf78 | ||
|
|
77f5799bf1 | ||
|
|
6503df5411 | ||
|
|
99f202b18a | ||
|
|
2b36221890 | ||
|
|
4536bc7fc8 | ||
|
|
ebea0c94d1 | ||
|
|
afb6eca31f | ||
|
|
aa02516162 | ||
|
|
be45ccab31 | ||
|
|
0703575b04 | ||
|
|
499bf2c0a7 | ||
|
|
8d1898866c | ||
|
|
0c488f79b3 | ||
|
|
a9a6a3e247 | ||
|
|
2d0a3f8a47 | ||
|
|
61266958ff | ||
|
|
20d6923cb6 | ||
|
|
c6ab899259 | ||
|
|
20309f6e99 | ||
|
|
9c773166f9 | ||
|
|
623997a19e | ||
|
|
3a800f2a5f | ||
|
|
9972a75f10 | ||
|
|
699f594718 | ||
|
|
b3ad57982e | ||
|
|
84ad5a23cb | ||
|
|
3c4556bb04 | ||
|
|
b112b56424 | ||
|
|
e381a8fd01 | ||
|
|
cc0b7c18d1 | ||
|
|
cba08d1b4b | ||
|
|
fe26486eb5 | ||
|
|
181915ee57 | ||
|
|
0068c8f517 | ||
|
|
387a3a3150 | ||
|
|
b464a7f242 | ||
|
|
4f7f67f65d | ||
|
|
c888e81d71 | ||
|
|
7357a90c6b | ||
|
|
2f33d43546 | ||
|
|
6405b00cf7 | ||
|
|
c7cb91ea53 | ||
|
|
638cbab9a5 | ||
|
|
ca8fc73281 | ||
|
|
6de9cfe4e1 | ||
|
|
13bc5ecd11 | ||
|
|
7e6aa698fa | ||
|
|
2174db2006 | ||
|
|
a6f8818794 | ||
|
|
94ee7efdf9 | ||
|
|
cbdb2cc794 | ||
|
|
2ea8002002 | ||
|
|
06203faa9d | ||
|
|
b2e2df3fc9 | ||
|
|
33ad877b6d | ||
|
|
62b7ba1e49 | ||
|
|
b869863699 | ||
|
|
49cb977a73 | ||
|
|
be4d754ef4 | ||
|
|
5055373149 | ||
|
|
8e60c2af80 | ||
|
|
d9e13a953f | ||
|
|
599fc0fe6d | ||
|
|
6dd8f7abe8 | ||
|
|
0d4402ba51 | ||
|
|
a67b5d2960 | ||
|
|
76927382bc | ||
|
|
167ba9b370 | ||
|
|
8488b039a2 | ||
|
|
e5f31a02f3 | ||
|
|
e897ebd93b | ||
|
|
d2bd177b98 | ||
|
|
8b75c7c29f | ||
|
|
773bd6c1ae | ||
|
|
727bd37983 | ||
|
|
04428cdfed | ||
|
|
c8b01a6c37 | ||
|
|
6b28a97f63 | ||
|
|
a8cb5feafd | ||
|
|
29775397ef | ||
|
|
8fa9a652bc | ||
|
|
7ebda2525c | ||
|
|
bf4c88f3db | ||
|
|
bea16deba8 | ||
|
|
1d716e85b1 | ||
|
|
7415d3b37d | ||
|
|
378382b236 | ||
|
|
f075c63207 | ||
|
|
94ccbcd048 | ||
|
|
6a3b462176 | ||
|
|
c7f04be6d3 | ||
|
|
7baa1664ac | ||
|
|
2a443bb619 | ||
|
|
588e289901 | ||
|
|
eb5f366786 | ||
|
|
0a0e5add96 | ||
|
|
19362287bb | ||
|
|
ad11eb3109 | ||
|
|
ed7681ae0c | ||
|
|
45221f5243 | ||
|
|
f0e158f089 | ||
|
|
147db777b1 | ||
|
|
d14269a001 | ||
|
|
317df69d8c | ||
|
|
ad0370dada | ||
|
|
efed7caa01 | ||
|
|
a76759cba6 | ||
|
|
c9b36de54c | ||
|
|
40166aff60 | ||
|
|
1e29e69b5a | ||
|
|
d6bb4bdf7a | ||
|
|
d8561a9ed7 | ||
|
|
83e9314835 | ||
|
|
0837cbc44d | ||
|
|
45973a6804 | ||
|
|
705543521e | ||
|
|
70c84e20ba | ||
|
|
291120a4cd | ||
|
|
5c9e4842d4 | ||
|
|
a435ef6ada | ||
|
|
98c85c6de4 | ||
|
|
1830ea76b1 | ||
|
|
2f38d0162f | ||
|
|
e548a2e705 | ||
|
|
1d875bdf45 | ||
|
|
decc64a59b | ||
|
|
1d4806ff70 | ||
|
|
89f9e24aad | ||
|
|
4cc5ba05fd | ||
|
|
335106e867 | ||
|
|
50853e3def | ||
|
|
b8e000faa6 | ||
|
|
884b1d2b04 | ||
|
|
1bba0ba35c | ||
|
|
91138569fa | ||
|
|
9c4314b070 | ||
|
|
f378bb9cc7 | ||
|
|
02c973536b | ||
|
|
8b845ebb6e | ||
|
|
62100c2542 | ||
|
|
6cddd36f48 | ||
|
|
9f9c0ac4a1 | ||
|
|
284c33a0f5 | ||
|
|
467b2090e4 | ||
|
|
8564ef738b | ||
|
|
8d22483c9f | ||
|
|
87f4932f0e | ||
|
|
e0012d43fa | ||
|
|
e154960ce3 | ||
|
|
8d3e440a8b | ||
|
|
86f83f4ccf | ||
|
|
8891854218 | ||
|
|
24b1b60dbc | ||
|
|
68344a938c | ||
|
|
944e3818f6 | ||
|
|
2d7988d057 | ||
|
|
a668b22833 | ||
|
|
35668da062 | ||
|
|
ca9b3fbbe8 | ||
|
|
5a6341a0cf | ||
|
|
92b1072ab8 | ||
|
|
1868a58a6b | ||
|
|
96897b709c | ||
|
|
79fed48419 | ||
|
|
f91198094c | ||
|
|
591040ce09 | ||
|
|
581a234456 | ||
|
|
d43eefe522 | ||
|
|
81b35afe08 | ||
|
|
31eb549204 | ||
|
|
ed971d8f87 | ||
|
|
f267530b7c | ||
|
|
f4acdcebe5 | ||
|
|
dd165335e1 | ||
|
|
af0a28c0a4 | ||
|
|
3bf29982b7 | ||
|
|
811a8a139a | ||
|
|
2df8dd6392 | ||
|
|
4941bf8da0 | ||
|
|
59872eca3c | ||
|
|
7ea5cd3975 | ||
|
|
e5071f382b | ||
|
|
1fa38e583e | ||
|
|
4d8af67d0e | ||
|
|
c3546f0c97 | ||
|
|
ff16e979cd | ||
|
|
a507761696 | ||
|
|
3794892f28 | ||
|
|
46ba36e896 | ||
|
|
739c5b8545 | ||
|
|
3f5b29a07e | ||
|
|
487f736c8f | ||
|
|
b28a92baa4 | ||
|
|
f6252418d9 | ||
|
|
8474233335 | ||
|
|
c8f249fc97 | ||
|
|
9e3a83464f | ||
|
|
09c719623b | ||
|
|
6de925c1b6 | ||
|
|
2f83a04521 | ||
|
|
e447fb8c90 | ||
|
|
db4fd82595 | ||
|
|
a85638ddd1 | ||
|
|
4164ca557e | ||
|
|
51b1b031d4 | ||
|
|
28c5bf1b06 | ||
|
|
cd985b7d49 | ||
|
|
8f99be0f2e | ||
|
|
522ede0fca | ||
|
|
c186781d8b | ||
|
|
9bb85ab9af | ||
|
|
6dc9138a64 | ||
|
|
95012e03b4 | ||
|
|
bf2923c4ba | ||
|
|
dab4aa5e79 | ||
|
|
34b39e2f3c | ||
|
|
c930bf7872 | ||
|
|
9da4e4cdf7 | ||
|
|
6b6aa82be1 | ||
|
|
b5a82554a9 | ||
|
|
56617b07af | ||
|
|
317ec4388c | ||
|
|
0485e7f4ba | ||
|
|
4d654c5185 | ||
|
|
fd1ed6649b | ||
|
|
cc65915d16 | ||
|
|
fa1dcd73e2 | ||
|
|
2dd832e2d5 | ||
|
|
5564856feb | ||
|
|
26c6e3df44 | ||
|
|
dc3ccc4ea0 | ||
|
|
1086e4aab8 | ||
|
|
a0a17b154c | ||
|
|
805ffba836 | ||
|
|
c5c1763774 | ||
|
|
cf7138b5e1 | ||
|
|
daeda9db47 | ||
|
|
d1260e1878 | ||
|
|
39b3d55f8a | ||
|
|
68a3eabe20 | ||
|
|
443301f9ee | ||
|
|
a38c58ef48 | ||
|
|
9c3db37ca2 | ||
|
|
a7e22d299f | ||
|
|
7a8235a586 | ||
|
|
1f19bf4a27 | ||
|
|
0153457580 | ||
|
|
52b4f873c7 | ||
|
|
484612f638 | ||
|
|
5406fc5629 | ||
|
|
6939d95cae | ||
|
|
75305dfedf | ||
|
|
930fa1cada | ||
|
|
9a58f2d086 | ||
|
|
6e2caa9f86 | ||
|
|
ef1cd55d24 | ||
|
|
a540a7138a | ||
|
|
0042240c05 | ||
|
|
a60b49fad0 | ||
|
|
e5b12dab06 | ||
|
|
5f992be525 | ||
|
|
fd53de7c46 | ||
|
|
2be04524b3 | ||
|
|
a5f531838b | ||
|
|
aa2a580626 | ||
|
|
bd105a569b | ||
|
|
600c25098f | ||
|
|
c4ad8e3a9b | ||
|
|
339f8ed35b | ||
|
|
26ed66cfe1 | ||
|
|
4c2bcd637c | ||
|
|
47c0af3f1b | ||
|
|
531dc5a5aa | ||
|
|
caf3193261 | ||
|
|
5524e2520a | ||
|
|
2797d468c5 | ||
|
|
1767a28371 | ||
|
|
76e7f1de07 | ||
|
|
afce16c8d2 | ||
|
|
4d2e8e3455 | ||
|
|
77a91a714a | ||
|
|
f63a437d5b | ||
|
|
f968bb3269 | ||
|
|
0a27d4a5d4 | ||
|
|
eb534b5caf | ||
|
|
94014c5594 | ||
|
|
f3e05e0ad8 | ||
|
|
a34f106e93 | ||
|
|
dbfed89a36 | ||
|
|
3d0ed97d71 | ||
|
|
0dc76090d7 | ||
|
|
9e28655a8a | ||
|
|
e88d3d7583 | ||
|
|
15b346e6ca | ||
|
|
ea5db94fe3 | ||
|
|
de04cbe917 | ||
|
|
857f538c08 | ||
|
|
1f7fd07c0d | ||
|
|
1a49d18dd1 | ||
|
|
d4874373a4 | ||
|
|
c167d59c70 | ||
|
|
fc45b7f6d8 | ||
|
|
9cb931bac9 | ||
|
|
85bfcdfcfd | ||
|
|
746a1e0364 | ||
|
|
9fc4108899 | ||
|
|
dfb780a544 | ||
|
|
ae54c84bc9 | ||
|
|
3830cee850 | ||
|
|
f7f04df4d7 | ||
|
|
ef15e22815 | ||
|
|
2589f3f7d4 | ||
|
|
b3acae6b77 | ||
|
|
bf9a202222 | ||
|
|
0514e537ac | ||
|
|
a33a5741d8 | ||
|
|
7d9c0a4dd9 | ||
|
|
8663be2c32 | ||
|
|
85c7fc4d6e | ||
|
|
9be19c98d8 | ||
|
|
9da1814cdf | ||
|
|
0ccc94edd3 | ||
|
|
ba5e871329 | ||
|
|
5334ae5cbc | ||
|
|
8517c7c48d | ||
|
|
3ceb50f404 | ||
|
|
310cade6e5 | ||
|
|
2ce94fa581 | ||
|
|
91873e03eb | ||
|
|
5fbd726a11 | ||
|
|
dc6f7246a3 | ||
|
|
c20f4c2fcb | ||
|
|
c8a47c9fb3 | ||
|
|
baac184ed8 | ||
|
|
53df51310f | ||
|
|
3846376937 | ||
|
|
2d0fb534a2 | ||
|
|
9a698aa1ff | ||
|
|
9bbb263661 | ||
|
|
7464ce6e6e | ||
|
|
389c539da4 | ||
|
|
5fb854be9c | ||
|
|
125f460cef | ||
|
|
eec3353e83 | ||
|
|
76d3879a94 | ||
|
|
555635e13e | ||
|
|
b039465d41 | ||
|
|
098b9e70b4 | ||
|
|
3301d59f44 | ||
|
|
e6c16472e4 | ||
|
|
bfe3a9483d | ||
|
|
0ae1eafc9b | ||
|
|
ff14224ff9 | ||
|
|
34125d7e43 | ||
|
|
8427681d7c | ||
|
|
2586ec22df | ||
|
|
a98f6d127e | ||
|
|
f8983e25eb | ||
|
|
40dfdd8331 | ||
|
|
576e625de6 | ||
|
|
34e1d373bf | ||
|
|
a06219aeeb | ||
|
|
344888ceb5 | ||
|
|
3f45edf144 | ||
|
|
c13cda2229 | ||
|
|
b5827f4198 | ||
|
|
d64b30b3a4 | ||
|
|
358334c755 | ||
|
|
2eb5ef5b0d | ||
|
|
30fe8c4cae | ||
|
|
1f16c2e268 | ||
|
|
afe9a6301f | ||
|
|
ea6bb98fc7 | ||
|
|
593776f0de | ||
|
|
c5d43a33e6 | ||
|
|
afd61a7c4a | ||
|
|
a4c6ac3eff | ||
|
|
1ea44bf00b | ||
|
|
c7701f6e13 | ||
|
|
88cf4cf92d | ||
|
|
019d5de98e | ||
|
|
fa2b9566fb | ||
|
|
fb7bcefaa4 | ||
|
|
481f1c2b8b | ||
|
|
587d879f13 | ||
|
|
c59e94297c | ||
|
|
b60d641083 | ||
|
|
3a8f6f5aa5 | ||
|
|
3424229ee3 | ||
|
|
faba681c99 | ||
|
|
3926d21aa9 | ||
|
|
3b19cb80e6 | ||
|
|
63e60de76c | ||
|
|
a34fe4a7af | ||
|
|
0a54876e2c | ||
|
|
61e3dd99f7 | ||
|
|
69b5f78e86 | ||
|
|
dcd469d12e | ||
|
|
f170b89a92 | ||
|
|
80c2efe0f1 | ||
|
|
74d57ea9fd | ||
|
|
47b2cfbcd0 | ||
|
|
a96f19f02b | ||
|
|
e2bcb712fd | ||
|
|
936c6a055a | ||
|
|
5432419cd5 | ||
|
|
b13ea3e2f3 | ||
|
|
e6773dac3c | ||
|
|
1841658978 | ||
|
|
f38b17fb67 | ||
|
|
dbc04ddae0 | ||
|
|
88df1670ba | ||
|
|
83d6a6fbe7 | ||
|
|
009364e72e | ||
|
|
1532349227 | ||
|
|
312b4c056e | ||
|
|
8de8bc187a | ||
|
|
c882d169ff | ||
|
|
aad58d4c75 | ||
|
|
c9f03cc36a | ||
|
|
70d857a699 | ||
|
|
3936f3b79c | ||
|
|
1a6c864235 | ||
|
|
478f01d236 | ||
|
|
7a2361de7f | ||
|
|
9e9f9aec84 | ||
|
|
8e7e247589 | ||
|
|
d2a691aea8 | ||
|
|
7ba871c6f2 | ||
|
|
cbd9bb51c6 | ||
|
|
7591fca086 | ||
|
|
cd5f3f0a71 | ||
|
|
659a4d5bd3 | ||
|
|
828efab385 | ||
|
|
8ea2342703 | ||
|
|
53690bace0 | ||
|
|
9ce910f87f | ||
|
|
fdb74c27dd | ||
|
|
eecfa4074d | ||
|
|
13afa8c773 | ||
|
|
f7bc97b378 | ||
|
|
ba830cacf8 | ||
|
|
737999f182 | ||
|
|
95b3641725 | ||
|
|
f11d74ee7c | ||
|
|
82cf8a6bb3 | ||
|
|
1d1d27f9a4 | ||
|
|
993c108660 | ||
|
|
e90ebbbbe2 | ||
|
|
eba3957a21 | ||
|
|
b415d2e835 | ||
|
|
2f22346807 | ||
|
|
9b59966cc9 | ||
|
|
a5137872c1 | ||
|
|
3054babe0e | ||
|
|
1c3beb2a95 | ||
|
|
4a23b9cf4b | ||
|
|
7cd96b945f | ||
|
|
773f7e6b76 | ||
|
|
b2101947ca | ||
|
|
1ea549bfe4 | ||
|
|
5c26c963f8 | ||
|
|
6cc69494ca | ||
|
|
0065485fc0 | ||
|
|
c3f6b51055 | ||
|
|
bf63a8dd5e | ||
|
|
6fb99ef5e1 | ||
|
|
fc4a74001b | ||
|
|
173245a5b0 | ||
|
|
159e057a28 | ||
|
|
2d54f56724 | ||
|
|
80f2a75f58 | ||
|
|
35e317ae3a | ||
|
|
479377304f | ||
|
|
baaa606036 | ||
|
|
6d59233e62 | ||
|
|
c7bd7deebb | ||
|
|
937bf63315 | ||
|
|
cdd71b4d5d | ||
|
|
f173d6733d | ||
|
|
283b06453e | ||
|
|
12b46e6bbe | ||
|
|
8498dedb7d | ||
|
|
d90a072d90 | ||
|
|
39c3b04d0d | ||
|
|
380b355d77 | ||
|
|
fca801c17e | ||
|
|
fbb2285532 | ||
|
|
437881f53a | ||
|
|
d821aa1409 | ||
|
|
2657cb2fa6 | ||
|
|
88bb5677a8 | ||
|
|
da1d291d93 | ||
|
|
4dca02c89b | ||
|
|
e211f666a6 | ||
|
|
8587c2ba14 | ||
|
|
6290bf123a | ||
|
|
ad48f1e3e1 | ||
|
|
22978a7e62 | ||
|
|
535c502fe7 | ||
|
|
cedfc5e44c | ||
|
|
1b04d06014 | ||
|
|
fb3737aa03 | ||
|
|
9bf5ecaf04 | ||
|
|
fbabac15d4 | ||
|
|
04001fd943 | ||
|
|
1d3abfa4a7 | ||
|
|
55d41eb13c | ||
|
|
0bea7178a2 | ||
|
|
177e52a14d | ||
|
|
04fb60ea5d | ||
|
|
806a39a514 | ||
|
|
3ae319154c | ||
|
|
f8edb7c1a4 | ||
|
|
347d2a5bc2 | ||
|
|
9d0053f3ad | ||
|
|
7a4aaebab0 | ||
|
|
dc85b2ab07 | ||
|
|
8aa9cad703 | ||
|
|
686501c7de | ||
|
|
683ff6003c | ||
|
|
85ca8f6af5 | ||
|
|
2ded7bf193 | ||
|
|
205981a52a | ||
|
|
ce0483fc17 | ||
|
|
506320b548 | ||
|
|
743ca809cc | ||
|
|
a9f9b09acc | ||
|
|
57ab1790ad | ||
|
|
1fc7f50104 | ||
|
|
ff516650da | ||
|
|
d0ff4265c7 | ||
|
|
56f784473d | ||
|
|
76f3a29c79 | ||
|
|
fb8e8ac8f1 | ||
|
|
8fcb9b1007 | ||
|
|
fd3d9f615a | ||
|
|
7a34692a0d | ||
|
|
fda7f5bc14 | ||
|
|
c379da6ac9 | ||
|
|
26489863b0 | ||
|
|
4a55aa3e34 | ||
|
|
baffd3c78d | ||
|
|
e800368c91 | ||
|
|
c8b1b941f7 | ||
|
|
cf75981fc2 | ||
|
|
b3908bf81e | ||
|
|
568b754211 | ||
|
|
ea2e2a5bba | ||
|
|
fa33d0b90f | ||
|
|
27ef18ec2c | ||
|
|
6cf32cf4eb | ||
|
|
a0cb8f2ca2 | ||
|
|
5360a77505 | ||
|
|
9a978f0461 | ||
|
|
1fb5f3264d | ||
|
|
e52fc4aa08 | ||
|
|
9cb6cb2384 | ||
|
|
344b5cdb53 | ||
|
|
c83f214c9d | ||
|
|
79fce91359 | ||
|
|
e78cc6edc9 | ||
|
|
141fef26e8 | ||
|
|
30312e7546 | ||
|
|
64089568c8 | ||
|
|
336deb87de | ||
|
|
fa12cb441b | ||
|
|
9d3b3a6074 | ||
|
|
05260cf3b8 | ||
|
|
4cb4f6586e | ||
|
|
de8d70cc39 | ||
|
|
117be4feb1 | ||
|
|
a4fc1070c7 | ||
|
|
b0c72c92f3 | ||
|
|
18eb274878 | ||
|
|
c1a6a9cf3a | ||
|
|
cd9662f1d4 | ||
|
|
abbd8181b9 | ||
|
|
1a2daefd78 | ||
|
|
4d2335c8f5 | ||
|
|
823dc5a060 | ||
|
|
4e94c2f720 | ||
|
|
496a631203 | ||
|
|
b3b2cd3221 | ||
|
|
819dc49c44 | ||
|
|
267a2183ac | ||
|
|
0305d2a666 | ||
|
|
29660e8c4d | ||
|
|
839072c6dd | ||
|
|
1dbad7768d | ||
|
|
95660dc132 | ||
|
|
925ff53122 | ||
|
|
fe9e3163f0 | ||
|
|
867c5fd1f1 | ||
|
|
97bad77ef4 | ||
|
|
685802ee9f | ||
|
|
2af0984af0 | ||
|
|
4dce1181e1 | ||
|
|
1f99931dd3 | ||
|
|
1302ec76a4 | ||
|
|
cf1ba2071f | ||
|
|
d274eb6dac | ||
|
|
2f032392f3 | ||
|
|
3657b2bc9b | ||
|
|
17c6e46dcd | ||
|
|
e5d0074f95 | ||
|
|
2dbf6d43cf | ||
|
|
f8903c9e98 | ||
|
|
9da7acf846 | ||
|
|
19b0dc6e97 | ||
|
|
ea3e0ce0c5 | ||
|
|
684bc41d03 | ||
|
|
5f3e60b48a | ||
|
|
2f6c2cd486 | ||
|
|
dfa15c3f25 | ||
|
|
4f7144d753 | ||
|
|
8f3d13a115 | ||
|
|
505d001ad4 | ||
|
|
fb9266f479 | ||
|
|
ea0e971e27 | ||
|
|
a1f97c2f06 | ||
|
|
0a65ffc31a | ||
|
|
ad8aeca851 | ||
|
|
90dcc2b329 | ||
|
|
c2c381d55d | ||
|
|
fa4d2e5741 | ||
|
|
dd8016225d | ||
|
|
f91f7bc154 | ||
|
|
59deadc4c3 | ||
|
|
96703b79d4 | ||
|
|
4ea12e967b | ||
|
|
f6628954fc | ||
|
|
3b0da1d760 | ||
|
|
77e6a4a46d | ||
|
|
47dcd84e04 | ||
|
|
331a535d3c | ||
|
|
c97f025459 | ||
|
|
85f0320f5c | ||
|
|
1eb7796724 | ||
|
|
aa7c97adb9 | ||
|
|
d059a5b5a4 | ||
|
|
46cd4d7b72 | ||
|
|
711339e2ef | ||
|
|
45819abd09 | ||
|
|
e1939aac68 | ||
|
|
2559426c60 | ||
|
|
96af804cb5 | ||
|
|
1cd3d4af5d | ||
|
|
f7c40e3d7e | ||
|
|
c1a500c5b9 | ||
|
|
d665499055 | ||
|
|
a8eb09604d | ||
|
|
f7f7769460 | ||
|
|
206d837639 | ||
|
|
a9e743ee6d | ||
|
|
5f346dc3cc | ||
|
|
509afaf4cf | ||
|
|
f44b31e154 | ||
|
|
c8ce333a74 | ||
|
|
001f025119 | ||
|
|
ed62390244 | ||
|
|
bd5c5c1d26 | ||
|
|
b4d823902a | ||
|
|
dc75b2cf5e | ||
|
|
c2d2f22e6a | ||
|
|
46873b2826 | ||
|
|
d5f007dffb | ||
|
|
0dfd29efde | ||
|
|
76c620fc32 | ||
|
|
838304accf | ||
|
|
a1dc03a484 | ||
|
|
c1d293296c | ||
|
|
da99015b11 | ||
|
|
1a7c16eb9a | ||
|
|
2d8c29dad2 | ||
|
|
33f10d0e6e | ||
|
|
3b918ada2c | ||
|
|
400ab591cb | ||
|
|
ce411edc91 | ||
|
|
9262fba5ce | ||
|
|
8e5b1ac8e3 | ||
|
|
f58b1234fb | ||
|
|
022aba41a8 | ||
|
|
52921512c7 | ||
|
|
be028cc6cc | ||
|
|
14ad23044a | ||
|
|
a11446f2f0 | ||
|
|
35d6c23fd1 | ||
|
|
33afc7d3a5 | ||
|
|
6f47a8b463 | ||
|
|
b6618aee8e | ||
|
|
5c614fca48 | ||
|
|
a2894eff83 | ||
|
|
1b9751ed82 | ||
|
|
573cf92745 | ||
|
|
fed3996944 | ||
|
|
a06de3357a | ||
|
|
17211dcb65 | ||
|
|
a44cc8540d | ||
|
|
71c61f7eaa | ||
|
|
479185377e | ||
|
|
92adfea27c | ||
|
|
4e6e0d6c31 | ||
|
|
32d0a866f9 | ||
|
|
5967b5656f | ||
|
|
9518b041d5 | ||
|
|
a721b087a1 | ||
|
|
4517d8be65 | ||
|
|
cf1696aff3 | ||
|
|
6e31ad9ea8 | ||
|
|
ce83871f2b | ||
|
|
6fd41d626b | ||
|
|
5e22f9b373 | ||
|
|
a8a4c5dab3 | ||
|
|
060889afb2 | ||
|
|
d75b6b73b4 | ||
|
|
4e7379bd68 | ||
|
|
2b1f851d0a | ||
|
|
cbf56f0707 | ||
|
|
aee898595f | ||
|
|
fae90c8e4a | ||
|
|
2f078962a0 | ||
|
|
a788c41faa | ||
|
|
83c7a3c2f5 | ||
|
|
a0dc1abce1 | ||
|
|
706fe7b10c | ||
|
|
ac87c269ff | ||
|
|
36c591883b | ||
|
|
5722dc5355 | ||
|
|
27be1753c2 | ||
|
|
271119d9e3 | ||
|
|
7a7e23cab7 | ||
|
|
d27dec0312 | ||
|
|
c9525ab5fb | ||
|
|
f69861f7e3 | ||
|
|
e8d935298f | ||
|
|
b40fdc2470 | ||
|
|
fd2243df95 | ||
|
|
6d47626534 | ||
|
|
596b465bb1 | ||
|
|
9c1d2c3b3a | ||
|
|
726a31740e | ||
|
|
d9fd1b7305 | ||
|
|
f654615640 |
@@ -0,0 +1,48 @@
|
||||
# The AGENTS.md quality gate (`cargo xtask ci`: fmt, clippy -D warnings, tests, assets, layers,
|
||||
# wasm, parity --check) on every pull request and every push to main, so a merge burst can't land
|
||||
# a red tree that only the next agent session discovers.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
name: cargo xtask ci
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: "0"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install Linux build dependencies (winit, wgpu, rfd)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev \
|
||||
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
|
||||
- name: Install Rust (stable + clippy, rustfmt, wasm32)
|
||||
run: |
|
||||
rustup toolchain install stable --profile minimal --component clippy,rustfmt \
|
||||
--target wasm32-unknown-unknown
|
||||
rustup default stable
|
||||
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: Quality gate
|
||||
run: cargo xtask ci
|
||||
@@ -19,78 +19,5 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
ACTIONLINT_VERSION: 1.7.12
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- 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/gridcraft.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/gridcraft.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.gridcraft.desktop
|
||||
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.gridcraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.gridcraft.metainfo.xml"
|
||||
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.gridcraft.metainfo.xml"
|
||||
python3 - <<'EOF'
|
||||
import yaml
|
||||
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.gridcraft.yml"))
|
||||
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.gridcraft.bundle.yml"))
|
||||
for m in (src, bundle):
|
||||
assert m["id"] == "ai.storyteller.gridcraft" and m["command"] == "gridcraft", 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
|
||||
|
||||
desktop-shortcut:
|
||||
name: Windows desktop shortcut smoke
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Build fixture MSIs and test shortcut lifecycle
|
||||
shell: pwsh
|
||||
run: |
|
||||
dotnet tool install --tool-path "$env:RUNNER_TEMP\wix" wix --version 5.0.2
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not install WiX' }
|
||||
$env:PATH = "$env:RUNNER_TEMP\wix;$env:PATH"
|
||||
./packaging/windows/test-desktop-shortcut.ps1
|
||||
- name: Capture native MSI dialog previews
|
||||
shell: pwsh
|
||||
run: |
|
||||
pwsh -NoProfile -STA -File ./packaging/windows/preview-installer-dialogs.ps1 `
|
||||
-Msi "$env:RUNNER_TEMP\gridcraft-shortcut-smoke\gridcraft-90.0.0.msi" `
|
||||
-OutputDir "$env:RUNNER_TEMP\gridcraft-shortcut-smoke\dialogs"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Native MSI dialog preview failed' }
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: desktop-shortcut-msi-evidence
|
||||
path: |
|
||||
${{ runner.temp }}/gridcraft-shortcut-smoke/*.log
|
||||
${{ runner.temp }}/gridcraft-shortcut-smoke/dialogs/*
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
# 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
|
||||
|
||||
+23
-431
@@ -1,13 +1,3 @@
|
||||
# Release pipeline: every push to `release` builds signed installers for every platform and
|
||||
# creates or updates the draft GitHub Release "GridCraft v<version>". See docs/releasing.md.
|
||||
# Copied from DesignCraft (craftrules release/playbook.md); keep the two in step.
|
||||
#
|
||||
# The signing jobs (macOS, Windows) and the draft-release job 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 sign nothing and get no secrets, so a manual run from another branch is a dry run:
|
||||
# they build and upload their artifacts, the environment refuses the signing jobs, and the
|
||||
# draft-release job (which needs them) is skipped.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
@@ -21,431 +11,33 @@ on:
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
contents: write
|
||||
|
||||
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
|
||||
GRIDCRAFT_BUILD_SHA: ${{ github.sha }}
|
||||
INPUT_VERSION: ${{ inputs.version }}
|
||||
|
||||
jobs:
|
||||
version:
|
||||
name: version
|
||||
runs-on: ubuntu-latest
|
||||
# No `environment: release`: this job needs no secrets (see the header about dry runs).
|
||||
outputs:
|
||||
version: ${{ steps.v.outputs.version }}
|
||||
date: ${{ steps.v.outputs.date }}
|
||||
prerelease: ${{ steps.v.outputs.prerelease }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- id: v
|
||||
name: Resolve version
|
||||
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 "### GridCraft 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:
|
||||
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
path: craft-fonts
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
targets: aarch64-apple-darwin, x86_64-apple-darwin
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: release-macos-universal
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_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:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
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@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
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.
|
||||
# .github/workflows/windows-arm64.yml installs and runs it on ARM64 hardware.
|
||||
- { arch: arm64, target: aarch64-pc-windows-msvc }
|
||||
env:
|
||||
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
path: craft-fonts
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: release-windows-${{ matrix.arch }}
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
shell: bash
|
||||
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_VERSION"
|
||||
- name: Install WiX
|
||||
shell: pwsh
|
||||
run: dotnet tool install --global wix --version 5.0.2
|
||||
- name: Build, sign, package
|
||||
shell: pwsh
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
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@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
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:
|
||||
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
NFPM_VERSION: 2.47.0
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
path: craft-fonts
|
||||
- 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@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: release-linux-${{ matrix.arch }}
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_VERSION"
|
||||
- name: Build and package (AppImage, deb, rpm, tar.gz)
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
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/gridcraft$|metainfo|applications'
|
||||
ldd target/release/gridcraft
|
||||
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.gridcraft.yml')); assert m['id'] == 'ai.storyteller.gridcraft'"
|
||||
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.
|
||||
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
|
||||
test -s "$appimage.zsync"
|
||||
done
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: release-linux-${{ matrix.arch }}
|
||||
path: dist/release/*
|
||||
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:
|
||||
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: release-linux-${{ matrix.arch }}
|
||||
path: dist/linux
|
||||
- name: Install flatpak-builder
|
||||
run: |
|
||||
sudo apt-get update
|
||||
# librsvg2-common: the SVG pixbuf loader. flatpak-builder runs the host's
|
||||
# `appstreamcli compose`, which renders the scalable icon and fails without it.
|
||||
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/gridcraft-$GRIDCRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
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:
|
||||
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
TRUNK_VERSION: 0.21.14
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
path: craft-fonts
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
targets: wasm32-unknown-unknown
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
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 run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_VERSION"
|
||||
- name: Build and zip
|
||||
env:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
run: packaging/web/package.sh
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: release-web
|
||||
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:
|
||||
GRIDCRAFT_VERSION: ${{ needs.version.outputs.version }}
|
||||
GRIDCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Check out craft-fonts
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: storytold/craft-fonts
|
||||
ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
path: craft-fonts
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
targets: riscv64gc-unknown-linux-gnu
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: release-linux-riscv64
|
||||
- name: Apply version override
|
||||
if: inputs.version != ''
|
||||
run: cargo run -q -p xtask --no-default-features -- version set "$GRIDCRAFT_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:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
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@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: release-linux-riscv64
|
||||
path: dist/release/*.tar.gz
|
||||
if-no-files-found: error
|
||||
|
||||
# FreeBSD has no hosted runners: freebsd.yml builds in a FreeBSD VM and, with package: true,
|
||||
# uploads the release-freebsd artifact (gridcraft-<v>-freebsd-x86_64.tar.gz). It needs no
|
||||
# secrets, so the called workflow runs without the release environment (and in dry runs).
|
||||
freebsd:
|
||||
name: FreeBSD
|
||||
needs: version
|
||||
uses: ./.github/workflows/freebsd.yml
|
||||
with:
|
||||
version: ${{ needs.version.outputs.version }}
|
||||
version_override: ${{ inputs.version != '' }}
|
||||
package: true
|
||||
|
||||
release:
|
||||
name: Draft GitHub Release
|
||||
needs: [version, macos, windows, linux, linux-riscv64, flatpak, web, freebsd]
|
||||
# Belt and braces for branch dry runs: only the release branch drafts a release (the
|
||||
# environment's branch rule refuses this job and the signing jobs anywhere else, too).
|
||||
if: github.ref == 'refs/heads/release'
|
||||
runs-on: ubuntu-latest
|
||||
environment: release
|
||||
permissions:
|
||||
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@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
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="GridCraft 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: gridcraft
|
||||
app-title: GridCraft
|
||||
craft-fonts-ref: abb83316d96aa59c1cf64784289e378fe9fa5695
|
||||
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 }}
|
||||
|
||||
@@ -17,71 +17,10 @@ concurrency:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
|
||||
jobs:
|
||||
package:
|
||||
name: package (cross-compiled on x64)
|
||||
if: github.ref == 'refs/heads/release'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
|
||||
with:
|
||||
targets: aarch64-pc-windows-msvc
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
key: windows-arm64-package
|
||||
- name: Install WiX
|
||||
shell: pwsh
|
||||
run: dotnet tool install --global wix --version 5.0.2
|
||||
- name: Build and package (unsigned)
|
||||
shell: pwsh
|
||||
env:
|
||||
DIST: ${{ github.workspace }}\dist\arm64
|
||||
run: ./packaging/windows/package.ps1 -Arch arm64
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: gridcraft-windows-arm64
|
||||
path: dist/arm64/*
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
install:
|
||||
name: install and run on ARM64
|
||||
needs: package
|
||||
runs-on: windows-11-arm
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: gridcraft-windows-arm64
|
||||
path: dist
|
||||
- name: Install the MSI, check it, run it, uninstall it
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$msi = (Get-ChildItem dist/*.msi | Select-Object -First 1).FullName
|
||||
$p = Start-Process msiexec.exe -ArgumentList '/i', "`"$msi`"", '/qn', '/l*v', 'install.log' -Wait -PassThru
|
||||
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; throw "msiexec /i exited $($p.ExitCode)" }
|
||||
$dir = Join-Path $env:ProgramFiles 'GridCraft'
|
||||
foreach ($exe in 'gridcraft.exe', 'gridcraft-cli.exe') {
|
||||
$path = Join-Path $dir $exe
|
||||
if (-not (Test-Path $path)) { throw "$exe not installed in $dir" }
|
||||
$bytes = [System.IO.File]::ReadAllBytes($path)
|
||||
$machine = [BitConverter]::ToUInt16($bytes, [BitConverter]::ToInt32($bytes, 0x3C) + 4)
|
||||
if ($machine -ne 0xAA64) { throw "$exe is for machine 0x$('{0:X}' -f $machine), not ARM64" }
|
||||
Write-Output "ok $path (ARM64)"
|
||||
}
|
||||
# The installed CLI runs natively on ARM64.
|
||||
$cli = Join-Path $dir 'gridcraft-cli.exe'
|
||||
$out = & $cli --version 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 0) { Write-Output $out; throw "gridcraft-cli --version exited $LASTEXITCODE" }
|
||||
Write-Output "ok gridcraft-cli --version: $($out.Trim())"
|
||||
$p = Start-Process msiexec.exe -ArgumentList '/x', "`"$msi`"", '/qn' -Wait -PassThru
|
||||
if ($p.ExitCode -ne 0) { throw "msiexec /x exited $($p.ExitCode)" }
|
||||
if (Test-Path (Join-Path $dir 'gridcraft.exe')) { throw 'uninstall left gridcraft.exe behind' }
|
||||
Write-Output 'ok uninstalled'
|
||||
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: gridcraft
|
||||
app-dir: GridCraft
|
||||
|
||||
@@ -26,7 +26,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
|
||||
- **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): `get()` instead of indexing, checked/saturating arithmetic, cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references).
|
||||
- **Bound recursion** (formula nesting, dependency chains, names referring to names).
|
||||
- **Last-resort guard:** `Session::execute` catches escaped panics and restores the workbook. It's a safety net, not a licence.
|
||||
- **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command).
|
||||
- **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command; `crates/engine/tests/command_sequence_fuzz.rs` fuzzes random command sequences against undo/redo, XLSX round-trip and full-recalc invariants; soak it with `GRIDCRAFT_FUZZ_SEEDS`/`GRIDCRAFT_FUZZ_STEPS`, replay with `GRIDCRAFT_FUZZ_SEED`).
|
||||
- Crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
|
||||
|
||||
## Non-negotiables
|
||||
|
||||
@@ -26,7 +26,7 @@ People trust GridCraft with their numbers; a crash loses their work. **This outr
|
||||
- **Input-derived numbers are hostile** (files, formulas, commands, MCP/control params): `get()` instead of indexing, checked/saturating arithmetic, cap input-sized allocations (huge ranges, `REPT`, `SEQUENCE`, whole-column references).
|
||||
- **Bound recursion** (formula nesting, dependency chains, names referring to names).
|
||||
- **Last-resort guard:** `Session::execute` catches escaped panics and restores the workbook. It's a safety net, not a licence.
|
||||
- **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command).
|
||||
- **Prove it:** every crash fix lands with a regression test (`tests::every_command_survives_empty_params` fuzzes every command; `crates/engine/tests/command_sequence_fuzz.rs` fuzzes random command sequences against undo/redo, XLSX round-trip and full-recalc invariants; soak it with `GRIDCRAFT_FUZZ_SEEDS`/`GRIDCRAFT_FUZZ_STEPS`, replay with `GRIDCRAFT_FUZZ_SEED`).
|
||||
- Crates carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
|
||||
|
||||
## Non-negotiables
|
||||
|
||||
Generated
+161
-28
@@ -121,6 +121,17 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
"cpubits",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
@@ -447,6 +458,15 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -599,6 +619,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
@@ -697,6 +727,37 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d#d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d"
|
||||
dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d#d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
@@ -746,6 +807,15 @@ version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -776,6 +846,16 @@ dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch"
|
||||
version = "0.2.0"
|
||||
@@ -1416,9 +1496,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"craft-print",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fmv-macos-events",
|
||||
@@ -1427,6 +1508,9 @@ dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
"muda",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"pollster 1.0.1",
|
||||
"rfd",
|
||||
"serde_json",
|
||||
"winresource",
|
||||
@@ -1434,7 +1518,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-calc"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
@@ -1446,7 +1530,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-chart"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-calc",
|
||||
"gridcraft-core",
|
||||
@@ -1457,18 +1541,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-cli"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-engine",
|
||||
"gridcraft-mcp",
|
||||
"log",
|
||||
"quick-xml",
|
||||
"serde_json",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-core"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1476,7 +1563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-engine"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-calc",
|
||||
"gridcraft-chart",
|
||||
@@ -1497,7 +1584,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-formula"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"serde",
|
||||
@@ -1506,7 +1593,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-functions"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"regex",
|
||||
@@ -1514,7 +1601,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-mcp"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-engine",
|
||||
"log",
|
||||
@@ -1523,46 +1610,52 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-model"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-numfmt"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-pdf"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-ui-egui"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
"epaint_default_fonts",
|
||||
"gridcraft-chart",
|
||||
"gridcraft-engine",
|
||||
"gridcraft-xlsx",
|
||||
"image",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"sys-locale",
|
||||
"toml",
|
||||
"web-sys",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-web"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -1579,12 +1672,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-xlsx"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
"gridcraft-model",
|
||||
"quick-xml 0.38.4",
|
||||
"quick-xml",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
]
|
||||
@@ -1663,6 +1759,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image"
|
||||
version = "0.25.10"
|
||||
@@ -1689,6 +1794,15 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-docker"
|
||||
version = "0.2.0"
|
||||
@@ -2480,7 +2594,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2739,15 +2853,6 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.38.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.41.0"
|
||||
@@ -3071,6 +3176,28 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -3452,6 +3579,12 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "uds_windows"
|
||||
version = "1.2.1"
|
||||
@@ -3725,7 +3858,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quick-xml 0.41.0",
|
||||
"quick-xml",
|
||||
"quote",
|
||||
]
|
||||
|
||||
@@ -4393,7 +4526,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"gridcraft-engine",
|
||||
"serde_json",
|
||||
|
||||
+11
-2
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.90"
|
||||
@@ -32,8 +32,12 @@ serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
log = "0.4"
|
||||
rayon = "1"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
|
||||
quick-xml = "0.38"
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
# Decrypting password-protected workbooks ([MS-OFFCRYPTO]): AES and SHA-1, pure Rust (wasm-safe).
|
||||
aes = { version = "0.9", default-features = false }
|
||||
sha1 = { version = "0.11", default-features = false }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
|
||||
# ui
|
||||
@@ -45,6 +49,11 @@ rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
# The desktop's preferred language, for the first-run interface language (native only).
|
||||
sys-locale = "0.3"
|
||||
# Font parser egui's epaint uses; the UI validates system font files with it before handing them
|
||||
# to egui, which panics on a file it can't parse. Same version as epaint's, so no second copy.
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
# Real font bytes for tests (Ubuntu Light, compiled into epaint).
|
||||
epaint_default_fonts = "0.36"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
@@ -84,6 +84,7 @@
|
||||
- **Compatible.** XLSX is the native format: styles, themes, formulas (including dynamic arrays),
|
||||
tables, conditional formats, validation, comments, hyperlinks, charts, pictures, sparklines,
|
||||
PivotTables and print settings round-trip. CSV and TSV too.
|
||||
Excel 97-2003 `.xls` workbooks open with their values, formulas and number formats (formatting and objects not yet).
|
||||
[XLSB worksheet data can be imported](docs/xlsb-import.md), using saved values instead of formulas.
|
||||
[ODS worksheet data can be imported](docs/ods-import.md), using saved values instead of formulas.
|
||||
[Static pictures can live inside cells](docs/cell-pictures.md), fitting their size and moving with the data.
|
||||
@@ -197,7 +198,7 @@ egui frontend is a separate crate, so the UI can be swapped without touching the
|
||||
|
||||
GridCraft is in **alpha**: the core workflow works end to end, but depth, fidelity and file
|
||||
compatibility are still rough. It covers 89% of the Excel ribbon commands in our catalog
|
||||
([`docs/parity-checklist.md`](docs/parity-checklist.md)) and 501 of Excel's 523 worksheet functions
|
||||
([`docs/parity-checklist.md`](docs/parity-checklist.md)) and 513 of Excel's 523 worksheet functions
|
||||
([`docs/function-parity.md`](docs/function-parity.md)); weighted by what Excel users rely on, we
|
||||
estimate it is about 50% ready for real work. Next up: XLSX fidelity on real-world files, very large
|
||||
workbooks and multi-threaded recalc, chart depth, text in every script, and `.xls` import. Stage,
|
||||
@@ -230,8 +231,21 @@ $env:WGPU_BACKEND = "vulkan"
|
||||
Remove-Item Env:WGPU_BACKEND # restore the default for later launches
|
||||
```
|
||||
|
||||
An explicit `gl` override can bring the driver crash back on affected systems. The macOS, Linux
|
||||
and web backend defaults are unchanged.
|
||||
An explicit `gl` override can bring the driver crash back on affected systems, and `vulkan` can
|
||||
bring back a crash in some Intel UHD Graphics drivers (`igvk64.dll`, #120). The macOS, Linux and
|
||||
web backend defaults are unchanged.
|
||||
|
||||
**If the app is slow on an older Windows PC, or DirectX 12 can't start:** when DirectX 12 finds no
|
||||
graphics card with a driver for it, it only offers Microsoft's software renderer, which draws every
|
||||
frame on the processor. In that case GridCraft uses OpenGL instead, without setting anything; if
|
||||
the first renderer fails to start, it tries the other one once. The log file records the choice
|
||||
(lines starting with `graphics:`). `WGPU_BACKEND` still overrides it (and then nothing else is
|
||||
tried), e.g. `$env:WGPU_BACKEND = "gl"` or `"dx12"`.
|
||||
|
||||
DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcompiler.dll` or
|
||||
`dxil.dll` is needed, and a copy another program put on `PATH` can no longer stop the app at start
|
||||
("Parent device is lost", #339). `$env:WGPU_DX12_COMPILER = "dxc"` (or `"auto"`) selects wgpu's DXC
|
||||
handling again for troubleshooting.
|
||||
|
||||
### macOS
|
||||
|
||||
|
||||
+81
-11
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (full re-measure against Excel for Mac 16.113.4; restructured to the craftrules progress-docs standard) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
|
||||
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
|
||||
@@ -21,7 +21,7 @@ This page is the summary. The detail is in:
|
||||
|
||||
| Number | Value | Kind |
|
||||
|---|---|---|
|
||||
| **Feature breadth** (weighted) | **~75%** | estimated, anchored on two measurements: ribbon catalog 258 / 290 (89.0%), worksheet functions 501 / 523 (95.8%; 492 working, 94.1%) |
|
||||
| **Feature breadth** (weighted) | **~75%** | estimated, anchored on two measurements: ribbon catalog 274 / 290 (94.5%), worksheet functions 513 / 523 (98.1%; 504 working, 96.4%) |
|
||||
| **Ready for real work** | **~50%** | estimated from written weights (51.6); [target-app-parity.md](docs/target-app-parity.md) |
|
||||
| **Mainstream practitioner** | **~50%** | estimated: typical analyst/finance user, weekly features, × 0.90 interaction × 0.92 stability × 0.88 file exchange; [method](docs/target-app-parity.md#mainstream-practitioner) |
|
||||
| **Essentials user** | **~63%** | estimated: core features only, × 0.92 launch/stability × 0.95 clarity × 0.90 opening sent files; [method](docs/target-app-parity.md#essentials-user) |
|
||||
@@ -32,7 +32,7 @@ This page is the summary. The detail is in:
|
||||
|---|---|---|---|
|
||||
| Full target (ready for real work) | ~50% | ~650–1,050 | Get & Transform and the data model, localization (twelve languages), charts depth, file fidelity (`.xls`, corpus, pass-through), PivotTables, collaboration, mobile |
|
||||
| Mainstream practitioner | ~50% | ~200–310 | File exchange with Excel users (corpus and Excel verification, pass-through, large files, `.xls`, encryption: 63–97 h), common-chart depth (30–45 h), PivotTables (20–30 h), keyboard and interaction (18–28 h), calc correctness and functions (20–33 h) |
|
||||
| Essentials user | ~63% | ~60–100 | Opening files people send (`.xls` and encrypted import 28–42 h; macOS Finder open 2–4 h), launch stability (6–10 h), basic chart resize and polish (6–10 h), print and Page Layout (8–12 h), small editing and UI fixes (10–16 h) |
|
||||
| Essentials user | ~63% | ~60–100 | Opening files people send (`.xls` import and saving with a password 24–36 h; macOS Finder open 2–4 h), launch stability (6–10 h), basic chart resize and polish (6–10 h), print and Page Layout (8–12 h), small editing and UI fixes (10–16 h) |
|
||||
|
||||
Each tier is a subset of the one above, so its hours are too. Calibrated as in [Effort and
|
||||
calibration](docs/target-app-parity.md#effort-and-calibration) (~6–10 h per readiness point for the remaining, verification-heavy
|
||||
@@ -62,7 +62,7 @@ collaboration, mobile, AI).
|
||||
| File formats | ~50% | 80–120 | [file-format-parity.md](docs/file-format-parity.md) |
|
||||
| Performance | ~35% | 35–55 | [target-app-parity.md](docs/target-app-parity.md#performance) |
|
||||
| Stability | ~60% | 15–25 | [gaps.md](docs/gaps.md) |
|
||||
| Localization | ~10% (ribbon in 5 languages) | 100–165 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Localization | ~10% (ribbon in 6 languages) | 100–165 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Hardware (multi-core calc, GPU, pen, multi-window) | ~40% | 25–40 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Platforms | ~80% (no iOS/Android; ahead on Linux, BSD, RISC-V) | 30–60 | [target-app-parity.md](docs/target-app-parity.md#platforms) |
|
||||
| Ecosystem / add-ins | ~10% (VBA out of scope; own scripts, MCP, CLI) | 25–40 | [target-app-parity.md](docs/target-app-parity.md#ecosystem-and-ai) |
|
||||
@@ -74,7 +74,7 @@ collaboration, mobile, AI).
|
||||
| Area | Breadth | Ready | Hours | Doc |
|
||||
|---|---|---|---|---|
|
||||
| Formula language and calculation | ~92% | ~72% | 20–30 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
|
||||
| Worksheet functions | 95.8% measured | ~82% | 18–30 | [function-parity.md](docs/function-parity.md) |
|
||||
| Worksheet functions | 96.6% measured | ~82% | 16–26 | [function-parity.md](docs/function-parity.md) |
|
||||
| Editing, navigation, clipboard, fill | ~90% | ~70% | 15–25 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| Cell formatting, styles, conditional formatting | ~95% | ~80% | 8–14 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
|
||||
| Sort, filter, tables, validation, outline | ~82% | ~70% | 10–16 | [target-app-parity.md](docs/target-app-parity.md#feature-areas) |
|
||||
@@ -89,11 +89,12 @@ collaboration, mobile, AI).
|
||||
|
||||
## Languages
|
||||
|
||||
The ribbon is translated into Japanese, Simplified Chinese, Korean, Brazilian Portuguese and
|
||||
Russian (266–268 labels each, ~12% of ~2,200 strings; merged 10-10 in #31, #104, #82), the
|
||||
The ribbon is translated into Japanese, Simplified Chinese, Korean, Brazilian Portuguese, Russian
|
||||
and German (266–268 labels each, ~12% of ~2,200 strings; merged 10-10 in #31, #104, #82, German
|
||||
added 10-11), the
|
||||
interface follows the system language, and CJK, Thai and Hebrew text falls back to system fonts
|
||||
(#38). Dialogs, menus and messages are English; formulas and number formats are en-US only. German
|
||||
is in PR #163. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
(#38). Dialogs, menus and messages are English; formulas and number formats are en-US only.
|
||||
Localized German formulas and numbers are in PR #163. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
| Language | Code | Status | UI strings |
|
||||
|---|---|---|---|
|
||||
@@ -106,11 +107,11 @@ is in PR #163. Detail: [localization-parity.md](docs/localization-parity.md).
|
||||
| Portuguese | pt-BR | menus only | ~12% |
|
||||
| Indonesian | id | none | 0% |
|
||||
| Japanese | ja | menus only | ~12% |
|
||||
| German | de | none (PR #163 open) | 0% |
|
||||
| German | de | menus only | ~12% |
|
||||
| Korean | ko | menus only | ~12% |
|
||||
| Vietnamese | vi | none | 0% |
|
||||
|
||||
Other shipped languages: 1 (Russian, menus only, ~12%).
|
||||
Other shipped languages: 2 (Russian and German, menus only, ~12%).
|
||||
|
||||
## Upcoming
|
||||
|
||||
@@ -131,6 +132,56 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) |
|
||||
| 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) |
|
||||
| 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) |
|
||||
| 2026-10-12 | Security: cell hyperlinks open only http, https and mailto, after a confirmation; other schemes (file:, smb:, UNC, custom handlers) are refused (#777, part 1) |
|
||||
| 2026-10-12 | Deleting several Ctrl-selected rows or columns removes them all in one undo step (#758) |
|
||||
| 2026-10-12 | XLSX chart sheets are kept on open and save: the sheet, its drawing and chart (with style and colours) are written back unchanged in their place among the worksheets, and left out when the sheet they plot is deleted or renamed or a worksheet took their name (#727) |
|
||||
| 2026-10-12 | CSV and tab-separated export is capped at 512 MiB: a sheet whose used range would expand to more (two cells far apart, such as A1 and XFD1048576, are 16 GiB of commas) is refused with the rows, columns and limit, before anything is allocated or written (#528) |
|
||||
| 2026-10-12 | PDF writer hardening: text width cannot overflow, all-zero dash arrays and negative or NaN stroke widths are sanitised, non-finite sizes and positions draw nothing (#812) |
|
||||
| 2026-10-12 | PDF export writes the document title and author as UTF-16BE when they are not ASCII, so viewers show accents, currency signs and non-Latin text correctly (#813) |
|
||||
| 2026-10-12 | `TEXT()` over a range and chart labels parse each number format code once instead of once per value (#806) |
|
||||
| 2026-10-12 | SUBTOTAL(109) over hidden rows recalculates after Row Height, AutoFit Row Height and Ungroup reveal rows (found by the command-sequence fuzz) |
|
||||
| 2026-10-12 | Page Layout view: drag the margin edges on the rulers to set the page margins (resize cursor, live preview, value tooltip, one undo step, Esc cancels) (#792) |
|
||||
| 2026-10-12 | Forecast Sheet gets Forecast Start: begin the forecast inside the history to compare it with the actuals (#785) |
|
||||
| 2026-10-12 | Ink strokes save as unfilled DrawingML paths and reopen as editable ink with their points, colour and width; icons in #551 remain a follow-up |
|
||||
| 2026-10-12 | The selection outline stays visible when extended to the last row (Ctrl+Shift+Down): its sides are cut to the viewport instead of stroking a 20-million-point rectangle (#687) |
|
||||
| 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available |
|
||||
| 2026-10-11 | Command-sequence fuzzing: random command sequences checked against undo/redo, XLSX round-trip and full recalculation; fixes for the table, legacy-array, spill, AutoSum, Watch Window and sheet-copy bugs it found |
|
||||
| 2026-10-11 | Password-protected workbooks open: GridCraft asks for the password and decrypts Agile and Standard encryption (#11) |
|
||||
| 2026-10-11 | Text boxes keep their formatting: run size, bold, italic, typeface, text colour and outline, alignment, vertical anchor and "no outline" (#377) |
|
||||
| 2026-10-11 | Desktop printing opens the print PDF in the system viewer; Save As offers CSV, web page and PDF; macOS File › Properties opens File › Info (#370, #343) |
|
||||
| 2026-10-11 | Windows: DirectX 12 shaders compile with FXC, so a missing or stray `dxcompiler.dll` no longer stops the app at start (#339, #354) |
|
||||
| 2026-10-11 | Merged cells draw their whole outline: right and bottom edges come from the last column's and last row's cells (#376) |
|
||||
| 2026-10-11 | Shrink to fit draws too-wide text and numbers in a smaller font inside the cell or merged area (#375) |
|
||||
| 2026-10-11 | Shift+Space and Ctrl+Space select the row / column without starting an edit; Control+Space on Mac (#338) |
|
||||
| 2026-10-11 | Workbooks reopen at their saved scroll position (`topLeftCell`, also with frozen panes) and save the current one back (#378) |
|
||||
| 2026-10-11 | Protect Sheet passwords use Excel-compatible hashes and round-trip in XLSX `sheetProtection` (imported passwords verify instead of being dropped) |
|
||||
| 2026-10-11 | Review › Protect Workbook opens a dialog with an optional password (Excel-compatible hash, kept in XLSX `workbookProtection`); unprotecting verifies it (#345) |
|
||||
| 2026-10-11 | Formula bar, name box and dialogs fall back to the cell font: Hebrew (and any script cells can show) no longer turns into boxes there (#349) |
|
||||
| 2026-10-11 | Headers and footers: first-page and odd/even variants are read, kept, printed and edited in Page Layout view; Insert › Header & Footer edits the header in place (#344) |
|
||||
| 2026-10-11 | Legacy Excel 97-2003 `.xls` (BIFF8) import with formulas, number formats, merges, sizes and names (#121) |
|
||||
| 2026-10-11 | XLSX pass-through: custom XML, external links, connections, query tables, printer settings, form/ActiveX controls and OLE objects are kept on save (#330, #324) |
|
||||
| 2026-10-11 | Data › Forecast › Forecast Sheet: a new sheet with the history, FORECAST.ETS forecast, confidence bounds, statistics and a chart (#322) |
|
||||
| 2026-10-11 | Startup no longer panics on a system font egui can't parse: fonts are validated and skipped (#226) |
|
||||
| 2026-10-11 | Ctrl+drag on the fill handle swaps copying and extending a series (#264) |
|
||||
| 2026-10-11 | Odd-period bond functions ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD: Financial 55 / 55 (#275) |
|
||||
| 2026-10-11 | PERCENTOF and EUROCONVERT worksheet functions (#279) |
|
||||
| 2026-10-11 | BAHTTEXT: amounts in Thai words with Baht and Satang (#291) |
|
||||
| 2026-10-11 | TRIMRANGE: ranges and arrays without blank outer rows and columns (#296) |
|
||||
| 2026-10-11 | Selected charts, pictures and shapes can be deleted from the keyboard (#213) |
|
||||
| 2026-10-11 | Ribbon translated into German (266 labels; `de`, `de-DE`, `de-AT`, `de-CH` locale tags resolve to German) |
|
||||
| 2026-10-11 | View › Interface size: a saved 75–200 % scale for the whole window (#230) |
|
||||
| 2026-10-11 | View › Formula Bar and Zoom 100% reachable from the CLI and MCP (#289) |
|
||||
| 2026-10-11 | Freeze panes by dragging the freeze handles on the header edges (#195) |
|
||||
| 2026-10-11 | XLSX: threaded comments (replies, resolved, timestamps) and note visibility survive a save (#300) |
|
||||
| 2026-10-11 | Cell checkboxes: Insert › Checkbox on the ribbon, Excel's Delete and value rules, XLSX round trip as Excel cell controls (#196) |
|
||||
| 2026-10-11 | Review › Allow Edit Ranges with Excel-compatible password hashes, kept in XLSX (#307) |
|
||||
| 2026-10-11 | PivotTable calculated fields (`pivot.calculatedField`), evaluated on sums like Excel, with XLSX round-trip (#304) |
|
||||
| 2026-10-11 | PivotCharts (`insert.pivotChart`): charts bound to a PivotTable's report, following refreshes and layout changes (#311) |
|
||||
| 2026-10-11 | FORECAST.ETS, FORECAST.ETS.CONFINT, FORECAST.ETS.SEASONALITY, FORECAST.ETS.STAT: AAA exponential smoothing forecasts (#314) |
|
||||
| 2026-10-11 | File tab Backstage view (Home, New, Open, Info, Save As, Print preview, Export, Options) and `file.options` (#174) |
|
||||
| 2026-10-10 | Ribbon translated into Japanese, Chinese, Korean, Brazilian Portuguese and Russian with system-language default (#31, #104, #82); CJK/Thai/Hebrew font fallback (#38); clear messages for encrypted and `.xls` files (#17); smooth line charts (#62). Progress docs restructured to the craftrules standard; full re-measure (this page). Initial ribbon key tips (#43), in-place text box editing (#84), copy as HTML table (#36). ODS and XLSB data import (#100, #101); recalc linear in the number of range formulas (#66); RISC-V Linux build; Flatpak repository on Pages; web cell-commit trap fixed |
|
||||
| 2026-10-09 | Community fixes: spill range operator `A1#`, sheet-scoped names, protection refuses locked-cell edits, Insert/Delete Cells adjust references, `DATE(1900,2,29)`, SUMIF sizing, `ROUND` at 15 digits, `_xlpm.` LAMBDA parameters in XLSX, vertical scrollbar, system appearance, border previews; v0.4.0 |
|
||||
| 2026-10-08 | v0.2.0 and v0.3.0 releases; Flatpak, AppImage zsync, branded DMG; desktop log file; DirectX 12 default on Windows |
|
||||
@@ -142,6 +193,25 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row |
|
||||
| 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) |
|
||||
| 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) |
|
||||
| 2026-10-12 | trivial | Progress log: CSV export size cap (#528) |
|
||||
| 2026-10-12 | minor | Progress log: margins dragged on the Page Layout rulers (#792) |
|
||||
| 2026-10-12 | minor | Ink preservation across XLSX save/reopen (ink portion of #551) |
|
||||
| 2026-10-12 | minor | Desktop File > Print now discovers printers and submits PDF jobs through pinned craft-print with printer choice, copies, duplex and grayscale; browser printing and PDF export remain available. Remaining print parity includes page ranges and driver-specific tray/options UI; physical printer fidelity needs hardware validation. |
|
||||
| 2026-10-11 | minor | Password-encrypted workbooks open (#11); progress log row |
|
||||
| 2026-10-11 | minor | Forecast Sheet (#322); progress log row |
|
||||
| 2026-10-11 | minor | Worksheet functions 505 / 523 (ODD* bond functions); progress log row |
|
||||
| 2026-10-11 | minor | Worksheet functions 503 / 523 (PERCENTOF, EUROCONVERT); progress log row |
|
||||
| 2026-10-11 | minor | Worksheet functions 502 / 523 (BAHTTEXT); progress log row |
|
||||
| 2026-10-11 | minor | Worksheet functions 502 / 523 (TRIMRANGE); progress log row |
|
||||
| 2026-10-11 | minor | Selected objects can be deleted from the keyboard (#213) |
|
||||
| 2026-10-11 | minor | Catalog 258 → 260 / 290: View › Formula Bar and Zoom 100% (#289) |
|
||||
| 2026-10-11 | minor | Progress log: XLSX threaded comments round trip (#300) |
|
||||
| 2026-10-11 | minor | Catalog 258 → 259 / 290: Allow Edit Ranges (#307) |
|
||||
| 2026-10-11 | minor | Worksheet functions 505 / 523 (FORECAST.ETS family); progress log row |
|
||||
| 2026-10-11 | minor | Czech (cs) listed under other shipped languages: ribbon only, ~12% |
|
||||
| 2026-10-10 | minor | Readiness-by-audience table with hours to ~95% per audience; full number unchanged (additive weighted sum) |
|
||||
| 2026-10-10 | minor | Added Mainstream practitioner (~50%) and Essentials user (~63%); languages updated for the 10-10 merges (ribbon in ja, zh, ko, pt-BR, ru); localization 5%→10%; full number re-checked (51.6, unchanged) |
|
||||
| 2026-10-10 | minor | Checked against the alpha gate (six core workflows pass): stays alpha |
|
||||
|
||||
@@ -18,3 +18,6 @@ gridcraft-engine = { workspace = true }
|
||||
gridcraft-mcp = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# `check`: validating the packages GridCraft writes (content types, relationships).
|
||||
zip = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@
|
||||
//! gridcraft-cli convert <in> <out> [--sheet NAME]
|
||||
//! gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
|
||||
//! gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
|
||||
//! gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
|
||||
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
|
||||
//! gridcraft-cli commands [--json] [--search X]
|
||||
//! gridcraft-cli functions [--json] [--search X] [--category C]
|
||||
@@ -28,6 +29,8 @@ macro_rules! outln {
|
||||
}};
|
||||
}
|
||||
|
||||
mod check;
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -36,6 +39,8 @@ const USAGE: &str = "usage:
|
||||
gridcraft-cli convert <in> <out> [--sheet NAME] xlsx/csv/tsv/json/html by extension
|
||||
gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
|
||||
gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
|
||||
gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
|
||||
cached-value calc oracle + XLSX round-trip fidelity (exit 1 on any difference)
|
||||
gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl]
|
||||
[--out FILE] [--print RANGE] [--quiet]
|
||||
gridcraft-cli commands [--json] [--search X]
|
||||
@@ -71,6 +76,7 @@ fn main() -> ExitCode {
|
||||
Some("eval") => eval(rest),
|
||||
Some("cat") => cat(rest),
|
||||
Some("run") => run(rest),
|
||||
Some("check") => return check::main(rest),
|
||||
Some("commands") => commands(rest),
|
||||
Some("functions") => functions(rest),
|
||||
Some("mcp") => mcp(rest),
|
||||
@@ -271,7 +277,7 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
let mut s = open(input)?;
|
||||
activate_sheet(&mut s, a.opt("sheet"))?;
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
let bytes = gridcraft_engine::io::save_bytes(&d.wb, out).map_err(|e| e.to_string())?;
|
||||
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(|e| e.to_string())?;
|
||||
gridcraft_engine::io::write_file(out, &bytes).map_err(|e| e.to_string())?;
|
||||
eprintln!("wrote {out} ({} bytes)", bytes.len());
|
||||
Ok(())
|
||||
|
||||
@@ -150,3 +150,27 @@ fn mcp_over_stdio() {
|
||||
assert_eq!(lines[0]["result"]["serverInfo"]["name"], "gridcraft");
|
||||
assert!(lines[1]["result"]["content"][0]["text"].as_str().unwrap().contains("42"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_exit_codes_and_json() {
|
||||
let dir = tmpdir("check");
|
||||
let book = dir.join("calc.xlsx");
|
||||
let book_s = book.to_str().unwrap();
|
||||
ok(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"2"}"#, "--cmd", r#"cell.set={"cell":"B1","input":"=A1*3"}"#, "--out", book_s, "--quiet"]);
|
||||
// GridCraft's own file: its cached values are its own results, and it round-trips.
|
||||
let o = run(&["check", dir.to_str().unwrap()]);
|
||||
let out = String::from_utf8_lossy(&o.stdout);
|
||||
assert_eq!(o.status.code(), Some(0), "{out}");
|
||||
assert!(out.contains("1 checked: 1 matched, 0 mismatched"), "{out}");
|
||||
let v: serde_json::Value = serde_json::from_str(&ok(&["check", book_s, "--json"])).unwrap();
|
||||
assert_eq!(v["schema"], "gridcraft-check/1");
|
||||
assert_eq!(v["totals"]["matched"], 1);
|
||||
// A file that can't be opened is reported, not fatal, and fails the check.
|
||||
let o = run(&["check", book_s, "/no/such/file.xlsx"]);
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&o.stdout).contains("1 failed to open"));
|
||||
// Usage errors exit 2.
|
||||
assert_eq!(run(&["check"]).status.code(), Some(2));
|
||||
assert_eq!(run(&["check", book_s, "--tolerance", "x"]).status.code(), Some(2));
|
||||
assert_eq!(run(&["check", book_s, "--bogus"]).status.code(), Some(2));
|
||||
}
|
||||
|
||||
@@ -26,4 +26,4 @@ rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams"] }
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<title>GridCraft</title>
|
||||
<link data-trunk rel="icon" href="../../assets/app-icon/gridcraft.ico" />
|
||||
<link data-trunk rel="rust" data-bin="gridcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #f3f3f3; }
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed
|
||||
//! GridCraft in an `<iframe>` (such as a Nextcloud app). Messages are plain objects with a `type`:
|
||||
//!
|
||||
//! - `gridcraft:ready` (to the parent): `{ version }`, the app is listening; send a file now.
|
||||
//! - `gridcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
|
||||
//! `Uint8Array`. It opens like a workbook picked with File › Open or dropped on the window.
|
||||
//! - `gridcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
|
||||
//! file GridCraft would otherwise download: Save and Save As (an .xlsx workbook) and Export
|
||||
//! as PDF. The parent stores it and reports failures itself.
|
||||
//! - `gridcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
|
||||
//! - `gridcraft: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 page
|
||||
//! starts with an empty workbook instead of a sample, and the parent guards leaving the page.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use gridcraft_ui_egui::{Inbox, Services, SheetApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
|
||||
/// Saving one of these hands the whole workbook to the parent, which stores it: the workbook
|
||||
/// counts as saved under that name, as it would after Save on the desktop.
|
||||
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
|
||||
|
||||
/// The longest user name taken from `?author=`.
|
||||
const MAX_AUTHOR_CHARS: usize = 200;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
window: web_sys::Window,
|
||||
parent: web_sys::Window,
|
||||
origin: String,
|
||||
/// Names of the files handed to the parent since the last frame.
|
||||
saved: Rc<RefCell<Vec<String>>>,
|
||||
/// The unsaved-changes state last reported to the parent.
|
||||
reported: Rc<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, saved: Rc::default(), reported: Rc::default() })
|
||||
}
|
||||
|
||||
/// Send saved and exported files to the parent instead of downloading them, and hear files
|
||||
/// from it.
|
||||
pub fn connect(&self, services: &mut Services, inbox: Inbox, ctx: egui::Context) {
|
||||
self.listen(inbox, ctx);
|
||||
let bridge = self.clone();
|
||||
services.download = Some(Box::new(move |name: &str, bytes: &[u8]| {
|
||||
if let Err(e) = bridge.post_save(name, bytes) {
|
||||
log::error!("couldn't hand {name} to the page: {e}");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/// `?author=`: the host's name for the user signs new notes and comments.
|
||||
pub fn set_author(app: &mut SheetApp, author: &str) {
|
||||
let author: String = author.trim().chars().take(MAX_AUTHOR_CHARS).collect();
|
||||
if !author.is_empty() {
|
||||
app.session.prefs.user_name = author;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn post_ready(&self) {
|
||||
self.send(&[("type", "gridcraft:ready".into()), ("version", env!("CARGO_PKG_VERSION").into())]);
|
||||
}
|
||||
|
||||
pub fn post_failed(&self, error: &str) {
|
||||
self.send(&[("type", "gridcraft:failed".into()), ("error", error.into())]);
|
||||
}
|
||||
|
||||
/// After each frame: a workbook handed to the parent this frame counts as saved under the
|
||||
/// name it was saved as, and the parent hears when unsaved changes appear or go away.
|
||||
pub fn sync(&self, app: &mut SheetApp) {
|
||||
let saved = std::mem::take(&mut *self.saved.borrow_mut());
|
||||
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
|
||||
&& let Some(doc) = app.session.active_mut()
|
||||
{
|
||||
doc.saved = doc.wb.clone();
|
||||
if doc.path.is_none() {
|
||||
doc.title = name.clone();
|
||||
}
|
||||
}
|
||||
let dirty = app.session.documents().iter().any(|d| d.is_dirty());
|
||||
if self.reported.get() != Some(dirty) && self.send(&[("type", "gridcraft:dirty".into()), ("dirty", dirty.into())]) {
|
||||
self.reported.set(Some(dirty));
|
||||
}
|
||||
}
|
||||
|
||||
fn post_save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
|
||||
let buffer = js_sys::Uint8Array::from(bytes).buffer();
|
||||
let message = message(&[("type", "gridcraft:save".into()), ("name", name.as_str().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:?}")))?;
|
||||
self.saved.borrow_mut().push(name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn listen(&self, inbox: Inbox, ctx: egui::Context) {
|
||||
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("gridcraft:open") {
|
||||
return;
|
||||
}
|
||||
let name = string(&data, "name").filter(|n| !n.trim().is_empty()).unwrap_or_else(|| "Book.xlsx".to_string());
|
||||
let Some(bytes) = bytes(&data) else { return };
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_workbook(name: &str) -> bool {
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
|
||||
}
|
||||
|
||||
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` as an `ArrayBuffer` or `Uint8Array`.
|
||||
fn bytes(data: &JsValue) -> Option<Vec<u8>> {
|
||||
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
|
||||
if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
|
||||
Some(array.to_vec())
|
||||
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
|
||||
Some(js_sys::Uint8Array::new(&bytes).to_vec())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,14 @@
|
||||
//! (bytes arrive asynchronously through `Services::inbox`); Save downloads the file; dropped
|
||||
//! files are read asynchronously.
|
||||
//!
|
||||
//! URL query flags: `?webgl` forces WebGL2; `?sample=sales|budget|grades` opens a sample.
|
||||
//! URL query flags: `?webgl` forces WebGL2; `?sample=sales|budget|grades` opens a sample;
|
||||
//! `?host=parent` (inside an `<iframe>`) talks to a same-origin parent page instead: it sends the
|
||||
//! workbook to open and stores what GridCraft saves (`host`), and `&author=` names the user for
|
||||
//! notes and comments.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
|
||||
|
||||
+212
-10
@@ -3,6 +3,7 @@
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_ui_egui::{Inbox, Services, SheetApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::JsValue;
|
||||
|
||||
const CANVAS_ID: &str = "gridcraft_canvas";
|
||||
const LOADING_ID: &str = "gridcraft_loading";
|
||||
@@ -24,6 +25,10 @@ pub fn start() {
|
||||
{
|
||||
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
|
||||
}
|
||||
// `?host=parent`: a same-origin page framing GridCraft (such as a Nextcloud app) opens
|
||||
// workbooks in it and stores what it saves (`host`).
|
||||
let bridge = if query_param("host").as_deref() == Some("parent") { crate::host::Bridge::new() } else { None };
|
||||
let app_bridge = bridge.clone();
|
||||
let result = eframe::WebRunner::new()
|
||||
.start(
|
||||
canvas,
|
||||
@@ -31,13 +36,19 @@ pub fn start() {
|
||||
Box::new(move |cc| {
|
||||
let inbox: Inbox = Inbox::default();
|
||||
let mut session = Session::new();
|
||||
let q = query();
|
||||
// In host mode the parent sends the workbook to edit; no sample meanwhile.
|
||||
let q = if app_bridge.is_some() { String::new() } else { query() };
|
||||
if let Some(name) = q.split(['?', '&']).find_map(|kv| kv.strip_prefix("sample=")) {
|
||||
let _ = session.execute("file.new", serde_json::json!({"sample": name}));
|
||||
} else if q.contains("sample") {
|
||||
let _ = session.execute("file.new", serde_json::json!({"sample": "sales"}));
|
||||
}
|
||||
let mut app = SheetApp::new(session, services(inbox.clone(), cc.egui_ctx.clone()));
|
||||
let mut services = services(inbox.clone(), cc.egui_ctx.clone());
|
||||
if let Some(bridge) = &app_bridge {
|
||||
bridge.connect(&mut services, inbox.clone(), cc.egui_ctx.clone());
|
||||
}
|
||||
let mut app = SheetApp::new(session, services);
|
||||
app.ui.system_theme = true;
|
||||
// Follow the browser's language, except a CJK one: the web build has no system
|
||||
// CJK fonts (none are bundled), so that interface would render as tofu.
|
||||
let browser = gridcraft_ui_egui::i18n::Language::system();
|
||||
@@ -48,10 +59,19 @@ pub fn start() {
|
||||
app.ui.language = browser;
|
||||
}
|
||||
SheetApp::setup_context_for_language(&cc.egui_ctx, false, app.ui.language);
|
||||
Ok(Box::new(WebShell { app, inbox }))
|
||||
if let Some(bridge) = &app_bridge {
|
||||
if let Some(author) = query_param("author") {
|
||||
crate::host::Bridge::set_author(&mut app, &author);
|
||||
}
|
||||
bridge.post_ready();
|
||||
}
|
||||
Ok(Box::new(WebShell { app, inbox, bridge: app_bridge }))
|
||||
}),
|
||||
)
|
||||
.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(),
|
||||
@@ -65,9 +85,14 @@ 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)
|
||||
}
|
||||
|
||||
struct WebShell {
|
||||
app: SheetApp,
|
||||
inbox: Inbox,
|
||||
bridge: Option<crate::host::Bridge>,
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
@@ -96,6 +121,9 @@ impl eframe::App for WebShell {
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.app.ui(ui);
|
||||
if let Some(bridge) = &self.bridge {
|
||||
bridge.sync(&mut self.app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +137,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
let ctx = ctx.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let Some(file) = rfd::AsyncFileDialog::new()
|
||||
.add_filter("Spreadsheets", &["xlsx", "xlsm", "xlsb", "ods", "csv", "tsv", "txt", "json"])
|
||||
.add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "json"])
|
||||
.pick_file()
|
||||
.await
|
||||
else {
|
||||
@@ -136,9 +164,16 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
log::error!("download of {name} failed: {e}");
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(|bytes: &[u8]| {
|
||||
if let Err(e) = print_pdf(bytes) {
|
||||
log::error!("print failed: {e}");
|
||||
}
|
||||
})),
|
||||
open_url: Some(Box::new(|url: &str| {
|
||||
if let Some(w) = web_sys::window() {
|
||||
let _ = w.open_with_url_and_target(url, "_blank");
|
||||
if let Some(w) = web_sys::window()
|
||||
&& let gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url)
|
||||
{
|
||||
let _ = w.open_with_url_and_target(&url, "_blank");
|
||||
}
|
||||
})),
|
||||
inbox: Some(inbox),
|
||||
@@ -179,17 +214,184 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Triggers a browser download of `bytes`.
|
||||
fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
|
||||
/// `print()` once it has finished loading — the standard way to drive the browser's native print
|
||||
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
|
||||
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
|
||||
/// them.
|
||||
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type(if name.ends_with(".csv") { "text/csv" } else { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
|
||||
opts.set_type("application/pdf");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
|
||||
|
||||
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
|
||||
iframe.style().set_property("display", "none").map_err(js)?;
|
||||
document.body().ok_or("no body")?.append_child(&iframe).map_err(js)?;
|
||||
|
||||
// `onload` fires once the PDF has actually rendered inside the iframe;
|
||||
// printing before that would show a blank page. Set the handler BEFORE
|
||||
// `src` so a fast/cached load can't fire before we're listening.
|
||||
let iframe_for_load = iframe.clone();
|
||||
let url_for_cleanup = url.clone();
|
||||
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
let Some(content_window) = iframe_for_load.content_window() else { return };
|
||||
let _ = content_window.print();
|
||||
// `afterprint` fires once the print dialog (or print preview) closes, whether the user
|
||||
// printed or cancelled — the right moment to release the blob URL and drop the iframe.
|
||||
let iframe_for_cleanup = iframe_for_load.clone();
|
||||
let on_after_print = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
web_sys::Url::revoke_object_url(&url_for_cleanup).ok();
|
||||
iframe_for_cleanup.remove();
|
||||
});
|
||||
let _ = content_window.add_event_listener_with_callback("afterprint", on_after_print.unchecked_ref());
|
||||
});
|
||||
iframe.set_onload(Some(on_load.unchecked_ref()));
|
||||
iframe.set_src(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
Some("xlsm") => "application/vnd.ms-excel.sheet.macroEnabled.12",
|
||||
Some("xlsb") => "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
|
||||
Some("ods") => "application/vnd.oasis.opendocument.spreadsheet",
|
||||
Some("csv") => "text/csv",
|
||||
Some("tsv" | "txt") => "text/plain",
|
||||
Some("pdf") => "application/pdf",
|
||||
Some("html" | "htm") => "text/html",
|
||||
Some("json") => "application/json",
|
||||
Some("png") => "image/png",
|
||||
Some("jpg" | "jpeg") => "image/jpeg",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
/// Trigger a browser save dialog or download of `bytes` named after `name`.
|
||||
|
||||
fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
|
||||
let show_picker_fn: Option<js_sys::Function> =
|
||||
js_sys::Reflect::get(&window, &JsValue::from_str("showSaveFilePicker")).ok().and_then(|v| v.dyn_into().ok());
|
||||
|
||||
if let Some(picker_fn) = show_picker_fn {
|
||||
let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or("xlsx").to_ascii_lowercase();
|
||||
let dot_ext = format!(".{ext}");
|
||||
let mime = mime_for(name);
|
||||
|
||||
let accept_obj = js_sys::Object::new();
|
||||
let exts_arr = js_sys::Array::new();
|
||||
exts_arr.push(&JsValue::from_str(&dot_ext));
|
||||
let _ = js_sys::Reflect::set(&accept_obj, &JsValue::from_str(mime), &exts_arr);
|
||||
|
||||
let type_desc = match ext.as_str() {
|
||||
"xlsx" => "Excel Workbook (*.xlsx)",
|
||||
"xlsm" => "Excel Macro-Enabled Workbook (*.xlsm)",
|
||||
"xlsb" => "Excel Binary Workbook (*.xlsb)",
|
||||
"ods" => "OpenDocument Spreadsheet (*.ods)",
|
||||
"csv" => "CSV (Comma delimited) (*.csv)",
|
||||
"tsv" => "Tab Delimited Text (*.tsv)",
|
||||
"txt" => "Plain Text (*.txt)",
|
||||
"pdf" => "PDF Document (*.pdf)",
|
||||
"html" | "htm" => "HTML Document (*.html)",
|
||||
"json" => "JSON Document (*.json)",
|
||||
"png" => "PNG Image (*.png)",
|
||||
"jpg" | "jpeg" => "JPEG Image (*.jpeg)",
|
||||
_ => "Spreadsheet",
|
||||
};
|
||||
|
||||
let type_obj = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&type_obj, &JsValue::from_str("description"), &JsValue::from_str(type_desc));
|
||||
let _ = js_sys::Reflect::set(&type_obj, &JsValue::from_str("accept"), &accept_obj);
|
||||
|
||||
let types_arr = js_sys::Array::new();
|
||||
types_arr.push(&type_obj);
|
||||
|
||||
let picker_opts = js_sys::Object::new();
|
||||
let _ = js_sys::Reflect::set(&picker_opts, &JsValue::from_str("suggestedName"), &JsValue::from_str(name));
|
||||
let _ = js_sys::Reflect::set(&picker_opts, &JsValue::from_str("types"), &types_arr);
|
||||
|
||||
let prom_val = picker_fn.call1(&window, &picker_opts).map_err(js)?;
|
||||
let prom: js_sys::Promise = prom_val.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
|
||||
let bytes_vec = bytes.to_vec();
|
||||
let name_owned = name.to_string();
|
||||
// Anything but the user cancelling (no user gesture, a denied permission, a failed write)
|
||||
// falls back to an ordinary download, so a save never fails silently.
|
||||
let fallback = move |bytes: &[u8]| {
|
||||
if let Some(w) = web_sys::window()
|
||||
&& let Err(e) = trigger_anchor_download(&w, &name_owned, bytes)
|
||||
{
|
||||
log::error!("download fallback failed: {e}");
|
||||
}
|
||||
};
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match wasm_bindgen_futures::JsFuture::from(prom).await {
|
||||
Ok(handle_val) => {
|
||||
if let Err(e) = write_file_handle(&handle_val, &bytes_vec).await {
|
||||
log::error!("failed writing to file handle: {e}");
|
||||
fallback(&bytes_vec);
|
||||
} else {
|
||||
log::info!("Successfully saved file through save file picker");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let err_name = js_sys::Reflect::get(&e, &JsValue::from_str("name")).ok().and_then(|v| v.as_string()).unwrap_or_default();
|
||||
if err_name == "AbortError" {
|
||||
log::info!("Save file dialog cancelled by user");
|
||||
} else {
|
||||
log::warn!("showSaveFilePicker refused ({err_name}); downloading instead");
|
||||
fallback(&bytes_vec);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Fallback for browsers without showSaveFilePicker (e.g. Firefox, Safari):
|
||||
trigger_anchor_download(&window, name, bytes)
|
||||
}
|
||||
|
||||
async fn write_file_handle(handle: &JsValue, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let create_fn: js_sys::Function = js_sys::Reflect::get(handle, &JsValue::from_str("createWritable"))
|
||||
.map_err(js)?
|
||||
.dyn_into()
|
||||
.map_err(|_| "createWritable is not a function".to_string())?;
|
||||
let stream_prom: js_sys::Promise = create_fn.call0(handle).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
let stream = wasm_bindgen_futures::JsFuture::from(stream_prom).await.map_err(js)?;
|
||||
|
||||
let write_fn: js_sys::Function =
|
||||
js_sys::Reflect::get(&stream, &JsValue::from_str("write")).map_err(js)?.dyn_into().map_err(|_| "write is not a function".to_string())?;
|
||||
let uint8 = js_sys::Uint8Array::from(bytes);
|
||||
let write_prom: js_sys::Promise = write_fn.call1(&stream, &uint8).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
wasm_bindgen_futures::JsFuture::from(write_prom).await.map_err(js)?;
|
||||
|
||||
let close_fn: js_sys::Function =
|
||||
js_sys::Reflect::get(&stream, &JsValue::from_str("close")).map_err(js)?.dyn_into().map_err(|_| "close is not a function".to_string())?;
|
||||
let close_prom: js_sys::Promise = close_fn.call0(&stream).map_err(js)?.dyn_into().map_err(|_| "not a promise".to_string())?;
|
||||
wasm_bindgen_futures::JsFuture::from(close_prom).await.map_err(js)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trigger_anchor_download(window: &web_sys::Window, name: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let document = window.document().ok_or("no document")?;
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type(mime_for(name));
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor".to_string())?;
|
||||
a.set_href(&url);
|
||||
a.set_download(name);
|
||||
a.style().set_property("display", "none").map_err(js)?;
|
||||
|
||||
@@ -24,12 +24,17 @@ image = { workspace = true }
|
||||
winresource = "0.1"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d27646a5f7c8b4fc85d9dd3213b8c88b58e0088d" }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
|
||||
arboard = { workspace = true, features = ["wayland-data-control"] }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe.
|
||||
pollster = "1"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
muda = { version = "0.21", default-features = false }
|
||||
# Finder double-click, Open With, Dock drops and `open -a GridCraft file.xlsx` arrive as a
|
||||
@@ -37,3 +42,13 @@ muda = { version = "0.21", default-features = false }
|
||||
# by PdfCraft and PhotoCraft) registers the handler (Objective-C interop needs unsafe, which our
|
||||
# workspace forbids) behind a safe API. Pinned exactly: review the diff before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
|
||||
# tests/mac_menu_appkit.rs: reads AppKit's menu bar back. Already in Cargo.lock (muda, winit);
|
||||
# pinned exactly to the same versions.
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
objc2 = "=0.6.5"
|
||||
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSMenu", "NSMenuItem", "NSResponder"] }
|
||||
|
||||
[[test]]
|
||||
name = "mac_menu_appkit"
|
||||
harness = false
|
||||
|
||||
+202
-17
@@ -1,47 +1,232 @@
|
||||
//! Windows graphics instance configuration, applied before wgpu can initialize any driver.
|
||||
//!
|
||||
//! Vulkan is never initialized unless `WGPU_BACKEND` asks for it: enumerating Vulkan adapters
|
||||
//! crashes inside Intel's `igvk64.dll` on some UHD Graphics drivers (#120), and that access
|
||||
//! violation happens in the driver, where no Rust error handling can catch it.
|
||||
//!
|
||||
//! DirectX 12 shaders are compiled with FXC (`d3dcompiler_47.dll`, part of Windows), never with
|
||||
//! whichever `dxcompiler.dll` the DLL search path happens to find (#339, #354): see
|
||||
//! [`dx12_compiler`].
|
||||
|
||||
use eframe::{NativeOptions, egui_wgpu::WgpuSetup, wgpu::Backends};
|
||||
use eframe::{
|
||||
NativeOptions,
|
||||
egui_wgpu::WgpuSetup,
|
||||
wgpu::{Backends, DeviceType, 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>) {
|
||||
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
|
||||
// window never appears. Choosing an adapter afterwards is too late: only leaving GL
|
||||
// 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);
|
||||
/// What the start-up probe learned about one DirectX 12 adapter.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Dx12Adapter {
|
||||
/// `Cpu` is WARP (Microsoft's software rasteriser): it works, but every frame is drawn on the
|
||||
/// processor, which makes the app lag on older machines.
|
||||
pub device_type: DeviceType,
|
||||
/// Whether the adapter offers the limits eframe will ask for when it creates the device.
|
||||
pub meets_limits: bool,
|
||||
}
|
||||
|
||||
/// The backends to initialize on Windows.
|
||||
///
|
||||
/// An explicit `backend_override` (normally `Backends::from_env()`, i.e. `WGPU_BACKEND`) always
|
||||
/// wins. Otherwise DirectX 12 only, as long as `dx12_adapters` (what a DirectX 12-only probe found)
|
||||
/// contains a usable hardware GPU. Without one, OpenGL is the way to the GPU: graphics chips whose
|
||||
/// driver has no DirectX 12 support still have an OpenGL driver, and GL can't reach the AMD driver
|
||||
/// crash described in [`configure_backends`], because an AMD GPU with a driver shows up as a
|
||||
/// DirectX 12 adapter and keeps us on DirectX 12. When DirectX 12 offers only WARP, it stays
|
||||
/// enabled next to GL as a last resort for machines without an OpenGL driver either (virtual
|
||||
/// machines): wgpu prefers any GPU over a software adapter, so it's only picked when GL has
|
||||
/// nothing better. Vulkan is never part of the default.
|
||||
pub fn choose_backends(backend_override: Option<Backends>, dx12_adapters: &[Dx12Adapter]) -> Backends {
|
||||
if let Some(backends) = backend_override {
|
||||
return backends;
|
||||
}
|
||||
let hardware = |a: &&Dx12Adapter| a.device_type != DeviceType::Cpu;
|
||||
if dx12_adapters.iter().filter(hardware).any(|a| a.meets_limits) {
|
||||
Backends::DX12
|
||||
} else if !dx12_adapters.is_empty() && !dx12_adapters.iter().any(|a| hardware(&a)) {
|
||||
Backends::DX12 | Backends::GL
|
||||
} else {
|
||||
// No DirectX 12 adapter at all, or only GPUs that can't run the app: GL alone, so a
|
||||
// DirectX 12 GPU that would fail device creation isn't picked over the OpenGL one.
|
||||
Backends::GL
|
||||
}
|
||||
}
|
||||
|
||||
/// The backends for a second start when the first one failed with a graphics error before the
|
||||
/// app was created (no adapter, no device, no surface): the other one of DirectX 12 and OpenGL.
|
||||
/// `None` when `WGPU_BACKEND` chose the backends (the user asked for exactly those) or the first
|
||||
/// start already tried both. Never Vulkan (#120).
|
||||
pub fn fallback_backends(backend_override: Option<Backends>, first: Backends) -> Option<Backends> {
|
||||
if backend_override.is_some() {
|
||||
return None;
|
||||
}
|
||||
let rest = (Backends::DX12 | Backends::GL).difference(first);
|
||||
(!rest.is_empty()).then_some(rest)
|
||||
}
|
||||
|
||||
/// The DirectX 12 shader compiler: `env_choice` (normally `Dx12Compiler::from_env()`, i.e.
|
||||
/// `WGPU_DX12_COMPILER`, for troubleshooting) or else FXC.
|
||||
///
|
||||
/// wgpu's default (`Auto`) loads the first `dxcompiler.dll` on the DLL search path. GridCraft ships
|
||||
/// none, so that is another program's copy (a Windows SDK, an Edge or WebView folder, anything on
|
||||
/// `PATH`). Without a matching `dxil.dll` beside it, DXC prints "DXIL signing library not found",
|
||||
/// wgpu treats that warning as a compile error, its internal compute pipelines fail, the device is
|
||||
/// lost and the app quits before the first frame ("Parent device is lost"). FXC is part of Windows
|
||||
/// and needs no extra DLL; egui's shaders don't need anything newer.
|
||||
pub fn dx12_compiler(env_choice: Option<Dx12Compiler>) -> Dx12Compiler {
|
||||
env_choice.unwrap_or(Dx12Compiler::Fxc)
|
||||
}
|
||||
|
||||
/// Restricts the wgpu instance eframe creates to `backends`, and pins its DirectX 12 shader
|
||||
/// compiler ([`dx12_compiler`]).
|
||||
pub fn configure_backends(options: &mut NativeOptions, backends: Backends) {
|
||||
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.instance_descriptor.backend_options.dx12.shader_compiler = dx12_compiler(Dx12Compiler::from_env());
|
||||
// eframe's default includes Vulkan and GL. Creating the GL backend can crash inside AMD's
|
||||
// atio6axx.dll, and enumerating Vulkan adapters inside Intel's igvk64.dll (#120), before
|
||||
// adapter selection or any Rust error handling runs, so the window never appears.
|
||||
// Choosing an adapter afterwards is too late: only leaving the backend out of the
|
||||
// instance avoids it. This matches the verified WGPU_BACKEND=dx12 workaround without
|
||||
// mutating process environment variables.
|
||||
create.instance_descriptor.backends = backends;
|
||||
}
|
||||
}
|
||||
|
||||
/// Chooses the backends ([`choose_backends`]), applies them to `options` and returns them.
|
||||
/// Without a `backend_override` this first probes DirectX 12 with a short-lived instance of its
|
||||
/// own, which is dropped before eframe creates the real one.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn configure(options: &mut NativeOptions, backend_override: Option<Backends>) -> Backends {
|
||||
let backends = match backend_override {
|
||||
Some(backends) => {
|
||||
log::info!("graphics: WGPU_BACKEND override, backends {backends:?}");
|
||||
backends
|
||||
}
|
||||
None => {
|
||||
let adapters = probe_dx12(options);
|
||||
let backends = choose_backends(None, &adapters);
|
||||
log::info!("graphics: {} DirectX 12 adapter(s) {adapters:?}, backends {backends:?}", adapters.len());
|
||||
backends
|
||||
}
|
||||
};
|
||||
configure_backends(options, backends);
|
||||
backends
|
||||
}
|
||||
|
||||
/// Lists the DirectX 12 adapters, checking each against the limits eframe's device descriptor
|
||||
/// will require. Empty when this build has no DirectX 12 backend.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn probe_dx12(options: &NativeOptions) -> Vec<Dx12Adapter> {
|
||||
use eframe::wgpu::{Instance, InstanceDescriptor};
|
||||
// `Instance::new` panics when the build has no backend for the platform.
|
||||
if !Instance::enabled_backend_features().contains(Backends::DX12) {
|
||||
return Vec::new();
|
||||
}
|
||||
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else {
|
||||
return Vec::new();
|
||||
};
|
||||
let instance = Instance::new(InstanceDescriptor { backends: Backends::DX12, ..InstanceDescriptor::new_without_display_handle() });
|
||||
pollster::block_on(instance.enumerate_adapters(Backends::DX12))
|
||||
.iter()
|
||||
.map(|adapter| {
|
||||
let info = adapter.get_info();
|
||||
let required = (create.device_descriptor)(adapter).required_limits;
|
||||
let meets_limits = required.check_limits(&adapter.limits());
|
||||
log::info!("graphics: DirectX 12 adapter {:?} ({:?}, driver {:?}), limits ok: {meets_limits}", info.name, info.device_type, info.driver);
|
||||
Dx12Adapter { device_type: info.device_type, meets_limits }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn configured_backends(backend_override: Option<Backends>) -> Backends {
|
||||
fn configured_backends(backends: Backends) -> Backends {
|
||||
let mut options = NativeOptions::default();
|
||||
configure(&mut options, backend_override);
|
||||
configure_backends(&mut options, backends);
|
||||
let WgpuSetup::CreateNew(create) = options.wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
create.instance_descriptor.backends
|
||||
}
|
||||
|
||||
const fn adapter(device_type: DeviceType, meets_limits: bool) -> Dx12Adapter {
|
||||
Dx12Adapter { device_type, meets_limits }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_initializes_only_dx12() {
|
||||
// eframe's own default (PRIMARY | GL) would initialize OpenGL as well.
|
||||
fn windows_default_never_initializes_vulkan() {
|
||||
// eframe's own default (PRIMARY | GL) would initialize Vulkan and OpenGL as well.
|
||||
let WgpuSetup::CreateNew(eframe_default) = NativeOptions::default().wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
assert!(eframe_default.instance_descriptor.backends.contains(Backends::GL));
|
||||
assert_eq!(configured_backends(None), Backends::DX12);
|
||||
let gpu = [adapter(DeviceType::IntegratedGpu, true)];
|
||||
assert_eq!(configured_backends(choose_backends(None, &gpu)), Backends::DX12);
|
||||
// #120: whatever the DirectX 12 probe finds, and whatever the retry picks, no Vulkan.
|
||||
let probes: [&[Dx12Adapter]; 4] = [&[], &gpu, &[adapter(DeviceType::Cpu, true)], &[adapter(DeviceType::IntegratedGpu, false)]];
|
||||
for adapters in probes {
|
||||
let first = choose_backends(None, adapters);
|
||||
assert!(!first.contains(Backends::VULKAN), "{adapters:?}");
|
||||
if let Some(second) = fallback_backends(None, first) {
|
||||
assert!(!second.contains(Backends::VULKAN), "{adapters:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_backend_override_is_preserved() {
|
||||
let warp_only = [adapter(DeviceType::Cpu, true)];
|
||||
for backends in [Backends::VULKAN, Backends::GL, Backends::DX12, Backends::VULKAN | Backends::DX12, Backends::empty()] {
|
||||
assert_eq!(configured_backends(Some(backends)), backends);
|
||||
// Whatever the probe would have found, the override wins (the probe doesn't run then),
|
||||
// and a failed start isn't retried with something the user didn't ask for.
|
||||
assert_eq!(choose_backends(Some(backends), &[]), backends);
|
||||
assert_eq!(choose_backends(Some(backends), &warp_only), backends);
|
||||
assert_eq!(configured_backends(backends), backends);
|
||||
assert_eq!(fallback_backends(Some(backends), backends), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gl_when_dx12_has_no_usable_gpu() {
|
||||
// No DirectX 12 driver, so DirectX 12 offers only WARP (or nothing) and lags.
|
||||
let warp_only = [adapter(DeviceType::Cpu, true)];
|
||||
assert_eq!(choose_backends(None, &warp_only), Backends::GL | Backends::DX12);
|
||||
assert_eq!(choose_backends(None, &[]), Backends::GL);
|
||||
// A GPU that can't create eframe's device: GL alone, so it isn't picked over the GL one.
|
||||
let weak_gpu = [adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::Cpu, true)];
|
||||
assert_eq!(choose_backends(None, &weak_gpu), Backends::GL);
|
||||
// Any usable GPU keeps DirectX 12 only, next to WARP or a weaker GPU.
|
||||
let mixed = [adapter(DeviceType::Cpu, true), adapter(DeviceType::IntegratedGpu, false), adapter(DeviceType::DiscreteGpu, true)];
|
||||
assert_eq!(choose_backends(None, &mixed), Backends::DX12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_start_retries_with_the_other_backend() {
|
||||
assert_eq!(fallback_backends(None, Backends::DX12), Some(Backends::GL));
|
||||
assert_eq!(fallback_backends(None, Backends::GL), Some(Backends::DX12));
|
||||
// Both were already tried: nothing left to fall back to.
|
||||
assert_eq!(fallback_backends(None, Backends::DX12 | Backends::GL), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dx12_compiles_shaders_with_fxc_unless_asked() {
|
||||
// #339, #354: wgpu's `Auto` would load a stray dxcompiler.dll and lose the device.
|
||||
assert!(matches!(dx12_compiler(None), Dx12Compiler::Fxc));
|
||||
assert!(matches!(dx12_compiler(Some(Dx12Compiler::Auto)), Dx12Compiler::Auto));
|
||||
assert!(matches!(dx12_compiler(Some(Dx12Compiler::default_dynamic_dxc())), Dx12Compiler::DynamicDxc { .. }));
|
||||
// eframe's own default is `Auto`; the configured instance (first start and retry) uses FXC.
|
||||
let WgpuSetup::CreateNew(eframe_default) = NativeOptions::default().wgpu_options.wgpu_setup else {
|
||||
panic!("default native options must create a wgpu instance");
|
||||
};
|
||||
if Dx12Compiler::from_env().is_none() {
|
||||
assert!(matches!(eframe_default.instance_descriptor.backend_options.dx12.shader_compiler, Dx12Compiler::Auto));
|
||||
let mut options = NativeOptions::default();
|
||||
configure_backends(&mut options, Backends::DX12);
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+168
-50
@@ -16,6 +16,10 @@ mod graphics;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod print;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_ui_egui::{Services, SheetApp};
|
||||
@@ -36,6 +40,10 @@ impl eframe::App for App {
|
||||
apple_events::poll(&self.2, &mut self.0, ctx);
|
||||
}
|
||||
self.0.logic(ctx);
|
||||
self.0.poll_printing(ctx);
|
||||
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
}
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(raw);
|
||||
@@ -50,7 +58,18 @@ impl eframe::App for App {
|
||||
self.0.ui(ui);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
print::finish_pending_jobs();
|
||||
save_prefs(&self.0);
|
||||
// macOS (#117): end the process here, before eframe tears the window down. AccessKit's
|
||||
// macOS adapter subclasses the window's content view and restores its class on teardown;
|
||||
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
|
||||
// `-[_NSTouchBarFinderObservation invalidate]` throws "not registered" and the quit ends
|
||||
// in a crash report. eframe calls `on_exit` on every way of quitting (Quit/⌘Q, the Dock,
|
||||
// the close button, `app.quit`), and nothing after it is needed: the preferences are
|
||||
// saved and the log file is unbuffered. eframe does the same when it doesn't
|
||||
// run-and-return. `on_exit` only runs once the app exists, never on a failed start.
|
||||
#[cfg(target_os = "macos")]
|
||||
std::process::exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +103,8 @@ fn load_prefs(app: &mut SheetApp) {
|
||||
}
|
||||
// First run (or a ui.json without a usable language): follow the desktop's language.
|
||||
app.ui.language = gridcraft_ui_egui::i18n::Language::system();
|
||||
// ...and its light or dark appearance (#239), until a theme is chosen and saved in ui.json.
|
||||
app.ui.system_theme = true;
|
||||
let Some(dir) = config_dir() else { return };
|
||||
if let Ok(b) = std::fs::read(dir.join("ui.json"))
|
||||
&& let Ok(ui) = serde_json::from_slice::<gridcraft_ui_egui::UiState>(&b)
|
||||
@@ -114,20 +135,37 @@ fn save_prefs(app: &SheetApp) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the system clipboard through the shared handle, creating it on first use.
|
||||
fn read_clipboard<T>(
|
||||
handle: &RefCell<Option<arboard::Clipboard>>,
|
||||
read: impl FnOnce(&mut arboard::Clipboard) -> Result<T, arboard::Error>,
|
||||
) -> Option<T> {
|
||||
let mut clipboard = handle.try_borrow_mut().ok()?;
|
||||
if clipboard.is_none() {
|
||||
*clipboard = arboard::Clipboard::new().ok();
|
||||
}
|
||||
read(clipboard.as_mut()?).ok()
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
// Keep the owner alive: X11/Wayland serve clipboard data from this handle.
|
||||
let mut clipboard: Option<arboard::Clipboard> = None;
|
||||
let clipboard: Rc<RefCell<Option<arboard::Clipboard>>> = Rc::default();
|
||||
let (html_clipboard, text_clipboard) = (clipboard.clone(), clipboard.clone());
|
||||
Services {
|
||||
copy_html: Some(Box::new(move |html, text| {
|
||||
let mut clipboard = clipboard.borrow_mut();
|
||||
if clipboard.is_none() {
|
||||
clipboard = Some(arboard::Clipboard::new().map_err(|e| e.to_string())?);
|
||||
*clipboard = Some(arboard::Clipboard::new().map_err(|e| e.to_string())?);
|
||||
}
|
||||
clipboard.as_mut().ok_or("clipboard unavailable")?.set_html(html, Some(text)).map_err(|e| e.to_string())
|
||||
})),
|
||||
paste_html: Some(Box::new(move || read_clipboard(&html_clipboard, |clipboard| clipboard.get().html()))),
|
||||
paste_text: Some(Box::new(move || read_clipboard(&text_clipboard, |clipboard| clipboard.get_text()))),
|
||||
pick_open: Some(Box::new(|| {
|
||||
rfd::FileDialog::new()
|
||||
.add_filter("Spreadsheets", &["xlsx", "xlsm", "xlsb", "ods", "csv", "tsv", "txt", "json"])
|
||||
.add_filter("Spreadsheets", &["xlsx", "xlsm", "xls", "xlsb", "ods", "csv", "tsv", "txt", "json"])
|
||||
.add_filter("Excel Workbook", &["xlsx", "xlsm"])
|
||||
.add_filter("Excel 97-2003 Workbook (import)", &["xls"])
|
||||
.add_filter("Excel Binary Workbook (data import)", &["xlsb"])
|
||||
.add_filter("OpenDocument Spreadsheet (data import)", &["ods"])
|
||||
.add_filter("CSV", &["csv"])
|
||||
@@ -141,30 +179,51 @@ fn services() -> Services {
|
||||
.and_then(|p| p.to_str().map(str::to_string))
|
||||
})),
|
||||
pick_save: Some(Box::new(|suggested: &str| {
|
||||
let stem = std::path::Path::new(suggested).file_stem().and_then(|s| s.to_str()).unwrap_or("Book1").to_string();
|
||||
rfd::FileDialog::new()
|
||||
.set_file_name(format!("{stem}.xlsx"))
|
||||
.add_filter("Excel Workbook (.xlsx)", &["xlsx"])
|
||||
.add_filter("CSV UTF-8 (.csv)", &["csv"])
|
||||
.add_filter("Web Page (.html)", &["html"])
|
||||
.save_file()
|
||||
.and_then(|p| p.to_str().map(str::to_string))
|
||||
})),
|
||||
open_url: Some(Box::new(|url: &str| {
|
||||
let cmd = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let _ = std::process::Command::new(cmd).arg(url).spawn();
|
||||
let path = std::path::Path::new(suggested);
|
||||
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Book1").to_string();
|
||||
// The suggested name's type (an export asks for .pdf, .csv or .html) comes first.
|
||||
const TYPES: [(&str, &str); 4] =
|
||||
[("Excel Workbook (.xlsx)", "xlsx"), ("CSV UTF-8 (.csv)", "csv"), ("Web Page (.html)", "html"), ("PDF (.pdf)", "pdf")];
|
||||
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).filter(|e| TYPES.iter().any(|(_, x)| x == e));
|
||||
let ext = ext.unwrap_or_else(|| "xlsx".to_string());
|
||||
let mut dialog = rfd::FileDialog::new().set_file_name(format!("{stem}.{ext}"));
|
||||
for (label, x) in TYPES.iter().filter(|(_, x)| *x == ext).chain(TYPES.iter().filter(|(_, x)| *x != ext)) {
|
||||
dialog = dialog.add_filter(*label, &[*x]);
|
||||
}
|
||||
dialog.save_file().and_then(|p| p.to_str().map(str::to_string))
|
||||
})),
|
||||
open_url: Some(Box::new(|url: &str| open_with_system(url))),
|
||||
printers: Some(print::discover()),
|
||||
print_native: Some(print::submit()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a URL or file with the system's default application.
|
||||
fn open_with_system(target: &str) {
|
||||
// Last line of defence behind `link.open` and the click prompt: the system only ever gets
|
||||
// http, https and mailto addresses.
|
||||
let gridcraft_engine::links::LinkKind::External(target) = gridcraft_engine::links::classify(target) else {
|
||||
log::warn!("refused to open {target:?}: only http, https and mailto links are opened");
|
||||
return;
|
||||
};
|
||||
let target = target.as_str();
|
||||
let cmd = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
if let Err(e) = std::process::Command::new(cmd).arg(target).spawn() {
|
||||
log::warn!("{cmd} {target}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn icon() -> Option<egui::IconData> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let bytes = include_bytes!("../../../assets/app-icon/gridcraft-macos-512.png");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let bytes = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png");
|
||||
let img = image::load_from_memory(bytes).ok()?.to_rgba8();
|
||||
Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() })
|
||||
@@ -235,18 +294,20 @@ fn main() -> eframe::Result<()> {
|
||||
{
|
||||
log::warn!("sample {s}: {e}");
|
||||
}
|
||||
for f in &files {
|
||||
if let Err(e) = session.execute("file.open", json!({"path": f})) {
|
||||
log::warn!("{f}: {e}");
|
||||
}
|
||||
}
|
||||
if session.documents().is_empty() {
|
||||
session.new_workbook();
|
||||
}
|
||||
let mut app = SheetApp::new(session, services());
|
||||
app.after_engine(); // Show warnings from files opened on the command line.
|
||||
app.watch_desktop_theme();
|
||||
app.after_engine(); // Show warnings from the sample.
|
||||
let control_port = control_port;
|
||||
load_prefs(&mut app);
|
||||
// Files named on the command line (a double-click on Windows and Linux) open as File › Open
|
||||
// opens them: a password-protected one asks for its password, and errors are shown, not
|
||||
// only logged. Each replaces the untouched blank Book1, as a file opened from Finder does.
|
||||
for f in &files {
|
||||
app.open_path(f);
|
||||
}
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_title("GridCraft")
|
||||
.with_inner_size([1440.0, 900.0])
|
||||
@@ -260,37 +321,94 @@ fn main() -> eframe::Result<()> {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
let options = eframe::NativeOptions { viewport, ..Default::default() };
|
||||
// Before eframe creates the wgpu instance: default Windows to DirectX 12 only (see graphics.rs).
|
||||
// Before eframe creates the wgpu instance: Windows starts on DirectX 12, or OpenGL when
|
||||
// DirectX 12 has no GPU driver, and never touches Vulkan unless asked (see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
let options = {
|
||||
let backend_override = eframe::wgpu::Backends::from_env();
|
||||
#[cfg(target_os = "windows")]
|
||||
let (options, first_backends) = {
|
||||
let mut options = options;
|
||||
graphics::configure(&mut options, eframe::wgpu::Backends::from_env());
|
||||
options
|
||||
let backends = graphics::configure(&mut options, backend_override);
|
||||
(options, backends)
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
let retry_options = options.clone();
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = apple_events::AppleEvents::install();
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
eframe::run_native(
|
||||
"GridCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
|
||||
if let Some(port) = control_port {
|
||||
match control_server::start(port, cc.egui_ctx.clone()) {
|
||||
Ok(rx) => app.control_rx = Some(rx),
|
||||
Err(e) => log::error!("control channel on port {port}: {e}"),
|
||||
// The app waits here until a start gets as far as creating it; a start that fails before
|
||||
// (no graphics adapter, device or surface) leaves it here for the next attempt.
|
||||
let pending = std::cell::Cell::new(Some(app));
|
||||
let run = |options: eframe::NativeOptions| {
|
||||
eframe::run_native(
|
||||
"GridCraft",
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
let Some(mut app) = pending.take() else {
|
||||
return Err("the app was already created".into());
|
||||
};
|
||||
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
|
||||
if let Some(port) = control_port {
|
||||
match control_server::start(port, cc.egui_ctx.clone()) {
|
||||
Ok(rx) => app.control_rx = Some(rx),
|
||||
Err(e) => log::error!("control channel on port {port}: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events.connect(&cc.egui_ctx),
|
||||
)))
|
||||
}),
|
||||
)
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events.connect(&cc.egui_ctx),
|
||||
)))
|
||||
}),
|
||||
)
|
||||
};
|
||||
let result = run(options);
|
||||
// A graphics error before the app existed: start once more with the other backend (eframe
|
||||
// reuses its event loop for the second run). Errors after that, or from winit, are returned.
|
||||
#[cfg(target_os = "windows")]
|
||||
if let Err(eframe::Error::Wgpu(e)) = &result
|
||||
&& let Some(app) = pending.take()
|
||||
&& let Some(backends) = graphics::fallback_backends(backend_override, first_backends)
|
||||
{
|
||||
log::error!("graphics: the renderer didn't start on {first_backends:?} ({e}); trying {backends:?}");
|
||||
pending.set(Some(app));
|
||||
let mut options = retry_options;
|
||||
graphics::configure_backends(&mut options, backends);
|
||||
return run(options);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod packaging_tests {
|
||||
use gridcraft_engine::io::FileKind;
|
||||
|
||||
/// The text between `start` and `end` that follows each `marker` in `text`, sorted (e.g. the
|
||||
/// `xlsb` in `Classes\.xlsb\OpenWithProgids`).
|
||||
fn extensions(text: &str, marker: &str, start: &str, end: char) -> Vec<String> {
|
||||
let mut v: Vec<String> = text.split(marker).skip(1).filter_map(|s| s.split_once(start)?.1.split(end).next()).map(str::to_string).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// macOS Open With (`CFBundleDocumentTypes`) offers GridCraft for the same files as Windows
|
||||
/// Open with, and GridCraft opens each of them. #321 added `.xlsb` and `.ods` on Windows and
|
||||
/// Linux only.
|
||||
#[test]
|
||||
fn macos_and_windows_offer_the_same_file_types() {
|
||||
let plist = include_str!("../../../packaging/macos/Info.plist.in");
|
||||
let wxs = include_str!("../../../packaging/windows/gridcraft.wxs");
|
||||
let mac = extensions(plist, "<key>CFBundleTypeExtensions</key>", "<string>", '<');
|
||||
let win = extensions(wxs, "Key=\"Software\\Classes\\.", "", '\\');
|
||||
assert!(mac.iter().any(|e| e == "xlsx"), "Info.plist.in extensions not found: {mac:?}");
|
||||
assert_eq!(mac, win);
|
||||
for ext in &mac {
|
||||
assert!(FileKind::from_path(&format!("book.{ext}")).is_some(), "GridCraft doesn't open .{ext}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,13 +24,14 @@ fn tree() -> Vec<(&'static str, Vec<Entry>)> {
|
||||
("Close", "file.close", Some("CMD+W")),
|
||||
("Save", "file.save", Some("CMD+S")),
|
||||
("Save As…", "file.saveAs", Some("CMD+SHIFT+S")),
|
||||
("Export as PDF…", "file.exportPdf", None),
|
||||
("Export as CSV…", "dialog:saveCopy:csv", None),
|
||||
("Save as Web Page…", "dialog:saveCopy:html", None),
|
||||
("-", "", None),
|
||||
("Page Setup…", "dialog:pageSetup", None),
|
||||
("Print…", "file.print", Some("CMD+P")),
|
||||
("-", "", None),
|
||||
("Properties…", "file.properties", None),
|
||||
("Properties…", "dialog:backstage:info", None),
|
||||
],
|
||||
),
|
||||
(
|
||||
@@ -160,6 +161,8 @@ fn tree() -> Vec<(&'static str, Vec<Entry>)> {
|
||||
("-", "", None),
|
||||
("Group", "data.group", None),
|
||||
("Ungroup", "data.ungroup", None),
|
||||
("Show Detail", "data.showDetail", None),
|
||||
("Hide Detail", "data.hideDetail", None),
|
||||
("Subtotal…", "dialog:subtotal", None),
|
||||
("-", "", None),
|
||||
("Calculate Now", "formulas.calculateNow", None),
|
||||
@@ -213,6 +216,7 @@ impl NativeMenu {
|
||||
]);
|
||||
let _ = menu.append(&app_menu);
|
||||
let mut theme_items = Vec::new();
|
||||
let mut window_menu = None;
|
||||
for (title, entries) in tree() {
|
||||
let sub = Submenu::new(title, true);
|
||||
for (label, id, acc) in entries {
|
||||
@@ -235,8 +239,17 @@ impl NativeMenu {
|
||||
let _ = sub.append(&item);
|
||||
}
|
||||
let _ = menu.append(&sub);
|
||||
if title == "Window" {
|
||||
window_menu = Some(sub);
|
||||
}
|
||||
}
|
||||
menu.init_for_nsapp();
|
||||
// NSApp's windowsMenu is where macOS adds Move & Resize, Fill and Center, the targets of the
|
||||
// system tiling shortcuts (Fn+Ctrl+arrows, Fn+F). Only once the menu is NSApp's: muda looks
|
||||
// the submenu up in the installed main menu.
|
||||
if let Some(window) = window_menu {
|
||||
window.set_as_windows_menu_for_nsapp();
|
||||
}
|
||||
let (tx, rx) = channel();
|
||||
let ctx = ctx.clone();
|
||||
MenuEvent::set_event_handler(Some(move |e: MenuEvent| {
|
||||
@@ -289,12 +302,15 @@ impl NativeMenu {
|
||||
("note", _) => json!({"threaded": false}),
|
||||
("comment", _) => json!({"threaded": true}),
|
||||
("about", tab) => json!({"tab": tab}),
|
||||
("backstage", page) => json!({"page": page}),
|
||||
_ => json!({}),
|
||||
};
|
||||
let name = if name == "note" { "comment" } else { name };
|
||||
app.open_dialog(name, params);
|
||||
} else if id == "edit.copy" || id == "edit.cut" {
|
||||
app.copy_to_clipboard(ctx, &id);
|
||||
} else if id == "edit.paste" {
|
||||
app.paste_from_clipboard();
|
||||
} else {
|
||||
app.run_or_alert(&id, json!({}));
|
||||
}
|
||||
@@ -312,6 +328,15 @@ impl NativeMenu {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn file_menu_has_export_as_pdf_dispatching_the_command() {
|
||||
let tree = tree();
|
||||
let (_, file) = tree.iter().find(|(title, _)| *title == "File").expect("File menu");
|
||||
let item = file.iter().find(|e| e.0 == "Export as PDF…").expect("Export as PDF… in the File menu");
|
||||
assert_eq!(item.1, "file.exportPdf");
|
||||
assert!(gridcraft_engine::find_command("file.exportPdf").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_choices_use_the_shared_preference_command() {
|
||||
let mut app = SheetApp::new(gridcraft_engine::Session::new(), Default::default());
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
|
||||
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
|
||||
|
||||
pub fn discover() -> Discover {
|
||||
Box::new(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
|
||||
let printers = craft_print::printers().into_iter().map(|printer| Printer { name: printer.name, default: printer.default }).collect();
|
||||
let _ = sender.send(printers);
|
||||
});
|
||||
receiver
|
||||
})
|
||||
}
|
||||
|
||||
// Keep submission workers reachable until normal app shutdown; dropping a JoinHandle would
|
||||
// let process exit kill PowerShell/CUPS before it hands the job to the spooler.
|
||||
static JOBS: std::sync::Mutex<Vec<std::thread::JoinHandle<()>>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
pub fn finish_pending_jobs() {
|
||||
let workers = std::mem::take(&mut *JOBS.lock().unwrap_or_else(|poison| poison.into_inner()));
|
||||
for worker in workers {
|
||||
if worker.join().is_err() {
|
||||
log::error!("the print worker stopped unexpectedly during shutdown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn submit() -> Submit {
|
||||
Box::new(|bytes, settings: Settings| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
|
||||
let job = craft_print::Job {
|
||||
printer: Some(settings.printer),
|
||||
copies: settings.copies.clamp(1, 999),
|
||||
duplex: settings.duplex.map(|value| match value {
|
||||
Duplex::LongEdge => craft_print::Duplex::LongEdge,
|
||||
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
|
||||
Duplex::Off => craft_print::Duplex::Off,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
title: "GridCraft document".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let _ = sender.send(craft_print::submit(&bytes, &job).map_err(|error| error.to_string()));
|
||||
});
|
||||
if let Ok(worker) = worker {
|
||||
let mut jobs = JOBS.lock().unwrap_or_else(|poison| poison.into_inner());
|
||||
jobs.retain(|job| !job.is_finished());
|
||||
jobs.push(worker);
|
||||
}
|
||||
receiver
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn shutdown_waits_for_pending_submission_workers() {
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
let (completed, completion) = std::sync::mpsc::channel();
|
||||
let worker = std::thread::spawn(move || {
|
||||
wait.recv().unwrap();
|
||||
completed.send(()).unwrap();
|
||||
});
|
||||
JOBS.lock().unwrap().push(worker);
|
||||
let shutdown = std::thread::spawn(finish_pending_jobs);
|
||||
assert!(completion.try_recv().is_err(), "the print worker is still pending");
|
||||
release.send(()).unwrap();
|
||||
shutdown.join().unwrap();
|
||||
completion.recv().unwrap();
|
||||
assert!(JOBS.lock().unwrap().is_empty(), "workers were joined before shutdown returned");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The macOS menu bar as AppKit sees it, on the main thread (`harness = false`): install it through
|
||||
//! the real muda backend (`src/native_menu.rs`) and read NSApp back. The Window menu must be NSApp's
|
||||
//! `windowsMenu`: that is where macOS adds Move & Resize, Fill and Center, the targets of the system
|
||||
//! window tiling shortcuts (Fn+Ctrl+arrows, Fn+F), and lists the open windows (#716).
|
||||
|
||||
// The app's own module, built into this test (cargo builds harness = false tests with cfg(test), so its
|
||||
// unit tests compile here too without a harness to run them).
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "../src/native_menu.rs"]
|
||||
#[allow(unused_imports, dead_code)]
|
||||
mod native_menu;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn main() {
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::NSApplication;
|
||||
|
||||
let mtm = MainThreadMarker::new().expect("harness = false runs on the main thread");
|
||||
let nsapp = NSApplication::sharedApplication(mtm);
|
||||
nsapp.finishLaunching();
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
let _menu = native_menu::NativeMenu::install(&ctx);
|
||||
|
||||
let bar = nsapp.mainMenu().expect("a main menu");
|
||||
let tops: Vec<String> = (0..bar.numberOfItems()).filter_map(|i| bar.itemAtIndex(i)?.submenu()).map(|m| m.title().to_string()).collect();
|
||||
assert_eq!(tops, ["GridCraft", "File", "Edit", "View", "Insert", "Format", "Tools", "Data", "Window", "Help"]);
|
||||
assert_eq!(nsapp.windowsMenu().map(|m| m.title().to_string()).as_deref(), Some("Window"), "AppKit knows the Window menu");
|
||||
|
||||
println!("mac_menu_appkit: ok");
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn main() {}
|
||||
@@ -28,3 +28,40 @@ sync_github_name = false
|
||||
|
||||
[people.edurbs]
|
||||
sync_github_name = true
|
||||
|
||||
[people.arcanii]
|
||||
real_name = "Bryan Mark"
|
||||
display_name = "Arcanii"
|
||||
sync_github_name = false
|
||||
|
||||
[people.vangel76]
|
||||
real_name = "Valentin Klein"
|
||||
sync_github_name = true
|
||||
|
||||
[people.MacJedi42]
|
||||
sync_github_name = true
|
||||
|
||||
[people.alexanderalber]
|
||||
real_name = "Alexander Alber"
|
||||
|
||||
[people.webdevtodayjason]
|
||||
display_name = "Jason Brashear"
|
||||
sync_github_name = false
|
||||
|
||||
[people.Losminek]
|
||||
sync_github_name = true
|
||||
|
||||
[people.GhostMitra]
|
||||
sync_github_name = true
|
||||
|
||||
[people.shrshk]
|
||||
real_name = "Shirish Veerabattini"
|
||||
sync_github_name = true
|
||||
[people.jsymes21-byte]
|
||||
real_name = "James Symes"
|
||||
sync_github_name = true
|
||||
|
||||
|
||||
[people.Silvertree2010]
|
||||
display_name = "Netter"
|
||||
sync_github_name = false
|
||||
|
||||
+418
-60
@@ -71,6 +71,11 @@ pub trait Host {
|
||||
fn used_range(&mut self, sheet: usize) -> Option<RangeRef> {
|
||||
self.workbook().sheet(sheet).and_then(|s| s.used_range())
|
||||
}
|
||||
/// Calls `f` on each stored value of a block, row-major (formula cells evaluated first),
|
||||
/// until `f` returns false. `false` when this host can't (callers use `range_values`).
|
||||
fn visit_range(&mut self, _sheet: usize, _range: RangeRef, _f: &mut dyn FnMut(&Value) -> bool) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Evaluator<'h> {
|
||||
@@ -83,6 +88,8 @@ pub struct Evaluator<'h> {
|
||||
|
||||
struct FnCtx<'a, 'h> {
|
||||
ev: &'a mut Evaluator<'h>,
|
||||
/// The criteria argument of a database function, when it is a reference.
|
||||
criteria: Option<Area>,
|
||||
}
|
||||
|
||||
impl Ctx for FnCtx<'_, '_> {
|
||||
@@ -95,6 +102,28 @@ impl Ctx for FnCtx<'_, '_> {
|
||||
fn random(&mut self) -> f64 {
|
||||
self.ev.host.random()
|
||||
}
|
||||
/// Excel's "formula as criteria": the formula is written for the first record, so its relative
|
||||
/// references move down to `record`'s row, and the database's labels name its fields.
|
||||
/// Known gap: the shifted references are not dependencies of the calling cell. One that lands
|
||||
/// outside both the database and the criteria cell's own precedents (say `=G2<H2` with column H
|
||||
/// outside the database) is read here but not tracked, so editing that cell doesn't recalculate
|
||||
/// the D-function until something else does.
|
||||
fn computed_criterion(&mut self, row: usize, col: usize, db: &Array, record: usize) -> Option<bool> {
|
||||
let area = self.criteria?;
|
||||
let at = area.range.start.offset(row as i64, col as i64).filter(|c| area.range.contains(*c))?;
|
||||
let expr = self.ev.host.workbook().sheet(area.sheet)?.cell(at)?.formula.as_ref()?.expr_arc()?;
|
||||
let shifted = gridcraft_formula::adjust::shift_relative((*expr).clone(), record as i64 - 1, 0);
|
||||
let env = (0..db.cols)
|
||||
.filter_map(|c| match db.get(0, c) {
|
||||
Some(Value::Text(t)) if !t.trim().is_empty() => {
|
||||
Some((t.trim().to_string(), Ev::V(db.get(record, c).cloned().unwrap_or(Value::Empty))))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut ev = Evaluator { host: &mut *self.ev.host, sheet: area.sheet, at, env, depth: self.ev.depth };
|
||||
Some(matches!(ev.value(&shifted).scalar().to_bool(), Ok(true)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'h> Evaluator<'h> {
|
||||
@@ -244,6 +273,13 @@ impl<'h> Evaluator<'h> {
|
||||
let scope = def.scope.unwrap_or(self.sheet);
|
||||
return match gridcraft_formula::parse(&text) {
|
||||
Ok(expr) => {
|
||||
// Relative references in a name are relative to A1: used here, they move by
|
||||
// this cell's offset from it.
|
||||
let expr = if gridcraft_formula::adjust::has_relative_refs(&expr) {
|
||||
gridcraft_formula::adjust::shift_relative_wrapping(expr, self.at.row as i64, self.at.col as i64)
|
||||
} else {
|
||||
expr
|
||||
};
|
||||
let saved = self.sheet;
|
||||
// Unqualified references in a name refer to the scope sheet.
|
||||
self.sheet = scope;
|
||||
@@ -340,6 +376,9 @@ impl<'h> Evaluator<'h> {
|
||||
}
|
||||
|
||||
fn unary(&mut self, op: UnOp, x: &Expr) -> Ev {
|
||||
if let UnOp::Trim(mode) = op {
|
||||
return self.trim_ref(mode, x);
|
||||
}
|
||||
if op == UnOp::Spill {
|
||||
return match self.eval(x) {
|
||||
Ev::R(areas) => match areas.as_slice() {
|
||||
@@ -368,15 +407,17 @@ impl<'h> Evaluator<'h> {
|
||||
};
|
||||
}
|
||||
let v = self.value(x);
|
||||
let sys = self.host.workbook().date_system;
|
||||
Ev::V(map_unary(
|
||||
&v,
|
||||
&|n| match op {
|
||||
UnOp::Neg => Value::number(-n),
|
||||
UnOp::Plus => Value::number(n),
|
||||
UnOp::Percent => Value::number(n / 100.0),
|
||||
UnOp::At | UnOp::Spill => Value::number(n),
|
||||
UnOp::At | UnOp::Spill | UnOp::Trim(_) => Value::number(n),
|
||||
},
|
||||
op == UnOp::Plus,
|
||||
sys,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -450,9 +491,22 @@ impl<'h> Evaluator<'h> {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let x = self.value(a);
|
||||
let y = self.value(b);
|
||||
Ev::V(binary_values(op, &x, &y))
|
||||
// A long chain such as A1+A2+…+A500 nests to the left: fold it in a loop instead
|
||||
// of one level of recursion per operator (past the depth limit it was #CALC!).
|
||||
let mut rest = vec![(op, b)];
|
||||
let mut left = a;
|
||||
while let Expr::Binary(o, l, r) = left
|
||||
&& !matches!(o, BinOp::Range | BinOp::Union | BinOp::Intersect)
|
||||
{
|
||||
rest.push((*o, r.as_ref()));
|
||||
left = l.as_ref();
|
||||
}
|
||||
let mut acc = self.value(left);
|
||||
while let Some((o, r)) = rest.pop() {
|
||||
let y = self.value(r);
|
||||
acc = binary_values(o, &acc, &y, self.host.workbook().date_system);
|
||||
}
|
||||
Ev::V(acc)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -554,7 +608,20 @@ impl<'h> Evaluator<'h> {
|
||||
if args.len() < 2 {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let i = match self.arg_num(args, 0, 0.0) {
|
||||
let index = self.value(&args[0]);
|
||||
if let Value::Array(_) = index {
|
||||
// An array of indexes picks element by element: `CHOOSE({1,2},A1:A3,B1:B3)`
|
||||
// is a two-column array. The library CHOOSE lifts over its arguments.
|
||||
let Some(spec) = gridcraft_functions::lookup(name) else { return err(CellError::Name) };
|
||||
let mut evaluated = vec![Arg { value: index, from_ref: false }];
|
||||
for a in &args[1..] {
|
||||
let value = self.value(a);
|
||||
evaluated.push(Arg { value, from_ref: false });
|
||||
}
|
||||
let mut ctx = FnCtx { ev: self, criteria: None };
|
||||
return gridcraft_functions::call(spec, &evaluated, &mut ctx).pipe(Ev::V);
|
||||
}
|
||||
let i = match index.to_number() {
|
||||
Ok(n) => n.trunc() as i64,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
@@ -663,7 +730,9 @@ impl<'h> Evaluator<'h> {
|
||||
"OFFSET" => self.offset(args),
|
||||
"INDIRECT" => self.indirect(args),
|
||||
"INDEX" => self.index(args),
|
||||
"XLOOKUP" => self.xlookup(args),
|
||||
"CELL" => self.cell_info(args),
|
||||
"TRIMRANGE" => self.trimrange(args),
|
||||
"SUBTOTAL" | "AGGREGATE" => self.subtotal(name, args),
|
||||
"TEXT" => {
|
||||
if args.len() != 2 {
|
||||
@@ -707,6 +776,20 @@ impl<'h> Evaluator<'h> {
|
||||
Ev::V(Value::Bool(r))
|
||||
}
|
||||
"MAP" | "REDUCE" | "SCAN" | "BYROW" | "BYCOL" | "MAKEARRAY" => self.higher_order(name, args),
|
||||
"GROUPBY" | "PIVOTBY" => {
|
||||
// The aggregation may be a function given by name (`SUM`): pass it as its name.
|
||||
let i = if name == "GROUPBY" { 2 } else { 3 };
|
||||
match args.get(i).and_then(|a| self.function_by_name(a)) {
|
||||
Some(f) => {
|
||||
let mut args = args.to_vec();
|
||||
if let Some(a) = args.get_mut(i) {
|
||||
*a = Expr::Text(f.into());
|
||||
}
|
||||
self.builtin(name, &args)
|
||||
}
|
||||
None => self.builtin(name, args),
|
||||
}
|
||||
}
|
||||
"NOW" | "TODAY" | "RAND" | "RANDBETWEEN" | "RANDARRAY" => {
|
||||
self.host.note_volatile();
|
||||
self.builtin(name, args)
|
||||
@@ -726,11 +809,23 @@ impl<'h> Evaluator<'h> {
|
||||
if args.len() < spec.min_args || args.len() > spec.max_args {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
if let Some(kind) = Agg::of(spec.name) {
|
||||
return self.aggregate(kind, args);
|
||||
}
|
||||
let mut evaluated = Vec::with_capacity(args.len());
|
||||
// SUMIF/AVERAGEIF: the size of the criteria range (argument 1), which the sum range takes.
|
||||
let mut criteria_shape = None;
|
||||
// Database functions: the criteria range (argument 2), whose formulas are computed criteria.
|
||||
let mut criteria = None;
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
let mut ev = self.eval(a);
|
||||
if spec.category == gridcraft_functions::Category::Database
|
||||
&& i == 2
|
||||
&& let Ev::R(areas) = &ev
|
||||
&& let [area] = areas.as_slice()
|
||||
{
|
||||
criteria = Some(*area);
|
||||
}
|
||||
if resizes_sum_range(name, args.len()) {
|
||||
if i == 0 {
|
||||
criteria_shape = ev_shape(&ev);
|
||||
@@ -758,12 +853,81 @@ impl<'h> Evaluator<'h> {
|
||||
};
|
||||
evaluated.push(Arg { value, from_ref });
|
||||
}
|
||||
let mut ctx = FnCtx { ev: self };
|
||||
let mut ctx = FnCtx { ev: self, criteria };
|
||||
gridcraft_functions::call(spec, &evaluated, &mut ctx).pipe(Ev::V)
|
||||
}
|
||||
|
||||
/// Performs aggregation operations without copying its ranges: blocks are folded over the stored
|
||||
/// cells, so no array is built and there is no `MAX_CELLS` limit. Arguments are evaluated and read one
|
||||
/// after another, as the array path does, so volatile formulas (like `RAND`) see the same order.
|
||||
/// Only `SUM`, `COUNT` and `AVG` are supported currently.
|
||||
fn aggregate(&mut self, kind: Agg, args: &[Expr]) -> Ev {
|
||||
let mut acc = Acc::default();
|
||||
let mut first_error = None;
|
||||
for a in args {
|
||||
let ev = self.eval(a);
|
||||
let steps = match ev {
|
||||
Ev::R(areas) => areas.iter().map(|area| self.aggregate_area(kind, area, &mut acc)).collect(),
|
||||
ev => {
|
||||
let value = self.deref(ev);
|
||||
vec![self.aggregate_value(kind, value, false, &mut acc)]
|
||||
}
|
||||
};
|
||||
if first_error.is_none() {
|
||||
first_error = steps.into_iter().find_map(Result::err);
|
||||
}
|
||||
}
|
||||
first_error.unwrap_or_else(|| Ev::V(acc.finish(kind)))
|
||||
}
|
||||
|
||||
/// Adds one area to `acc`; `Err` is the result the function ends with.
|
||||
fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> {
|
||||
if !a.range.is_single() {
|
||||
let mut error = None;
|
||||
let walked = self.host.visit_range(a.sheet, a.range, &mut |v| match acc.add_cell(kind, v) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
error = Some(e);
|
||||
false
|
||||
}
|
||||
});
|
||||
if walked {
|
||||
return error.map_or(Ok(()), |e| Err(err(e)));
|
||||
}
|
||||
}
|
||||
let value = self.area_value(a);
|
||||
self.aggregate_value(kind, value, true, acc)
|
||||
}
|
||||
|
||||
/// Adds one argument's value by calling `SUM` and `COUNT` on it, so coercion and error rules
|
||||
/// stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`).
|
||||
fn aggregate_value(&mut self, kind: Agg, value: Value, from_ref: bool, acc: &mut Acc) -> Result<(), Ev> {
|
||||
let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), gridcraft_functions::lookup("COUNT")) else {
|
||||
return Err(err(CellError::Name));
|
||||
};
|
||||
let args = [Arg { value, from_ref }];
|
||||
if kind != Agg::Count {
|
||||
match gridcraft_functions::call(sum, &args, &mut FnCtx { ev: self, criteria: None }) {
|
||||
Value::Number(n) => acc.sum += n,
|
||||
other => return Err(Ev::V(other)),
|
||||
}
|
||||
}
|
||||
if kind != Agg::Sum {
|
||||
match gridcraft_functions::call(count, &args, &mut FnCtx { ev: self, criteria: None }) {
|
||||
Value::Number(n) => acc.count = acc.count.saturating_add(n as u64),
|
||||
other => return Err(Ev::V(other)),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev {
|
||||
if args.len() > l.params.len() {
|
||||
// Too many or too few argument positions is #VALUE!. An explicitly empty position, as in
|
||||
// `(1,)`, is `Expr::Missing` and still counts as a position (it binds as omitted). `f()`
|
||||
// parses to no arguments, which for a one-parameter lambda can also be read as one empty
|
||||
// position, so that call still binds the parameter as omitted.
|
||||
let positions_ok = args.len() == l.params.len() || (args.is_empty() && l.params.len() == 1);
|
||||
if !positions_ok {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let mut bound = Vec::with_capacity(l.params.len());
|
||||
@@ -806,7 +970,26 @@ impl<'h> Evaluator<'h> {
|
||||
r
|
||||
}
|
||||
|
||||
fn lambda_arg(&mut self, e: Option<&Expr>) -> Option<Arc<Lambda>> {
|
||||
/// A worksheet function given by name where a function is expected (`BYROW(A1:C3,SUM)`,
|
||||
/// `GROUPBY(A2:A9,B2:B9,SUM)`): its name, unless a LET/LAMBDA variable or a defined name has
|
||||
/// that name.
|
||||
fn function_by_name(&self, e: &Expr) -> Option<String> {
|
||||
let Expr::Name(n) = e else { return None };
|
||||
if self.env.iter().any(|(k, _)| k.eq_ignore_ascii_case(n)) || self.host.workbook().name(n, self.sheet).is_some() {
|
||||
return None;
|
||||
}
|
||||
let u = n.to_ascii_uppercase();
|
||||
gridcraft_functions::lookup(&u).map(|_| u)
|
||||
}
|
||||
|
||||
/// The function argument of a LAMBDA helper; a function given by name takes `arity`
|
||||
/// arguments.
|
||||
fn lambda_arg(&mut self, e: Option<&Expr>, arity: usize) -> Option<Arc<Lambda>> {
|
||||
if let Some(f) = e.and_then(|x| self.function_by_name(x)) {
|
||||
let params: Vec<String> = (0..arity).map(|i| format!("_xleta.{i}")).collect();
|
||||
let body = Expr::Call(f, params.iter().map(|p| Expr::Name(p.clone())).collect());
|
||||
return Some(Arc::new(Lambda { params, body, env: Vec::new() }));
|
||||
}
|
||||
match e.map(|x| self.eval(x)) {
|
||||
Some(Ev::L(l)) => Some(l),
|
||||
_ => None,
|
||||
@@ -825,7 +1008,7 @@ impl<'h> Evaluator<'h> {
|
||||
if args.len() < 2 {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let Some(l) = self.lambda_arg(args.last()) else { return err(CellError::Value) };
|
||||
let Some(l) = self.lambda_arg(args.last(), args.len() - 1) else { return err(CellError::Value) };
|
||||
let arrays: Vec<Arc<Array>> = args[..args.len() - 1].iter().map(|a| as_array(self.value(a))).collect();
|
||||
let rows = arrays.iter().map(|a| a.rows).max().unwrap_or(1);
|
||||
let cols = arrays.iter().map(|a| a.cols).max().unwrap_or(1);
|
||||
@@ -848,7 +1031,7 @@ impl<'h> Evaluator<'h> {
|
||||
}
|
||||
let mut acc = self.value(&args[0]);
|
||||
let arr = as_array(self.value(&args[1]));
|
||||
let Some(l) = self.lambda_arg(args.get(2)) else { return err(CellError::Value) };
|
||||
let Some(l) = self.lambda_arg(args.get(2), 2) else { return err(CellError::Value) };
|
||||
if l.params.len() != 2 {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
@@ -872,7 +1055,7 @@ impl<'h> Evaluator<'h> {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let arr = as_array(self.value(&args[0]));
|
||||
let Some(l) = self.lambda_arg(args.get(1)) else { return err(CellError::Value) };
|
||||
let Some(l) = self.lambda_arg(args.get(1), 1) else { return err(CellError::Value) };
|
||||
let Some(p) = l.params.first().cloned() else { return err(CellError::Value) };
|
||||
let by_row = name == "BYROW";
|
||||
let n = if by_row { arr.rows } else { arr.cols };
|
||||
@@ -901,7 +1084,7 @@ impl<'h> Evaluator<'h> {
|
||||
if rows < 1.0 || cols < 1.0 || rows * cols > MAX_CELLS as f64 {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let Some(l) = self.lambda_arg(args.get(2)) else { return err(CellError::Value) };
|
||||
let Some(l) = self.lambda_arg(args.get(2), 2) else { return err(CellError::Value) };
|
||||
if l.params.len() != 2 {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
@@ -957,10 +1140,10 @@ impl<'h> Evaluator<'h> {
|
||||
if h == 0 || w == 0 {
|
||||
return err(CellError::Ref);
|
||||
}
|
||||
let r0 = base.range.start.row as i64 + rows;
|
||||
let c0 = base.range.start.col as i64 + cols;
|
||||
let (r0, r1) = if h > 0 { (r0, r0 + h - 1) } else { (r0 + h + 1, r0) };
|
||||
let (c0, c1) = if w > 0 { (c0, c0 + w - 1) } else { (c0 + w + 1, c0) };
|
||||
let r0 = (base.range.start.row as i64).saturating_add(rows);
|
||||
let c0 = (base.range.start.col as i64).saturating_add(cols);
|
||||
let (r0, r1) = if h > 0 { (r0, r0.saturating_add(h - 1)) } else { (r0.saturating_add(h + 1), r0) };
|
||||
let (c0, c1) = if w > 0 { (c0, c0.saturating_add(w - 1)) } else { (c0.saturating_add(w + 1), c0) };
|
||||
if r0 < 0 || c0 < 0 || r1 >= MAX_ROWS as i64 || c1 >= MAX_COLS as i64 {
|
||||
return err(CellError::Ref);
|
||||
}
|
||||
@@ -984,8 +1167,18 @@ impl<'h> Evaluator<'h> {
|
||||
v.scalar().to_bool().unwrap_or(true)
|
||||
}
|
||||
};
|
||||
let text = if a1 { text } else { r1c1_to_a1(&text, self.at).unwrap_or(text) };
|
||||
// With a1 = FALSE, text that isn't R1C1 can still be a name, but never an A1 reference.
|
||||
let (text, a1_ok) = if a1 {
|
||||
(text, true)
|
||||
} else {
|
||||
match r1c1_to_a1(&text, self.at) {
|
||||
Ok(Some(a1_text)) => (a1_text, true),
|
||||
Ok(None) => (text, false),
|
||||
Err(e) => return err(e),
|
||||
}
|
||||
};
|
||||
match gridcraft_formula::parse(&text) {
|
||||
Ok(Expr::Ref(_)) if !a1_ok => err(CellError::Ref),
|
||||
Ok(e @ (Expr::Ref(_) | Expr::Name(_) | Expr::Struct(_))) => match self.eval(&e) {
|
||||
r @ Ev::R(_) => r,
|
||||
_ => err(CellError::Ref),
|
||||
@@ -999,27 +1192,67 @@ impl<'h> Evaluator<'h> {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let src = self.eval(&args[0]);
|
||||
let row = match self.arg_num(args, 1, 0.0) {
|
||||
Ok(n) => n.trunc() as i64,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let col = match self.arg_num(args, 2, 0.0) {
|
||||
Ok(n) => n.trunc() as i64,
|
||||
Err(e) => return err(e),
|
||||
let mut arg = |i: usize| match args.get(i) {
|
||||
None | Some(Expr::Missing) => None,
|
||||
Some(e) => Some(self.value(e)),
|
||||
};
|
||||
let (rows, cols) = (arg(1), arg(2));
|
||||
let area_n = match self.arg_num(args, 3, 1.0) {
|
||||
Ok(n) => n.trunc() as i64,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
let two = args.len() == 2;
|
||||
let num = |v: &Option<Value>| v.as_ref().map_or(Ok(0.0), |v| v.to_number()).map(|n| n.trunc() as i64);
|
||||
// Arrays of positions pick a value for each: INDEX(A1:C10,{1;2},{1,3}) is 2×2.
|
||||
if let (Some(Value::Array(_)), _) | (_, Some(Value::Array(_))) = (&rows, &cols) {
|
||||
let as_array = |v: &Option<Value>| match v {
|
||||
Some(Value::Array(a)) => Arc::clone(a),
|
||||
Some(v) => Arc::new(Array::scalar(v.clone())),
|
||||
None => Arc::new(Array::scalar(Value::Number(0.0))),
|
||||
};
|
||||
let (ra, ca) = (as_array(&rows), as_array(&cols));
|
||||
let (h, w) = (ra.rows.max(ca.rows), ra.cols.max(ca.cols));
|
||||
if (h as u64).saturating_mul(w as u64) > MAX_CELLS {
|
||||
return err(CellError::Num);
|
||||
}
|
||||
let mut out = Vec::with_capacity(h * w);
|
||||
for r in 0..h {
|
||||
for c in 0..w {
|
||||
let pos = (num(&Some(ra.get_broadcast(r, c))), num(&Some(ca.get_broadcast(r, c))));
|
||||
let v = match pos {
|
||||
(Ok(row), Ok(col)) => {
|
||||
let one = self.index_one(src.clone(), row, col, area_n, two);
|
||||
match self.deref(one) {
|
||||
Value::Array(a) if a.rows * a.cols > 1 => Value::Error(CellError::Calc),
|
||||
v => v.scalar(),
|
||||
}
|
||||
}
|
||||
(Err(e), _) | (_, Err(e)) => Value::Error(e),
|
||||
};
|
||||
out.push(v);
|
||||
}
|
||||
}
|
||||
return Ev::V(Array::new(h, w, out).map(Value::from).unwrap_or(Value::Error(CellError::Value)));
|
||||
}
|
||||
let (row, col) = match (num(&rows), num(&cols)) {
|
||||
(Ok(r), Ok(c)) => (r, c),
|
||||
(Err(e), _) | (_, Err(e)) => return err(e),
|
||||
};
|
||||
self.index_one(src, row, col, area_n, two)
|
||||
}
|
||||
|
||||
/// INDEX for one row and column position (0 = the whole column or row).
|
||||
fn index_one(&mut self, src: Ev, row: i64, col: i64, area_n: i64, two_args: bool) -> Ev {
|
||||
if row < 0 || col < 0 {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
match src {
|
||||
Ev::R(areas) => {
|
||||
let Some(a) = areas.get((area_n - 1).max(0) as usize).copied() else { return err(CellError::Ref) };
|
||||
let area = usize::try_from((area_n as u64).saturating_sub(1)).ok();
|
||||
let Some(a) = area.and_then(|i| areas.get(i)).copied() else { return err(CellError::Ref) };
|
||||
let r = a.range;
|
||||
// A single row or column with one index picks along it.
|
||||
let (row, col) = if args.len() == 2 && r.height() == 1 { (1, row) } else { (row, col) };
|
||||
let (row, col) = if two_args && r.height() == 1 { (1, row) } else { (row, col) };
|
||||
if row as u64 > r.height() as u64 || col as u64 > r.width() as u64 {
|
||||
return err(CellError::Ref);
|
||||
}
|
||||
@@ -1028,7 +1261,7 @@ impl<'h> Evaluator<'h> {
|
||||
Ev::R(vec![Area { sheet: a.sheet, range: RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1)) }])
|
||||
}
|
||||
Ev::V(Value::Array(arr)) => {
|
||||
let (row, col) = if args.len() == 2 && arr.rows == 1 { (1, row) } else { (row, col) };
|
||||
let (row, col) = if two_args && arr.rows == 1 { (1, row) } else { (row, col) };
|
||||
if row as usize > arr.rows || col as usize > arr.cols {
|
||||
return err(CellError::Ref);
|
||||
}
|
||||
@@ -1051,6 +1284,66 @@ impl<'h> Evaluator<'h> {
|
||||
}
|
||||
}
|
||||
|
||||
/// XLOOKUP whose result range is a reference returns a reference, as in Excel, so that it can
|
||||
/// end a range (`SUM(XLOOKUP(a,…):XLOOKUP(b,…))`) or feed CELL. Everything else (arrays of
|
||||
/// lookup values, array arguments, errors) goes to the library function.
|
||||
fn xlookup(&mut self, args: &[Expr]) -> Ev {
|
||||
if (3..=6).contains(&args.len())
|
||||
&& let (Ev::R(look), Ev::R(ret)) = (self.eval(&args[1]), self.eval(&args[2]))
|
||||
&& let ([l], [r]) = (look.as_slice(), ret.as_slice())
|
||||
&& let Some(spec) = gridcraft_functions::lookup("XMATCH")
|
||||
{
|
||||
let key = self.value(&args[0]);
|
||||
let (l, r) = (*l, *r);
|
||||
let vertical = l.range.width() == 1 && l.range.height() > 1;
|
||||
let horizontal = l.range.height() == 1 && l.range.width() > 1;
|
||||
let same_len = if vertical { r.range.height() == l.range.height() } else { r.range.width() == l.range.width() };
|
||||
if !matches!(key, Value::Array(_)) && (vertical || horizontal) && same_len {
|
||||
let mut xargs = vec![Arg { value: key, from_ref: false }, Arg { value: self.area_value(&l), from_ref: true }];
|
||||
// An empty match_mode before a given search_mode is the default (0), not the end.
|
||||
let given = |i: usize| args.get(i).is_some_and(|e| !matches!(e, Expr::Missing));
|
||||
let last = if given(5) {
|
||||
5
|
||||
} else if given(4) {
|
||||
4
|
||||
} else {
|
||||
3
|
||||
};
|
||||
for i in 4..=last {
|
||||
match args.get(i) {
|
||||
Some(Expr::Missing) | None => xargs.push(Arg { value: Value::Number(0.0), from_ref: false }),
|
||||
Some(e) => {
|
||||
let value = self.value(e);
|
||||
xargs.push(Arg { value, from_ref: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ctx = FnCtx { ev: self, criteria: None };
|
||||
return match gridcraft_functions::call(spec, &xargs, &mut ctx) {
|
||||
Value::Number(p) if p >= 1.0 => {
|
||||
let k = p as u32 - 1;
|
||||
let range = if vertical {
|
||||
RangeRef::new(
|
||||
CellRef::new(r.range.start.row + k, r.range.start.col),
|
||||
CellRef::new(r.range.start.row + k, r.range.end.col),
|
||||
)
|
||||
} else {
|
||||
RangeRef::new(
|
||||
CellRef::new(r.range.start.row, r.range.start.col + k),
|
||||
CellRef::new(r.range.end.row, r.range.start.col + k),
|
||||
)
|
||||
};
|
||||
Ev::R(vec![Area { sheet: r.sheet, range }])
|
||||
}
|
||||
Value::Error(CellError::NA) if args.get(3).is_some_and(|e| !matches!(e, Expr::Missing)) => self.eval(&args[3]),
|
||||
Value::Error(e) => err(e),
|
||||
_ => err(CellError::Value),
|
||||
};
|
||||
}
|
||||
}
|
||||
self.builtin("XLOOKUP", args)
|
||||
}
|
||||
|
||||
fn cell_info(&mut self, args: &[Expr]) -> Ev {
|
||||
let kind = match self.arg_val(args, 0).map(|v| v.scalar().to_text()) {
|
||||
Some(Ok(t)) => t.to_ascii_lowercase(),
|
||||
@@ -1079,7 +1372,7 @@ impl<'h> Evaluator<'h> {
|
||||
_ => "v",
|
||||
}))
|
||||
}
|
||||
"width" => Ev::V(Value::number(sheet.map_or(8.43, |s| (s.col_width(c.col) as f64 / 7.0 * 100.0).round() / 100.0).round())),
|
||||
"width" => Ev::V(Value::number(sheet.map_or(8.43, |s| gridcraft_model::points_to_chars(s.col_width(c.col) as f64)).round())),
|
||||
"filename" => Ev::V(Value::text(String::new())),
|
||||
"sheetname" => Ev::V(Value::text(sheet.map(|s| s.name.clone()).unwrap_or_default())),
|
||||
"protect" => Ev::V(Value::number(if sheet.is_some_and(|s| wb.styles.get(s.style_id(c)).protection.locked) { 1.0 } else { 0.0 })),
|
||||
@@ -1094,7 +1387,9 @@ impl<'h> Evaluator<'h> {
|
||||
}
|
||||
|
||||
fn subtotal(&mut self, name: &str, args: &[Expr]) -> Ev {
|
||||
if args.len() < 2 {
|
||||
// SUBTOTAL needs function_num and ref1; AGGREGATE needs function_num, options and ref1.
|
||||
let min_args = if name == "AGGREGATE" { 3 } else { 2 };
|
||||
if args.len() < min_args {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let code = match self.arg_num(args, 0, 0.0) {
|
||||
@@ -1115,8 +1410,12 @@ impl<'h> Evaluator<'h> {
|
||||
return err(CellError::Value);
|
||||
}
|
||||
let skip_hidden = matches!(options, 1 | 3 | 5 | 7);
|
||||
// SUBTOTAL leaves out rows a filter hides whatever the function number (Microsoft's
|
||||
// SUBTOTAL documentation); 101-111 also leave out rows hidden by hand.
|
||||
let skip_filtered = name == "SUBTOTAL";
|
||||
let skip_errors = matches!(options, 2 | 3 | 6 | 7);
|
||||
let skip_nested = options <= 3;
|
||||
// SUBTOTAL always leaves out nested SUBTOTAL/AGGREGATE cells (101-111 too); AGGREGATE does so for options 0-3.
|
||||
let skip_nested = name == "SUBTOTAL" || options <= 3;
|
||||
let mut values = Vec::new();
|
||||
let mut k = None;
|
||||
let refs = if name == "AGGREGATE" && func >= 14 { &rest[..1.min(rest.len())] } else { rest };
|
||||
@@ -1132,7 +1431,8 @@ impl<'h> Evaluator<'h> {
|
||||
let (hidden, nested) = {
|
||||
let wb = self.host.workbook();
|
||||
let s = wb.sheet(a.sheet);
|
||||
let hidden = skip_hidden && s.is_some_and(|s| s.is_row_hidden(c.row));
|
||||
let hidden =
|
||||
s.is_some_and(|s| if skip_hidden { s.is_row_hidden(c.row) } else { skip_filtered && s.is_row_filtered(c.row) });
|
||||
let nested = skip_nested
|
||||
&& s.and_then(|s| s.cell(c)).and_then(|cell| cell.formula.as_ref()).is_some_and(|f| {
|
||||
let u = f.text.to_ascii_uppercase();
|
||||
@@ -1206,47 +1506,103 @@ fn same_kind(a: &Value, b: &Value) -> bool {
|
||||
std::mem::discriminant(a) == std::mem::discriminant(b) || (a.is_empty() || b.is_empty())
|
||||
}
|
||||
|
||||
/// Converts an R1C1 reference text to A1 (for INDIRECT(…, FALSE)).
|
||||
pub fn r1c1_to_a1(s: &str, at: CellRef) -> Option<String> {
|
||||
/// Converts an R1C1 reference text to A1 (for INDIRECT(…, FALSE)). `Ok(None)` means the text is
|
||||
/// not R1C1; `Err` means it is R1C1 but points past the sheet.
|
||||
pub fn r1c1_to_a1(s: &str, at: CellRef) -> Result<Option<String>, CellError> {
|
||||
let (sheet, body) = match s.rsplit_once('!') {
|
||||
Some((sh, b)) => (format!("{sh}!"), b),
|
||||
None => (String::new(), s),
|
||||
};
|
||||
let conv = |part: &str| -> Option<String> {
|
||||
let conv = |part: &str| -> Result<Option<String>, CellError> {
|
||||
let u = part.to_ascii_uppercase();
|
||||
let rest = u.strip_prefix('R')?;
|
||||
let (rpart, cpart) = rest.split_once('C')?;
|
||||
let num = |p: &str, base: u32| -> Option<(u32, bool)> {
|
||||
if p.is_empty() {
|
||||
return Some((base, false));
|
||||
}
|
||||
if let Some(inner) = p.strip_prefix('[').and_then(|x| x.strip_suffix(']')) {
|
||||
let d: i64 = inner.parse().ok()?;
|
||||
let v = base as i64 + d;
|
||||
return if v >= 0 { Some((v as u32, false)) } else { None };
|
||||
}
|
||||
let v: u32 = p.parse().ok()?;
|
||||
Some((v.checked_sub(1)?, true))
|
||||
let Some((rpart, cpart)) = u.strip_prefix('R').and_then(|rest| rest.split_once('C')) else { return Ok(None) };
|
||||
// `None`: not R1C1. `Some(None)`: R1C1, but past the sheet.
|
||||
let num = |p: &str, base: u32, max: u32| -> Option<Option<(u32, bool)>> {
|
||||
let (v, absolute) = if p.is_empty() {
|
||||
(Some(i64::from(base)), false)
|
||||
} else if let Some(inner) = p.strip_prefix('[').and_then(|x| x.strip_suffix(']')) {
|
||||
(i64::from(base).checked_add(inner.parse().ok()?), false)
|
||||
} else {
|
||||
(p.parse::<u32>().ok()?.checked_sub(1).map(i64::from), true)
|
||||
};
|
||||
Some(v.filter(|v| (0..i64::from(max)).contains(v)).map(|v| (v as u32, absolute)))
|
||||
};
|
||||
let (r, ra) = num(rpart, at.row)?;
|
||||
let (c, ca) = num(cpart, at.col)?;
|
||||
Some(format!("{}{}{}{}", if ca { "$" } else { "" }, gridcraft_core::col_to_letters(c), if ra { "$" } else { "" }, r + 1))
|
||||
let (Some(r), Some(c)) = (num(rpart, at.row, MAX_ROWS), num(cpart, at.col, MAX_COLS)) else { return Ok(None) };
|
||||
let (Some((r, ra)), Some((c, ca))) = (r, c) else { return Err(CellError::Ref) };
|
||||
Ok(Some(format!("{}{}{}{}", if ca { "$" } else { "" }, gridcraft_core::col_to_letters(c), if ra { "$" } else { "" }, r + 1)))
|
||||
};
|
||||
let out = match body.split_once(':') {
|
||||
Some((a, b)) => format!("{}:{}", conv(a)?, conv(b)?),
|
||||
None => conv(body)?,
|
||||
Some((a, b)) => match (conv(a)?, conv(b)?) {
|
||||
(Some(a), Some(b)) => format!("{a}:{b}"),
|
||||
_ => return Ok(None),
|
||||
},
|
||||
None => match conv(body)? {
|
||||
Some(x) => x,
|
||||
None => return Ok(None),
|
||||
},
|
||||
};
|
||||
Some(format!("{sheet}{out}"))
|
||||
Ok(Some(format!("{sheet}{out}")))
|
||||
}
|
||||
|
||||
/// The aggregates that can fold a reference without building an array.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Agg {
|
||||
Sum,
|
||||
Count,
|
||||
Average,
|
||||
}
|
||||
|
||||
impl Agg {
|
||||
fn of(name: &str) -> Option<Agg> {
|
||||
match name {
|
||||
"SUM" => Some(Agg::Sum),
|
||||
"COUNT" => Some(Agg::Count),
|
||||
"AVERAGE" => Some(Agg::Average),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a folded aggregate carries from one value to the next.
|
||||
#[derive(Default)]
|
||||
struct Acc {
|
||||
sum: f64,
|
||||
count: u64,
|
||||
}
|
||||
|
||||
impl Acc {
|
||||
/// Takes a value found inside a reference: only numbers count. `Err` is an error value that
|
||||
/// ends `SUM` and `AVERAGE`; `COUNT` skips errors.
|
||||
fn add_cell(&mut self, kind: Agg, v: &Value) -> Result<(), CellError> {
|
||||
match v {
|
||||
Value::Number(n) => {
|
||||
self.sum += n;
|
||||
self.count = self.count.saturating_add(1);
|
||||
Ok(())
|
||||
}
|
||||
Value::Error(e) if kind != Agg::Count => Err(*e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self, kind: Agg) -> Value {
|
||||
match kind {
|
||||
Agg::Sum => Value::number(self.sum),
|
||||
Agg::Count => Value::number(self.count as f64),
|
||||
Agg::Average if self.count == 0 => Value::Error(CellError::Div0),
|
||||
Agg::Average => Value::number(self.sum / self.count as f64),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- operators
|
||||
|
||||
fn map_unary(v: &Value, f: &dyn Fn(f64) -> Value, plus: bool) -> Value {
|
||||
fn map_unary(v: &Value, f: &dyn Fn(f64) -> Value, plus: bool, sys: gridcraft_core::DateSystem) -> Value {
|
||||
match v {
|
||||
Value::Array(a) => Value::from(Array { rows: a.rows, cols: a.cols, data: a.data.iter().map(|x| map_unary(x, f, plus)).collect() }),
|
||||
Value::Array(a) => Value::from(Array { rows: a.rows, cols: a.cols, data: a.data.iter().map(|x| map_unary(x, f, plus, sys)).collect() }),
|
||||
Value::Error(e) => Value::Error(*e),
|
||||
Value::Text(_) if plus => v.clone(),
|
||||
other => match other.to_number() {
|
||||
other => match other.to_number_in(sys) {
|
||||
Ok(n) => f(n),
|
||||
Err(e) => Value::Error(e),
|
||||
},
|
||||
@@ -1299,18 +1655,18 @@ fn zip3(c: &Array, t: &Value, f: &Value, g: impl Fn(&Value, &Value, &Value) -> V
|
||||
Value::from(Array { rows, cols, data })
|
||||
}
|
||||
|
||||
pub fn binary_values(op: BinOp, x: &Value, y: &Value) -> Value {
|
||||
zip2(x, y, |a, b| binary_scalar(op, a, b))
|
||||
pub fn binary_values(op: BinOp, x: &Value, y: &Value, sys: gridcraft_core::DateSystem) -> Value {
|
||||
zip2(x, y, |a, b| binary_scalar(op, a, b, sys))
|
||||
}
|
||||
|
||||
fn binary_scalar(op: BinOp, a: &Value, b: &Value) -> Value {
|
||||
fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSystem) -> Value {
|
||||
if let Value::Error(e) = a {
|
||||
return Value::Error(*e);
|
||||
}
|
||||
if let Value::Error(e) = b {
|
||||
return Value::Error(*e);
|
||||
}
|
||||
let num = |f: fn(f64, f64) -> Value| match (a.to_number(), b.to_number()) {
|
||||
let num = |f: fn(f64, f64) -> Value| match (a.to_number_in(sys), b.to_number_in(sys)) {
|
||||
(Ok(x), Ok(y)) => f(x, y),
|
||||
(Err(e), _) | (_, Err(e)) => Value::Error(e),
|
||||
};
|
||||
@@ -1455,6 +1811,7 @@ fn is_special(n: &str) -> bool {
|
||||
| "INDIRECT"
|
||||
| "INDEX"
|
||||
| "CELL"
|
||||
| "TRIMRANGE"
|
||||
| "SUBTOTAL"
|
||||
| "AGGREGATE"
|
||||
| "TEXT"
|
||||
@@ -1492,6 +1849,7 @@ pub const SPECIAL_FUNCTIONS: &[&str] = &[
|
||||
"INDIRECT",
|
||||
"INDEX",
|
||||
"CELL",
|
||||
"TRIMRANGE",
|
||||
"SUBTOTAL",
|
||||
"AGGREGATE",
|
||||
"TEXT",
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
pub mod eval;
|
||||
pub mod recalc;
|
||||
mod trimrange;
|
||||
|
||||
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
|
||||
pub use recalc::{Calc, Key, evaluate, now_serial};
|
||||
|
||||
+208
-44
@@ -6,7 +6,9 @@
|
||||
//! O(log n + matches) however many ranges share the column. After an edit, the dirty set is the
|
||||
//! transitive closure of dependents; it is evaluated in topological order, with on-demand
|
||||
//! evaluation as a safety net for dynamic references. Cycles produce `#CIRC!` unless iterative
|
||||
//! calculation is on.
|
||||
//! calculation is on: then a formula read while it is being evaluated gives its previous value,
|
||||
//! and the formulas that read one are evaluated again until the loop settles
|
||||
//! (`PassHost::iterate_loops`).
|
||||
|
||||
use std::collections::{BTreeSet, VecDeque};
|
||||
use std::hash::{BuildHasherDefault, Hasher};
|
||||
@@ -58,6 +60,10 @@ const WIDE: u32 = 64;
|
||||
/// Insertions an [`Intervals`] keeps aside (scanned by every query) before merging them in.
|
||||
const PENDING: usize = 32;
|
||||
|
||||
/// Formula evaluations iterative calculation may spend on one recalculation (passes × formulas
|
||||
/// evaluated again), however high Maximum Iterations is.
|
||||
const MAX_ITERATION_WORK: usize = 10_000_000;
|
||||
|
||||
/// Row intervals `[r0, r1]`, each with a payload, answering "which intervals overlap rows
|
||||
/// `a..=b`?" in O(log n + k).
|
||||
///
|
||||
@@ -389,6 +395,44 @@ struct PassHost<'a> {
|
||||
cycle: bool,
|
||||
cycles: Vec<Key>,
|
||||
depth: usize,
|
||||
/// Iterative calculation: a circular reference reads the cell's previous value instead of
|
||||
/// giving `#CIRC!`.
|
||||
iterate: bool,
|
||||
/// Values from the previous iteration; cells not in it read their stored value.
|
||||
prev: HashMap<Key, Value>,
|
||||
/// Formulas being evaluated, innermost last (kept only when iterating).
|
||||
stack: Vec<Key>,
|
||||
/// Formulas found on a circular reference (when iterating).
|
||||
members: HashSet<Key>,
|
||||
/// Results that read a previous value, directly or through other formulas.
|
||||
tainted: HashSet<Key>,
|
||||
/// Whether the formula being evaluated has read a previous value.
|
||||
taint: bool,
|
||||
}
|
||||
|
||||
impl<'a> PassHost<'a> {
|
||||
fn new(wb: &'a Workbook, exprs: &'a HashMap<Key, std::sync::Arc<Expr>>, rng: &'a mut u64, now: f64) -> Self {
|
||||
PassHost {
|
||||
wb,
|
||||
exprs,
|
||||
results: HashMap::with_capacity_and_hasher(exprs.len(), Default::default()),
|
||||
pending: exprs.keys().copied().collect(),
|
||||
in_progress: HashSet::default(),
|
||||
spills: HashMap::default(),
|
||||
used: HashMap::default(),
|
||||
rng,
|
||||
now,
|
||||
cycle: false,
|
||||
cycles: vec![],
|
||||
depth: 0,
|
||||
iterate: false,
|
||||
prev: HashMap::default(),
|
||||
stack: Vec::new(),
|
||||
members: HashSet::default(),
|
||||
tainted: HashSet::default(),
|
||||
taint: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
|
||||
@@ -415,18 +459,29 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
|
||||
impl PassHost<'_> {
|
||||
fn compute(&mut self, k: Key) -> Value {
|
||||
if let Some(v) = self.results.get(&k) {
|
||||
return v.clone();
|
||||
let v = v.clone();
|
||||
if self.iterate && self.tainted.contains(&k) {
|
||||
self.taint = true;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
let Some(expr) = self.exprs.get(&k) else {
|
||||
return self.wb.sheet(k.0).map(|s| s.value(k.1)).unwrap_or_default();
|
||||
};
|
||||
if self.in_progress.contains(&k) || self.depth > 2000 {
|
||||
self.cycle = true;
|
||||
if self.iterate {
|
||||
return self.circular_read(k);
|
||||
}
|
||||
self.cycles.push(k);
|
||||
return Value::Error(CellError::Circ);
|
||||
}
|
||||
self.in_progress.insert(k);
|
||||
self.depth += 1;
|
||||
let outer_taint = std::mem::replace(&mut self.taint, false);
|
||||
if self.iterate {
|
||||
self.stack.push(k);
|
||||
}
|
||||
let expr = std::sync::Arc::clone(expr);
|
||||
let v = {
|
||||
let mut ev = Evaluator::new(self, k.0, k.1);
|
||||
@@ -441,6 +496,15 @@ impl PassHost<'_> {
|
||||
self.depth -= 1;
|
||||
self.in_progress.remove(&k);
|
||||
self.pending.remove(&k);
|
||||
if self.iterate {
|
||||
self.stack.pop();
|
||||
if self.taint {
|
||||
self.tainted.insert(k);
|
||||
} else {
|
||||
self.tainted.remove(&k);
|
||||
}
|
||||
}
|
||||
self.taint |= outer_taint;
|
||||
// A blank cell shows as 0 in a formula's result, inside an array as well (`=A1:A3`,
|
||||
// FILTER or SORT of a range with blanks). GROUPBY and PIVOTBY lay out blank cells
|
||||
// of their own, which stay blank.
|
||||
@@ -472,6 +536,68 @@ impl PassHost<'_> {
|
||||
self.results.insert(k, v.clone());
|
||||
v
|
||||
}
|
||||
|
||||
/// A formula's previous value for iterative calculation: from the last iteration, else the
|
||||
/// value it shows. Blank, and the `#CIRC!` of a loop calculated with iteration off, are 0.
|
||||
fn previous(&self, k: Key) -> Value {
|
||||
let v = match self.prev.get(&k) {
|
||||
Some(v) => v.clone(),
|
||||
None => self.wb.sheet(k.0).map(|s| s.value(k.1)).unwrap_or_default(),
|
||||
};
|
||||
if matches!(v, Value::Empty | Value::Error(CellError::Circ)) { Value::Number(0.0) } else { v }
|
||||
}
|
||||
|
||||
/// Reading `k` while it is being evaluated, with iterative calculation on: its previous value.
|
||||
/// The formulas around the loop are the ones whose changes decide when iteration stops.
|
||||
fn circular_read(&mut self, k: Key) -> Value {
|
||||
self.taint = true;
|
||||
match self.stack.iter().rposition(|s| *s == k) {
|
||||
Some(i) => self.members.extend(self.stack.get(i..).unwrap_or_default().iter().copied()),
|
||||
// Too deep to follow: the formula itself is watched.
|
||||
None => {
|
||||
self.members.insert(k);
|
||||
}
|
||||
}
|
||||
self.previous(k)
|
||||
}
|
||||
|
||||
/// Iterative calculation, after a first pass over `order` that met circular references. The
|
||||
/// formulas that read a previous value (the loops and what depends on them) are evaluated
|
||||
/// again in the same order, each pass starting from the last one's values and reading what it
|
||||
/// has already produced (Gauss-Seidel), until no formula on a loop changes by `max_change` or
|
||||
/// more, or after `max_iterations` passes in all. Returns the number of passes.
|
||||
fn iterate_loops(&mut self, order: &[Key], max_iterations: u32, max_change: f64) -> u32 {
|
||||
let again: Vec<Key> = order.iter().copied().filter(|k| self.tainted.contains(k)).collect();
|
||||
let set: HashSet<Key> = again.iter().copied().collect();
|
||||
// Bounds the work whatever Maximum Iterations says.
|
||||
let max_passes = u32::try_from(MAX_ITERATION_WORK / again.len().max(1)).unwrap_or(u32::MAX).max(1);
|
||||
let mut passes = 1u32;
|
||||
while passes < max_iterations.min(max_passes) && !self.converged(max_change) {
|
||||
self.prev = again.iter().filter_map(|k| self.results.remove(k).map(|v| (*k, v))).collect();
|
||||
self.pending = set.clone();
|
||||
self.spills.retain(|a, _| !set.contains(a));
|
||||
for k in &again {
|
||||
self.compute(*k);
|
||||
}
|
||||
passes += 1;
|
||||
}
|
||||
passes
|
||||
}
|
||||
|
||||
/// Whether every formula on a loop changed by less than `max_change` in the last pass (text,
|
||||
/// logical and error values: not at all).
|
||||
fn converged(&self, max_change: f64) -> bool {
|
||||
self.members.iter().all(|k| {
|
||||
let Some(new) = self.results.get(k) else { return true };
|
||||
match (new, &self.previous(*k)) {
|
||||
(Value::Number(a), Value::Number(b)) => {
|
||||
let d = (a - b).abs();
|
||||
d < max_change || d == 0.0
|
||||
}
|
||||
(new, old) => new == old,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A legacy (Ctrl+Shift+Enter) array formula's result fitted to the range it was entered in, as
|
||||
@@ -532,6 +658,9 @@ impl Host for PassHost<'_> {
|
||||
if anchor.0 == sheet && c.row >= anchor.1.row && c.col >= anchor.1.col {
|
||||
let (dr, dc) = ((c.row - anchor.1.row) as usize, (c.col - anchor.1.col) as usize);
|
||||
if dr < arr.rows && dc < arr.cols {
|
||||
if self.iterate && self.tainted.contains(anchor) {
|
||||
self.taint = true;
|
||||
}
|
||||
return arr.get(dr, dc).cloned().unwrap_or_default();
|
||||
}
|
||||
}
|
||||
@@ -590,6 +719,18 @@ impl Host for PassHost<'_> {
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
// Iterating: an array spilled by a formula that read a previous value.
|
||||
if self.iterate
|
||||
&& self.spills.iter().any(|(a, arr)| {
|
||||
let end = CellRef::new(
|
||||
a.1.row.saturating_add((arr.rows as u32).saturating_sub(1)),
|
||||
a.1.col.saturating_add((arr.cols as u32).saturating_sub(1)),
|
||||
);
|
||||
a.0 == sheet && self.tainted.contains(a) && RangeRef::new(a.1, end).intersects(&range)
|
||||
})
|
||||
{
|
||||
self.taint = true;
|
||||
}
|
||||
for (i, v) in new {
|
||||
if let Some(slot) = out.get_mut(i) {
|
||||
*slot = v;
|
||||
@@ -598,6 +739,30 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
out
|
||||
}
|
||||
fn visit_range(&mut self, sheet: usize, range: RangeRef, f: &mut dyn FnMut(&Value) -> bool) -> bool {
|
||||
let wb = self.wb;
|
||||
let Some(sh) = wb.sheet(sheet) else { return false };
|
||||
// Formula cells first, in row-major order like `range_values`: reading one calculates it
|
||||
// and the pass remembers the value, so the walk below gets the same value again without
|
||||
// this method holding any.
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
if cell.formula.is_some() {
|
||||
let _ = self.cell_value(sheet, c);
|
||||
}
|
||||
}
|
||||
// Spilled values sit between the stored cells (and the formulas just calculated may have
|
||||
// produced some): leave such blocks to `range_values`.
|
||||
if self.spills.keys().any(|a| a.0 == sheet) || sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c)) {
|
||||
return false;
|
||||
}
|
||||
for (c, cell) in sh.cells.iter_range(range) {
|
||||
let go = if cell.formula.is_some() { f(&self.cell_value(sheet, c)) } else { f(&cell.value) };
|
||||
if !go {
|
||||
break;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
fn used_range(&mut self, sheet: usize) -> Option<RangeRef> {
|
||||
let wb = self.wb;
|
||||
*self.used.entry(sheet).or_insert_with(|| wb.sheet(sheet).and_then(|s| s.used_range()))
|
||||
@@ -733,11 +898,11 @@ impl Calc {
|
||||
// Spill areas of changed anchors also change.
|
||||
for &k in changed {
|
||||
if let Some(r) = wb.sheet(k.0).and_then(|s| s.spill_ranges.get(&k.1)) {
|
||||
seeds.extend(r.iter().take(65536).map(|c| (k.0, c)));
|
||||
seeds.extend(r.iter().map(|c| (k.0, c)));
|
||||
}
|
||||
}
|
||||
for (si, r) in &cleared {
|
||||
seeds.extend(r.iter().take(65536).map(|c| (*si, c)));
|
||||
seeds.extend(r.iter().map(|c| (*si, c)));
|
||||
}
|
||||
let t0 = prof_now();
|
||||
let dirty = self.dirty_closure(wb, &seeds);
|
||||
@@ -801,23 +966,17 @@ impl Calc {
|
||||
let mut rng = self.rng;
|
||||
let tp = prof_now();
|
||||
let (results, spills, cycles) = {
|
||||
let mut host = PassHost {
|
||||
wb,
|
||||
exprs: &exprs,
|
||||
results: HashMap::with_capacity_and_hasher(dirty.len(), Default::default()),
|
||||
pending: exprs.keys().copied().collect(),
|
||||
in_progress: HashSet::default(),
|
||||
spills: HashMap::default(),
|
||||
used: HashMap::default(),
|
||||
rng: &mut rng,
|
||||
now,
|
||||
cycle: false,
|
||||
cycles: vec![],
|
||||
depth: 0,
|
||||
};
|
||||
let mut host = PassHost::new(wb, &exprs, &mut rng, now);
|
||||
host.iterate = wb.calc.iterative;
|
||||
for k in &dirty {
|
||||
host.compute(*k);
|
||||
}
|
||||
if host.iterate && !host.members.is_empty() {
|
||||
let passes = host.iterate_loops(&dirty, wb.calc.max_iterations, wb.calc.max_change);
|
||||
if std::env::var_os("GRIDCRAFT_PROFILE").is_some() {
|
||||
eprintln!(" iterative calculation: {} passes over {} formulas", passes, host.tainted.len());
|
||||
}
|
||||
}
|
||||
(host.results, host.spills, host.cycles)
|
||||
};
|
||||
self.rng = rng;
|
||||
@@ -919,17 +1078,11 @@ impl Calc {
|
||||
}
|
||||
}
|
||||
|
||||
/// Local date-time as a serial (1900 system). Wasm without a clock returns a fixed date.
|
||||
#[allow(clippy::disallowed_methods)] // the clock is read only off wasm
|
||||
/// Current date-time as a serial (1900 system), from the system clock (browser clock on wasm).
|
||||
/// UTC; the local offset isn't available without platform calls. Falls back to a fixed date only
|
||||
/// when no clock is available.
|
||||
pub fn now_serial() -> f64 {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if let Ok(d) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
|
||||
// UTC; local offset isn't available without platform calls.
|
||||
return 25569.0 + d.as_secs_f64() / 86400.0;
|
||||
}
|
||||
}
|
||||
46302.5
|
||||
gridcraft_core::date::unix_now_ms().map_or(46302.5, gridcraft_core::date::serial_from_unix_ms)
|
||||
}
|
||||
|
||||
/// Evaluates a formula in the context of a cell without storing it (conditional formats, data
|
||||
@@ -943,20 +1096,7 @@ pub fn evaluate(wb: &Workbook, sheet: usize, at: CellRef, formula: &str) -> Valu
|
||||
pub fn evaluate_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> Value {
|
||||
let exprs = HashMap::default();
|
||||
let mut rng = 0x1234_5678_9ABC_DEF0u64;
|
||||
let mut host = PassHost {
|
||||
wb,
|
||||
exprs: &exprs,
|
||||
results: HashMap::default(),
|
||||
pending: HashSet::default(),
|
||||
in_progress: HashSet::default(),
|
||||
spills: HashMap::default(),
|
||||
used: HashMap::default(),
|
||||
rng: &mut rng,
|
||||
now: now_serial(),
|
||||
cycle: false,
|
||||
cycles: vec![],
|
||||
depth: 0,
|
||||
};
|
||||
let mut host = PassHost::new(wb, &exprs, &mut rng, now_serial());
|
||||
let mut ev = Evaluator::new(&mut host, sheet, at);
|
||||
ev.value(expr)
|
||||
}
|
||||
@@ -974,13 +1114,13 @@ fn prof_now() -> f64 {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value};
|
||||
use gridcraft_model::{Cell, Formula, Workbook};
|
||||
|
||||
use super::{Calc, Intervals, Key};
|
||||
use super::{Calc, HashMap, Host, Intervals, Key, PassHost};
|
||||
|
||||
/// xorshift64 for repeatable pseudo-random cases.
|
||||
fn rng(state: &mut u64) -> u64 {
|
||||
@@ -1181,4 +1321,28 @@ mod tests {
|
||||
calc.graph.dependents(1, CellRef::parse("A2").unwrap(), &mut deps);
|
||||
assert_eq!(deps, vec![at("DA9"), at("DA9")]);
|
||||
}
|
||||
|
||||
/// For tests of `PassHost::visit_range`, which can't be reached from outside this module: the
|
||||
/// values it hands over for `range` while the formulas in `pending` (cell, formula) have not been
|
||||
/// calculated yet, or `None` when it declines the block.
|
||||
pub(crate) fn probe_visit_range(wb: &Workbook, pending: &[(&str, &str)], range: RangeRef) -> Option<Vec<Value>> {
|
||||
let mut exprs = HashMap::default();
|
||||
for (at, formula) in pending {
|
||||
let expr = gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).ok()?;
|
||||
exprs.insert((0, CellRef::parse(at)?), std::sync::Arc::new(expr));
|
||||
}
|
||||
|
||||
// A cell in `pending` is calculated the first time something reads it, which is the state
|
||||
// of a real pass partway through; `visit_range` has to cope with the formulas it reads
|
||||
// being calculated under it.
|
||||
let mut rng = 1u64;
|
||||
let mut host = PassHost::new(wb, &exprs, &mut rng, 0.0);
|
||||
|
||||
let mut seen = Vec::new();
|
||||
host.visit_range(0, range, &mut |v| {
|
||||
seen.push(v.clone());
|
||||
true
|
||||
})
|
||||
.then_some(seen)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,39 @@ fn chains_out_of_order() {
|
||||
assert_eq!(t.num("A5"), 5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xlookup_returns_a_reference() {
|
||||
let mut t = T::new();
|
||||
for (i, (k, v)) in [("a", 1), ("b", 2), ("c", 3), ("d", 4)].iter().enumerate() {
|
||||
t.set(&format!("A{}", i + 1), k);
|
||||
t.set(&format!("B{}", i + 1), &v.to_string());
|
||||
}
|
||||
t.set("D1", "=SUM(XLOOKUP(\"b\",A1:A4,B1:B4):XLOOKUP(\"d\",A1:A4,B1:B4))");
|
||||
assert_eq!(t.num("D1"), 9.0);
|
||||
t.set("D2", "=SUM(B1:XLOOKUP(\"c\",A1:A4,B1:B4))");
|
||||
assert_eq!(t.num("D2"), 6.0);
|
||||
t.set("D3", "=CELL(\"address\",XLOOKUP(\"c\",A1:A4,B1:B4))");
|
||||
assert_eq!(t.get("D3"), Value::from("$B$3"));
|
||||
// Not found: if_not_found, else #N/A, as before.
|
||||
t.set("D4", "=XLOOKUP(\"z\",A1:A4,B1:B4,\"none\")");
|
||||
assert_eq!(t.get("D4"), Value::from("none"));
|
||||
t.set("D5", "=XLOOKUP(\"z\",A1:A4,B1:B4)");
|
||||
assert_eq!(t.get("D5"), Value::Error(CellError::NA));
|
||||
// A match on an empty cell is a blank reference: ISBLANK is TRUE and & adds nothing (#374).
|
||||
t.set("A5", "e");
|
||||
t.set("D6", "=ISBLANK(XLOOKUP(\"e\",A1:A5,B1:B5))");
|
||||
assert_eq!(t.get("D6"), Value::Bool(true));
|
||||
t.set("D7", "=\"x\"&XLOOKUP(\"e\",A1:A5,B1:B5)&\"y\"");
|
||||
assert_eq!(t.get("D7"), Value::from("xy"));
|
||||
// An empty match_mode keeps the search_mode after it: search last to first.
|
||||
t.set("A6", "b");
|
||||
t.set("B6", "20");
|
||||
t.set("D8", "=XLOOKUP(\"b\",A1:A6,B1:B6,,,-1)");
|
||||
assert_eq!(t.num("D8"), 20.0);
|
||||
t.set("D9", "=XLOOKUP(\"b\",A1:A6,B1:B6)");
|
||||
assert_eq!(t.num("D9"), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_chain() {
|
||||
let mut t = T::new();
|
||||
@@ -106,6 +139,39 @@ fn long_chain() {
|
||||
assert_eq!(t.num("A3000"), 3009.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_with_arrays_of_positions() {
|
||||
let mut t = T::new();
|
||||
for (i, row) in [[1, 2, 3], [4, 5, 6], [7, 8, 9]].iter().enumerate() {
|
||||
for (j, v) in row.iter().enumerate() {
|
||||
t.set(&format!("{}{}", ["A", "B", "C"][j], i + 1), &v.to_string());
|
||||
}
|
||||
}
|
||||
t.set("E1", "=INDEX(A1:C3,{1;3},{1,3})");
|
||||
assert_eq!([t.num("E1"), t.num("F1"), t.num("E2"), t.num("F2")], [1.0, 3.0, 7.0, 9.0]);
|
||||
t.set("E4", "=SUM(INDEX(A1:C3,{1,2,3},2))");
|
||||
assert_eq!(t.num("E4"), 15.0);
|
||||
t.set("E5", "=INDEX({10,20,30},{3,1})");
|
||||
assert_eq!([t.num("E5"), t.num("F5")], [30.0, 10.0]);
|
||||
t.set("E7", "=INDEX(A1:C3,2,3)");
|
||||
assert_eq!(t.num("E7"), 6.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_area_number_overflow() {
|
||||
let mut t = T::new();
|
||||
t.set("A1", "7");
|
||||
t.set("D1", "9");
|
||||
for (area, expected) in [("1", 7.0), ("2", 9.0)] {
|
||||
t.set("G5", &format!("=INDEX((A1:B2,D1:E2),1,1,{area})"));
|
||||
assert_eq!(t.num("G5"), expected, "area {area}");
|
||||
}
|
||||
for area in ["3", "1E300", "-1", "-1E300"] {
|
||||
t.set("G5", &format!("=INDEX((A1:B2,D1:E2),1,1,{area})"));
|
||||
assert_eq!(t.get("G5"), Value::Error(CellError::Ref), "area {area}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_and_cycles() {
|
||||
let mut t = T::new();
|
||||
@@ -116,10 +182,134 @@ fn errors_and_cycles() {
|
||||
assert!(t.get("B1").is_error());
|
||||
t.set("C1", "=NOSUCHFN(1)");
|
||||
assert_eq!(t.get("C1"), Value::Error(CellError::Name));
|
||||
// `_xludf.` marks a user-defined function, never the built-in of the same name (#726).
|
||||
for f in ["=_xludf.CONCAT(\"a\",\"b\")", "=_xludf.SUM(1,2)", "=_xludf.EOMONTH()"] {
|
||||
t.set("C3", f);
|
||||
assert_eq!(t.get("C3"), Value::Error(CellError::Name), "{f}");
|
||||
}
|
||||
t.set("C2", "=1+");
|
||||
assert_eq!(t.get("C2"), Value::Error(CellError::Name));
|
||||
}
|
||||
|
||||
impl T {
|
||||
fn iterative(max_iterations: u32, max_change: f64) -> T {
|
||||
let mut t = T::new();
|
||||
t.wb.calc.iterative = true;
|
||||
t.wb.calc.set_max_iterations(max_iterations);
|
||||
t.wb.calc.set_max_change(max_change);
|
||||
t
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterative_calculation_stops_at_maximum_iterations() {
|
||||
// A1 =A1+1 never settles: every recalculation adds Maximum Iterations.
|
||||
let mut t = T::iterative(100, 0.001);
|
||||
t.set("A1", "=A1+1");
|
||||
assert_eq!(t.num("A1"), 100.0);
|
||||
assert!(t.calc.circular.is_empty());
|
||||
// An edit outside the loop doesn't recalculate it.
|
||||
t.set("B1", "7");
|
||||
assert_eq!(t.num("A1"), 100.0);
|
||||
// Each recalculation starts from the value the cell shows.
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.num("A1"), 200.0);
|
||||
t.wb.calc.set_max_iterations(5);
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.num("A1"), 205.0);
|
||||
// Through a range that holds the formula itself.
|
||||
t.set("C1", "1");
|
||||
t.set("C2", "2");
|
||||
t.set("C3", "=SUM(C1:C3)");
|
||||
assert_eq!(t.num("C3"), 15.0);
|
||||
// Excel's largest Maximum Iterations.
|
||||
let mut t = T::iterative(32767, 0.001);
|
||||
t.set("A1", "=A1+1");
|
||||
assert_eq!(t.num("A1"), 32767.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterative_calculation_converges_within_maximum_change() {
|
||||
let mut t = T::iterative(100, 0.001);
|
||||
t.set("A1", "=(A2+10)/2");
|
||||
t.set("A2", "=A1");
|
||||
assert!((t.num("A1") - 10.0).abs() < 0.002, "{}", t.num("A1"));
|
||||
assert!((t.num("A2") - 10.0).abs() < 0.002, "{}", t.num("A2"));
|
||||
assert!(t.calc.circular.is_empty());
|
||||
// A loop fed by a constant, and a formula that reads the loop, follow a change.
|
||||
t.set("D1", "10");
|
||||
t.set("A1", "=(A2+D1)/2");
|
||||
t.set("E1", "=A1*2");
|
||||
t.set("D1", "30");
|
||||
assert!((t.num("A1") - 30.0).abs() < 0.002, "{}", t.num("A1"));
|
||||
assert!((t.num("E1") - 60.0).abs() < 0.004, "{}", t.num("E1"));
|
||||
// Already settled: recalculating changes it by less than Maximum Change.
|
||||
let a1 = t.num("A1");
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert!((t.num("A1") - a1).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterative_calculation_stops_once_changes_are_below_maximum_change() {
|
||||
// A1 halves its distance to 10 each pass, from 5: 7.5, 8.75, 9.375, 9.6875, and A2 trails
|
||||
// one pass behind. Maximum Change 1 stops once neither moved by 1 or more.
|
||||
let mut t = T::iterative(100, 1.0);
|
||||
t.set("A1", "=(A2+10)/2");
|
||||
assert_eq!(t.num("A1"), 5.0);
|
||||
t.set("A2", "=A1");
|
||||
assert_eq!((t.num("A1"), t.num("A2")), (9.6875, 9.375));
|
||||
// Maximum Iterations 2 stops first.
|
||||
let mut t = T::iterative(2, 1.0);
|
||||
t.set("A1", "=(A2+10)/2");
|
||||
t.set("A2", "=A1");
|
||||
assert_eq!((t.num("A1"), t.num("A2")), (8.75, 7.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterative_calculation_of_text_and_errors() {
|
||||
let mut t = T::iterative(100, 0.001);
|
||||
t.set("A1", "=IF(ISTEXT(A1),A1&\"\",\"go\")");
|
||||
assert_eq!(t.get("A1"), Value::from("go"));
|
||||
t.set("B1", "=B1+1/0");
|
||||
assert_eq!(t.get("B1"), Value::Error(CellError::Div0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circular_references_without_iterative_calculation() {
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=A1+1");
|
||||
assert_eq!(t.get("A1"), Value::Error(CellError::Circ));
|
||||
assert_eq!(t.calc.circular, vec![(0, c("A1"))]);
|
||||
// Switched on, the loop is calculated from 0 rather than from the error.
|
||||
t.wb.calc.iterative = true;
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.num("A1"), 100.0);
|
||||
assert!(t.calc.circular.is_empty());
|
||||
t.wb.calc.iterative = false;
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.get("A1"), Value::Error(CellError::Circ));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_text_coerces_in_the_workbook_date_system() {
|
||||
for (sys, serial) in [(gridcraft_core::DateSystem::D1900, 1462.0), (gridcraft_core::DateSystem::D1904, 0.0)] {
|
||||
let mut t = T::new();
|
||||
t.wb.date_system = sys;
|
||||
t.set("A1", "'1/1/1904");
|
||||
t.set("B1", "=A1+0");
|
||||
t.set("C1", "=VALUE(A1)");
|
||||
t.set("D1", "=-A1");
|
||||
t.set("E1", "=DATEVALUE(A1)");
|
||||
t.set("F1", "=NUMBERVALUE(A1)");
|
||||
assert_eq!(t.get("A1"), Value::from("1/1/1904"));
|
||||
assert_eq!(t.num("B1"), serial, "{sys:?}");
|
||||
assert_eq!(t.num("C1"), serial, "{sys:?}");
|
||||
assert_eq!(t.num("D1"), -serial, "{sys:?}");
|
||||
assert_eq!(t.num("E1"), serial, "{sys:?}");
|
||||
assert_eq!(t.num("F1"), serial, "{sys:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operators() {
|
||||
let mut t = T::new();
|
||||
@@ -195,6 +385,9 @@ fn arrays_do_not_spill_in_tables() {
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: false,
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
});
|
||||
t.set("C4", "=SEQUENCE(2)");
|
||||
t.set("E1", "=SEQUENCE(4)");
|
||||
@@ -219,6 +412,25 @@ fn ifs_and_lazy() {
|
||||
assert_eq!(t.get("B4"), Value::from("five"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choose_with_an_array_index() {
|
||||
let mut t = T::new();
|
||||
for (i, (k, v)) in [(1, 10), (2, 20), (3, 30)].iter().enumerate() {
|
||||
t.set(&format!("A{}", i + 1), &k.to_string());
|
||||
t.set(&format!("B{}", i + 1), &v.to_string());
|
||||
}
|
||||
t.set("D1", "=CHOOSE({1,2},\"a\",\"b\")");
|
||||
assert_eq!(t.get("D1"), Value::from("a"));
|
||||
assert_eq!(t.get("E1"), Value::from("b"));
|
||||
// The usual "look left" idiom: a two-column array from two ranges.
|
||||
t.set("D3", "=VLOOKUP(20,CHOOSE({1,2},B1:B3,A1:A3),2,FALSE)");
|
||||
assert_eq!(t.num("D3"), 2.0);
|
||||
t.set("D4", "=SUM(CHOOSE({1,2},A1:A3,B1:B3))");
|
||||
assert_eq!(t.num("D4"), 66.0);
|
||||
t.set("D5", "=CHOOSE(2,A1:A3,B1:B3)");
|
||||
assert_eq!(t.num("D7"), 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_functions() {
|
||||
let mut t = T::new();
|
||||
@@ -233,6 +445,22 @@ fn references_functions() {
|
||||
assert_eq!(t.num("B3"), 50.0);
|
||||
t.set("B4", "=INDIRECT(\"A\"&4)");
|
||||
assert_eq!(t.num("B4"), 40.0);
|
||||
// With a1 = FALSE the text must be R1C1: A1-style text is #REF!, not read as A1.
|
||||
t.set("C1", "=INDIRECT(\"R3C1\",FALSE)");
|
||||
assert_eq!(t.num("C1"), 30.0);
|
||||
t.set("C2", "=INDIRECT(\"A3\",FALSE)");
|
||||
assert_eq!(t.get("C2"), Value::Error(CellError::Ref));
|
||||
// Defined names don't depend on the reference style.
|
||||
t.wb.names.push(gridcraft_model::DefinedName {
|
||||
name: "Third".into(),
|
||||
scope: None,
|
||||
formula: "Sheet1!$A$3".into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
t.calc.rebuild(&t.wb);
|
||||
t.set("C3", "=INDIRECT(\"Third\",FALSE)");
|
||||
assert_eq!(t.num("C3"), 30.0);
|
||||
t.set("B5", "=SUM(A1:INDEX(A1:A4,3))");
|
||||
assert_eq!(t.num("B5"), 60.0);
|
||||
t.set("B6", "=SUM(A:A)");
|
||||
@@ -242,6 +470,63 @@ fn references_functions() {
|
||||
assert_eq!(t.num("B6"), 105.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indirect_r1c1_out_of_bounds() {
|
||||
for reference in ["R[9223372036854775807]C", "RC[9223372036854775807]", "R[4294967296]C", "R[4294967291]C", "R[2000000]C", "RC[20000]"] {
|
||||
let mut t = T::new();
|
||||
t.set("D5", &format!("=ROW(INDIRECT(\"{reference}\",FALSE))"));
|
||||
assert_eq!(t.get("D5"), Value::Error(CellError::Ref), "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indirect_r1c1_past_the_sheet_does_not_fall_back_to_a1() {
|
||||
let mut t = T::new();
|
||||
t.set("RC16385", "78");
|
||||
for reference in ["RC16385", "rc16385", "RC1:RC16385"] {
|
||||
t.set("D5", &format!("=INDIRECT(\"{reference}\",FALSE)"));
|
||||
assert_eq!(t.get("D5"), Value::Error(CellError::Ref), "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indirect_r1c1_valid_references() {
|
||||
let mut t = T::new();
|
||||
t.set("E6", "11");
|
||||
t.set("A1", "22");
|
||||
t.set("D4", "33");
|
||||
for (reference, expected) in [("R[1]C[1]", 11.0), ("R1C1", 22.0), ("R[-1]C", 33.0)] {
|
||||
t.set("D5", &format!("=INDIRECT(\"{reference}\",FALSE)"));
|
||||
assert_eq!(t.num("D5"), expected, "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_names() {
|
||||
let mut t = T::new();
|
||||
// As files store them: relative to A1. `Left` is the cell to the left, `Above3` the three
|
||||
// cells above, `Mixed` column A of the same row.
|
||||
for (name, formula) in [("Left", "Sheet1!XFD1"), ("Above3", "Sheet1!A1048574:A1048576"), ("Mixed", "Sheet1!$A1")] {
|
||||
t.wb.names.push(gridcraft_model::DefinedName {
|
||||
name: name.into(),
|
||||
scope: None,
|
||||
formula: formula.into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
}
|
||||
t.calc.rebuild(&t.wb);
|
||||
for r in 1..=5 {
|
||||
t.set(&format!("A{r}"), &(r * 10).to_string());
|
||||
}
|
||||
t.set("B2", "=Left");
|
||||
assert_eq!(t.num("B2"), 20.0);
|
||||
t.set("B4", "=Left+Mixed");
|
||||
assert_eq!(t.num("B4"), 80.0);
|
||||
t.set("A6", "=SUM(Above3)");
|
||||
assert_eq!(t.num("A6"), 120.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spills() {
|
||||
let mut t = T::new();
|
||||
@@ -305,6 +590,59 @@ fn let_lambda() {
|
||||
assert_eq!(t.num("A4"), 14.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_given_by_name() {
|
||||
let mut t = T::new();
|
||||
for (i, (k, v)) in [("a", 1), ("b", -2), ("a", 3)].iter().enumerate() {
|
||||
t.set(&format!("A{}", i + 1), k);
|
||||
t.set(&format!("B{}", i + 1), &v.to_string());
|
||||
}
|
||||
t.set("D1", "=BYROW(B1:B3,SUM)");
|
||||
assert_eq!(t.num("D2"), -2.0);
|
||||
t.set("E1", "=MAP(B1:B3,ABS)");
|
||||
assert_eq!(t.num("E2"), 2.0);
|
||||
t.set("F1", "=REDUCE(0,B1:B3,SUM)");
|
||||
assert_eq!(t.num("F1"), 2.0);
|
||||
t.set("G1", "=GROUPBY(A1:A3,B1:B3,SUM,0,0)");
|
||||
assert_eq!(t.get("G1"), Value::from("a"));
|
||||
assert_eq!(t.num("H1"), 4.0);
|
||||
// A LET variable of that name is still the variable.
|
||||
t.set("J1", "=LET(ABS,LAMBDA(x,x*10),SUM(MAP(B1:B3,ABS)))");
|
||||
assert_eq!(t.num("J1"), 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lambda_argument_count() {
|
||||
let mut t = T::new();
|
||||
t.wb.names.push(gridcraft_model::DefinedName {
|
||||
name: "AddPair".into(),
|
||||
scope: None,
|
||||
formula: "LAMBDA(a,b,a+b)".into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
t.calc.rebuild(&t.wb);
|
||||
let omit = "LAMBDA(x,y,IF(ISOMITTED(y),\"Missing\",x+y))";
|
||||
t.set("A1", "=LAMBDA(a,b,a+b)(2)");
|
||||
t.set("A2", "=LAMBDA(a,b,a+b)(2,3,4)");
|
||||
t.set("A3", &format!("={omit}(1,)"));
|
||||
t.set("A4", &format!("={omit}(1)"));
|
||||
t.set("A5", &format!("={omit}(1,2)"));
|
||||
t.set("A6", "=LAMBDA(7)()");
|
||||
t.set("A7", "=AddPair(2)");
|
||||
t.set("A8", "=AddPair(2,3)");
|
||||
assert_eq!(t.get("A1"), Value::Error(CellError::Value));
|
||||
assert_eq!(t.get("A2"), Value::Error(CellError::Value));
|
||||
assert_eq!(t.get("A3"), Value::Text("Missing".into()));
|
||||
assert_eq!(t.get("A4"), Value::Error(CellError::Value));
|
||||
assert_eq!(t.num("A5"), 3.0);
|
||||
assert_eq!(t.num("A6"), 7.0);
|
||||
assert_eq!(t.get("A7"), Value::Error(CellError::Value));
|
||||
assert_eq!(t.num("A8"), 5.0);
|
||||
t.set("A9", "=LAMBDA(x,ISOMITTED(x))()");
|
||||
assert_eq!(t.get("A9"), Value::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_and_sheets() {
|
||||
let mut t = T::new();
|
||||
@@ -353,6 +691,17 @@ fn text_function() {
|
||||
assert_eq!(t.get("A1"), Value::from("1,234.50"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_operator_chains() {
|
||||
let mut t = T::new();
|
||||
t.set("A1", "1");
|
||||
// 1,000 additions: a formula of 3,000 characters, well within Excel's 8,192.
|
||||
t.set("B1", &format!("={}", vec!["A1"; 1000].join("+")));
|
||||
assert_eq!(t.num("B1"), 1000.0);
|
||||
t.set("B2", &format!("=5{}", "+1-1".repeat(600)));
|
||||
assert_eq!(t.num("B2"), 5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtotal_skips_hidden() {
|
||||
let mut t = T::new();
|
||||
@@ -366,6 +715,101 @@ fn subtotal_skips_hidden() {
|
||||
assert_eq!(t.num("B2"), 6.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtotal_109_skips_nested_subtotal() {
|
||||
let mut t = T::new();
|
||||
t.set("A1", "2");
|
||||
t.set("A2", "=SUBTOTAL(9,A1)");
|
||||
t.set("C1", "=SUBTOTAL(109,A1:A2)");
|
||||
t.set("C2", "=SUBTOTAL(9,A1:A2)");
|
||||
t.set("C3", "=SUBTOTAL(109,A1)");
|
||||
assert_eq!(t.num("C1"), 2.0);
|
||||
assert_eq!(t.num("C2"), 2.0);
|
||||
assert_eq!(t.num("C3"), 2.0);
|
||||
// Manually hidden rows are still left out by 109 only.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "1");
|
||||
t.set("A2", "2");
|
||||
t.set("A3", "=SUBTOTAL(9,A1:A2)");
|
||||
t.wb.sheet_mut(0).unwrap().rows.insert(1, gridcraft_model::LineInfo { hidden: true, ..Default::default() });
|
||||
t.set("B1", "=SUBTOTAL(109,A1:A3)");
|
||||
t.set("B2", "=SUBTOTAL(9,A1:A3)");
|
||||
assert_eq!(t.num("B1"), 1.0);
|
||||
assert_eq!(t.num("B2"), 3.0);
|
||||
}
|
||||
|
||||
/// SUBTOTAL leaves out rows a filter hides for every function number, while 1-11 keep rows
|
||||
/// hidden by hand (as in ConditionalFormattingSamples.xlsx, where `SUBTOTAL(9,Table69[Sales])`
|
||||
/// under a filtered table adds only the visible rows).
|
||||
#[test]
|
||||
fn subtotal_skips_filtered_rows() {
|
||||
use gridcraft_model::{AutoFilter, FilterCriterion, LineInfo};
|
||||
let mut t = T::new();
|
||||
for (i, v) in [1, 2, 4, 8, 16, 32].iter().enumerate() {
|
||||
t.set(&format!("A{}", i + 2), &v.to_string());
|
||||
t.set(&format!("C{}", i + 2), &v.to_string());
|
||||
}
|
||||
let crit = || vec![(0, FilterCriterion::Custom { a: (">".into(), "1".into()), b: None, and: false })];
|
||||
let sh = t.wb.sheet_mut(0).unwrap();
|
||||
sh.tables.push(gridcraft_model::Table {
|
||||
id: 1,
|
||||
name: "Sales".into(),
|
||||
range: gridcraft_core::RangeRef::parse("A1:A7").unwrap(),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![gridcraft_model::TableColumn {
|
||||
name: "Amount".into(),
|
||||
totals: Default::default(),
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
xml: None,
|
||||
}],
|
||||
style: String::new(),
|
||||
banded_rows: false,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: true,
|
||||
filter: crit(),
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
});
|
||||
sh.autofilter = Some(AutoFilter { range: gridcraft_core::RangeRef::parse("C1:C7").unwrap(), criteria: crit() });
|
||||
// Rows 3 and 5 are filtered out; row 9 (outside both filters) is hidden by hand.
|
||||
for row in [2, 4, 8] {
|
||||
sh.rows.insert(row, LineInfo { hidden: true, ..Default::default() });
|
||||
}
|
||||
t.set("A9", "64");
|
||||
t.set("E1", "=SUBTOTAL(9,Sales[Amount])");
|
||||
t.set("E2", "=SUBTOTAL(109,Sales[Amount])");
|
||||
t.set("E3", "=SUBTOTAL(9,C2:C7)");
|
||||
t.set("E4", "=SUBTOTAL(9,A2:A9)");
|
||||
t.set("E5", "=SUBTOTAL(109,A2:A9)");
|
||||
t.set("E6", "=SUBTOTAL(2,A2:A7)");
|
||||
t.set("E7", "=AGGREGATE(9,4,A2:A7)");
|
||||
for (at, want) in [("E1", 53.0), ("E2", 53.0), ("E3", 53.0), ("E4", 117.0), ("E5", 53.0), ("E6", 4.0), ("E7", 63.0)] {
|
||||
assert_eq!(t.num(at), want, "{at}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_without_data_argument_is_an_error() {
|
||||
let mut t = T::new();
|
||||
t.set("A1", "1");
|
||||
t.set("A2", "2");
|
||||
t.set("D1", "=AGGREGATE(9,0)");
|
||||
t.set("D2", "=AGGREGATE(4,0)");
|
||||
t.set("D3", "=AGGREGATE(9,0,A1:A2)");
|
||||
t.set("D4", "=AGGREGATE(9,0,A3:A4)");
|
||||
t.set("D5", "=AGGREGATE(9,0,A1:A2,A1:A2)");
|
||||
assert_eq!(t.get("D1"), Value::Error(CellError::Value));
|
||||
assert_eq!(t.get("D2"), Value::Error(CellError::Value));
|
||||
assert_eq!(t.num("D3"), 3.0);
|
||||
assert_eq!(t.num("D4"), 0.0);
|
||||
assert_eq!(t.num("D5"), 6.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recalc_all_after_load() {
|
||||
let mut t = T::new();
|
||||
@@ -467,3 +911,358 @@ fn sumif_resized_sum_range_on_another_sheet_and_through_a_name() {
|
||||
assert_eq!(t.num("C1"), 10.0);
|
||||
assert_eq!(t.num("C2"), 5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimrange() {
|
||||
let mut t = T::new();
|
||||
t.set("C3", "1");
|
||||
t.set("D5", "2");
|
||||
let cases = [
|
||||
("J1", "=ROWS(TRIMRANGE(A1:F10))", 3.0),
|
||||
("J2", "=COLUMNS(TRIMRANGE(A1:F10))", 2.0),
|
||||
("J3", "=ROWS(TRIMRANGE(A1:F10,2))", 5.0),
|
||||
("J4", "=ROWS(TRIMRANGE(A1:F10,1,0))", 8.0),
|
||||
("J5", "=COLUMNS(TRIMRANGE(A1:F10,1,0))", 6.0),
|
||||
("J6", "=ROWS(TRIMRANGE(A1:F10,0,0))", 10.0),
|
||||
("J7", "=SUM(TRIMRANGE(C:C))", 1.0),
|
||||
("J8", "=ROWS(TRIMRANGE(C:C))", 1.0),
|
||||
("J9", "=ROWS(TRIMRANGE(C:C,2))", 3.0),
|
||||
("J10", "=MIN(ROW(TRIMRANGE(A1:F10)))", 3.0),
|
||||
("J11", "=COLUMNS(TRIMRANGE({1,2;3,4}))", 2.0),
|
||||
];
|
||||
for (at, f, _) in cases {
|
||||
t.set(at, f);
|
||||
}
|
||||
for (at, f, want) in cases {
|
||||
assert_eq!(t.num(at), want, "{f}");
|
||||
}
|
||||
// The result spills as the trimmed block and follows edits.
|
||||
t.set("L1", "=TRIMRANGE(A1:F10)");
|
||||
assert_eq!((t.num("L1"), t.num("M3")), (1.0, 2.0));
|
||||
t.set("E6", "3");
|
||||
assert_eq!((t.num("J1"), t.num("J2")), (4.0, 3.0));
|
||||
// Errors: a bad trim code, nothing but blanks, several areas.
|
||||
t.set("K1", "=TRIMRANGE(A1:F10,4)");
|
||||
assert_eq!(t.get("K1"), Value::Error(CellError::Value));
|
||||
t.set("K2", "=TRIMRANGE(Q1:Q9)");
|
||||
assert_eq!(t.get("K2"), Value::Error(CellError::Calc));
|
||||
t.set("K3", "=TRIMRANGE((A1:B2,C3:D4))");
|
||||
assert_eq!(t.get("K3"), Value::Error(CellError::Value));
|
||||
}
|
||||
|
||||
/// `formula` in AB1 over a small mixed sheet. The ranges in the cases below are cut from it:
|
||||
///
|
||||
/// ```text
|
||||
/// A B C E
|
||||
/// 1 1.5 10 =A1*4 (C1 is a formula cell inside the ranges)
|
||||
/// 2 2 TRUE #DIV/0! (E2 only when `error` is set)
|
||||
/// 3 text 3
|
||||
/// 4 -0.25
|
||||
/// ```
|
||||
fn aggregate_of(error: bool, formula: &str) -> Value {
|
||||
let mut t = T::new();
|
||||
for (at, v) in [("A1", "1.5"), ("A2", "2"), ("A3", "skipped"), ("A4", "-0.25"), ("B1", "10"), ("B2", "TRUE"), ("B3", "3"), ("C1", "=A1*4")] {
|
||||
t.set(at, v);
|
||||
}
|
||||
if error {
|
||||
t.set("E2", "#DIV/0!");
|
||||
}
|
||||
|
||||
// AB1 is outside every range used, so the formula can't read itself.
|
||||
t.set("AB1", formula);
|
||||
t.get("AB1")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_count_average_over_ranges() {
|
||||
// Text, booleans, blanks and a formula cell inside ranges; direct arguments; unions; whole
|
||||
// columns; blocks holding an error or nothing numeric. The expected values are what the
|
||||
// array path (the ranges copied into an array) gave before the ranges were folded in place,
|
||||
// so any difference is a change of behavior.
|
||||
let n = Value::Number;
|
||||
let e = Value::Error;
|
||||
|
||||
// (formula written with SUM, error in E2?, [SUM, COUNT, AVERAGE] of that formula)
|
||||
#[rustfmt::skip]
|
||||
let cases: &[(&str, bool, [Value; 3])] = &[
|
||||
("=SUM(A1:A1,B3)", false, [n(4.5), n(2.0), n(2.25)]),
|
||||
("=SUM(A1:A1,B3)", true, [n(4.5), n(2.0), n(2.25)]),
|
||||
("=SUM((A1:A2,B1:B3))", false, [n(16.5), n(4.0), n(4.125)]),
|
||||
("=SUM((A1:A2,B1:B3))", true, [n(16.5), n(4.0), n(4.125)]),
|
||||
("=SUM(A1:A4,B1:B3)", false, [n(16.25), n(5.0), n(3.25)]),
|
||||
("=SUM(A1:A4,B1:B3)", true, [n(16.25), n(5.0), n(3.25)]),
|
||||
("=SUM(A1:A4,\"x\")", false, [e(CellError::Value), n(3.0), e(CellError::Value)]),
|
||||
("=SUM(A1:A4,\"x\")", true, [e(CellError::Value), n(3.0), e(CellError::Value)]),
|
||||
("=SUM(A1:B4,5,\"7\",TRUE)", false, [n(29.25), n(8.0), n(3.65625)]),
|
||||
("=SUM(A1:B4,5,\"7\",TRUE)", true, [n(29.25), n(8.0), n(3.65625)]),
|
||||
("=SUM(A1:C4)+SUM(B1:B3)", false, [n(35.25), n(8.0), n(10.208333333333334)]),
|
||||
("=SUM(A1:C4)+SUM(B1:B3)", true, [n(35.25), n(8.0), n(10.208333333333334)]),
|
||||
("=SUM(A1:C4)", false, [n(22.25), n(6.0), n(3.7083333333333335)]),
|
||||
("=SUM(A1:C4)", true, [n(22.25), n(6.0), n(3.7083333333333335)]),
|
||||
("=SUM(A1:E4)", false, [n(22.25), n(6.0), n(3.7083333333333335)]),
|
||||
("=SUM(A1:E4)", true, [e(CellError::Div0), n(6.0), e(CellError::Div0)]),
|
||||
("=SUM(A1)", false, [n(1.5), n(1.0), n(1.5)]),
|
||||
("=SUM(A1)", true, [n(1.5), n(1.0), n(1.5)]),
|
||||
("=SUM(A3,B2)", false, [n(0.0), n(0.0), e(CellError::Div0)]),
|
||||
("=SUM(A3,B2)", true, [n(0.0), n(0.0), e(CellError::Div0)]),
|
||||
("=SUM(A:C)", false, [n(22.25), n(6.0), n(3.7083333333333335)]),
|
||||
("=SUM(A:C)", true, [n(22.25), n(6.0), n(3.7083333333333335)]),
|
||||
("=SUM(E1:E3)", false, [n(0.0), n(0.0), e(CellError::Div0)]),
|
||||
("=SUM(E1:E3)", true, [e(CellError::Div0), n(0.0), e(CellError::Div0)]),
|
||||
("=SUM(Z1:Z9)", false, [n(0.0), n(0.0), e(CellError::Div0)]),
|
||||
("=SUM(Z1:Z9)", true, [n(0.0), n(0.0), e(CellError::Div0)]),
|
||||
];
|
||||
|
||||
for (formula, error, want) in cases {
|
||||
for (func, want) in ["SUM", "COUNT", "AVERAGE"].into_iter().zip(want) {
|
||||
// The same formula for each function: `SUM(` becomes `COUNT(` or `AVERAGE(`.
|
||||
let f = formula.replace("SUM", func);
|
||||
|
||||
assert_eq!(&aggregate_of(*error, &f), want, "{f} (error in E2: {error})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_count_average_have_no_size_limit() {
|
||||
// One stored cell far down stretches the used range to 27 million cells (27 columns by a
|
||||
// million rows), past the 16M-cell limit of ranges copied into an array. Only two cells are
|
||||
// stored, so the sheet itself is tiny.
|
||||
for (func, want) in [("SUM", Value::Number(2.5)), ("COUNT", Value::Number(2.0)), ("AVERAGE", Value::Number(1.25))] {
|
||||
for range in ["A1:AA1000000", "A:AA"] {
|
||||
let mut t = T::new();
|
||||
t.set("A1", "1.5");
|
||||
t.set("Z1000000", "1");
|
||||
|
||||
t.set("AB1", &format!("={func}({range})"));
|
||||
|
||||
assert_eq!(t.get("AB1"), want, "{func}({range})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_count_average_over_spilled_values() {
|
||||
// A1 spills over A1:A3, so the block holds values that exist only as a spill (they have no
|
||||
// stored cell of their own). The host must not fold such a block in place: it falls back
|
||||
// to the array path, which sees the spill. Expected: 1 + 2 + 3 + 10.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=SEQUENCE(3)");
|
||||
t.set("A4", "10");
|
||||
|
||||
for (f, want) in [("SUM", 16.0), ("COUNT", 4.0), ("AVERAGE", 4.0)] {
|
||||
t.set("C1", &format!("={f}(A1:A5)"));
|
||||
|
||||
assert_eq!(t.num("C1"), want, "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_arguments_are_read_in_order() {
|
||||
// Volatile cells draw a random number each time they are calculated, so the order in which
|
||||
// the arguments are read decides which draw each one gets. `B1:B2` comes first, so B2 must
|
||||
// draw before the `RAND()` argument does. (Reading the plain `RAND()` first once gave
|
||||
// 7.9043 here.) The expected values are what the array path gave; they depend on the random
|
||||
// generator and its seed, and must be updated if either changes.
|
||||
let mut t = T::new();
|
||||
t.set("B1", "1");
|
||||
t.set("B2", "=RAND()*10");
|
||||
|
||||
t.set("A1", "=SUM(B1:B2,RAND())");
|
||||
|
||||
assert_eq!((t.num("A1"), t.num("B2")), (4.968520165759784, 3.3112028100185356));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_count_average_follow_edits_inside_the_range() {
|
||||
// A range read in place must still count as a precedent of the formula: if it didn't, an
|
||||
// edit inside it would leave the formula showing a stale value. Each step below changes one
|
||||
// cell inside the range and checks all three functions; the last one changes a cell outside.
|
||||
for range in ["A1:A5", "A:A"] {
|
||||
let mut t = T::new();
|
||||
t.set("A1", "1");
|
||||
t.set("A3", "3");
|
||||
t.set("C1", &format!("=SUM({range})"));
|
||||
t.set("C2", &format!("=COUNT({range})"));
|
||||
t.set("C3", &format!("=AVERAGE({range})"));
|
||||
let all = |t: &T| (t.num("C1"), t.num("C2"), t.num("C3"));
|
||||
assert_eq!(all(&t), (4.0, 2.0, 2.0), "{range}");
|
||||
|
||||
t.set("A1", "5");
|
||||
assert_eq!(all(&t), (8.0, 2.0, 4.0), "{range}: edit");
|
||||
|
||||
t.set("A2", "10");
|
||||
assert_eq!(all(&t), (18.0, 3.0, 6.0), "{range}: fill a blank");
|
||||
|
||||
t.set("A3", "text");
|
||||
assert_eq!(all(&t), (15.0, 2.0, 7.5), "{range}: number to text");
|
||||
|
||||
t.set("A2", "");
|
||||
assert_eq!(all(&t), (5.0, 1.0, 5.0), "{range}: clear");
|
||||
|
||||
t.set("A5", "=A1*2");
|
||||
assert_eq!(all(&t), (15.0, 2.0, 7.5), "{range}: formula in the range");
|
||||
|
||||
t.set("A1", "1");
|
||||
assert_eq!(all(&t), (3.0, 2.0, 1.5), "{range}: its precedent changes");
|
||||
|
||||
// A7 is inside the whole column A:A but outside A1:A5.
|
||||
t.set("A7", "100");
|
||||
let outside = if range == "A:A" { (103.0, 3.0, 103.0 / 3.0) } else { (3.0, 2.0, 1.5) };
|
||||
assert_eq!(all(&t), outside, "{range}: a cell outside the range");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visit_range_declines_when_a_formula_in_the_block_spills_into_it() {
|
||||
// The sheet: D1 = SEQUENCE(3) and D4 = 10, and D1 has not been calculated yet when the
|
||||
// block D1:D5 is read.
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.cells.set(c("D1"), Cell::formula(Formula::new("=SEQUENCE(3)")));
|
||||
sh.cells.set(c("D4"), Cell::value(Value::Number(10.0)));
|
||||
let block = gridcraft_core::RangeRef::parse("D1:D5").unwrap();
|
||||
|
||||
// Reading the block calculates D1, which spills over D2:D3. A walk over the stored cells
|
||||
// would never see 2 and 3, so the host must decline and leave the block to `range_values`.
|
||||
// (`Calc` recalculates a pass that produced new spills, so final results are right either
|
||||
// way; only this direct call shows the host's contract.)
|
||||
let walked = crate::recalc::tests::probe_visit_range(&wb, &[("D1", "=SEQUENCE(3)")], block);
|
||||
|
||||
assert_eq!(walked, None, "walked a block holding a spill it can't see");
|
||||
}
|
||||
|
||||
/// Trim references evaluate as `TRIMRANGE(range, code, code)`.
|
||||
#[test]
|
||||
fn trim_references() {
|
||||
let mut t = T::new();
|
||||
t.set("C3", "1");
|
||||
t.set("D5", "2");
|
||||
t.set("A20", "5");
|
||||
t.set("A21", "6");
|
||||
let cases = [
|
||||
("J1", "=ROWS(A1.:.F10)", "=ROWS(TRIMRANGE(A1:F10,3,3))", 3.0),
|
||||
("J2", "=COLUMNS(A1.:.F10)", "=COLUMNS(TRIMRANGE(A1:F10,3,3))", 2.0),
|
||||
("J3", "=ROWS(A1:.F10)", "=ROWS(TRIMRANGE(A1:F10,2,2))", 5.0),
|
||||
("J4", "=COLUMNS(A1:.F10)", "=COLUMNS(TRIMRANGE(A1:F10,2,2))", 4.0),
|
||||
("J5", "=ROWS(A1.:F10)", "=ROWS(TRIMRANGE(A1:F10,1,1))", 8.0),
|
||||
("J6", "=MIN(ROW(A1.:F10))", "=MIN(ROW(TRIMRANGE(A1:F10,1,1)))", 3.0),
|
||||
("J7", "=SUM(A:.A)", "=SUM(TRIMRANGE(A:A,2,2))", 11.0),
|
||||
("J8", "=ROWS(A:.A)", "=ROWS(TRIMRANGE(A:A,2,2))", 21.0),
|
||||
("J9", "=ROWS(A.:.A)", "=ROWS(TRIMRANGE(A:A,3,3))", 2.0),
|
||||
("J10", "=ROWS(20.:.30)", "=ROWS(TRIMRANGE(20:30,3,3))", 2.0),
|
||||
];
|
||||
for (at, f, _, _) in cases {
|
||||
t.set(at, f);
|
||||
}
|
||||
for (i, (at, f, same, want)) in cases.iter().enumerate() {
|
||||
assert_eq!(t.num(at), *want, "{f}");
|
||||
let k = format!("K{}", i + 1);
|
||||
t.set(&k, same);
|
||||
assert_eq!(t.num(&k), *want, "{same}");
|
||||
}
|
||||
// The trimmed block spills and follows edits to the full range.
|
||||
t.set("L1", "=C1.:.F10");
|
||||
assert_eq!((t.num("L1"), t.num("M3")), (1.0, 2.0));
|
||||
t.set("A22", "4");
|
||||
assert_eq!((t.num("J7"), t.num("J8")), (15.0, 22.0));
|
||||
// Nothing but blanks.
|
||||
t.set("K20", "=SUM(Q1:.Q9)");
|
||||
assert_eq!(t.get("K20"), Value::Error(CellError::Calc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_width_is_the_column_width_dialog_value_rounded() {
|
||||
// #735: Excel 365 values. Widths in px as `home.columnWidth {"chars"}` sets them
|
||||
// (chars * 7 + 5): 10.71 -> 80, 12 -> 89, 10.57 -> 79, 2.86 -> 25; B keeps the default 8.43 (64).
|
||||
let mut t = T::new();
|
||||
let sh = t.wb.sheet_mut(0).unwrap();
|
||||
for (col, px) in [(2, 80.0), (3, 89.0), (4, 79.0), (5, 25.0)] {
|
||||
sh.cols.insert(col, gridcraft_model::LineInfo { size: Some(px), ..Default::default() });
|
||||
}
|
||||
for (at, col) in [("H1", "B"), ("H2", "C"), ("H3", "D"), ("H4", "E"), ("H5", "F")] {
|
||||
t.set(at, &format!("=CELL(\"width\",{col}1)"));
|
||||
}
|
||||
assert_eq!([t.num("H1"), t.num("H2"), t.num("H3"), t.num("H4"), t.num("H5")], [8.0, 11.0, 12.0, 11.0, 3.0]);
|
||||
}
|
||||
|
||||
/// Expected results are Excel's, from Apache POI's `DGet.xls` (rows 46-49): a criteria cell holding
|
||||
/// a formula under a label that names no field is evaluated for every record.
|
||||
#[test]
|
||||
fn database_functions_with_computed_criteria() {
|
||||
let mut t = T::new();
|
||||
let db = [
|
||||
["name", "age", "size", "headgear", "glasses"],
|
||||
["Huey", "6", "45", "cap~", "FALSE"],
|
||||
["Dewey", "7", "fourty-six", "cap?", "FALSE"],
|
||||
["Louie", "8", "47", "cap*", "FALSE"],
|
||||
["Donald", "32", "70", "sailor's hat", "FALSE"],
|
||||
["Scrooge", "62", "65", "top hat", "TRUE"],
|
||||
];
|
||||
for (r, row) in db.iter().enumerate() {
|
||||
for (c, v) in row.iter().enumerate() {
|
||||
t.set(&format!("{}{}", ["F", "G", "H", "I", "J"][c], r + 2), v);
|
||||
}
|
||||
}
|
||||
t.set("G45", "7");
|
||||
let cases = [
|
||||
// Relative references are to the first record's row and move to each record's row;
|
||||
// `$G$45` stays put.
|
||||
("G", "=G2<$G$45", "Dewey"),
|
||||
// Column labels stand for the record's fields.
|
||||
("H", "=glasses=TRUE", "Scrooge"),
|
||||
("I", "=age<7", "Huey"),
|
||||
("J", "=size/7=10", "Donald"),
|
||||
// An absolute reference to a cell that is not the first record's.
|
||||
("K", "=H3=$L$1", "Donald"),
|
||||
];
|
||||
t.set("L1", "70");
|
||||
for (i, (col, formula, _)) in cases.iter().enumerate() {
|
||||
t.set(&format!("{col}46"), "Formula");
|
||||
t.set(&format!("{col}47"), formula);
|
||||
t.set(&format!("B{}", 46 + i), &format!("=DGET($F$2:$J$7,\"name\",{col}46:{col}47)"));
|
||||
}
|
||||
for (i, (_, formula, want)) in cases.iter().enumerate() {
|
||||
assert_eq!(t.get(&format!("B{}", 46 + i)), Value::text(*want), "{formula}");
|
||||
}
|
||||
// Every database function takes them, ANDed with the other criteria of their row.
|
||||
// Text sorts after numbers, so Dewey's "fourty-six" is > 40.
|
||||
t.set("L47", "=size>40");
|
||||
t.set("M46", "age");
|
||||
t.set("M47", ">6");
|
||||
t.set("B51", "=DCOUNT($F$2:$J$7,\"age\",I46:I47)");
|
||||
t.set("B52", "=DSUM($F$2:$J$7,\"age\",G46:G47)");
|
||||
t.set("B53", "=DCOUNTA($F$2:$J$7,\"name\",L46:M47)");
|
||||
assert_eq!(t.num("B51"), 1.0);
|
||||
assert_eq!(t.num("B52"), 7.0);
|
||||
assert_eq!(t.num("B53"), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_extreme_arguments_return_ref() {
|
||||
let wb = Workbook::new();
|
||||
for formula in [
|
||||
"=OFFSET(B2,1E300,0)",
|
||||
"=OFFSET(B2,0,1E300)",
|
||||
"=OFFSET(B2,0,0,1E300,1)",
|
||||
"=OFFSET(B2,0,0,1,1E300)",
|
||||
"=OFFSET(B2,-1E300,0)",
|
||||
"=OFFSET(B2,0,-1E300)",
|
||||
"=OFFSET(B2,0,0,-1E300,1)",
|
||||
"=OFFSET(B2,0,0,1,-1E300)",
|
||||
"=OFFSET(B2,1E300,0,-1E300,1)",
|
||||
"=OFFSET(B2,0,1E300,1,-1E300)",
|
||||
"=OFFSET(B2,-1E300,0,-1E300,1)",
|
||||
] {
|
||||
assert_eq!(crate::evaluate(&wb, 0, c("D1"), formula), Value::Error(CellError::Ref), "{formula}");
|
||||
}
|
||||
for (formula, expected) in [
|
||||
("=ROW(OFFSET(B2,1.9,0))", 3.0),
|
||||
("=COLUMN(OFFSET(B2,0,-1.9))", 1.0),
|
||||
("=ROWS(OFFSET(B2,0,0,-2,1))", 2.0),
|
||||
("=COLUMNS(OFFSET(B2,0,0,1,-2))", 2.0),
|
||||
("=ROWS(OFFSET(A1,0,0,1048576,1))", 1048576.0),
|
||||
] {
|
||||
assert_eq!(crate::evaluate(&wb, 0, c("D1"), formula), Value::Number(expected), "{formula}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! TRIMRANGE: a range or array without its blank outer rows and columns (Microsoft's
|
||||
//! documented semantics: trim_rows / trim_cols 0 none, 1 leading, 2 trailing, 3 both).
|
||||
|
||||
use gridcraft_core::{Array, CellError, CellRef, RangeRef, Value};
|
||||
use gridcraft_formula::{Expr, TrimMode};
|
||||
|
||||
use crate::eval::{Area, Ev, Evaluator, MAX_CELLS};
|
||||
|
||||
/// (leading, trailing) for a trim_rows / trim_cols code.
|
||||
fn mode(code: f64) -> Result<(bool, bool), CellError> {
|
||||
match code.trunc() {
|
||||
0.0 => Ok((false, false)),
|
||||
1.0 => Ok((true, false)),
|
||||
2.0 => Ok((false, true)),
|
||||
3.0 => Ok((true, true)),
|
||||
_ => Err(CellError::Value),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows and columns (first, last) holding a non-blank value in a row-major grid.
|
||||
fn bounds(values: &[Value], width: usize) -> Option<((usize, usize), (usize, usize))> {
|
||||
let mut b: Option<((usize, usize), (usize, usize))> = None;
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
if matches!(v, Value::Empty) {
|
||||
continue;
|
||||
}
|
||||
let (r, c) = (i / width.max(1), i % width.max(1));
|
||||
b = Some(match b {
|
||||
None => ((r, r), (c, c)),
|
||||
Some(((r0, r1), (c0, c1))) => ((r0.min(r), r1.max(r)), (c0.min(c), c1.max(c))),
|
||||
});
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The kept span of `0..len` given the non-blank span and the trim flags.
|
||||
fn keep(len: usize, nonblank: (usize, usize), (lead, trail): (bool, bool)) -> (usize, usize) {
|
||||
(if lead { nonblank.0 } else { 0 }, if trail { nonblank.1 } else { len.saturating_sub(1) })
|
||||
}
|
||||
|
||||
impl Evaluator<'_> {
|
||||
pub(crate) fn trimrange(&mut self, args: &[Expr]) -> Ev {
|
||||
match self.trimrange_inner(args) {
|
||||
Ok(ev) => ev,
|
||||
Err(e) => Ev::V(Value::Error(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A trim reference `A1.:E10` / `A1:.E10` / `A1.:.E10`: `TRIMRANGE(range, code, code)`.
|
||||
pub(crate) fn trim_ref(&mut self, mode: TrimMode, x: &Expr) -> Ev {
|
||||
let flags = match mode {
|
||||
TrimMode::Leading => (true, false),
|
||||
TrimMode::Trailing => (false, true),
|
||||
TrimMode::All => (true, true),
|
||||
};
|
||||
let ev = self.eval(x);
|
||||
match self.trim_ev(ev, flags, flags) {
|
||||
Ok(ev) => ev,
|
||||
Err(e) => Ev::V(Value::Error(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn trim_mode(&mut self, args: &[Expr], i: usize) -> Result<(bool, bool), CellError> {
|
||||
match args.get(i) {
|
||||
None | Some(Expr::Missing) => Ok((true, true)),
|
||||
Some(e) => match self.value(e).scalar() {
|
||||
Value::Error(e) => Err(e),
|
||||
v => mode(v.to_number()?),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn trimrange_inner(&mut self, args: &[Expr]) -> Result<Ev, CellError> {
|
||||
let first = match args {
|
||||
[first] | [first, _] | [first, _, _] => first,
|
||||
_ => return Err(CellError::Value),
|
||||
};
|
||||
let rows = self.trim_mode(args, 1)?;
|
||||
let cols = self.trim_mode(args, 2)?;
|
||||
let ev = self.eval(first);
|
||||
self.trim_ev(ev, rows, cols)
|
||||
}
|
||||
|
||||
fn trim_ev(&mut self, ev: Ev, rows: (bool, bool), cols: (bool, bool)) -> Result<Ev, CellError> {
|
||||
let none = rows == (false, false) && cols == (false, false);
|
||||
match ev {
|
||||
Ev::R(areas) => {
|
||||
let [a] = areas.as_slice() else { return Err(CellError::Value) };
|
||||
if none {
|
||||
return Ok(Ev::R(vec![*a]));
|
||||
}
|
||||
// Cells past the used range are blank: only the used part is read.
|
||||
let part = self.trim(a);
|
||||
let (h, w) = (part.height() as usize, part.width() as usize);
|
||||
if (h as u64) * (w as u64) > MAX_CELLS {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let values = self.host.range_values(a.sheet, part);
|
||||
let ((r0, r1), (c0, c1)) = bounds(&values, w).ok_or(CellError::Calc)?;
|
||||
let (h_all, w_all) = (a.range.height() as usize, a.range.width() as usize);
|
||||
let (kr0, kr1) = keep(h_all, (r0, r1), rows);
|
||||
let (kc0, kc1) = keep(w_all, (c0, c1), cols);
|
||||
let at = |r: usize, c: usize| CellRef::new(a.range.start.row.saturating_add(r as u32), a.range.start.col.saturating_add(c as u32));
|
||||
Ok(Ev::R(vec![Area { sheet: a.sheet, range: RangeRef::new(at(kr0, kc0), at(kr1, kc1)) }]))
|
||||
}
|
||||
Ev::V(Value::Array(arr)) => {
|
||||
if none {
|
||||
return Ok(Ev::V(Value::Array(arr)));
|
||||
}
|
||||
let ((r0, r1), (c0, c1)) = bounds(&arr.data, arr.cols).ok_or(CellError::Calc)?;
|
||||
let (kr0, kr1) = keep(arr.rows, (r0, r1), rows);
|
||||
let (kc0, kc1) = keep(arr.cols, (c0, c1), cols);
|
||||
let mut data = Vec::with_capacity((kr1 + 1 - kr0) * (kc1 + 1 - kc0));
|
||||
for r in kr0..=kr1 {
|
||||
for c in kc0..=kc1 {
|
||||
data.push(arr.get(r, c).cloned().unwrap_or(Value::Empty));
|
||||
}
|
||||
}
|
||||
Array::new(kr1 + 1 - kr0, kc1 + 1 - kc0, data).map(|a| Ev::V(Value::from(a))).ok_or(CellError::Value)
|
||||
}
|
||||
Ev::V(Value::Error(e)) => Err(e),
|
||||
Ev::V(Value::Empty) if !none => Err(CellError::Calc),
|
||||
Ev::V(v) => Ok(Ev::V(v)),
|
||||
Ev::L(_) => Err(CellError::Value),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,7 +122,7 @@ impl Fmt {
|
||||
pub fn new(code: &str) -> Fmt {
|
||||
let t = code.trim();
|
||||
let general = t.is_empty() || t.eq_ignore_ascii_case("general");
|
||||
Fmt { general, fmt: NumberFormat::parse(if general { "General" } else { t }) }
|
||||
Fmt { general, fmt: NumberFormat::parse_cached(if general { "General" } else { t }) }
|
||||
}
|
||||
/// Formats `v`; `step` (axis labels) fixes the decimals for General.
|
||||
pub fn format(&self, v: f64, step: Option<f64>) -> String {
|
||||
|
||||
+17
-3
@@ -15,17 +15,18 @@ mod raster;
|
||||
mod render;
|
||||
mod resolve;
|
||||
mod sparkline;
|
||||
mod trend;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use gridcraft_model::{Chart, ChartKind, LegendPos, SparklineKind};
|
||||
pub use gridcraft_model::{Chart, ChartKind, LegendPos, SparklineKind, Trendline, TrendlineKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use axis::{Scale, format_number, nice_scale};
|
||||
pub use raster::rasterize;
|
||||
pub use render::{Swatch, legend_entries, render};
|
||||
pub use resolve::{default_palette, resolve, series_color};
|
||||
pub use render::{Swatch, legend_entries, render, supports_trendline};
|
||||
pub use resolve::{default_palette, resolve, series_color, series_plot_kind};
|
||||
pub use sparkline::render_sparkline;
|
||||
|
||||
/// Straight (non-premultiplied) RGBA colour.
|
||||
@@ -123,6 +124,9 @@ impl Measure for ApproxMeasure {
|
||||
pub struct ChartData {
|
||||
pub categories: Vec<String>,
|
||||
pub series: Vec<SeriesData>,
|
||||
/// Workbook-theme colours for the points of pie-like charts, repeating (point `j` uses entry `j % len`); empty uses the default theme.
|
||||
#[serde(default)]
|
||||
pub palette: Vec<Rgba>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -140,10 +144,19 @@ pub struct SeriesData {
|
||||
pub secondary: bool,
|
||||
/// Draw line segments as a smoothed (spline) curve.
|
||||
pub smooth: bool,
|
||||
/// Trendlines to fit and draw over this series.
|
||||
pub trendlines: Vec<TrendlineData>,
|
||||
/// Number format code of the source values ("General" by default).
|
||||
pub number_format: String,
|
||||
}
|
||||
|
||||
/// A trendline to draw: the model settings with the line colour resolved against the theme.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TrendlineData {
|
||||
pub spec: Trendline,
|
||||
pub color: Rgba,
|
||||
}
|
||||
|
||||
impl Default for SeriesData {
|
||||
fn default() -> Self {
|
||||
SeriesData {
|
||||
@@ -155,6 +168,7 @@ impl Default for SeriesData {
|
||||
kind: ChartKind::ColumnClustered,
|
||||
secondary: false,
|
||||
smooth: false,
|
||||
trendlines: vec![],
|
||||
number_format: "General".into(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +138,8 @@ fn circle(cx: f32, cy: f32, r: f32) -> Vec<[f32; 2]> {
|
||||
}
|
||||
|
||||
fn rounded_rect(x: f32, y: f32, w: f32, h: f32, r: f32) -> Vec<[f32; 2]> {
|
||||
let r = r.clamp(0.0, w.min(h) / 2.0);
|
||||
// A negative or NaN extent gives an upper bound of 0 (clamp panics if max < min or NaN).
|
||||
let r = r.clamp(0.0, (w.min(h) / 2.0).max(0.0));
|
||||
if r < 0.5 {
|
||||
return vec![[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
|
||||
}
|
||||
|
||||
+261
-34
@@ -3,10 +3,11 @@
|
||||
use std::collections::HashSet;
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
use gridcraft_model::{Chart, ChartKind, LegendPos, Theme};
|
||||
use gridcraft_model::{Chart, ChartKind, LegendPos, LineDash, Theme, TrendlineKind};
|
||||
|
||||
use crate::axis::{Fmt, Scale, clean, fixed_scale, nice_scale};
|
||||
use crate::resolve::{MAX_POINTS, MAX_SERIES, series_color};
|
||||
use crate::resolve::{MAX_POINTS, MAX_SERIES, MAX_TRENDLINES, series_color};
|
||||
use crate::trend::{auto_name, fit_trendline, moving_average};
|
||||
use crate::{ChartData, HAlign, Measure, Prim, Rgba, SeriesData, VAlign};
|
||||
|
||||
pub(crate) const TEXT: Rgba = [0x59, 0x59, 0x59, 0xFF];
|
||||
@@ -128,7 +129,7 @@ fn plot_kind(chart: &Chart, s: &SeriesData) -> ChartKind {
|
||||
fn point_color(data: &ChartData, j: usize) -> Rgba {
|
||||
match (j, data.series.first()) {
|
||||
(0, Some(s)) => s.color,
|
||||
_ => series_color(&Theme::default(), j),
|
||||
_ => j.checked_rem(data.palette.len()).and_then(|k| data.palette.get(k)).copied().unwrap_or_else(|| series_color(&Theme::default(), j)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,20 +159,28 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
|
||||
let total = data.series.first().map(|s| s.color).unwrap_or(TEXT);
|
||||
vec![("Increase".into(), UP, Swatch::Box), ("Decrease".into(), DOWN, Swatch::Box), ("Total".into(), total, Swatch::Box)]
|
||||
}
|
||||
_ => data
|
||||
.series
|
||||
.iter()
|
||||
.take(MAX_SERIES)
|
||||
.map(|s| {
|
||||
let sw = match plot_kind(chart, s) {
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
|
||||
ChartKind::LineMarkers => Swatch::LineMarker,
|
||||
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
|
||||
_ => Swatch::Box,
|
||||
};
|
||||
(s.name.clone(), s.color, sw)
|
||||
})
|
||||
.collect(),
|
||||
_ => {
|
||||
let series = data.series.iter().take(MAX_SERIES);
|
||||
let mut out: Vec<(String, Rgba, Swatch)> = series
|
||||
.clone()
|
||||
.map(|s| {
|
||||
let sw = match plot_kind(chart, s) {
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
|
||||
ChartKind::LineMarkers => Swatch::LineMarker,
|
||||
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
|
||||
_ => Swatch::Box,
|
||||
};
|
||||
(s.name.clone(), s.color, sw)
|
||||
})
|
||||
.collect();
|
||||
// Trendlines follow the series, named "Linear (Sales)" unless given a name.
|
||||
for s in series.filter(|s| supports_trendline(plot_kind(chart, s))) {
|
||||
for t in s.trendlines.iter().take(MAX_TRENDLINES) {
|
||||
out.push((t.spec.name.clone().unwrap_or_else(|| auto_name(t.spec.kind, &s.name)), t.color, Swatch::Line));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +190,7 @@ fn sanitize_vals(v: &[Option<f64>]) -> Vec<Option<f64>> {
|
||||
|
||||
fn sanitize(d: &ChartData) -> ChartData {
|
||||
ChartData {
|
||||
palette: d.palette.iter().take(MAX_POINTS).copied().collect(),
|
||||
categories: d.categories.iter().take(MAX_POINTS).cloned().collect(),
|
||||
series: d
|
||||
.series
|
||||
@@ -195,6 +205,7 @@ fn sanitize(d: &ChartData) -> ChartData {
|
||||
kind: s.kind,
|
||||
secondary: s.secondary,
|
||||
smooth: s.smooth,
|
||||
trendlines: s.trendlines.iter().take(MAX_TRENDLINES).cloned().collect(),
|
||||
number_format: s.number_format.clone(),
|
||||
})
|
||||
.collect(),
|
||||
@@ -244,7 +255,7 @@ fn draw_kind(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
Doughnut => pie(ctx, chart, data, area, 0.5, false),
|
||||
Sunburst => pie(ctx, chart, data, area, 0.2, true),
|
||||
Treemap => treemap(ctx, chart, data, area),
|
||||
Funnel => funnel(ctx, data, area),
|
||||
Funnel => funnel(ctx, chart, data, area),
|
||||
Radar => radar(ctx, chart, data, area),
|
||||
_ => {
|
||||
let area = axis_titles(ctx, chart, area);
|
||||
@@ -256,8 +267,8 @@ fn draw_kind(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
Scatter | ScatterLines | Bubble => scatter(ctx, chart, data, area),
|
||||
Histogram => histogram(ctx, chart, data, area),
|
||||
Waterfall => waterfall(ctx, chart, data, area),
|
||||
BoxWhisker => box_whisker(ctx, data, area),
|
||||
Stock => stock(ctx, data, area),
|
||||
BoxWhisker => box_whisker(ctx, chart, data, area),
|
||||
Stock => stock(ctx, chart, data, area),
|
||||
_ => cartesian(ctx, chart, data, area, false),
|
||||
}
|
||||
}
|
||||
@@ -630,6 +641,160 @@ fn value_range(it: impl Iterator<Item = f64>) -> Option<(f64, f64)> {
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- trendlines
|
||||
|
||||
/// Samples along a regression trendline.
|
||||
const TREND_STEPS: usize = 200;
|
||||
|
||||
/// Whether series drawn as `k` show trendlines (Excel offers them on 2-D unstacked column,
|
||||
/// bar, line, area, scatter and bubble charts).
|
||||
pub fn supports_trendline(k: ChartKind) -> bool {
|
||||
use ChartKind::*;
|
||||
matches!(k, ColumnClustered | BarClustered | Line | LineMarkers | Area | Scatter | ScatterLines | Bubble)
|
||||
}
|
||||
|
||||
/// A forecast distance as drawn: finite, non-negative and bounded.
|
||||
fn forecast(v: f64) -> f64 {
|
||||
if v.is_finite() && v > 0.0 { v.min(1e9) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Longest forward forecast among `s`'s regression trendlines.
|
||||
fn max_forward(s: &SeriesData) -> f64 {
|
||||
s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.forward)).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// Longest backward forecast among `s`'s regression trendlines.
|
||||
fn max_backward(s: &SeriesData) -> f64 {
|
||||
s.trendlines.iter().filter(|t| !matches!(t.spec.kind, TrendlineKind::MovingAverage(_))).map(|t| forecast(t.spec.backward)).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// Liang–Barsky: the part of segment `a`–`b` inside the unit square, with whether the start and
|
||||
/// end were cut.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn clip_segment(a: (f64, f64), b: (f64, f64)) -> Option<((f64, f64), (f64, f64), bool, bool)> {
|
||||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||||
let (mut t0, mut t1) = (0.0f64, 1.0f64);
|
||||
for (p, q) in [(-dx, a.0), (dx, 1.0 - a.0), (-dy, a.1), (dy, 1.0 - a.1)] {
|
||||
if p == 0.0 {
|
||||
if q < 0.0 {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
let r = q / p;
|
||||
if p < 0.0 {
|
||||
if r > t1 {
|
||||
return None;
|
||||
}
|
||||
t0 = t0.max(r);
|
||||
} else {
|
||||
if r < t0 {
|
||||
return None;
|
||||
}
|
||||
t1 = t1.min(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(((a.0 + t0 * dx, a.1 + t0 * dy), (a.0 + t1 * dx, a.1 + t1 * dy), t0 > 0.0, t1 < 1.0))
|
||||
}
|
||||
|
||||
/// Clips a sampled polyline in plot fractions (`None` = gap) to the plot box (the unit
|
||||
/// square), returning the visible runs.
|
||||
fn clip_unit(pts: &[Option<(f64, f64)>]) -> Vec<Vec<(f64, f64)>> {
|
||||
const LIM: f64 = 1e9;
|
||||
let ok = |p: &(f64, f64)| p.0.is_finite() && p.1.is_finite();
|
||||
let cl = |p: (f64, f64)| (p.0.clamp(-LIM, LIM), p.1.clamp(-LIM, LIM));
|
||||
let mut runs: Vec<Vec<(f64, f64)>> = Vec::new();
|
||||
let mut run: Vec<(f64, f64)> = Vec::new();
|
||||
for w in pts.windows(2) {
|
||||
let seg = match w {
|
||||
[Some(a), Some(b)] if ok(a) && ok(b) => clip_segment(cl(*a), cl(*b)),
|
||||
_ => None,
|
||||
};
|
||||
match seg {
|
||||
Some((p, q, cut_start, cut_end)) => {
|
||||
if cut_start || run.is_empty() {
|
||||
if run.len() >= 2 {
|
||||
runs.push(std::mem::take(&mut run));
|
||||
}
|
||||
run.clear();
|
||||
run.push(p);
|
||||
}
|
||||
run.push(q);
|
||||
if cut_end {
|
||||
runs.push(std::mem::take(&mut run));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if run.len() >= 2 {
|
||||
runs.push(std::mem::take(&mut run));
|
||||
}
|
||||
run.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
if run.len() >= 2 {
|
||||
runs.push(run);
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// Draws `s`'s trendlines fitted to its plotted points `pts` (data x, y). `frac` maps data to
|
||||
/// fractions of the plot box (0..1 inside, along the x and y axes), `px` fractions to pixels.
|
||||
/// Equation and R² label lines are appended to `labels`. Degenerate fits draw nothing.
|
||||
fn draw_trendlines(
|
||||
ctx: &mut Ctx,
|
||||
s: &SeriesData,
|
||||
pts: &[(f64, f64)],
|
||||
frac: &dyn Fn(f64, f64) -> (f64, f64),
|
||||
px: &dyn Fn((f64, f64)) -> [f32; 2],
|
||||
labels: &mut Vec<String>,
|
||||
) {
|
||||
let Some((xlo, xhi)) = value_range(pts.iter().map(|p| p.0)) else { return };
|
||||
for t in s.trendlines.iter().take(MAX_TRENDLINES) {
|
||||
let spec = &t.spec;
|
||||
let samples: Vec<Option<(f64, f64)>> = match spec.kind {
|
||||
TrendlineKind::MovingAverage(p) => moving_average(pts, p).into_iter().map(|(x, y)| Some(frac(x, y))).collect(),
|
||||
_ => {
|
||||
let Some(fit) = fit_trendline(spec, pts) else { continue };
|
||||
let (lo, hi) = (xlo - forecast(spec.backward), xhi + forecast(spec.forward));
|
||||
if spec.display_equation {
|
||||
labels.push(fit.equation());
|
||||
}
|
||||
if spec.display_r_squared {
|
||||
labels.push(fit.r_squared());
|
||||
}
|
||||
(0..=TREND_STEPS)
|
||||
.map(|i| {
|
||||
let x = lo + (hi - lo) * i as f64 / TREND_STEPS as f64;
|
||||
fit.eval(x).map(|y| frac(x, y))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
let width = spec.width.filter(|w| w.is_finite()).unwrap_or(1.5).clamp(0.25, 12.0);
|
||||
let dash = spec.dash != Some(LineDash::Solid);
|
||||
for run in clip_unit(&samples) {
|
||||
let line = decimate(run.into_iter().map(px).collect(), MAX_LINE_PTS);
|
||||
if line.len() >= 2 {
|
||||
ctx.out.push(Prim::Line { pts: line, color: t.color, width, dash });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trendline equation / R² labels, stacked in the plot's top-right corner.
|
||||
fn draw_trend_labels(ctx: &mut Ctx, plot: Bx, labels: &[String]) {
|
||||
let lh = LABEL_SIZE * 1.3;
|
||||
for (i, t) in labels.iter().enumerate() {
|
||||
let y = plot.y + 4.0 + i as f32 * lh;
|
||||
if y + lh > plot.bottom() {
|
||||
break;
|
||||
}
|
||||
let t = ctx.fit(t, LABEL_SIZE, plot.w - 8.0);
|
||||
ctx.text(plot.right() - 4.0, y, &t, LABEL_SIZE, TEXT, HAlign::Right, VAlign::Top);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- cartesian (column/bar/line/area/combo)
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -763,14 +928,23 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta
|
||||
let Some((s1, f1)) = axes.first() else { return };
|
||||
let y1 = ValAxis { scale: *s1, fmt: f1 };
|
||||
let y2 = axes.get(1).map(|(s, f)| ValAxis { scale: *s, fmt: f });
|
||||
let labels: Vec<String> = (0..ncat).map(|j| cat_label(data, j)).collect();
|
||||
// A forward forecast on a category axis adds empty category slots after the data.
|
||||
let fwd = data
|
||||
.series
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| kinds.get(*i).is_some_and(|k| supports_trendline(*k)))
|
||||
.map(|(_, s)| max_forward(s))
|
||||
.fold(0.0, f64::max);
|
||||
let ncat_slots = ncat.saturating_add(fwd.ceil() as usize).min(MAX_CATS.max(ncat));
|
||||
let labels: Vec<String> = (0..ncat_slots).map(|j| if j < ncat { cat_label(data, j) } else { String::new() }).collect();
|
||||
let plot = frame(ctx, area, CatAxis::Labels(&labels), &y1, y2.as_ref(), horizontal, chart.gridlines);
|
||||
if !plot.ok() {
|
||||
return;
|
||||
}
|
||||
let scale_of = |i: usize| -> Scale { if sec.get(i).copied().unwrap_or(false) { y2.as_ref().map(|a| a.scale).unwrap_or(*s1) } else { *s1 } };
|
||||
let cat_len = if horizontal { plot.h } else { plot.w };
|
||||
let cw = cat_len / ncat as f32;
|
||||
let cw = cat_len / ncat_slots as f32;
|
||||
let center = |j: usize| if horizontal { plot.bottom() - (j as f32 + 0.5) * cw } else { plot.x + (j as f32 + 0.5) * cw };
|
||||
let vpos = |v: f64, sc: &Scale| if horizontal { plot.x + sc.frac(v) * plot.w } else { plot.bottom() - sc.frac(v) * plot.h };
|
||||
|
||||
@@ -797,6 +971,8 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta
|
||||
let nslots = slot_keys.len().max(1) as f32;
|
||||
let bw = cw / (nslots + 1.5);
|
||||
let labels_on = chart.data_labels && ncat <= MAX_LABELS;
|
||||
// Area labels wait until every area is filled, so a later (stacked) area can't paint over them.
|
||||
let mut area_labels = Vec::new();
|
||||
|
||||
// Areas first, then columns, then lines on top.
|
||||
for pass in 0..3 {
|
||||
@@ -825,6 +1001,13 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta
|
||||
let c = center(j);
|
||||
top.push([c, vpos(t, &sc)]);
|
||||
base.push([c, vpos(b, &sc)]);
|
||||
// Source values (not stack totals), just above the top edge like the line labels.
|
||||
if labels_on
|
||||
&& sp.is_some()
|
||||
&& let Some(v) = s.values.get(j).copied().flatten()
|
||||
{
|
||||
area_labels.push((c, vpos(t, &sc) - 5.0, fmt.format(v, None)));
|
||||
}
|
||||
}
|
||||
if top.len() == 1 {
|
||||
// A single point: give it some width.
|
||||
@@ -899,7 +1082,29 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta
|
||||
}
|
||||
}
|
||||
}
|
||||
for (x, y, t) in area_labels.drain(..) {
|
||||
ctx.text(x, y, &t, LABEL_SIZE, TEXT, HAlign::Center, VAlign::Bottom);
|
||||
}
|
||||
}
|
||||
// Trendlines on top: x is the category number 1..n.
|
||||
let mut trend_labels = Vec::new();
|
||||
for (i, s) in data.series.iter().enumerate() {
|
||||
if s.trendlines.is_empty() || !kinds.get(i).is_some_and(|k| supports_trendline(*k)) {
|
||||
continue;
|
||||
}
|
||||
let sc = scale_of(i);
|
||||
let pts: Vec<(f64, f64)> = s.values.iter().take(ncat).enumerate().filter_map(|(j, v)| v.map(|v| ((j + 1) as f64, v))).collect();
|
||||
let frac = |x: f64, y: f64| ((x - 0.5) / ncat_slots as f64, (y - sc.min) / (sc.max - sc.min));
|
||||
let px = |(fx, fy): (f64, f64)| {
|
||||
if horizontal {
|
||||
[plot.x + fy as f32 * plot.w, plot.bottom() - fx as f32 * plot.h]
|
||||
} else {
|
||||
[plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h]
|
||||
}
|
||||
};
|
||||
draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels);
|
||||
}
|
||||
draw_trend_labels(ctx, plot, &trend_labels);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- scatter & bubble
|
||||
@@ -922,7 +1127,14 @@ fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
.collect()
|
||||
};
|
||||
let all: Vec<Vec<Option<(f64, f64)>>> = data.series.iter().map(pts_of).collect();
|
||||
let Some((xlo, xhi)) = value_range(all.iter().flatten().flatten().map(|p| p.0)) else { return };
|
||||
let Some((mut xlo, mut xhi)) = value_range(all.iter().flatten().flatten().map(|p| p.0)) else { return };
|
||||
// Forecasts extend the x axis to the trendline's ends.
|
||||
for (s, pts) in data.series.iter().zip(&all) {
|
||||
if let Some((lo, hi)) = value_range(pts.iter().flatten().map(|p| p.0)).filter(|_| !s.trendlines.is_empty()) {
|
||||
xlo = xlo.min(lo - max_backward(s));
|
||||
xhi = xhi.max(hi + max_forward(s));
|
||||
}
|
||||
}
|
||||
let Some((ylo, yhi)) = value_range(all.iter().flatten().flatten().map(|p| p.1)) else { return };
|
||||
let xs = nice_scale(xlo, xhi, false);
|
||||
let ys = nice_scale(ylo, yhi, false);
|
||||
@@ -976,6 +1188,17 @@ fn scatter(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut trend_labels = Vec::new();
|
||||
for (s, pts) in data.series.iter().zip(&all) {
|
||||
if s.trendlines.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let pts: Vec<(f64, f64)> = pts.iter().flatten().copied().collect();
|
||||
let frac = |x: f64, y: f64| ((x - xs.min) / (xs.max - xs.min), (y - ys.min) / (ys.max - ys.min));
|
||||
let px = |(fx, fy): (f64, f64)| [plot.x + fx as f32 * plot.w, plot.bottom() - fy as f32 * plot.h];
|
||||
draw_trendlines(ctx, s, &pts, &frac, &px, &mut trend_labels);
|
||||
}
|
||||
draw_trend_labels(ctx, plot, &trend_labels);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- histogram
|
||||
@@ -991,10 +1214,12 @@ fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
bins = 1;
|
||||
}
|
||||
let width = if bins == 1 && span.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { 1.0 } else { span / bins as f64 };
|
||||
// Upper edge of each bin, exactly as shown in the labels below. Bins are right-inclusive (the first is closed on both sides), so a value
|
||||
// equal to an edge belongs to the bin that ends there.
|
||||
let edges: Vec<f64> = (0..bins).map(|b| if b + 1 == bins { hi.max(lo + b as f64 * width) } else { lo + (b + 1) as f64 * width }).collect();
|
||||
let mut counts = vec![0usize; bins];
|
||||
for v in &vals {
|
||||
let b = if width > 0.0 { ((v - lo) / width).floor() } else { 0.0 };
|
||||
let b = if b.is_finite() && b > 0.0 { (b as usize).min(bins - 1) } else { 0 };
|
||||
let b = edges.partition_point(|e| e < v).min(bins - 1);
|
||||
if let Some(c) = counts.get_mut(b) {
|
||||
*c += 1;
|
||||
}
|
||||
@@ -1003,7 +1228,7 @@ fn histogram(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let labels: Vec<String> = (0..bins)
|
||||
.map(|b| {
|
||||
let a = lo + b as f64 * width;
|
||||
let e = if b + 1 == bins { hi.max(a) } else { a + width };
|
||||
let e = edges.get(b).copied().unwrap_or(a);
|
||||
let open = if b == 0 { '[' } else { '(' };
|
||||
format!("{open}{}, {}]", f.format(a, Some(width / 10.0)), f.format(e, Some(width / 10.0)))
|
||||
})
|
||||
@@ -1091,7 +1316,7 @@ fn waterfall(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
|
||||
// ---------------------------------------------------------------- funnel
|
||||
|
||||
fn funnel(ctx: &mut Ctx, data: &ChartData, area: Bx) {
|
||||
fn funnel(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let Some(s) = data.series.first() else { return };
|
||||
let n = data.categories.len().max(s.values.len()).min(MAX_CATS);
|
||||
if n == 0 {
|
||||
@@ -1121,9 +1346,11 @@ fn funnel(ctx: &mut Ctx, data: &ChartData, area: Bx) {
|
||||
}
|
||||
if show {
|
||||
let yc = y + bh / 2.0;
|
||||
let t = f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None);
|
||||
let color = if ctx.tw(&t, LABEL_SIZE) + 4.0 <= bw { on(s.color) } else { TEXT };
|
||||
ctx.text(plot.cx(), yc, &t, LABEL_SIZE, color, HAlign::Center, VAlign::Middle);
|
||||
if chart.data_labels {
|
||||
let t = f.format(s.values.get(j).copied().flatten().unwrap_or(0.0), None);
|
||||
let color = if ctx.tw(&t, LABEL_SIZE) + 4.0 <= bw { on(s.color) } else { TEXT };
|
||||
ctx.text(plot.cx(), yc, &t, LABEL_SIZE, color, HAlign::Center, VAlign::Middle);
|
||||
}
|
||||
let l = ctx.fit(labels.get(j).map(String::as_str).unwrap_or(""), LABEL_SIZE, lw - 8.0);
|
||||
ctx.text(plot.x - 6.0, yc, &l, LABEL_SIZE, TEXT, HAlign::Right, VAlign::Middle);
|
||||
}
|
||||
@@ -1347,12 +1574,12 @@ fn quantile(sorted: &[f64], q: f64) -> f64 {
|
||||
a + (b - a) * frac
|
||||
}
|
||||
|
||||
fn box_whisker(ctx: &mut Ctx, data: &ChartData, area: Bx) {
|
||||
fn box_whisker(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let labels: Vec<String> = data.series.iter().map(|s| s.name.clone()).collect();
|
||||
let Some((lo, hi)) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())) else { return };
|
||||
let ys = nice_scale(lo, hi, false);
|
||||
let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General"));
|
||||
let plot = frame(ctx, area, CatAxis::Labels(&labels), &ValAxis { scale: ys, fmt: &f }, None, false, true);
|
||||
let plot = frame(ctx, area, CatAxis::Labels(&labels), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines);
|
||||
if !plot.ok() {
|
||||
return;
|
||||
}
|
||||
@@ -1391,7 +1618,7 @@ fn box_whisker(ctx: &mut Ctx, data: &ChartData, area: Bx) {
|
||||
|
||||
// ---------------------------------------------------------------- stock
|
||||
|
||||
fn stock(ctx: &mut Ctx, data: &ChartData, area: Bx) {
|
||||
fn stock(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx) {
|
||||
let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS);
|
||||
if ncat == 0 {
|
||||
return;
|
||||
@@ -1400,7 +1627,7 @@ fn stock(ctx: &mut Ctx, data: &ChartData, area: Bx) {
|
||||
let Some((lo, hi)) = value_range(data.series.iter().flat_map(|s| s.values.iter().flatten().copied())) else { return };
|
||||
let ys = nice_scale(lo, hi, false);
|
||||
let f = Fmt::new(data.series.first().map(|s| s.number_format.as_str()).unwrap_or("General"));
|
||||
let plot = frame(ctx, area, CatAxis::Labels(&labels), &ValAxis { scale: ys, fmt: &f }, None, false, true);
|
||||
let plot = frame(ctx, area, CatAxis::Labels(&labels), &ValAxis { scale: ys, fmt: &f }, None, false, chart.gridlines);
|
||||
if !plot.ok() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5,15 +5,19 @@ use gridcraft_core::{CellRef, RangeRef, Value, number_to_text};
|
||||
use gridcraft_model::{Chart, ChartKind, Theme, Workbook, style::apply_tint};
|
||||
use gridcraft_numfmt::{NumberFormat, format_value};
|
||||
|
||||
use crate::{ChartData, Rgba, SeriesData};
|
||||
use crate::{ChartData, Rgba, SeriesData, TrendlineData};
|
||||
|
||||
/// Cap on points per series (keeps whole-column references from exploding).
|
||||
pub(crate) const MAX_POINTS: usize = 100_000;
|
||||
/// Cap on series per chart.
|
||||
pub(crate) const MAX_SERIES: usize = 255;
|
||||
/// Cap on trendlines drawn per series.
|
||||
pub(crate) const MAX_TRENDLINES: usize = 16;
|
||||
|
||||
/// Tints used for series beyond the six theme accents: lighter, darker, lighter still…
|
||||
const CYCLE_TINTS: [f64; 6] = [0.0, 0.4, -0.25, 0.6, -0.5, 0.2];
|
||||
/// `series_color` repeats after this many colours (six accents × the tints).
|
||||
pub(crate) const PALETTE_CYCLE: usize = 6 * CYCLE_TINTS.len();
|
||||
|
||||
/// Colour of the `i`-th series: theme accents 1–6, then tinted variations of them.
|
||||
pub fn series_color(theme: &Theme, i: usize) -> Rgba {
|
||||
@@ -46,12 +50,54 @@ fn parse_ref(wb: &Workbook, sheet: usize, formula: &str) -> Option<(usize, Range
|
||||
Some((sh, r))
|
||||
}
|
||||
|
||||
/// Evaluates a series formula to a flat list of values (row-major), capped.
|
||||
/// The parts of a union reference `(Sheet1!$A$1:$A$3,Sheet1!$A$5)`, or `None`.
|
||||
fn union_parts(f: &str) -> Option<Vec<&str>> {
|
||||
let inner = f.strip_prefix('(')?.strip_suffix(')')?;
|
||||
let mut parts = Vec::new();
|
||||
let (mut depth, mut quoted, mut start) = (0i32, false, 0usize);
|
||||
for (i, c) in inner.char_indices() {
|
||||
match c {
|
||||
'\'' => quoted = !quoted,
|
||||
'(' if !quoted => depth += 1,
|
||||
')' if !quoted => depth -= 1,
|
||||
',' if !quoted && depth == 0 => {
|
||||
parts.push(inner.get(start..i)?);
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if depth < 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
parts.push(inner.get(start..)?);
|
||||
(parts.len() > 1).then_some(parts)
|
||||
}
|
||||
|
||||
/// Evaluates a series formula to a flat list of values (row-major), capped. A union of
|
||||
/// references (`(A1:A3,A5)`, as PivotCharts use) is read part by part.
|
||||
fn eval_list(wb: &Workbook, sheet: usize, formula: &str) -> Vec<Value> {
|
||||
eval_list_in(wb, sheet, formula, 0)
|
||||
}
|
||||
|
||||
fn eval_list_in(wb: &Workbook, sheet: usize, formula: &str, depth: u32) -> Vec<Value> {
|
||||
let f = formula.trim();
|
||||
if f.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
if depth < 4
|
||||
&& let Some(parts) = union_parts(f)
|
||||
{
|
||||
let mut out = Vec::new();
|
||||
for p in parts {
|
||||
if out.len() >= MAX_POINTS {
|
||||
break;
|
||||
}
|
||||
let rest = MAX_POINTS - out.len();
|
||||
out.extend(eval_list_in(wb, sheet, p, depth + 1).into_iter().take(rest));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
match evaluate(wb, sheet, CellRef::default(), f) {
|
||||
Value::Array(a) => a.iter().take(MAX_POINTS).cloned().collect(),
|
||||
v => vec![v],
|
||||
@@ -101,7 +147,7 @@ fn category_texts(wb: &Workbook, sheet: usize, formula: &str) -> Vec<String> {
|
||||
if let Some(c) = at {
|
||||
let code = &wb.styles.get(s.style_id(c)).num_fmt.0;
|
||||
if !code.eq_ignore_ascii_case("general") {
|
||||
return format_value(v, &NumberFormat::parse(code), wb.date_system).text;
|
||||
return format_value(v, &NumberFormat::parse_cached(code), wb.date_system).text;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,6 +185,11 @@ fn effective_kind(chart_kind: ChartKind, series_kind: Option<ChartKind>, i: usiz
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind series `i` of `chart` is drawn as: its own kind in a combo chart, else the chart's.
|
||||
pub fn series_plot_kind(chart: &Chart, i: usize) -> ChartKind {
|
||||
if chart.kind == ChartKind::Combo { effective_kind(chart.kind, chart.series.get(i).and_then(|s| s.kind), i) } else { chart.kind }
|
||||
}
|
||||
|
||||
/// Evaluates a chart's series formulas: names, values, categories (default "1", "2", …), X
|
||||
/// values (scatter/bubble), bubble sizes, number formats and colours (explicit, else the
|
||||
/// default palette derived from the workbook theme accents).
|
||||
@@ -166,6 +217,15 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
}
|
||||
}
|
||||
let sizes = s.bubble_sizes.as_deref().map(|f| nums(wb, sheet, f));
|
||||
let trendlines = s
|
||||
.trendlines
|
||||
.iter()
|
||||
.take(MAX_TRENDLINES)
|
||||
.map(|t| TrendlineData {
|
||||
spec: t.clone(),
|
||||
color: t.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or(color),
|
||||
})
|
||||
.collect();
|
||||
series.push(SeriesData {
|
||||
name,
|
||||
values,
|
||||
@@ -175,10 +235,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
kind,
|
||||
secondary: s.secondary,
|
||||
smooth: s.smooth,
|
||||
trendlines,
|
||||
number_format: ref_format(wb, sheet, &s.values),
|
||||
});
|
||||
}
|
||||
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
|
||||
let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect());
|
||||
ChartData { categories, series }
|
||||
let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE));
|
||||
ChartData { categories, series, palette }
|
||||
}
|
||||
|
||||
+408
-9
@@ -48,6 +48,7 @@ fn chart(kind: ChartKind) -> Chart {
|
||||
y_title: Some("Revenue".into()),
|
||||
source: None,
|
||||
by_rows: false,
|
||||
pivot: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +62,7 @@ fn series(name: &str, values: &[f64], color: Rgba, kind: ChartKind) -> SeriesDat
|
||||
kind,
|
||||
secondary: false,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: "$#,##0".into(),
|
||||
}
|
||||
}
|
||||
@@ -72,6 +74,7 @@ fn sample(kind: ChartKind) -> ChartData {
|
||||
let mut b = series("East", &[38000.0, 30000.0, 45000.0, 61870.0, 52000.0, 41000.0], [200, 80, 40, 255], k2);
|
||||
b.secondary = kind == ChartKind::Combo;
|
||||
ChartData {
|
||||
palette: vec![],
|
||||
categories: cats.iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![
|
||||
series("North", &[12000.0, -4000.0, 23000.0, 31000.0, 18000.0, 27000.0], [20, 96, 130, 255], k1),
|
||||
@@ -225,6 +228,7 @@ fn resolve_from_workbook() {
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -235,6 +239,7 @@ fn resolve_from_workbook() {
|
||||
secondary: true,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
},
|
||||
Series {
|
||||
name: Some("Literal".into()),
|
||||
@@ -245,6 +250,7 @@ fn resolve_from_workbook() {
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -282,6 +288,7 @@ fn resolve_from_workbook() {
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -292,6 +299,7 @@ fn resolve_from_workbook() {
|
||||
secondary: true,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -307,6 +315,7 @@ fn resolve_from_workbook() {
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
|
||||
@@ -323,6 +332,7 @@ fn resolve_from_workbook() {
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
}];
|
||||
let d = resolve(&wb, 7, &c);
|
||||
assert_eq!(d.series.len(), 1);
|
||||
@@ -353,7 +363,7 @@ fn scatter_with_text_x_values_numbers_the_points() {
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series[0].x, None, "{kind:?}");
|
||||
let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure);
|
||||
let empty = render(&c, &ChartData { categories: vec![], series: vec![] }, 400.0, 300.0, &ApproxMeasure);
|
||||
let empty = render(&c, &ChartData { palette: vec![], categories: vec![], series: vec![] }, 400.0, 300.0, &ApproxMeasure);
|
||||
assert!(prims.len() > empty.len() + 2, "{kind:?} draws its points");
|
||||
// Numeric X values are kept.
|
||||
c.series[0].categories = Some("Sheet1!$C$1:$C$3".into());
|
||||
@@ -411,6 +421,16 @@ fn rasterize_bar_center_has_bar_color() {
|
||||
assert!(rasterize(&[], 100_000, 100_000, [0; 4]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_does_not_panic_on_negative_rect_extents() {
|
||||
let red = [255, 0, 0, 255];
|
||||
for (w, h) in [(-10.0, 10.0), (10.0, -10.0), (-10.0, -10.0), (f32::NAN, f32::NAN)] {
|
||||
let rect = Prim::Rect { x: 5.0, y: 5.0, w, h, fill: Some(red), stroke: Some((red, 2.0)), radius: 0.0 };
|
||||
let img = rasterize(&[rect], 20, 20, [0, 0, 0, 0]);
|
||||
assert_eq!(img.len(), 20 * 20 * 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pie_starts_at_twelve_clockwise() {
|
||||
let c = chart(ChartKind::Pie);
|
||||
@@ -436,7 +456,8 @@ fn pie_starts_at_twelve_clockwise() {
|
||||
#[test]
|
||||
fn negative_values_put_axis_below_zero() {
|
||||
let c = chart(ChartKind::ColumnClustered);
|
||||
let d = ChartData { categories: vec![], series: vec![series("N", &[-5.0, 3.0, -2.0], [1, 2, 3, 255], ChartKind::ColumnClustered)] };
|
||||
let d =
|
||||
ChartData { palette: vec![], categories: vec![], series: vec![series("N", &[-5.0, 3.0, -2.0], [1, 2, 3, 255], ChartKind::ColumnClustered)] };
|
||||
let prims = render(&c, &d, 400.0, 300.0, &ApproxMeasure);
|
||||
let t = texts(&prims);
|
||||
assert!(t.iter().any(|s| s.starts_with('-') || s.starts_with("($") || s.starts_with("-$")), "{t:?}");
|
||||
@@ -447,8 +468,13 @@ fn negative_values_put_axis_below_zero() {
|
||||
fn edge_cases_never_panic() {
|
||||
let m = ApproxMeasure;
|
||||
let empty = ChartData::default();
|
||||
let zeros = ChartData { categories: vec!["a".into(), "b".into()], series: vec![series("z", &[0.0, 0.0], [0, 0, 0, 255], ChartKind::Line)] };
|
||||
let zeros = ChartData {
|
||||
palette: vec![],
|
||||
categories: vec!["a".into(), "b".into()],
|
||||
series: vec![series("z", &[0.0, 0.0], [0, 0, 0, 255], ChartKind::Line)],
|
||||
};
|
||||
let weird = ChartData {
|
||||
palette: vec![],
|
||||
categories: vec![String::new(); 3],
|
||||
series: vec![SeriesData {
|
||||
name: "w".repeat(500),
|
||||
@@ -479,7 +505,7 @@ fn thousands_of_points_are_decimated() {
|
||||
let vals: Vec<f64> = (0..n).map(|i| ((i as f64) * 0.01).sin() * 100.0 + i as f64 * 0.001).collect();
|
||||
let mut c = chart(ChartKind::Line);
|
||||
c.data_labels = true;
|
||||
let d = ChartData { categories: vec![], series: vec![series("big", &vals, [9, 9, 9, 255], ChartKind::Line)] };
|
||||
let d = ChartData { palette: vec![], categories: vec![], series: vec![series("big", &vals, [9, 9, 9, 255], ChartKind::Line)] };
|
||||
let prims = render(&c, &d, 800.0, 400.0, &ApproxMeasure);
|
||||
let max_line = prims
|
||||
.iter()
|
||||
@@ -504,7 +530,7 @@ fn smooth_line_adds_interpolated_points_and_keeps_endpoints() {
|
||||
let line_pts = |smooth: bool, m: &ApproxMeasure| -> usize {
|
||||
let mut s = series("L", &[1.0, 5.0, 2.0, 6.0], [10, 20, 30, 255], ChartKind::Line);
|
||||
s.smooth = smooth;
|
||||
let d = ChartData { categories: cats.clone(), series: vec![s] };
|
||||
let d = ChartData { palette: vec![], categories: cats.clone(), series: vec![s] };
|
||||
render(&chart(ChartKind::Line), &d, 600.0, 400.0, m)
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
@@ -521,7 +547,7 @@ fn smooth_line_adds_interpolated_points_and_keeps_endpoints() {
|
||||
// Rendering either way must stay finite and inside the canvas.
|
||||
let mut s = series("L", &[1.0, 5.0, 2.0, 6.0], [10, 20, 30, 255], ChartKind::Line);
|
||||
s.smooth = true;
|
||||
let d = ChartData { categories: cats, series: vec![s] };
|
||||
let d = ChartData { palette: vec![], categories: cats, series: vec![s] };
|
||||
assert_sane(&render(&chart(ChartKind::Line), &d, 600.0, 400.0, &m), 600.0, 400.0);
|
||||
}
|
||||
|
||||
@@ -531,7 +557,7 @@ fn smooth_line_splits_at_gaps() {
|
||||
let mut s = series("L", &[1.0, 5.0, 2.0, 6.0], [10, 20, 30, 255], ChartKind::Line);
|
||||
s.smooth = true;
|
||||
s.values[1] = None; // gap between two data points
|
||||
let d = ChartData { categories: vec!["a".into(), "b".into(), "c".into(), "d".into()], series: vec![s] };
|
||||
let d = ChartData { palette: vec![], categories: vec!["a".into(), "b".into(), "c".into(), "d".into()], series: vec![s] };
|
||||
let prims = render(&chart(ChartKind::Line), &d, 600.0, 400.0, &m);
|
||||
// Two separate runs (before/after the gap) → at least two line primitives.
|
||||
let lines = prims.iter().filter(|p| matches!(p, Prim::Line { .. })).count();
|
||||
@@ -582,11 +608,33 @@ fn fuzz_random_data_and_sizes() {
|
||||
kind: ALL_KINDS[(r.next() % ALL_KINDS.len() as u64) as usize],
|
||||
secondary: r.next().is_multiple_of(3),
|
||||
smooth: r.next().is_multiple_of(4),
|
||||
trendlines: (0..r.next() % 3)
|
||||
.map(|_| TrendlineData {
|
||||
spec: Trendline {
|
||||
kind: [
|
||||
TrendlineKind::Linear,
|
||||
TrendlineKind::Exponential,
|
||||
TrendlineKind::Logarithmic,
|
||||
TrendlineKind::Polynomial((r.next() % 8) as u8),
|
||||
TrendlineKind::Power,
|
||||
TrendlineKind::MovingAverage((r.next() % 6) as u32),
|
||||
][(r.next() % 6) as usize],
|
||||
forward: [0.0, 1.5, -2.0, f64::NAN, 1e300][(r.next() % 5) as usize],
|
||||
backward: [0.0, 0.5, f64::INFINITY][(r.next() % 3) as usize],
|
||||
intercept: [None, Some(0.0), Some(-5.0), Some(f64::NAN)][(r.next() % 4) as usize],
|
||||
display_equation: r.next().is_multiple_of(2),
|
||||
display_r_squared: r.next().is_multiple_of(2),
|
||||
width: [None, Some(0.0), Some(f32::NAN), Some(3.0)][(r.next() % 4) as usize],
|
||||
..Trendline::default()
|
||||
},
|
||||
color: [0, 0, 0, 255],
|
||||
})
|
||||
.collect(),
|
||||
number_format: ["General", "$#,##0", "0.00%", "yyyy-mm-dd", "#,##0.0;[Red]-#,##0.0", "@"][(r.next() % 6) as usize].into(),
|
||||
})
|
||||
.collect();
|
||||
let ncat = (r.next() % 50) as usize;
|
||||
let d = ChartData { categories: (0..ncat).map(|i| "c".repeat(i % 7) + &i.to_string()).collect(), series };
|
||||
let d = ChartData { palette: vec![], categories: (0..ncat).map(|i| "c".repeat(i % 7) + &i.to_string()).collect(), series };
|
||||
let mut c = chart(kind);
|
||||
c.legend = [LegendPos::None, LegendPos::Bottom, LegendPos::Top, LegendPos::Left, LegendPos::Right][(r.next() % 5) as usize];
|
||||
c.data_labels = r.next().is_multiple_of(2);
|
||||
@@ -630,9 +678,197 @@ fn sparklines() {
|
||||
assert!(render_sparkline(SparklineKind::Line, &[], [0; 4], false, 10.0, 10.0).is_empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- trendlines
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() <= 1e-9 * (1.0 + b.abs())
|
||||
}
|
||||
|
||||
fn fit(kind: TrendlineKind, pts: &[(f64, f64)]) -> crate::trend::TrendFit {
|
||||
crate::trend::fit_trendline(&Trendline { kind, ..Trendline::default() }, pts).expect("fits")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_trendline_matches_least_squares() {
|
||||
// Slope 0.6, intercept 2.2, R² = 1 - 2.4 / 6.
|
||||
let f = fit(TrendlineKind::Linear, &[(1.0, 2.0), (2.0, 4.0), (3.0, 5.0), (4.0, 4.0), (5.0, 5.0)]);
|
||||
assert!(close(f.coef[0], 2.2) && close(f.coef[1], 0.6), "{:?}", f.coef);
|
||||
assert!(close(f.r2.unwrap(), 0.6));
|
||||
assert_eq!(f.equation(), "y = 0.6x + 2.2");
|
||||
assert_eq!(f.r_squared(), "R² = 0.6");
|
||||
assert!(close(f.eval(10.0).unwrap(), 8.2));
|
||||
let down = fit(TrendlineKind::Linear, &[(0.0, 1.0), (1.0, -1.0), (2.0, -3.0)]);
|
||||
assert_eq!(down.equation(), "y = -2x + 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_intercept_fits_through_it() {
|
||||
// Through the origin: slope Σxy / Σx² = 30 / 14; R² against the uncentred total.
|
||||
let pts = [(1.0, 2.0), (2.0, 5.0), (3.0, 6.0)];
|
||||
let f = crate::trend::fit_trendline(&Trendline { intercept: Some(0.0), ..Trendline::default() }, &pts).unwrap();
|
||||
assert!(close(f.coef[0], 0.0) && close(f.coef[1], 15.0 / 7.0), "{:?}", f.coef);
|
||||
let ss_res: f64 = pts.iter().map(|(x, y)| (y - 15.0 / 7.0 * x).powi(2)).sum();
|
||||
assert!(close(f.r2.unwrap(), 1.0 - ss_res / 65.0));
|
||||
let q = crate::trend::fit_trendline(
|
||||
&Trendline { kind: TrendlineKind::Polynomial(2), intercept: Some(2.0), ..Trendline::default() },
|
||||
&[(1.0, 0.0), (2.0, 0.0), (3.0, 2.0), (4.0, 6.0)],
|
||||
)
|
||||
.unwrap();
|
||||
assert!(close(q.coef[0], 2.0) && close(q.coef[1], -3.0) && close(q.coef[2], 1.0), "{:?}", q.coef);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transformed_trendlines_recover_their_curves() {
|
||||
let xs: [f64; 6] = [0.5, 1.0, 2.0, 3.0, 4.5, 6.0];
|
||||
let e = fit(TrendlineKind::Exponential, &xs.map(|x| (x, 3.0 * (0.5 * x).exp())));
|
||||
assert!(close(e.coef[0].exp(), 3.0) && close(e.coef[1], 0.5));
|
||||
assert_eq!(e.equation(), "y = 3e^(0.5x)");
|
||||
let l = fit(TrendlineKind::Logarithmic, &xs.map(|x| (x, 2.0 * x.ln() + 1.0)));
|
||||
assert!(close(l.coef[1], 2.0) && close(l.coef[0], 1.0));
|
||||
assert_eq!(l.equation(), "y = 2ln(x) + 1");
|
||||
let p = fit(TrendlineKind::Power, &xs.map(|x| (x, 4.0 * x.powf(1.5))));
|
||||
assert!(close(p.coef[0].exp(), 4.0) && close(p.coef[1], 1.5));
|
||||
assert_eq!(p.equation(), "y = 4x^1.5");
|
||||
assert!(close(p.r2.unwrap(), 1.0));
|
||||
assert_eq!(p.eval(-1.0), None, "power is undefined left of zero");
|
||||
// Points the transform can't take are skipped, as Excel documents.
|
||||
let skip = fit(TrendlineKind::Exponential, &[(1.0, 2.0f64.exp()), (2.0, 0.0), (3.0, -4.0), (4.0, 8.0f64.exp())]);
|
||||
assert!(close(skip.coef[1], 2.0) && close(skip.coef[0], 0.0), "{:?}", skip.coef);
|
||||
assert!(
|
||||
crate::trend::fit_trendline(&Trendline { kind: TrendlineKind::Power, ..Trendline::default() }, &[(-1.0, 1.0), (0.0, 2.0), (3.0, 3.0)])
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polynomial_trendlines_are_stable() {
|
||||
let q = fit(TrendlineKind::Polynomial(2), &[0.0, 1.0, 2.0, 3.0, 4.0].map(|x| (x, x * x - 3.0 * x + 2.0)));
|
||||
assert!(close(q.coef[0], 2.0) && close(q.coef[1], -3.0) && close(q.coef[2], 1.0), "{:?}", q.coef);
|
||||
assert_eq!(q.equation(), "y = x² - 3x + 2");
|
||||
// Year-valued x would make the raw normal equations hopelessly ill-conditioned.
|
||||
let curve = |x: f64| {
|
||||
let t = x - 2000.0;
|
||||
0.001 * t.powi(6) - 0.02 * t.powi(5) + 0.1 * t.powi(3) - t + 7.0
|
||||
};
|
||||
let years: Vec<(f64, f64)> = (2001..=2012).map(|x| (f64::from(x), curve(f64::from(x)))).collect();
|
||||
let six = fit(TrendlineKind::Polynomial(6), &years);
|
||||
for x in [2001.0, 2006.5, 2012.0, 2014.0] {
|
||||
let (got, want) = (six.eval(x).unwrap(), curve(x));
|
||||
assert!((got - want).abs() <= 1e-6 * (1.0 + want.abs()), "{x}: {got} vs {want}");
|
||||
}
|
||||
assert!(six.r2.unwrap() > 0.999_999);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_trendlines_fit_nothing() {
|
||||
let lin = |pts: &[(f64, f64)]| crate::trend::fit_trendline(&Trendline::default(), pts);
|
||||
assert!(lin(&[]).is_none());
|
||||
assert!(lin(&[(1.0, 1.0)]).is_none());
|
||||
assert!(lin(&[(2.0, 1.0), (2.0, 5.0), (2.0, 3.0)]).is_none(), "all x equal is singular");
|
||||
assert!(lin(&[(f64::NAN, 1.0), (1.0, f64::INFINITY), (2.0, 3.0)]).is_none());
|
||||
assert!(
|
||||
crate::trend::fit_trendline(&Trendline { kind: TrendlineKind::Polynomial(3), ..Trendline::default() }, &[(1.0, 1.0), (2.0, 4.0), (3.0, 9.0)])
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
crate::trend::fit_trendline(&Trendline { kind: TrendlineKind::MovingAverage(2), ..Trendline::default() }, &[(1.0, 1.0), (2.0, 2.0)])
|
||||
.is_none()
|
||||
);
|
||||
let flat = lin(&[(1.0, 4.0), (2.0, 4.0), (3.0, 4.0)]).unwrap();
|
||||
assert_eq!((flat.equation(), flat.r2), ("y = 4".to_string(), None));
|
||||
assert!(lin(&[(0.0, 1e300), (1.0, -1e300), (2.0, 1e300)]).is_none_or(|f| f.coef.iter().all(|c| c.is_finite())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_average_and_labels() {
|
||||
let pts = [(1.0, 1.0), (2.0, 2.0), (3.0, 6.0), (4.0, f64::NAN), (5.0, 4.0)];
|
||||
assert_eq!(crate::trend::moving_average(&pts, 2), vec![(2.0, 1.5), (3.0, 4.0), (5.0, 5.0)]);
|
||||
assert_eq!(crate::trend::moving_average(&pts, 3), vec![(3.0, 3.0), (5.0, 4.0)]);
|
||||
assert!(crate::trend::moving_average(&pts, 9).is_empty());
|
||||
assert_eq!(crate::trend::num_text(0.000012345), "1.2345E-05");
|
||||
assert_eq!(crate::trend::num_text(-0.00001), "-1E-05");
|
||||
assert_eq!(crate::trend::num_text(1234.56789), "1234.5679");
|
||||
assert_eq!(crate::trend::auto_name(TrendlineKind::MovingAverage(3), "Sales"), "3 per. Mov. Avg. (Sales)");
|
||||
assert_eq!(crate::trend::auto_name(TrendlineKind::Exponential, "Sales"), "Expon. (Sales)");
|
||||
}
|
||||
|
||||
fn lines_of(prims: &[Prim], color: Rgba) -> Vec<&Vec<[f32; 2]>> {
|
||||
prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Line { pts, color: c, .. } if *c == color => Some(pts),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_chart_draws_trendline_forecast_and_labels() {
|
||||
let m = ApproxMeasure;
|
||||
let tc: Rgba = [1, 2, 3, 255];
|
||||
let mut s = series("Sales", &[9.0, 7.0, 5.0, 3.0], [10, 20, 30, 255], ChartKind::Line);
|
||||
s.trendlines =
|
||||
vec![TrendlineData { spec: Trendline { forward: 1.0, display_equation: true, display_r_squared: true, ..Trendline::default() }, color: tc }];
|
||||
let d = ChartData { palette: vec![], categories: ["a", "b", "c", "d"].map(String::from).to_vec(), series: vec![s.clone()] };
|
||||
let mut c = chart(ChartKind::Line);
|
||||
c.legend = LegendPos::None; // keeps legend swatches out of the line counts
|
||||
let prims = render(&c, &d, 600.0, 400.0, &m);
|
||||
assert_sane(&prims, 600.0, 400.0);
|
||||
let data = lines_of(&prims, [10, 20, 30, 255]);
|
||||
let trend = lines_of(&prims, tc);
|
||||
assert_eq!((data.len(), trend.len()), (1, 1));
|
||||
let (d0, dn) = (data[0][0], data[0][3]);
|
||||
let (t0, tn) = (trend[0][0], *trend[0].last().unwrap());
|
||||
// Exact data: the trendline starts on the first point and runs through the last,
|
||||
// then on one more category (the forecast slot).
|
||||
assert!((t0[0] - d0[0]).abs() < 0.01 && (t0[1] - d0[1]).abs() < 0.01, "{t0:?} vs {d0:?}");
|
||||
let step = (dn[0] - d0[0]) / 3.0;
|
||||
assert!((tn[0] - (dn[0] + step)).abs() < 0.01, "forecast end {tn:?}, last point {dn:?}");
|
||||
assert!(tn[1] > dn[1], "keeps falling past the data");
|
||||
let t = texts(&prims);
|
||||
assert!(t.contains(&"y = -2x + 11") && t.contains(&"R² = 1"), "{t:?}");
|
||||
assert!(legend_entries(&chart(ChartKind::Line), &d).iter().any(|(n, col, sw)| n == "Linear (Sales)" && *col == tc && *sw == Swatch::Line));
|
||||
// Not on chart kinds Excel doesn't offer trendlines on.
|
||||
let pie = render(&chart(ChartKind::Pie), &d, 600.0, 400.0, &m);
|
||||
assert!(lines_of(&pie, tc).is_empty());
|
||||
// One point: nothing to fit, nothing drawn.
|
||||
s.values.truncate(1);
|
||||
let one = ChartData { palette: vec![], categories: vec!["a".into()], series: vec![s] };
|
||||
assert!(lines_of(&render(&c, &one, 600.0, 400.0, &m), tc).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_trendlines_use_x_values_and_stay_in_the_plot() {
|
||||
let m = ApproxMeasure;
|
||||
let xs = [1.0, 2.0, 4.0, 8.0];
|
||||
let mut s = series("P", &xs.map(|x| 4.0 * x * x), [10, 20, 30, 255], ChartKind::Scatter);
|
||||
s.x = Some(xs.iter().map(|x| Some(*x)).collect());
|
||||
let colors: [Rgba; 3] = [[1, 0, 0, 255], [2, 0, 0, 255], [3, 0, 0, 255]];
|
||||
s.trendlines = vec![
|
||||
TrendlineData {
|
||||
spec: Trendline { kind: TrendlineKind::Power, backward: 0.5, display_equation: true, ..Trendline::default() },
|
||||
color: colors[0],
|
||||
},
|
||||
// A steep exponential leaves the plot box and is clipped to it.
|
||||
TrendlineData { spec: Trendline { kind: TrendlineKind::Exponential, forward: 30.0, ..Trendline::default() }, color: colors[1] },
|
||||
TrendlineData { spec: Trendline { kind: TrendlineKind::MovingAverage(2), ..Trendline::default() }, color: colors[2] },
|
||||
];
|
||||
let d = ChartData { palette: vec![], categories: vec![], series: vec![s] };
|
||||
let mut c = chart(ChartKind::Scatter);
|
||||
c.legend = LegendPos::None;
|
||||
let prims = render(&c, &d, 600.0, 400.0, &m);
|
||||
assert_sane(&prims, 600.0, 400.0);
|
||||
for c in colors {
|
||||
assert!(!lines_of(&prims, c).is_empty(), "{c:?} not drawn");
|
||||
}
|
||||
assert_eq!(lines_of(&prims, colors[2])[0].len(), 3, "moving average: one point per full window");
|
||||
assert!(texts(&prims).contains(&"y = 4x^2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn treemap_and_histogram_shapes() {
|
||||
let d = ChartData {
|
||||
palette: vec![],
|
||||
categories: vec!["a".into(), "b".into(), "c".into(), "d".into()],
|
||||
series: vec![series("t", &[6.0, 6.0, 4.0, 3.0], [10, 20, 30, 255], ChartKind::Treemap)],
|
||||
};
|
||||
@@ -653,8 +889,171 @@ fn treemap_and_histogram_shapes() {
|
||||
assert!((rects[0] / rects[3] - 2.0).abs() < 0.05, "{rects:?}");
|
||||
|
||||
let vals: Vec<f64> = (0..100).map(|i| i as f64).collect();
|
||||
let d = ChartData { categories: vec![], series: vec![series("h", &vals, [10, 20, 30, 255], ChartKind::Histogram)] };
|
||||
let d = ChartData { palette: vec![], categories: vec![], series: vec![series("h", &vals, [10, 20, 30, 255], ChartKind::Histogram)] };
|
||||
let prims = render(&chart(ChartKind::Histogram), &d, 600.0, 400.0, &ApproxMeasure);
|
||||
let bins = prims.iter().filter(|p| matches!(p, Prim::Rect { fill: Some([10, 20, 30, 255]), .. })).count();
|
||||
assert_eq!(bins, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_boundary_values_match_interval_labels() {
|
||||
let heights = |vals: &[f64]| -> Vec<f32> {
|
||||
let d = ChartData { palette: vec![], categories: vec![], series: vec![series("h", vals, [10, 20, 30, 255], ChartKind::Histogram)] };
|
||||
let prims = render(&chart(ChartKind::Histogram), &d, 600.0, 400.0, &ApproxMeasure);
|
||||
prims.iter().filter_map(|p| if let Prim::Rect { h, fill: Some([10, 20, 30, 255]), .. } = p { Some(*h) } else { None }).collect()
|
||||
};
|
||||
// Labels are "[0, 7.5]" and "(7.5, 15.0]": 7.5 belongs to the first bar, so the counts are 2 and 1.
|
||||
let h = heights(&[0.0, 7.5, 15.0]);
|
||||
assert_eq!(h.len(), 2);
|
||||
assert!((h[0] / h[1] - 2.0).abs() < 0.01, "{h:?}");
|
||||
let h = heights(&[-15.0, -7.5, 0.0]);
|
||||
assert!((h[0] / h[1] - 2.0).abs() < 0.01, "{h:?}");
|
||||
// A value off the boundary still goes right: [0, 7.5] holds 1, (7.5, 15.0] holds 2.
|
||||
let h = heights(&[0.0, 7.75, 15.0]);
|
||||
assert!((h[1] / h[0] - 2.0).abs() < 0.01, "{h:?}");
|
||||
// Five values, three bins [0,5] (5,10] (10,15]: counts 3, 1, 1.
|
||||
let h = heights(&[0.0, 5.0, 5.0, 10.0, 15.0]);
|
||||
assert_eq!(h.len(), 3);
|
||||
assert!((h[0] / h[1] - 3.0).abs() < 0.01 && (h[1] - h[2]).abs() < 0.01, "{h:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn union_series_references() {
|
||||
let mut wb = Workbook::new();
|
||||
{
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
for (r, (l, v)) in [("a", 1.0), ("b", 2.0), ("Total", 3.0), ("d", 4.0)].iter().enumerate() {
|
||||
s.set_value(CellRef::new(r as u32, 0), Value::from(*l));
|
||||
s.set_value(CellRef::new(r as u32, 1), Value::Number(*v));
|
||||
}
|
||||
}
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.series = vec![Series {
|
||||
name: Some("\"Sum of X\"".into()),
|
||||
categories: Some("(Sheet1!$A$1:$A$2,Sheet1!$A$4)".into()),
|
||||
values: "(Sheet1!$B$1:$B$2,Sheet1!$B$4)".into(),
|
||||
..Series::default()
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series[0].values, vec![Some(1.0), Some(2.0), Some(4.0)]);
|
||||
assert_eq!(d.series[0].name, "Sum of X");
|
||||
assert_eq!(d.categories, vec!["a", "b", "d"]);
|
||||
// Deeply nested parentheses from a file are bounded, not a crash.
|
||||
c.series[0].values = format!("{}Sheet1!$B$1,Sheet1!$B$2{}", "(".repeat(5000), ")".repeat(5000));
|
||||
let _ = resolve(&wb, 0, &c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_and_stock_charts_honour_the_gridlines_flag() {
|
||||
// Horizontal full-width lines in the gridline colour are the value-axis gridlines.
|
||||
let grid: Rgba = [217, 217, 217, 255];
|
||||
let is_grid = |p: &Prim| match p {
|
||||
Prim::Line { color, pts, .. } => *color == grid && pts.len() == 2 && pts[0][1] == pts[1][1] && pts[1][0] - pts[0][0] > 200.0,
|
||||
_ => false,
|
||||
};
|
||||
let grids = |prims: &[Prim]| prims.iter().filter(|p| is_grid(p)).count();
|
||||
for kind in [ChartKind::BoxWhisker, ChartKind::Stock, ChartKind::ColumnClustered] {
|
||||
let mut d = sample(kind);
|
||||
d.series.push(series("Close", &[10000.0, 12000.0, 9000.0, 14000.0, 20000.0, 16000.0], [90, 90, 90, 255], kind));
|
||||
let mut c = chart(kind);
|
||||
let on = render(&c, &d, 500.0, 350.0, &ApproxMeasure);
|
||||
c.gridlines = false;
|
||||
let off = render(&c, &d, 500.0, 350.0, &ApproxMeasure);
|
||||
assert!(grids(&on) > 0, "{kind:?}: gridlines on must draw lines");
|
||||
assert_eq!(grids(&off), 0, "{kind:?}: gridlines off must hide them");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn funnel_value_labels_follow_the_data_labels_flag() {
|
||||
let data = ChartData {
|
||||
palette: vec![],
|
||||
categories: vec!["a".into(), "b".into(), "c".into()],
|
||||
series: vec![series("S", &[11111.0, 22222.0, 33333.0], [20, 96, 130, 255], ChartKind::Funnel)],
|
||||
};
|
||||
let mut c = chart(ChartKind::Funnel);
|
||||
c.data_labels = false;
|
||||
let off = render(&c, &data, 500.0, 350.0, &ApproxMeasure);
|
||||
c.data_labels = true;
|
||||
let on = render(&c, &data, 500.0, 350.0, &ApproxMeasure);
|
||||
let values = ["$11,111", "$22,222", "$33,333"];
|
||||
for v in values {
|
||||
assert!(texts(&on).contains(&v), "{v} missing with labels on");
|
||||
assert!(!texts(&off).contains(&v), "{v} drawn with labels off");
|
||||
}
|
||||
for cat in ["a", "b", "c"] {
|
||||
assert!(texts(&off).contains(&cat));
|
||||
assert!(texts(&on).contains(&cat));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pie_points_follow_workbook_theme() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.theme.colors[4] = 0x4F6D8A;
|
||||
wb.theme.colors[5] = 0x8AA1B8;
|
||||
let mut c = chart(ChartKind::Pie);
|
||||
c.series = vec![Series {
|
||||
name: None,
|
||||
categories: None,
|
||||
values: "{5,3}".into(),
|
||||
bubble_sizes: None,
|
||||
color: None,
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
let expected = vec![series_color(&wb.theme, 0), series_color(&wb.theme, 1)];
|
||||
assert_eq!(expected, vec![[0x4F, 0x6D, 0x8A, 0xFF], [0x8A, 0xA1, 0xB8, 0xFF]]);
|
||||
let legend: Vec<Rgba> = legend_entries(&c, &d).iter().map(|e| e.1).collect();
|
||||
assert_eq!(legend, expected);
|
||||
let fills: Vec<Rgba> = render(&c, &d, 480.0, 288.0, &ApproxMeasure)
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Wedge { fill, .. } => Some(*fill),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(fills, expected);
|
||||
for kind in [ChartKind::Doughnut, ChartKind::Treemap, ChartKind::Sunburst] {
|
||||
c.kind = kind;
|
||||
let legend: Vec<Rgba> = legend_entries(&c, &d).iter().map(|e| e.1).collect();
|
||||
assert_eq!(legend, expected, "{kind:?}");
|
||||
}
|
||||
// Past the 36-colour cycle the points keep following the workbook theme.
|
||||
c.kind = ChartKind::Pie;
|
||||
c.series[0].values = format!("{{{}}}", ["1"; 40].join(","));
|
||||
let d = resolve(&wb, 0, &c);
|
||||
let legend: Vec<Rgba> = legend_entries(&c, &d).iter().map(|e| e.1).collect();
|
||||
assert_eq!(legend.len(), 40);
|
||||
assert_eq!(legend.get(37), Some(&series_color(&wb.theme, 37)));
|
||||
assert_ne!(series_color(&wb.theme, 37), series_color(&gridcraft_model::Theme::default(), 37));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_charts_draw_source_value_labels_only_when_enabled() {
|
||||
for kind in [ChartKind::Area, ChartKind::AreaStacked] {
|
||||
let d = sample(kind);
|
||||
let mut c = chart(kind);
|
||||
c.data_labels = false;
|
||||
let off = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
c.data_labels = true;
|
||||
let on = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
let count = |p: &[Prim], v: &str| texts(p).iter().filter(|t| **t == v).count();
|
||||
// One label per point: 3 series x 6 categories.
|
||||
assert_eq!(texts(&on).len(), texts(&off).len() + 18, "{kind:?}");
|
||||
for v in ["$12,000", "$38,000", "$9,000", "$27,000"] {
|
||||
assert_eq!(count(&on, v), count(&off, v) + 1, "{kind:?}: {v}");
|
||||
}
|
||||
// Stacked areas label the source values, not cumulative totals (12,000 + 38,000).
|
||||
assert_eq!(count(&on, "$50,000"), count(&off, "$50,000"), "{kind:?}: cumulative total shown");
|
||||
let polys = |p: &[Prim]| p.iter().filter(|p| matches!(p, Prim::Polygon { .. })).cloned().collect::<Vec<_>>();
|
||||
assert_eq!(polys(&on), polys(&off));
|
||||
// The first series' labels are drawn after every area, so the next area can't cover them.
|
||||
let last_poly = on.iter().rposition(|p| matches!(p, Prim::Polygon { .. }));
|
||||
let first_label = on.iter().position(|p| matches!(p, Prim::Text { text, .. } if text == "$12,000"));
|
||||
assert!(first_label > last_poly, "{kind:?}: label drawn under a later area");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Trendline maths: least-squares fits behind chart trendlines and moving averages.
|
||||
//!
|
||||
//! Exponential, logarithmic and power trendlines are linear fits of transformed data
|
||||
//! (`ln y` against `x`, `y` against `ln x`, `ln y` against `ln x`), the way Excel documents them;
|
||||
//! points where the transform is undefined (non-positive values) are skipped and R² is reported
|
||||
//! for the transformed fit. Polynomials solve the normal equations on centred, scaled x.
|
||||
|
||||
use gridcraft_model::{Trendline, TrendlineKind};
|
||||
|
||||
/// A fitted regression trendline.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct TrendFit {
|
||||
kind: TrendlineKind,
|
||||
/// Coefficients `c0..=cd` of `Y = Σ cₖ·Xᵏ` in the transformed variables, for the equation.
|
||||
pub coef: Vec<f64>,
|
||||
/// The same polynomial in `u = (X - center) / scale`, for stable evaluation.
|
||||
center: f64,
|
||||
scale: f64,
|
||||
a: Vec<f64>,
|
||||
/// Coefficient of determination; `None` when undefined (all Y equal).
|
||||
pub r2: Option<f64>,
|
||||
}
|
||||
|
||||
/// Polynomial degree in the transformed variable; `None` for moving averages.
|
||||
fn degree(k: TrendlineKind) -> Option<usize> {
|
||||
match k {
|
||||
TrendlineKind::Linear | TrendlineKind::Exponential | TrendlineKind::Logarithmic | TrendlineKind::Power => Some(1),
|
||||
TrendlineKind::Polynomial(o) => Some(usize::from(o.clamp(2, 6))),
|
||||
TrendlineKind::MovingAverage(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn log_x(k: TrendlineKind) -> bool {
|
||||
matches!(k, TrendlineKind::Logarithmic | TrendlineKind::Power)
|
||||
}
|
||||
|
||||
fn log_y(k: TrendlineKind) -> bool {
|
||||
matches!(k, TrendlineKind::Exponential | TrendlineKind::Power)
|
||||
}
|
||||
|
||||
/// Fits `t` to the points `(x, y)`. `None` for moving averages and degenerate data (too few
|
||||
/// usable points, all x equal, a singular system, non-finite results).
|
||||
pub(crate) fn fit_trendline(t: &Trendline, pts: &[(f64, f64)]) -> Option<TrendFit> {
|
||||
let kind = t.kind;
|
||||
let d = degree(kind)?;
|
||||
let data: Vec<(f64, f64)> = pts
|
||||
.iter()
|
||||
.filter(|(x, y)| x.is_finite() && y.is_finite() && (!log_x(kind) || *x > 0.0) && (!log_y(kind) || *y > 0.0))
|
||||
.map(|&(x, y)| (if log_x(kind) { x.ln() } else { x }, if log_y(kind) { y.ln() } else { y }))
|
||||
.collect();
|
||||
if data.len() < 2 || data.len() <= d {
|
||||
return None;
|
||||
}
|
||||
// Set Intercept applies to linear, exponential and polynomial trendlines; it fixes Y at x = 0.
|
||||
let fixed = match kind {
|
||||
TrendlineKind::Linear | TrendlineKind::Polynomial(_) => t.intercept,
|
||||
TrendlineKind::Exponential => t.intercept.filter(|b| *b > 0.0).map(f64::ln),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|b| b.is_finite());
|
||||
let n = data.len() as f64;
|
||||
let center = if fixed.is_some() { 0.0 } else { data.iter().map(|p| p.0).sum::<f64>() / n };
|
||||
let scale = data.iter().map(|p| (p.0 - center).abs()).fold(0.0f64, f64::max);
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let first = usize::from(fixed.is_some());
|
||||
let b0 = fixed.unwrap_or(0.0);
|
||||
// Normal equations over the unknown powers `first..=d` of u.
|
||||
let m = d + 1 - first;
|
||||
let mut ata = vec![vec![0.0f64; m]; m];
|
||||
let mut aty = vec![0.0f64; m];
|
||||
for &(x, y) in &data {
|
||||
let u = (x - center) / scale;
|
||||
let pows: Vec<f64> = (first..=d).map(|k| u.powi(k as i32)).collect();
|
||||
for (i, pi) in pows.iter().enumerate() {
|
||||
if let Some(v) = aty.get_mut(i) {
|
||||
*v += pi * (y - b0);
|
||||
}
|
||||
for (j, pj) in pows.iter().enumerate() {
|
||||
if let Some(v) = ata.get_mut(i).and_then(|r| r.get_mut(j)) {
|
||||
*v += pi * pj;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let sol = solve(ata, aty)?;
|
||||
let mut a = vec![b0; d + 1];
|
||||
for (k, v) in sol.into_iter().enumerate() {
|
||||
if let Some(slot) = a.get_mut(k + first) {
|
||||
*slot = v;
|
||||
}
|
||||
}
|
||||
let coef = expand(&a, center, scale)?;
|
||||
let fit = TrendFit { kind, coef, center, scale, a, r2: None };
|
||||
let mean = data.iter().map(|p| p.1).sum::<f64>() / n;
|
||||
let (mut ss_res, mut ss_tot) = (0.0f64, 0.0f64);
|
||||
for &(x, y) in &data {
|
||||
ss_res += (y - fit.poly(x)).powi(2);
|
||||
// A set intercept is LINEST(y - b, x, FALSE): the total sum of squares is not centred.
|
||||
ss_tot += if fixed.is_some() { (y - b0).powi(2) } else { (y - mean).powi(2) };
|
||||
}
|
||||
let r2 = (ss_tot > 0.0 && ss_tot.is_finite() && ss_res.is_finite()).then(|| 1.0 - ss_res / ss_tot);
|
||||
Some(TrendFit { r2, ..fit })
|
||||
}
|
||||
|
||||
/// Gaussian elimination with partial pivoting; `None` when (nearly) singular.
|
||||
fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
|
||||
let n = b.len();
|
||||
let big = a.iter().flatten().fold(0.0f64, |m, v| m.max(v.abs()));
|
||||
if !(big.is_finite() && big > 0.0) {
|
||||
return None;
|
||||
}
|
||||
for col in 0..n {
|
||||
let piv = (col..n).max_by(|&i, &j| {
|
||||
let vi = a.get(i).and_then(|r| r.get(col)).map_or(0.0, |v| v.abs());
|
||||
let vj = a.get(j).and_then(|r| r.get(col)).map_or(0.0, |v| v.abs());
|
||||
vi.total_cmp(&vj)
|
||||
})?;
|
||||
a.swap(col, piv);
|
||||
b.swap(col, piv);
|
||||
let p = *a.get(col)?.get(col)?;
|
||||
if !p.is_finite() || p.abs() <= big * 1e-13 {
|
||||
return None;
|
||||
}
|
||||
let prow = a.get(col)?.clone();
|
||||
let pb = *b.get(col)?;
|
||||
for r in col + 1..n {
|
||||
let row = a.get_mut(r)?;
|
||||
let f = *row.get(col)? / p;
|
||||
for (v, pv) in row.iter_mut().zip(&prow).skip(col) {
|
||||
*v -= f * pv;
|
||||
}
|
||||
*b.get_mut(r)? -= f * pb;
|
||||
}
|
||||
}
|
||||
let mut x = vec![0.0f64; n];
|
||||
for r in (0..n).rev() {
|
||||
let row = a.get(r)?;
|
||||
let s: f64 = (r + 1..n).map(|c| row.get(c).copied().unwrap_or(0.0) * x.get(c).copied().unwrap_or(0.0)).sum();
|
||||
let v = (b.get(r)? - s) / row.get(r)?;
|
||||
*x.get_mut(r)? = v;
|
||||
}
|
||||
x.iter().all(|v| v.is_finite()).then_some(x)
|
||||
}
|
||||
|
||||
/// Coefficients in X of `Σ aₖ·((X - c) / s)ᵏ` (binomial expansion).
|
||||
fn expand(a: &[f64], c: f64, s: f64) -> Option<Vec<f64>> {
|
||||
let mut out = vec![0.0f64; a.len()];
|
||||
for (k, ak) in a.iter().enumerate() {
|
||||
let lead = ak / s.powi(k as i32);
|
||||
let mut binom = 1.0f64;
|
||||
for j in 0..=k {
|
||||
// C(k, j) · (-c)^(k-j) · X^j
|
||||
if let Some(o) = out.get_mut(j) {
|
||||
*o += lead * binom * (-c).powi((k - j) as i32);
|
||||
}
|
||||
binom = binom * (k - j) as f64 / (j + 1) as f64;
|
||||
}
|
||||
}
|
||||
out.iter().all(|v| v.is_finite()).then_some(out)
|
||||
}
|
||||
|
||||
impl TrendFit {
|
||||
/// The fitted polynomial at transformed `x` (Horner in u).
|
||||
fn poly(&self, x: f64) -> f64 {
|
||||
let u = (x - self.center) / self.scale;
|
||||
self.a.iter().rev().fold(0.0, |acc, c| acc * u + c)
|
||||
}
|
||||
|
||||
/// The trendline's y at `x`; `None` outside its domain (x ≤ 0 for log/power) or when not finite.
|
||||
pub(crate) fn eval(&self, x: f64) -> Option<f64> {
|
||||
let xx = if log_x(self.kind) { if x > 0.0 { x.ln() } else { return None } } else { x };
|
||||
let p = self.poly(xx);
|
||||
let y = if log_y(self.kind) { p.exp() } else { p };
|
||||
y.is_finite().then_some(y)
|
||||
}
|
||||
|
||||
/// Equation label text, e.g. `y = 2x + 1`, `y = 0.5x² - 2x + 1`, `y = 3e^(0.2x)`.
|
||||
pub(crate) fn equation(&self) -> String {
|
||||
let c0 = self.coef.first().copied().unwrap_or(0.0);
|
||||
let c1 = self.coef.get(1).copied().unwrap_or(0.0);
|
||||
match self.kind {
|
||||
TrendlineKind::Exponential => format!("y = {}e^({}x)", num_text(c0.exp()), num_text(c1)),
|
||||
TrendlineKind::Power => format!("y = {}x^{}", num_text(c0.exp()), num_text(c1)),
|
||||
TrendlineKind::Logarithmic => terms(&[(c1, "ln(x)"), (c0, "")]),
|
||||
_ => {
|
||||
let parts: Vec<(f64, &str)> = self.coef.iter().enumerate().rev().map(|(k, c)| (*c, POWERS.get(k).copied().unwrap_or("x"))).collect();
|
||||
terms(&parts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// R² label text, e.g. `R² = 0.9963`.
|
||||
pub(crate) fn r_squared(&self) -> String {
|
||||
match self.r2 {
|
||||
Some(r) => format!("R² = {}", num_text(r)),
|
||||
None => "R² = #N/A".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const POWERS: [&str; 7] = ["", "x", "x²", "x³", "x⁴", "x⁵", "x⁶"];
|
||||
|
||||
/// `y = a·t1 ± b·t2 …`, skipping terms whose coefficient shows as 0.
|
||||
fn terms(parts: &[(f64, &str)]) -> String {
|
||||
let mut s = String::from("y = ");
|
||||
let mut first = true;
|
||||
for (c, t) in parts {
|
||||
let txt = num_text(c.abs());
|
||||
if txt == "0" {
|
||||
continue;
|
||||
}
|
||||
let neg = *c < 0.0;
|
||||
if first {
|
||||
if neg {
|
||||
s.push('-');
|
||||
}
|
||||
} else {
|
||||
s.push_str(if neg { " - " } else { " + " });
|
||||
}
|
||||
// A unit coefficient on a power of x is left out: `y = x² - x + 1`.
|
||||
if txt != "1" || t.is_empty() {
|
||||
s.push_str(&txt);
|
||||
}
|
||||
s.push_str(t);
|
||||
first = false;
|
||||
}
|
||||
if first {
|
||||
s.push('0');
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// A coefficient as trendline labels show it: up to four decimals, scientific when tiny or huge.
|
||||
pub(crate) fn num_text(v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "#NUM!".into();
|
||||
}
|
||||
let a = v.abs();
|
||||
if a == 0.0 {
|
||||
return "0".into();
|
||||
}
|
||||
if !(1e-4..1e11).contains(&a) {
|
||||
let s = format!("{v:.4E}");
|
||||
let (mant, exp) = s.split_once('E').unwrap_or((s.as_str(), "0"));
|
||||
let mant = trim_zeros(mant);
|
||||
let e: i32 = exp.parse().unwrap_or(0);
|
||||
return format!("{mant}E{}{:02}", if e < 0 { '-' } else { '+' }, e.unsigned_abs());
|
||||
}
|
||||
let s = trim_zeros(&format!("{v:.4}"));
|
||||
if s == "-0" { "0".into() } else { s }
|
||||
}
|
||||
|
||||
fn trim_zeros(s: &str) -> String {
|
||||
if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s.to_string() }
|
||||
}
|
||||
|
||||
/// Moving average of `period` consecutive points in plotted order: point `i` (from
|
||||
/// `period - 1`) is `(xᵢ, mean(yᵢ₋ₚ₊₁..=yᵢ))`. Empty when there are fewer points than `period`.
|
||||
pub(crate) fn moving_average(pts: &[(f64, f64)], period: u32) -> Vec<(f64, f64)> {
|
||||
let p = period.clamp(2, 255) as usize;
|
||||
let pts: Vec<(f64, f64)> = pts.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect();
|
||||
pts.windows(p).filter_map(|w| w.last().map(|(x, _)| (*x, w.iter().map(|q| q.1).sum::<f64>() / p as f64))).collect()
|
||||
}
|
||||
|
||||
/// Excel's automatic trendline name for the legend, e.g. `Linear (Sales)`.
|
||||
pub(crate) fn auto_name(kind: TrendlineKind, series: &str) -> String {
|
||||
let k = match kind {
|
||||
TrendlineKind::Linear => "Linear".to_string(),
|
||||
TrendlineKind::Exponential => "Expon.".into(),
|
||||
TrendlineKind::Logarithmic => "Log.".into(),
|
||||
TrendlineKind::Polynomial(_) => "Poly.".into(),
|
||||
TrendlineKind::Power => "Power".into(),
|
||||
TrendlineKind::MovingAverage(p) => format!("{} per. Mov. Avg.", p.clamp(2, 255)),
|
||||
};
|
||||
format!("{k} ({series})")
|
||||
}
|
||||
@@ -12,5 +12,8 @@ workspace = true
|
||||
serde = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
js-sys = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+19
-4
@@ -30,14 +30,14 @@ impl CellRef {
|
||||
}
|
||||
/// Moved by `(dr, dc)`, `None` when the result leaves the sheet.
|
||||
pub fn offset(&self, dr: i64, dc: i64) -> Option<CellRef> {
|
||||
let r = self.row as i64 + dr;
|
||||
let c = self.col as i64 + dc;
|
||||
let r = (self.row as i64).checked_add(dr)?;
|
||||
let c = (self.col as i64).checked_add(dc)?;
|
||||
if (0..MAX_ROWS as i64).contains(&r) && (0..MAX_COLS as i64).contains(&c) { Some(CellRef::new(r as u32, c as u32)) } else { None }
|
||||
}
|
||||
/// Moved by `(dr, dc)` and clamped to the sheet.
|
||||
pub fn offset_clamped(&self, dr: i64, dc: i64) -> CellRef {
|
||||
let r = (self.row as i64 + dr).clamp(0, MAX_ROWS as i64 - 1);
|
||||
let c = (self.col as i64 + dc).clamp(0, MAX_COLS as i64 - 1);
|
||||
let r = (self.row as i64).saturating_add(dr).clamp(0, MAX_ROWS as i64 - 1);
|
||||
let c = (self.col as i64).saturating_add(dc).clamp(0, MAX_COLS as i64 - 1);
|
||||
CellRef::new(r as u32, c as u32)
|
||||
}
|
||||
/// Parses `A1`, `$A$1`, `xfd1048576` (case-insensitive). `None` if malformed or out of range.
|
||||
@@ -272,6 +272,21 @@ mod tests {
|
||||
assert_eq!(a.iter().count(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_offsets() {
|
||||
let cell = CellRef::new(1, 1);
|
||||
for delta in [i64::MIN, i64::MAX] {
|
||||
assert_eq!(cell.offset(delta, 0), None);
|
||||
assert_eq!(cell.offset(0, delta), None);
|
||||
assert_eq!(cell.offset(delta, delta), None);
|
||||
}
|
||||
assert_eq!(cell.offset_clamped(i64::MAX, i64::MAX), CellRef::new(MAX_ROWS - 1, MAX_COLS - 1));
|
||||
assert_eq!(cell.offset_clamped(i64::MIN, i64::MIN), CellRef::new(0, 0));
|
||||
assert_eq!(cell.offset_clamped(i64::MAX, i64::MIN), CellRef::new(MAX_ROWS - 1, 0));
|
||||
assert_eq!(cell.offset_clamped(i64::MIN, i64::MAX), CellRef::new(0, MAX_COLS - 1));
|
||||
assert_eq!(cell.offset(2, -1), Some(CellRef::new(3, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets() {
|
||||
assert_eq!(CellRef::new(0, 0).offset(-1, 0), None);
|
||||
|
||||
+50
-2
@@ -39,6 +39,34 @@ pub fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
|
||||
era * 146097 + doe - 719468
|
||||
}
|
||||
|
||||
/// Milliseconds since the Unix epoch (UTC) from the system clock; `None` when the clock is unavailable.
|
||||
/// On wasm32 `std::time::SystemTime::now` traps, so the browser clock is read through `Date.now()`.
|
||||
#[allow(clippy::disallowed_methods)] // the std clock is read only off wasm
|
||||
pub fn unix_now_ms() -> Option<f64> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?;
|
||||
Some(d.as_secs_f64() * 1000.0)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
Some(js_sys::Date::now())
|
||||
}
|
||||
}
|
||||
|
||||
/// Date serial (1900 system, with fraction) for a Unix time in milliseconds.
|
||||
pub fn serial_from_unix_ms(ms: f64) -> f64 {
|
||||
25569.0 + ms / 86_400_000.0
|
||||
}
|
||||
|
||||
/// Converts a 1900-system serial (as the clock supplies it) to the serial of the same instant in `sys`.
|
||||
pub fn serial_in_system(sys: DateSystem, serial_1900: f64) -> f64 {
|
||||
match sys {
|
||||
DateSystem::D1900 => serial_1900,
|
||||
DateSystem::D1904 => serial_1900 - 1462.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn civil_from_days(z: i64) -> (i32, u32, u32) {
|
||||
let z = z + 719468;
|
||||
let era = if z >= 0 { z } else { z - 146096 } / 146097;
|
||||
@@ -75,6 +103,14 @@ pub fn days_in_month_in(sys: DateSystem, y: i32, m: u32) -> u32 {
|
||||
if sys == DateSystem::D1900 && y == 1900 && m == 2 { 29 } else { days_in_month(y, m) }
|
||||
}
|
||||
|
||||
/// Last serial that is a valid date in a date system: 9999-12-31 (2958465 in the 1900 system, 2957003 in the 1904 system).
|
||||
pub fn max_serial(sys: DateSystem) -> i64 {
|
||||
match sys {
|
||||
DateSystem::D1900 => 2_958_465,
|
||||
DateSystem::D1904 => 2_958_465 - 1462,
|
||||
}
|
||||
}
|
||||
|
||||
/// Serial for a date. Month and day overflow roll over like `DATE()` (month 13 = January next
|
||||
/// year, day 0 = last day of the previous month), in the date system's own calendar: in the 1900
|
||||
/// system February 1900 has 29 days, so `(1900, 2, 29)` and `(1900, 3, 0)` are serial 60.
|
||||
@@ -97,7 +133,7 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
|
||||
DateSystem::D1904 => first - UNIX_1904_01_01,
|
||||
};
|
||||
let serial = first.checked_add(day)?.checked_sub(1)?;
|
||||
if !(0..=2_958_465).contains(&serial) {
|
||||
if !(0..=max_serial(sys)).contains(&serial) {
|
||||
return None;
|
||||
}
|
||||
Some(serial as f64)
|
||||
@@ -105,7 +141,7 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
|
||||
|
||||
/// Date/time from a serial. `None` for negative or too-large serials.
|
||||
pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option<DateTime> {
|
||||
if !serial.is_finite() || !(0.0..2_958_466.0).contains(&serial) {
|
||||
if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) {
|
||||
return None;
|
||||
}
|
||||
let mut day = serial.floor() as i64;
|
||||
@@ -160,6 +196,14 @@ pub const WEEKDAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Th
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serial_from_unix_time() {
|
||||
assert_eq!(serial_from_unix_ms(0.0), 25569.0);
|
||||
// 2026-10-10T12:00:00Z
|
||||
assert_eq!(serial_from_unix_ms(1_791_633_600_000.0), 46305.5);
|
||||
assert!(unix_now_ms().is_some_and(|ms| serial_from_unix_ms(ms) > 46305.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_serials() {
|
||||
let s = DateSystem::D1900;
|
||||
@@ -169,6 +213,10 @@ mod tests {
|
||||
assert_eq!(serial_from_ymd(s, 2000, 1, 1), Some(36526.0));
|
||||
assert_eq!(serial_from_ymd(s, 2026, 10, 7), Some(46302.0));
|
||||
assert_eq!(serial_from_ymd(s, 9999, 12, 31), Some(2958465.0));
|
||||
assert_eq!(serial_from_ymd(DateSystem::D1904, 9999, 12, 31), Some(2957003.0));
|
||||
assert_eq!(serial_from_ymd(DateSystem::D1904, 9999, 12, 32), None);
|
||||
assert!(datetime_from_serial(DateSystem::D1904, 2957003.5).is_some());
|
||||
assert!(datetime_from_serial(DateSystem::D1904, 2957004.0).is_none());
|
||||
assert_eq!(serial_from_ymd(s, 2020, 13, 1), serial_from_ymd(s, 2021, 1, 1));
|
||||
assert_eq!(serial_from_ymd(s, 2020, 3, 0), serial_from_ymd(s, 2020, 2, 29));
|
||||
assert_eq!(serial_from_ymd(s, 120, 1, 1), serial_from_ymd(s, 2020, 1, 1));
|
||||
|
||||
+36
-11
@@ -41,7 +41,12 @@ pub fn parse_input(s: &str, sys: DateSystem) -> Parsed {
|
||||
|
||||
/// Numeric text as arithmetic coerces it ("1,000", "50%", "$3", "1/2/2020", "10:00").
|
||||
pub fn parse_number_text(s: &str) -> Option<f64> {
|
||||
parse_numeric(s.trim(), DateSystem::D1900).map(|(n, _)| n)
|
||||
parse_number_text_in(s, DateSystem::D1900)
|
||||
}
|
||||
|
||||
/// Like [`parse_number_text`], with date text read in the given workbook date system.
|
||||
pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option<f64> {
|
||||
parse_numeric(s.trim(), sys).map(|(n, _)| n)
|
||||
}
|
||||
|
||||
fn parse_numeric(t: &str, sys: DateSystem) -> Option<(f64, Option<&'static str>)> {
|
||||
@@ -252,10 +257,14 @@ fn parse_date(t: &str, sys: DateSystem) -> Option<(f64, &'static str)> {
|
||||
// "Mar 4, 2026" / "March 4 2026" / "4 March 2026"
|
||||
let words: Vec<&str> = t.split([' ', ',']).filter(|w| !w.is_empty()).collect();
|
||||
if words.len() == 3 {
|
||||
// Two-digit years follow the same 2029 rule as the dashed forms above.
|
||||
let expand = |w: &str, y: i64| if w.len() <= 2 { if y < 30 { 2000 + y } else { 1900 + y } } else { y };
|
||||
if let (Some(m), Some(d), Some(y)) = (month_from_name(words[0]), num(words[1]), num(words[2])) {
|
||||
let y = expand(words[2], y);
|
||||
return valid_ymd(sys, y, m as i64, d).map(|s| (s, "d-mmm-yy"));
|
||||
}
|
||||
if let (Some(d), Some(m), Some(y)) = (num(words[0]), month_from_name(words[1]), num(words[2])) {
|
||||
let y = expand(words[2], y);
|
||||
return valid_ymd(sys, y, m as i64, d).map(|s| (s, "d-mmm-yy"));
|
||||
}
|
||||
}
|
||||
@@ -263,7 +272,8 @@ fn parse_date(t: &str, sys: DateSystem) -> Option<(f64, &'static str)> {
|
||||
}
|
||||
|
||||
fn valid_ymd(sys: DateSystem, y: i64, m: i64, d: i64) -> Option<f64> {
|
||||
if !(1..=12).contains(&m) || d < 1 {
|
||||
// Dates before 1900 stay text (`DATE()` would add 1900 to such a year).
|
||||
if !(1..=12).contains(&m) || d < 1 || y < 1900 {
|
||||
return None;
|
||||
}
|
||||
let max = crate::date::days_in_month_in(sys, y as i32, m as u32) as i64;
|
||||
@@ -273,16 +283,12 @@ fn valid_ymd(sys: DateSystem, y: i64, m: i64, d: i64) -> Option<f64> {
|
||||
serial_from_ymd(sys, y, m, d)
|
||||
}
|
||||
|
||||
/// The year used for dates typed without one. Fixed per process from the system clock when
|
||||
/// available (wasm without clock falls back to 2026).
|
||||
#[allow(clippy::disallowed_methods)] // the clock is read only off wasm
|
||||
/// The year used for dates typed without one, from the system clock (browser clock on wasm).
|
||||
/// Falls back to 2026 only when no clock is available.
|
||||
pub fn current_year() -> i64 {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if let Ok(d) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
|
||||
let days = (d.as_secs() / 86400) as i64;
|
||||
return crate::date::civil_from_days(days).0 as i64;
|
||||
}
|
||||
if let Some(ms) = crate::date::unix_now_ms() {
|
||||
let days = (ms / 86_400_000.0).floor() as i64;
|
||||
return crate::date::civil_from_days(days).0 as i64;
|
||||
}
|
||||
2026
|
||||
}
|
||||
@@ -290,6 +296,8 @@ pub fn current_year() -> i64 {
|
||||
fn parse_datetime(t: &str, sys: DateSystem) -> Option<(f64, Option<&'static str>)> {
|
||||
if let Some((tf, secs, ampm)) = parse_time(t) {
|
||||
let f = match (secs, ampm) {
|
||||
// 24 hours or more: elapsed hours, so 25:00 shows as 25:00:00, not 1:00.
|
||||
_ if tf >= 1.0 => "[h]:mm:ss",
|
||||
(false, false) => "h:mm",
|
||||
(true, false) => "h:mm:ss",
|
||||
(false, true) => "h:mm AM/PM",
|
||||
@@ -318,6 +326,16 @@ mod tests {
|
||||
parse_input(s, DateSystem::D1900)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn month_name_short_year() {
|
||||
for s in ["Mar 4, 26", "Mar 4 26", "March 4 26", "4 March 26", "Mar 4, 2026"] {
|
||||
assert_eq!(p(s).value, Value::Number(46085.0), "{s}");
|
||||
}
|
||||
assert_eq!(p("Mar 4, 99").value, p("Mar 4, 1999").value);
|
||||
assert_eq!(p("Mar 4, 1776").value, Value::text("Mar 4, 1776"));
|
||||
assert_eq!(p("Feb 30, 26").value, Value::text("Feb 30, 26"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers() {
|
||||
assert_eq!(p("42").value, Value::Number(42.0));
|
||||
@@ -352,11 +370,18 @@ mod tests {
|
||||
assert_eq!(p("7-Oct-2026").value, Value::Number(46302.0));
|
||||
assert_eq!(p("Oct 7, 2026").value, Value::Number(46302.0));
|
||||
assert_eq!(p("2/30/2026").value, Value::text("2/30/2026"));
|
||||
assert_eq!(p("7/4/1776").value, Value::text("7/4/1776"));
|
||||
assert_eq!(p("1776-07-04").value, Value::text("1776-07-04"));
|
||||
assert_eq!(p("4-Jul-1776").value, Value::text("4-Jul-1776"));
|
||||
assert_eq!(p("12/31/1899").value, Value::text("12/31/1899"));
|
||||
assert_eq!(p("1/1/1900").value, Value::Number(1.0));
|
||||
assert_eq!(p("12:00").value, Value::Number(0.5));
|
||||
assert_eq!(p("6:00 PM").value, Value::Number(0.75));
|
||||
assert_eq!(p("12:00 AM").value, Value::Number(0.0));
|
||||
assert_eq!(p("10/7/2026 18:00").value, Value::Number(46302.75));
|
||||
assert_eq!(p("25:00").value, Value::Number(25.0 / 24.0));
|
||||
assert_eq!(p("25:00").format, Some("[h]:mm:ss"));
|
||||
assert_eq!(p("23:59").format, Some("h:mm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -224,13 +224,17 @@ impl Value {
|
||||
/// Coercion to a number as arithmetic does it: empty = 0, TRUE = 1, numeric text parses
|
||||
/// (including dates, times, percentages and currency), other text = `#VALUE!`.
|
||||
pub fn to_number(&self) -> Result<f64, CellError> {
|
||||
self.to_number_in(crate::DateSystem::D1900)
|
||||
}
|
||||
/// [`Value::to_number`] with date text read in the given workbook date system.
|
||||
pub fn to_number_in(&self, sys: crate::DateSystem) -> Result<f64, CellError> {
|
||||
match self {
|
||||
Value::Empty => Ok(0.0),
|
||||
Value::Number(n) => Ok(*n),
|
||||
Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
|
||||
Value::Text(t) => crate::parse::parse_number_text(t).ok_or(CellError::Value),
|
||||
Value::Text(t) => crate::parse::parse_number_text_in(t, sys).ok_or(CellError::Value),
|
||||
Value::Error(e) => Err(*e),
|
||||
Value::Array(a) => a.data.first().map(|v| v.to_number()).unwrap_or(Ok(0.0)),
|
||||
Value::Array(a) => a.data.first().map(|v| v.to_number_in(sys)).unwrap_or(Ok(0.0)),
|
||||
}
|
||||
}
|
||||
/// Coercion to text as `&` does it.
|
||||
|
||||
@@ -25,4 +25,5 @@ gridcraft-pdf = { workspace = true }
|
||||
image = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
gridcraft-xlsx = { workspace = true, features = ["test-support"] }
|
||||
zip = { workspace = true }
|
||||
|
||||
+120
-15
@@ -90,10 +90,7 @@ fn lerp(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] {
|
||||
]
|
||||
}
|
||||
|
||||
/// Number of icons in a set name like `3TrafficLights1`, `5Quarters`.
|
||||
pub fn icon_count(set: &str) -> usize {
|
||||
set.chars().next().and_then(|c| c.to_digit(10)).unwrap_or(3) as usize
|
||||
}
|
||||
pub use gridcraft_model::icon_count;
|
||||
|
||||
impl CfCache {
|
||||
pub fn new() -> Self {
|
||||
@@ -144,7 +141,8 @@ impl CfCache {
|
||||
CfOperator::GreaterOrEqual => compare(&v, &av) != std::cmp::Ordering::Less,
|
||||
CfOperator::LessOrEqual => compare(&v, &av) != std::cmp::Ordering::Greater,
|
||||
};
|
||||
(ok && !v.is_empty()).then_some(style.as_ref())
|
||||
// As in Excel, a blank cell compares as 0 (or ""), and an error never matches.
|
||||
(ok && !v.is_error()).then_some(style.as_ref())
|
||||
}
|
||||
CfRule::Expression { formula, style } => {
|
||||
gridcraft_calc::evaluate(wb, sheet, c, &relative(formula, first, c)).to_bool().unwrap_or(false).then_some(style.as_ref())
|
||||
@@ -154,7 +152,7 @@ impl CfCache {
|
||||
CfRule::BeginsWith { text: t, style } => text.to_lowercase().starts_with(&t.to_lowercase()).then_some(style.as_ref()),
|
||||
CfRule::EndsWith { text: t, style } => text.to_lowercase().ends_with(&t.to_lowercase()).then_some(style.as_ref()),
|
||||
CfRule::Blanks { style } => (v.is_empty() || text.trim().is_empty()).then_some(style.as_ref()),
|
||||
CfRule::NoBlanks { style } => (!v.is_empty()).then_some(style.as_ref()),
|
||||
CfRule::NoBlanks { style } => (!v.is_empty() && !text.trim().is_empty()).then_some(style.as_ref()),
|
||||
CfRule::Errors { style } => v.is_error().then_some(style.as_ref()),
|
||||
CfRule::NoErrors { style } => (!v.is_error()).then_some(style.as_ref()),
|
||||
CfRule::Duplicate { style } => {
|
||||
@@ -186,7 +184,7 @@ impl CfCache {
|
||||
},
|
||||
CfRule::TimePeriod { period, style } => match v.as_f64() {
|
||||
Some(n) => {
|
||||
let today = gridcraft_calc::now_serial().floor();
|
||||
let today = gridcraft_core::date::serial_in_system(wb.date_system, gridcraft_calc::now_serial()).floor();
|
||||
let d = n.floor();
|
||||
let wd = gridcraft_core::date::datetime_from_serial(wb.date_system, today).map(|x| x.weekday as f64).unwrap_or(0.0);
|
||||
let week_start = today - wd;
|
||||
@@ -261,11 +259,18 @@ impl CfCache {
|
||||
CfRule::IconSet { set, thresholds, reverse, show_value } => {
|
||||
if let Some(n) = v.as_f64() {
|
||||
let k = icon_count(set);
|
||||
let cuts: Vec<f64> = if thresholds.len() + 1 == k {
|
||||
thresholds.iter().map(|t| threshold(wb, sheet, c, &st, t)).collect()
|
||||
} else {
|
||||
(1..k).map(|i| percentile(&st.sorted, i as f64 * 100.0 / k as f64)).collect()
|
||||
// One threshold per icon, the first being the lower bound (as in the file);
|
||||
// also accept the lower bound left out, else Excel's defaults.
|
||||
let defaults;
|
||||
let lower = match thresholds.len() {
|
||||
n if n == k => thresholds.get(1..).unwrap_or_default(),
|
||||
n if n + 1 == k => thresholds.as_slice(),
|
||||
_ => {
|
||||
defaults = default_icon_thresholds(set);
|
||||
defaults.get(1..).unwrap_or_default()
|
||||
}
|
||||
};
|
||||
let cuts: Vec<f64> = lower.iter().map(|t| threshold(wb, sheet, c, &st, t)).collect();
|
||||
let mut idx = cuts.iter().filter(|cut| n >= **cut).count();
|
||||
if *reverse {
|
||||
idx = k - 1 - idx.min(k - 1);
|
||||
@@ -281,10 +286,12 @@ impl CfCache {
|
||||
};
|
||||
if let Some(st) = matched_style {
|
||||
any = true;
|
||||
out.style = Some(match out.style.take() {
|
||||
None => st.clone(),
|
||||
Some(prev) => prev,
|
||||
});
|
||||
// Every matching rule applies; where two set the same part, the rule with the
|
||||
// higher priority (seen first) wins.
|
||||
match &mut out.style {
|
||||
None => out.style = Some(st.clone()),
|
||||
Some(prev) => layer_under(prev, st),
|
||||
}
|
||||
if cf.stop_if_true {
|
||||
break;
|
||||
}
|
||||
@@ -294,6 +301,39 @@ impl CfCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the parts `lower` sets that `style` leaves unset (differential styles: default parts
|
||||
/// are unset).
|
||||
fn layer_under(style: &mut Style, lower: &Style) {
|
||||
if style.fill.pattern == PatternType::None {
|
||||
style.fill = lower.fill;
|
||||
}
|
||||
if style.font.color == Color::Auto {
|
||||
style.font.color = lower.font.color;
|
||||
}
|
||||
style.font.bold |= lower.font.bold;
|
||||
style.font.italic |= lower.font.italic;
|
||||
style.font.strike |= lower.font.strike;
|
||||
if style.font.underline == Underline::None {
|
||||
style.font.underline = lower.font.underline;
|
||||
}
|
||||
let b = &mut style.borders;
|
||||
for (dst, src) in [
|
||||
(&mut b.left, lower.borders.left),
|
||||
(&mut b.right, lower.borders.right),
|
||||
(&mut b.top, lower.borders.top),
|
||||
(&mut b.bottom, lower.borders.bottom),
|
||||
(&mut b.diag_down, lower.borders.diag_down),
|
||||
(&mut b.diag_up, lower.borders.diag_up),
|
||||
] {
|
||||
if dst.is_none() {
|
||||
*dst = src;
|
||||
}
|
||||
}
|
||||
if style.num_fmt.as_str() == "General" {
|
||||
style.num_fmt = lower.num_fmt.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Shifts a rule formula written for the top-left cell of the range to `c`.
|
||||
fn relative(f: &str, first: CellRef, c: CellRef) -> String {
|
||||
if first == c {
|
||||
@@ -306,3 +346,68 @@ fn relative(f: &str, first: CellRef, c: CellRef) -> String {
|
||||
Err(_) => f.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_matching_rule_applies() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[200], [400], [510]]})).unwrap();
|
||||
let rule = |op: &str, value: &str, preset: &str| json!({"range": "A1:A3", "rule": {"type": "cellIs", "operator": op, "value": value, "preset": preset}});
|
||||
s.execute("home.conditionalFormat", rule("greaterThan", "300", "lightRedFill")).unwrap();
|
||||
s.execute("home.conditionalFormat", rule("greaterThan", "500", "redBorder")).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let mut cache = CfCache::new();
|
||||
let mut look = |a: &str| cache.look(&d.wb, 0, CellRef::parse(a).unwrap()).and_then(|l| l.style);
|
||||
assert!(look("A1").is_none());
|
||||
let only_fill = look("A2").unwrap();
|
||||
assert_eq!(only_fill.fill.pattern, PatternType::Solid);
|
||||
assert!(only_fill.borders.top.is_none());
|
||||
let both = look("A3").unwrap();
|
||||
assert_eq!(both.fill, only_fill.fill);
|
||||
assert!(!both.borders.top.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_value_rules_on_blanks_and_errors() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[3, "=NA()"], [null, 7], ["=NA()", null], [" ", null], [7, null]]})).unwrap();
|
||||
let rule = |range: &str, r: serde_json::Value| json!({"range": range, "rule": r});
|
||||
s.execute("home.conditionalFormat", rule("A1:A5", json!({"type": "cellIs", "operator": "less", "value": "5", "preset": "lightRedFill"})))
|
||||
.unwrap();
|
||||
s.execute("home.conditionalFormat", rule("A1:A5", json!({"type": "noBlanks", "preset": "redBorder"}))).unwrap();
|
||||
s.execute("home.conditionalFormat", rule("B1:B2", json!({"type": "cellIs", "operator": "greater", "value": "5", "preset": "lightRedFill"})))
|
||||
.unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let mut cache = CfCache::new();
|
||||
let mut look = |a: &str| cache.look(&d.wb, 0, CellRef::parse(a).unwrap()).and_then(|l| l.style);
|
||||
let fill = |st: Option<Style>| st.is_some_and(|st| st.fill.pattern == PatternType::Solid);
|
||||
let border = |st: Option<Style>| st.is_some_and(|st| !st.borders.top.is_none());
|
||||
// Less than 5: 3 and the blank cell (as 0), not #N/A.
|
||||
assert_eq!([look("A1"), look("A2"), look("A3"), look("A5")].map(fill), [true, true, false, false]);
|
||||
// Greater than 5: 7, not #N/A.
|
||||
assert_eq!([look("B1"), look("B2")].map(fill), [false, true]);
|
||||
// No blanks: neither the empty cell nor the one holding a space.
|
||||
assert_eq!([look("A1"), look("A2"), look("A4")].map(border), [true, false, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_value_operator_names() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[3], [7]]})).unwrap();
|
||||
let rule = |op: &str| json!({"range": "A1:A2", "rule": {"type": "cellIs", "operator": op, "value": "5", "preset": "lightRedFill"}});
|
||||
s.execute("home.conditionalFormat", rule("lessThan")).unwrap();
|
||||
assert!(s.execute("home.conditionalFormat", rule("smaller")).is_err());
|
||||
let d = s.doc().unwrap();
|
||||
let mut cache = CfCache::new();
|
||||
let mut look = |a: &str| cache.look(&d.wb, 0, CellRef::parse(a).unwrap()).and_then(|l| l.style).is_some();
|
||||
assert_eq!([look("A1"), look("A2")], [true, false]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
//! Reading the HTML flavour of the system clipboard on paste.
|
||||
//!
|
||||
//! Spreadsheets put an HTML table on the clipboard next to the tab-separated text. The text holds
|
||||
//! what each cell *shows* ("Rp10,000.00"), which en-US input parsing can't always turn back into a
|
||||
//! number. The HTML of the common sources also carries the underlying number as a cell attribute:
|
||||
//! `x:num="10000"` (Excel, Excel for the web) and `sdval="10000"` (LibreOffice Calc). Paste uses
|
||||
//! it to keep such cells numeric (#257). Only the table structure, the cell text and these two
|
||||
//! attributes are read; everything else in the markup is ignored.
|
||||
|
||||
/// Largest clipboard HTML we look at; past this the paste uses the plain text alone.
|
||||
const MAX_HTML: usize = 16 * 1024 * 1024;
|
||||
/// Widest `colspan` honoured (the sheet's column count).
|
||||
const MAX_SPAN: usize = gridcraft_core::MAX_COLS as usize;
|
||||
|
||||
/// One table cell: its visible text and the number the source recorded for it, if any.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct HtmlCell {
|
||||
pub text: String,
|
||||
pub num: Option<f64>,
|
||||
}
|
||||
|
||||
/// The cells of the first table in `html`, row by row; a cell spanning columns is followed by
|
||||
/// empty cells so positions line up with the tab-separated text. Empty when there is no table.
|
||||
pub(crate) fn table_cells(html: &str) -> Vec<Vec<HtmlCell>> {
|
||||
let mut rows: Vec<Vec<HtmlCell>> = Vec::new();
|
||||
if html.len() > MAX_HTML {
|
||||
return rows;
|
||||
}
|
||||
let mut cell: Option<(HtmlCell, usize)> = None;
|
||||
let mut in_table = false;
|
||||
let mut rest = html;
|
||||
while !rest.is_empty() {
|
||||
let Some(lt) = rest.find('<') else {
|
||||
if let Some((c, _)) = cell.as_mut() {
|
||||
c.text.push_str(rest);
|
||||
}
|
||||
break;
|
||||
};
|
||||
if let Some((c, _)) = cell.as_mut() {
|
||||
c.text.push_str(rest.get(..lt).unwrap_or_default());
|
||||
}
|
||||
rest = rest.get(lt..).unwrap_or_default();
|
||||
if let Some(after) = rest.strip_prefix("<!--") {
|
||||
rest = after.find("-->").and_then(|e| after.get(e + 3..)).unwrap_or_default();
|
||||
continue;
|
||||
}
|
||||
let Some(gt) = tag_end(rest) else { break };
|
||||
let tag = rest.get(1..gt).unwrap_or_default();
|
||||
rest = rest.get(gt + 1..).unwrap_or_default();
|
||||
let closing = tag.starts_with('/');
|
||||
let body = tag.trim_start_matches('/');
|
||||
let name_end = body.find(|c: char| c.is_whitespace() || c == '/').unwrap_or(body.len());
|
||||
let name = body.get(..name_end).unwrap_or_default().to_ascii_lowercase();
|
||||
let attrs = body.get(name_end..).unwrap_or_default();
|
||||
match (name.as_str(), closing) {
|
||||
("style" | "script", false) => {
|
||||
// Raw text: skip to the closing tag.
|
||||
let end = format!("</{name}");
|
||||
rest = find_ci(rest, &end).and_then(|i| rest.get(i..)).unwrap_or_default();
|
||||
}
|
||||
("table", false) => {
|
||||
if in_table {
|
||||
break; // a nested table: the outer one is the clipboard grid, stop here
|
||||
}
|
||||
in_table = true;
|
||||
}
|
||||
("table", true) => {
|
||||
finish(&mut rows, &mut cell);
|
||||
if !rows.is_empty() {
|
||||
break;
|
||||
}
|
||||
in_table = false;
|
||||
}
|
||||
("tr", false) if in_table => {
|
||||
finish(&mut rows, &mut cell);
|
||||
rows.push(Vec::new());
|
||||
}
|
||||
("td" | "th", false) if in_table => {
|
||||
finish(&mut rows, &mut cell);
|
||||
if rows.is_empty() {
|
||||
rows.push(Vec::new());
|
||||
}
|
||||
let num = attr(attrs, "x:num").or_else(|| attr(attrs, "sdval")).and_then(|v| v.trim().parse::<f64>().ok()).filter(|n| n.is_finite());
|
||||
let span = attr(attrs, "colspan").and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(1).clamp(1, MAX_SPAN);
|
||||
cell = Some((HtmlCell { text: String::new(), num }, span));
|
||||
}
|
||||
("td" | "th", true) | ("tr", true) => finish(&mut rows, &mut cell),
|
||||
("br", _) => {
|
||||
if let Some((c, _)) = cell.as_mut() {
|
||||
c.text.push(' ');
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
finish(&mut rows, &mut cell);
|
||||
rows
|
||||
}
|
||||
|
||||
/// Closes the open cell (if any) into the last row, decoding its text.
|
||||
fn finish(rows: &mut Vec<Vec<HtmlCell>>, cell: &mut Option<(HtmlCell, usize)>) {
|
||||
let Some((mut c, span)) = cell.take() else { return };
|
||||
c.text = decode(&c.text);
|
||||
if rows.is_empty() {
|
||||
rows.push(Vec::new());
|
||||
}
|
||||
if let Some(row) = rows.last_mut() {
|
||||
row.push(c);
|
||||
let room = MAX_SPAN.saturating_sub(row.len());
|
||||
row.extend(std::iter::repeat_n(HtmlCell::default(), span.saturating_sub(1).min(room)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte index of the `>` that closes the tag `rest` starts with; a `>` inside a quoted attribute
|
||||
/// value (an inline `mso-number-format` condition such as `[>=1000]`) doesn't end it.
|
||||
fn tag_end(rest: &str) -> Option<usize> {
|
||||
let mut quote: Option<char> = None;
|
||||
for (i, c) in rest.char_indices() {
|
||||
match (quote, c) {
|
||||
(Some(q), c) if c == q => quote = None,
|
||||
(Some(_), _) => {}
|
||||
(None, '"' | '\'') => quote = Some(c),
|
||||
(None, '>') => return Some(i),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Case-insensitive ASCII search.
|
||||
fn find_ci(hay: &str, needle: &str) -> Option<usize> {
|
||||
let (h, n) = (hay.as_bytes(), needle.as_bytes());
|
||||
if n.is_empty() || h.len() < n.len() {
|
||||
return None;
|
||||
}
|
||||
(0..=h.len() - n.len()).find(|&i| h.get(i..i + n.len()).is_some_and(|w| w.eq_ignore_ascii_case(n)))
|
||||
}
|
||||
|
||||
/// The value of attribute `name` in a tag's attribute text (quoted or bare). A bare attribute
|
||||
/// without `=` has no value.
|
||||
fn attr<'a>(attrs: &'a str, name: &str) -> Option<&'a str> {
|
||||
let mut s = attrs;
|
||||
loop {
|
||||
s = s.trim_start_matches(|c: char| c.is_whitespace() || c == '/');
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let key_end = s.find(|c: char| c.is_whitespace() || c == '=' || c == '/').unwrap_or(s.len());
|
||||
let key = s.get(..key_end).unwrap_or_default();
|
||||
s = s.get(key_end..).unwrap_or_default().trim_start();
|
||||
let mut value = None;
|
||||
if let Some(after) = s.strip_prefix('=') {
|
||||
let after = after.trim_start();
|
||||
let (v, next) = match after.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => {
|
||||
let inner = after.get(1..).unwrap_or_default();
|
||||
let end = inner.find(q).unwrap_or(inner.len());
|
||||
(inner.get(..end).unwrap_or_default(), inner.get(end + 1..).unwrap_or_default())
|
||||
}
|
||||
_ => {
|
||||
let end = after.find(char::is_whitespace).unwrap_or(after.len());
|
||||
(after.get(..end).unwrap_or_default(), after.get(end..).unwrap_or_default())
|
||||
}
|
||||
};
|
||||
value = Some(v);
|
||||
s = next;
|
||||
}
|
||||
if key.eq_ignore_ascii_case(name) {
|
||||
return value;
|
||||
}
|
||||
if key.is_empty() && value.is_none() {
|
||||
// Stray character (e.g. a lone '='): skip it so the loop always advances.
|
||||
let mut chars = s.chars();
|
||||
chars.next();
|
||||
s = chars.as_str();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// HTML text to plain text: entities decoded, whitespace runs (and `<br>`) collapsed to one
|
||||
/// space, trimmed. The text only serves to match a cell with the tab-separated text.
|
||||
fn decode(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
let mut rest = raw;
|
||||
while let Some(amp) = rest.find('&') {
|
||||
out.push_str(rest.get(..amp).unwrap_or_default());
|
||||
rest = rest.get(amp..).unwrap_or_default();
|
||||
let semi = rest.get(..12).unwrap_or(rest).find(';');
|
||||
let entity = semi.and_then(|e| rest.get(1..e));
|
||||
let ch = entity.and_then(|e| match e {
|
||||
"amp" => Some('&'),
|
||||
"lt" => Some('<'),
|
||||
"gt" => Some('>'),
|
||||
"quot" => Some('"'),
|
||||
"apos" => Some('\''),
|
||||
"nbsp" => Some('\u{a0}'),
|
||||
_ => {
|
||||
let n = e
|
||||
.strip_prefix("#x")
|
||||
.or_else(|| e.strip_prefix("#X"))
|
||||
.map(|h| u32::from_str_radix(h, 16))
|
||||
.or_else(|| e.strip_prefix('#').map(str::parse::<u32>));
|
||||
n.and_then(Result::ok).and_then(char::from_u32)
|
||||
}
|
||||
});
|
||||
match (ch, semi) {
|
||||
(Some(c), Some(e)) => {
|
||||
out.push(c);
|
||||
rest = rest.get(e + 1..).unwrap_or_default();
|
||||
}
|
||||
_ => {
|
||||
out.push('&');
|
||||
rest = rest.get(1..).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
let mut text = String::with_capacity(out.len());
|
||||
let mut space = false;
|
||||
for c in out.chars() {
|
||||
if c.is_whitespace() && c != '\u{a0}' {
|
||||
space = true;
|
||||
continue;
|
||||
}
|
||||
if space && !text.is_empty() {
|
||||
text.push(' ');
|
||||
}
|
||||
space = false;
|
||||
text.push(c);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Same-looking text: non-breaking spaces as spaces, whitespace runs collapsed, trimmed.
|
||||
pub(crate) fn normalized(s: &str) -> String {
|
||||
s.replace('\u{a0}', " ").split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// A number format that shows `n` exactly as `shown` ("Rp10,000.00" for 10000 →
|
||||
/// `"Rp"#,##0.00`), inferred from the text around the digits. `None` unless the format renders
|
||||
/// `shown` back character for character.
|
||||
pub(crate) fn format_for(shown: &str, n: f64) -> Option<String> {
|
||||
let shown = normalized(shown);
|
||||
let start = shown.find(|c: char| c.is_ascii_digit())?;
|
||||
let end = shown.rfind(|c: char| c.is_ascii_digit()).map(|i| i + 1)?;
|
||||
let core = shown.get(start..end)?;
|
||||
let mut prefix = shown.get(..start)?.to_string();
|
||||
let suffix = shown.get(end..)?;
|
||||
if core.chars().any(|c| !(c.is_ascii_digit() || c == ',' || c == '.')) {
|
||||
return None;
|
||||
}
|
||||
if n < 0.0 {
|
||||
// A one-section format shows the minus sign itself, in front of everything.
|
||||
prefix = prefix.strip_prefix('-')?.to_string();
|
||||
}
|
||||
let decimals = core.split_once('.').map_or(0, |(_, f)| f.len());
|
||||
let mut code = String::new();
|
||||
let quote = |s: &str| if s.is_empty() { String::new() } else { format!("\"{}\"", s.replace('"', "")) };
|
||||
code.push_str("e(&prefix));
|
||||
code.push_str(if core.contains(',') { "#,##0" } else { "0" });
|
||||
if decimals > 0 {
|
||||
code.push('.');
|
||||
code.push_str(&"0".repeat(decimals.min(30)));
|
||||
}
|
||||
code.push_str("e(suffix));
|
||||
let rendered = gridcraft_numfmt::text_function(&gridcraft_core::Value::number(n), &code, gridcraft_core::date::DateSystem::D1900).ok()?;
|
||||
(normalized(&rendered) == shown).then_some(code)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_excel_and_libreoffice_cell_values() {
|
||||
let excel = r#"<html><head><style>td{mso-number-format:General}</style></head><body><table>
|
||||
<!--StartFragment--><tr height=20><td class=xl65 x:num="10000">Rp10,000.00</td><td x:str>Name</td></tr>
|
||||
<tr><td colspan=2 x:num="2.5">2.50 & up</td><td>x</td></tr><!--EndFragment--></table></body></html>"#;
|
||||
let rows = table_cells(excel);
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(rows[0][0], HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0) });
|
||||
assert_eq!(rows[0][1], HtmlCell { text: "Name".into(), num: None });
|
||||
assert_eq!(rows[1].len(), 3, "colspan keeps the next cell in its column");
|
||||
assert_eq!(rows[1][0].text, "2.50 & up");
|
||||
assert_eq!(rows[1][2].text, "x");
|
||||
|
||||
let calc = r#"<table cellspacing="0" border="0"><colgroup width="85"></colgroup><tr>
|
||||
<td height="17" align="right" sdval="10000" sdnum="1033;0;[$Rp-421]#,##0.00"><font face="Liberation Sans">Rp10,000.00</font></td></tr></table>"#;
|
||||
assert_eq!(table_cells(calc), vec![vec![HtmlCell { text: "Rp10,000.00".into(), num: Some(10000.0) }]]);
|
||||
|
||||
let quoted_gt = r#"<table><tr><td style='mso-number-format:"\[>=1000\]0"' x:num="1500">1500</td></tr></table>"#;
|
||||
assert_eq!(table_cells(quoted_gt), vec![vec![HtmlCell { text: "1500".into(), num: Some(1500.0) }]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_markup_does_not_panic() {
|
||||
for html in [
|
||||
"",
|
||||
"<",
|
||||
"<td",
|
||||
"<table><td x:num=>",
|
||||
"<table><tr><td colspan=999999999>a",
|
||||
"�&",
|
||||
"<table><td x:num='1e999'>1</td>",
|
||||
"<!--",
|
||||
"<style>",
|
||||
"<table><table><td>",
|
||||
] {
|
||||
let _ = table_cells(html);
|
||||
}
|
||||
assert_eq!(table_cells("<table><td x:num='1e999'>1</td></table>")[0][0].num, None);
|
||||
assert!(table_cells("<table><tr><td colspan=999999999>a</td></tr></table>")[0].len() <= MAX_SPAN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn infers_a_format_that_shows_the_same_text() {
|
||||
assert_eq!(format_for("Rp10,000.00", 10000.0).as_deref(), Some("\"Rp\"#,##0.00"));
|
||||
assert_eq!(format_for("1 234 kr", 1234.0), None, "space grouping is not reproduced");
|
||||
assert_eq!(format_for("10.000,00 €", 10000.0), None, "comma decimals don't render back in en-US");
|
||||
assert_eq!(format_for("-Rp5", -5.0).as_deref(), Some("\"Rp\"0"));
|
||||
assert_eq!(format_for("12 EUR", 12.0).as_deref(), Some("0\" EUR\""));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+405
-70
@@ -8,6 +8,7 @@ use gridcraft_model::*;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::*;
|
||||
use crate::outline;
|
||||
use crate::selection::current_region;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -29,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"data.filter",
|
||||
"Filter",
|
||||
["Data", "Sort & Filter"],
|
||||
Some("Cmd+Shift+F"),
|
||||
Some("Ctrl+Shift+L"),
|
||||
"{range?} toggles AutoFilter on the current region",
|
||||
has_doc,
|
||||
toggle_filter
|
||||
@@ -74,10 +75,37 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!(query "data.validate", "Check Value Against Validation", [], None, "{cell?, input} → {ok, message?}", has_doc, validate_cmd),
|
||||
cmd!(noundo "data.circleInvalid", "Circle Invalid Data", ["Data", "Data Tools", "Data Validation"], None, "{} → invalid cells", has_doc, circle_invalid),
|
||||
cmd!("data.group", "Group", ["Data", "Outline"], Some("Cmd+Shift+K"), "{rows?: \"2:5\" | cols?: \"B:C\"}", has_doc, |s, p| group(s, p, true)),
|
||||
cmd!("data.ungroup", "Ungroup", ["Data", "Outline"], Some("Cmd+Shift+J"), "{rows? | cols?}", has_doc, |s, p| group(s, p, false)),
|
||||
cmd!("data.hideDetail", "Hide Detail", ["Data", "Outline"], None, "{rows? | cols?}", has_doc, |s, p| detail(s, p, true)),
|
||||
cmd!("data.showDetail", "Show Detail", ["Data", "Outline"], None, "{rows? | cols?}", has_doc, |s, p| detail(s, p, false)),
|
||||
cmd!(
|
||||
"data.group",
|
||||
"Group",
|
||||
["Data", "Outline"],
|
||||
Some("Alt+Shift+Right"),
|
||||
"{rows?: \"2:5\" | cols?: \"B:C\" | by?: rows|cols (the selection's rows or columns; a block of cells groups rows by default)}",
|
||||
has_doc,
|
||||
|s, p| group(s, p, true)
|
||||
),
|
||||
cmd!("data.ungroup", "Ungroup", ["Data", "Outline"], Some("Alt+Shift+Left"), "{rows? | cols? | by?: rows|cols}", has_doc, |s, p| group(
|
||||
s, p, false
|
||||
)),
|
||||
cmd!(
|
||||
"data.hideDetail",
|
||||
"Hide Detail",
|
||||
["Data", "Outline"],
|
||||
None,
|
||||
"{rows? | cols? | by?, level?: 1-7} (the innermost group, or the one at `level`, holding the lines or summarised by them)",
|
||||
has_doc,
|
||||
|s, p| detail(s, p, true)
|
||||
),
|
||||
cmd!("data.showDetail", "Show Detail", ["Data", "Outline"], None, "{rows? | cols? | by?, level?: 1-7}", has_doc, |s, p| detail(s, p, false)),
|
||||
cmd!(
|
||||
"data.showLevels",
|
||||
"Show Outline Levels",
|
||||
[],
|
||||
None,
|
||||
"{rows?: 1-8, cols?: 1-8} (1 shows only the top-level summaries, as the outline's level buttons)",
|
||||
has_doc,
|
||||
show_levels
|
||||
),
|
||||
cmd!(
|
||||
"data.subtotal",
|
||||
"Subtotal",
|
||||
@@ -94,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn col_param(v: Option<&Json>, base: u32) -> Option<u32> {
|
||||
match v? {
|
||||
Json::String(s) => gridcraft_core::letters_to_col(s.trim_start_matches('$')),
|
||||
Json::Number(n) => n.as_u64().map(|o| base + o as u32),
|
||||
Json::Number(n) => n.as_u64().and_then(|o| u32::try_from(o).ok()).and_then(|o| base.checked_add(o)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -170,27 +198,29 @@ fn sort(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let header = bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r));
|
||||
let by_cols = str_param(p, "orientation") == Some("columns");
|
||||
let case = bool_param(p, "matchCase").unwrap_or(false);
|
||||
let keys: Vec<SortKey> = p
|
||||
.get("keys")
|
||||
.and_then(Json::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|k| {
|
||||
let col = if by_cols {
|
||||
k.get("row").and_then(Json::as_u64).map(|r| r as u32 - 1).or_else(|| col_param(k.get("column"), r.start.row))?
|
||||
} else {
|
||||
col_param(k.get("column"), r.start.col)?
|
||||
};
|
||||
Some(SortKey {
|
||||
col,
|
||||
desc: k.get("order").and_then(Json::as_str) == Some("desc"),
|
||||
by: k.get("by").and_then(Json::as_str).unwrap_or("values").to_string(),
|
||||
list: k.get("customList").and_then(Json::as_array).map(|l| l.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut keys: Vec<SortKey> = Vec::new();
|
||||
for k in p.get("keys").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default() {
|
||||
let col = if by_cols {
|
||||
let row = match k.get("row").and_then(Json::as_u64) {
|
||||
// Worksheet rows are 1-based; 0 (or a value past u32) has no coordinate.
|
||||
Some(n) => {
|
||||
let row = u32::try_from(n).ok().and_then(|n| n.checked_sub(1));
|
||||
Some(row.ok_or_else(|| bad("data.sort", "sort key row must be 1 or greater"))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
row.or_else(|| col_param(k.get("column"), r.start.row))
|
||||
} else {
|
||||
col_param(k.get("column"), r.start.col)
|
||||
};
|
||||
let Some(col) = col else { continue };
|
||||
keys.push(SortKey {
|
||||
col,
|
||||
desc: k.get("order").and_then(Json::as_str) == Some("desc"),
|
||||
by: k.get("by").and_then(Json::as_str).unwrap_or("values").to_string(),
|
||||
list: k.get("customList").and_then(Json::as_array).map(|l| l.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()),
|
||||
});
|
||||
}
|
||||
if keys.is_empty() {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header})));
|
||||
return ok();
|
||||
@@ -248,7 +278,7 @@ fn do_sort(s: &mut Session, r: RangeRef, header: bool, keys: Vec<SortKey>, by_co
|
||||
let pos = |v: &Value| v.as_text().and_then(|t| list.iter().position(|x| x.eq_ignore_ascii_case(t))).unwrap_or(usize::MAX);
|
||||
pos(va).cmp(&pos(vb))
|
||||
} else if case && va.is_text() && vb.is_text() {
|
||||
va.as_text().unwrap_or("").cmp(vb.as_text().unwrap_or(""))
|
||||
sort_compare(va, vb).then_with(|| case_order(va.as_text().unwrap_or(""), vb.as_text().unwrap_or("")))
|
||||
} else {
|
||||
sort_compare(va, vb)
|
||||
};
|
||||
@@ -416,6 +446,9 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) {
|
||||
t.filter_button = !t.filter_button;
|
||||
if !t.filter_button {
|
||||
t.filter.clear();
|
||||
}
|
||||
}
|
||||
Ok(Json::Null)
|
||||
});
|
||||
@@ -423,15 +456,34 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if has {
|
||||
return edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// Reveal only rows the filter hid; rows hidden by hand or by a collapsed group stay hidden.
|
||||
let filtered: Vec<u32> = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect();
|
||||
sh.autofilter = None;
|
||||
for info in sh.rows.values_mut() {
|
||||
info.hidden = false;
|
||||
for r in filtered {
|
||||
if let Some(info) = sh.rows.get_mut(&r) {
|
||||
info.hidden = false;
|
||||
}
|
||||
}
|
||||
cx.structural = true;
|
||||
Ok(json!({"filter": false}))
|
||||
});
|
||||
}
|
||||
let r = data_range(s, p)?;
|
||||
install_filter(s, p)
|
||||
}
|
||||
|
||||
/// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection.
|
||||
fn install_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
let mut r = data_range(s, p)?;
|
||||
// A selected header row filters the data below it (#201).
|
||||
if p.get("range").is_none() && r.height() == 1 {
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let below = current_region(sh, r.start).end.row;
|
||||
if below > r.end.row {
|
||||
r = RangeRef::new(r.start, CellRef::new(below, r.end.col));
|
||||
}
|
||||
}
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] });
|
||||
Ok(json!({"filter": true, "range": r.a1()}))
|
||||
@@ -444,11 +496,16 @@ fn filter_by(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let af = match &sh.autofilter {
|
||||
Some(a) => a.clone(),
|
||||
None => {
|
||||
toggle_filter(s, &json!({}))?;
|
||||
install_filter(s, &json!({}))?;
|
||||
s.doc()?.wb.sheet(sheet).and_then(|sh| sh.autofilter.clone()).ok_or_else(|| EngineError::Other("no filter".into()))?
|
||||
}
|
||||
};
|
||||
let col = col_param(p.get("column"), af.range.start.col).ok_or_else(|| bad("data.filterBy", "missing `column`"))?;
|
||||
let col = match col_param(p.get("column"), af.range.start.col) {
|
||||
Some(c) => c,
|
||||
// A number too large to be a column is outside the filter range, not a missing parameter.
|
||||
None if p.get("column").is_some_and(|v| v.as_u64().is_some()) => return Err(bad("data.filterBy", "column outside the filter range")),
|
||||
None => return Err(bad("data.filterBy", "missing `column`")),
|
||||
};
|
||||
if col < af.range.start.col || col > af.range.end.col {
|
||||
return Err(bad("data.filterBy", "column outside the filter range"));
|
||||
}
|
||||
@@ -530,19 +587,28 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
let Some(af) = sh.autofilter.clone() else { return };
|
||||
let r = af.range;
|
||||
let mut hide = Vec::new();
|
||||
// Precompute per-column numbers for top10/average.
|
||||
let mut col_stats: std::collections::HashMap<u32, (Vec<f64>, f64)> = std::collections::HashMap::new();
|
||||
for (off, c) in &af.criteria {
|
||||
// Precompute per-criterion top10 threshold and average once, not per row.
|
||||
let mut col_stats: std::collections::HashMap<usize, (Option<f64>, f64)> = std::collections::HashMap::new();
|
||||
for (i, (off, c)) in af.criteria.iter().enumerate() {
|
||||
if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) {
|
||||
let col = r.start.col + off;
|
||||
let nums: Vec<f64> = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect();
|
||||
let mut nums: Vec<f64> = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect();
|
||||
let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::<f64>() / nums.len() as f64 };
|
||||
col_stats.insert(*off, (nums, avg));
|
||||
let thr = match c {
|
||||
FilterCriterion::Top10 { bottom, percent, count } => {
|
||||
nums.sort_by(|a, b| if *bottom { a.partial_cmp(b) } else { b.partial_cmp(a) }.unwrap_or(Ordering::Equal));
|
||||
let k = if *percent { ((nums.len() as f64) * (*count as f64) / 100.0).ceil() as usize } else { *count as usize };
|
||||
let k = k.clamp(1, nums.len().max(1));
|
||||
nums.get(k - 1).copied()
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
col_stats.insert(i, (thr, avg));
|
||||
}
|
||||
}
|
||||
for row in r.start.row + 1..=r.end.row {
|
||||
let mut visible = true;
|
||||
for (off, crit) in &af.criteria {
|
||||
for (i, (off, crit)) in af.criteria.iter().enumerate() {
|
||||
let c = CellRef::new(row, r.start.col + off);
|
||||
let v = sh.value(c);
|
||||
let text = crate::display::cell_text(wb, sh, c);
|
||||
@@ -564,18 +630,14 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
None => x,
|
||||
}
|
||||
}
|
||||
FilterCriterion::Top10 { bottom, percent, count } => match (v.as_f64(), col_stats.get(off)) {
|
||||
(Some(n), Some((nums, _))) => {
|
||||
let mut sorted = nums.clone();
|
||||
sorted.sort_by(|a, b| if *bottom { a.partial_cmp(b) } else { b.partial_cmp(a) }.unwrap_or(Ordering::Equal));
|
||||
let k = if *percent { ((sorted.len() as f64) * (*count as f64) / 100.0).ceil() as usize } else { *count as usize };
|
||||
let k = k.clamp(1, sorted.len().max(1));
|
||||
let thr = sorted.get(k - 1).copied().unwrap_or(n);
|
||||
FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) {
|
||||
(Some(n), Some((thr, _))) => {
|
||||
let thr = thr.unwrap_or(n);
|
||||
if *bottom { n <= thr } else { n >= thr }
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(off)) {
|
||||
FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) {
|
||||
(Some(n), Some((_, avg))) => {
|
||||
if *above {
|
||||
n > *avg
|
||||
@@ -587,6 +649,8 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
},
|
||||
FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col,
|
||||
FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col,
|
||||
// Icons are not evaluated here: the row keeps its current visibility.
|
||||
FilterCriterion::Icon { .. } => !sh.is_row_hidden(row),
|
||||
};
|
||||
if !ok {
|
||||
visible = false;
|
||||
@@ -653,6 +717,12 @@ pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool
|
||||
seen.into_iter().map(|((_, t), on)| (t, on)).collect()
|
||||
}
|
||||
|
||||
/// Case-sensitive tie-break for text that is equal ignoring case: as in Excel, lowercase sorts
|
||||
/// before uppercase at the first letter that differs in case.
|
||||
fn case_order(a: &str, b: &str) -> Ordering {
|
||||
a.chars().zip(b.chars()).find(|(x, y)| x != y).map_or(Ordering::Equal, |(x, y)| y.is_lowercase().cmp(&x.is_lowercase()))
|
||||
}
|
||||
|
||||
fn sort_key(v: &Value) -> (u8, i64, String) {
|
||||
match v {
|
||||
Value::Number(n) => (0, (n * 1e6) as i64, String::new()),
|
||||
@@ -685,8 +755,11 @@ fn remove_duplicates(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) };
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut keep: Vec<u32> = Vec::new();
|
||||
// Cells are compared by the text they show, as in Excel: the same date in two formats
|
||||
// isn't a duplicate, while 1.01 and 1.02 shown as 1.0 are.
|
||||
let shown = |c: CellRef| crate::display::format(&sh.value(c), cx.wb.styles.get(sh.style_id(c)).num_fmt.as_str(), &cx.wb).text;
|
||||
for row in start..=r.end.row {
|
||||
let key: Vec<String> = cols.iter().map(|c| sh.value(CellRef::new(row, *c)).display().to_lowercase()).collect();
|
||||
let key: Vec<String> = cols.iter().map(|c| shown(CellRef::new(row, *c)).to_lowercase()).collect();
|
||||
if seen.insert(key) {
|
||||
keep.push(row);
|
||||
} else {
|
||||
@@ -741,7 +814,7 @@ fn text_to_columns(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
p.get("fixedWidths").and_then(Json::as_array).map(|a| a.iter().filter_map(|x| x.as_u64().map(|v| v as usize)).collect());
|
||||
let consecutive = bool_param(p, "treatConsecutive").unwrap_or(false);
|
||||
let quote = str_param(p, "textQualifier").and_then(|q| q.chars().next()).unwrap_or('"');
|
||||
let dest = cell_param(p, "destination").unwrap_or(r.start);
|
||||
let dest = cell_param_on(s, p, "destination", sheet)?.unwrap_or(r.start);
|
||||
edit(s, |cx| {
|
||||
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) };
|
||||
let mut out: Vec<(CellRef, String)> = Vec::new();
|
||||
@@ -845,7 +918,7 @@ fn subtract_range(r: RangeRef, cut: &RangeRef) -> Vec<RangeRef> {
|
||||
}
|
||||
|
||||
/// Removes the cells of `cuts` from every validation, keeping the rest of each rule's ranges.
|
||||
fn remove_validation_cells(validations: &mut Vec<Validation>, cuts: &[RangeRef]) {
|
||||
pub(super) fn remove_validation_cells(validations: &mut Vec<Validation>, cuts: &[RangeRef]) {
|
||||
for dv in validations.iter_mut() {
|
||||
for cut in cuts {
|
||||
dv.ranges = dv.ranges.iter().flat_map(|r| subtract_range(*r, cut)).collect();
|
||||
@@ -934,10 +1007,26 @@ pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -
|
||||
return None;
|
||||
}
|
||||
let v = gridcraft_core::parse::parse_input(input, wb.date_system).value;
|
||||
let num = |f: &str| gridcraft_calc::evaluate(wb, sheet, at, f).to_number().ok();
|
||||
// The formulas are written for the first cell of the range and see the value being entered,
|
||||
// as in Excel (a custom `=A1>10` on A1:A9 checks A5's new value at A5).
|
||||
let first = dv.ranges.first().map(|r| r.start).unwrap_or(at);
|
||||
let entered;
|
||||
let wb = if sh.value(at) == v {
|
||||
wb
|
||||
} else {
|
||||
let mut w = wb.clone();
|
||||
if let Some(sh) = w.sheet_mut(sheet) {
|
||||
let style = sh.style_id(at);
|
||||
sh.cells.set(at, Cell { value: v.clone(), style, ..Default::default() });
|
||||
}
|
||||
entered = w;
|
||||
&entered
|
||||
};
|
||||
let eval = |f: &str| gridcraft_calc::evaluate(wb, sheet, at, &formula_at(f, first, at));
|
||||
let num = |f: &str| eval(f).to_number().ok();
|
||||
let ok = match dv.kind {
|
||||
ValidationKind::List => list_items(wb, sheet, dv).iter().any(|x| x.eq_ignore_ascii_case(input)),
|
||||
ValidationKind::Custom => gridcraft_calc::evaluate(wb, sheet, at, &dv.f1).to_bool().unwrap_or(false),
|
||||
ValidationKind::Custom => eval(&dv.f1).to_bool().unwrap_or(false),
|
||||
ValidationKind::TextLength => {
|
||||
let n = input.chars().count() as f64;
|
||||
compare_op(dv.op, n, num(&dv.f1), dv.f2.as_deref().and_then(num))
|
||||
@@ -964,6 +1053,33 @@ pub fn check_validation(wb: &Workbook, sheet: usize, at: CellRef, input: &str) -
|
||||
Some((dv.clone(), msg))
|
||||
}
|
||||
|
||||
/// A formula written for `first`, as seen from `at` (relative references shifted).
|
||||
fn formula_at(f: &str, first: CellRef, at: CellRef) -> String {
|
||||
if first == at {
|
||||
return f.to_string();
|
||||
}
|
||||
match gridcraft_formula::parse(f.trim_start_matches('=')) {
|
||||
Ok(e) => gridcraft_formula::print(&gridcraft_formula::adjust::shift_relative(
|
||||
e,
|
||||
at.row as i64 - first.row as i64,
|
||||
at.col as i64 - first.col as i64,
|
||||
)),
|
||||
Err(_) => f.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the relative references of a rule formula written for `first` so it reads the same cells from `to`
|
||||
/// (pasting a rule); text without relative references (constants, literal lists) stays as typed.
|
||||
pub(super) fn move_rule_formula(f: &str, first: CellRef, to: CellRef) -> String {
|
||||
if first == to {
|
||||
return f.to_string();
|
||||
}
|
||||
let moved = formula_at(f, first, to);
|
||||
let has_relative = gridcraft_formula::parse(f.trim_start_matches('=')).is_ok_and(|e| gridcraft_formula::print(&e) != moved);
|
||||
let eq = if f.starts_with('=') { "=" } else { "" };
|
||||
if has_relative { format!("{eq}{moved}") } else { f.to_string() }
|
||||
}
|
||||
|
||||
fn compare_op(op: CfOperator, n: f64, a: Option<f64>, b: Option<f64>) -> bool {
|
||||
let Some(a) = a else { return false };
|
||||
match op {
|
||||
@@ -980,7 +1096,7 @@ fn compare_op(op: CfOperator, n: f64, a: Option<f64>, b: Option<f64>) -> bool {
|
||||
|
||||
fn validate_cmd(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let input = str_param(p, "input").unwrap_or("");
|
||||
match check_validation(&d.wb, d.wb.active_sheet, at, input) {
|
||||
None => Ok(json!({"ok": true})),
|
||||
@@ -1018,7 +1134,12 @@ fn outline_lines(s: &Session, p: &Json) -> Result<(bool, u32, u32)> {
|
||||
return Ok((false, r.start.col, r.end.col));
|
||||
}
|
||||
let r = s.doc()?.selection.current();
|
||||
if r.is_full_cols() && !r.is_full_rows() { Ok((false, r.start.col, r.end.col)) } else { Ok((true, r.start.row, r.end.row)) }
|
||||
match str_param(p, "by") {
|
||||
Some("rows") => Ok((true, r.start.row, r.end.row)),
|
||||
Some("cols" | "columns") => Ok((false, r.start.col, r.end.col)),
|
||||
_ if r.is_full_cols() && !r.is_full_rows() => Ok((false, r.start.col, r.end.col)),
|
||||
_ => Ok((true, r.start.row, r.end.row)),
|
||||
}
|
||||
}
|
||||
|
||||
fn group(s: &mut Session, p: &Json, on: bool) -> Result<Json> {
|
||||
@@ -1027,39 +1148,95 @@ fn group(s: &mut Session, p: &Json, on: bool) -> Result<Json> {
|
||||
let si = cx.sheet_index();
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
let map = if rows { &mut sh.rows } else { &mut sh.cols };
|
||||
for i in a..=b.min(a + 1_048_575) {
|
||||
let b = b.min(a.saturating_add(1_048_575));
|
||||
for i in a..=b {
|
||||
let e = map.entry(i).or_default();
|
||||
e.outline = if on { (e.outline + 1).min(7) } else { e.outline.saturating_sub(1) };
|
||||
e.outline = if on { (e.outline + 1).min(outline::MAX_LEVEL) } else { e.outline.saturating_sub(1) };
|
||||
if !on && e.outline == 0 {
|
||||
e.hidden = false;
|
||||
}
|
||||
}
|
||||
// A summary line whose group is gone has nothing left to collapse.
|
||||
if !on
|
||||
&& !outline::groups(map).iter().any(|g| g.end == b)
|
||||
&& let Some(e) = map.get_mut(&b.saturating_add(1))
|
||||
{
|
||||
e.collapsed = false;
|
||||
}
|
||||
cx.structural = true; // ungrouping reveals hidden rows: SUBTOTAL(10x) depends on it
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
/// Hide Detail / Show Detail: the innermost group (or the one at `level`) that holds the lines, or
|
||||
/// failing that the one they are the summary of. Hiding marks the summary line collapsed (the
|
||||
/// + button, saved to XLSX); showing keeps inner groups that were collapsed on their own collapsed.
|
||||
fn detail(s: &mut Session, p: &Json, hide: bool) -> Result<Json> {
|
||||
let (rows, a, b) = outline_lines(s, p)?;
|
||||
let want = p.get("level").and_then(Json::as_u64).map(|l| l.min(outline::MAX_LEVEL as u64) as u8);
|
||||
edit(s, |cx| {
|
||||
let si = cx.sheet_index();
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
let map = if rows { &mut sh.rows } else { &mut sh.cols };
|
||||
// Expand to the whole group around the selection.
|
||||
let level = (a..=b).filter_map(|i| map.get(&i).map(|e| e.outline)).max().unwrap_or(0);
|
||||
if level == 0 {
|
||||
return Ok(Json::Null);
|
||||
let all = outline::groups(map);
|
||||
let level_ok = |g: &outline::OutlineGroup| want.is_none_or(|l| g.level == l);
|
||||
let pick = |hit: &dyn Fn(&outline::OutlineGroup) -> bool| -> Vec<outline::OutlineGroup> {
|
||||
let hits: Vec<_> = all.iter().filter(|g| level_ok(g) && hit(g)).copied().collect();
|
||||
let deepest = hits.iter().map(|g| g.level).max().unwrap_or(0);
|
||||
hits.into_iter().filter(|g| g.level == deepest).collect()
|
||||
};
|
||||
let mut chosen = pick(&|g| g.start <= b && g.end >= a);
|
||||
if chosen.is_empty() {
|
||||
chosen = pick(&|g| g.summary() >= a && g.summary() <= b);
|
||||
}
|
||||
let mut lo = a;
|
||||
while lo > 0 && map.get(&(lo - 1)).is_some_and(|e| e.outline >= level) {
|
||||
lo -= 1;
|
||||
for g in chosen {
|
||||
// Inner groups collapsed on their own (their summary marked), before this one changes.
|
||||
let inner: Vec<outline::OutlineGroup> = all
|
||||
.iter()
|
||||
.filter(|o| o.level > g.level && o.start >= g.start && o.end <= g.end && o.summary() != g.summary())
|
||||
.filter(|o| map.get(&o.summary()).is_some_and(|e| e.collapsed))
|
||||
.copied()
|
||||
.collect();
|
||||
for i in g.start..=g.end {
|
||||
if let Some(e) = map.get_mut(&i) {
|
||||
e.hidden = hide || inner.iter().any(|o| o.contains(i));
|
||||
}
|
||||
}
|
||||
if hide {
|
||||
map.entry(g.summary()).or_default().collapsed = true;
|
||||
} else if let Some(e) = map.get_mut(&g.summary()) {
|
||||
e.collapsed = false;
|
||||
}
|
||||
}
|
||||
let mut hi = b;
|
||||
while map.get(&(hi + 1)).is_some_and(|e| e.outline >= level) {
|
||||
hi += 1;
|
||||
}
|
||||
for i in lo..=hi {
|
||||
if let Some(e) = map.get_mut(&i) {
|
||||
e.hidden = hide;
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
/// The outline's level buttons: show rows / columns down to outline level `n` (1 = only the
|
||||
/// top-level summaries); deeper detail is hidden and its summary lines marked collapsed.
|
||||
fn show_levels(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let level = |k: &str| p.get(k).and_then(Json::as_u64).map(|n| n.clamp(1, outline::MAX_LEVEL as u64 + 1) as u8);
|
||||
let (rows, cols) = (level("rows"), level("cols"));
|
||||
if rows.is_none() && cols.is_none() {
|
||||
return Err(EngineError::BadParams {
|
||||
cmd: "data.showLevels".into(),
|
||||
msg: "give `rows` or `cols`: the outline level to show (1 = top-level summaries only)".into(),
|
||||
});
|
||||
}
|
||||
edit(s, |cx| {
|
||||
let si = cx.sheet_index();
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
for (map, n) in [(&mut sh.rows, rows), (&mut sh.cols, cols)] {
|
||||
let Some(n) = n else { continue };
|
||||
let groups = outline::groups(map);
|
||||
for e in map.values_mut().filter(|e| e.outline > 0) {
|
||||
e.hidden = e.outline >= n;
|
||||
}
|
||||
// Inner groups come first, so a summary line shared with the group around it ends up
|
||||
// as that outer group says.
|
||||
for g in groups {
|
||||
map.entry(g.summary()).or_default().collapsed = g.level >= n;
|
||||
}
|
||||
}
|
||||
cx.structural = true;
|
||||
@@ -1136,6 +1313,38 @@ fn subtotal(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn filter_by_huge_numeric_column_is_rejected_not_overflowed() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "B1", "values": [["Name", "Qty"], ["a", 1], ["b", 2]]})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "B1:C3"})).unwrap();
|
||||
for col in [json!(2), json!(u64::from(u32::MAX)), json!(u64::MAX)] {
|
||||
let err = s.execute("data.filterBy", json!({"column": col, "values": ["a"]})).unwrap_err();
|
||||
assert!(err.to_string().contains("column outside the filter range"), "{col}: {err}");
|
||||
}
|
||||
let ok = s.execute("data.filterBy", json!({"column": 0, "values": ["a"]})).unwrap();
|
||||
assert_eq!(ok["hiddenRows"], json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_by_inside_a_table_installs_the_autofilter_and_keeps_the_button() {
|
||||
for sel in [json!({"cell": "A1"}), json!({"cell": "A2"}), json!({"range": "A1:A3"})] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:A3", "header": true})).unwrap();
|
||||
s.execute("selection.set", sel.clone()).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "A", "values": ["a"]})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.autofilter.as_ref().map(|a| a.range.a1()), Some("A1:A3".to_string()), "{sel}");
|
||||
assert!(sh.tables[0].filter_button, "{sel}");
|
||||
assert!(!sh.is_row_hidden(1), "{sel}");
|
||||
assert!(sh.is_row_hidden(2), "{sel}");
|
||||
assert_eq!(sh.value(CellRef::new(2, 0)).display(), "b", "{sel}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_validation_edits_keep_the_rest_of_the_old_rule() {
|
||||
let mut s = Session::new();
|
||||
@@ -1158,6 +1367,132 @@ mod tests {
|
||||
assert!(!ok(&mut s, "B1", "150"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_an_autofilter_keeps_manually_hidden_and_collapsed_rows() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"], ["c"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A10", "values": [["z"]]})).unwrap();
|
||||
s.execute("data.group", json!({"rows": "2:4"})).unwrap();
|
||||
s.execute("data.hideDetail", json!({"rows": "2:4"})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows": "10:10"})).unwrap();
|
||||
let hidden = |s: &Session| -> Vec<u32> {
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
sh.rows.iter().filter(|(_, l)| l.hidden).map(|(r, _)| *r).collect()
|
||||
};
|
||||
let before = hidden(&s);
|
||||
assert_eq!(before, [1, 2, 3, 9]);
|
||||
s.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none());
|
||||
assert_eq!(hidden(&s), before);
|
||||
assert_eq!(row_state(&s, 4..=4), [(false, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_dropdown_setup_outside_the_table_keeps_manually_hidden_rows() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["H"], ["a"], ["b"], ["c"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A10", "values": [["z"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:A4", "header": true})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows": "3:3"})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows": "10:10"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "E1"})).unwrap();
|
||||
// The table filter dropdown installs an AutoFilter on demand by toggling `data.filter` twice.
|
||||
s.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.rows.iter().filter(|(_, l)| l.hidden).map(|(r, _)| *r).collect::<Vec<_>>(), [2, 9]);
|
||||
}
|
||||
|
||||
/// Rows 5:8 grouped, with 6:7 grouped again inside (0-based 4..=7 and 5..=6).
|
||||
fn nested_rows() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("data.group", json!({"rows": "5:8"})).unwrap();
|
||||
s.execute("data.group", json!({"rows": "6:7"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// (hidden, collapsed) of 0-based rows.
|
||||
fn row_state(s: &Session, rows: std::ops::RangeInclusive<u32>) -> Vec<(bool, bool)> {
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
rows.map(|r| sh.rows.get(&r).map(|l| (l.hidden, l.collapsed)).unwrap_or_default()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_detail_marks_the_summary_collapsed_and_show_detail_keeps_inner_groups_collapsed() {
|
||||
let mut s = nested_rows();
|
||||
s.execute("data.hideDetail", json!({"rows": "6:7", "level": 2})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]);
|
||||
s.execute("data.hideDetail", json!({"rows": "5:8", "level": 1})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]);
|
||||
s.execute("data.showDetail", json!({"rows": "5:8", "level": 1})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]);
|
||||
s.execute("data.showDetail", json!({"rows": "6:7", "level": 2})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(false, false); 5]);
|
||||
// Each step is one undoable command.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(row_state(&s, 5..=7), [(true, false), (true, false), (false, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_detail_on_the_summary_row_collapses_the_group_above_it() {
|
||||
let mut s = nested_rows();
|
||||
s.execute("data.hideDetail", json!({"rows": "9:9"})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, false), (false, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_levels_collapses_and_expands_to_a_level() {
|
||||
let mut s = nested_rows();
|
||||
s.execute("data.showLevels", json!({"rows": 1})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(true, false), (true, false), (true, false), (true, true), (false, true)]);
|
||||
s.execute("data.showLevels", json!({"rows": 2})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(false, false), (true, false), (true, false), (false, true), (false, false)]);
|
||||
s.execute("data.showLevels", json!({"rows": 3})).unwrap();
|
||||
assert_eq!(row_state(&s, 4..=8), [(false, false); 5]);
|
||||
// Columns are separate; no level at all is an error rather than a guess.
|
||||
s.execute("data.group", json!({"cols": "C:E"})).unwrap();
|
||||
s.execute("data.showLevels", json!({"cols": 1})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!((2..=4).all(|c| sh.cols.get(&c).is_some_and(|l| l.hidden)));
|
||||
assert!(sh.cols.get(&5).is_some_and(|l| l.collapsed));
|
||||
assert_eq!(row_state(&s, 4..=4), [(false, false)]);
|
||||
assert!(s.execute("data.showLevels", json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_by_columns_for_a_block_of_cells() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
|
||||
s.execute("data.group", json!({"by": "cols"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!((1..=2).all(|c| sh.cols.get(&c).is_some_and(|l| l.outline == 1)));
|
||||
assert!(sh.rows.values().all(|l| l.outline == 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_shortcuts_are_the_windows_ones() {
|
||||
let sc = |id: &str| specs().into_iter().find(|c| c.id == id).and_then(|c| c.shortcut);
|
||||
assert_eq!(sc("data.group"), Some("Alt+Shift+Right"));
|
||||
assert_eq!(sc("data.ungroup"), Some("Alt+Shift+Left"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_sort_rejects_row_key_zero_without_panicking() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "2"})).unwrap();
|
||||
for row in [0u64, 1 << 32] {
|
||||
let params = json!({"range": "A1:B2", "header": false, "orientation": "columns", "keys": [{"row": row}]});
|
||||
let err = s.execute("data.sort", params).unwrap_err();
|
||||
assert!(matches!(err, EngineError::BadParams { .. }), "row {row}: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split() {
|
||||
assert_eq!(split_delimited("a,b,,c", &[','], false, '"'), ["a", "b", "", "c"]);
|
||||
|
||||
@@ -94,6 +94,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fill: Color::from_hex(&format!("#{:02X}0000", width.round().clamp(0.0, 255.0) as u8)).unwrap_or_default(),
|
||||
line: Color::from_hex(&color).unwrap_or(Color::rgb(0x1F, 0x5F, 0xC9)),
|
||||
text,
|
||||
format: Default::default(),
|
||||
};
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(si)?.shapes.push(shape);
|
||||
|
||||
+277
-45
@@ -1,6 +1,6 @@
|
||||
//! Cell entry, selection, undo/redo, clipboard, clear, fill, find & replace.
|
||||
|
||||
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
|
||||
use gridcraft_core::{CellRef, MAX_ROWS, RangeRef, Value};
|
||||
use gridcraft_model::{Cell, Formula, StyleId};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Home", "Clipboard"],
|
||||
Some("Cmd+V"),
|
||||
"{at?: \"C3\", text?: \"tab-separated text from the system clipboard\"}",
|
||||
"{at?: \"C3\", text?: \"tab-separated text from the system clipboard\", html?: \"the clipboard's HTML flavour; cells the source recorded as numbers (x:num, sdval) stay numbers\"}",
|
||||
has_doc,
|
||||
paste
|
||||
),
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"AutoFill",
|
||||
[],
|
||||
None,
|
||||
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|copy|formats|values}: the fill-handle drag",
|
||||
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies)",
|
||||
has_doc,
|
||||
auto_fill
|
||||
),
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
fill_series
|
||||
),
|
||||
cmd!("edit.flashFill", "Flash Fill", ["Home", "Editing", "Fill"], Some("Cmd+E"), "{range?}", has_doc, flash_fill),
|
||||
cmd!("edit.flashFill", "Flash Fill", ["Home", "Editing", "Fill"], Some("Ctrl+E"), "{range?}", has_doc, flash_fill),
|
||||
cmd!(noundo "edit.find", "Find…", ["Home", "Editing", "Find & Select"], Some("Cmd+F"), "{what, matchCase?, wholeCell?, lookIn?: formulas|values, byColumns?, all?: bool, within?: sheet|workbook}", has_doc, find),
|
||||
cmd!(
|
||||
"edit.replace",
|
||||
@@ -150,6 +150,7 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
|
||||
}
|
||||
let expr = parsed.map_err(|e| EngineError::Other(format!("There's a problem with this formula: {e}")))?;
|
||||
let expr = wb.name_call_case(expr);
|
||||
check_arg_counts(&expr)?;
|
||||
let mut cell = Cell::formula(Formula::from_expr(expr));
|
||||
cell.style = style;
|
||||
// Formulas whose result is a date/time get a format from functions like TODAY().
|
||||
@@ -190,24 +191,56 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
|
||||
Ok(Some(Cell { value: parsed.value, formula: None, style }))
|
||||
}
|
||||
|
||||
/// Like Excel, a formula that calls a built-in function with too few or too many arguments is
|
||||
/// refused when it's entered, rather than stored to show `#VALUE!`. Functions the registry doesn't
|
||||
/// hold (special forms like LET, LAMBDA, OFFSET, INDIRECT, SUBTOTAL), defined LAMBDA names and
|
||||
/// unknown functions are skipped.
|
||||
fn check_arg_counts(expr: &gridcraft_formula::Expr) -> Result<()> {
|
||||
let mut bad = None;
|
||||
expr.walk(&mut |e| {
|
||||
if bad.is_none()
|
||||
&& let gridcraft_formula::Expr::Call(name, args) = e
|
||||
&& let Some(spec) = gridcraft_functions::lookup(name)
|
||||
&& !spec.accepts(args.len())
|
||||
{
|
||||
let few = args.len() < spec.min_args;
|
||||
bad = Some(format!("{} has too {} arguments. Use {}", spec.name, if few { "few" } else { "many" }, spec.signature));
|
||||
}
|
||||
});
|
||||
match bad {
|
||||
Some(msg) => Err(EngineError::Other(msg)),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn cell_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = match cell_param(p, "cell") {
|
||||
let at = match cell_param_on(s, p, "cell", sheet)? {
|
||||
Some(c) => c,
|
||||
None => s.doc()?.selection.active,
|
||||
};
|
||||
let input =
|
||||
str_param(p, "input").or_else(|| str_param(p, "value")).map(str::to_string).or_else(|| p.get("value").map(json_to_input)).unwrap_or_default();
|
||||
// Both spellings take a string, number or boolean, as typed (#697).
|
||||
let input = p.get("input").or_else(|| p.get("value")).map(json_to_input).ok_or_else(|| bad("cell.set", "missing `input` (or `value`)"))?;
|
||||
let array = bool_param(p, "array").unwrap_or(false);
|
||||
let protected =
|
||||
s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.is_protected() && s.doc().is_ok_and(|d| d.wb.styles.get(sh.style_id(at)).protection.locked));
|
||||
if protected {
|
||||
return Err(EngineError::Other("The cell or chart you're trying to change is on a protected sheet.".into()));
|
||||
let d = s.doc()?;
|
||||
if let Some(sh) = d.wb.sheet(sheet)
|
||||
&& sh.is_protected()
|
||||
&& d.wb.styles.get(sh.style_id(at)).protection.locked
|
||||
&& let Some(m) = locked_cell_error(sh, at, &d.unlocked_ranges)
|
||||
{
|
||||
return Err(EngineError::Other(m));
|
||||
}
|
||||
let active_sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
if array {
|
||||
// Legacy Ctrl+Shift+Enter array formula over the selection.
|
||||
let range = cx.sel.current();
|
||||
// Legacy Ctrl+Shift+Enter array formula over the selection, when the selection holds
|
||||
// the cell; a cell elsewhere (or on another sheet) gets a one-cell array.
|
||||
let selected = cx.sel.current();
|
||||
let range = if sheet == active_sheet && selected.contains(at) { selected } else { RangeRef::cell(at) };
|
||||
// A table header can't hold an array's value, and a table resizes under it.
|
||||
if !range.is_single() && cx.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.range.intersects(&range))) {
|
||||
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
|
||||
}
|
||||
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
|
||||
if let Some(f) = cell.formula.as_mut() {
|
||||
std::sync::Arc::make_mut(f).array = Some(range);
|
||||
@@ -340,8 +373,9 @@ fn selection_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
s.doc_mut()?.wb_switch_sheet(i);
|
||||
}
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let active = cell_param(s, p, "active")?;
|
||||
let d = s.doc_mut()?;
|
||||
let active = cell_param(p, "active").or_else(|| ranges.last().map(|r| r.start)).unwrap_or_default();
|
||||
let active = active.or_else(|| ranges.last().map(|r| r.start)).unwrap_or_default();
|
||||
let mut sel = crate::Selection { active, anchor: ranges.last().map(|r| r.start).unwrap_or(active), ranges };
|
||||
if let Some(sh) = d.wb.active() {
|
||||
sel.expand_merges(sh);
|
||||
@@ -383,14 +417,7 @@ fn selection_move(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let Some(sheet) = d.wb.active() else { return Err(EngineError::NoDocument) };
|
||||
let sel = &mut d.selection;
|
||||
// Extension moves the far corner, not the active cell.
|
||||
let from = if extend {
|
||||
let r = sel.current();
|
||||
let far_row = if sel.anchor.row == r.start.row { r.end.row } else { r.start.row };
|
||||
let far_col = if sel.anchor.col == r.start.col { r.end.col } else { r.start.col };
|
||||
CellRef::new(far_row, far_col)
|
||||
} else {
|
||||
sel.active
|
||||
};
|
||||
let from = if extend { sel.moving_end() } else { sel.active };
|
||||
// Skip hidden rows/columns and step over merged areas.
|
||||
let mut to = if jmp {
|
||||
jump(sheet, from, dr.signum(), dc.signum())
|
||||
@@ -408,9 +435,9 @@ fn selection_move(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if !extend && let Some(m) = sheet.merge_at(from) {
|
||||
// Leaving a merged cell moves from its edge.
|
||||
if dr > 0 {
|
||||
t = CellRef::new((m.end.row + dr as u32).min(MAX_ROWS - 1), from.col);
|
||||
t = CellRef::new(m.end.offset_clamped(dr, 0).row, from.col);
|
||||
} else if dc > 0 {
|
||||
t = CellRef::new(from.row, (m.end.col + dc as u32).min(MAX_COLS - 1));
|
||||
t = CellRef::new(from.row, m.end.offset_clamped(0, dc).col);
|
||||
}
|
||||
}
|
||||
t
|
||||
@@ -476,7 +503,7 @@ fn select_col(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
Ok(json!({"selection": d.selection.a1()}))
|
||||
}
|
||||
|
||||
fn go_to(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
pub(super) fn go_to(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let Some(reference) = str_param(p, "reference").or_else(|| str_param(p, "range")) else { return Err(bad("edit.goTo", "missing `reference`")) };
|
||||
// A defined name or table?
|
||||
let d = s.doc()?;
|
||||
@@ -571,6 +598,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let steps = u32_param(p, "steps").unwrap_or(1).max(1);
|
||||
let d = s.doc_mut()?;
|
||||
let mut label = String::new();
|
||||
let now = d.wb.clone();
|
||||
for _ in 0..steps {
|
||||
let Some(e) = d.undo.pop() else { break };
|
||||
let cur = crate::HistoryEntry { label: e.label.clone(), wb: d.wb.clone(), selection: d.selection.clone() };
|
||||
@@ -579,6 +607,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.wb = e.wb;
|
||||
d.selection = e.selection;
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
d.calc.rebuild(&d.wb);
|
||||
d.revision += 1;
|
||||
Ok(json!({"undone": label}))
|
||||
@@ -588,6 +617,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let steps = u32_param(p, "steps").unwrap_or(1).max(1);
|
||||
let d = s.doc_mut()?;
|
||||
let mut label = String::new();
|
||||
let now = d.wb.clone();
|
||||
for _ in 0..steps {
|
||||
let Some(e) = d.redo.pop() else { break };
|
||||
let cur = crate::HistoryEntry { label: e.label.clone(), wb: d.wb.clone(), selection: d.selection.clone() };
|
||||
@@ -596,6 +626,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.wb = e.wb;
|
||||
d.selection = e.selection;
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
d.calc.rebuild(&d.wb);
|
||||
d.revision += 1;
|
||||
Ok(json!({"redone": label}))
|
||||
@@ -604,25 +635,36 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
// ---------------------------------------------------------------- clipboard
|
||||
|
||||
fn copy_impl(s: &mut Session, p: &Json, cut: bool) -> Result<Json> {
|
||||
let multiple = || EngineError::Other("This action won't work on multiple selections.".into());
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let ranges = target_ranges(s, p)?;
|
||||
if ranges.len() > 1 {
|
||||
return Err(EngineError::Other("This action won't work on multiple selections.".into()));
|
||||
if ranges.len() > 1 && cut {
|
||||
return Err(multiple());
|
||||
}
|
||||
let range = ranges.first().copied().unwrap_or_default();
|
||||
// The selection as made (untrimmed), for Insert Copied Cells.
|
||||
let selected = ranges.first().copied().unwrap_or_default();
|
||||
let d = s.doc()?;
|
||||
let Some(sh) = d.wb.sheet(sheet) else { return Err(EngineError::NoDocument) };
|
||||
let range = if range.is_full_cols() || range.is_full_rows() {
|
||||
let used = sh.used_range().unwrap_or(RangeRef::cell(range.start));
|
||||
range.intersection(&used.union(&RangeRef::cell(range.start))).unwrap_or(range)
|
||||
} else {
|
||||
range
|
||||
let trim = |range: RangeRef| {
|
||||
if range.is_full_cols() || range.is_full_rows() {
|
||||
let used = sh.used_range().unwrap_or(RangeRef::cell(range.start));
|
||||
range.intersection(&used.union(&RangeRef::cell(range.start))).unwrap_or(range)
|
||||
} else {
|
||||
range
|
||||
}
|
||||
};
|
||||
let text = crate::display::range_text(&d.wb, sheet, range);
|
||||
let (wb, range, areas) = if ranges.len() > 1 {
|
||||
let areas: Vec<RangeRef> = ranges.iter().map(|r| trim(*r)).collect();
|
||||
let (wb, block) = slide_together(&d.wb, sheet, &areas).ok_or_else(multiple)?;
|
||||
(std::sync::Arc::new(wb), block, areas)
|
||||
} else {
|
||||
(d.wb.clone(), trim(ranges.first().copied().unwrap_or_default()), Vec::new())
|
||||
};
|
||||
let text = crate::display::range_text(&wb, sheet, range);
|
||||
// The HTML rendering is for the host clipboard (UI); it can reach 4 MB, so agents and
|
||||
// scripts get it only when they ask for it.
|
||||
let html = if p.get("html").and_then(Json::as_bool) == Some(true) { crate::io::range_html(&d.wb, sheet, range, &text) } else { None };
|
||||
let clip = Clipboard { wb: d.wb.clone(), sheet, range, cut, doc_uid: d.uid, text: text.clone() };
|
||||
let html = if p.get("html").and_then(Json::as_bool) == Some(true) { crate::io::range_html(&wb, sheet, range, &text) } else { None };
|
||||
let clip = Clipboard { wb, sheet, range, cut, doc_uid: d.uid, text: text.clone(), areas, selected };
|
||||
s.clipboard = Some(clip);
|
||||
let mut result = json!({"range": range.a1(), "text": text});
|
||||
if let Some(html) = html {
|
||||
@@ -631,6 +673,83 @@ fn copy_impl(s: &mut Session, p: &Json, cut: bool) -> Result<Json> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Excel copies a multi-area selection only when the areas line up: all cover the same rows (they
|
||||
/// slide together side by side, left to right) or all cover the same columns (stacked, top to
|
||||
/// bottom), without overlapping. Returns a copy of the workbook whose sheet holds the areas packed
|
||||
/// into one block at the first area's place, and that block. Formulas travel as their values, as
|
||||
/// in Excel. `None` when the areas don't line up.
|
||||
fn slide_together(wb: &gridcraft_model::Workbook, sheet: usize, areas: &[RangeRef]) -> Option<(gridcraft_model::Workbook, RangeRef)> {
|
||||
let first = *areas.first()?;
|
||||
let across = areas.iter().all(|a| a.start.row == first.start.row && a.end.row == first.end.row);
|
||||
let down = areas.iter().all(|a| a.start.col == first.start.col && a.end.col == first.end.col);
|
||||
let mut sorted = areas.to_vec();
|
||||
if across {
|
||||
sorted.sort_by_key(|a| a.start.col);
|
||||
} else if down {
|
||||
sorted.sort_by_key(|a| a.start.row);
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
if sorted.windows(2).any(|w| matches!(w, [a, b] if a.intersects(b))) {
|
||||
return None;
|
||||
}
|
||||
let anchor = sorted.first()?.start;
|
||||
let (h, w) = if across {
|
||||
(first.height(), sorted.iter().map(RangeRef::width).fold(0u32, u32::saturating_add))
|
||||
} else {
|
||||
(sorted.iter().map(RangeRef::height).fold(0u32, u32::saturating_add), first.width())
|
||||
};
|
||||
let block = RangeRef::new(anchor, anchor.offset(i64::from(h) - 1, i64::from(w) - 1)?);
|
||||
let src = wb.sheet(sheet)?;
|
||||
let mut out = wb.clone();
|
||||
let dst = out.sheet_mut(sheet)?;
|
||||
dst.take_cells(block);
|
||||
dst.spill.retain(|c, _| !block.contains(*c));
|
||||
dst.spill_ranges.retain(|c, _| !block.contains(*c));
|
||||
dst.comments.retain(|c, _| !block.contains(*c));
|
||||
dst.merges.retain(|m| !m.intersects(&block));
|
||||
if across {
|
||||
dst.cols.retain(|c, _| !(block.start.col..=block.end.col).contains(c));
|
||||
} else {
|
||||
dst.rows.retain(|r, _| !(block.start.row..=block.end.row).contains(r));
|
||||
}
|
||||
let mut next = if across { anchor.col } else { anchor.row };
|
||||
for a in &sorted {
|
||||
let (dr, dc) = if across { (0, i64::from(next) - i64::from(a.start.col)) } else { (i64::from(next) - i64::from(a.start.row), 0) };
|
||||
let cells = src.cells.iter_range(*a).map(|(c, _)| c).chain(src.spill.keys().copied().filter(|c| a.contains(*c)));
|
||||
for c in cells {
|
||||
let Some(to) = c.offset(dr, dc) else { continue };
|
||||
let style = src.cell(c).map(|x| x.style).unwrap_or_default();
|
||||
dst.set_cell(to, Cell { value: src.value(c), formula: None, style });
|
||||
if let Some(picture) = src.cell_pictures.get(&c) {
|
||||
dst.cell_pictures.insert(to, picture.clone());
|
||||
}
|
||||
}
|
||||
for (c, comment) in src.comments.iter().filter(|(c, _)| a.contains(**c)) {
|
||||
if let Some(to) = c.offset(dr, dc) {
|
||||
dst.comments.insert(to, comment.clone());
|
||||
}
|
||||
}
|
||||
for m in src.merges.iter().filter(|m| a.contains_range(m)) {
|
||||
if let (Some(s), Some(e)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) {
|
||||
dst.merges.push(RangeRef::new(s, e));
|
||||
}
|
||||
}
|
||||
// Column widths (side by side) or row heights and hidden rows (stacked) follow their cells.
|
||||
if across {
|
||||
for (c, info) in src.cols.range(a.start.col..=a.end.col) {
|
||||
dst.cols.insert(next.saturating_add(c.saturating_sub(a.start.col)), *info);
|
||||
}
|
||||
} else {
|
||||
for (r, info) in src.rows.range(a.start.row..=a.end.row) {
|
||||
dst.rows.insert(next.saturating_add(r.saturating_sub(a.start.row)), *info);
|
||||
}
|
||||
}
|
||||
next = next.saturating_add(if across { a.width() } else { a.height() });
|
||||
}
|
||||
Some((out, block))
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
copy_impl(s, p, false)
|
||||
}
|
||||
@@ -672,15 +791,20 @@ fn paste(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn paste_text(s: &mut Session, p: &Json, text: &str) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param(p, "at").unwrap_or(s.doc()?.selection.current().start);
|
||||
let at = cell_param_on(s, p, "at", sheet)?.unwrap_or(s.doc()?.selection.current().start);
|
||||
let rows: Vec<Vec<String>> = parse_tsv(text);
|
||||
// The HTML flavour, when the host passed it: the number behind each cell's shown text.
|
||||
let html = str_param(p, "html").map(crate::clip_html::table_cells).unwrap_or_default();
|
||||
let h = rows.len();
|
||||
let w = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
edit(s, |cx| {
|
||||
for (ri, row) in rows.iter().enumerate() {
|
||||
for (ci, v) in row.iter().enumerate() {
|
||||
let Some(c) = at.offset(ri as i64, ci as i64) else { continue };
|
||||
let cell = input_to_cell(v, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(v.as_str()))));
|
||||
let mut cell = input_to_cell(v, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(v.as_str()))));
|
||||
if let Some(cl) = cell.as_mut() {
|
||||
numeric_from_html(cl, v, html.get(ri).and_then(|r| r.get(ci)), &mut cx.wb);
|
||||
}
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
match cell {
|
||||
Some(cell) => sh.set_cell(c, cell),
|
||||
@@ -700,6 +824,27 @@ fn paste_text(s: &mut Session, p: &Json, text: &str) -> Result<Json> {
|
||||
Ok(json!({"rows": h, "cols": w}))
|
||||
}
|
||||
|
||||
/// A pasted cell that came out as text ("Rp10,000.00" isn't en-US input) becomes the number the
|
||||
/// source recorded for it in its HTML, with a format that shows the same text when one can be
|
||||
/// inferred and the cell has none. The HTML cell must show the same text as the tab-separated
|
||||
/// field, so HTML that belongs to another copy (or a table laid out differently) changes nothing.
|
||||
fn numeric_from_html(cell: &mut Cell, field: &str, html: Option<&crate::clip_html::HtmlCell>, wb: &mut gridcraft_model::Workbook) {
|
||||
let Some(hc) = html else { return };
|
||||
let Some(n) = hc.num else { return };
|
||||
if cell.formula.is_some() || !matches!(cell.value, Value::Text(_)) || wb.styles.get(cell.style).num_fmt.as_str() == "@" {
|
||||
return;
|
||||
}
|
||||
if crate::clip_html::normalized(&hc.text) != crate::clip_html::normalized(field) {
|
||||
return;
|
||||
}
|
||||
cell.value = Value::number(n);
|
||||
if wb.styles.get(cell.style).num_fmt.as_str() == "General"
|
||||
&& let Some(code) = crate::clip_html::format_for(field, n)
|
||||
{
|
||||
cell.style = wb.styles.derive(cell.style, |s| s.num_fmt = gridcraft_model::NumFmt::new(&code));
|
||||
}
|
||||
}
|
||||
|
||||
/// Tab-separated text with Excel-style quoting.
|
||||
pub(crate) fn parse_tsv(text: &str) -> Vec<Vec<String>> {
|
||||
let mut rows = Vec::new();
|
||||
@@ -769,16 +914,19 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let skip_blanks = bool_param(p, "skipBlanks").unwrap_or(false);
|
||||
let transpose = bool_param(p, "transpose").unwrap_or(false);
|
||||
let link = bool_param(p, "link").unwrap_or(false);
|
||||
if link && !clip.areas.is_empty() {
|
||||
return Err(EngineError::Other("This action won't work on multiple selections.".into()));
|
||||
}
|
||||
let dest_sheet = target_sheet(s, p)?;
|
||||
let sel = s.doc()?.selection.current();
|
||||
let at = cell_param(p, "at").unwrap_or(sel.start);
|
||||
let at = cell_param_on(s, p, "at", dest_sheet)?.unwrap_or(sel.start);
|
||||
let src = clip.range;
|
||||
let (h, w) = if transpose { (src.width(), src.height()) } else { (src.height(), src.width()) };
|
||||
// Tile the copy over a larger destination that is a multiple of its size.
|
||||
let tile = sel.height() % h == 0
|
||||
&& sel.width() % w == 0
|
||||
&& !sel.is_single()
|
||||
&& cell_param(p, "at").is_none()
|
||||
&& cell_param_on(s, p, "at", dest_sheet)?.is_none()
|
||||
&& !sel.is_full_cols()
|
||||
&& !sel.is_full_rows()
|
||||
&& sel.count() <= 4_000_000;
|
||||
@@ -848,7 +996,9 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
e
|
||||
};
|
||||
let mut moved = Formula::from_expr(e);
|
||||
moved.array = f.array;
|
||||
// The array range moves with its formula.
|
||||
let (dr, dc) = (dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64);
|
||||
moved.array = f.array.and_then(|a| Some(RangeRef::new(a.start.offset(dr, dc)?, a.end.offset(dr, dc)?)));
|
||||
return Some(std::sync::Arc::new(moved));
|
||||
}
|
||||
let moved =
|
||||
@@ -951,6 +1101,20 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The copied cell's validation rule replaces whatever rule the destination had.
|
||||
if !link && matches!(what, What::All | What::AllExceptBorders | What::Validation) {
|
||||
let rule = src_sheet.validations.iter().find(|dv| dv.ranges.iter().any(|r| r.contains(sc))).cloned();
|
||||
let sh = cx.sheet_mut(dest_sheet)?;
|
||||
super::data::remove_validation_cells(&mut sh.validations, &[RangeRef::new(dest, dest)]);
|
||||
if let Some(mut dv) = rule {
|
||||
// Relative references move with the rule, as pasted formulas do.
|
||||
let first = dv.ranges.first().map_or(sc, |r| r.start);
|
||||
dv.f1 = super::data::move_rule_formula(&dv.f1, first, dest);
|
||||
dv.f2 = dv.f2.map(|f| super::data::move_rule_formula(&f, first, dest));
|
||||
dv.ranges = vec![RangeRef::new(dest, dest)];
|
||||
sh.validations.push(dv);
|
||||
}
|
||||
}
|
||||
match what {
|
||||
What::Comments => {
|
||||
if let Some(cm) = src_sheet.comments.get(&sc).cloned() {
|
||||
@@ -1015,6 +1179,10 @@ fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
/// Applies a reference adjustment to every cell formula and defined name in the workbook.
|
||||
pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) {
|
||||
use gridcraft_formula::adjust::Edit;
|
||||
// Rows and columns inserted or deleted on the target sheet move its legacy array ranges too
|
||||
// (a cut moves its arrays itself).
|
||||
let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
|
||||
for si in 0..wb.sheets.len() {
|
||||
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
|
||||
@@ -1022,16 +1190,21 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
|
||||
if keys.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let on_target = moves_arrays && host.eq_ignore_ascii_case(target);
|
||||
let Some(sheet) = wb.sheet_mut(si) else { continue };
|
||||
for (c, f) in keys {
|
||||
let Some(expr) = f.expr() else { continue };
|
||||
let new = gridcraft_formula::adjust::adjust(expr, &host, target, e);
|
||||
let text = gridcraft_formula::print(&new);
|
||||
if text != f.text
|
||||
let array = match f.array {
|
||||
Some(a) if on_target => super::sheet::map_range(a, e),
|
||||
a => a,
|
||||
};
|
||||
if (text != f.text || array != f.array)
|
||||
&& let Some(cell) = sheet.cells.get_mut(c)
|
||||
{
|
||||
let mut nf = Formula::from_expr(new);
|
||||
nf.array = f.array;
|
||||
nf.array = array;
|
||||
cell.formula = Some(std::sync::Arc::new(nf));
|
||||
}
|
||||
}
|
||||
@@ -1050,6 +1223,18 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
|
||||
fn clear(s: &mut Session, p: &Json, what: &str) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let ranges = target_ranges(s, p)?;
|
||||
// Delete on checkboxes works in two passes (as in Excel): checked boxes are unchecked first,
|
||||
// and only when every box in the selection is unchecked are the boxes removed.
|
||||
let uncheck_only = what == "contents" && {
|
||||
let d = s.doc()?;
|
||||
d.wb.sheet(sheet).is_some_and(|sh| {
|
||||
ranges.iter().any(|r| {
|
||||
r.intersection(&sh.used_range().unwrap_or(RangeRef::cell(r.start))).is_some_and(|r| {
|
||||
sh.cells.iter_range(r).any(|(c, x)| x.value == Value::Bool(true) && super::extra::is_checkbox_cell(&d.wb, sh, c))
|
||||
})
|
||||
})
|
||||
})
|
||||
};
|
||||
edit(s, |cx| {
|
||||
for r in &ranges {
|
||||
let r = match cx.wb.sheet(sheet).and_then(|sh| sh.used_range()) {
|
||||
@@ -1061,6 +1246,21 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result<Json> {
|
||||
};
|
||||
let cells: Vec<(CellRef, Cell)> =
|
||||
cx.wb.sheet(sheet).map(|sh| sh.cells.iter_range(r).map(|(c, x)| (c, x.clone())).collect()).unwrap_or_default();
|
||||
let mut cells = cells;
|
||||
if what == "contents" {
|
||||
for (_, cell) in cells.iter_mut() {
|
||||
let checkbox = cx.wb.styles.get(cell.style).num_fmt.as_str() == "checkbox";
|
||||
cell.formula = None;
|
||||
if checkbox && uncheck_only {
|
||||
cell.value = Value::Bool(false);
|
||||
} else {
|
||||
cell.value = Value::Empty;
|
||||
if checkbox {
|
||||
cell.style = cx.wb.styles.derive(cell.style, |st| st.num_fmt = gridcraft_model::NumFmt::new("General"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
for (c, mut cell) in cells {
|
||||
match what {
|
||||
@@ -1068,8 +1268,6 @@ fn clear(s: &mut Session, p: &Json, what: &str) -> Result<Json> {
|
||||
sh.remove_cell(c);
|
||||
}
|
||||
"contents" => {
|
||||
cell.value = Value::Empty;
|
||||
cell.formula = None;
|
||||
sh.set_cell(c, cell);
|
||||
}
|
||||
"formats" => {
|
||||
@@ -1139,6 +1337,7 @@ fn auto_fill(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let Some(target) = str_param(p, "target").and_then(RangeRef::parse) else { return Err(bad("edit.autoFill", "missing `target`")) };
|
||||
let mode = match str_param(p, "mode").unwrap_or("series") {
|
||||
"copy" => crate::fill::FillMode::Copy,
|
||||
"alternate" => crate::fill::FillMode::Alternate,
|
||||
"formats" => crate::fill::FillMode::Formats,
|
||||
"values" => crate::fill::FillMode::ValuesOnly,
|
||||
_ => crate::fill::FillMode::Series,
|
||||
@@ -1388,6 +1587,23 @@ fn begin_edit(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cell_set_takes_numbers_for_input_and_value() {
|
||||
// #697: a JSON number for `input` used to clear the cell instead of entering it.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": 123.5})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "value": 77})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A3", "input": true})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A4", "input": "=A1+A2"})).unwrap();
|
||||
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
|
||||
assert_eq!(get(&mut s, "A1")["value"], json!(123.5));
|
||||
assert_eq!(get(&mut s, "A2")["value"], json!(77.0));
|
||||
assert_eq!(get(&mut s, "A3")["value"], json!(true));
|
||||
assert_eq!(get(&mut s, "A4")["value"], json!(200.5));
|
||||
assert!(s.execute("cell.set", json!({"cell": "A5"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_array_entry() {
|
||||
let mut s = Session::new();
|
||||
@@ -1404,6 +1620,22 @@ mod tests {
|
||||
assert_eq!(bar.as_deref(), Some("{=B2:B3*2}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_entered_outside_the_selection_covers_only_its_cell() {
|
||||
// Found by the command-sequence fuzzer: the array took the selection's range even with
|
||||
// `cell` elsewhere (or on another sheet), so its formula sat outside its own range and the
|
||||
// selected cells were wiped.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "K20", "input": "keep"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "K20:K22"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "H5", "input": "=1+1", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
let f = sh.cell(CellRef::parse("H5").unwrap()).and_then(|c| c.formula.clone()).unwrap();
|
||||
assert_eq!(f.array, Some(RangeRef::parse("H5").unwrap()));
|
||||
assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcards() {
|
||||
assert!(wildcard("hello", "h*o"));
|
||||
|
||||
+249
-43
@@ -15,7 +15,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Chart Element",
|
||||
["Chart Design", "Chart Layouts"],
|
||||
None,
|
||||
"{chart?, element: title|legend|dataLabels|gridlines|axisTitles|smooth, on?: bool, position?: bottom|top|left|right}",
|
||||
"{chart?, element: title|legend|dataLabels|gridlines|axisTitles|smooth|trendline, on?: bool, position?: bottom|top|left|right; trendline: series?: index (default all), type?: linear|exponential|linearForecast|movingAverage|logarithmic|power|polynomial, order?: 2..6, period?: 2..255, forward?, backward?, displayEquation?, displayRSquared?}",
|
||||
has_doc,
|
||||
add_element
|
||||
),
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Data…",
|
||||
["Chart Design", "Data"],
|
||||
None,
|
||||
"{chart?, range: \"Sheet1!A1:D7\", byRows?: bool}",
|
||||
"{chart?, range?: \"Sheet1!A1:D7\", byRows?: bool, categories?: \"Sheet1!A2:A7\" (Horizontal (Category) Axis Labels for every series; \"\" clears), removeSeries?: [index…]}",
|
||||
has_doc,
|
||||
select_data
|
||||
),
|
||||
@@ -116,9 +116,29 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
rotate
|
||||
),
|
||||
// Views
|
||||
cmd!(noundo "view.normal", "Normal", ["View", "Workbook Views"], None, "{}", has_doc, |s, _| set_view(s, "normal")),
|
||||
cmd!(noundo "view.pageLayout", "Page Layout", ["View", "Workbook Views"], None, "{}", has_doc, |s, _| set_view(s, "pageLayout")),
|
||||
cmd!(noundo "view.pageBreakPreview", "Page Break Preview", ["View", "Workbook Views"], None, "{}", has_doc, |s, _| set_view(s, "pageBreakPreview")),
|
||||
cmd!(noundo "view.normal", "Normal", ["View", "Workbook Views"], None, "{sheet?} → {view} (per sheet, saved with the file)", has_doc, |s, p| set_view(
|
||||
s,
|
||||
p,
|
||||
SheetViewMode::Normal
|
||||
)),
|
||||
cmd!(
|
||||
noundo "view.pageLayout",
|
||||
"Page Layout",
|
||||
["View", "Workbook Views"],
|
||||
None,
|
||||
"{sheet?} → {view}: pages on paper with rulers; headers and footers are edited in place (per sheet, saved with the file)",
|
||||
has_doc,
|
||||
|s, p| set_view(s, p, SheetViewMode::PageLayout)
|
||||
),
|
||||
cmd!(
|
||||
noundo "view.pageBreakPreview",
|
||||
"Page Break Preview",
|
||||
["View", "Workbook Views"],
|
||||
None,
|
||||
"{sheet?} → {view} (per sheet, saved with the file)",
|
||||
has_doc,
|
||||
|s, p| set_view(s, p, SheetViewMode::PageBreakPreview)
|
||||
),
|
||||
cmd!(noundo "view.customViews", "Custom Views…", ["View", "Workbook Views"], None, "{save?: name, show?: name, delete?: name} → list", has_doc, custom_views),
|
||||
cmd!(noundo "view.split", "Split", ["View", "Window"], None, "{} (toggles a split at the active cell; shown as frozen panes in this version)", has_doc, split),
|
||||
cmd!(noundo "view.newWindow", "New Window", ["View", "Window"], None, "{} opens a second window on the same workbook (a linked copy)", has_doc, new_window),
|
||||
@@ -126,7 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(noundo "view.hideWindow", "Hide", ["View", "Window"], None, "{}", has_doc, hide_window),
|
||||
cmd!(noundo "view.unhideWindow", "Unhide…", ["View", "Window"], None, "{index?}", has_doc, unhide_window),
|
||||
cmd!(query "view.switchWindows", "Switch Windows", ["View", "Window"], None, "{} → open windows", always, switch_windows),
|
||||
cmd!(noundo "view.ruler", "Ruler", ["View", "Show"], None, "{on?}", has_doc, |_, _| ok()),
|
||||
cmd!(noundo "view.ruler", "Ruler", ["View", "Show"], None, "{on?} → {on}: rulers in Page Layout view (an application option)", has_doc, ruler),
|
||||
cmd!(query "view.macros", "Macros", ["View", "Macros"], None, "{} → scripts", has_doc, all_scripts),
|
||||
// Table tools
|
||||
cmd!("table.resize", "Resize Table", ["Table Design", "Properties"], None, "{table?, range: \"A1:F20\"}", has_doc, table_resize),
|
||||
@@ -181,7 +201,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Checkbox",
|
||||
["Insert", "Cell Controls"],
|
||||
None,
|
||||
"{range?} (cells hold TRUE/FALSE and draw as checkboxes; Space toggles)",
|
||||
"{range?} (TRUE/FALSE and empty cells draw as checkboxes, empty ones become FALSE, other values show as they are; click or Space toggles; Delete unchecks, then removes; Clear Formats removes and keeps the values)",
|
||||
has_doc,
|
||||
checkbox
|
||||
),
|
||||
@@ -296,12 +316,68 @@ fn add_element(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
s.smooth = on;
|
||||
}
|
||||
}
|
||||
"trendline" => {
|
||||
let only = u32_param(p, "series").map(|i| i as usize);
|
||||
if only.is_some_and(|i| i >= c.series.len()) {
|
||||
return Err(bad("chart.addElement", "no such series"));
|
||||
}
|
||||
let targets: Vec<usize> = (0..c.series.len()).filter(|i| only.is_none_or(|o| o == *i)).collect();
|
||||
if !on {
|
||||
for i in targets {
|
||||
if let Some(se) = c.series.get_mut(i) {
|
||||
se.trendlines.clear();
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let t = trendline_param(p)?;
|
||||
let eligible: Vec<usize> =
|
||||
targets.into_iter().filter(|i| gridcraft_chart::supports_trendline(gridcraft_chart::series_plot_kind(c, *i))).collect();
|
||||
if eligible.is_empty() {
|
||||
return Err(bad("chart.addElement", "trendlines need a 2-D column, bar, line, area, scatter or bubble series"));
|
||||
}
|
||||
for i in eligible {
|
||||
if let Some(se) = c.series.get_mut(i) {
|
||||
se.trendlines.push(t.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
other => return Err(bad("chart.addElement", format!("unknown element `{other}`"))),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// The trendline described by `chart.addElement`'s trendline parameters (Excel's Add Chart
|
||||
/// Element ▸ Trendline choices, plus the Format Trendline options).
|
||||
fn trendline_param(p: &Json) -> Result<Trendline> {
|
||||
let num = |k: &str| f64_param(p, k).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(0.0);
|
||||
let mut t = Trendline {
|
||||
forward: num("forward"),
|
||||
backward: num("backward"),
|
||||
display_equation: bool_param(p, "displayEquation").unwrap_or(false),
|
||||
display_r_squared: bool_param(p, "displayRSquared").unwrap_or(false),
|
||||
..Trendline::default()
|
||||
};
|
||||
t.kind = match str_param(p, "type").unwrap_or("linear") {
|
||||
"linear" => TrendlineKind::Linear,
|
||||
// Excel's Linear Forecast: a linear trendline projected two periods ahead.
|
||||
"linearForecast" => {
|
||||
if t.forward == 0.0 {
|
||||
t.forward = 2.0;
|
||||
}
|
||||
TrendlineKind::Linear
|
||||
}
|
||||
"exponential" => TrendlineKind::Exponential,
|
||||
"logarithmic" => TrendlineKind::Logarithmic,
|
||||
"power" => TrendlineKind::Power,
|
||||
"polynomial" => TrendlineKind::Polynomial(u32_param(p, "order").unwrap_or(2).clamp(2, 6) as u8),
|
||||
"movingAverage" => TrendlineKind::MovingAverage(u32_param(p, "period").unwrap_or(2).clamp(2, 255)),
|
||||
other => return Err(bad("chart.addElement", format!("unknown trendline type `{other}`"))),
|
||||
};
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
fn quick_layout(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let n = u32_param(p, "layout").unwrap_or(1);
|
||||
with_chart(s, p, |c| {
|
||||
@@ -350,22 +426,71 @@ fn change_colors(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn select_data(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let range = str_param(p, "range").ok_or_else(|| bad("chart.selectData", "missing `range`"))?.to_string();
|
||||
let (sheet_name, body) = split_sheet(&range);
|
||||
let d = s.doc()?;
|
||||
let src_si = match sheet_name {
|
||||
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
|
||||
None => d.wb.active_sheet,
|
||||
// A new data range rebuilds the series, as in Excel's Select Data › Chart data range.
|
||||
let rebuilt = match str_param(p, "range") {
|
||||
Some(range) => {
|
||||
let range = range.trim_start_matches('=');
|
||||
let (sheet_name, body) = split_sheet(range);
|
||||
let src_si = match sheet_name {
|
||||
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
|
||||
None => d.wb.active_sheet,
|
||||
};
|
||||
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "not a range"))?;
|
||||
if r.count() > 1_000_000 {
|
||||
return Err(bad("chart.selectData", "range too large for a chart"));
|
||||
}
|
||||
let src = d.wb.sheet(src_si).ok_or(EngineError::NoDocument)?;
|
||||
let by_rows = bool_param(p, "byRows").unwrap_or(r.width() > r.height() + 1);
|
||||
let series = super::insert::series_from_range(src, r, by_rows);
|
||||
Some((series, format!("{}!{}", gridcraft_formula::quote_sheet(&src.name), r.a1()), by_rows))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "not a range"))?;
|
||||
let src = d.wb.sheet(src_si).ok_or(EngineError::NoDocument)?;
|
||||
let by_rows = bool_param(p, "byRows").unwrap_or(r.width() > r.height() + 1);
|
||||
let series = super::insert::series_from_range(src, r, by_rows);
|
||||
let source = format!("{}!{}", gridcraft_formula::quote_sheet(&src.name), r.a1());
|
||||
// Horizontal (Category) Axis Labels › Edit: one labels range for every series ("" clears).
|
||||
let categories = match str_param(p, "categories") {
|
||||
None => None,
|
||||
Some(t) if t.trim().trim_start_matches('=').is_empty() => Some(None),
|
||||
Some(t) => {
|
||||
let t = t.trim().trim_start_matches('=');
|
||||
let (sheet_name, body) = split_sheet(t);
|
||||
let si = match sheet_name {
|
||||
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
|
||||
None => d.wb.active_sheet,
|
||||
};
|
||||
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "`categories` is not a range"))?;
|
||||
let name = d.wb.sheet(si).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?;
|
||||
let abs = |c: CellRef| format!("${}${}", gridcraft_core::col_to_letters(c.col), c.row + 1);
|
||||
Some(Some(format!("{}!{}:{}", gridcraft_formula::quote_sheet(&name), abs(r.start), abs(r.end))))
|
||||
}
|
||||
};
|
||||
let mut remove: Vec<usize> = p
|
||||
.get("removeSeries")
|
||||
.and_then(Json::as_array)
|
||||
.map(|a| a.iter().filter_map(Json::as_u64).filter_map(|i| usize::try_from(i).ok()).collect())
|
||||
.unwrap_or_default();
|
||||
remove.sort_unstable();
|
||||
remove.dedup();
|
||||
if rebuilt.is_none() && categories.is_none() && remove.is_empty() {
|
||||
return Err(bad("chart.selectData", "missing `range`, `categories` or `removeSeries`"));
|
||||
}
|
||||
with_chart(s, p, move |c| {
|
||||
c.series = series;
|
||||
c.source = Some(source);
|
||||
c.by_rows = by_rows;
|
||||
if let Some((series, source, by_rows)) = rebuilt {
|
||||
c.series = series;
|
||||
super::insert::scatter_x_from_first(c.kind, &mut c.series);
|
||||
c.source = Some(source);
|
||||
c.by_rows = by_rows;
|
||||
}
|
||||
for i in remove.iter().rev() {
|
||||
if *i < c.series.len() && c.series.len() > 1 {
|
||||
c.series.remove(*i);
|
||||
}
|
||||
}
|
||||
if let Some(cats) = categories {
|
||||
for se in &mut c.series {
|
||||
se.categories = cats.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -376,7 +501,7 @@ fn move_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Some(n) => Some(s.doc()?.wb.sheet_index(n).ok_or_else(|| bad("chart.move", "no such sheet"))?),
|
||||
None => None,
|
||||
};
|
||||
let at = cell_param(p, "at");
|
||||
let at = cell_param_on(s, p, "at", target.unwrap_or(si))?;
|
||||
edit(s, |cx| {
|
||||
let mut chart = cx.sheet_mut(si)?.charts.remove(ci);
|
||||
if let Some(a) = at {
|
||||
@@ -540,9 +665,26 @@ fn rotate(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
with_shape(s, p, |sh| std::mem::swap(&mut sh.anchor.width, &mut sh.anchor.height))
|
||||
}
|
||||
|
||||
fn set_view(s: &mut Session, mode: &str) -> Result<Json> {
|
||||
s.view_mode = mode.to_string();
|
||||
Ok(json!({"view": mode}))
|
||||
/// Switches a sheet's view. Like zoom, the view is saved with the file but is not an edit: it
|
||||
/// neither records an undo step nor marks a clean workbook as changed.
|
||||
fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result<Json> {
|
||||
let si = target_sheet(s, p)?;
|
||||
let d = s.doc_mut()?;
|
||||
let dirty = d.is_dirty();
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
if let Some(sh) = wb.sheet_mut(si) {
|
||||
sh.view = mode;
|
||||
}
|
||||
if !dirty {
|
||||
d.saved = d.wb.clone();
|
||||
}
|
||||
Ok(json!({"view": mode.as_str()}))
|
||||
}
|
||||
|
||||
fn ruler(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let on = bool_param(p, "on").unwrap_or(s.hide_ruler);
|
||||
s.hide_ruler = !on;
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
|
||||
const VIEWS_NAME: &str = "_sc_custom_views";
|
||||
@@ -559,6 +701,12 @@ fn stash_get(wb: &Workbook, key: &str) -> Json {
|
||||
.unwrap_or(json!({}))
|
||||
}
|
||||
|
||||
/// Like `stash_get`, for the name-keyed lists (views, scripts): a stored value that is not a JSON object is treated as empty.
|
||||
fn stash_map(wb: &Workbook, key: &str) -> Json {
|
||||
let v = stash_get(wb, key);
|
||||
if v.is_object() { v } else { json!({}) }
|
||||
}
|
||||
|
||||
fn stash_set(wb: &mut Workbook, key: &str, v: &Json) {
|
||||
let text = v.to_string();
|
||||
let formula = format!("\"{}\"", text.replace('"', "\"\""));
|
||||
@@ -566,9 +714,22 @@ fn stash_set(wb: &mut Workbook, key: &str, v: &Json) {
|
||||
wb.names.push(DefinedName { name: key.into(), scope: None, formula, comment: String::new(), hidden: true });
|
||||
}
|
||||
|
||||
/// The Watch Window list isn't an edit (Excel doesn't undo it): undo and redo keep the current
|
||||
/// list when they swap in another snapshot of the workbook.
|
||||
pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc<Workbook>) {
|
||||
let find = |wb: &Workbook| wb.names.iter().find(|n| n.name == WATCH_NAME).cloned();
|
||||
let keep = find(from);
|
||||
if keep == find(to) {
|
||||
return;
|
||||
}
|
||||
let wb = std::sync::Arc::make_mut(to);
|
||||
wb.names.retain(|n| n.name != WATCH_NAME);
|
||||
wb.names.extend(keep);
|
||||
}
|
||||
|
||||
fn custom_views(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let mut views = stash_get(&d.wb, VIEWS_NAME);
|
||||
let mut views = stash_map(&d.wb, VIEWS_NAME);
|
||||
if let Some(name) = str_param(p, "save") {
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
views[name] = json!({"sheet": d.wb.active_sheet, "selection": d.selection.a1(), "zoom": sh.zoom, "freeze": sh.freeze});
|
||||
@@ -588,6 +749,17 @@ fn custom_views(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let Some(z) = v["zoom"].as_u64() {
|
||||
s.execute("view.zoom", json!({"percent": z}))?;
|
||||
}
|
||||
if let Some(f) = v.get("freeze") {
|
||||
let freeze = match (f[0].as_u64(), f[1].as_u64()) {
|
||||
(Some(r), Some(c)) => u32::try_from(r).ok().zip(u32::try_from(c).ok()),
|
||||
_ => None,
|
||||
};
|
||||
edit(s, |cx| {
|
||||
let si = cx.sheet_index();
|
||||
cx.sheet_mut(si)?.freeze = freeze;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
} else if let Some(name) = str_param(p, "delete") {
|
||||
if let Some(o) = views.as_object_mut() {
|
||||
o.remove(name);
|
||||
@@ -657,7 +829,7 @@ fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = cx.sheet_mut(si)?;
|
||||
let headers: Vec<String> = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect();
|
||||
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
|
||||
if r.start.row != t.range.start.row {
|
||||
if r.start.row != t.range.start.row || !r.intersects(&t.range) {
|
||||
return Err(EngineError::Other(
|
||||
"The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(),
|
||||
));
|
||||
@@ -666,7 +838,14 @@ fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
for (i, h) in headers.iter().enumerate() {
|
||||
let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() };
|
||||
let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned();
|
||||
cols.push(existing.unwrap_or(TableColumn { name, totals: TotalsFn::None, totals_label: None, formula: None }));
|
||||
cols.push(existing.unwrap_or(TableColumn {
|
||||
name,
|
||||
totals: TotalsFn::None,
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
xml: None,
|
||||
}));
|
||||
}
|
||||
t.columns = cols;
|
||||
t.range = r;
|
||||
@@ -783,7 +962,7 @@ fn new_script(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(bad("automate.newScript", "`commands` must be an array"));
|
||||
}
|
||||
edit(s, |cx| {
|
||||
let mut all = stash_get(&cx.wb, SCRIPTS_NAME);
|
||||
let mut all = stash_map(&cx.wb, SCRIPTS_NAME);
|
||||
all[name.as_str()] = cmds.clone();
|
||||
stash_set(&mut cx.wb, SCRIPTS_NAME, &all);
|
||||
Ok(json!({"name": name}))
|
||||
@@ -791,10 +970,16 @@ fn new_script(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn all_scripts(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
let all = stash_get(&s.doc()?.wb, SCRIPTS_NAME);
|
||||
Ok(Json::Array(
|
||||
all.as_object().map(|o| o.iter().map(|(k, v)| json!({"name": k, "steps": v.as_array().map_or(0, Vec::len)})).collect()).unwrap_or_default(),
|
||||
))
|
||||
let wb = &s.doc()?.wb;
|
||||
let all = stash_get(wb, SCRIPTS_NAME);
|
||||
let mut list: Vec<Json> =
|
||||
all.as_object().map(|o| o.iter().map(|(k, v)| json!({"name": k, "steps": v.as_array().map_or(0, Vec::len)})).collect()).unwrap_or_default();
|
||||
// A preserved VBA project is reported alongside GridCraft's own scripts; it is carried on
|
||||
// save but never executed here, so it has no step count.
|
||||
if let Some(bytes) = &wb.vba_project {
|
||||
list.push(json!({"name": "(VBA)", "steps": 0, "kind": "vba", "size": bytes.len(), "executed": false}));
|
||||
}
|
||||
Ok(Json::Array(list))
|
||||
}
|
||||
|
||||
fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
@@ -816,7 +1001,7 @@ fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn delete_script(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("automate.deleteScript", "missing `name`"))?.to_string();
|
||||
edit(s, |cx| {
|
||||
let mut all = stash_get(&cx.wb, SCRIPTS_NAME);
|
||||
let mut all = stash_map(&cx.wb, SCRIPTS_NAME);
|
||||
if let Some(o) = all.as_object_mut() {
|
||||
o.remove(&name);
|
||||
}
|
||||
@@ -828,6 +1013,11 @@ fn delete_script(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
/// Number format that marks checkbox cells (TRUE/FALSE values drawn as boxes).
|
||||
pub const CHECKBOX_FORMAT: &str = "\"☐\";\"☐\";\"☐\";[=1]\"☑\"";
|
||||
|
||||
/// Whether `c` has checkbox formatting.
|
||||
pub(crate) fn is_checkbox_cell(wb: &gridcraft_model::Workbook, sh: &gridcraft_model::Sheet, c: CellRef) -> bool {
|
||||
wb.styles.get(sh.style_id(c)).num_fmt.as_str() == "checkbox"
|
||||
}
|
||||
|
||||
fn checkbox(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let si = target_sheet(s, p)?;
|
||||
@@ -843,9 +1033,14 @@ fn checkbox(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
s.align.h = HAlign::Center;
|
||||
});
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
let v = sh.value(c);
|
||||
let value = if matches!(v, Value::Bool(_)) { v } else { Value::Bool(false) };
|
||||
sh.set_cell(c, Cell { value, formula: None, style: new });
|
||||
// Values and formulas already there stay (only TRUE/FALSE draw as a box); an empty
|
||||
// cell starts unchecked.
|
||||
let mut cell = sh.cell(c).cloned().unwrap_or_default();
|
||||
if cell.value.is_empty() && cell.formula.is_none() {
|
||||
cell.value = Value::Bool(false);
|
||||
}
|
||||
cell.style = new;
|
||||
sh.set_cell(c, cell);
|
||||
cx.touch(si, c);
|
||||
}
|
||||
}
|
||||
@@ -856,18 +1051,24 @@ fn checkbox(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn toggle_checkbox(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let si = target_sheet(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let cells: Vec<CellRef> = match cell_param(p, "cell") {
|
||||
let cells: Vec<CellRef> = match cell_param_on(s, p, "cell", si)? {
|
||||
Some(c) => vec![c],
|
||||
None => d.selection.ranges.iter().flat_map(|r| r.iter().take(100_000).collect::<Vec<_>>()).collect(),
|
||||
};
|
||||
edit(s, |cx| {
|
||||
for c in cells {
|
||||
let checkbox = cx.wb.sheet(si).is_some_and(|sh| is_checkbox_cell(&cx.wb, sh, c));
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
if let Some(cell) = sh.cells.get_mut(c)
|
||||
&& let Value::Bool(b) = cell.value
|
||||
&& cell.formula.is_none()
|
||||
{
|
||||
cell.value = Value::Bool(!b);
|
||||
// An empty checkbox cell counts as FALSE.
|
||||
let next = match cell.value {
|
||||
Value::Bool(b) if checkbox => Value::Bool(!b),
|
||||
Value::Empty if checkbox => Value::Bool(true),
|
||||
_ => continue,
|
||||
};
|
||||
cell.value = next;
|
||||
cx.changed.push((si, c));
|
||||
}
|
||||
}
|
||||
@@ -875,8 +1076,13 @@ fn toggle_checkbox(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Copy of the params that is always a JSON object, so keys can be assigned; any other JSON value counts as no params (like null).
|
||||
fn object_params(p: &Json) -> Json {
|
||||
Json::Object(p.as_object().cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
fn theme_colors(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let mut params = p.clone();
|
||||
let mut params = object_params(p);
|
||||
if params.get("name").is_none() {
|
||||
params["name"] = json!(s.doc()?.wb.theme.name.clone());
|
||||
}
|
||||
@@ -897,7 +1103,7 @@ fn background(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Ok(Json::Null)
|
||||
});
|
||||
}
|
||||
let mut params = p.clone();
|
||||
let mut params = object_params(p);
|
||||
params["alt"] = json!("Sheet background");
|
||||
params["at"] = json!("A1");
|
||||
s.execute("insert.picture", params)
|
||||
@@ -913,7 +1119,7 @@ fn draw_border(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"outline" => "outside",
|
||||
_ => "all",
|
||||
};
|
||||
let mut params = p.clone();
|
||||
let mut params = object_params(p);
|
||||
params["preset"] = json!(preset);
|
||||
s.execute("home.borders", params)
|
||||
}
|
||||
@@ -922,7 +1128,7 @@ fn new_cell_style(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("home.newCellStyle", "missing `name`"))?.to_string();
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let c = cell_param(p, "fromCell").unwrap_or(d.selection.active);
|
||||
let c = cell_param(s, p, "fromCell")?.unwrap_or(d.selection.active);
|
||||
let style = d.wb.styles.get(sh.style_id(c)).clone();
|
||||
edit(s, |cx| {
|
||||
cx.wb.cell_styles.retain(|(n, _)| !n.eq_ignore_ascii_case(&name));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! File menu: new, open, save, close, export, properties.
|
||||
//! File menu: new, open, save, close, export, properties, options.
|
||||
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
@@ -8,14 +8,23 @@ use crate::DocState;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook),
|
||||
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64} (xlsx, xlsm, xlsb and ods data import, csv, tsv, txt, json)", always, open),
|
||||
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html by extension)", has_doc, save),
|
||||
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, save_as),
|
||||
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
|
||||
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save),
|
||||
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as),
|
||||
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes),
|
||||
cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{force?: bool}", has_doc, close),
|
||||
cmd!(noundo "file.exportCsv", "Export as CSV", ["File", "Export"], None, "{path, sheet?}", has_doc, |s, p| export(s, p, "csv")),
|
||||
cmd!(noundo "file.exportHtml", "Save as Web Page", ["File", "Export"], None, "{path}", has_doc, |s, p| export(s, p, "html")),
|
||||
cmd!("file.properties", "Properties", ["File"], None, "{title?, subject?, author?, company?, keywords?, description?}", has_doc, properties),
|
||||
cmd!(
|
||||
query "file.options",
|
||||
"Options",
|
||||
["File"],
|
||||
None,
|
||||
"{} → {calculation: {mode, iterative, maxIterations, maxChange}} for the active workbook (the interface opens File › Options; change settings with their own commands, e.g. formulas.calculationOptions, view.theme, app.language.set)",
|
||||
always,
|
||||
options
|
||||
),
|
||||
cmd!(noundo "window.activate", "Switch Window", ["Window"], None, "{index}", has_doc, activate_window),
|
||||
]
|
||||
}
|
||||
@@ -46,27 +55,38 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("open".into(), json!({})));
|
||||
return ok();
|
||||
};
|
||||
let (wb, warnings) = crate::io::open_bytes(&name, &bytes)?;
|
||||
let imported = matches!(crate::io::FileKind::from_path(&name), Some(crate::io::FileKind::Ods | crate::io::FileKind::Xlsb))
|
||||
|| matches!(gridcraft_xlsx::sniff(&bytes), gridcraft_xlsx::Format::Ods | gridcraft_xlsx::Format::Xlsb);
|
||||
let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted;
|
||||
let (mut wb, warnings) = crate::io::open_bytes_with_password(&name, &bytes, str_param(p, "password"))?;
|
||||
wb.source_dir = str_param(p, "path").and_then(crate::io::source_dir);
|
||||
let imported =
|
||||
matches!(crate::io::FileKind::from_path(&name), Some(crate::io::FileKind::Ods | crate::io::FileKind::Xlsb | crate::io::FileKind::Xls))
|
||||
|| matches!(gridcraft_xlsx::sniff(&bytes), gridcraft_xlsx::Format::Ods | gridcraft_xlsx::Format::Xlsb | gridcraft_xlsx::Format::Xls);
|
||||
let title = if imported {
|
||||
format!("{} (imported).xlsx", std::path::Path::new(&name).file_stem().and_then(|n| n.to_str()).unwrap_or("Book"))
|
||||
} else {
|
||||
std::path::Path::new(&name).file_name().and_then(|n| n.to_str()).unwrap_or("Book").to_string()
|
||||
};
|
||||
// An import has no save target: ordinary Save must ask for a new destination.
|
||||
let path = str_param(p, "path").filter(|_| !imported).map(str::to_string);
|
||||
// An import has no save target: ordinary Save must ask for a new destination. Neither does a
|
||||
// workbook decrypted with its password, so Save never replaces the encrypted original with
|
||||
// an unprotected copy.
|
||||
let path = str_param(p, "path").filter(|_| !imported && !encrypted).map(str::to_string);
|
||||
// Replace an untouched blank Book1 like Excel does.
|
||||
if s.documents().len() == 1
|
||||
&& s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty()))
|
||||
{
|
||||
s.close_document(0);
|
||||
}
|
||||
let i = s.add_document(DocState::new(wb, path, title));
|
||||
if !warnings.is_empty() {
|
||||
let mut message = warnings.iter().take(5).cloned().collect::<Vec<_>>().join("\n\n");
|
||||
if warnings.len() > 5 {
|
||||
message.push_str(&format!("\n\n{} additional import warnings.", warnings.len() - 5));
|
||||
let mut doc = DocState::new(wb, path, title);
|
||||
if crate::io::FileKind::from_path(&name).is_none() && gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Xlsx {
|
||||
doc.content_kind = Some(crate::io::FileKind::Xlsx);
|
||||
}
|
||||
let i = s.add_document(doc);
|
||||
// The decrypted-workbook notice is for the info bar, not a message box.
|
||||
let shown: Vec<&str> = warnings.iter().map(String::as_str).filter(|w| *w != crate::io::DECRYPTED_NOTICE).collect();
|
||||
if !shown.is_empty() {
|
||||
let mut message = shown.iter().take(5).copied().collect::<Vec<_>>().join("\n\n");
|
||||
if shown.len() > 5 {
|
||||
message.push_str(&format!("\n\n{} additional import warnings.", shown.len() - 5));
|
||||
}
|
||||
s.ui_requests.push(crate::UiRequest::Message(message));
|
||||
}
|
||||
@@ -84,12 +104,24 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return ok();
|
||||
}
|
||||
};
|
||||
// A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the
|
||||
// document keeps its file and its unsaved changes.
|
||||
if std::path::Path::new(&path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
|
||||
return super::print::export_pdf(s, &json!({"path": path}));
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
let bytes = crate::io::save_bytes(&d.wb, &path)?;
|
||||
// The document's own file keeps the format its content had when opened; any other path
|
||||
// goes by its extension. Relative paths to linked workbooks are rewritten for the new folder.
|
||||
let kind = crate::io::FileKind::from_path(&path).or(d.content_kind.filter(|_| d.path.as_deref() == Some(path.as_str())));
|
||||
let rebased = crate::io::source_dir(&path).and_then(|f| gridcraft_xlsx::rebase_links(&d.wb, &f));
|
||||
let wb = rebased.as_ref().unwrap_or(&d.wb);
|
||||
let bytes = match kind {
|
||||
Some(kind) => crate::io::save_bytes_as(wb, &path, kind)?,
|
||||
None => crate::io::save_bytes(wb, &path)?,
|
||||
};
|
||||
crate::io::write_file(&path, &bytes)?;
|
||||
let kind = crate::io::FileKind::from_path(&path).unwrap_or(crate::io::FileKind::Xlsx);
|
||||
// Only a full-fidelity format clears the dirty flag and becomes the document's file.
|
||||
if matches!(kind, crate::io::FileKind::Xlsx | crate::io::FileKind::Json) {
|
||||
if matches!(kind, Some(crate::io::FileKind::Xlsx | crate::io::FileKind::Json)) {
|
||||
d.saved = d.wb.clone();
|
||||
d.path = Some(path.clone());
|
||||
}
|
||||
@@ -156,6 +188,22 @@ fn properties(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// File › Options: reports the workbook-level settings and asks the interface to show its Options
|
||||
/// page. Nothing changes here; every setting has its own command.
|
||||
fn options(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("options".into(), json!({})));
|
||||
let calculation = s.active().map(|d| {
|
||||
let c = &d.wb.calc;
|
||||
let mode = match c.mode {
|
||||
gridcraft_model::CalcMode::Automatic => "automatic",
|
||||
gridcraft_model::CalcMode::AutomaticExceptTables => "automaticExceptTables",
|
||||
gridcraft_model::CalcMode::Manual => "manual",
|
||||
};
|
||||
json!({"mode": mode, "iterative": c.iterative, "maxIterations": c.max_iterations, "maxChange": c.max_change})
|
||||
});
|
||||
Ok(json!({"calculation": calculation}))
|
||||
}
|
||||
|
||||
fn activate_window(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let i = u32_param(p, "index").ok_or_else(|| bad("window.activate", "missing `index`"))? as usize;
|
||||
if i >= s.documents().len() {
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
//! Data › Forecast › Forecast Sheet: a new sheet with the history, a FORECAST.ETS column, the
|
||||
//! FORECAST.ETS.CONFINT confidence bounds, optional FORECAST.ETS.STAT statistics and a chart.
|
||||
//!
|
||||
//! Like Excel, the sheet holds a copy of the timeline and values (sorted by time) and live
|
||||
//! formulas over that copy, so the forecast follows edits to the copied history.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value};
|
||||
use gridcraft_functions::Timeline;
|
||||
use gridcraft_model::{Anchor, Cell, Chart, ChartKind, Formula, LegendPos, Series, Sheet, StyleId, Table, TableColumn, TotalsFn};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::*;
|
||||
use crate::selection::current_region;
|
||||
|
||||
const CMD: &str = "data.forecastSheet";
|
||||
/// Most history rows a forecast sheet copies.
|
||||
const MAX_HISTORY: u64 = 10_000;
|
||||
/// Most forecast rows.
|
||||
const MAX_PERIODS: u32 = 10_000;
|
||||
/// Most history rows × forecast rows. Every forecast row holds three ETS formulas that each refit
|
||||
/// the model over the whole history (about 3 µs per history point in a release build), so this
|
||||
/// bounds a sheet's recalculation to a few seconds: 10,000 rows of history get 50 forecast rows,
|
||||
/// 50 rows of history the full 10,000.
|
||||
const MAX_WORK: u64 = 500_000;
|
||||
|
||||
/// Forecast rows by default: a third of the history, within [`max_periods`].
|
||||
fn default_periods(history: usize) -> u32 {
|
||||
u32::try_from(history.div_ceil(3)).unwrap_or(u32::MAX).clamp(1, max_periods(history))
|
||||
}
|
||||
|
||||
/// Most forecast rows for `history` rows of history.
|
||||
fn max_periods(history: usize) -> u32 {
|
||||
let h = u64::try_from(history).unwrap_or(u64::MAX).max(1);
|
||||
u32::try_from(MAX_WORK / h).unwrap_or(u32::MAX).clamp(1, MAX_PERIODS)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"data.forecastSheet",
|
||||
"Forecast Sheet",
|
||||
["Data", "Forecast"],
|
||||
None,
|
||||
"{timeline?: \"A2:A25\", values?: \"B2:B25\" (default: the first two columns of `range`, the selection or the current region; a text first cell is the header), end?: timeline value or date text | periods?: n (default: a third of the history, at least 1; ≤10,000 and history × periods ≤ 500,000; history ≤ 10,000 rows), forecastStart?: a timeline value or date text on the history, before its last point (hindcast: the model is fit to the points before it, the forecast columns start there and run over the actuals; default and the last point: forecast after the history), confidenceInterval?: bool (default true), confidence?: 0.95 or 95, seasonality?: \"auto\" | 0 (none) | 2–8,760, fillMissing?: interpolate|zeros, aggregate?: average|count|counta|max|median|min|sum, statistics?: bool, chart?: line|column} → {sheet, table, chart, history, periods}. Inserts a sheet before the active one: timeline, values, Forecast (FORECAST.ETS), Lower/Upper Confidence Bound (FORECAST.ETS.CONFINT), optional FORECAST.ETS.STAT table, and a chart.",
|
||||
has_doc,
|
||||
forecast_sheet
|
||||
)]
|
||||
}
|
||||
|
||||
/// The cells of a one-row or one-column range, at most `MAX_HISTORY + 1`.
|
||||
fn line_cells(r: RangeRef) -> Result<Vec<CellRef>> {
|
||||
if r.count() > MAX_HISTORY + 1 {
|
||||
return Err(bad(CMD, format!("at most {MAX_HISTORY} rows of history")));
|
||||
}
|
||||
if r.width() == 1 {
|
||||
Ok((r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect())
|
||||
} else if r.height() == 1 {
|
||||
Ok((r.start.col..=r.end.col).map(|col| CellRef::new(r.start.row, col)).collect())
|
||||
} else {
|
||||
Err(bad(CMD, "the timeline and the values are each one row or one column"))
|
||||
}
|
||||
}
|
||||
|
||||
/// A range parameter on any sheet (whole columns trimmed to the used range).
|
||||
fn range_on(s: &Session, t: &str) -> Result<(usize, RangeRef)> {
|
||||
let d = s.doc()?;
|
||||
let (sh, body) = split_sheet(t);
|
||||
let si = match sh {
|
||||
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad(CMD, format!("no sheet named `{n}`")))?,
|
||||
None => d.wb.active_sheet,
|
||||
};
|
||||
let r = RangeRef::parse(body.trim()).ok_or_else(|| bad(CMD, format!("not a range: `{t}`")))?;
|
||||
let r = if r.is_full_cols() || r.is_full_rows() {
|
||||
match d.wb.sheet(si).and_then(|s| s.used_range()) {
|
||||
Some(u) => r.intersection(&RangeRef::new(CellRef::new(0, 0), u.end)).unwrap_or(RangeRef::cell(r.start)),
|
||||
None => RangeRef::cell(r.start),
|
||||
}
|
||||
} else {
|
||||
r
|
||||
};
|
||||
Ok((si, r))
|
||||
}
|
||||
|
||||
/// (sheet, timeline cells, value cells).
|
||||
fn source(s: &Session, p: &Json) -> Result<(usize, Vec<CellRef>, Vec<CellRef>)> {
|
||||
let text = |k: &str| str_param(p, k).map(str::trim).filter(|t| !t.is_empty());
|
||||
match (text("timeline"), text("values")) {
|
||||
(Some(t), Some(v)) => {
|
||||
let (ts, tr) = range_on(s, t)?;
|
||||
let (vs, vr) = range_on(s, v)?;
|
||||
if ts != vs {
|
||||
return Err(bad(CMD, "the timeline and the values must be on one sheet"));
|
||||
}
|
||||
Ok((ts, line_cells(tr)?, line_cells(vr)?))
|
||||
}
|
||||
(None, None) => {
|
||||
let d = s.doc()?;
|
||||
let (si, r) = match text("range") {
|
||||
Some(t) => range_on(s, t)?,
|
||||
None => {
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let sel = d.selection.current();
|
||||
(d.wb.active_sheet, if sel.is_single() { current_region(sh, d.selection.active) } else { sel })
|
||||
}
|
||||
};
|
||||
if r.width() < 2 {
|
||||
return Err(EngineError::Other("Select a timeline column and a values column for the forecast.".into()));
|
||||
}
|
||||
let col = |c: u32| RangeRef::new(CellRef::new(r.start.row, c), CellRef::new(r.end.row, c));
|
||||
Ok((si, line_cells(col(r.start.col))?, line_cells(col(r.start.col + 1))?))
|
||||
}
|
||||
_ => Err(bad(CMD, "give both `timeline` and `values`, or neither")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number parameter given as a number or as text.
|
||||
fn number(p: &Json, key: &str) -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
None | Some(Json::Null) => Ok(None),
|
||||
Some(Json::Number(n)) => Ok(n.as_f64()),
|
||||
Some(Json::String(t)) if t.trim().is_empty() => Ok(None),
|
||||
Some(Json::String(t)) => {
|
||||
t.trim().trim_end_matches('%').trim().parse::<f64>().map(Some).map_err(|_| bad(CMD, format!("`{key}` is not a number")))
|
||||
}
|
||||
Some(_) => Err(bad(CMD, format!("`{key}` is not a number"))),
|
||||
}
|
||||
}
|
||||
|
||||
struct Options {
|
||||
seasonality: u32,
|
||||
fill: u8,
|
||||
aggregate: Option<u8>,
|
||||
confidence: Option<f64>,
|
||||
statistics: bool,
|
||||
column_chart: bool,
|
||||
}
|
||||
|
||||
fn options(p: &Json) -> Result<Options> {
|
||||
let seasonality = match p.get("seasonality") {
|
||||
Some(Json::String(t)) if t.trim().is_empty() || t.trim().eq_ignore_ascii_case("auto") => 1,
|
||||
None | Some(Json::Null) => 1,
|
||||
_ => match number(p, "seasonality")? {
|
||||
Some(n) if n == n.trunc() && (0.0..=8760.0).contains(&n) => n as u32,
|
||||
_ => return Err(bad(CMD, "`seasonality` is \"auto\", 0 (none) or a season length from 2 to 8,760")),
|
||||
},
|
||||
};
|
||||
let fill = match str_param(p, "fillMissing").map(|t| t.trim().to_ascii_lowercase()) {
|
||||
None => 1,
|
||||
Some(t) if t.is_empty() || t == "interpolate" || t == "interpolation" => 1,
|
||||
Some(t) if t == "zeros" || t == "zero" => 0,
|
||||
Some(t) => return Err(bad(CMD, format!("`fillMissing` is interpolate or zeros, not `{t}`"))),
|
||||
};
|
||||
let aggregate = match str_param(p, "aggregate").map(|t| t.trim().to_ascii_lowercase()) {
|
||||
None => None,
|
||||
Some(t) => match t.as_str() {
|
||||
"" | "average" => None,
|
||||
"count" => Some(2),
|
||||
"counta" => Some(3),
|
||||
"max" => Some(4),
|
||||
"median" => Some(5),
|
||||
"min" => Some(6),
|
||||
"sum" => Some(7),
|
||||
_ => return Err(bad(CMD, format!("unknown `aggregate`: `{t}`"))),
|
||||
},
|
||||
};
|
||||
let confidence = if bool_param(p, "confidenceInterval").unwrap_or(true) {
|
||||
let c = number(p, "confidence")?.unwrap_or(0.95);
|
||||
let c = if c >= 1.0 { c / 100.0 } else { c };
|
||||
if !(c > 0.0 && c < 1.0) {
|
||||
return Err(bad(CMD, "`confidence` is between 0 and 1 (or 0 and 100%)"));
|
||||
}
|
||||
Some(c)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let column_chart = match str_param(p, "chart").map(|t| t.trim().to_ascii_lowercase()) {
|
||||
None => false,
|
||||
Some(t) if t.is_empty() || t == "line" => false,
|
||||
Some(t) if t == "column" => true,
|
||||
Some(t) => return Err(bad(CMD, format!("`chart` is line or column, not `{t}`"))),
|
||||
};
|
||||
Ok(Options { seasonality, fill, aggregate, confidence, statistics: bool_param(p, "statistics").unwrap_or(false), column_chart })
|
||||
}
|
||||
|
||||
fn col_letters(c: u32) -> String {
|
||||
gridcraft_core::col_to_letters(c)
|
||||
}
|
||||
|
||||
fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let opts = options(p)?;
|
||||
let (si, tcells, vcells) = source(s, p)?;
|
||||
if tcells.len() != vcells.len() {
|
||||
return Err(bad(CMD, "the timeline and the values need the same number of cells"));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
if d.wb.protected_structure {
|
||||
return Err(EngineError::Other("The workbook is protected and cannot be changed.".into()));
|
||||
}
|
||||
let sys = d.wb.date_system;
|
||||
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
// A text first cell is the header.
|
||||
let header = tcells.first().is_some_and(|c| sh.value(*c).is_text()) || vcells.first().is_some_and(|c| sh.value(*c).is_text());
|
||||
let name_of = |c: Option<&CellRef>, fallback: &str| match c.map(|c| sh.value(*c)) {
|
||||
Some(v) if header && !v.is_empty() => v.display(),
|
||||
_ => fallback.to_string(),
|
||||
};
|
||||
let (tname, vname) = (name_of(tcells.first(), "Timeline"), name_of(vcells.first(), "Values"));
|
||||
let skip = usize::from(header);
|
||||
let mut rows: Vec<(f64, Value)> = Vec::new();
|
||||
for (t, v) in tcells.iter().zip(&vcells).skip(skip) {
|
||||
let (tv, vv) = (sh.value(*t), sh.value(*v));
|
||||
match tv {
|
||||
Value::Number(x) => rows.push((x, if matches!(vv, Value::Number(_)) { vv } else { Value::Empty })),
|
||||
Value::Empty if vv.is_empty() => {}
|
||||
_ => return Err(EngineError::Other(format!("The timeline must hold numbers or dates ({} isn't one).", t.a1()))),
|
||||
}
|
||||
}
|
||||
rows.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let times: Vec<f64> = rows.iter().map(|r| r.0).collect();
|
||||
let timeline =
|
||||
Timeline::detect(×, sys).ok_or_else(|| EngineError::Other("The timeline needs at least two points a constant step apart.".into()))?;
|
||||
if !rows.iter().any(|r| matches!(r.1, Value::Number(_))) {
|
||||
return Err(EngineError::Other("There are no values to forecast.".into()));
|
||||
}
|
||||
let time_param = |key: &str| -> Result<Option<f64>> {
|
||||
match p.get(key) {
|
||||
Some(Json::Number(n)) => Ok(n.as_f64()),
|
||||
Some(Json::String(t)) if !t.trim().is_empty() => match gridcraft_core::parse::parse_input(t.trim(), sys).value {
|
||||
Value::Number(x) => Ok(Some(x)),
|
||||
_ => Err(bad(CMD, format!("`{key}` is not a number or a date: `{t}`"))),
|
||||
},
|
||||
None | Some(Json::Null) => Ok(None),
|
||||
Some(Json::String(_)) => Ok(None),
|
||||
Some(_) => Err(bad(CMD, format!("`{key}` is not a number or a date"))),
|
||||
}
|
||||
};
|
||||
let end = time_param("end")?;
|
||||
// Forecast Start: the index (into `rows`) of the first forecast point, or `rows.len()` for the
|
||||
// usual forecast after the history.
|
||||
let fit = match time_param("forecastStart")? {
|
||||
None => rows.len(),
|
||||
Some(start) => {
|
||||
let last_t = times.last().copied().unwrap_or(f64::NAN);
|
||||
let tol = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0);
|
||||
if tol(start, last_t) || timeline.after_last(1).is_some_and(|next| tol(start, next)) {
|
||||
rows.len()
|
||||
} else {
|
||||
let i = times
|
||||
.iter()
|
||||
.position(|t| tol(*t, start))
|
||||
.ok_or_else(|| bad(CMD, "`forecastStart` is not on the timeline (it is a point of the history, before its last point)"))?;
|
||||
if rows.get(..i).is_none_or(|h| h.iter().filter(|r| matches!(r.1, Value::Number(_))).count() < 2) {
|
||||
return Err(EngineError::Other("The forecast start needs at least two values before it to fit the forecast.".into()));
|
||||
}
|
||||
i
|
||||
}
|
||||
}
|
||||
};
|
||||
let cap = max_periods(rows.len());
|
||||
let periods = match end {
|
||||
Some(end) => steps_to(&timeline, end, cap)?,
|
||||
None => match number(p, "periods")? {
|
||||
Some(n) if n >= 1.0 && n.ceil() <= f64::from(cap) => n.ceil() as u32,
|
||||
Some(_) => return Err(bad(CMD, format!("`periods` is from 1 to {cap} for {} rows of history", rows.len()))),
|
||||
None => default_periods(rows.len()),
|
||||
},
|
||||
};
|
||||
let future: Vec<f64> =
|
||||
(1..=periods).map(|k| timeline.after_last(k)).collect::<Option<_>>().ok_or_else(|| bad(CMD, "the forecast runs past the last date"))?;
|
||||
let fmt_of = |c: Option<&CellRef>| c.map(|c| d.wb.styles.get(sh.style_id(*c)).num_fmt.clone()).unwrap_or_default();
|
||||
let (tfmt, vfmt) = (fmt_of(tcells.get(skip)), fmt_of(vcells.get(skip)));
|
||||
let sheet_name = d.wb.next_sheet_name();
|
||||
let table_name = (1..).map(|n| format!("Table{n}")).find(|n| d.wb.table(n).is_none()).unwrap_or_else(|| "Table".into());
|
||||
let chart_id = d.wb.next_object_id();
|
||||
let table_id = chart_id.saturating_add(1);
|
||||
|
||||
// Columns: A timeline, B values, C forecast, D/E bounds.
|
||||
let n = rows.len() as u32;
|
||||
let last = n + 1; // 1-based row of the last history point
|
||||
let fit_last = fit as u32 + 1; // 1-based row of the last point the model is fit to
|
||||
let end_row = last + periods; // 1-based row of the last forecast
|
||||
let hist = |col: u32| format!("${0}$2:${0}${fit_last}", col_letters(col));
|
||||
let mut tail = format!("{},{}", opts.seasonality, opts.fill);
|
||||
if let Some(a) = opts.aggregate {
|
||||
tail.push_str(&format!(",{a}"));
|
||||
}
|
||||
let mut headers = vec![tname, vname.clone(), format!("Forecast({vname})")];
|
||||
if opts.confidence.is_some() {
|
||||
headers.push(format!("Lower Confidence Bound({vname})"));
|
||||
headers.push(format!("Upper Confidence Bound({vname})"));
|
||||
}
|
||||
// Table column names are unique.
|
||||
for i in 1..headers.len() {
|
||||
let base = headers.get(i).cloned().unwrap_or_default();
|
||||
let mut name = base.clone();
|
||||
let mut k = 2;
|
||||
while headers.iter().take(i).any(|h| h.eq_ignore_ascii_case(&name)) {
|
||||
name = format!("{base}{k}");
|
||||
k += 1;
|
||||
}
|
||||
if let Some(h) = headers.get_mut(i) {
|
||||
*h = name;
|
||||
}
|
||||
}
|
||||
let width = headers.len() as u32;
|
||||
let stats_col = width + 1;
|
||||
let chart_col = if opts.statistics { stats_col + 3 } else { width + 1 };
|
||||
|
||||
let at = s.doc()?.wb.active_sheet;
|
||||
let index = edit(s, |cx| {
|
||||
let at = at.min(cx.wb.sheets.len());
|
||||
let bold = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.font.bold = true);
|
||||
let tstyle = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.num_fmt = tfmt.clone());
|
||||
let vstyle = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.num_fmt = vfmt.clone());
|
||||
let mut sheet = Sheet::new(sheet_name.clone());
|
||||
let put = |sheet: &mut Sheet, row: u32, col: u32, v: Value, style: StyleId| {
|
||||
sheet.set_cell(CellRef::new(row, col), Cell { value: v, formula: None, style });
|
||||
};
|
||||
let formula = |sheet: &mut Sheet, row: u32, col: u32, text: String, style: StyleId| {
|
||||
let mut cell = Cell::formula(Formula::new(&text));
|
||||
cell.style = style;
|
||||
sheet.set_cell(CellRef::new(row, col), cell);
|
||||
};
|
||||
for (c, h) in headers.iter().enumerate() {
|
||||
put(&mut sheet, 0, c as u32, Value::text(h.as_str()), StyleId::DEFAULT);
|
||||
}
|
||||
for (i, (t, v)) in rows.iter().enumerate() {
|
||||
let r = i as u32 + 1;
|
||||
put(&mut sheet, r, 0, Value::Number(*t), tstyle);
|
||||
if !v.is_empty() {
|
||||
put(&mut sheet, r, 1, v.clone(), vstyle);
|
||||
}
|
||||
}
|
||||
// The last point the model is fit to starts the forecast lines, so they join the values.
|
||||
let join = fit_last - 1; // 0-based row
|
||||
formula(&mut sheet, join, 2, format!("=B{fit_last}"), vstyle);
|
||||
if opts.confidence.is_some() {
|
||||
formula(&mut sheet, join, 3, format!("=C{fit_last}"), vstyle);
|
||||
formula(&mut sheet, join, 4, format!("=C{fit_last}"), vstyle);
|
||||
}
|
||||
let (tl, vl) = (hist(0), hist(1));
|
||||
let forecast_row = |sheet: &mut Sheet, r: u32| {
|
||||
formula(sheet, r - 1, 2, format!("=FORECAST.ETS(A{r},{vl},{tl},{tail})"), vstyle);
|
||||
if let Some(c) = opts.confidence {
|
||||
let ci = format!("FORECAST.ETS.CONFINT(A{r},{vl},{tl},{c},{tail})");
|
||||
formula(sheet, r - 1, 3, format!("=C{r}-{ci}"), vstyle);
|
||||
formula(sheet, r - 1, 4, format!("=C{r}+{ci}"), vstyle);
|
||||
}
|
||||
};
|
||||
// Hindcast: forecasts over the actuals from the start to the last history point.
|
||||
for r in (fit_last + 1)..=last {
|
||||
forecast_row(&mut sheet, r);
|
||||
}
|
||||
for (k, t) in future.iter().enumerate() {
|
||||
let r = last + k as u32 + 1; // 1-based
|
||||
put(&mut sheet, r - 1, 0, Value::Number(*t), tstyle);
|
||||
forecast_row(&mut sheet, r);
|
||||
}
|
||||
if opts.statistics {
|
||||
put(&mut sheet, 0, stats_col, Value::text("Statistic"), bold);
|
||||
put(&mut sheet, 0, stats_col + 1, Value::text("Value"), bold);
|
||||
for (k, label) in ["Alpha", "Beta", "Gamma", "MASE", "SMAPE", "MAE", "RMSE"].iter().enumerate() {
|
||||
let r = k as u32 + 1;
|
||||
put(&mut sheet, r, stats_col, Value::text(*label), StyleId::DEFAULT);
|
||||
formula(&mut sheet, r, stats_col + 1, format!("=FORECAST.ETS.STAT({vl},{tl},{},{tail})", k + 1), StyleId::DEFAULT);
|
||||
}
|
||||
}
|
||||
for c in 0..width {
|
||||
sheet.cols.insert(
|
||||
c,
|
||||
gridcraft_model::LineInfo {
|
||||
size: Some(match c {
|
||||
0 | 1 => 90.0,
|
||||
2 => 130.0,
|
||||
_ => 230.0,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let range = RangeRef::new(CellRef::new(0, 0), CellRef::new(end_row - 1, width - 1));
|
||||
sheet.tables.push(Table {
|
||||
id: table_id,
|
||||
name: table_name.clone(),
|
||||
range,
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: headers
|
||||
.iter()
|
||||
.map(|h| TableColumn { name: h.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.collect(),
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: true,
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
});
|
||||
let q = gridcraft_formula::quote_sheet(&sheet_name);
|
||||
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
|
||||
let series = (1..width)
|
||||
.map(|c| Series {
|
||||
name: Some(format!("{q}!${}$1", col_letters(c))),
|
||||
categories: Some(col_ref(0)),
|
||||
values: col_ref(c),
|
||||
bubble_sizes: None,
|
||||
color: None,
|
||||
secondary: false,
|
||||
kind: (opts.column_chart && c >= 3).then_some(ChartKind::Line),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
sheet.charts.push(Chart {
|
||||
id: chart_id,
|
||||
kind: if opts.column_chart { ChartKind::ColumnClustered } else { ChartKind::Line },
|
||||
anchor: Anchor { cell: CellRef::new(1, chart_col), dx: 0.0, dy: 0.0, width: 480.0, height: 288.0, mode: Default::default() },
|
||||
title: None,
|
||||
series,
|
||||
legend: LegendPos::Bottom,
|
||||
data_labels: false,
|
||||
gridlines: true,
|
||||
style: 1,
|
||||
x_title: None,
|
||||
y_title: None,
|
||||
source: None,
|
||||
by_rows: false,
|
||||
pivot: None,
|
||||
});
|
||||
cx.wb.sheets.insert(at, Arc::new(sheet));
|
||||
for nm in cx.wb.names.iter_mut() {
|
||||
if let Some(sc) = nm.scope.as_mut()
|
||||
&& *sc >= at
|
||||
{
|
||||
*sc += 1;
|
||||
}
|
||||
}
|
||||
cx.wb.active_sheet = at;
|
||||
*cx.sel = crate::Selection::at(CellRef::new(0, 0));
|
||||
cx.structural = true;
|
||||
Ok(at)
|
||||
})?;
|
||||
if let Ok(d) = s.doc_mut() {
|
||||
d.sheet_selections.insert(index.min(d.sheet_selections.len()), crate::Selection::default());
|
||||
}
|
||||
Ok(json!({"sheet": sheet_name, "table": table_name, "chart": chart_id, "history": n, "periods": periods, "fitted": fit}))
|
||||
}
|
||||
|
||||
/// Forecast rows needed to reach `end` (rounded up to whole steps).
|
||||
fn steps_to(timeline: &Timeline, end: f64, cap: u32) -> Result<u32> {
|
||||
let steps = timeline.steps_after_last(end).ok_or_else(|| bad(CMD, "`end` is not on the timeline"))?;
|
||||
if steps < 1e-9 {
|
||||
return Err(EngineError::Other("The forecast end must be after the last point of the timeline.".into()));
|
||||
}
|
||||
let steps = steps.ceil();
|
||||
if steps > f64::from(cap) {
|
||||
return Err(bad(CMD, format!("at most {cap} forecast steps for this much history")));
|
||||
}
|
||||
Ok(steps as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session_with_history() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let mut rows = vec![json!(["Month", "Sales"])];
|
||||
// y = 10 + 2t with a four-step season.
|
||||
let season = [3.0, -1.0, 4.0, -6.0];
|
||||
for t in 1..=16 {
|
||||
rows.push(json!([t, 10.0 + 2.0 * t as f64 + season[(t - 1) % 4]]));
|
||||
}
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn value(s: &Session, sheet: usize, a1: &str) -> Value {
|
||||
s.doc().unwrap().wb.sheet(sheet).unwrap().value(CellRef::parse(a1).unwrap())
|
||||
}
|
||||
|
||||
fn formula(s: &Session, sheet: usize, a1: &str) -> String {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
wb.sheet(sheet).unwrap().cell(CellRef::parse(a1).unwrap()).and_then(|c| c.formula.as_ref()).map(|f| f.text.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forecast_sheet_builds_table_formulas_and_chart() {
|
||||
let mut s = session_with_history();
|
||||
s.execute("selection.set", json!({"range": "A1:B17"})).unwrap();
|
||||
let r = s.execute("data.forecastSheet", json!({"periods": 4, "statistics": true})).unwrap();
|
||||
assert_eq!(r["history"], 16);
|
||||
assert_eq!(r["periods"], 4);
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
// Inserted before the data sheet and activated.
|
||||
assert_eq!(wb.active_sheet, 0);
|
||||
let sh = wb.sheet(0).unwrap();
|
||||
assert_eq!(sh.name, r["sheet"].as_str().unwrap());
|
||||
assert_eq!(value(&s, 0, "C1"), Value::text("Forecast(Sales)"));
|
||||
assert_eq!(value(&s, 0, "D1"), Value::text("Lower Confidence Bound(Sales)"));
|
||||
assert_eq!(value(&s, 0, "E1"), Value::text("Upper Confidence Bound(Sales)"));
|
||||
assert_eq!(formula(&s, 0, "C17"), "B17");
|
||||
assert_eq!(formula(&s, 0, "C18"), "FORECAST.ETS(A18,$B$2:$B$17,$A$2:$A$17,1,1)");
|
||||
assert_eq!(formula(&s, 0, "D18"), "C18-FORECAST.ETS.CONFINT(A18,$B$2:$B$17,$A$2:$A$17,0.95,1,1)");
|
||||
assert_eq!(formula(&s, 0, "H2"), "FORECAST.ETS.STAT($B$2:$B$17,$A$2:$A$17,1,1,1)");
|
||||
// Future timeline and the exact continuation of the seasonal series (t = 17 → 10 + 34 + 3).
|
||||
assert_eq!(value(&s, 0, "A18"), Value::Number(17.0));
|
||||
assert_eq!(value(&s, 0, "A21"), Value::Number(20.0));
|
||||
let c18 = value(&s, 0, "C18").as_f64().unwrap();
|
||||
assert!((c18 - 47.0).abs() < 1e-6, "{c18}");
|
||||
let (lo, hi) = (value(&s, 0, "D19").as_f64().unwrap(), value(&s, 0, "E19").as_f64().unwrap());
|
||||
assert!(lo <= hi);
|
||||
assert_eq!(sh.tables.first().map(|t| t.range.a1()), Some("A1:E21".into()));
|
||||
let chart = sh.charts.first().unwrap();
|
||||
assert_eq!(chart.series.len(), 4);
|
||||
assert_eq!(chart.series[1].values, format!("{}!$C$2:$C$21", r["sheet"].as_str().unwrap()));
|
||||
// One undo step removes the sheet again.
|
||||
let sheets = s.doc().unwrap().wb.sheets.len();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_and_periods_are_capped() {
|
||||
use super::{MAX_HISTORY, MAX_PERIODS, MAX_WORK, default_periods, max_periods};
|
||||
// The default (a third of the history) never exceeds the caps.
|
||||
assert_eq!(default_periods(16), 6);
|
||||
assert_eq!(default_periods(1_200), 400);
|
||||
assert_eq!(default_periods(3_000), 166);
|
||||
assert_eq!(default_periods(100_000), 5);
|
||||
assert_eq!(max_periods(10), MAX_PERIODS);
|
||||
assert_eq!(max_periods(0), MAX_PERIODS);
|
||||
for h in [1usize, 2, 3, 50, 51, 1_000, 1_300, 3_000, 10_000, 100_000, usize::MAX] {
|
||||
let (d, m) = (default_periods(h), max_periods(h));
|
||||
assert!(d >= 1 && d <= m && m <= MAX_PERIODS, "{h}: {d} {m}");
|
||||
assert!(u64::try_from(h).unwrap_or(u64::MAX).saturating_mul(u64::from(m)) <= MAX_WORK.max(u64::try_from(h).unwrap_or(u64::MAX)), "{h}");
|
||||
}
|
||||
// Explicit periods or an end past the cap are refused before anything is built.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let mut rows = vec![json!(["t", "y"])];
|
||||
rows.extend((1..=1_300).map(|t| json!([t, (t % 7) as f64 + t as f64 * 0.5])));
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let sheets = s.doc().unwrap().wb.sheets.len();
|
||||
let cap = max_periods(1_300); // 384
|
||||
let err = |r: crate::Result<serde_json::Value>| r.err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(err(s.execute("data.forecastSheet", json!({"range": "A1:B1301", "periods": cap + 1}))).contains("from 1 to 384"));
|
||||
assert!(err(s.execute("data.forecastSheet", json!({"range": "A1:B1301", "end": 1_300 + cap + 1}))).contains("at most 384"));
|
||||
assert!(s.execute("data.forecastSheet", json!({"range": "A1:B1301", "periods": 10_000})).is_err());
|
||||
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets);
|
||||
// More history rows than MAX_HISTORY are refused.
|
||||
let big = MAX_HISTORY + 2;
|
||||
let r = s.execute("data.forecastSheet", json!({"timeline": format!("A1:A{big}"), "values": format!("B1:B{big}")}));
|
||||
assert!(r.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forecast_sheet_parameters_and_errors() {
|
||||
let mut s = session_with_history();
|
||||
let r = s
|
||||
.execute(
|
||||
"data.forecastSheet",
|
||||
json!({"timeline": "A2:A17", "values": "B2:B17", "end": "22", "confidenceInterval": false, "seasonality": 4, "fillMissing": "zeros", "aggregate": "sum", "chart": "column"}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["periods"], 6);
|
||||
assert_eq!(value(&s, 0, "B1"), Value::text("Values"));
|
||||
assert_eq!(formula(&s, 0, "C18"), "FORECAST.ETS(A18,$B$2:$B$17,$A$2:$A$17,4,0,7)");
|
||||
assert_eq!(value(&s, 0, "D1"), Value::Empty);
|
||||
let sh = s.doc().unwrap().wb.sheet(0).unwrap();
|
||||
assert_eq!(sh.charts.first().map(|c| c.kind), Some(gridcraft_model::ChartKind::ColumnClustered));
|
||||
// Errors: end before the data, bad seasonality, uneven timeline, one column only.
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
|
||||
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!A1:B17", "end": 3})).is_err());
|
||||
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!A1:B17", "seasonality": 9000})).is_err());
|
||||
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!B1:B17"})).is_err());
|
||||
s.execute("cell.set", json!({"cell": "A5", "input": "4.5"})).unwrap();
|
||||
assert!(s.execute("data.forecastSheet", json!({"range": "Sheet1!A1:B17"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forecast_start_hindcasts_over_the_actuals() {
|
||||
let mut s = session_with_history(); // t = 1..16 in A2:A17
|
||||
let r = s.execute("data.forecastSheet", json!({"range": "A1:B17", "forecastStart": 13, "periods": 2, "confidenceInterval": false})).unwrap();
|
||||
assert_eq!(r["fitted"], 12);
|
||||
// Fit to t = 1..12 (rows 2..13); the line joins at row 13 and forecasts rows 14..19.
|
||||
assert_eq!(formula(&s, 0, "C13"), "B13");
|
||||
assert_eq!(value(&s, 0, "C13"), value(&s, 0, "B13"));
|
||||
assert_eq!(formula(&s, 0, "C14"), "FORECAST.ETS(A14,$B$2:$B$13,$A$2:$A$13,1,1)");
|
||||
assert_eq!(formula(&s, 0, "C19"), "FORECAST.ETS(A19,$B$2:$B$13,$A$2:$A$13,1,1)");
|
||||
// The exact seasonal series is recovered, and the actual is still shown next to it.
|
||||
let c14 = value(&s, 0, "C14").as_f64().unwrap();
|
||||
assert!((c14 - 39.0).abs() < 1e-6, "{c14}"); // t = 13: 10 + 26 + 3
|
||||
assert!(value(&s, 0, "B14").as_f64().is_some());
|
||||
// Start at the last point or one step later: as without forecastStart.
|
||||
for start in [json!(16), json!(17)] {
|
||||
let r = s.execute("data.forecastSheet", json!({"range": "Sheet1!A1:B17", "forecastStart": start, "periods": 2})).unwrap();
|
||||
assert_eq!(r["fitted"], 16);
|
||||
}
|
||||
assert_eq!(formula(&s, 0, "C18"), "FORECAST.ETS(A18,$B$2:$B$17,$A$2:$A$17,1,1)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forecast_start_invalid_values_are_errors() {
|
||||
let mut s = session_with_history();
|
||||
let sheets = s.doc().unwrap().wb.sheets.len();
|
||||
for bad in [json!(0), json!(2), json!(3.5), json!(18), json!(1000), json!("abc"), json!([1]), json!(1e308)] {
|
||||
assert!(s.execute("data.forecastSheet", json!({"range": "A1:B17", "forecastStart": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets);
|
||||
// Blank or null behaves like no start; empty params unchanged.
|
||||
let r = s.execute("data.forecastSheet", json!({"range": "A1:B17", "forecastStart": ""})).unwrap();
|
||||
assert_eq!(r["fitted"], 16);
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Alignment
|
||||
cmd!("home.alignLeft", "Align Left", ["Home", "Alignment"], Some("Cmd+L"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Left)),
|
||||
cmd!("home.alignCenter", "Center", ["Home", "Alignment"], Some("Cmd+E"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Center)),
|
||||
cmd!("home.alignRight", "Align Right", ["Home", "Alignment"], Some("Cmd+R"), "{range?}", has_doc, |s, p| halign(s, p, HAlign::Right)),
|
||||
cmd!("home.alignRight", "Align Right", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Right)),
|
||||
cmd!("home.justify", "Justify", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| halign(s, p, HAlign::Justify)),
|
||||
cmd!("home.alignTop", "Top Align", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| valign(s, p, VAlign::Top)),
|
||||
cmd!("home.alignMiddle", "Middle Align", ["Home", "Alignment"], None, "{range?}", has_doc, |s, p| valign(s, p, VAlign::Center)),
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Row Height…",
|
||||
["Home", "Cells", "Format"],
|
||||
None,
|
||||
"{rows?: \"2:5\", height: 20 (points on screen)}",
|
||||
"{rows?: \"2:5\" | \"2:2,4:5\", height: 20 (points on screen)}",
|
||||
has_doc,
|
||||
row_height
|
||||
),
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Column Width…",
|
||||
["Home", "Cells", "Format"],
|
||||
None,
|
||||
"{cols?: \"B:D\", width: 64 (points) | chars: 8.43}",
|
||||
"{cols?: \"B:D\" | \"B:B,D:F\", width: 64 (points) | chars: 8.43}",
|
||||
has_doc,
|
||||
col_width
|
||||
),
|
||||
@@ -237,10 +237,12 @@ pub(crate) fn apply_style(s: &mut Session, p: &Json, f: impl Fn(&mut Style)) ->
|
||||
// Existing cells in those lines.
|
||||
let cells: Vec<(CellRef, StyleId)> =
|
||||
cx.wb.sheet(sheet).map(|sh| sh.cells.iter_range(*r).map(|(c, x)| (c, x.style)).collect()).unwrap_or_default();
|
||||
for (c, st) in cells {
|
||||
let new = *cache.entry(st).or_insert_with(|| cx.wb.styles.derive(st, &f));
|
||||
cx.sheet_mut(sheet)?.set_style(c, new);
|
||||
for (c, st) in &cells {
|
||||
let new = *cache.entry(*st).or_insert_with(|| cx.wb.styles.derive(*st, &f));
|
||||
cx.sheet_mut(sheet)?.set_style(*c, new);
|
||||
}
|
||||
// Formatting touched these cells: re-fit their rows (Excel auto-fits).
|
||||
cx.fit_rows.extend(cells.iter().map(|(c, _)| (sheet, c.row)));
|
||||
continue;
|
||||
}
|
||||
if r.count() > 4_000_000 {
|
||||
@@ -561,8 +563,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
|
||||
if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how };
|
||||
edit(s, |cx| {
|
||||
let mut touched = Vec::new();
|
||||
// Areas whose merging changes: a merged cell blocks a dynamic array's spill.
|
||||
let mut areas: Vec<RangeRef> = ranges.clone();
|
||||
for r in &ranges {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
areas.extend(sh.merges.iter().filter(|m| m.intersects(r)));
|
||||
sh.merges.retain(|m| !m.intersects(r));
|
||||
match how {
|
||||
"unmerge" => {}
|
||||
@@ -571,6 +576,16 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
|
||||
let m = RangeRef::new(CellRef::new(row, r.start.col), CellRef::new(row, r.end.col));
|
||||
if !m.is_single() {
|
||||
sh.merges.push(m);
|
||||
// As below: only the first value of each row survives.
|
||||
let others: Vec<CellRef> = sh.cells.iter_range(m).map(|(c, _)| c).filter(|c| *c != m.start).collect();
|
||||
for c in others {
|
||||
if let Some(mut cell) = sh.cells.get(c).cloned() {
|
||||
cell.value = gridcraft_core::Value::Empty;
|
||||
cell.formula = None;
|
||||
sh.set_cell(c, cell);
|
||||
}
|
||||
touched.push((sheet, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -593,6 +608,17 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Spills over the areas, and blocked ones that could reach them, are evaluated again.
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
for a in &areas {
|
||||
touched.extend(sh.spill_ranges.iter().filter(|(_, r)| r.intersects(a)).map(|(anchor, _)| (sheet, *anchor)));
|
||||
let reach = RangeRef::new(CellRef::new(0, 0), a.end);
|
||||
let blocked = sh
|
||||
.cells
|
||||
.iter_range(reach)
|
||||
.filter(|(_, x)| x.formula.is_some() && x.value == gridcraft_core::Value::Error(gridcraft_core::CellError::Spill));
|
||||
touched.extend(blocked.map(|(c, _)| (sheet, c)));
|
||||
}
|
||||
cx.changed.extend(touched);
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -910,8 +936,14 @@ fn cell_style(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn line_targets(s: &Session, p: &Json, rows: bool) -> Result<Vec<(u32, u32)>> {
|
||||
let key = if rows { "rows" } else { "cols" };
|
||||
if let Some(t) = str_param(p, key) {
|
||||
let r = RangeRef::parse(t).ok_or_else(|| bad(key, format!("not a range: {t}")))?;
|
||||
return Ok(vec![if rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) }]);
|
||||
// A comma-separated list ("B:B,D:F") targets several areas, like a multi-area selection.
|
||||
return t
|
||||
.split(',')
|
||||
.map(|part| {
|
||||
let r = RangeRef::parse(part).ok_or_else(|| bad(key, format!("not a range: {part}")))?;
|
||||
Ok(if rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
Ok(s.doc()?.selection.ranges.iter().map(|r| if rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) }).collect())
|
||||
}
|
||||
@@ -933,6 +965,7 @@ fn row_height(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
e.custom = true;
|
||||
}
|
||||
}
|
||||
cx.structural = true; // setting a height shows or hides rows: SUBTOTAL(10x) depends on it
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
@@ -972,9 +1005,7 @@ pub fn chars_to_points(c: f64) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn points_to_chars(px: f64) -> f64 {
|
||||
if px <= 12.0 { (px / 12.0 * 100.0).round() / 100.0 } else { ((px - 5.0) / 7.0 * 100.0 + 0.5).trunc() / 100.0 }
|
||||
}
|
||||
pub use gridcraft_model::points_to_chars;
|
||||
|
||||
/// Approximate text width in points for autofit (no font metrics in the engine: average glyph
|
||||
/// widths for the default font; the UI refines with real measurement when it autofits).
|
||||
@@ -1013,7 +1044,9 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let st = cx.wb.styles.get(sh.style_id(cell));
|
||||
let text = crate::display::cell_text(&cx.wb, sh, cell);
|
||||
for line in text.lines() {
|
||||
max = max.max(approx_text_width(line, st.font.size, st.font.bold) + 6.0 + st.align.indent as f32 * 9.0);
|
||||
max = max.max(
|
||||
approx_text_width(line, st.font.size, st.font.bold) + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell),
|
||||
);
|
||||
}
|
||||
}
|
||||
if max > 0.0 {
|
||||
@@ -1047,6 +1080,7 @@ fn autofit_rows(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
cx.fit_rows.extend((a..=b).map(|r| (si, r)));
|
||||
}
|
||||
cx.structural = true; // autofit reveals hidden rows: SUBTOTAL(10x) depends on it
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
@@ -1090,6 +1124,19 @@ fn hide(s: &mut Session, p: &Json, rows: bool, on: bool) -> Result<Json> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn merge_across_keeps_the_first_value_of_each_row() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2], [3, 4]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=SUM(A1:B2)"})).unwrap();
|
||||
s.execute("home.mergeAcross", json!({"range": "A1:B2"})).unwrap();
|
||||
let v = |s: &mut crate::Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone();
|
||||
assert_eq!(v(&mut s, "B1"), Json::Null);
|
||||
assert_eq!(v(&mut s, "B2"), Json::Null);
|
||||
assert_eq!(v(&mut s, "D1"), json!(4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_steps() {
|
||||
let v = gridcraft_core::Value::Number(1.5);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Formulas tab: AutoSum, Insert Function, names, auditing, calculation.
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef};
|
||||
use gridcraft_model::{CalcMode, DefinedName};
|
||||
use gridcraft_model::{CalcMode, DefinedName, Formula};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::*;
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Define Name…",
|
||||
["Formulas", "Defined Names"],
|
||||
None,
|
||||
"{name, refersTo?: \"=Sheet1!$A$1:$A$10\" (default: the selection), scope?: \"Workbook\"|sheet name, comment?}",
|
||||
"{name, refersTo?: \"=Sheet1!$A$1:$A$10\" (default: the selection), scope?: \"Workbook\"|sheet name, comment?, oldName?, oldScope?} (oldName: edit that name (Name Manager › Edit); a new name also renames it in formulas)",
|
||||
has_doc,
|
||||
define_name
|
||||
),
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Calculation Options",
|
||||
["Formulas", "Calculation"],
|
||||
None,
|
||||
"{mode: automatic|automaticExceptTables|manual, iterative?, maxIterations?, maxChange?}",
|
||||
"{mode?: automatic|automaticExceptTables|manual, iterative?: bool (Enable iterative calculation), maxIterations?: 1–32767 (100), maxChange?: number (0.001)} → the settings. File › Options › Formulas › Calculation options; stored in the workbook.",
|
||||
has_doc,
|
||||
calc_options
|
||||
),
|
||||
@@ -78,18 +78,28 @@ fn auto_sum(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
if !sel.is_single() {
|
||||
// A block: totals below each column (and to the right when a blank column is included).
|
||||
let num_end = sel.end;
|
||||
let below = CellRef::new(num_end.row + 1, 0);
|
||||
let mut writes = Vec::new();
|
||||
let last_row_blank = (sel.start.col..=sel.end.col).all(|c| sh.value(CellRef::new(sel.end.row, c)).is_empty());
|
||||
let (data_end_row, out_row) = if last_row_blank { (sel.end.row.saturating_sub(1), sel.end.row) } else { (sel.end.row, below.row) };
|
||||
for c in sel.start.col..=sel.end.col {
|
||||
let r = RangeRef::new(CellRef::new(sel.start.row, c), CellRef::new(data_end_row, c));
|
||||
writes.push((CellRef::new(out_row, c), format!("={func}({})", r.a1())));
|
||||
}
|
||||
for (c, f) in writes {
|
||||
s.execute("cell.set", json!({"cell": c.a1(), "input": f}))?;
|
||||
// Columns past the sheet's data get no total (a whole-row selection doesn't write 16,384
|
||||
// formulas), and all totals are one edit (one undo step).
|
||||
let Some(last_col) = sh.cells.used_range().map(|u| u.end.col.min(sel.end.col)) else { return ok() };
|
||||
let last_row_blank = (sel.start.col..=last_col).all(|c| sh.value(CellRef::new(sel.end.row, c)).is_empty());
|
||||
let (data_end_row, out_row) = if last_row_blank { (sel.end.row.saturating_sub(1), sel.end.row) } else { (sel.end.row, sel.end.row + 1) };
|
||||
if out_row >= gridcraft_core::MAX_ROWS {
|
||||
return Err(EngineError::Other("There's no room below the selection for the totals.".into()));
|
||||
}
|
||||
let writes: Vec<(CellRef, String)> = (sel.start.col..=last_col)
|
||||
.map(|c| {
|
||||
(CellRef::new(out_row, c), format!("={func}({})", RangeRef::new(CellRef::new(sel.start.row, c), CellRef::new(data_end_row, c)).a1()))
|
||||
})
|
||||
.collect();
|
||||
let sheet = d.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
for (c, f) in &writes {
|
||||
let cell = super::edit::input_to_cell(f, sheet, *c, &mut cx.wb)?.unwrap_or_default();
|
||||
cx.sheet_mut(sheet)?.set_cell(*c, cell);
|
||||
cx.touch(sheet, *c);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
// Single cell: guess the range above, else to the left.
|
||||
@@ -185,6 +195,7 @@ pub fn function_list() -> Vec<Json> {
|
||||
("SHEET", "Information", "SHEET([value])", "Sheet number."),
|
||||
("SHEETS", "Information", "SHEETS([reference])", "Number of sheets."),
|
||||
("AREAS", "Lookup", "AREAS(reference)", "Number of areas in a reference."),
|
||||
("TRIMRANGE", "Lookup", "TRIMRANGE(range, [trim_rows], [trim_cols])", "A range or array without its blank outer rows and columns."),
|
||||
("ISOMITTED", "Information", "ISOMITTED(argument)", "TRUE when a LAMBDA argument was left out."),
|
||||
];
|
||||
for (n, c, sig, d) in specials {
|
||||
@@ -252,7 +263,15 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Some(sh) => Some(d.wb.sheet_index(sh).ok_or_else(|| bad("formulas.defineName", "no such sheet"))?),
|
||||
};
|
||||
let refers = match str_param(p, "refersTo") {
|
||||
Some(r) => r.trim_start_matches('=').to_string(),
|
||||
// As in Excel, relative references are relative to the active cell; names keep them
|
||||
// relative to A1, as files do.
|
||||
Some(r) => match gridcraft_formula::parse(r.trim_start_matches('=')) {
|
||||
Ok(e) if gridcraft_formula::adjust::has_relative_refs(&e) => {
|
||||
let at = d.selection.active;
|
||||
gridcraft_formula::print(&gridcraft_formula::adjust::shift_relative_wrapping(e, -(at.row as i64), -(at.col as i64)))
|
||||
}
|
||||
_ => r.trim_start_matches('=').to_string(),
|
||||
},
|
||||
None => {
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let r = d.selection.current();
|
||||
@@ -265,7 +284,32 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(EngineError::Other("There's a problem with this formula.".into()));
|
||||
}
|
||||
let comment = str_param(p, "comment").unwrap_or("").to_string();
|
||||
// Editing an existing name (Name Manager › Edit…): it must exist, and its new name must not
|
||||
// collide with another name in the target scope.
|
||||
let old = match str_param(p, "oldName") {
|
||||
Some(old_name) => {
|
||||
let old_scope = match str_param(p, "oldScope") {
|
||||
None | Some("Workbook") => None,
|
||||
Some(sh) => Some(d.wb.sheet_index(sh).ok_or_else(|| bad("formulas.defineName", "no such sheet"))?),
|
||||
};
|
||||
if !d.wb.names.iter().any(|n| n.name.eq_ignore_ascii_case(old_name) && n.scope == old_scope) {
|
||||
return Err(bad("formulas.defineName", "no such name to edit"));
|
||||
}
|
||||
let same = old_name.eq_ignore_ascii_case(&name) && old_scope == scope;
|
||||
if !same && d.wb.names.iter().any(|n| n.name.eq_ignore_ascii_case(&name) && n.scope == scope) {
|
||||
return Err(EngineError::Other("The name entered already exists. Enter a unique name.".into()));
|
||||
}
|
||||
Some((old_name.to_string(), old_scope))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
edit(s, |cx| {
|
||||
if let Some((old_name, old_scope)) = &old {
|
||||
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(old_name) && n.scope == *old_scope));
|
||||
if !old_name.eq_ignore_ascii_case(&name) {
|
||||
rename_name_in_formulas(&mut cx.wb, old_name, *old_scope, &name);
|
||||
}
|
||||
}
|
||||
cx.wb.names.retain(|n| !(n.name.eq_ignore_ascii_case(&name) && n.scope == scope));
|
||||
cx.wb.names.push(DefinedName { name: name.clone(), scope, formula: refers.clone(), comment: comment.clone(), hidden: false });
|
||||
cx.structural = true;
|
||||
@@ -273,6 +317,51 @@ fn define_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Formulas that use a renamed name follow it: cell formulas and other names' definitions, on
|
||||
/// the sheets where `old` resolves to the renamed name (its own sheet for a sheet-scoped name;
|
||||
/// every sheet without a same-named sheet-level name for a workbook-level one).
|
||||
fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_scope: Option<usize>, new: &str) {
|
||||
let shadowed: Vec<usize> = wb.names.iter().filter(|n| n.name.eq_ignore_ascii_case(old)).filter_map(|n| n.scope).collect();
|
||||
let applies = |sheet: usize| match old_scope {
|
||||
Some(s) => s == sheet,
|
||||
None => !shadowed.contains(&sheet),
|
||||
};
|
||||
// The renamed expression, or `None` when the name doesn't occur in it.
|
||||
let rename = |e: gridcraft_formula::Expr| {
|
||||
let mut hit = false;
|
||||
let out = e.map(&mut |x| match x {
|
||||
gridcraft_formula::Expr::Name(n) if n.eq_ignore_ascii_case(old) => {
|
||||
hit = true;
|
||||
gridcraft_formula::Expr::Name(new.to_string())
|
||||
}
|
||||
o => o,
|
||||
});
|
||||
hit.then_some(out)
|
||||
};
|
||||
for i in 0..wb.sheets.len() {
|
||||
if !applies(i) {
|
||||
continue;
|
||||
}
|
||||
let Some(sh) = wb.sheet_mut(i) else { continue };
|
||||
let formulas: Vec<(CellRef, std::sync::Arc<Formula>)> = sh.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect();
|
||||
for (c, f) in formulas {
|
||||
let Some(e) = f.expr().and_then(rename) else { continue };
|
||||
let mut nf = Formula::from_expr(e);
|
||||
nf.array = f.array;
|
||||
if let Some(cell) = sh.cells.get_mut(c) {
|
||||
cell.formula = Some(std::sync::Arc::new(nf));
|
||||
}
|
||||
}
|
||||
}
|
||||
for n in wb.names.iter_mut() {
|
||||
if n.scope.is_none_or(applies)
|
||||
&& let Some(e) = gridcraft_formula::parse(&n.formula).ok().and_then(rename)
|
||||
{
|
||||
n.formula = gridcraft_formula::print(&e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn delete_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("formulas.deleteName", "missing `name`"))?.to_string();
|
||||
let scope = match str_param(p, "scope") {
|
||||
@@ -373,7 +462,7 @@ fn create_from_selection(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn trace_precedents(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let areas = d.calc.graph.precedents_of((d.wb.active_sheet, at));
|
||||
let v: Vec<Json> = areas.iter().map(|a| json!({"sheet": d.wb.sheet(a.sheet).map(|s| s.name.clone()), "range": a.range.a1()})).collect();
|
||||
Ok(Json::Array(v))
|
||||
@@ -381,7 +470,7 @@ fn trace_precedents(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn trace_dependents(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let mut deps = Vec::new();
|
||||
d.calc.graph.dependents(d.wb.active_sheet, at, &mut deps);
|
||||
deps.sort();
|
||||
@@ -422,7 +511,7 @@ fn error_checking(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
|
||||
fn evaluate_formula(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let sheet = d.wb.active_sheet;
|
||||
let text = match str_param(p, "formula") {
|
||||
Some(f) => f.trim_start_matches('=').to_string(),
|
||||
@@ -454,7 +543,7 @@ fn evaluate_formula(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn evaluate(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let f = str_param(p, "formula").ok_or_else(|| bad("formulas.evaluate", "missing `formula`"))?;
|
||||
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let v = gridcraft_calc::evaluate(&d.wb, d.wb.active_sheet, at, f);
|
||||
Ok(crate::cmd::inspect::value_json(&v))
|
||||
}
|
||||
@@ -475,6 +564,7 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
_ => None,
|
||||
};
|
||||
edit(s, |cx| {
|
||||
let before = cx.wb.calc.clone();
|
||||
if let Some(m) = mode {
|
||||
cx.wb.calc.mode = m;
|
||||
}
|
||||
@@ -482,14 +572,42 @@ fn calc_options(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
cx.wb.calc.iterative = v;
|
||||
}
|
||||
if let Some(v) = u32_param(p, "maxIterations") {
|
||||
cx.wb.calc.max_iterations = v.clamp(1, 32767);
|
||||
cx.wb.calc.set_max_iterations(v);
|
||||
}
|
||||
if let Some(v) = f64_param(p, "maxChange") {
|
||||
cx.wb.calc.max_change = v.abs();
|
||||
cx.wb.calc.set_max_change(v);
|
||||
}
|
||||
if mode == Some(CalcMode::Automatic) {
|
||||
let c = &cx.wb.calc;
|
||||
// Switching to automatic, or changing how circular references are calculated outside
|
||||
// manual mode, recalculates the workbook.
|
||||
let iteration_changed = (c.iterative, c.max_iterations, c.max_change) != (before.iterative, before.max_iterations, before.max_change);
|
||||
if mode == Some(CalcMode::Automatic) || (iteration_changed && c.mode != CalcMode::Manual) {
|
||||
cx.structural = true;
|
||||
}
|
||||
Ok(json!({"mode": format!("{:?}", cx.wb.calc.mode)}))
|
||||
Ok(json!({"mode": format!("{:?}", c.mode), "iterative": c.iterative, "maxIterations": c.max_iterations, "maxChange": c.max_change}))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_with_relative_references() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [3]]})).unwrap();
|
||||
// Defined from B2, `=Sheet1!A2` is "the cell to the left".
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
let r = s.execute("formulas.defineName", json!({"name": "LeftCell", "refersTo": "=Sheet1!A2"})).unwrap();
|
||||
assert_eq!(r["refersTo"], "=Sheet1!XFD1");
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": "=LeftCell"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "B3", "input": "=LeftCell*10"})).unwrap();
|
||||
let v = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone();
|
||||
assert_eq!(v(&mut s, "B1"), json!(1.0));
|
||||
assert_eq!(v(&mut s, "B3"), json!(30.0));
|
||||
// Absolute references are kept as they are.
|
||||
let r = s.execute("formulas.defineName", json!({"name": "First", "refersTo": "=Sheet1!$A$1"})).unwrap();
|
||||
assert_eq!(r["refersTo"], "=Sheet1!$A$1");
|
||||
}
|
||||
}
|
||||
|
||||
+284
-49
@@ -1,7 +1,7 @@
|
||||
//! Insert tab: tables, charts, sparklines, pictures, shapes, hyperlinks, comments and notes,
|
||||
//! conditional formatting (Home › Styles) and symbols.
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef};
|
||||
use gridcraft_core::{CellRef, MAX_ROWS, RangeRef};
|
||||
use gridcraft_model::*;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
@@ -67,10 +67,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
insert_chart
|
||||
),
|
||||
cmd!("insert.recommendedCharts", "Recommended Charts", ["Insert", "Charts"], None, "{range?}", has_doc, |s, p| insert_chart(
|
||||
s,
|
||||
&with(p, "type", json!("auto"))
|
||||
)),
|
||||
cmd!(
|
||||
"insert.recommendedCharts",
|
||||
"Recommended Charts",
|
||||
["Insert", "Charts"],
|
||||
None,
|
||||
"{range?, type?, subtype?} (no type: the first of insert.chartRecommendations; the ribbon button opens the dialog)",
|
||||
has_doc,
|
||||
|s, p| insert_chart(s, &if p.get("type").is_some() { p.clone() } else { with(p, "type", json!("auto")) })
|
||||
),
|
||||
cmd!(
|
||||
query "insert.chartRecommendations",
|
||||
"Chart Recommendations",
|
||||
[],
|
||||
None,
|
||||
"{range?} → [{type, subtype, label}] chart types that suit the data's shape, best first",
|
||||
has_doc,
|
||||
|s, p| Ok(Json::Array(recommend_charts(s, p)?.into_iter().map(|(t, sub, label)| json!({"type": t, "subtype": sub, "label": label})).collect()))
|
||||
),
|
||||
cmd!(
|
||||
"chart.set",
|
||||
"Chart Properties",
|
||||
@@ -139,12 +153,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Link",
|
||||
["Insert", "Links"],
|
||||
Some("Cmd+K"),
|
||||
"{cell?, target: \"https://…\" | \"Sheet2!A1\" | \"mailto:…\", text?, tooltip?, remove?: bool}",
|
||||
"{cell?, target: \"https://…\" | \"Book.xlsx\" | \"Sheet2!A1\" | \"mailto:…\", text?, tooltip?, remove?: bool}",
|
||||
has_doc,
|
||||
insert_link
|
||||
),
|
||||
cmd!("review.newNote", "New Note", ["Review", "Notes"], None, "{cell?, text, author?}", has_doc, |s, p| comment(s, p, false)),
|
||||
cmd!("review.newComment", "New Comment", ["Review", "Comments"], None, "{cell?, text, author?}", has_doc, |s, p| comment(s, p, true)),
|
||||
cmd!(
|
||||
"link.open",
|
||||
"Open Hyperlink",
|
||||
[],
|
||||
None,
|
||||
"{url?: \"https://…\" | \"mailto:…\" | \"Sheet2!A1\", cell?} (default: the cell's link); only http, https and mailto are opened, any other scheme is an error; the UI asks before opening",
|
||||
has_doc,
|
||||
open_link
|
||||
),
|
||||
cmd!("review.newNote", "New Note", ["Review", "Notes"], Some("Shift+F2"), "{cell?, text, author?}", has_doc, |s, p| comment(s, p, false)),
|
||||
cmd!("review.newComment", "New Comment", ["Review", "Comments"], Some("Cmd+Shift+F2"), "{cell?, text, author?}", has_doc, |s, p| comment(
|
||||
s, p, true
|
||||
)),
|
||||
cmd!("review.replyComment", "Reply", [], None, "{cell?, text, author?}", has_doc, reply_comment),
|
||||
cmd!("review.resolveComment", "Resolve Thread", [], None, "{cell?, resolved?: true}", has_doc, resolve_comment),
|
||||
cmd!("review.deleteComment", "Delete Comment", ["Review", "Comments"], None, "{cell?}", has_doc, delete_comment),
|
||||
@@ -208,6 +233,12 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if d.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.range.intersects(&r))) {
|
||||
return Err(EngineError::Other("A table can't overlap another table.".into()));
|
||||
}
|
||||
let arrays = |sh: &gridcraft_model::Sheet| {
|
||||
sh.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r)))
|
||||
};
|
||||
if d.wb.sheet(sheet).is_some_and(arrays) {
|
||||
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
|
||||
}
|
||||
if r.count() > 50_000_000 {
|
||||
return Err(bad("insert.table", "range too large"));
|
||||
}
|
||||
@@ -218,9 +249,19 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let name = str_param(p, "name")
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| (1..).map(|n| format!("Table{n}")).find(|n| d.wb.table(n).is_none()).unwrap_or_else(|| "Table".into()));
|
||||
if !valid_table_name(&name) {
|
||||
return Err(EngineError::Other("The name that you entered is not valid.".into()));
|
||||
}
|
||||
if d.wb.table(&name).is_some() || d.wb.names.iter().any(|n| n.name.eq_ignore_ascii_case(&name)) {
|
||||
return Err(EngineError::Other("The name entered already exists. Enter a unique name.".into()));
|
||||
}
|
||||
// Without a header row, the data moves down a row to make room for one: never a table with it.
|
||||
let moves_a_table = |sh: &gridcraft_model::Sheet| {
|
||||
sh.tables.iter().any(|t| t.range.end.row >= r.start.row && t.range.start.col <= r.end.col && t.range.end.col >= r.start.col)
|
||||
};
|
||||
if !header && d.wb.sheet(sheet).is_some_and(moves_a_table) {
|
||||
return Err(EngineError::Other("This operation isn't allowed: it would shift cells in a table on your worksheet.".into()));
|
||||
}
|
||||
let style = str_param(p, "style").unwrap_or("TableStyleMedium2").to_string();
|
||||
let id = d.wb.next_object_id();
|
||||
edit(s, |cx| {
|
||||
@@ -229,6 +270,11 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
r
|
||||
} else {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// The header row pushes the data down one row: never off the end of the sheet.
|
||||
let last = RangeRef::new(CellRef::new(MAX_ROWS - 1, r.start.col), CellRef::new(MAX_ROWS - 1, r.end.col));
|
||||
if sh.cells.iter_range(last).any(|(_, x)| x.formula.is_some() || !x.value.is_empty()) {
|
||||
return Err(EngineError::Other("To prevent possible loss of data, cells can't be pushed off the end of the worksheet.".into()));
|
||||
}
|
||||
sh.cells.shift_rows_in_cols(r.start.col, r.end.col, r.start.row, 1);
|
||||
sh.cell_pictures = std::mem::take(&mut sh.cell_pictures)
|
||||
.into_iter()
|
||||
@@ -241,7 +287,7 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
sh.set_value(CellRef::new(r.start.row, c), gridcraft_core::Value::text(format!("Column{}", i + 1)));
|
||||
}
|
||||
cx.structural = true;
|
||||
RangeRef::new(r.start, CellRef::new(r.end.row + 1, r.end.col))
|
||||
RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col))
|
||||
};
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
@@ -273,13 +319,19 @@ fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
range: r,
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: names.into_iter().map(|n| TableColumn { name: n, totals: TotalsFn::None, totals_label: None, formula: None }).collect(),
|
||||
columns: names
|
||||
.into_iter()
|
||||
.map(|n| TableColumn { name: n, totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.collect(),
|
||||
style,
|
||||
banded_rows: true,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: true,
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
});
|
||||
cx.structural = true;
|
||||
Ok(json!({"table": name, "range": r.a1()}))
|
||||
@@ -311,6 +363,9 @@ fn table_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
|
||||
"totals" => {
|
||||
let v = on.unwrap_or(!t.totals_row);
|
||||
if v != t.totals_row {
|
||||
if v && t.range.end.row.saturating_add(1) >= MAX_ROWS {
|
||||
return Err(EngineError::Other("There's no room below the table for the total row.".into()));
|
||||
}
|
||||
t.totals_row = v;
|
||||
if v {
|
||||
t.range.end.row += 1;
|
||||
@@ -339,7 +394,12 @@ fn table_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
|
||||
"bandedCols" => t.banded_cols = on.unwrap_or(!t.banded_cols),
|
||||
"firstCol" => t.first_col = on.unwrap_or(!t.first_col),
|
||||
"lastCol" => t.last_col = on.unwrap_or(!t.last_col),
|
||||
"header" => t.filter_button = on.unwrap_or(!t.filter_button),
|
||||
"header" => {
|
||||
t.filter_button = on.unwrap_or(!t.filter_button);
|
||||
if !t.filter_button {
|
||||
t.filter.clear();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(Json::Null)
|
||||
@@ -405,14 +465,19 @@ fn table_style(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Table names follow the Microsoft name rules, as the xlsx writer does: letters, digits, `_` and `.`,
|
||||
/// starting with a letter, `_` or `\`. Anything else (a hyphen, say) would read as an operator inside a
|
||||
/// structured reference, and the writer would rename the table on save.
|
||||
fn valid_table_name(name: &str) -> bool {
|
||||
name.starts_with(|c: char| c.is_alphabetic() || c == '_' || c == '\\')
|
||||
&& CellRef::parse(name).is_none()
|
||||
&& name.chars().enumerate().all(|(i, c)| c.is_alphanumeric() || c == '_' || c == '.' || (i == 0 && c == '\\'))
|
||||
}
|
||||
|
||||
fn table_rename(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, ti) = find_table(s, p)?;
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("table.rename", "missing `name`"))?.to_string();
|
||||
if name.is_empty()
|
||||
|| name.contains(' ')
|
||||
|| name.chars().next().is_some_and(|c| c.is_ascii_digit())
|
||||
|| gridcraft_core::CellRef::parse(&name).is_some()
|
||||
{
|
||||
if !valid_table_name(&name) {
|
||||
return Err(EngineError::Other("The name that you entered is not valid.".into()));
|
||||
}
|
||||
if s.doc()?.wb.table(&name).is_some_and(|x| x != (si, ti)) {
|
||||
@@ -427,6 +492,8 @@ fn table_rename(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
for i in 0..cx.wb.sheets.len() {
|
||||
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
|
||||
cx.wb.sheets.get(i).map(|s| s.cells.iter().filter_map(|(c, x)| x.formula.clone().map(|f| (c, f))).collect()).unwrap_or_default();
|
||||
// A bare name that is also a defined name resolves to the defined name, so it is not the table.
|
||||
let shadowed = cx.wb.name(&old, i).is_some();
|
||||
let Some(sh) = cx.wb.sheet_mut(i) else { continue };
|
||||
for (c, f) in keys {
|
||||
let Some(e) = f.expr() else { continue };
|
||||
@@ -435,7 +502,7 @@ fn table_rename(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
st.table = name.clone();
|
||||
gridcraft_formula::Expr::Struct(st)
|
||||
}
|
||||
gridcraft_formula::Expr::Name(n) if n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()),
|
||||
gridcraft_formula::Expr::Name(n) if !shadowed && n.eq_ignore_ascii_case(&old) => gridcraft_formula::Expr::Name(name.clone()),
|
||||
o => o,
|
||||
});
|
||||
if let Some(cell) = sh.cells.get_mut(c) {
|
||||
@@ -518,7 +585,12 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
|
||||
let header_row = r.height() > 1
|
||||
&& (r.start.col..=r.end.col).any(|c| sh.value(CellRef::new(r.start.row, c)).is_text())
|
||||
&& (r.start.col..=r.end.col).filter(|c| *c != r.start.col).all(|c| is_text(CellRef::new(r.start.row, c)));
|
||||
let label_col = r.width() > 1 && (r.start.row + header_row as u32..=r.end.row).all(|row| is_text(CellRef::new(row, r.start.col)));
|
||||
// A blank top-left cell above a header row marks the first column as the category labels even
|
||||
// when it holds numbers (years, X values), the usual spreadsheet convention, so it isn't
|
||||
// plotted as a series of its own (#287).
|
||||
let blank_corner = header_row && sh.value(r.start).is_empty();
|
||||
let label_col =
|
||||
r.width() > 1 && (blank_corner || (r.start.row + header_row as u32..=r.end.row).all(|row| is_text(CellRef::new(row, r.start.col))));
|
||||
let data = RangeRef::new(CellRef::new(r.start.row + header_row as u32, r.start.col + label_col as u32), r.end);
|
||||
let mut out = Vec::new();
|
||||
if !by_rows {
|
||||
@@ -532,6 +604,7 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -546,16 +619,33 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A scatter plot of a block without category labels takes its first column (or row) as the X
|
||||
/// values of the others, as Excel does: two plain columns make one series of points, not two (#428).
|
||||
pub fn scatter_x_from_first(kind: ChartKind, series: &mut Vec<Series>) {
|
||||
if matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines) && series.len() > 1 && series[0].categories.is_none() {
|
||||
let x = series.remove(0).values;
|
||||
for se in series.iter_mut() {
|
||||
se.categories = Some(x.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Most cells a chart's source block may span (bounds the series it builds).
|
||||
const MAX_CHART_CELLS: u64 = 1_000_000;
|
||||
|
||||
fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
/// Chart types that suit the shape of the data, best first, as `(type, subtype, label)` for
|
||||
/// `insert.chart`. Our own heuristic from the shape of the block (series count, points per
|
||||
/// series, text categories, negative values), not a copy of Excel's ranking: two numeric columns
|
||||
/// without labels → scatter; one short series → column, pie, bar; long series → line; several
|
||||
/// series → clustered and stacked columns and bars, line.
|
||||
pub fn recommend_charts(s: &Session, p: &Json) -> Result<Vec<(&'static str, &'static str, &'static str)>> {
|
||||
let r = block(s, p)?;
|
||||
if r.count() > MAX_CHART_CELLS {
|
||||
return Err(bad("insert.chart", "range too large for a chart"));
|
||||
@@ -563,21 +653,85 @@ fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
let by_rows = r.width() > r.height() + 1;
|
||||
let series = series_from_range(sh, r, by_rows);
|
||||
let ranges: Vec<RangeRef> = series
|
||||
.iter()
|
||||
.filter_map(|x| match gridcraft_formula::parse(&x.values) {
|
||||
Ok(gridcraft_formula::Expr::Ref(rf)) => Some(rf.range()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let points = ranges.first().map_or(0, RangeRef::count);
|
||||
let (mut any_number, mut non_negative) = (false, true);
|
||||
for n in ranges.iter().flat_map(|rr| rr.iter()).filter_map(|c| sh.value(c).as_f64()) {
|
||||
any_number = true;
|
||||
non_negative &= n >= 0.0;
|
||||
}
|
||||
if series.is_empty() || !any_number {
|
||||
return Err(EngineError::Other("Select data for the chart first.".into()));
|
||||
}
|
||||
let labelled = series.first().is_some_and(|x| x.categories.is_some());
|
||||
const COLUMN: (&str, &str, &str) = ("column", "", "Clustered Column");
|
||||
const BAR: (&str, &str, &str) = ("bar", "", "Clustered Bar");
|
||||
const LINE: (&str, &str, &str) = ("line", "", "Line");
|
||||
const LINE_MARKERS: (&str, &str, &str) = ("line", "markers", "Line with Markers");
|
||||
const PIE: (&str, &str, &str) = ("pie", "", "Pie");
|
||||
const DOUGHNUT: (&str, &str, &str) = ("doughnut", "", "Doughnut");
|
||||
const AREA: (&str, &str, &str) = ("area", "", "Area");
|
||||
const SCATTER: (&str, &str, &str) = ("scatter", "", "Scatter");
|
||||
const STACKED_COLUMN: (&str, &str, &str) = ("column", "stacked", "Stacked Column");
|
||||
const STACKED_BAR: (&str, &str, &str) = ("bar", "stacked", "Stacked Bar");
|
||||
let mut out = Vec::new();
|
||||
if series.len() == 2 && !labelled && !by_rows {
|
||||
out.extend([SCATTER, LINE_MARKERS, COLUMN]);
|
||||
} else if series.len() == 1 {
|
||||
if points > 12 {
|
||||
out.extend([LINE, COLUMN, AREA]);
|
||||
} else {
|
||||
out.extend([COLUMN, BAR]);
|
||||
if non_negative && points >= 2 {
|
||||
out.extend([PIE, DOUGHNUT]);
|
||||
}
|
||||
out.push(LINE_MARKERS);
|
||||
}
|
||||
} else if points > 12 {
|
||||
out.extend([LINE, COLUMN, AREA, STACKED_COLUMN]);
|
||||
} else {
|
||||
out.extend([COLUMN, BAR, STACKED_COLUMN, LINE_MARKERS, STACKED_BAR]);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The chart `insert.chart` would insert for these params, without inserting it: the sheet it
|
||||
/// goes on and the chart (previews in the Recommended Charts dialog).
|
||||
pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
|
||||
let r = block(s, p)?;
|
||||
if r.count() > MAX_CHART_CELLS {
|
||||
return Err(bad("insert.chart", "range too large for a chart"));
|
||||
}
|
||||
let mut t = str_param(p, "type").unwrap_or("column").to_string();
|
||||
let mut sub = str_param(p, "subtype").unwrap_or("").to_string();
|
||||
if t == "auto" {
|
||||
let first = recommend_charts(s, p)?.into_iter().next().unwrap_or(("column", "", ""));
|
||||
t = first.0.into();
|
||||
sub = first.1.into();
|
||||
}
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
// Excel plots series by the longer dimension (more rows → series in columns).
|
||||
let data_h = r.height();
|
||||
let data_w = r.width();
|
||||
let by_rows = data_w > data_h + 1;
|
||||
if t == "auto" {
|
||||
t = if data_h > 12 && data_w <= 3 { "line".into() } else { "column".into() };
|
||||
}
|
||||
let kind = chart_kind(&t, str_param(p, "subtype").unwrap_or(""));
|
||||
let series = series_from_range(sh, r, by_rows);
|
||||
let kind = chart_kind(&t, &sub);
|
||||
let mut series = series_from_range(sh, r, by_rows);
|
||||
if series.is_empty() {
|
||||
return Err(EngineError::Other("Select data for the chart first.".into()));
|
||||
}
|
||||
scatter_x_from_first(kind, &mut series);
|
||||
let id = d.wb.next_object_id();
|
||||
let at = cell_param(p, "at").unwrap_or_else(|| CellRef::new(r.start.row, r.end.col + 2));
|
||||
let at = cell_param_on(s, p, "at", sheet)?.unwrap_or_else(|| CellRef::new(r.start.row, r.end.col + 2));
|
||||
let title = str_param(p, "title").map(str::to_string).or_else(|| {
|
||||
if series.len() == 1 {
|
||||
series[0].name.as_ref().map(|n| gridcraft_calc::evaluate(&d.wb, sheet, at, n).display())
|
||||
@@ -606,7 +760,14 @@ fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
y_title: None,
|
||||
source: Some(format!("{}!{}", gridcraft_formula::quote_sheet(&sh.name), r.a1())),
|
||||
by_rows,
|
||||
pivot: None,
|
||||
};
|
||||
Ok((sheet, chart))
|
||||
}
|
||||
|
||||
fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (sheet, chart) = build_chart(s, p)?;
|
||||
let id = chart.id;
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.charts.push(chart);
|
||||
Ok(json!({"chart": id}))
|
||||
@@ -626,6 +787,7 @@ fn find_chart(s: &Session, p: &Json) -> Result<(usize, usize)> {
|
||||
|
||||
fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, ci) = find_chart(s, p)?;
|
||||
let at = cell_param_on(s, p, "at", si)?;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
let Some(c) = sh.charts.get_mut(ci) else { return Ok(Json::Null) };
|
||||
@@ -659,7 +821,7 @@ fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let Some(t) = p.get("yTitle") {
|
||||
c.y_title = t.as_str().map(str::to_string);
|
||||
}
|
||||
if let Some(at) = cell_param(p, "at") {
|
||||
if let Some(at) = at {
|
||||
c.anchor.cell = at;
|
||||
}
|
||||
if let Some(w) = f64_param(p, "width") {
|
||||
@@ -704,6 +866,7 @@ fn chart_switch(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
c.source.get_or_insert(src);
|
||||
c.by_rows = by_rows;
|
||||
c.series = series;
|
||||
scatter_x_from_first(c.kind, &mut c.series);
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
@@ -742,7 +905,7 @@ fn chart_delete(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn insert_sparkline(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let src = str_param(p, "range").ok_or_else(|| bad("insert.sparkline", "missing `range`"))?.to_string();
|
||||
let loc = cell_param(p, "location").ok_or_else(|| bad("insert.sparkline", "missing `location`"))?;
|
||||
let loc = cell_param(s, p, "location")?.ok_or_else(|| bad("insert.sparkline", "missing `location`"))?;
|
||||
let kind = match str_param(p, "type") {
|
||||
Some("column") => SparklineKind::Column,
|
||||
Some("winLoss") => SparklineKind::WinLoss,
|
||||
@@ -782,7 +945,7 @@ fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
let at = sh.merge_at(at).map(|r| r.start).unwrap_or(at);
|
||||
let style = sh.style_id(at);
|
||||
if sh.is_protected() && d.wb.styles.get(style).protection.locked {
|
||||
if sh.is_protected() && d.wb.styles.get(style).protection.locked && locked_cell_error(sh, at, &d.unlocked_ranges).is_some() {
|
||||
return Err(EngineError::Other("The cell you're trying to change is on a protected sheet.".into()));
|
||||
}
|
||||
let picture = CellPicture { data, mime: mime.into(), alt: str_param(p, "alt").unwrap_or("").into() };
|
||||
@@ -801,7 +964,7 @@ fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (w, h) = crate::io::image_size(&data).unwrap_or((320, 240));
|
||||
let d = s.doc()?;
|
||||
let id = d.wb.next_object_id();
|
||||
let at = cell_param(p, "at").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active);
|
||||
let scale = (640.0 / w.max(1) as f32).min(1.0);
|
||||
let img = Image {
|
||||
id,
|
||||
@@ -864,7 +1027,7 @@ fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
let d = s.doc()?;
|
||||
let id = d.wb.next_object_id();
|
||||
let at = cell_param(p, "at").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active);
|
||||
let fill =
|
||||
super::format::color_param(p.get("fill")).unwrap_or(if kind == ShapeKind::TextBox { Color::rgb(255, 255, 255) } else { Color::Theme(4, 0) });
|
||||
let line = super::format::color_param(p.get("line")).unwrap_or(if kind == ShapeKind::TextBox {
|
||||
@@ -886,6 +1049,7 @@ fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fill,
|
||||
line,
|
||||
text: str_param(p, "text").unwrap_or("").into(),
|
||||
format: Default::default(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
@@ -934,6 +1098,7 @@ fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
match kind.as_str() {
|
||||
"chart" => sh.charts.retain(|c| c.id != id),
|
||||
"image" => sh.images.retain(|c| c.id != id),
|
||||
"slicer" => sh.slicers.retain(|c| c.id != id),
|
||||
_ => sh.shapes.retain(|c| c.id != id),
|
||||
}
|
||||
Ok(Json::Null)
|
||||
@@ -944,16 +1109,18 @@ fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad("object.move", "missing `id`"))?;
|
||||
let kind = str_param(p, "kind").unwrap_or("").to_string();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
let at = cell_param(s, p, "at")?;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let anchor = match kind.as_str() {
|
||||
"chart" => sh.charts.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
"image" => sh.images.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
"slicer" => sh.slicers.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
"shape" => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
_ => None,
|
||||
};
|
||||
let Some(a) = anchor else { return Err(bad("object.move", "no such object")) };
|
||||
if let Some(at) = cell_param(p, "at") {
|
||||
if let Some(at) = at {
|
||||
a.cell = at;
|
||||
}
|
||||
if let Some(v) = f64_param(p, "dx") {
|
||||
@@ -1000,7 +1167,7 @@ fn set_anchor_mode(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
|
||||
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
|
||||
if bool_param(p, "remove").unwrap_or(false) {
|
||||
return edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.hyperlinks.remove(&at);
|
||||
@@ -1013,6 +1180,7 @@ fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
let text = str_param(p, "text").map(str::to_string);
|
||||
let tooltip = str_param(p, "tooltip").map(str::to_string);
|
||||
let external = links_outside(&s.doc()?.wb, sheet, &target);
|
||||
edit(s, |cx| {
|
||||
let link_style = cx.wb.styles.derive(cx.wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(), |st| {
|
||||
st.font.color = Color::Theme(10, 0);
|
||||
@@ -1024,28 +1192,72 @@ fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
} else {
|
||||
sh.set_style(at, link_style);
|
||||
}
|
||||
sh.hyperlinks.insert(at, Hyperlink { target: target.clone(), tooltip: tooltip.clone() });
|
||||
sh.hyperlinks.insert(at, Hyperlink { target: target.clone(), tooltip: tooltip.clone(), external });
|
||||
cx.touch(sheet, at);
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
/// Follows a link: a reference selects it, an `http`/`https`/`mailto` address is handed to the
|
||||
/// host (`UiRequest::OpenUrl`); anything else is refused ([`crate::links::classify`]). Opens no
|
||||
/// dialog; the interactive click asks for confirmation first, in the UI.
|
||||
fn open_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let target = match str_param(p, "url").or_else(|| str_param(p, "target")) {
|
||||
Some(t) => t.to_string(),
|
||||
None => {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
|
||||
let Some(h) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.hyperlinks.get(&at)) else {
|
||||
return Err(EngineError::Other("There's no hyperlink in this cell.".into()));
|
||||
};
|
||||
h.target.clone()
|
||||
}
|
||||
};
|
||||
match crate::links::classify(&target) {
|
||||
crate::links::LinkKind::Internal(r) => super::edit::go_to(s, &json!({"reference": r.trim_start_matches('#')})),
|
||||
crate::links::LinkKind::External(u) => {
|
||||
s.ui_requests.push(crate::UiRequest::OpenUrl(u.clone()));
|
||||
Ok(json!({"opened": u}))
|
||||
}
|
||||
crate::links::LinkKind::Refused(why) => Err(EngineError::Other(why)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorts a link target as the two pages of Excel's Insert Hyperlink dialog do: "Place in This
|
||||
/// Document" is a sheet reference, a defined name or `#…`; anything else ("Existing File or Web
|
||||
/// Page") is outside the workbook and saved as a relationship.
|
||||
fn links_outside(wb: &Workbook, sheet: usize, target: &str) -> bool {
|
||||
let t = target.trim();
|
||||
if t.starts_with('#') || wb.name(t, sheet).is_some() || wb.table(t).is_some() {
|
||||
return false;
|
||||
}
|
||||
let (on, body) = split_sheet(t);
|
||||
// Sheet names can't hold `: \ / ? * [ ]`, so `https://…!A1` or `C:\…!A1` is no sheet reference,
|
||||
// and `Book.xlsx#Sheet1!A1` is a place in another file unless a sheet has that name.
|
||||
let on_sheet = on.is_none_or(|name| {
|
||||
wb.sheets.iter().any(|s| s.name.eq_ignore_ascii_case(&name))
|
||||
|| (!name.is_empty() && !name.contains([':', '\\', '/', '?', '*', '[', ']', '#']))
|
||||
});
|
||||
!(on_sheet && RangeRef::parse(body).is_some())
|
||||
}
|
||||
|
||||
fn comment(s: &mut Session, p: &Json, threaded: bool) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
|
||||
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
|
||||
let text = str_param(p, "text").unwrap_or("").to_string();
|
||||
let author = str_param(p, "author").map(str::to_string).unwrap_or_else(|| s.prefs.user_name.clone());
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?
|
||||
.comments
|
||||
.insert(at, Comment { author: author.clone(), text: text.clone(), replies: vec![], threaded, resolved: false, visible: false });
|
||||
cx.sheet_mut(sheet)?.comments.insert(
|
||||
at,
|
||||
Comment { author: author.clone(), text: text.clone(), replies: vec![], threaded, resolved: false, visible: false, dates: vec![] },
|
||||
);
|
||||
Ok(json!({"cell": at.a1()}))
|
||||
})
|
||||
}
|
||||
|
||||
fn reply_comment(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
|
||||
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
|
||||
let text = str_param(p, "text").unwrap_or("").to_string();
|
||||
let author = str_param(p, "author").map(str::to_string).unwrap_or_else(|| s.prefs.user_name.clone());
|
||||
edit(s, |cx| {
|
||||
@@ -1057,7 +1269,7 @@ fn reply_comment(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn resolve_comment(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
|
||||
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
|
||||
let v = bool_param(p, "resolved").unwrap_or(true);
|
||||
edit(s, |cx| {
|
||||
if let Some(c) = cx.sheet_mut(sheet)?.comments.get_mut(&at) {
|
||||
@@ -1078,7 +1290,7 @@ fn delete_comment(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn show_note(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
|
||||
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
|
||||
edit(s, |cx| {
|
||||
if let Some(c) = cx.sheet_mut(sheet)?.comments.get_mut(&at) {
|
||||
c.visible = !c.visible;
|
||||
@@ -1157,15 +1369,17 @@ fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
let rule = match kind.as_str() {
|
||||
"cellIs" => {
|
||||
// Excel's file and VBA names (`lessThan`, …) are accepted too.
|
||||
let op = match g("operator").as_deref().unwrap_or("greater") {
|
||||
"between" => CfOperator::Between,
|
||||
"notBetween" => CfOperator::NotBetween,
|
||||
"equal" => CfOperator::Equal,
|
||||
"notEqual" => CfOperator::NotEqual,
|
||||
"less" => CfOperator::Less,
|
||||
"greaterOrEqual" => CfOperator::GreaterOrEqual,
|
||||
"lessOrEqual" => CfOperator::LessOrEqual,
|
||||
_ => CfOperator::Greater,
|
||||
"less" | "lessThan" => CfOperator::Less,
|
||||
"greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual,
|
||||
"lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual,
|
||||
"greater" | "greaterThan" => CfOperator::Greater,
|
||||
other => return Err(bad("home.conditionalFormat", format!("unknown operator `{other}`"))),
|
||||
};
|
||||
let a = rule.get("value").map(super::edit::json_to_input).unwrap_or_default();
|
||||
let b = rule.get("value2").map(super::edit::json_to_input);
|
||||
@@ -1274,20 +1488,20 @@ fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let n = sh.cond_formats.len();
|
||||
// The count is taken again after each step: a delete shortens the list.
|
||||
if let Some(i) = u32_param(p, "delete").map(|v| v as usize)
|
||||
&& i < n
|
||||
&& i < sh.cond_formats.len()
|
||||
{
|
||||
sh.cond_formats.remove(i);
|
||||
}
|
||||
if let Some(i) = u32_param(p, "moveUp").map(|v| v as usize)
|
||||
&& i > 0
|
||||
&& i < n
|
||||
&& i < sh.cond_formats.len()
|
||||
{
|
||||
sh.cond_formats.swap(i, i - 1);
|
||||
}
|
||||
if let Some(i) = u32_param(p, "moveDown").map(|v| v as usize)
|
||||
&& i + 1 < n
|
||||
&& i + 1 < sh.cond_formats.len()
|
||||
{
|
||||
sh.cond_formats.swap(i, i + 1);
|
||||
}
|
||||
@@ -1303,7 +1517,7 @@ fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let size = f64_param(p, "size").unwrap_or(48.0).clamp(8.0, 1000.0) as f32;
|
||||
let d = s.doc()?;
|
||||
let id = d.wb.next_object_id();
|
||||
let at = cell_param(p, "at").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active);
|
||||
let color = super::format::color_param(p.get("color")).unwrap_or(Color::Theme(1, 0));
|
||||
let shape = Shape {
|
||||
id,
|
||||
@@ -1312,6 +1526,7 @@ fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fill: color,
|
||||
line: Color::Auto,
|
||||
text: name,
|
||||
format: Default::default(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
@@ -1319,3 +1534,23 @@ fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Ok(json!({"shape": id}))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn manage_rules_delete_then_move() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
for v in ["1", "2"] {
|
||||
let rule = json!({"type": "cellIs", "operator": "greaterThan", "value": v, "preset": "lightRedFill"});
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": rule})).unwrap();
|
||||
}
|
||||
// Deleting first left two rules' worth of indices for the move: it panicked.
|
||||
s.execute("home.manageRules", json!({"delete": 0, "moveUp": 1})).unwrap();
|
||||
s.execute("home.manageRules", json!({"delete": 0, "moveDown": 0})).unwrap();
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ fn inspect(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
"freeze": sh.freeze,
|
||||
"merges": sh.merges.iter().map(|m| m.a1()).collect::<Vec<_>>(),
|
||||
"tables": sh.tables.iter().map(|t| json!({"name": t.name, "range": t.range.a1(), "style": t.style, "totals": t.totals_row, "columns": t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>()})).collect::<Vec<_>>(),
|
||||
"charts": sh.charts.iter().map(|c| json!({"id": c.id, "kind": format!("{:?}", c.kind), "title": c.title, "at": c.anchor.cell.a1(), "series": c.series.len()})).collect::<Vec<_>>(),
|
||||
"charts": sh.charts.iter().map(|c| json!({"id": c.id, "kind": format!("{:?}", c.kind), "title": c.title, "at": c.anchor.cell.a1(), "series": c.series.len(), "trendlines": c.series.iter().flat_map(|s| s.trendlines.iter().map(|t| format!("{:?}", t.kind))).collect::<Vec<_>>()})).collect::<Vec<_>>(),
|
||||
"images": sh.images.len(),
|
||||
"shapes": sh.shapes.len(),
|
||||
"conditionalFormats": sh.cond_formats.len(),
|
||||
@@ -119,7 +119,7 @@ fn cell_get(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
let c = cell_param(p, "cell").unwrap_or(d.selection.active);
|
||||
let c = cell_param_on(s, p, "cell", sheet)?.unwrap_or(d.selection.active);
|
||||
let cell = sh.cell(c);
|
||||
let style = d.wb.styles.get(sh.style_id(c));
|
||||
Ok(json!({
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
//! The command registry. Ids follow Excel's ribbon (`home.bold`, `insert.chart`,
|
||||
//! `data.sortAscending`) plus primitive editing commands (`cell.set`, `selection.set`).
|
||||
|
||||
pub mod analysis;
|
||||
pub mod data;
|
||||
pub mod draw;
|
||||
pub mod edit;
|
||||
pub mod extra;
|
||||
pub mod file;
|
||||
pub mod forecast;
|
||||
pub mod format;
|
||||
pub mod formulas;
|
||||
pub mod insert;
|
||||
@@ -14,6 +16,8 @@ pub mod pivot;
|
||||
pub mod print;
|
||||
pub mod review;
|
||||
pub mod sheet;
|
||||
pub mod slicer;
|
||||
pub mod solver;
|
||||
pub mod spelling;
|
||||
pub mod view;
|
||||
pub mod whatif;
|
||||
@@ -69,6 +73,21 @@ impl CommandSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// Params that hold a secret: `password`, or a name ending in `Password`.
|
||||
pub fn is_secret_param(key: &str) -> bool {
|
||||
key == "password" || key.ends_with("Password")
|
||||
}
|
||||
|
||||
/// The params as the journal records them: secret params are left out, so a password never
|
||||
/// reaches the journal dialog, `engine.journal` or a recorded script (saved in the workbook).
|
||||
/// Replaying such an entry runs the command without that param.
|
||||
pub fn journal_params(params: &Json) -> Json {
|
||||
match params {
|
||||
Json::Object(o) => Json::Object(o.iter().filter(|(k, _)| !is_secret_param(k)).map(|(k, v)| (k.clone(), v.clone())).collect()),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn always(_: &Session) -> std::result::Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -118,15 +137,54 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(extra::specs());
|
||||
v.extend(draw::specs());
|
||||
v.extend(spelling::specs());
|
||||
v.extend(solver::specs());
|
||||
v.extend(pivot::specs());
|
||||
v.extend(slicer::specs());
|
||||
v.extend(whatif::specs());
|
||||
v.extend(forecast::specs());
|
||||
v.extend(analysis::specs());
|
||||
v.extend(print::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id)
|
||||
if let Some(spec) = command_specs().iter().find(|c| c.id == id) {
|
||||
return Some(spec);
|
||||
}
|
||||
// Commands registered by UI integration tests (pending keytips go live
|
||||
// the moment their command lands, with no table edit).
|
||||
test_commands().iter().find(|c| c.id == id).copied()
|
||||
}
|
||||
|
||||
static TEST_COMMANDS: std::sync::Mutex<Vec<&'static CommandSpec>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// Test-only: register an extra command so UI integration tests can prove a pending
|
||||
/// keytip becomes live the moment its command lands (see crates/ui-egui/tests/keytips.rs).
|
||||
/// Not part of the public API; harmless no-op for production callers who never call it.
|
||||
#[doc(hidden)]
|
||||
pub fn register_test_command(id: &'static str, run: Run) {
|
||||
// Leaked intentionally: test commands live for the whole process.
|
||||
let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec {
|
||||
id,
|
||||
label: id,
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: "",
|
||||
enabled: |_| Ok(()),
|
||||
run,
|
||||
journal: true,
|
||||
undoable: false,
|
||||
}));
|
||||
test_commands().push(spec);
|
||||
}
|
||||
|
||||
fn test_commands() -> std::sync::MutexGuard<'static, Vec<&'static CommandSpec>> {
|
||||
#[allow(clippy::unwrap_used)] // a poisoned test registry has no meaningful recovery
|
||||
match TEST_COMMANDS.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- param helpers
|
||||
@@ -219,8 +277,28 @@ pub(crate) fn split_sheet(r: &str) -> (Option<String>, &str) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cell_param(p: &Json, key: &str) -> Option<CellRef> {
|
||||
str_param(p, key).and_then(|t| CellRef::parse(split_sheet(t).1))
|
||||
/// A single-cell parameter. Absent or null is `Ok(None)` (callers default it); a value that is not
|
||||
/// a cell reference, or that names a sheet other than the active one, is an error rather than a
|
||||
/// silent fallback to some other cell.
|
||||
pub(crate) fn cell_param(s: &Session, p: &Json, key: &str) -> Result<Option<CellRef>> {
|
||||
cell_param_on(s, p, key, s.doc()?.wb.active_sheet)
|
||||
}
|
||||
|
||||
/// Like [`cell_param`], for a command that operates on `sheet` (a `Sheet!` prefix must name it).
|
||||
pub(crate) fn cell_param_on(s: &Session, p: &Json, key: &str, sheet: usize) -> Result<Option<CellRef>> {
|
||||
let t = match p.get(key) {
|
||||
None | Some(Json::Null) => return Ok(None),
|
||||
Some(Json::String(t)) => t,
|
||||
Some(v) => return Err(bad("cell", format!("invalid cell reference `{v}` for `{key}`"))),
|
||||
};
|
||||
let (sh, body) = split_sheet(t);
|
||||
let c = CellRef::parse(body).ok_or_else(|| bad("cell", format!("invalid cell reference `{t}` for `{key}`")))?;
|
||||
if let Some(name) = sh
|
||||
&& s.doc()?.wb.sheet_index(&name) != Some(sheet)
|
||||
{
|
||||
return Err(bad("cell", format!("`{t}` for `{key}` names a sheet other than the one this command works on")));
|
||||
}
|
||||
Ok(Some(c))
|
||||
}
|
||||
|
||||
/// Applies an edit to a copy of the active workbook, then recalculates and commits it.
|
||||
@@ -257,7 +335,10 @@ pub(crate) fn commit<R>(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result<R>)
|
||||
let r = f(&mut ctx)?;
|
||||
let Ctx { mut wb, changed, structural, mut fit_rows, protection_checked, .. } = ctx;
|
||||
if !protection_checked {
|
||||
check_protection(&d.wb, &wb)?;
|
||||
check_protection(&d.wb, &wb, &d.unlocked_ranges)?;
|
||||
}
|
||||
if !structural {
|
||||
check_arrays(&d.wb, &wb)?;
|
||||
}
|
||||
if changed.len() <= 200_000 {
|
||||
fit_rows.extend(changed.iter().map(|(s, c)| (*s, c.row)));
|
||||
@@ -292,7 +373,7 @@ pub(crate) const PROTECTED: &str = "The cell or chart you're trying to change is
|
||||
/// Refuses an edit that changed what a locked cell on a protected sheet holds (its value or
|
||||
/// formula), whichever command made it. Sheets are matched by name, so moving, renaming or
|
||||
/// deleting a sheet isn't an edit of its cells.
|
||||
fn check_protection(old: &Workbook, new: &Workbook) -> Result<()> {
|
||||
fn check_protection(old: &Workbook, new: &Workbook, unlocked: &[(String, String)]) -> Result<()> {
|
||||
for sh in &old.sheets {
|
||||
if !sh.is_protected() {
|
||||
continue;
|
||||
@@ -302,8 +383,57 @@ fn check_protection(old: &Workbook, new: &Workbook) -> Result<()> {
|
||||
continue;
|
||||
}
|
||||
for c in sh.cells.diff(&after.cells) {
|
||||
if !same_content(sh.cell(c), after.cell(c)) && old.styles.get(sh.style_id(c)).protection.locked {
|
||||
return Err(EngineError::Other(PROTECTED.into()));
|
||||
if !same_content(sh.cell(c), after.cell(c))
|
||||
&& old.styles.get(sh.style_id(c)).protection.locked
|
||||
&& let Some(m) = locked_cell_error(sh, c, unlocked)
|
||||
{
|
||||
return Err(EngineError::Other(m));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a locked cell on a protected sheet stays locked: `None` when it's in an Allow Edit
|
||||
/// Range without a password or one unlocked in this session, else the message to show.
|
||||
pub(crate) fn locked_cell_error(sh: &gridcraft_model::Sheet, c: CellRef, unlocked: &[(String, String)]) -> Option<String> {
|
||||
let mut needs_password = None;
|
||||
for r in sh.edit_ranges.iter().filter(|r| r.contains(c)) {
|
||||
if r.password.is_none() || unlocked.iter().any(|(s, t)| *s == sh.name && *t == r.title) {
|
||||
return None;
|
||||
}
|
||||
needs_password.get_or_insert(r.title.as_str());
|
||||
}
|
||||
Some(match needs_password {
|
||||
Some(t) => format!("The range \"{t}\" needs its password before it can be changed (Review › Allow Edit Ranges)."),
|
||||
None => PROTECTED.into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Refuses an edit that put something into a cell of a multi-cell legacy array other than its
|
||||
/// formula cell, while the array stays (Excel: "You can't change part of an array."). The array
|
||||
/// would show its value there while the file kept the new content. Cells shifted by row and
|
||||
/// column edits aren't edits of their content, so structural commits aren't checked.
|
||||
fn check_arrays(old: &Workbook, new: &Workbook) -> Result<()> {
|
||||
for sh in &old.sheets {
|
||||
if sh.spill.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(after) = new.sheet_index(&sh.name).and_then(|i| new.sheets.get(i)) else { continue };
|
||||
if std::sync::Arc::ptr_eq(sh, after) {
|
||||
continue;
|
||||
}
|
||||
for c in sh.cells.diff(&after.cells) {
|
||||
let filled = after.cell(c).is_some_and(|x| x.formula.is_some() || !x.value.is_empty());
|
||||
if !filled || !sh.spill.contains_key(&c) || same_content(sh.cell(c), after.cell(c)) {
|
||||
continue;
|
||||
}
|
||||
let in_array = sh.spill_ranges.keys().any(|&anchor| {
|
||||
anchor != c
|
||||
&& after.cell(anchor).and_then(|x| x.formula.as_ref()).and_then(|f| f.array).is_some_and(|a| a.start == anchor && a.contains(c))
|
||||
});
|
||||
if in_array {
|
||||
return Err(EngineError::Other("You can't change part of an array.".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+619
-26
@@ -43,6 +43,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
summarize_table
|
||||
),
|
||||
cmd!(
|
||||
"pivot.calculatedField",
|
||||
"Calculated Field",
|
||||
["PivotTable Analyze", "Calculations"],
|
||||
None,
|
||||
"{pivot?, name, formula?: \"=Sales*0.1\" (fields bare or 'quoted'; evaluated on each cell's sums), delete?: bool, values?: bool (add a new field to Values, default true)} adds, changes or deletes a calculated field; without `name` opens the dialog → {name, formula, calculatedFields}",
|
||||
has_doc,
|
||||
calculated_field
|
||||
),
|
||||
cmd!(
|
||||
"insert.pivotChart",
|
||||
"PivotChart",
|
||||
["Insert", "Charts"],
|
||||
None,
|
||||
"{pivot?: name | id | a cell of the report (\"Sheet2!B5\"; default: the PivotTable at the active cell), type?: column|bar|line|pie|area|… (default column), subtype?, title?, at?: \"H2\", width?, height?} adds a chart bound to the PivotTable's report: categories are the innermost row items, series the column items × value fields; it follows refreshes and layout changes → {chart, pivot, series}",
|
||||
has_doc,
|
||||
insert_pivot_chart
|
||||
),
|
||||
cmd!(query "pivot.fields", "PivotTable Fields", [], None, "{pivot?} → source fields (name, numeric, date, samples, areas) and the current layout", has_doc, fields),
|
||||
cmd!(query "pivot.fieldList", "Field List", ["PivotTable Analyze", "Show"], None, "{pivot?} (same as pivot.fields)", has_doc, fields),
|
||||
cmd!(query "pivot.list", "PivotTables", [], None, "{} → every PivotTable in the workbook", has_doc, list),
|
||||
@@ -69,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Field",
|
||||
[],
|
||||
None,
|
||||
"{pivot?, field, from: rows|columns|values|filters, to: rows|columns|values|filters, position?: index, replace?}",
|
||||
"{pivot?, field (\"Σ Values\" moves the value fields between rows and columns; in columns it stays after the last field), from: rows|columns|values|filters, to: rows|columns|values|filters, position?: index, replace?}",
|
||||
has_doc,
|
||||
move_field
|
||||
),
|
||||
@@ -315,11 +333,89 @@ fn in_axes(pt: &PivotTable, field: &str) -> bool {
|
||||
pt.rows.iter().chain(pt.columns.iter()).any(|f| f.source_col.eq_ignore_ascii_case(field))
|
||||
}
|
||||
|
||||
/// Name of the Σ Values pseudo-field (where the value fields sit when there are two or more).
|
||||
const VALUES_FIELD: &str = "Σ Values";
|
||||
|
||||
/// Whether `field` names Σ Values: `Σ Values`, or `Values` unless a source field has that name.
|
||||
fn is_values_field(src: &pv::Source, field: &str) -> bool {
|
||||
let f = field.trim();
|
||||
f == VALUES_FIELD || (f.eq_ignore_ascii_case("values") && src.col(f).is_none())
|
||||
}
|
||||
|
||||
/// Keeps Σ Values in place after a field left (`inserted` false) or arrived at index `i` of
|
||||
/// Rows (`rows`) or Columns.
|
||||
fn shift_values(pt: &mut PivotTable, rows: bool, i: usize, inserted: bool) {
|
||||
if pt.values_on_rows != rows {
|
||||
return;
|
||||
}
|
||||
let Some(p) = pt.values_position else { return };
|
||||
// Σ Values stays just ahead of the field it preceded.
|
||||
let p = match inserted {
|
||||
true if i <= p => p + 1,
|
||||
false if i < p => p - 1,
|
||||
_ => p,
|
||||
};
|
||||
let n = if rows { pt.rows.len() } else { pt.columns.len() };
|
||||
pt.values_position = (p < n).then_some(p);
|
||||
}
|
||||
|
||||
/// Takes `field` out of Rows and Columns (Σ Values keeps its place); returns its first entry.
|
||||
fn take_from_axes(pt: &mut PivotTable, field: &str) -> Option<PivotField> {
|
||||
let mut first = None;
|
||||
for rows in [true, false] {
|
||||
loop {
|
||||
let list = if rows { &mut pt.rows } else { &mut pt.columns };
|
||||
let Some(i) = list.iter().position(|f| f.source_col.eq_ignore_ascii_case(field)) else { break };
|
||||
let f = list.remove(i);
|
||||
shift_values(pt, rows, i, false);
|
||||
first.get_or_insert(f);
|
||||
}
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
/// Inserts `f` into Rows (`rows`) or Columns at `position` (default: the end).
|
||||
fn insert_axis_field(pt: &mut PivotTable, rows: bool, f: PivotField, position: Option<usize>) {
|
||||
let list = if rows { &mut pt.rows } else { &mut pt.columns };
|
||||
let at = position.unwrap_or(list.len()).min(list.len());
|
||||
list.insert(at, f);
|
||||
shift_values(pt, rows, at, true);
|
||||
}
|
||||
|
||||
/// Moves Σ Values between Rows and Columns, or within Rows, to `position` (default: the end).
|
||||
/// In Columns it always comes after the last column field: the column layout doesn't place it
|
||||
/// anywhere else yet.
|
||||
fn move_values_field(cmd: &str, pt: &mut PivotTable, from: &str, to: &str, position: Option<usize>) -> Result<Json> {
|
||||
let current = if pt.values_on_rows { "rows" } else { "columns" };
|
||||
if from != current {
|
||||
return Err(bad(cmd, format!("`{VALUES_FIELD}` isn't in the {from} area")));
|
||||
}
|
||||
if !matches!(to, "rows" | "columns") {
|
||||
return Err(other("The field you are moving cannot be placed in that PivotTable area."));
|
||||
}
|
||||
pt.values_on_rows = to == "rows";
|
||||
pt.values_position = position.filter(|p| pt.values_on_rows && *p < pt.rows.len());
|
||||
Ok(json!({"field": VALUES_FIELD, "to": to}))
|
||||
}
|
||||
|
||||
/// The canonical source field name for `field`.
|
||||
fn canonical(cmd: &str, src: &pv::Source, field: &str) -> Result<String> {
|
||||
src.col(field).and_then(|c| src.headers.get(c).cloned()).ok_or_else(|| bad(cmd, format!("no field `{field}` in the source data")))
|
||||
}
|
||||
|
||||
/// The calculated field named `field`, if any.
|
||||
fn calc_field<'a>(pt: &'a PivotTable, field: &str) -> Option<&'a PivotCalcField> {
|
||||
pt.calculated_fields.iter().find(|c| c.name.eq_ignore_ascii_case(field.trim()))
|
||||
}
|
||||
|
||||
/// The canonical name of a source or calculated field.
|
||||
fn canonical_any(cmd: &str, pt: &PivotTable, src: &pv::Source, field: &str) -> Result<String> {
|
||||
match calc_field(pt, field) {
|
||||
Some(c) if src.col(field).is_none() => Ok(c.name.clone()),
|
||||
_ => canonical(cmd, src, field),
|
||||
}
|
||||
}
|
||||
|
||||
fn unique_value_name(pt: &PivotTable, base: &str, except: Option<usize>) -> String {
|
||||
let taken = |n: &str| pt.values.iter().enumerate().any(|(i, v)| Some(i) != except && v.name.eq_ignore_ascii_case(n));
|
||||
if !taken(base) {
|
||||
@@ -343,33 +439,27 @@ fn add_to_area(
|
||||
name: Option<&str>,
|
||||
position: Option<usize>,
|
||||
) -> Result<()> {
|
||||
let field = canonical(cmd, src, field)?;
|
||||
let is_calc = src.col(field).is_none() && calc_field(pt, field).is_some();
|
||||
if is_calc && area != "values" {
|
||||
return Err(other("A calculated field can only be placed in the Values area."));
|
||||
}
|
||||
let field = canonical_any(cmd, pt, src, field)?;
|
||||
match area {
|
||||
"rows" | "columns" => {
|
||||
if pt.rows.len() + pt.columns.len() >= pv::MAX_AXIS_FIELDS && !in_axes(pt, &field) {
|
||||
return Err(other(format!("A PivotTable can have at most {} row and column fields.", pv::MAX_AXIS_FIELDS)));
|
||||
}
|
||||
let existing = pt
|
||||
.rows
|
||||
.iter()
|
||||
.chain(pt.columns.iter())
|
||||
.find(|f| f.source_col.eq_ignore_ascii_case(&field))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| PivotField { source_col: field.clone(), ..Default::default() });
|
||||
pt.rows.retain(|f| !f.source_col.eq_ignore_ascii_case(&field));
|
||||
pt.columns.retain(|f| !f.source_col.eq_ignore_ascii_case(&field));
|
||||
let existing = take_from_axes(pt, &field).unwrap_or_else(|| PivotField { source_col: field.clone(), ..Default::default() });
|
||||
// A report filter that selects nothing in particular goes away; a selection stays
|
||||
// as the field's hidden items.
|
||||
pt.filters.retain(|f| !(f.source_col.eq_ignore_ascii_case(&field) && f.selected.is_none()));
|
||||
let list = if area == "rows" { &mut pt.rows } else { &mut pt.columns };
|
||||
let at = position.unwrap_or(list.len()).min(list.len());
|
||||
list.insert(at, existing);
|
||||
insert_axis_field(pt, area == "rows", existing, position);
|
||||
}
|
||||
"values" => {
|
||||
if pt.values.len() >= pv::MAX_VALUE_FIELDS {
|
||||
return Err(other(format!("A PivotTable can have at most {} value fields.", pv::MAX_VALUE_FIELDS)));
|
||||
}
|
||||
let numeric = src.col(&field).and_then(|c| src.numeric.get(c).copied()).unwrap_or(false);
|
||||
let numeric = is_calc || src.col(&field).and_then(|c| src.numeric.get(c).copied()).unwrap_or(false);
|
||||
let f = func.unwrap_or(if numeric { PivotFunc::Sum } else { PivotFunc::Count });
|
||||
let base = match name {
|
||||
Some(n) if !n.trim().is_empty() => {
|
||||
@@ -386,8 +476,7 @@ fn add_to_area(
|
||||
pt.values.insert(at, v);
|
||||
}
|
||||
_ => {
|
||||
pt.rows.retain(|f| !f.source_col.eq_ignore_ascii_case(&field));
|
||||
pt.columns.retain(|f| !f.source_col.eq_ignore_ascii_case(&field));
|
||||
take_from_axes(pt, &field);
|
||||
let existing = pt.filters.iter().position(|f| f.source_col.eq_ignore_ascii_case(&field));
|
||||
let entry = match existing {
|
||||
Some(i) => pt.filters.remove(i),
|
||||
@@ -404,12 +493,14 @@ fn add_to_area(
|
||||
fn remove_from_area(cmd: &str, pt: &mut PivotTable, field: &str, area: &str) -> Result<String> {
|
||||
match area {
|
||||
"rows" | "columns" => {
|
||||
let list = if area == "rows" { &mut pt.rows } else { &mut pt.columns };
|
||||
let rows = area == "rows";
|
||||
let list = if rows { &mut pt.rows } else { &mut pt.columns };
|
||||
let i = list
|
||||
.iter()
|
||||
.position(|f| f.source_col.eq_ignore_ascii_case(field))
|
||||
.ok_or_else(|| bad(cmd, format!("`{field}` isn't in the {area} area")))?;
|
||||
let f = list.remove(i);
|
||||
shift_values(pt, rows, i, false);
|
||||
pt.filters.retain(|x| !x.source_col.eq_ignore_ascii_case(&f.source_col));
|
||||
Ok(f.source_col)
|
||||
}
|
||||
@@ -663,6 +754,9 @@ fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
|
||||
"subtotals": if !pt.subtotals { "none" } else if pt.subtotals_top { "top" } else { "bottom" },
|
||||
"style": pt.style,
|
||||
"showHeaders": pt.show_headers,
|
||||
"calculatedFields": pt.calculated_fields.iter().map(|c| json!({"name": c.name, "formula": c.formula})).collect::<Vec<_>>(),
|
||||
"valuesOnRows": pt.values_on_rows,
|
||||
"valuesPosition": pt.values_position,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -702,6 +796,11 @@ fn fields(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
.collect(),
|
||||
Err(_) => vec![],
|
||||
};
|
||||
let mut list = list;
|
||||
for c in &pt.calculated_fields {
|
||||
let areas: Vec<&str> = if pt.values.iter().any(|v| v.source_col.eq_ignore_ascii_case(&c.name)) { vec!["values"] } else { vec![] };
|
||||
list.push(json!({"name": c.name, "numeric": true, "date": false, "samples": [], "areas": areas, "calculated": true, "formula": c.formula}));
|
||||
}
|
||||
if let Some(m) = out.as_object_mut() {
|
||||
m.insert("fields".into(), Json::Array(list));
|
||||
if let Ok(src) = &src {
|
||||
@@ -743,7 +842,76 @@ fn add_field(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let pos = position_param(p);
|
||||
update(s, p, |pt, src, _| {
|
||||
add_to_area(C, pt, src, &field, area, func, name.as_deref(), pos)?;
|
||||
Ok(json!({"field": canonical(C, src, &field)?, "area": area}))
|
||||
Ok(json!({"field": canonical_any(C, pt, src, &field)?, "area": area}))
|
||||
})
|
||||
}
|
||||
|
||||
fn calculated_field(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
const C: &str = "pivot.calculatedField";
|
||||
let Some(name) = str_param(p, "name").map(|n| n.trim().to_string()) else {
|
||||
// Menu-style call: the Insert Calculated Field dialog.
|
||||
let (si, pi) = find_pivot(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let pt = d.wb.sheet(si).and_then(|sh| sh.pivots.get(pi)).ok_or_else(|| other("There's no such PivotTable."))?;
|
||||
let n = (1..).map(|k| format!("Field{k}")).find(|n| calc_field(pt, n).is_none()).unwrap_or_else(|| "Field1".into());
|
||||
let pivot = pt.name.clone();
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("pivotCalculatedField".into(), json!({"pivot": pivot, "name": n, "formula": "= 0"})));
|
||||
return ok();
|
||||
};
|
||||
if name.is_empty() || name.chars().count() > 255 {
|
||||
return Err(bad(C, "`name` must be 1 to 255 characters"));
|
||||
}
|
||||
let delete = bool_param(p, "delete").unwrap_or(false);
|
||||
let formula = str_param(p, "formula").map(|f| {
|
||||
let f = f.trim();
|
||||
if f.starts_with('=') { f.to_string() } else { format!("={f}") }
|
||||
});
|
||||
let to_values = bool_param(p, "values").unwrap_or(true);
|
||||
if !delete && formula.is_none() {
|
||||
return Err(bad(C, "missing `formula`"));
|
||||
}
|
||||
update(s, p, |pt, src, _| {
|
||||
let existing = pt.calculated_fields.iter().position(|c| c.name.eq_ignore_ascii_case(&name));
|
||||
if delete {
|
||||
let i = existing.ok_or_else(|| bad(C, format!("no calculated field `{name}`")))?;
|
||||
let gone = pt.calculated_fields.remove(i);
|
||||
pt.values.retain(|v| !v.source_col.eq_ignore_ascii_case(&gone.name));
|
||||
return Ok(json!({"name": gone.name, "deleted": true}));
|
||||
}
|
||||
let formula = formula.clone().unwrap_or_default();
|
||||
if src.col(&name).is_some() {
|
||||
return Err(other("PivotTable field name already exists."));
|
||||
}
|
||||
let canon = match existing {
|
||||
Some(i) => {
|
||||
let c = pt.calculated_fields.get_mut(i).ok_or_else(|| other("There's no such calculated field."))?;
|
||||
c.formula = formula.clone();
|
||||
c.name.clone()
|
||||
}
|
||||
None => {
|
||||
if pt.calculated_fields.len() >= crate::pivot_calc::MAX_CALC_FIELDS {
|
||||
return Err(other(format!("A PivotTable can have at most {} calculated fields.", crate::pivot_calc::MAX_CALC_FIELDS)));
|
||||
}
|
||||
pt.calculated_fields.push(PivotCalcField { name: name.clone(), formula: formula.clone() });
|
||||
name.clone()
|
||||
}
|
||||
};
|
||||
let set = crate::pivot_calc::CalcSet::new(pt, &src.headers);
|
||||
let i = set.index(&canon).ok_or_else(|| other("There's no such calculated field."))?;
|
||||
if let Some(e) = set.error(i) {
|
||||
return Err(bad(C, e.to_string()));
|
||||
}
|
||||
if set.is_cyclic(i) {
|
||||
return Err(bad(C, format!("`{canon}` refers to itself through its formula")));
|
||||
}
|
||||
if existing.is_none() && to_values && !pt.values.iter().any(|v| v.source_col.eq_ignore_ascii_case(&canon)) {
|
||||
add_to_area(C, pt, src, &canon, "values", Some(PivotFunc::Sum), None, None)?;
|
||||
}
|
||||
Ok(json!({
|
||||
"name": canon,
|
||||
"formula": formula,
|
||||
"calculatedFields": pt.calculated_fields.iter().map(|c| json!({"name": c.name, "formula": c.formula})).collect::<Vec<_>>(),
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -780,18 +948,22 @@ fn move_field(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let to = area_param(C, str_param(p, "to"))?;
|
||||
let pos = position_param(p);
|
||||
update(s, p, |pt, src, _| {
|
||||
if is_values_field(src, &field) {
|
||||
return move_values_field(C, pt, from, to, pos);
|
||||
}
|
||||
if from == to {
|
||||
// Reorder within the area.
|
||||
match from {
|
||||
"rows" | "columns" => {
|
||||
let list = if from == "rows" { &mut pt.rows } else { &mut pt.columns };
|
||||
let rows = from == "rows";
|
||||
let list = if rows { &mut pt.rows } else { &mut pt.columns };
|
||||
let i = list
|
||||
.iter()
|
||||
.position(|f| f.source_col.eq_ignore_ascii_case(&field))
|
||||
.ok_or_else(|| bad(C, format!("`{field}` isn't in the {from} area")))?;
|
||||
let f = list.remove(i);
|
||||
let at = pos.unwrap_or(list.len()).min(list.len());
|
||||
list.insert(at, f);
|
||||
shift_values(pt, rows, i, false);
|
||||
insert_axis_field(pt, rows, f, pos);
|
||||
}
|
||||
"values" => {
|
||||
let i = pt
|
||||
@@ -1160,8 +1332,20 @@ fn change_source(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
ok
|
||||
};
|
||||
pt.rows.retain(|f| keep(&f.source_col, &mut dropped));
|
||||
pt.columns.retain(|f| keep(&f.source_col, &mut dropped));
|
||||
// Axis fields leave one by one so Σ Values keeps its place among the rest.
|
||||
for rows in [true, false] {
|
||||
let mut i = 0;
|
||||
loop {
|
||||
let list = if rows { &mut pt.rows } else { &mut pt.columns };
|
||||
let Some(f) = list.get(i) else { break };
|
||||
if keep(&f.source_col, &mut dropped) {
|
||||
i += 1;
|
||||
} else {
|
||||
list.remove(i);
|
||||
shift_values(pt, rows, i, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
pt.values.retain(|f| keep(&f.source_col, &mut dropped));
|
||||
pt.filters.retain(|f| keep(&f.source_col, &mut dropped));
|
||||
Ok(json!({"source": source, "dropped": dropped}))
|
||||
@@ -1171,6 +1355,18 @@ fn change_source(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn delete(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, pi) = find_pivot(s, p)?;
|
||||
edit(s, |cx| {
|
||||
// Its PivotCharts become ordinary charts.
|
||||
let link = cx.wb.sheet(si).and_then(|sh| sh.pivots.get(pi).map(|pt| (sh.name.clone(), pt.name.clone())));
|
||||
if let Some((sheet, name)) = link {
|
||||
for i in 0..cx.wb.sheets.len() {
|
||||
let linked = |c: &Chart| c.pivot.as_deref().is_some_and(|l| pv::links_to(l, &sheet, &name));
|
||||
if cx.wb.sheet(i).is_some_and(|sh| sh.charts.iter().any(linked)) {
|
||||
for c in cx.sheet_mut(i)?.charts.iter_mut().filter(|c| linked(c)) {
|
||||
c.pivot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pv::clear_output(&mut cx.wb, si, pi);
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
if pi < sh.pivots.len() {
|
||||
@@ -1181,6 +1377,81 @@ fn delete(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- PivotChart
|
||||
|
||||
/// The PivotTable a PivotChart call targets: `pivot` may also be a cell of its report.
|
||||
fn chart_pivot(s: &Session, p: &Json) -> Result<(usize, usize)> {
|
||||
if let Some(t) = str_param(p, "pivot") {
|
||||
let d = s.doc()?;
|
||||
let (sheet, addr) = match t.rsplit_once('!') {
|
||||
Some((sh, a)) => {
|
||||
let sh = sh.trim();
|
||||
let sh = sh.strip_prefix('\'').and_then(|x| x.strip_suffix('\'')).map(|x| x.replace("''", "'")).unwrap_or_else(|| sh.to_string());
|
||||
(d.wb.sheet_index(&sh), a)
|
||||
}
|
||||
None => (Some(d.wb.active_sheet), t),
|
||||
};
|
||||
if let (Some(si), Some(c)) = (sheet, CellRef::parse(addr.trim().replace('$', "").as_str())) {
|
||||
let hit = d.wb.sheet(si).and_then(|sh| sh.pivots.iter().position(|pt| pt.last_range.is_some_and(|r| r.contains(c)) || pt.anchor == c));
|
||||
return hit.map(|pi| (si, pi)).ok_or_else(|| bad("insert.pivotChart", format!("{t} is not in a PivotTable")));
|
||||
}
|
||||
}
|
||||
find_pivot(s, p)
|
||||
}
|
||||
|
||||
fn insert_pivot_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, pi) = chart_pivot(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
let pt = sh.pivots.get(pi).ok_or_else(|| other("There's no such PivotTable."))?;
|
||||
let area = pt.last_range.ok_or_else(|| other("Refresh the PivotTable before adding a PivotChart."))?;
|
||||
let out = pv::compute(&d.wb, pt, si).map_err(other)?;
|
||||
if out.chart_rows.is_empty() || out.chart_cols.is_empty() {
|
||||
return Err(other("Add a field to the Values area and one to Rows or Columns before creating a PivotChart."));
|
||||
}
|
||||
let series = pv::chart_series(&sh.name, area.start, &out);
|
||||
let t = str_param(p, "type").unwrap_or("column");
|
||||
let kind = super::insert::chart_kind(t, str_param(p, "subtype").unwrap_or(""));
|
||||
let at =
|
||||
cell_param(s, p, "at")?.unwrap_or_else(|| CellRef::new(area.start.row, area.end.col.saturating_add(2).min(gridcraft_core::MAX_COLS - 1)));
|
||||
let title = match p.get("title") {
|
||||
Some(Json::String(t)) => Some(t.clone()),
|
||||
Some(Json::Null) => None,
|
||||
_ => Some(if series.len() == 1 { "Total".to_string() } else { "Chart Title".to_string() }),
|
||||
};
|
||||
let id = d.wb.next_object_id();
|
||||
let link = pv::chart_link(&sh.name, &pt.name);
|
||||
let pivot_name = pt.name.clone();
|
||||
let n = series.len();
|
||||
let chart = Chart {
|
||||
id,
|
||||
kind,
|
||||
anchor: Anchor {
|
||||
cell: at,
|
||||
dx: 0.0,
|
||||
dy: 0.0,
|
||||
width: f64_param(p, "width").unwrap_or(480.0).clamp(10.0, 10_000.0) as f32,
|
||||
height: f64_param(p, "height").unwrap_or(288.0).clamp(10.0, 10_000.0) as f32,
|
||||
mode: anchor_mode_param(p).unwrap_or_default(),
|
||||
},
|
||||
title,
|
||||
series,
|
||||
legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom },
|
||||
data_labels: false,
|
||||
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
|
||||
style: 1,
|
||||
x_title: None,
|
||||
y_title: None,
|
||||
source: None,
|
||||
by_rows: false,
|
||||
pivot: Some(link),
|
||||
};
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(si)?.charts.push(chart);
|
||||
Ok(json!({"chart": id, "pivot": pivot_name, "series": n}))
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- recommended
|
||||
|
||||
fn suggestions(wb: &Workbook, src: &pv::Source) -> Vec<Json> {
|
||||
@@ -1280,8 +1551,8 @@ fn recommended(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use serde_json::json;
|
||||
use gridcraft_core::{CellError, CellRef, Value};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -1525,6 +1796,167 @@ mod tests {
|
||||
assert_eq!(text(&s, "A5"), "Apples");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_on_rows_layouts() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales", "Units"]})).unwrap();
|
||||
assert_eq!(text(&s, "C3"), "Sum of Units");
|
||||
// Σ Values after Region: each region holds one line per value field.
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "rows"})).unwrap();
|
||||
let p = pt(&s);
|
||||
assert!(p.values_on_rows);
|
||||
assert_eq!(p.values_position, None);
|
||||
let r = p.last_range.unwrap();
|
||||
assert_eq!(r.width(), 2);
|
||||
// header + 3 × (region + 2 values) + 2 grand totals
|
||||
assert_eq!(r.height(), 1 + 9 + 2);
|
||||
assert_eq!(text(&s, "A4"), "East");
|
||||
assert_eq!(val(&s, "B4"), Value::Empty);
|
||||
assert_eq!(text(&s, "A5"), "Sum of Sales");
|
||||
assert_eq!(val(&s, "B5"), Value::Number(415.0));
|
||||
assert_eq!(text(&s, "A6"), "Sum of Units");
|
||||
assert_eq!(val(&s, "B6"), Value::Number(33.0));
|
||||
assert_eq!(text(&s, "A13"), "Total Sum of Sales");
|
||||
assert_eq!(val(&s, "B13"), Value::Number(TOTAL));
|
||||
assert_eq!(text(&s, "A14"), "Total Sum of Units");
|
||||
assert_eq!(val(&s, "B14"), Value::Number(72.0));
|
||||
// Tabular, no column field: "Total" heads the data column, as Excel saves it.
|
||||
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
|
||||
assert_eq!(text(&s, "A3"), "Region");
|
||||
assert_eq!(text(&s, "B3"), "Values");
|
||||
assert_eq!(text(&s, "C3"), "Total");
|
||||
s.execute("pivot.layout", json!({"layout": "compact"})).unwrap();
|
||||
// Σ Values before Region: the value fields are the outer items.
|
||||
s.execute("pivot.moveField", json!({"field": "Values", "from": "rows", "to": "rows", "position": 0})).unwrap();
|
||||
assert_eq!(pt(&s).values_position, Some(0));
|
||||
assert_eq!(text(&s, "A4"), "Sum of Sales");
|
||||
assert_eq!(val(&s, "B4"), Value::Empty);
|
||||
assert_eq!(text(&s, "A5"), "East");
|
||||
assert_eq!(val(&s, "B5"), Value::Number(415.0));
|
||||
assert_eq!(text(&s, "A8"), "Sum of Units");
|
||||
assert_eq!(text(&s, "A9"), "East");
|
||||
assert_eq!(val(&s, "B9"), Value::Number(33.0));
|
||||
assert_eq!(text(&s, "A12"), "Total Sum of Sales");
|
||||
assert_eq!(val(&s, "B13"), Value::Number(72.0));
|
||||
// Adding a row field in front keeps Σ Values ahead of Region.
|
||||
s.execute("pivot.addField", json!({"field": "Product", "area": "rows", "position": 0})).unwrap();
|
||||
assert_eq!(pt(&s).values_position, Some(1));
|
||||
s.execute("pivot.removeField", json!({"field": "Product", "area": "rows"})).unwrap();
|
||||
assert_eq!(pt(&s).values_position, Some(0));
|
||||
// No row field: one line per value field and no grand total.
|
||||
s.execute("pivot.removeField", json!({"field": "Region", "area": "rows"})).unwrap();
|
||||
let r = pt(&s).last_range.unwrap();
|
||||
assert_eq!(r.height(), 1 + 2);
|
||||
assert_eq!(text(&s, "A4"), "Sum of Sales");
|
||||
assert_eq!(val(&s, "B4"), Value::Number(TOTAL));
|
||||
assert_eq!(text(&s, "A5"), "Sum of Units");
|
||||
assert_eq!(val(&s, "B5"), Value::Number(72.0));
|
||||
// Back to Columns.
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "rows", "to": "columns"})).unwrap();
|
||||
assert!(!pt(&s).values_on_rows);
|
||||
assert_eq!(text(&s, "A3"), "Sum of Sales");
|
||||
assert_eq!(text(&s, "B3"), "Sum of Units");
|
||||
assert!(s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "filters"})).is_err());
|
||||
assert!(s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "rows", "to": "columns"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_item_puts_values_in_the_values_column() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales", "Units"]})).unwrap();
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "rows"})).unwrap();
|
||||
s.execute("pivot.collapse", json!({"field": "Region", "items": ["East"]})).unwrap();
|
||||
for layout in ["tabular", "outline"] {
|
||||
s.execute("pivot.layout", json!({"layout": layout})).unwrap();
|
||||
assert_eq!(text(&s, "C3"), "Values", "{layout}");
|
||||
let east = (4..20).find(|r| text(&s, &format!("A{r}")) == "East").unwrap();
|
||||
let first = if layout == "tabular" { east } else { east + 1 };
|
||||
assert_eq!(text(&s, &format!("B{first}")), "", "{layout}");
|
||||
assert_eq!(text(&s, &format!("C{first}")), "Sum of Sales", "{layout}");
|
||||
assert_eq!(val(&s, &format!("D{first}")), Value::Number(415.0), "{layout}");
|
||||
assert_eq!(text(&s, &format!("C{}", first + 1)), "Sum of Units", "{layout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_stay_last_in_columns() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Product"], "columns": ["Region"], "values": ["Sales", "Units"]})).unwrap();
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "columns", "position": 0})).unwrap();
|
||||
let p = pt(&s);
|
||||
assert!(!p.values_on_rows);
|
||||
assert_eq!(p.values_position, None);
|
||||
// Σ Values to Rows and back with a position: still last in Columns.
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "rows"})).unwrap();
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "rows", "to": "columns", "position": 0})).unwrap();
|
||||
assert_eq!(pt(&s).values_position, None);
|
||||
assert_eq!(text(&s, "B5"), "Sum of Sales");
|
||||
assert_eq!(text(&s, "C5"), "Sum of Units");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_source_keeps_values_ahead_of_its_field() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales", "Units"]})).unwrap();
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "rows", "position": 1})).unwrap();
|
||||
// The new source has no Region: Σ Values stays ahead of Product.
|
||||
s.execute("pivot.changeSource", json!({"source": "Sheet1!B1:E13"})).unwrap();
|
||||
let p = pt(&s);
|
||||
assert_eq!(p.rows.len(), 1);
|
||||
assert_eq!(p.values_position, Some(0));
|
||||
assert_eq!(text(&s, "A4"), "Sum of Sales");
|
||||
assert_eq!(text(&s, "A5"), "Apples");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_on_rows_between_row_fields() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales", "Units"]})).unwrap();
|
||||
s.execute("pivot.moveField", json!({"field": "Σ Values", "from": "columns", "to": "rows", "position": 1})).unwrap();
|
||||
// Compact: East, then per value field its products, then per-value subtotals of East.
|
||||
assert_eq!(text(&s, "A4"), "East");
|
||||
assert_eq!(text(&s, "A5"), "Sum of Sales");
|
||||
assert_eq!(text(&s, "A6"), "Apples");
|
||||
assert_eq!(val(&s, "B6"), Value::Number(160.0));
|
||||
assert_eq!(text(&s, "A9"), "Sum of Units");
|
||||
assert_eq!(text(&s, "A10"), "Apples");
|
||||
assert_eq!(val(&s, "B10"), Value::Number(16.0));
|
||||
assert_eq!(text(&s, "A13"), "East Sum of Sales");
|
||||
assert_eq!(val(&s, "B13"), Value::Number(415.0));
|
||||
assert_eq!(text(&s, "A14"), "East Sum of Units");
|
||||
assert_eq!(val(&s, "B14"), Value::Number(33.0));
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
assert_eq!(d.wb.styles.get(sh.style_id(CellRef::parse("A5").unwrap())).align.indent, 1);
|
||||
assert_eq!(d.wb.styles.get(sh.style_id(CellRef::parse("A6").unwrap())).align.indent, 2);
|
||||
// Outline: one column per level, "Values" heads the Σ Values column.
|
||||
s.execute("pivot.layout", json!({"layout": "outline"})).unwrap();
|
||||
assert_eq!(pt(&s).last_range.unwrap().width(), 4);
|
||||
assert_eq!(text(&s, "A3"), "Region");
|
||||
assert_eq!(text(&s, "B3"), "Values");
|
||||
assert_eq!(text(&s, "C3"), "Product");
|
||||
assert_eq!(text(&s, "B5"), "Sum of Sales");
|
||||
assert_eq!(text(&s, "C6"), "Apples");
|
||||
assert_eq!(val(&s, "D6"), Value::Number(160.0));
|
||||
// Tabular: labels start on their parent's row; totals per value field below each group.
|
||||
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
|
||||
assert_eq!(text(&s, "A4"), "East");
|
||||
assert_eq!(text(&s, "B4"), "Sum of Sales");
|
||||
assert_eq!(text(&s, "C4"), "Apples");
|
||||
assert_eq!(val(&s, "D4"), Value::Number(160.0));
|
||||
assert_eq!(text(&s, "B7"), "Sum of Units");
|
||||
assert_eq!(text(&s, "C7"), "Apples");
|
||||
assert_eq!(val(&s, "D7"), Value::Number(16.0));
|
||||
assert_eq!(text(&s, "A10"), "East Sum of Sales");
|
||||
assert_eq!(val(&s, "D10"), Value::Number(415.0));
|
||||
assert_eq!(text(&s, "A11"), "East Sum of Units");
|
||||
let r = pt(&s).last_range.unwrap();
|
||||
let last = r.end.row + 1;
|
||||
assert_eq!(text(&s, &format!("A{}", last - 1)), "Total Sum of Sales");
|
||||
assert_eq!(text(&s, &format!("A{last}")), "Total Sum of Units");
|
||||
assert_eq!(val(&s, &format!("D{last}")), Value::Number(72.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_after_source_edits() {
|
||||
let mut s = sales();
|
||||
@@ -1550,6 +1982,133 @@ mod tests {
|
||||
s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
|
||||
}
|
||||
|
||||
fn pivot_chart(s: &Session) -> gridcraft_model::Chart {
|
||||
s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone()
|
||||
}
|
||||
fn plotted(s: &Session) -> Vec<Vec<Option<f64>>> {
|
||||
let d = s.doc().unwrap();
|
||||
let data = gridcraft_chart::resolve(&d.wb, d.wb.active_sheet, &pivot_chart(s));
|
||||
data.series.into_iter().map(|x| x.values).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_chart_follows_the_report() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
|
||||
// Any cell of the report picks the PivotTable.
|
||||
let r = s.execute("insert.pivotChart", json!({"pivot": "B5"})).unwrap();
|
||||
assert_eq!(r["series"], 1);
|
||||
let ch = pivot_chart(&s);
|
||||
assert_eq!(ch.pivot.as_deref(), Some("Sheet2!PivotTable1"));
|
||||
assert_eq!(ch.title.as_deref(), Some("Total"));
|
||||
assert_eq!(ch.series[0].values, "Sheet2!$B$4:$B$6");
|
||||
assert_eq!(ch.series[0].categories.as_deref(), Some("Sheet2!$A$4:$A$6"));
|
||||
assert_eq!(plotted(&s), vec![vec![Some(415.0), Some(135.0), Some(285.0)]]);
|
||||
// A column field: one series per item, rebound by the layout change.
|
||||
s.execute("pivot.addField", json!({"field": "Product", "area": "columns"})).unwrap();
|
||||
let ch = pivot_chart(&s);
|
||||
let names: Vec<_> = ch.series.iter().map(|x| x.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, vec!["\"Apples\"", "\"Pears\"", "\"Plums\""]);
|
||||
assert_eq!(plotted(&s)[0], vec![Some(160.0), Some(90.0), Some(170.0)]);
|
||||
// Nested row fields: the innermost items only, as a union around the parent rows.
|
||||
s.execute("pivot.moveField", json!({"field": "Product", "from": "columns", "to": "rows"})).unwrap();
|
||||
let ch = pivot_chart(&s);
|
||||
assert!(ch.series[0].values.starts_with('('), "{}", ch.series[0].values);
|
||||
let pts = plotted(&s);
|
||||
assert_eq!(pts[0].len(), 9);
|
||||
assert_eq!(pts[0].iter().flatten().sum::<f64>(), TOTAL);
|
||||
// Survives an XLSX round trip as a PivotChart.
|
||||
let wb = (*s.doc().unwrap().wb).clone();
|
||||
let (back, _) = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap();
|
||||
let si = back.sheet_index("Sheet2").unwrap();
|
||||
assert_eq!(back.sheet(si).unwrap().charts.first().and_then(|c| c.pivot.clone()).as_deref(), Some("Sheet2!PivotTable1"));
|
||||
// Renaming the sheet keeps the link; a refresh still rebinds.
|
||||
s.execute("sheet.rename", json!({"name": "Report"})).unwrap();
|
||||
assert_eq!(pivot_chart(&s).pivot.as_deref(), Some("Report!PivotTable1"));
|
||||
s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap();
|
||||
assert_eq!(pivot_chart(&s).series.len(), 3);
|
||||
// Deleting the PivotTable leaves an ordinary chart.
|
||||
s.execute("pivot.delete", json!({})).unwrap();
|
||||
assert_eq!(pivot_chart(&s).pivot, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_chart_errors() {
|
||||
let mut s = sales();
|
||||
// No PivotTable yet.
|
||||
assert!(s.execute("insert.pivotChart", json!({})).is_err());
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"]})).unwrap();
|
||||
// Not in the report; no values.
|
||||
assert!(s.execute("insert.pivotChart", json!({"pivot": "Z99"})).is_err());
|
||||
assert!(s.execute("insert.pivotChart", json!({})).unwrap_err().to_string().contains("Values"));
|
||||
s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap();
|
||||
let r = s.execute("insert.pivotChart", json!({"pivot": "PivotTable1", "type": "line", "title": null})).unwrap();
|
||||
assert_eq!(r["series"], 1);
|
||||
let ch = pivot_chart(&s);
|
||||
assert_eq!(ch.kind, gridcraft_model::ChartKind::Line);
|
||||
assert_eq!(ch.title, None);
|
||||
// One undo step.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().charts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculated_field_on_sums() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
|
||||
let r = s.execute("pivot.calculatedField", json!({"name": "Price", "formula": "Sales / Units"})).unwrap();
|
||||
assert_eq!(r["formula"], "=Sales / Units");
|
||||
assert_eq!(text(&s, "C3"), "Sum of Price");
|
||||
assert_eq!(text(&s, "A4"), "East");
|
||||
// East: 415 sales over 33 units, from the sums.
|
||||
let east = val(&s, "C4").as_f64().unwrap();
|
||||
assert!((east - 415.0 / 33.0).abs() < 1e-12, "{east}");
|
||||
// The grand total applies the formula to the totals, not the sum of the rows.
|
||||
assert_eq!(text(&s, "A7"), "Grand Total");
|
||||
let total = val(&s, "C7").as_f64().unwrap();
|
||||
assert!((total - TOTAL / 72.0).abs() < 1e-12, "{total}");
|
||||
// Quoted names, functions, and another calculated field.
|
||||
s.execute("pivot.calculatedField", json!({"name": "Rounded", "formula": "=ROUND('Price'*2,1)"})).unwrap();
|
||||
assert_eq!(val(&s, "D4"), Value::Number(25.2));
|
||||
// Division by zero shows #DIV/0! cells.
|
||||
s.execute("pivot.calculatedField", json!({"name": "Zero", "formula": "=Sales/(Units-Units)"})).unwrap();
|
||||
assert_eq!(val(&s, "E4"), Value::Error(CellError::Div0));
|
||||
// Change and delete.
|
||||
s.execute("pivot.calculatedField", json!({"name": "zero", "formula": "=Units*2"})).unwrap();
|
||||
assert_eq!(val(&s, "E4"), Value::Number(66.0));
|
||||
s.execute("pivot.calculatedField", json!({"name": "Zero", "delete": true})).unwrap();
|
||||
assert_eq!(pt(&s).values.len(), 3);
|
||||
assert_eq!(pt(&s).calculated_fields.len(), 2);
|
||||
// The field list shows calculated fields.
|
||||
let f = s.execute("pivot.fields", json!({})).unwrap();
|
||||
assert!(f["fields"].as_array().unwrap().iter().any(|x| x["name"] == "Price" && x["calculated"] == true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculated_field_errors() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
|
||||
let mut e = |p: Json| s.execute("pivot.calculatedField", p).unwrap_err().to_string();
|
||||
assert!(e(json!({"name": "Bad", "formula": "=Sales*Bogus"})).contains("Bogus"));
|
||||
assert!(e(json!({"name": "Bad", "formula": "=A1*2"})).contains("cells"));
|
||||
assert!(e(json!({"name": "Bad", "formula": "=Sales*("})).contains("error"));
|
||||
assert!(e(json!({"name": "Sales", "formula": "=1"})).contains("already exists"));
|
||||
assert!(e(json!({"name": "Bad"})).contains("formula"));
|
||||
assert!(e(json!({"name": "Gone", "delete": true})).contains("Gone"));
|
||||
// A cycle is refused.
|
||||
s.execute("pivot.calculatedField", json!({"name": "X", "formula": "=Sales"})).unwrap();
|
||||
s.execute("pivot.calculatedField", json!({"name": "Y", "formula": "=X*2"})).unwrap();
|
||||
let err = s.execute("pivot.calculatedField", json!({"name": "X", "formula": "=Y"})).unwrap_err().to_string();
|
||||
assert!(err.contains("itself"), "{err}");
|
||||
// Calculated fields only go to Values; nothing changed after the failures.
|
||||
assert!(s.execute("pivot.addField", json!({"field": "Y", "area": "rows"})).is_err());
|
||||
assert_eq!(pt(&s).calculated_fields.len(), 2);
|
||||
// Without a name the dialog opens (menu-style call).
|
||||
s.ui_requests.clear();
|
||||
s.execute("pivot.calculatedField", json!({})).unwrap();
|
||||
assert!(matches!(s.ui_requests.last(), Some(crate::UiRequest::Dialog(n, _)) if n == "pivotCalculatedField"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_protection() {
|
||||
let mut s = sales();
|
||||
@@ -1715,4 +2274,38 @@ mod tests {
|
||||
assert!(e.contains("field name is not valid"), "{e}");
|
||||
assert!(s.execute("insert.pivotTable", json!({"source": "NoSuchTable"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_value_columns_are_refused() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let mut records: Vec<Json> = vec![json!(["Cat", "Sub", "V"])];
|
||||
for r in 0..64 {
|
||||
for c in 0..64 {
|
||||
records.push(json!([format!("c{r}"), format!("s{c}"), 1.0]));
|
||||
}
|
||||
}
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": records})).unwrap();
|
||||
let req = |n: usize| {
|
||||
let values: Vec<Json> = (0..n).map(|_| json!({"field": "V"})).collect();
|
||||
json!({"source": "A1:C4097", "rows": ["Cat"], "columns": ["Sub"], "values": values})
|
||||
};
|
||||
let e = s.execute("insert.pivotTable", req(256)).unwrap_err().to_string();
|
||||
assert!(e.contains("will not fit"), "{e}");
|
||||
assert!(s.execute("insert.pivotTable", req(128)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_column_items_count_as_one_column_group() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let mut records: Vec<Json> = vec![json!(["Grp", "Sub", "V"])];
|
||||
records.extend((0..64).map(|c| json!(["g", format!("s{c}"), 1.0])));
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": records})).unwrap();
|
||||
let values: Vec<Json> = (0..256).map(|_| json!({"field": "V"})).collect();
|
||||
s.execute("insert.pivotTable", json!({"source": "A1:C65", "columns": ["Grp"], "values": values})).unwrap();
|
||||
s.execute("pivot.collapse", json!({"field": "Grp"})).unwrap();
|
||||
// 64 Sub items under the collapsed "g" show as one column group: (1 + grand total) x 256 columns fit.
|
||||
s.execute("pivot.addField", json!({"field": "Sub", "area": "columns"})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
+357
-42
@@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Sheet geometry is in pixels at 96 dpi; PDF units are points.
|
||||
const PX_TO_PT: f32 = 0.75;
|
||||
pub(crate) const PX_TO_PT: f32 = 0.75;
|
||||
/// Most pages one export produces.
|
||||
pub const MAX_PAGES: usize = 2000;
|
||||
/// Cells in a page block above which only stored cells are visited (not every grid position).
|
||||
@@ -110,13 +110,15 @@ pub struct SheetLayout {
|
||||
/// Heading sizes in sheet pixels (0 when headings are off).
|
||||
pub heading_w: f32,
|
||||
pub heading_h: f32,
|
||||
/// Manual page breaks apply (they don't when the sheet is fitted to pages).
|
||||
pub manual_breaks: bool,
|
||||
}
|
||||
|
||||
impl SheetLayout {
|
||||
fn k(&self) -> f32 {
|
||||
PX_TO_PT * self.scale
|
||||
}
|
||||
fn avail(&self) -> (f32, f32) {
|
||||
pub(crate) fn avail(&self) -> (f32, f32) {
|
||||
let [l, r, t, b, ..] = self.margins;
|
||||
((self.page_w - l - r).max(36.0), (self.page_h - t - b).max(36.0))
|
||||
}
|
||||
@@ -271,30 +273,11 @@ pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_overrid
|
||||
title_cols,
|
||||
heading_w,
|
||||
heading_h,
|
||||
manual_breaks: fit.is_none(),
|
||||
};
|
||||
let paginate = |lay: &mut SheetLayout, manual: bool| {
|
||||
let k = lay.k();
|
||||
let (aw, ah) = lay.avail();
|
||||
let (aw, ah) = (aw / k, ah / k);
|
||||
let rb: Vec<u32> = if manual { st.row_breaks.clone() } else { vec![] };
|
||||
let cb: Vec<u32> = if manual { st.col_breaks.clone() } else { vec![] };
|
||||
let (mut rb, mut cb) = (rb, cb);
|
||||
rb.sort_unstable();
|
||||
cb.sort_unstable();
|
||||
let title_h = |start: u32| -> f32 {
|
||||
match title_rows {
|
||||
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|r| sh.row_height(r)).sum(),
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
let title_w = |start: u32| -> f32 {
|
||||
match title_cols {
|
||||
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|c| sh.col_width(c)).sum(),
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
lay.row_bands = bands(area.start.row, area.end.row, |r| sh.row_height(r), |start| (ah - heading_h - title_h(start)).max(1.0), &rb, MAX_PAGES);
|
||||
lay.col_bands = bands(area.start.col, area.end.col, |c| sh.col_width(c), |start| (aw - heading_w - title_w(start)).max(1.0), &cb, MAX_PAGES);
|
||||
lay.manual_breaks = manual;
|
||||
(lay.row_bands, lay.col_bands) = split_bands(sh, lay, MAX_PAGES);
|
||||
lay.pages.clear();
|
||||
'outer: for ci in 0..lay.col_bands.len() {
|
||||
for ri in 0..lay.row_bands.len() {
|
||||
@@ -332,6 +315,37 @@ pub fn layout_sheet(wb: &Workbook, si: usize, opts: &PrintOptions, range_overrid
|
||||
Some(lay)
|
||||
}
|
||||
|
||||
/// Splits a layout's area into row and column bands that fit its pages (at most `cap` of each),
|
||||
/// honouring manual breaks (when `lay.manual_breaks`), print headings and repeated titles. The
|
||||
/// one pagination rule shared by printing, PDF export, Page Break Preview and Page Layout view.
|
||||
pub(crate) fn split_bands(sh: &Sheet, lay: &SheetLayout, cap: usize) -> (Vec<(u32, u32)>, Vec<(u32, u32)>) {
|
||||
let k = lay.k();
|
||||
let (aw, ah) = lay.avail();
|
||||
let (aw, ah) = (aw / k, ah / k);
|
||||
let st = &lay.settings;
|
||||
let mut rb: Vec<u32> = if lay.manual_breaks { st.row_breaks.clone() } else { vec![] };
|
||||
let mut cb: Vec<u32> = if lay.manual_breaks { st.col_breaks.clone() } else { vec![] };
|
||||
rb.sort_unstable();
|
||||
cb.sort_unstable();
|
||||
let (title_rows, title_cols) = (lay.title_rows, lay.title_cols);
|
||||
let title_h = |start: u32| -> f32 {
|
||||
match title_rows {
|
||||
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|r| sh.row_height(r)).sum(),
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
let title_w = |start: u32| -> f32 {
|
||||
match title_cols {
|
||||
Some((a, b)) if a < start => (a..=b.min(start - 1)).map(|c| sh.col_width(c)).sum(),
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
let area = lay.area;
|
||||
let rows = bands(area.start.row, area.end.row, |r| sh.row_height(r), |start| (ah - lay.heading_h - title_h(start)).max(1.0), &rb, cap);
|
||||
let cols = bands(area.start.col, area.end.col, |c| sh.col_width(c), |start| (aw - lay.heading_w - title_w(start)).max(1.0), &cb, cap);
|
||||
(rows, cols)
|
||||
}
|
||||
|
||||
/// Lays out every sheet a print command covers.
|
||||
pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
let mut out = Vec::new();
|
||||
@@ -375,6 +389,132 @@ pub struct HfContext {
|
||||
pub time: String,
|
||||
}
|
||||
|
||||
/// Today's date and the current time as headers and footers show them (`&D`, `&T`).
|
||||
pub fn hf_date_time(wb: &Workbook) -> (String, String) {
|
||||
let now = gridcraft_core::date::serial_in_system(wb.date_system, gridcraft_calc::now_serial());
|
||||
let date = crate::display::format(&Value::Number(now.floor()), "m/d/yyyy", wb).text;
|
||||
let time = crate::display::format(&Value::Number(now), "h:mm AM/PM", wb).text;
|
||||
(date, time)
|
||||
}
|
||||
|
||||
/// Header/footer codes and the field names the Page Layout view shows for them while editing.
|
||||
pub const HF_FIELDS: [(char, &str); 8] = [
|
||||
('P', "&[Page]"),
|
||||
('N', "&[Pages]"),
|
||||
('D', "&[Date]"),
|
||||
('T', "&[Time]"),
|
||||
('Z', "&[Path]"),
|
||||
('F', "&[File]"),
|
||||
('A', "&[Tab]"),
|
||||
('G', "&[Picture]"),
|
||||
];
|
||||
|
||||
/// Splits a header/footer string into its raw left, centre and right sections (codes kept).
|
||||
/// Text before the first `&L`/`&C`/`&R` belongs to the centre, as when printing.
|
||||
pub fn split_header_footer(spec: &str) -> [String; 3] {
|
||||
let mut out: [String; 3] = Default::default();
|
||||
let mut cur = 1usize;
|
||||
let chars: Vec<char> = spec.chars().take(10_000).collect();
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
let next = chars.get(i + 1).copied();
|
||||
let sec = cur.min(2);
|
||||
match (c, next) {
|
||||
('&', Some('L' | 'l')) => cur = 0,
|
||||
('&', Some('C' | 'c')) => cur = 1,
|
||||
('&', Some('R' | 'r')) => cur = 2,
|
||||
('&', Some('"')) => {
|
||||
// &"Font,Style" is kept whole.
|
||||
let end = chars[i + 2..].iter().position(|ch| *ch == '"').map_or(chars.len(), |p| i + 3 + p);
|
||||
out[sec].extend(&chars[i..end.min(chars.len())]);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
('&', Some(n)) => {
|
||||
out[sec].push('&');
|
||||
out[sec].push(n);
|
||||
}
|
||||
('&', None) => {}
|
||||
(ch, _) => {
|
||||
out[sec].push(ch);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Joins raw left, centre and right sections into one header/footer string.
|
||||
pub fn join_header_footer(sections: &[String; 3]) -> String {
|
||||
let mut s = String::new();
|
||||
for (code, text) in ["&L", "&C", "&R"].iter().zip(sections) {
|
||||
if !text.is_empty() {
|
||||
s.push_str(code);
|
||||
s.push_str(text);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// A raw section as the user edits it: `&P` shows as `&[Page]`, `&N` as `&[Pages]`, and so on.
|
||||
pub fn codes_to_fields(raw: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut it = raw.chars().peekable();
|
||||
while let Some(c) = it.next() {
|
||||
if c != '&' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
// A dangling `&` at the end is dropped (printing ignores it too).
|
||||
if let Some(n) = it.next() {
|
||||
match HF_FIELDS.iter().find(|(code, _)| *code == n.to_ascii_uppercase()) {
|
||||
Some((_, field)) => out.push_str(field),
|
||||
None => {
|
||||
out.push('&');
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The inverse of [`codes_to_fields`]: field names become codes again; a dangling `&` at the end
|
||||
/// becomes a literal ampersand so it can't swallow the next section's code.
|
||||
pub fn fields_to_codes(text: &str) -> String {
|
||||
let chars: Vec<char> = text.chars().take(10_000).collect();
|
||||
let mut out = String::new();
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
if c != '&' {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if chars.get(i + 1) == Some(&'&') {
|
||||
out.push_str("&&");
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
let rest: String = chars[i..].iter().take(12).collect();
|
||||
if let Some((code, field)) = HF_FIELDS.iter().find(|(_, f)| rest.starts_with(f)) {
|
||||
out.push('&');
|
||||
out.push(*code);
|
||||
i += field.chars().count();
|
||||
continue;
|
||||
}
|
||||
if i + 1 == chars.len() {
|
||||
out.push_str("&&");
|
||||
} else {
|
||||
out.push('&');
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One header/footer section: its text and whether `&B` made it bold.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HfSection {
|
||||
@@ -887,6 +1027,21 @@ fn empty_for_overflow(sh: &Sheet, c: CellRef, merges: &[RangeRef]) -> bool {
|
||||
sh.value_ref(c).is_none_or(|v| v.is_empty()) && !merges.iter().any(|m| m.contains(c))
|
||||
}
|
||||
|
||||
/// Unscaled width of the empty Center Across Selection cells right of `c`, which its text is centred over too.
|
||||
fn center_across_width(styles: &StyleTable, sh: &Sheet, c: CellRef, merges: &[RangeRef]) -> f32 {
|
||||
let mut ext = 0.0;
|
||||
let mut col = c.col + 1;
|
||||
while col < MAX_COLS && ext < 20_000.0 {
|
||||
let nc = CellRef::new(c.row, col);
|
||||
if !empty_for_overflow(sh, nc, merges) || styles.get(sh.style_id(nc)).align.h != HAlign::CenterAcross {
|
||||
break;
|
||||
}
|
||||
ext += sh.col_width(col);
|
||||
col += 1;
|
||||
}
|
||||
ext
|
||||
}
|
||||
|
||||
fn draw_text(pg: &mut Page, b: &Block, c: CellRef, l: &Look, rect: (f32, f32, f32, f32), merged: bool, merges: &[RangeRef], limits: (f32, f32)) {
|
||||
let (x, y, w, h) = rect;
|
||||
let sh = b.sh;
|
||||
@@ -970,8 +1125,11 @@ fn draw_text(pg: &mut Page, b: &Block, c: CellRef, l: &Look, rect: (f32, f32, f3
|
||||
VAlign::Bottom => y + h - pad - size * 0.22 - (n - 1.0) * line_h,
|
||||
};
|
||||
// Overflow into empty neighbours (single-line text, not merged).
|
||||
let (mut clip_l, mut clip_r) = (x, x + w);
|
||||
if !wrap && !merged && !is_num && rot.abs() != 90 && tw + 2.0 * pad + indent > w {
|
||||
// Center Across Selection spans the empty Center Across cells to its right; the text stays within that run.
|
||||
let spans = st.align.h == HAlign::CenterAcross && !wrap && !merged && rot == 0;
|
||||
let across = if spans { center_across_width(&wb.styles, sh, c, merges) * b.k } else { 0.0 };
|
||||
let (mut clip_l, mut clip_r) = (x, x + w + across);
|
||||
if !wrap && !merged && !is_num && rot.abs() != 90 && across <= 0.0 && tw + 2.0 * pad + indent > w {
|
||||
let need = tw + 2.0 * pad + indent - w;
|
||||
let grow = |dir: i64, mut need: f32| -> f32 {
|
||||
let mut ext = 0.0;
|
||||
@@ -1043,7 +1201,7 @@ fn draw_text(pg: &mut Page, b: &Block, c: CellRef, l: &Look, rect: (f32, f32, f3
|
||||
let lw = gridcraft_pdf::text_width(font, size, line);
|
||||
let lx = match h_align {
|
||||
HAlign::Right => x + w - pad - lw - indent,
|
||||
HAlign::Center => x + (w - lw) / 2.0,
|
||||
HAlign::Center => x + (w + across - lw) / 2.0,
|
||||
_ => x + pad + indent,
|
||||
};
|
||||
let ly = first_baseline + i as f32 * line_h;
|
||||
@@ -1127,7 +1285,7 @@ fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block)
|
||||
}
|
||||
let (x, y, w, h) = place(r);
|
||||
let fill = rgb_of(shp.fill, wb);
|
||||
let line = rgb_of(shp.line, wb).map(|c| (c, (0.75 * b.k).max(0.25)));
|
||||
let line = rgb_of(shp.line, wb).filter(|_| !shp.format.no_line).map(|c| (c, (0.75 * b.k).max(0.25)));
|
||||
match shp.kind {
|
||||
ShapeKind::Ellipse => {
|
||||
let pts: Vec<[f32; 2]> = (0..72)
|
||||
@@ -1154,13 +1312,29 @@ fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block)
|
||||
}
|
||||
}
|
||||
if !shp.text.is_empty() {
|
||||
let size = 11.0 * b.scale;
|
||||
let lines = wrap_lines(&shp.text, Font::Helvetica, size, (w - 4.0 * b.k).max(size));
|
||||
let mut yy = y + 2.0 * b.k + size * 0.8;
|
||||
use gridcraft_model::{ShapeTextAlign, ShapeTextAnchor};
|
||||
let fm = &shp.format;
|
||||
let text_box = shp.kind == ShapeKind::TextBox;
|
||||
let size = fm.font_size.unwrap_or(11.0).clamp(1.0, 4000.0) * b.scale;
|
||||
let font = Font::styled(Font::family_for(fm.font.as_deref().unwrap_or("")), fm.bold, fm.italic);
|
||||
let color = fm.text_color.and_then(|c| rgb_of(c, wb)).unwrap_or([0, 0, 0]);
|
||||
let align = fm.align.unwrap_or(if text_box { ShapeTextAlign::Left } else { ShapeTextAlign::Center });
|
||||
let anchor = fm.anchor.unwrap_or(if text_box { ShapeTextAnchor::Top } else { ShapeTextAnchor::Middle });
|
||||
let lines = wrap_lines(&shp.text, font, size, (w - 4.0 * b.k).max(size));
|
||||
let block_h = lines.len().min(500) as f32 * size * 1.2;
|
||||
let mut yy = match anchor {
|
||||
ShapeTextAnchor::Top => y + 2.0 * b.k,
|
||||
ShapeTextAnchor::Middle => y + (h - block_h) / 2.0,
|
||||
ShapeTextAnchor::Bottom => y + h - 2.0 * b.k - block_h,
|
||||
} + size * 0.8;
|
||||
for l in lines.iter().take(500) {
|
||||
let lw = gridcraft_pdf::text_width(Font::Helvetica, size, l);
|
||||
let lx = if shp.kind == ShapeKind::TextBox { x + 2.0 * b.k } else { x + (w - lw) / 2.0 };
|
||||
pg.text(lx, yy, size, Font::Helvetica, [0, 0, 0], l);
|
||||
let lw = gridcraft_pdf::text_width(font, size, l);
|
||||
let lx = match align {
|
||||
ShapeTextAlign::Left => x + 2.0 * b.k,
|
||||
ShapeTextAlign::Center => x + (w - lw) / 2.0,
|
||||
ShapeTextAlign::Right => x + w - 2.0 * b.k - lw,
|
||||
};
|
||||
pg.text(lx, yy, size, font, color, l);
|
||||
yy += size * 1.2;
|
||||
}
|
||||
}
|
||||
@@ -1213,11 +1387,11 @@ fn draw_headings(pg: &mut Page, b: &Block, col_heads: bool, row_heads: bool, at:
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_header_footer(pg: &mut Page, lay: &SheetLayout, cx: &HfContext) {
|
||||
fn draw_header_footer(pg: &mut Page, lay: &SheetLayout, which: gridcraft_model::HfPage, cx: &HfContext) {
|
||||
let [l, r, _, _, hm, fm] = lay.margins;
|
||||
let pw = lay.page_w;
|
||||
let ph = lay.page_h;
|
||||
for (spec, header) in [(&lay.settings.header, true), (&lay.settings.footer, false)] {
|
||||
for (spec, header) in [(lay.settings.hf(which, false), true), (lay.settings.hf(which, true), false)] {
|
||||
if spec.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -1286,16 +1460,14 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
|
||||
doc.info.title = if wb.props.title.is_empty() { file.to_string() } else { wb.props.title.clone() };
|
||||
doc.info.author = wb.props.author.clone();
|
||||
let total: usize = layouts.iter().map(|l| l.pages.len()).sum();
|
||||
let now = gridcraft_calc::now_serial();
|
||||
let date = crate::display::format(&Value::Number(now.floor()), "m/d/yyyy", wb).text;
|
||||
let time = crate::display::format(&Value::Number(now), "h:mm AM/PM", wb).text;
|
||||
let (date, time) = hf_date_time(wb);
|
||||
let mut page_no = 0usize;
|
||||
for lay in layouts {
|
||||
let Some(sh) = wb.sheet(lay.sheet) else { continue };
|
||||
let mut cf = if sh.cond_formats.is_empty() { None } else { Some(crate::cf::CfCache::new()) };
|
||||
let k = lay.k();
|
||||
let (aw, ah) = lay.avail();
|
||||
for (ri, ci) in &lay.pages {
|
||||
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
|
||||
page_no += 1;
|
||||
let (Some(rband), Some(cband)) = (lay.row_bands.get(*ri).copied(), lay.col_bands.get(*ci).copied()) else { continue };
|
||||
let rsegs = segments(lay.title_rows, rband);
|
||||
@@ -1339,7 +1511,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
|
||||
date: date.clone(),
|
||||
time: time.clone(),
|
||||
};
|
||||
draw_header_footer(pg, lay, &cx);
|
||||
draw_header_footer(pg, lay, lay.settings.hf_page(pi == 0, page_no), &cx);
|
||||
}
|
||||
}
|
||||
let n = doc.page_count();
|
||||
@@ -1356,7 +1528,7 @@ fn build_pdf(s: &Session, p: &Json, cmd: &str) -> Result<(Vec<u8>, usize)> {
|
||||
Ok(render_pdf(&d.wb, &lays, &d.display_title(), &path))
|
||||
}
|
||||
|
||||
fn export_pdf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
pub(crate) fn export_pdf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (bytes, pages) = build_pdf(s, p, "file.exportPdf")?;
|
||||
match str_param(p, "path").filter(|x| !x.is_empty()) {
|
||||
Some(path) => {
|
||||
@@ -1587,6 +1759,71 @@ mod tests {
|
||||
hay.windows(needle.len()).any(|w| w == needle.as_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_sections_split_join_and_field_names() {
|
||||
let spec = "&L&\"Arial,Bold\"Sales &&Co&CPage &P of &N&R&D";
|
||||
let parts = split_header_footer(spec);
|
||||
assert_eq!(parts, ["&\"Arial,Bold\"Sales &&Co".to_string(), "Page &P of &N".into(), "&D".into()]);
|
||||
assert_eq!(join_header_footer(&parts), spec);
|
||||
// Text before any section code is the centre section, as when printing.
|
||||
assert_eq!(split_header_footer("Report"), [String::new(), "Report".into(), String::new()]);
|
||||
assert_eq!(codes_to_fields("Page &P of &N, &A (&F) &&"), "Page &[Page] of &[Pages], &[Tab] (&[File]) &&");
|
||||
assert_eq!(fields_to_codes("Page &[Page] of &[Pages], &[Tab] (&[File]) &&"), "Page &P of &N, &A (&F) &&");
|
||||
// A dangling ampersand stays literal instead of eating the next section's code.
|
||||
assert_eq!(fields_to_codes("R&"), "R&&");
|
||||
let joined = join_header_footer(&[fields_to_codes("R&"), "x".into(), String::new()]);
|
||||
assert_eq!(split_header_footer(&joined)[0], "R&&");
|
||||
let cx = HfContext { page: 2, pages: 5, sheet: "Data".into(), ..Default::default() };
|
||||
let out = expand_header_footer(&join_header_footer(&[String::new(), fields_to_codes("&[Page] / &[Pages]"), fields_to_codes("&[Tab]")]), &cx);
|
||||
assert_eq!((out[1].text.as_str(), out[2].text.as_str()), ("2 / 5", "Data"));
|
||||
// Hostile input never panics.
|
||||
for t in ["&", "&\"", "&\"unterminated", "&&&", "&[Pag", "\u{1F600}&[Page]"] {
|
||||
let _ = join_header_footer(&split_header_footer(t));
|
||||
let _ = fields_to_codes(&codes_to_fields(t));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_footer_date_follows_the_workbook_date_system() {
|
||||
let mut wb = Workbook::new();
|
||||
let date_1900 = hf_date_time(&wb).0;
|
||||
wb.date_system = gridcraft_core::DateSystem::D1904;
|
||||
assert_eq!(hf_date_time(&wb).0, date_1900);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_footer_section_edits_are_undoable_and_views_are_per_sheet() {
|
||||
let mut s = s();
|
||||
s.execute("pageLayout.headerFooter", json!({"header": "&LLeft&RRight"})).unwrap();
|
||||
let r = s.execute("pageLayout.headerFooter", json!({"part": "header", "section": "center", "text": "Page &[Page] of &[Pages]"})).unwrap();
|
||||
assert_eq!(r["header"], "&LLeft&CPage &P of &N&RRight");
|
||||
s.execute("pageLayout.headerFooter", json!({"part": "footer", "section": "right", "text": "&[Date]"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().print.footer, "&R&D");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().print.header, "&LLeft&RRight");
|
||||
assert!(s.execute("pageLayout.headerFooter", json!({"part": "middle", "text": "x"})).is_err());
|
||||
assert!(s.execute("pageLayout.headerFooter", json!({"section": "top"})).is_err());
|
||||
let long = "x".repeat(1000);
|
||||
s.execute("pageLayout.headerFooter", json!({"part": "header", "section": "left", "text": long})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.sheet(0).unwrap().print.header.chars().count() <= 255);
|
||||
// The view is per sheet and doesn't dirty a clean workbook.
|
||||
let mut fresh = Session::new();
|
||||
fresh.new_workbook();
|
||||
fresh.execute("home.insertSheet", json!({})).unwrap();
|
||||
fresh.doc_mut().unwrap().saved = fresh.doc().unwrap().wb.clone();
|
||||
fresh.execute("view.pageLayout", json!({"sheet": 0})).unwrap();
|
||||
let wb = &fresh.doc().unwrap().wb;
|
||||
assert_eq!((wb.sheet(0).unwrap().view, wb.sheet(1).unwrap().view), (SheetViewMode::PageLayout, SheetViewMode::Normal));
|
||||
assert!(!fresh.doc().unwrap().is_dirty(), "switching views is not an edit");
|
||||
s.execute("view.pageLayout", json!({"sheet": 0})).unwrap();
|
||||
s.execute("view.normal", json!({"sheet": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().view, SheetViewMode::Normal);
|
||||
assert_eq!(s.execute("view.ruler", json!({"on": false})).unwrap()["on"], false);
|
||||
assert!(s.hide_ruler);
|
||||
assert_eq!(s.execute("view.ruler", json!({})).unwrap()["on"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_count_300_rows_letter_portrait() {
|
||||
let mut s = s();
|
||||
@@ -1631,6 +1868,32 @@ mod tests {
|
||||
assert_eq!(pv["pageList"][2]["range"], "K1:O45");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_and_even_pages_print_their_own_headers() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]]})).unwrap();
|
||||
s.execute("pageLayout.pageSetup", json!({"rowBreaks": [2, 4]})).unwrap();
|
||||
let r = s
|
||||
.execute(
|
||||
"pageLayout.headerFooter",
|
||||
json!({"header": "&COdd &P", "evenHeader": "&CEven &P", "firstHeader": "&CCover", "differentFirst": true, "differentOddEven": true}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["firstHeader"], "&CCover");
|
||||
let (pdf, pages) = pdf_of(&mut s, json!({}));
|
||||
assert_eq!(pages, 3);
|
||||
assert!(contains(&pdf, "(Cover) Tj") && contains(&pdf, "(Even 2) Tj") && contains(&pdf, "(Odd 3) Tj"));
|
||||
assert!(!contains(&pdf, "(Odd 1) Tj"), "the first page has its own header");
|
||||
// One section of the even-page footer, edited in place.
|
||||
s.execute("pageLayout.headerFooter", json!({"page": "even", "part": "footer", "section": "right", "text": "&[Tab]"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheet(0).unwrap().print.even_footer, "&R&A");
|
||||
assert!(s.execute("pageLayout.headerFooter", json!({"page": "last", "part": "header", "text": "x"})).is_err());
|
||||
// Turned off, every page prints the odd header again.
|
||||
s.execute("pageLayout.headerFooter", json!({"differentFirst": false, "differentOddEven": false})).unwrap();
|
||||
let (pdf, _) = pdf_of(&mut s, json!({}));
|
||||
assert!(contains(&pdf, "(Odd 1) Tj") && contains(&pdf, "(Odd 2) Tj") && !contains(&pdf, "(Cover) Tj"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_contains_text_and_header_codes_expand() {
|
||||
let mut s = s();
|
||||
@@ -1686,6 +1949,24 @@ mod tests {
|
||||
assert!(r["base64"].as_str().unwrap().len() > 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_pdf_writes_a_pdf_and_keeps_the_workbook_file() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": "hello"})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-save-pdf-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Out.PDF");
|
||||
let r = s.execute("file.saveAs", json!({"path": path.to_str().unwrap()})).unwrap();
|
||||
assert_eq!(r["pages"], 1);
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert!(bytes.starts_with(b"%PDF-"));
|
||||
assert!(contains(&bytes, "(hello) Tj"));
|
||||
// The PDF is a print, not the workbook's file: Save still asks where to put the workbook.
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.path.is_none() && d.is_dirty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rich_sheet_renders() {
|
||||
let mut s = Session::new();
|
||||
@@ -1791,6 +2072,23 @@ mod tests {
|
||||
assert!(s.execute("file.exportPdf", json!({})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_pdf_without_a_path_returns_bytes_and_never_opens_a_dialog() {
|
||||
let mut s = s();
|
||||
for params in [json!({}), json!({"path": ""}), json!({"path": null})] {
|
||||
let r = s.execute("file.exportPdf", params).unwrap();
|
||||
assert!(r.get("path").is_none(), "no file is written without a path");
|
||||
let bytes = crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap();
|
||||
assert!(bytes.starts_with(b"%PDF-"));
|
||||
}
|
||||
assert!(s.take_ui_requests().is_empty(), "a programmatic call never queues a dialog");
|
||||
// Headless callers (CLI, MCP) get the same bytes, not an error.
|
||||
assert!(s.execute_headless("file.exportPdf", json!({})).is_ok());
|
||||
// With no workbook open it is a clear error, not a panic.
|
||||
let mut none = Session::new();
|
||||
assert!(none.execute("file.exportPdf", json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bands_unit() {
|
||||
let b = bands(0, 9, |_| 10.0, |_| 35.0, &[], 100);
|
||||
@@ -1808,6 +2106,23 @@ mod tests {
|
||||
assert!(w.len() > 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_across_spans_following_empty_center_across_cells() {
|
||||
let mut styles = StyleTable::default();
|
||||
let across = styles.intern(Style { align: Alignment { h: HAlign::CenterAcross, ..Alignment::default() }, ..Style::default() });
|
||||
let mut sh = Sheet::new("S");
|
||||
for col in 0..3 {
|
||||
sh.set_style(CellRef::new(0, col), across);
|
||||
}
|
||||
sh.set_value(CellRef::new(0, 0), Value::Text("Title".into()));
|
||||
let a1 = CellRef::new(0, 0);
|
||||
assert_eq!(center_across_width(&styles, &sh, a1, &[]), sh.col_width(1) + sh.col_width(2));
|
||||
sh.set_value(CellRef::new(0, 2), Value::Text("x".into()));
|
||||
assert_eq!(center_across_width(&styles, &sh, a1, &[]), sh.col_width(1));
|
||||
let merged = [RangeRef::new(CellRef::new(0, 1), CellRef::new(1, 1))];
|
||||
assert_eq!(center_across_width(&styles, &sh, a1, &merged), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_wrapped_text_prints_rotated() {
|
||||
// Upright headers over narrow columns (mark sheets) combine rotation with Wrap Text.
|
||||
|
||||
+447
-10
@@ -1,6 +1,8 @@
|
||||
//! Review tab: protection, spelling (basic), workbook statistics.
|
||||
//! Review tab: protection, spelling (basic), workbook statistics, comment navigation and the
|
||||
//! Comments pane, Show All Notes and Convert to Comments.
|
||||
|
||||
use gridcraft_model::{SheetProtection, password_hash};
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_model::{EditRange, PasswordHash, SheetProtection, Visibility, password_hash};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::*;
|
||||
@@ -17,17 +19,129 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
protect_sheet
|
||||
),
|
||||
cmd!("review.unprotectSheet", "Unprotect Sheet", ["Review", "Protect"], None, "{password?}", has_doc, unprotect_sheet),
|
||||
cmd!("review.protectWorkbook", "Protect Workbook", ["Review", "Protect"], None, "{on?: bool}", has_doc, protect_workbook),
|
||||
cmd!(
|
||||
"review.protectWorkbook",
|
||||
"Protect Workbook",
|
||||
["Review", "Protect"],
|
||||
None,
|
||||
"{on?: bool (default: toggle), password?} (structure protection; unprotecting needs the password when one was set)",
|
||||
has_doc,
|
||||
protect_workbook
|
||||
),
|
||||
cmd!(query "review.workbookStatistics", "Workbook Statistics", ["Review", "Proofing"], None, "{}", has_doc, stats),
|
||||
// Not journaled: the params can hold a password.
|
||||
CommandSpec {
|
||||
id: "review.allowEditRanges",
|
||||
label: "Allow Edit Ranges…",
|
||||
menu: &["Review", "Protect"],
|
||||
shortcut: None,
|
||||
params: "{action?: list (default) | add | modify | delete | unlock, title?, range?, password?, newTitle?, sheet?} → ranges",
|
||||
enabled: has_doc,
|
||||
run: allow_edit_ranges,
|
||||
journal: false,
|
||||
undoable: true,
|
||||
},
|
||||
cmd!(query "review.checkAccessibility", "Check Accessibility", ["Review", "Accessibility"], None, "{} → issues", has_doc, accessibility),
|
||||
cmd!(noundo "review.previousComment", "Previous Comment", ["Review", "Comments"], None, "{} → {sheet, cell}", has_comments, |s, _| {
|
||||
step_comment(s, false)
|
||||
}),
|
||||
cmd!(noundo "review.nextComment", "Next Comment", ["Review", "Comments"], None, "{} → {sheet, cell}", has_comments, |s, _| step_comment(
|
||||
s, true
|
||||
)),
|
||||
cmd!(query "review.showComments", "Show Comments", ["Review", "Comments"], None, "{on?: bool} (toggles the Comments pane)", has_doc, |s, p| {
|
||||
s.comments_pane = bool_param(p, "on").unwrap_or(!s.comments_pane);
|
||||
Ok(json!({"on": s.comments_pane}))
|
||||
}),
|
||||
cmd!(query "review.showAllNotes", "Show All Notes", ["Review", "Notes"], None, "{on?: bool}", has_doc, |s, p| {
|
||||
s.show_all_notes = bool_param(p, "on").unwrap_or(!s.show_all_notes);
|
||||
Ok(json!({"on": s.show_all_notes}))
|
||||
}),
|
||||
cmd!(
|
||||
"review.convertToComments",
|
||||
"Convert to Comments",
|
||||
["Review", "Notes"],
|
||||
None,
|
||||
"{} (every note in the workbook) → {converted}",
|
||||
has_doc,
|
||||
convert_notes
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Threaded comments in navigation order: visible sheets in tab order, then row by row.
|
||||
fn comment_cells(s: &Session) -> Vec<(usize, CellRef)> {
|
||||
let Some(d) = s.active() else { return vec![] };
|
||||
d.wb.sheets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, sh)| sh.visibility == Visibility::Visible)
|
||||
// `CellRef` orders by row, then column: reading order.
|
||||
.flat_map(|(i, sh)| sh.comments.iter().filter(|(_, c)| c.threaded).map(move |(at, _)| (i, *at)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn has_comments(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if comment_cells(s).is_empty() { Err("there are no comments in this workbook".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Selects the next (or previous) threaded comment after the active cell, moving on to the next
|
||||
/// sheet and wrapping around at the end of the workbook.
|
||||
fn step_comment(s: &mut Session, forward: bool) -> Result<Json> {
|
||||
let list = comment_cells(s);
|
||||
let d = s.doc()?;
|
||||
let here = (d.wb.active_sheet, d.selection.active);
|
||||
let target = if forward {
|
||||
list.iter().find(|c| **c > here).or_else(|| list.first())
|
||||
} else {
|
||||
list.iter().rev().find(|c| **c < here).or_else(|| list.last())
|
||||
};
|
||||
let Some(&(sheet, at)) = target else {
|
||||
return Err(EngineError::Other("There are no comments in this workbook.".into()));
|
||||
};
|
||||
let d = s.doc_mut()?;
|
||||
d.wb_switch_sheet(sheet);
|
||||
d.selection = crate::Selection::at(at);
|
||||
if let Some(sh) = d.wb.active() {
|
||||
d.selection.expand_merges(sh);
|
||||
}
|
||||
let name = d.wb.active().map(|sh| sh.name.clone()).unwrap_or_default();
|
||||
Ok(json!({"sheet": name, "cell": at.a1()}))
|
||||
}
|
||||
|
||||
/// Review › Notes › Convert to Comments: every note in the workbook becomes a threaded comment
|
||||
/// with the same author and text.
|
||||
fn convert_notes(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
let sheets: Vec<usize> =
|
||||
s.doc()?.wb.sheets.iter().enumerate().filter(|(_, sh)| sh.comments.values().any(|c| !c.threaded)).map(|(i, _)| i).collect();
|
||||
if sheets.is_empty() {
|
||||
return Ok(json!({"converted": 0}));
|
||||
}
|
||||
edit(s, |cx| {
|
||||
let mut n = 0usize;
|
||||
for i in &sheets {
|
||||
for c in cx.sheet_mut(*i)?.comments.values_mut().filter(|c| !c.threaded) {
|
||||
c.threaded = true;
|
||||
c.visible = false;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
Ok(json!({"converted": n}))
|
||||
})
|
||||
}
|
||||
|
||||
fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
// Re-protecting a password-protected sheet would replace the password without knowing it:
|
||||
// unprotect it first, as in Excel. One without a password can take new options directly.
|
||||
let has_password = |pr: &SheetProtection| pr.password.is_some() || pr.legacy_password_hash.is_some();
|
||||
if s.doc()?.wb.sheet(sheet).and_then(|sh| sh.protection.as_ref()).is_some_and(has_password) {
|
||||
return Err(EngineError::Other("The sheet is protected with a password. Unprotect it first (Review › Unprotect Sheet).".into()));
|
||||
}
|
||||
let b = |k: &str| bool_param(p, k).unwrap_or(false);
|
||||
let prot = SheetProtection {
|
||||
password_hash: str_param(p, "password").filter(|x| !x.is_empty()).map(password_hash),
|
||||
password: None,
|
||||
legacy_password_hash: None,
|
||||
select_locked: true,
|
||||
select_unlocked: true,
|
||||
format_cells: b("formatCells"),
|
||||
@@ -40,6 +154,9 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
sort: b("sort"),
|
||||
autofilter: b("autofilter"),
|
||||
};
|
||||
let d = s.doc()?;
|
||||
let what = d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
|
||||
let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_password_hash(d, &what, pw)), ..prot };
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.protection = Some(prot.clone());
|
||||
Ok(Json::Null)
|
||||
@@ -48,11 +165,16 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn unprotect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let ph = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.protection.as_ref()).and_then(|pr| pr.password_hash);
|
||||
if let Some(h) = ph
|
||||
&& str_param(p, "password").map(password_hash) != Some(h)
|
||||
{
|
||||
return Err(EngineError::Other("The password you supplied is not correct.".into()));
|
||||
if let Some(pr) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.protection.as_ref()) {
|
||||
let pw = str_param(p, "password").unwrap_or("");
|
||||
let ok = match (&pr.password, pr.legacy_password_hash) {
|
||||
(Some(h), _) => h.verify(pw).map_err(EngineError::Other)?,
|
||||
(None, Some(h)) => password_hash(pw) == h,
|
||||
(None, None) => true,
|
||||
};
|
||||
if !ok {
|
||||
return Err(EngineError::Other("The password you supplied is not correct.".into()));
|
||||
}
|
||||
}
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.protection = None;
|
||||
@@ -60,11 +182,143 @@ fn unprotect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A new Excel-compatible (SHA-512, salted) hash of `pw`. The salt mixes `what` is protected
|
||||
/// with the document, a counter and the clock, so equal passwords get different hashes.
|
||||
fn new_password_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
|
||||
static SALT_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = SALT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let seed = format!("{what}\u{0}{n}\u{0}{}\u{0}{}", d.uid, gridcraft_calc::now_serial().to_bits());
|
||||
PasswordHash::new_sha512(pw, &gridcraft_model::password::salt_from(seed.as_bytes()))
|
||||
}
|
||||
|
||||
fn range_text(r: &EditRange) -> String {
|
||||
r.ranges.iter().map(|x| x.a1()).collect::<Vec<_>>().join(",")
|
||||
}
|
||||
|
||||
/// Review › Allow Edit Ranges: list, add, modify or delete the ranges that stay editable on a
|
||||
/// protected sheet, or unlock a password range for this session.
|
||||
fn allow_edit_ranges(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let action = str_param(p, "action").unwrap_or("list");
|
||||
let title = str_param(p, "title").map(str::trim).filter(|t| !t.is_empty());
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
let sheet_name = sh.name.clone();
|
||||
let find = |t: Option<&str>| -> Result<usize> {
|
||||
let t = t.ok_or_else(|| bad("review.allowEditRanges", "missing `title`"))?;
|
||||
sh.edit_ranges
|
||||
.iter()
|
||||
.position(|r| r.title.eq_ignore_ascii_case(t))
|
||||
.ok_or_else(|| bad("review.allowEditRanges", format!("no range titled `{t}`")))
|
||||
};
|
||||
let hash = |pw: &str, title: &str| new_password_hash(d, &format!("{sheet_name}\u{0}{title}"), pw);
|
||||
if matches!(action, "add" | "modify" | "delete") && sh.is_protected() {
|
||||
return Err(EngineError::Other("Unprotect the sheet to change its edit ranges.".into()));
|
||||
}
|
||||
match action {
|
||||
"list" => {}
|
||||
"unlock" => {
|
||||
let i = find(title)?;
|
||||
let Some(r) = sh.edit_ranges.get(i) else { return Err(bad("review.allowEditRanges", "no such range")) };
|
||||
if let Some(h) = &r.password {
|
||||
let pw = str_param(p, "password").unwrap_or("");
|
||||
if !h.verify(pw).map_err(EngineError::Other)? {
|
||||
return Err(EngineError::Other("The password you supplied is not correct.".into()));
|
||||
}
|
||||
let key = (sheet_name.clone(), r.title.clone());
|
||||
let d = s.doc_mut()?;
|
||||
if !d.unlocked_ranges.contains(&key) {
|
||||
d.unlocked_ranges.push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
"add" => {
|
||||
let t = match title {
|
||||
Some(t) => t.to_string(),
|
||||
None => {
|
||||
(1..).map(|n| format!("Range{n}")).find(|t| !sh.edit_ranges.iter().any(|r| r.title.eq_ignore_ascii_case(t))).unwrap_or_default()
|
||||
}
|
||||
};
|
||||
if sh.edit_ranges.iter().any(|r| r.title.eq_ignore_ascii_case(&t)) {
|
||||
return Err(bad("review.allowEditRanges", format!("a range titled `{t}` already exists")));
|
||||
}
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let password = str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| hash(pw, &t));
|
||||
let r = EditRange { title: t, ranges, password, security_descriptor: None };
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.edit_ranges.push(r.clone());
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
"modify" => {
|
||||
let i = find(title)?;
|
||||
let mut r = sh.edit_ranges.get(i).cloned().ok_or_else(|| bad("review.allowEditRanges", "no such range"))?;
|
||||
if let Some(n) = str_param(p, "newTitle").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
if sh.edit_ranges.iter().enumerate().any(|(j, x)| j != i && x.title.eq_ignore_ascii_case(n)) {
|
||||
return Err(bad("review.allowEditRanges", format!("a range titled `{n}` already exists")));
|
||||
}
|
||||
r.title = n.to_string();
|
||||
}
|
||||
if let Some(pw) = str_param(p, "password") {
|
||||
r.password = (!pw.is_empty()).then(|| hash(pw, &r.title));
|
||||
}
|
||||
if p.get("range").is_some() {
|
||||
r.ranges = target_ranges(s, p)?;
|
||||
}
|
||||
edit(s, |cx| {
|
||||
if let Some(x) = cx.sheet_mut(sheet)?.edit_ranges.get_mut(i) {
|
||||
*x = r.clone();
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
"delete" => {
|
||||
let i = find(title)?;
|
||||
edit(s, |cx| {
|
||||
let list = &mut cx.sheet_mut(sheet)?.edit_ranges;
|
||||
if i < list.len() {
|
||||
list.remove(i);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
other => return Err(bad("review.allowEditRanges", format!("unknown action `{other}`"))),
|
||||
}
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
Ok(Json::Array(
|
||||
sh.edit_ranges
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let unlocked = r.password.is_none() || d.unlocked_ranges.iter().any(|(s, t)| *s == sh.name && *t == r.title);
|
||||
json!({"title": r.title, "range": range_text(r), "password": r.password.is_some(), "unlocked": unlocked})
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Review › Protect Workbook: lock the workbook structure (sheets can't be added, moved,
|
||||
/// renamed, hidden or deleted), optionally with a password that unprotecting must match.
|
||||
fn protect_workbook(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let cur = s.doc()?.wb.protected_structure;
|
||||
let d = s.doc()?;
|
||||
let cur = d.wb.protected_structure;
|
||||
let on = bool_param(p, "on").unwrap_or(!cur);
|
||||
if on == cur {
|
||||
return Ok(json!({"on": on}));
|
||||
}
|
||||
let password = if on {
|
||||
str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_password_hash(d, "workbook", pw))
|
||||
} else {
|
||||
if let Some(h) = &d.wb.structure_password
|
||||
&& !h.verify(str_param(p, "password").unwrap_or("")).map_err(EngineError::Other)?
|
||||
{
|
||||
return Err(EngineError::Other("The password you supplied is not correct.".into()));
|
||||
}
|
||||
None
|
||||
};
|
||||
edit(s, |cx| {
|
||||
cx.wb.protected_structure = on;
|
||||
cx.wb.structure_password = password.clone();
|
||||
Ok(json!({"on": on}))
|
||||
})
|
||||
}
|
||||
@@ -97,3 +351,186 @@ fn accessibility(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
}
|
||||
Ok(Json::Array(issues))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn book() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
for (sheet, cell) in [(0, "C1"), (0, "A3"), (1, "B2")] {
|
||||
s.execute("review.newComment", json!({"sheet": sheet, "cell": cell, "text": "c", "author": "Ann"})).unwrap();
|
||||
}
|
||||
s.execute("review.newNote", json!({"sheet": 0, "cell": "A2", "text": "note", "author": "Bob"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn at(s: &Session) -> (usize, String) {
|
||||
let d = s.doc().unwrap();
|
||||
(d.wb.active_sheet, d.selection.active.a1())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_and_previous_comment_go_in_reading_order_across_sheets_and_wrap() {
|
||||
let mut s = book();
|
||||
s.execute("selection.set", json!({"cell": "B1"})).unwrap();
|
||||
// Notes are skipped: A2 holds a note, not a comment.
|
||||
let order = [(0, "C1"), (0, "A3"), (1, "B2"), (0, "C1")];
|
||||
for (sheet, cell) in order {
|
||||
s.execute("review.nextComment", json!({})).unwrap();
|
||||
assert_eq!(at(&s), (sheet, cell.to_string()));
|
||||
}
|
||||
for (sheet, cell) in [(1, "B2"), (0, "A3"), (0, "C1")] {
|
||||
s.execute("review.previousComment", json!({})).unwrap();
|
||||
assert_eq!(at(&s), (sheet, cell.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_navigation_is_disabled_without_comments() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("review.newNote", json!({"cell": "A1", "text": "note"})).unwrap();
|
||||
assert!(s.execute("review.nextComment", json!({})).is_err());
|
||||
assert!(s.execute("review.previousComment", json!({})).is_err());
|
||||
assert_eq!(at(&s), (0, "A1".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_passwords_use_excel_hashes_and_old_json_hashes_still_verify() {
|
||||
let mut s = book();
|
||||
s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap();
|
||||
let prot = s.doc().unwrap().wb.active().unwrap().protection.clone().unwrap();
|
||||
assert!(matches!(&prot.password, Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512"));
|
||||
assert!(s.execute("review.unprotectSheet", json!({})).is_err());
|
||||
assert!(s.execute("review.unprotectSheet", json!({"password": "pass"})).is_err());
|
||||
// Protecting again can't swap the password out from under it.
|
||||
assert!(s.execute("review.protectSheet", json!({})).is_err());
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().protection.as_ref(), Some(&prot));
|
||||
s.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap();
|
||||
assert!(!s.doc().unwrap().wb.active().unwrap().is_protected());
|
||||
// A GridCraft JSON workbook saved before carried the internal hash under `password_hash`.
|
||||
let old = format!(
|
||||
r#"{{"password_hash": {}, "select_locked": true, "select_unlocked": true, "format_cells": false, "format_columns": false, "format_rows": false, "insert_columns": false, "insert_rows": false, "delete_columns": false, "delete_rows": false, "sort": false, "autofilter": false}}"#,
|
||||
password_hash("old")
|
||||
);
|
||||
let prot: SheetProtection = serde_json::from_str(&old).unwrap();
|
||||
assert_eq!((prot.legacy_password_hash, prot.password.is_none()), (Some(password_hash("old")), true));
|
||||
let i = s.doc().unwrap().wb.active_sheet;
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[i]).protection = Some(prot);
|
||||
assert!(s.execute("review.unprotectSheet", json!({"password": "new"})).is_err());
|
||||
s.execute("review.unprotectSheet", json!({"password": "old"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protect_workbook_with_a_password_really_verifies() {
|
||||
let mut s = book();
|
||||
s.execute("review.protectWorkbook", json!({"password": "pa55"})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.protected_structure);
|
||||
assert!(s.execute("home.insertSheet", json!({"name": "Three"})).is_err(), "the structure is locked");
|
||||
// A second Protect keeps it protected; unprotecting needs the right password.
|
||||
assert_eq!(s.execute("review.protectWorkbook", json!({"on": true})).unwrap()["on"], true);
|
||||
assert!(s.execute("review.protectWorkbook", json!({})).is_err());
|
||||
assert!(s.execute("review.protectWorkbook", json!({"on": false, "password": "pass"})).is_err());
|
||||
assert!(s.doc().unwrap().wb.protected_structure);
|
||||
s.execute("review.protectWorkbook", json!({"on": false, "password": "pa55"})).unwrap();
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
assert!(!wb.protected_structure && wb.structure_password.is_none());
|
||||
// Without a password it toggles freely.
|
||||
s.execute("review.protectWorkbook", json!({})).unwrap();
|
||||
s.execute("review.protectWorkbook", json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().wb.protected_structure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_comments_turns_every_note_into_a_comment_and_undoes() {
|
||||
let mut s = book();
|
||||
s.execute("review.newNote", json!({"sheet": 1, "cell": "D4", "text": "second", "author": "Cy"})).unwrap();
|
||||
s.execute("review.showNote", json!({"sheet": 1, "cell": "D4"})).unwrap();
|
||||
let r = s.execute("review.convertToComments", json!({})).unwrap();
|
||||
assert_eq!(r["converted"], 2);
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let a2 = &wb.sheets[0].comments[&CellRef::parse("A2").unwrap()];
|
||||
let d4 = &wb.sheets[1].comments[&CellRef::parse("D4").unwrap()];
|
||||
assert!(a2.threaded && d4.threaded && !d4.visible);
|
||||
assert_eq!((a2.author.as_str(), a2.text.as_str(), d4.author.as_str(), d4.text.as_str()), ("Bob", "note", "Cy", "second"));
|
||||
// Nothing left to convert; one undo restores the notes.
|
||||
assert_eq!(s.execute("review.convertToComments", json!({})).unwrap()["converted"], 0);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().wb.sheets[0].comments[&CellRef::parse("A2").unwrap()].threaded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_comments_and_show_all_notes_toggle() {
|
||||
let mut s = book();
|
||||
assert_eq!(s.execute("review.showComments", json!({})).unwrap()["on"], true);
|
||||
assert_eq!(s.execute("review.showComments", json!({})).unwrap()["on"], false);
|
||||
assert_eq!(s.execute("review.showComments", json!({"on": true})).unwrap()["on"], true);
|
||||
assert!(s.comments_pane);
|
||||
assert_eq!(s.execute("review.showAllNotes", json!({})).unwrap()["on"], true);
|
||||
assert_eq!(s.execute("review.showAllNotes", json!({"on": false})).unwrap()["on"], false);
|
||||
assert!(!s.show_all_notes);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod edit_range_tests {
|
||||
use super::*;
|
||||
|
||||
fn protected_book() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("review.allowEditRanges", json!({"action": "add", "title": "Open", "range": "A1:A3"})).unwrap();
|
||||
s.execute("review.allowEditRanges", json!({"action": "add", "title": "Budget", "range": "B1:B3,D1", "password": "pa55"})).unwrap();
|
||||
s.execute("review.protectSheet", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_ranges_open_locked_cells_and_passwords_really_verify() {
|
||||
let mut s = protected_book();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "1"})).unwrap();
|
||||
assert!(s.execute("cell.set", json!({"cell": "C1", "input": "1"})).is_err());
|
||||
let err = s.execute("cell.set", json!({"cell": "D1", "input": "1"})).unwrap_err().to_string();
|
||||
assert!(err.contains("Budget"), "{err}");
|
||||
// A paste or fill is checked the same way.
|
||||
assert!(s.execute("range.setValues", json!({"range": "B2", "values": [[5]]})).is_err());
|
||||
assert!(s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "Budget", "password": "pass"})).is_err());
|
||||
assert!(s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "Budget"})).is_err());
|
||||
let list = s.execute("review.allowEditRanges", json!({"action": "unlock", "title": "budget", "password": "pa55"})).unwrap();
|
||||
assert_eq!(list[1]["unlocked"], true);
|
||||
s.execute("range.setValues", json!({"range": "B2", "values": [[5]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "2"})).unwrap();
|
||||
// Ranges can't change while the sheet is protected.
|
||||
assert!(s.execute("review.allowEditRanges", json!({"action": "delete", "title": "Open"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_ranges_add_modify_delete_list_and_undo() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
// Empty params list; nothing to list yet.
|
||||
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap(), json!([]));
|
||||
s.execute("selection.set", json!({"range": "C3:D4"})).unwrap();
|
||||
let list = s.execute("review.allowEditRanges", json!({"action": "add"})).unwrap();
|
||||
assert_eq!(list, json!([{"title": "Range1", "range": "C3:D4", "password": false, "unlocked": true}]));
|
||||
assert!(s.execute("review.allowEditRanges", json!({"action": "add", "title": "range1", "range": "A1"})).is_err());
|
||||
let list = s
|
||||
.execute("review.allowEditRanges", json!({"action": "modify", "title": "Range1", "newTitle": "Mine", "range": "E5", "password": "x"}))
|
||||
.unwrap();
|
||||
assert_eq!((list[0]["title"].as_str(), list[0]["range"].as_str(), list[0]["password"].as_bool()), (Some("Mine"), Some("E5"), Some(true)));
|
||||
// Inserting a row above moves the range with its cells.
|
||||
s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap();
|
||||
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap()[0]["range"], "E6");
|
||||
s.execute("review.allowEditRanges", json!({"action": "delete", "title": "Mine"})).unwrap();
|
||||
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap(), json!([]));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.execute("review.allowEditRanges", json!({})).unwrap()[0]["title"], "Mine");
|
||||
assert!(s.execute("review.allowEditRanges", json!({"action": "nope"})).is_err());
|
||||
assert!(s.execute("review.allowEditRanges", json!({"action": "delete"})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+395
-40
@@ -35,7 +35,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
p,
|
||||
Axis::Cols
|
||||
)),
|
||||
cmd!("sheet.moveColumns", "Move Columns", [], None, "{cols?: \"B:C\", before: zero-based column index}", has_doc, move_columns),
|
||||
cmd!("home.insertCells", "Insert Cells…", ["Home", "Cells", "Insert"], None, "{range?, shift: right|down|row|column}", has_doc, insert_cells),
|
||||
cmd!(
|
||||
"home.insertCopiedCells",
|
||||
"Insert Copied Cells",
|
||||
["Home", "Cells", "Insert"],
|
||||
None,
|
||||
"{at?: \"B3\", shift?: down|right}: inserts the copied cells at `at` (the active cell) and pastes them there. Whole copied rows or columns insert whole rows or columns; other blocks shift the cells at `at` down (default) or right. A cut of whole rows or columns moves them (Insert Cut Cells)",
|
||||
has_clipboard,
|
||||
insert_copied_cells
|
||||
),
|
||||
cmd!("home.deleteCells", "Delete Cells…", ["Home", "Cells", "Delete"], None, "{range?, shift: left|up|row|column}", has_doc, delete_cells),
|
||||
cmd!("home.insertSheet", "Insert Sheet", ["Home", "Cells", "Insert"], Some("Shift+F11"), "{name?, before?: index}", has_doc, insert_sheet),
|
||||
cmd!("home.deleteSheet", "Delete Sheet", ["Home", "Cells", "Delete"], None, "{sheet?}", has_doc, delete_sheet),
|
||||
@@ -146,6 +156,10 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
|
||||
for cf in sh.cond_formats.iter_mut() {
|
||||
cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r)).collect();
|
||||
}
|
||||
for er in sh.edit_ranges.iter_mut() {
|
||||
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r)).collect();
|
||||
}
|
||||
sh.edit_ranges.retain(|er| !er.ranges.is_empty());
|
||||
sh.cond_formats.retain(|cf| !cf.ranges.is_empty());
|
||||
for dv in sh.validations.iter_mut() {
|
||||
dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r)).collect();
|
||||
@@ -153,27 +167,8 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
|
||||
sh.validations.retain(|dv| !dv.ranges.is_empty());
|
||||
for t in sh.tables.iter_mut() {
|
||||
if let Some(r) = map_range(t.range) {
|
||||
// Columns inserted inside a table become new table columns.
|
||||
if axis == Axis::Cols && insert && at > t.range.start.col && at <= t.range.end.col {
|
||||
let idx = (at - t.range.start.col) as usize;
|
||||
for k in 0..count {
|
||||
let name = format!("Column{}", t.columns.len() + 1);
|
||||
t.columns.insert(
|
||||
(idx + k as usize).min(t.columns.len()),
|
||||
gridcraft_model::TableColumn { name, totals: Default::default(), totals_label: None, formula: None },
|
||||
);
|
||||
}
|
||||
}
|
||||
if axis == Axis::Cols && !insert {
|
||||
let lo = at.max(t.range.start.col);
|
||||
let hi = (at + count).min(t.range.end.col + 1);
|
||||
if hi > lo {
|
||||
let a = (lo - t.range.start.col) as usize;
|
||||
let b = (hi - t.range.start.col) as usize;
|
||||
if b <= t.columns.len() {
|
||||
t.columns.drain(a..b);
|
||||
}
|
||||
}
|
||||
if axis == Axis::Cols {
|
||||
shift_table_columns(t, at, count, insert);
|
||||
}
|
||||
t.range = r;
|
||||
} else {
|
||||
@@ -254,10 +249,14 @@ fn cancel_copy_mode(s: &mut Session) {
|
||||
|
||||
fn insert_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
|
||||
let (at, count) = lines(s, p, axis)?;
|
||||
let limit = if axis == Axis::Rows { MAX_ROWS } else { MAX_COLS };
|
||||
if at.checked_add(count).is_none_or(|end| end > limit) {
|
||||
let cmd = if axis == Axis::Rows { "home.insertRows" } else { "home.insertColumns" };
|
||||
return Err(bad(cmd, "the inserted lines would extend past the end of the worksheet"));
|
||||
}
|
||||
check_lines_protection(s, p, axis, at, count, true)?;
|
||||
let sheet = target_sheet(s, p)?;
|
||||
// Refuse to push data off the sheet.
|
||||
let limit = if axis == Axis::Rows { MAX_ROWS } else { MAX_COLS };
|
||||
if let Some(u) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range()) {
|
||||
let last = if axis == Axis::Rows { u.end.row } else { u.end.col };
|
||||
if last >= at && last as u64 + count as u64 >= limit as u64 {
|
||||
@@ -293,27 +292,65 @@ fn insert_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The areas a line delete/insert targets as `(first line, count)`, merged and sorted from the
|
||||
/// last line to the first so deleting one never shifts the next. A comma-separated list
|
||||
/// (`"3:3,7:8"`) or a multi-area selection yields several; `count` forces the single-area form.
|
||||
fn delete_areas(s: &Session, p: &Json, axis: Axis) -> Result<Vec<(u32, u32)>> {
|
||||
let key = if axis == Axis::Rows { "rows" } else { "cols" };
|
||||
let spans: Vec<(u32, u32)> = if u32_param(p, "count").is_some() {
|
||||
let (at, count) = lines(s, p, axis)?;
|
||||
let limit = if axis == Axis::Rows { MAX_ROWS } else { MAX_COLS };
|
||||
// Deleting past the last line only removes up to the end of the worksheet.
|
||||
let count = count.min(limit.saturating_sub(at)).max(1);
|
||||
vec![(at, at.saturating_add(count - 1))]
|
||||
} else if let Some(t) = str_param(p, key).or_else(|| str_param(p, "range")) {
|
||||
t.split(',')
|
||||
.map(|part| {
|
||||
let r = RangeRef::parse(part).ok_or_else(|| bad(key, format!("not a range: {part}")))?;
|
||||
Ok(if axis == Axis::Rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) })
|
||||
})
|
||||
.collect::<Result<_>>()?
|
||||
} else {
|
||||
s.doc()?.selection.ranges.iter().map(|r| if axis == Axis::Rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) }).collect()
|
||||
};
|
||||
let mut spans: Vec<(u32, u32)> = spans.into_iter().map(|(a, b)| (a.min(b), a.max(b))).collect();
|
||||
spans.sort_unstable();
|
||||
let mut merged: Vec<(u32, u32)> = Vec::new();
|
||||
for (a, b) in spans {
|
||||
match merged.last_mut() {
|
||||
Some(last) if a <= last.1.saturating_add(1) => last.1 = last.1.max(b),
|
||||
_ => merged.push((a, b)),
|
||||
}
|
||||
}
|
||||
Ok(merged.into_iter().rev().map(|(a, b)| (a, b - a + 1)).collect())
|
||||
}
|
||||
|
||||
fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
|
||||
let (at, count) = lines(s, p, axis)?;
|
||||
check_lines_protection(s, p, axis, at, count, false)?;
|
||||
let areas = delete_areas(s, p, axis)?;
|
||||
for &(at, count) in &areas {
|
||||
check_lines_protection(s, p, axis, at, count, false)?;
|
||||
}
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let out = edit(s, |cx| {
|
||||
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
|
||||
cx.protection_checked = true;
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let block = match axis {
|
||||
Axis::Rows => RangeRef::rows(at, (at + count - 1).min(MAX_ROWS - 1)),
|
||||
Axis::Cols => RangeRef::cols(at, (at + count - 1).min(MAX_COLS - 1)),
|
||||
};
|
||||
sh.take_cells(block);
|
||||
match axis {
|
||||
Axis::Rows => sh.cells.shift_rows(at + count, -(count as i64)),
|
||||
Axis::Cols => sh.cells.shift_cols(at + count, -(count as i64)),
|
||||
// Last area first, so the earlier ones keep their positions.
|
||||
for (at, count) in areas {
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let block = match axis {
|
||||
Axis::Rows => RangeRef::rows(at, (at + count - 1).min(MAX_ROWS - 1)),
|
||||
Axis::Cols => RangeRef::cols(at, (at + count - 1).min(MAX_COLS - 1)),
|
||||
};
|
||||
sh.take_cells(block);
|
||||
match axis {
|
||||
Axis::Rows => sh.cells.shift_rows(at + count, -(count as i64)),
|
||||
Axis::Cols => sh.cells.shift_cols(at + count, -(count as i64)),
|
||||
}
|
||||
shift_sheet_features(sh, axis, at, count, false);
|
||||
}
|
||||
shift_sheet_features(sh, axis, at, count, false);
|
||||
rewrite(&mut cx.wb, &name, &Edit::Delete { axis, at, count });
|
||||
}
|
||||
rewrite(&mut cx.wb, &name, &Edit::Delete { axis, at, count });
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})?;
|
||||
@@ -321,6 +358,105 @@ fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reorders a contiguous block of whole columns without replacing the destination columns.
|
||||
/// `before` is a boundary in the original sheet: moving B:C before E produces A,D,B,C,E.
|
||||
fn move_columns(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (from, count) = lines(s, p, Axis::Cols)?;
|
||||
let before = u32_param(p, "before").ok_or_else(|| bad("sheet.moveColumns", "missing `before`"))?;
|
||||
let end =
|
||||
from.checked_add(count).filter(|end| *end <= MAX_COLS).ok_or_else(|| bad("sheet.moveColumns", "source columns are outside the worksheet"))?;
|
||||
if before >= MAX_COLS || before.checked_add(count).is_none_or(|end| end > MAX_COLS) {
|
||||
return Err(bad("sheet.moveColumns", "destination columns are outside the worksheet"));
|
||||
}
|
||||
if (from..=end).contains(&before) {
|
||||
return Ok(json!({"cols": RangeRef::cols(from, end.saturating_sub(1)).a1()}));
|
||||
}
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if let Some(u) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range())
|
||||
&& u.end.col >= before
|
||||
&& u.end.col as u64 + count as u64 >= MAX_COLS as u64
|
||||
{
|
||||
return Err(EngineError::Other("To prevent possible loss of data, columns cannot be shifted off of the worksheet.".into()));
|
||||
}
|
||||
check_lines_protection(s, &json!({"cols": RangeRef::cols(before, before).a1()}), Axis::Cols, before, count, true)?;
|
||||
check_lines_protection(s, &json!({"cols": RangeRef::cols(from, end - 1).a1()}), Axis::Cols, from, count, false)?;
|
||||
|
||||
let moved_from = if before <= from { from + count } else { from };
|
||||
if moved_from.checked_add(count).is_none_or(|end| end > MAX_COLS) {
|
||||
return Err(bad("sheet.moveColumns", "the move is too close to the worksheet boundary"));
|
||||
}
|
||||
let destination = before;
|
||||
let delete_at = moved_from;
|
||||
let final_start = if before > from { before - count } else { before };
|
||||
let active_row = s.doc()?.selection.active.row;
|
||||
let source = RangeRef::cols(moved_from, moved_from + count - 1);
|
||||
let out = edit(s, |cx| {
|
||||
let name = cx.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
|
||||
cx.protection_checked = true;
|
||||
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
sh.cells.shift_cols(before, count as i64);
|
||||
shift_sheet_features(sh, Axis::Cols, before, count, true);
|
||||
}
|
||||
rewrite(&mut cx.wb, &name, &Edit::Insert { axis: Axis::Cols, at: before, count });
|
||||
|
||||
let mut touched = Vec::new();
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let pictures: Vec<_> =
|
||||
sh.cell_pictures.iter().filter(|(cell, _)| source.contains(**cell)).map(|(cell, picture)| (*cell, picture.clone())).collect();
|
||||
let cells = sh.take_cells(source);
|
||||
let moved_lines: Vec<_> = (0..count).filter_map(|offset| sh.cols.remove(&(moved_from + offset)).map(|info| (offset, info))).collect();
|
||||
let movement = Edit::Move { from: source, to_row: 0, to_col: destination };
|
||||
shift_cell_features(sh, &movement);
|
||||
for object in sh
|
||||
.charts
|
||||
.iter_mut()
|
||||
.map(|o| &mut o.anchor)
|
||||
.chain(sh.images.iter_mut().map(|o| &mut o.anchor))
|
||||
.chain(sh.shapes.iter_mut().map(|o| &mut o.anchor))
|
||||
{
|
||||
if object.mode != AnchorMode::Absolute && (moved_from..moved_from + count).contains(&object.cell.col) {
|
||||
object.cell.col = destination + (object.cell.col - moved_from);
|
||||
}
|
||||
}
|
||||
for (cell, value) in cells {
|
||||
let dest = CellRef::new(cell.row, destination + (cell.col - moved_from));
|
||||
sh.cells.set(dest, value);
|
||||
touched.extend([cell, dest]);
|
||||
}
|
||||
for (cell, picture) in pictures {
|
||||
let dest = CellRef::new(cell.row, destination + (cell.col - moved_from));
|
||||
sh.cell_pictures.insert(dest, picture);
|
||||
}
|
||||
for (offset, info) in moved_lines {
|
||||
sh.cols.insert(destination + offset, info);
|
||||
}
|
||||
}
|
||||
for cell in touched {
|
||||
cx.touch(sheet, cell);
|
||||
}
|
||||
rewrite(&mut cx.wb, &name, &Edit::Move { from: source, to_row: 0, to_col: destination });
|
||||
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
sh.cells.shift_cols(delete_at + count, -(count as i64));
|
||||
shift_sheet_features(sh, Axis::Cols, delete_at, count, false);
|
||||
}
|
||||
rewrite(&mut cx.wb, &name, &Edit::Delete { axis: Axis::Cols, at: delete_at, count });
|
||||
*cx.sel = crate::Selection {
|
||||
active: CellRef::new(active_row, final_start),
|
||||
anchor: CellRef::new(active_row, final_start),
|
||||
ranges: vec![RangeRef::cols(final_start, final_start + count - 1)],
|
||||
};
|
||||
cx.structural = true;
|
||||
Ok(json!({"cols": RangeRef::cols(final_start, final_start + count - 1).a1()}))
|
||||
})?;
|
||||
cancel_copy_mode(s);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn insert_cells(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let shift = str_param(p, "shift").unwrap_or("down");
|
||||
let r = target_range(s, p)?;
|
||||
@@ -331,6 +467,9 @@ fn insert_cells(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
let e = Edit::InsertCells { axis: if shift == "right" { Axis::Cols } else { Axis::Rows }, range: r };
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if let Some(sh) = s.doc()?.wb.sheet(sheet) {
|
||||
check_table_shift(sh, &e)?;
|
||||
}
|
||||
let right = shift == "right";
|
||||
let out = edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
@@ -359,6 +498,9 @@ fn delete_cells(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
let e = Edit::DeleteCells { axis: if shift == "left" { Axis::Cols } else { Axis::Rows }, range: r };
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if let Some(sh) = s.doc()?.wb.sheet(sheet) {
|
||||
check_table_shift(sh, &e)?;
|
||||
}
|
||||
let left = shift == "left";
|
||||
let out = edit(s, |cx| {
|
||||
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
|
||||
@@ -381,6 +523,125 @@ fn delete_cells(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Insert Copied Cells / Insert Cut Cells: makes room at the destination, then pastes (or, for a
|
||||
/// cut, moves) the clipboard there, as one undo step.
|
||||
fn insert_copied_cells(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let Some(clip) = s.clipboard.clone() else { return Err(EngineError::Other("Nothing to paste.".into())) };
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let at = cell_param_on(s, p, "at", sheet)?.unwrap_or(d.selection.current().start);
|
||||
let shift = str_param(p, "shift").unwrap_or("down");
|
||||
if shift != "down" && shift != "right" {
|
||||
return Err(bad("home.insertCopiedCells", format!("unknown `shift`: {shift} (down or right)")));
|
||||
}
|
||||
let sel = clip.selected;
|
||||
let rows = sel.is_full_rows();
|
||||
let cols = sel.is_full_cols();
|
||||
if rows && cols {
|
||||
return Err(EngineError::Other("The copy area is the whole sheet; there is no room to insert it.".into()));
|
||||
}
|
||||
let same_doc = d.uid == clip.doc_uid;
|
||||
let cut = clip.cut && same_doc;
|
||||
if cut && !rows && !cols {
|
||||
return Err(EngineError::Other("Insert Cut Cells works on whole rows or columns; cut whole rows or columns, or use Paste.".into()));
|
||||
}
|
||||
// A moved block can't be inserted inside itself.
|
||||
if cut && clip.sheet == sheet {
|
||||
let inside = if rows { at.row > sel.start.row && at.row <= sel.end.row } else { at.col > sel.start.col && at.col <= sel.end.col };
|
||||
if inside {
|
||||
return Err(EngineError::Other("The cut rows or columns can't be inserted inside themselves.".into()));
|
||||
}
|
||||
}
|
||||
let revision = d.revision;
|
||||
let before = (d.wb.clone(), d.selection.clone());
|
||||
let result = insert_copied_steps(s, &clip, sheet, at, shift, cut);
|
||||
let d = s.doc_mut()?;
|
||||
// The nested steps collapse into this command's single undo step.
|
||||
for _ in 0..d.revision.saturating_sub(revision) {
|
||||
d.undo.pop();
|
||||
}
|
||||
match result {
|
||||
Ok((final_range, out)) => {
|
||||
d.selection = crate::Selection { active: final_range.start, anchor: final_range.start, ranges: vec![final_range] };
|
||||
// Like inserting cells, this ends copy mode (the copied block may have moved).
|
||||
cancel_copy_mode(s);
|
||||
Ok(out)
|
||||
}
|
||||
Err(e) => {
|
||||
d.wb = before.0;
|
||||
d.selection = before.1;
|
||||
d.calc.rebuild(&d.wb);
|
||||
s.clipboard = Some(clip);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_copied_steps(s: &mut Session, clip: &crate::Clipboard, sheet: usize, at: CellRef, shift: &str, cut: bool) -> Result<(RangeRef, Json)> {
|
||||
let sel = clip.selected;
|
||||
let rows = sel.is_full_rows();
|
||||
let cols = sel.is_full_cols();
|
||||
// Where the copied block's top-left lands, relative to the (untrimmed) copied lines.
|
||||
let (inserted, paste_at) = if rows {
|
||||
let h = sel.height();
|
||||
let start = at.row;
|
||||
let r = format!("{}:{}", start as u64 + 1, start as u64 + h as u64);
|
||||
s.execute("home.insertRows", json!({"rows": r, "sheet": sheet}))?;
|
||||
let dr = clip.range.start.row.saturating_sub(sel.start.row);
|
||||
(RangeRef::rows(start, start.saturating_add(h - 1).min(MAX_ROWS - 1)), CellRef::new(start.saturating_add(dr), clip.range.start.col))
|
||||
} else if cols {
|
||||
let w = sel.width();
|
||||
let start = at.col;
|
||||
let end = start.saturating_add(w - 1).min(MAX_COLS - 1);
|
||||
s.execute("home.insertColumns", json!({"cols": RangeRef::cols(start, end).a1(), "sheet": sheet}))?;
|
||||
let dc = clip.range.start.col.saturating_sub(sel.start.col);
|
||||
(RangeRef::cols(start, end), CellRef::new(clip.range.start.row, start.saturating_add(dc)))
|
||||
} else {
|
||||
let end = at
|
||||
.offset(clip.range.height() as i64 - 1, clip.range.width() as i64 - 1)
|
||||
.ok_or_else(|| EngineError::Other("The copied cells don't fit on the sheet at this position.".into()))?;
|
||||
let block = RangeRef::new(at, end);
|
||||
s.execute("home.insertCells", json!({"range": block.a1(), "shift": shift, "sheet": sheet}))?;
|
||||
(block, at)
|
||||
};
|
||||
// Inserting ended copy mode; bring the clipboard back for the paste. A cut reads the live
|
||||
// workbook, so it follows the source if the insert pushed it along.
|
||||
let mut clip = clip.clone();
|
||||
if cut {
|
||||
let pushed = clip.sheet == sheet && if rows { sel.start.row >= at.row } else { sel.start.col >= at.col };
|
||||
if pushed {
|
||||
let (dr, dc) = if rows { (inserted.height() as i64, 0) } else { (0, inserted.width() as i64) };
|
||||
clip.range = RangeRef::new(clip.range.start.offset_clamped(dr, dc), clip.range.end.offset_clamped(dr, dc));
|
||||
clip.selected = RangeRef::new(sel.start.offset_clamped(dr, dc), sel.end.offset_clamped(dr, dc));
|
||||
}
|
||||
clip.wb = s.doc()?.wb.clone();
|
||||
}
|
||||
let source_lines = clip.selected;
|
||||
s.clipboard = Some(clip.clone());
|
||||
let out = s.execute("edit.pasteSpecial", json!({"what": "all", "at": paste_at.a1(), "sheet": sheet}))?;
|
||||
if !cut {
|
||||
return Ok((inserted, out));
|
||||
}
|
||||
// Close the gap the moved lines left behind.
|
||||
let (removed, before_dest) = if rows {
|
||||
s.execute(
|
||||
"home.deleteRows",
|
||||
json!({"rows": format!("{}:{}", source_lines.start.row as u64 + 1, source_lines.end.row as u64 + 1), "sheet": clip.sheet}),
|
||||
)?;
|
||||
(source_lines.height(), clip.sheet == sheet && source_lines.start.row < inserted.start.row)
|
||||
} else {
|
||||
s.execute("home.deleteColumns", json!({"cols": RangeRef::cols(source_lines.start.col, source_lines.end.col).a1(), "sheet": clip.sheet}))?;
|
||||
(source_lines.width(), clip.sheet == sheet && source_lines.start.col < inserted.start.col)
|
||||
};
|
||||
let moved = if before_dest {
|
||||
let (dr, dc) = if rows { (-(removed as i64), 0) } else { (0, -(removed as i64)) };
|
||||
RangeRef::new(inserted.start.offset_clamped(dr, dc), inserted.end.offset_clamped(dr, dc))
|
||||
} else {
|
||||
inserted
|
||||
};
|
||||
Ok((moved, out))
|
||||
}
|
||||
|
||||
fn insert_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if s.doc()?.wb.protected_structure {
|
||||
return Err(EngineError::Other("The workbook is protected and cannot be changed.".into()));
|
||||
@@ -538,6 +799,12 @@ fn rename_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
se.categories = se.categories.as_deref().map(fix);
|
||||
se.name = se.name.as_deref().map(fix);
|
||||
}
|
||||
// A PivotChart follows its PivotTable's sheet.
|
||||
if let Some((sheet, pivot)) = ch.pivot.as_deref().and_then(crate::pivot::parse_chart_link)
|
||||
&& sheet.eq_ignore_ascii_case(&old)
|
||||
{
|
||||
ch.pivot = Some(crate::pivot::chart_link(&name, &pivot));
|
||||
}
|
||||
}
|
||||
}
|
||||
for n in cx.wb.names.iter_mut() {
|
||||
@@ -560,9 +827,18 @@ fn move_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if copy {
|
||||
let mut sh = (*src).clone();
|
||||
let base = sh.name.clone();
|
||||
let name = (2..).map(|k| format!("{base} ({k})")).find(|nm| cx.wb.sheet_index(nm).is_none()).unwrap_or(base.clone());
|
||||
sh.name = name.chars().take(31).collect();
|
||||
// `Name (2)`: the name is shortened so the suffix fits in Excel's 31 characters.
|
||||
let name = (2..)
|
||||
.map(|k| {
|
||||
let suffix = format!(" ({k})");
|
||||
let keep = 31usize.saturating_sub(suffix.chars().count());
|
||||
format!("{}{suffix}", base.chars().take(keep).collect::<String>().trim_end())
|
||||
})
|
||||
.find(|nm| cx.wb.sheet_index(nm).is_none())
|
||||
.unwrap_or(base.clone());
|
||||
sh.name = name;
|
||||
sh.tables.clear(); // table names must be unique
|
||||
sh.preserved = None; // kept file content (form controls, OLE objects…) stays with the original
|
||||
let at = to.min(n);
|
||||
// The copy gets its own copies of the sheet's names, referring to the copy.
|
||||
let copies: Vec<gridcraft_model::DefinedName> = cx
|
||||
@@ -671,7 +947,7 @@ fn step_sheet(s: &mut Session, dir: i64) -> Result<Json> {
|
||||
}
|
||||
|
||||
/// Where a range of the edited sheet goes after a structural edit (`None` = deleted).
|
||||
fn map_range(r: RangeRef, e: &Edit) -> Option<RangeRef> {
|
||||
pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option<RangeRef> {
|
||||
let expr = gridcraft_formula::Expr::Ref(gridcraft_formula::Reference {
|
||||
sheet: gridcraft_formula::SheetSel::Current,
|
||||
kind: gridcraft_formula::RefKind::Range(
|
||||
@@ -693,15 +969,26 @@ fn shift_cell_features(sh: &mut Sheet, e: &Edit) {
|
||||
for cf in sh.cond_formats.iter_mut() {
|
||||
cf.ranges = cf.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
|
||||
}
|
||||
for er in sh.edit_ranges.iter_mut() {
|
||||
er.ranges = er.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
|
||||
}
|
||||
sh.edit_ranges.retain(|er| !er.ranges.is_empty());
|
||||
sh.cond_formats.retain(|cf| !cf.ranges.is_empty());
|
||||
for dv in sh.validations.iter_mut() {
|
||||
dv.ranges = dv.ranges.iter().filter_map(|r| map_range(*r, e)).collect();
|
||||
}
|
||||
sh.validations.retain(|dv| !dv.ranges.is_empty());
|
||||
for t in sh.tables.iter_mut() {
|
||||
// Cells inserted or deleted across a table's full height add or remove table columns.
|
||||
if let Edit::InsertCells { axis: Axis::Cols, range } | Edit::DeleteCells { axis: Axis::Cols, range } = *e
|
||||
&& range.start.row <= t.range.start.row
|
||||
&& range.end.row >= t.range.end.row
|
||||
{
|
||||
shift_table_columns(t, range.start.col, range.width(), matches!(e, Edit::InsertCells { .. }));
|
||||
}
|
||||
t.range = map_range(t.range, e).unwrap_or_default();
|
||||
}
|
||||
sh.tables.retain(|t| t.range != RangeRef::default());
|
||||
sh.tables.retain(|t| t.range != RangeRef::default() && !t.columns.is_empty());
|
||||
if let Some(af) = sh.autofilter.as_mut() {
|
||||
match map_range(af.range, e) {
|
||||
Some(r) => af.range = r,
|
||||
@@ -721,3 +1008,71 @@ fn shift_cell_features(sh: &mut Sheet, e: &Edit) {
|
||||
sh.print.print_area = map_range(pa, e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Columns inserted inside a table become new table columns (with names no other column has);
|
||||
/// deleted ones leave it.
|
||||
fn shift_table_columns(t: &mut gridcraft_model::Table, at: u32, count: u32, insert: bool) {
|
||||
if insert {
|
||||
if at > t.range.start.col && at <= t.range.end.col {
|
||||
let idx = (at - t.range.start.col) as usize;
|
||||
let mut n = t.columns.len();
|
||||
for k in 0..count as usize {
|
||||
let name = loop {
|
||||
n += 1;
|
||||
let name = format!("Column{n}");
|
||||
if !t.columns.iter().any(|c| c.name.eq_ignore_ascii_case(&name)) {
|
||||
break name;
|
||||
}
|
||||
};
|
||||
let col = gridcraft_model::TableColumn {
|
||||
name,
|
||||
totals: Default::default(),
|
||||
totals_label: None,
|
||||
formula: None,
|
||||
unique_name: None,
|
||||
xml: None,
|
||||
};
|
||||
t.columns.insert((idx + k).min(t.columns.len()), col);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let lo = at.max(t.range.start.col);
|
||||
let hi = at.saturating_add(count).min(t.range.end.col + 1);
|
||||
if hi > lo {
|
||||
let a = (lo - t.range.start.col) as usize;
|
||||
let b = (hi - t.range.start.col) as usize;
|
||||
if b <= t.columns.len() {
|
||||
t.columns.drain(a..b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Like Excel, Insert/Delete Cells never shifts part of a table: cells shifted up or down must
|
||||
/// hold whole table columns, cells shifted left or right whole table rows, and deleting cells
|
||||
/// never takes a table's header row without the whole table.
|
||||
pub(crate) fn check_table_shift(sh: &Sheet, e: &Edit) -> Result<()> {
|
||||
let (axis, r, delete) = match *e {
|
||||
Edit::InsertCells { axis, range } => (axis, range, false),
|
||||
Edit::DeleteCells { axis, range } => (axis, range, true),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
for t in &sh.tables {
|
||||
let tr = t.range;
|
||||
let ok = match axis {
|
||||
Axis::Rows => {
|
||||
let moves = tr.end.row >= r.start.row && tr.start.col <= r.end.col && tr.end.col >= r.start.col;
|
||||
let header_alone = delete && t.header_row && r.start.row <= tr.start.row && r.end.row >= tr.start.row && r.end.row < tr.end.row;
|
||||
!moves || (r.start.col <= tr.start.col && r.end.col >= tr.end.col && !header_alone)
|
||||
}
|
||||
Axis::Cols => {
|
||||
let moves = tr.end.col >= r.start.col && tr.start.row <= r.end.row && tr.end.row >= r.start.row;
|
||||
!moves || (r.start.row <= tr.start.row && r.end.row >= tr.end.row)
|
||||
}
|
||||
};
|
||||
if !ok {
|
||||
return Err(EngineError::Other("This operation isn't allowed: it would shift cells in a table on your worksheet.".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Slicers: on-sheet widgets that filter one column of a table by clicking value tiles.
|
||||
//!
|
||||
//! A slicer is a thin front-end over the existing filter machinery: its selection is written as a
|
||||
//! [`FilterCriterion::Values`] into the sheet's [`AutoFilter`] (over the table's range) and
|
||||
//! [`super::data::apply_filter`] hides the rows. Creating a slicer (`insert.slicer` /
|
||||
//! `table.insertSlicer`) selects everything, i.e. applies no filter.
|
||||
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_model::*;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::*;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"insert.slicer",
|
||||
"Slicer",
|
||||
["Insert", "Filters"],
|
||||
None,
|
||||
"{table?, column?: \"Region\", columns?: 1, at?: \"H2\", width?, height?}",
|
||||
has_doc,
|
||||
insert_slicer
|
||||
),
|
||||
cmd!(
|
||||
"table.insertSlicer",
|
||||
"Insert Slicer",
|
||||
["Table", "Tools"],
|
||||
None,
|
||||
"{table?, column?: \"Region\", columns?: 1, at?, width?, height?}",
|
||||
has_doc,
|
||||
insert_slicer
|
||||
),
|
||||
cmd!("slicer.toggle", "Toggle Slicer Value", [], None, "{slicer?: id, value: \"East\", multi?: false}", has_doc, slicer_toggle),
|
||||
cmd!("slicer.selectAll", "Clear Slicer Filter", [], None, "{slicer?: id}", has_doc, slicer_select_all),
|
||||
cmd!("slicer.clear", "Clear Slicer Filter", [], None, "{slicer?: id}", has_doc, slicer_select_all),
|
||||
cmd!("slicer.delete", "Delete Slicer", [], None, "{slicer?: id}", has_doc, slicer_delete),
|
||||
]
|
||||
}
|
||||
|
||||
/// Distinct, non-blank display values of a table column, in first-seen order. Used to populate a
|
||||
/// slicer's tiles and to detect "everything selected".
|
||||
pub fn column_values(wb: &Workbook, sheet: usize, table: &str, column: &str) -> Vec<String> {
|
||||
let Some(sh) = wb.sheet(sheet) else { return vec![] };
|
||||
let Some(t) = sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(table)) else { return vec![] };
|
||||
let Some(ci) = t.column_index(column) else { return vec![] };
|
||||
let Some(dr) = t.data_range() else { return vec![] };
|
||||
let col = dr.start.col + ci as u32;
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for row in dr.start.row..=dr.end.row {
|
||||
let text = crate::display::cell_text(wb, sh, CellRef::new(row, col));
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(text.to_lowercase()) {
|
||||
out.push(text);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A slicer's tiles as `(value, selected)`, for the UI. `selected` is true for every tile when the
|
||||
/// slicer has no filter (`selected == None`).
|
||||
pub fn slicer_items(wb: &Workbook, sheet: usize, sl: &Slicer) -> Vec<(String, bool)> {
|
||||
column_values(wb, sheet, &sl.table, &sl.column)
|
||||
.into_iter()
|
||||
.map(|v| {
|
||||
let on = match &sl.selected {
|
||||
None => true,
|
||||
Some(set) => set.iter().any(|x| x.eq_ignore_ascii_case(&v)),
|
||||
};
|
||||
(v, on)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Writes the slicer's current selection into the sheet filter and re-applies it.
|
||||
fn reapply_slicer(wb: &mut Workbook, sheet: usize, id: u32) {
|
||||
let info = wb.sheet(sheet).and_then(|sh| {
|
||||
let sl = sh.slicers.iter().find(|s| s.id == id)?;
|
||||
let t = sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(&sl.table))?;
|
||||
let ci = t.column_index(&sl.column)?;
|
||||
Some((t.range, t.range.start.col + ci as u32, sl.selected.clone()))
|
||||
});
|
||||
let Some((table_range, abs_col, selected)) = info else { return };
|
||||
{
|
||||
let Some(sh) = wb.sheet_mut(sheet) else { return };
|
||||
let af = sh.autofilter.get_or_insert_with(|| AutoFilter { range: table_range, criteria: vec![] });
|
||||
let off = abs_col.saturating_sub(af.range.start.col);
|
||||
af.criteria.retain(|(o, _)| *o != off);
|
||||
if let Some(values) = selected {
|
||||
af.criteria.push((off, FilterCriterion::Values { values, blanks: false }));
|
||||
}
|
||||
}
|
||||
super::data::apply_filter(wb, sheet);
|
||||
}
|
||||
|
||||
fn insert_slicer(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
let t = match str_param(p, "table") {
|
||||
Some(name) => sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(name)),
|
||||
None => sh.table_at(d.selection.active),
|
||||
}
|
||||
.ok_or_else(|| EngineError::Other("Select a cell inside a table first, or pass `table`.".into()))?;
|
||||
let column = match str_param(p, "column") {
|
||||
Some(c) => t
|
||||
.columns
|
||||
.iter()
|
||||
.find(|tc| tc.name.eq_ignore_ascii_case(c))
|
||||
.map(|tc| tc.name.clone())
|
||||
.ok_or_else(|| bad("insert.slicer", format!("table has no column `{c}`")))?,
|
||||
None => {
|
||||
// Default to the active cell's column within the table, else the first column.
|
||||
let idx = d.selection.active.col.checked_sub(t.range.start.col).map(|o| o as usize).filter(|o| *o < t.columns.len()).unwrap_or(0);
|
||||
t.columns.get(idx).map(|tc| tc.name.clone()).ok_or_else(|| bad("insert.slicer", "the table has no columns"))?
|
||||
}
|
||||
};
|
||||
let table = t.name.clone();
|
||||
let at = cell_param(s, p, "at")?
|
||||
.unwrap_or_else(|| CellRef::new(t.range.start.row, t.range.end.col.saturating_add(2).min(gridcraft_core::MAX_COLS - 1)));
|
||||
let columns = u32_param(p, "columns").unwrap_or(1).clamp(1, 10);
|
||||
let width = f64_param(p, "width").unwrap_or(168.0).clamp(60.0, 10000.0) as f32;
|
||||
let height = f64_param(p, "height").unwrap_or(200.0).clamp(60.0, 10000.0) as f32;
|
||||
let id = d.wb.next_object_id();
|
||||
let slicer = Slicer {
|
||||
id,
|
||||
table,
|
||||
column: column.clone(),
|
||||
caption: column,
|
||||
anchor: Anchor { cell: at, dx: 4.0, dy: 4.0, width, height, mode: AnchorMode::MoveOnly },
|
||||
selected: None,
|
||||
columns,
|
||||
};
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.slicers.push(slicer);
|
||||
Ok(json!({"slicer": id}))
|
||||
})
|
||||
}
|
||||
|
||||
/// The target slicer: by `slicer` id, else the last one on the active sheet.
|
||||
fn find_slicer(s: &Session, p: &Json) -> Result<(usize, u32)> {
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let idx = match u32_param(p, "slicer") {
|
||||
Some(id) => sh.slicers.iter().position(|x| x.id == id),
|
||||
None => sh.slicers.len().checked_sub(1),
|
||||
};
|
||||
idx.and_then(|i| sh.slicers.get(i).map(|x| (i, x.id))).ok_or_else(|| bad("slicer", "no slicer on this sheet"))
|
||||
}
|
||||
|
||||
fn slicer_toggle(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (idx, id) = find_slicer(s, p)?;
|
||||
let value = str_param(p, "value").ok_or_else(|| bad("slicer.toggle", "missing `value`"))?.to_string();
|
||||
let multi = bool_param(p, "multi").unwrap_or(false);
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
let (table, column, current) = {
|
||||
let d = s.doc()?;
|
||||
let sl = d.wb.active().and_then(|sh| sh.slicers.get(idx)).ok_or_else(|| bad("slicer.toggle", "no slicer"))?;
|
||||
(sl.table.clone(), sl.column.clone(), sl.selected.clone())
|
||||
};
|
||||
let all = column_values(&s.doc()?.wb, sheet, &table, &column);
|
||||
if !all.iter().any(|v| v.eq_ignore_ascii_case(&value)) {
|
||||
return Err(bad("slicer.toggle", "value is not in the column"));
|
||||
}
|
||||
let new_selected: Option<Vec<String>> = if multi {
|
||||
let mut set: Vec<String> = current.unwrap_or_else(|| all.clone());
|
||||
match set.iter().position(|x| x.eq_ignore_ascii_case(&value)) {
|
||||
Some(pos) => {
|
||||
set.remove(pos);
|
||||
}
|
||||
None => set.push(value.clone()),
|
||||
}
|
||||
// Everything selected is the same as no filter.
|
||||
if set.len() == all.len() && all.iter().all(|a| set.iter().any(|x| x.eq_ignore_ascii_case(a))) { None } else { Some(set) }
|
||||
} else {
|
||||
// Single click: show only this value; clicking the sole selected value clears the filter.
|
||||
match ¤t {
|
||||
Some(set) if set.len() == 1 && set.iter().any(|x| x.eq_ignore_ascii_case(&value)) => None,
|
||||
_ => Some(vec![value.clone()]),
|
||||
}
|
||||
};
|
||||
edit(s, |cx| {
|
||||
if let Some(sl) = cx.sheet_mut(sheet)?.slicers.get_mut(idx) {
|
||||
sl.selected = new_selected;
|
||||
}
|
||||
reapply_slicer(&mut cx.wb, sheet, id);
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn slicer_select_all(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (idx, id) = find_slicer(s, p)?;
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
if let Some(sl) = cx.sheet_mut(sheet)?.slicers.get_mut(idx) {
|
||||
sl.selected = None;
|
||||
}
|
||||
reapply_slicer(&mut cx.wb, sheet, id);
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn slicer_delete(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (idx, id) = find_slicer(s, p)?;
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
// Absolute column of the slicer, so its filter criterion can be removed too.
|
||||
let abs_col = s.doc().ok().and_then(|d| {
|
||||
let sh = d.wb.active()?;
|
||||
let sl = sh.slicers.get(idx)?;
|
||||
let t = sh.tables.iter().find(|t| t.name.eq_ignore_ascii_case(&sl.table))?;
|
||||
let ci = t.column_index(&sl.column)?;
|
||||
Some(t.range.start.col + ci as u32)
|
||||
});
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
sh.slicers.retain(|x| x.id != id);
|
||||
if let (Some(abs), Some(af)) = (abs_col, sh.autofilter.as_mut()) {
|
||||
let off = abs.saturating_sub(af.range.start.col);
|
||||
af.criteria.retain(|(o, _)| *o != off);
|
||||
}
|
||||
super::data::apply_filter(&mut cx.wb, sheet);
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -21,17 +21,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn dictionary() -> &'static HashSet<String> {
|
||||
static DICT: OnceLock<HashSet<String>> = OnceLock::new();
|
||||
DICT.get_or_init(|| {
|
||||
let mut set = HashSet::new();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
HashSet::new()
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
for path in ["/usr/share/dict/words", "/usr/share/dict/american-english", "/usr/share/dict/british-english"] {
|
||||
if let Ok(text) = std::fs::read_to_string(path) {
|
||||
for w in text.lines().take(2_000_000) {
|
||||
set.insert(w.trim().to_lowercase());
|
||||
{
|
||||
let mut set = HashSet::new();
|
||||
for path in ["/usr/share/dict/words", "/usr/share/dict/american-english", "/usr/share/dict/british-english"] {
|
||||
if let Ok(text) = std::fs::read_to_string(path) {
|
||||
for w in text.lines().take(2_000_000) {
|
||||
set.insert(w.trim().to_lowercase());
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
set
|
||||
}
|
||||
set
|
||||
})
|
||||
}
|
||||
|
||||
@@ -58,7 +64,14 @@ fn known(s: &Session, w: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Longest word we generate suggestions for. Candidate text grows with the square of the word length, so longer
|
||||
/// tokens (no real word is this long) get no suggestions instead of an unbounded allocation.
|
||||
const MAX_SUGGEST_LEN: usize = 64;
|
||||
|
||||
fn edits1(w: &str) -> Vec<String> {
|
||||
if w.chars().count() > MAX_SUGGEST_LEN {
|
||||
return Vec::new();
|
||||
}
|
||||
let chars: Vec<char> = w.chars().collect();
|
||||
let mut out = Vec::new();
|
||||
let letters = "abcdefghijklmnopqrstuvwxyz";
|
||||
@@ -155,7 +168,7 @@ fn change(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if bool_param(p, "all").unwrap_or(false) {
|
||||
return s.execute("edit.replace", json!({"what": word, "with": to, "matchCase": true, "all": true}));
|
||||
}
|
||||
let c = cell_param(p, "cell").ok_or_else(|| bad("review.changeSpelling", "missing `cell`"))?;
|
||||
let c = cell_param(s, p, "cell")?.ok_or_else(|| bad("review.changeSpelling", "missing `cell`"))?;
|
||||
let text = s.doc()?.wb.active().and_then(|sh| sh.cell(c)).map(|x| x.input_text()).unwrap_or_default();
|
||||
s.execute("cell.set", json!({"cell": c.a1(), "input": text.replacen(&word, &to, 1)}))
|
||||
}
|
||||
@@ -171,3 +184,16 @@ fn thesaurus(_: &mut Session, p: &Json) -> Result<Json> {
|
||||
related.truncate(20);
|
||||
Ok(json!(related))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn edits1_is_capped_for_very_long_words() {
|
||||
assert_eq!(edits1("helo").len(), 54 * 4 + 25);
|
||||
assert_eq!(edits1(&"a".repeat(MAX_SUGGEST_LEN)).len(), 54 * MAX_SUGGEST_LEN + 25);
|
||||
assert!(edits1(&"a".repeat(MAX_SUGGEST_LEN + 1)).is_empty());
|
||||
assert!(edits1(&"a".repeat(1_000_000)).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("view.showZeros", "Show Zeros", [], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "zeros")),
|
||||
cmd!("view.rightToLeft", "Sheet Right-to-Left", ["Page Layout", "Sheet Options"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "rtl")),
|
||||
cmd!("view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom),
|
||||
cmd!("view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))),
|
||||
cmd!(query "view.formulaBar", "Formula Bar", ["View", "Show"], None, "{on?: bool}", always, |s, p| {
|
||||
s.prefs.formula_bar = bool_param(p, "on").unwrap_or(!s.prefs.formula_bar);
|
||||
Ok(json!({"on": s.prefs.formula_bar}))
|
||||
}),
|
||||
cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection),
|
||||
cmd!("pageLayout.orientation", "Orientation", ["Page Layout", "Page Setup"], None, "{orientation: portrait|landscape}", has_doc, orientation),
|
||||
cmd!("pageLayout.size", "Size", ["Page Layout", "Page Setup"], None, "{paper: Letter|Legal|A4|A3|A5|Tabloid|Executive}", has_doc, paper),
|
||||
@@ -91,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Header & Footer",
|
||||
["Insert", "Text"],
|
||||
None,
|
||||
"{header?: \"&C&P\", footer?: \"&CPage &P of &N\"}",
|
||||
"{sheet?, header?: \"&C&P\", footer?: \"&CPage &P of &N\", differentFirst?: bool, differentOddEven?: bool, firstHeader?, firstFooter?, evenHeader?, evenFooter?} or one section: {sheet?, page?: odd|even|first, part: header|footer, section: left|center|right, text: \"Page &[Page] of &[Pages]\"} (field names or codes) → {header, footer, differentFirst, differentOddEven, firstHeader, firstFooter, evenHeader, evenFooter}",
|
||||
has_doc,
|
||||
header_footer
|
||||
),
|
||||
@@ -113,7 +118,7 @@ fn freeze_panes(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if sh.freeze.is_some() && p.get("cell").is_none() {
|
||||
return set_freeze(s, None);
|
||||
}
|
||||
let at = cell_param(p, "cell").unwrap_or(d.selection.active);
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let top = sh.view_top_left;
|
||||
let rows = at.row.saturating_sub(top.row);
|
||||
let cols = at.col.saturating_sub(top.col);
|
||||
@@ -254,7 +259,7 @@ fn scale_fit(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn breaks(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let at = cell_param(p, "cell").unwrap_or(s.doc()?.selection.active);
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(s.doc()?.selection.active);
|
||||
let insert = bool_param(p, "insert").unwrap_or(false);
|
||||
let remove = bool_param(p, "remove").unwrap_or(false);
|
||||
let reset = bool_param(p, "reset").unwrap_or(false);
|
||||
@@ -281,17 +286,77 @@ fn breaks(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Excel keeps at most 255 characters per header or footer.
|
||||
const MAX_HEADER_FOOTER: usize = 255;
|
||||
|
||||
fn header_footer(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
const CMD: &str = "pageLayout.headerFooter";
|
||||
let si = target_sheet(s, p)?;
|
||||
let cap = |t: &str| t.chars().take(MAX_HEADER_FOOTER).collect::<String>();
|
||||
// One section edited in place (Page Layout view).
|
||||
let section = match (str_param(p, "part"), str_param(p, "section")) {
|
||||
(None, None) => None,
|
||||
(part, sec) => {
|
||||
let footer = match part.unwrap_or("header") {
|
||||
"header" => false,
|
||||
"footer" => true,
|
||||
other => return Err(bad(CMD, format!("`part` must be header or footer, not `{other}`"))),
|
||||
};
|
||||
let idx = match sec.unwrap_or("center") {
|
||||
"left" => 0usize,
|
||||
"center" | "centre" => 1,
|
||||
"right" => 2,
|
||||
other => return Err(bad(CMD, format!("`section` must be left, center or right, not `{other}`"))),
|
||||
};
|
||||
let page = match str_param(p, "page") {
|
||||
None => gridcraft_model::HfPage::Odd,
|
||||
Some(id) => gridcraft_model::HfPage::parse(id).ok_or_else(|| bad(CMD, format!("`page` must be odd, even or first, not `{id}`")))?,
|
||||
};
|
||||
Some((page, footer, idx, super::print::fields_to_codes(str_param(p, "text").unwrap_or(""))))
|
||||
}
|
||||
};
|
||||
edit(s, |cx| {
|
||||
let si = cx.sheet_index();
|
||||
let pr = &mut cx.sheet_mut(si)?.print;
|
||||
if let Some(h) = str_param(p, "header") {
|
||||
pr.header = h.to_string();
|
||||
pr.header = cap(h);
|
||||
}
|
||||
if let Some(f) = str_param(p, "footer") {
|
||||
pr.footer = f.to_string();
|
||||
pr.footer = cap(f);
|
||||
}
|
||||
Ok(Json::Null)
|
||||
for (key, slot) in [
|
||||
("firstHeader", &mut pr.first_header),
|
||||
("firstFooter", &mut pr.first_footer),
|
||||
("evenHeader", &mut pr.even_header),
|
||||
("evenFooter", &mut pr.even_footer),
|
||||
] {
|
||||
if let Some(t) = str_param(p, key) {
|
||||
*slot = cap(t);
|
||||
}
|
||||
}
|
||||
if let Some(on) = bool_param(p, "differentFirst") {
|
||||
pr.different_first = on;
|
||||
}
|
||||
if let Some(on) = bool_param(p, "differentOddEven") {
|
||||
pr.different_odd_even = on;
|
||||
}
|
||||
if let Some((page, footer, idx, text)) = §ion {
|
||||
let spec = pr.hf_mut(*page, *footer);
|
||||
let mut parts = super::print::split_header_footer(spec);
|
||||
if let Some(slot) = parts.get_mut(*idx) {
|
||||
*slot = text.clone();
|
||||
}
|
||||
*spec = cap(&super::print::join_header_footer(&parts));
|
||||
}
|
||||
Ok(json!({
|
||||
"header": pr.header,
|
||||
"footer": pr.footer,
|
||||
"differentFirst": pr.different_first,
|
||||
"differentOddEven": pr.different_odd_even,
|
||||
"firstHeader": pr.first_header,
|
||||
"firstFooter": pr.first_footer,
|
||||
"evenHeader": pr.even_header,
|
||||
"evenFooter": pr.even_footer,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -336,3 +401,28 @@ fn theme(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn unused(_: CellRef) {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zoom_100_resets_the_active_sheet_zoom() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("view.zoom", json!({"percent": 150})).unwrap();
|
||||
assert_eq!(s.execute("view.zoom100", json!({})).unwrap()["zoom"], 100);
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().zoom, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.prefs.formula_bar);
|
||||
assert_eq!(s.execute("view.formulaBar", json!({})).unwrap()["on"], false);
|
||||
assert_eq!(s.execute("view.formulaBar", json!({"on": true})).unwrap()["on"], true);
|
||||
// A prefs.json saved before the option existed keeps the formula bar shown.
|
||||
let old: crate::Prefs = serde_json::from_str(r#"{"userName": "Ann"}"#).unwrap();
|
||||
assert!(old.formula_bar);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ fn cell_arg(s: &Session, p: &Json, key: &str, cmd: &str) -> Result<(usize, CellR
|
||||
|
||||
/// A range text (`"A1:C9"`, `"Sheet2!A:C"`) resolved against the workbook. Whole rows/columns
|
||||
/// are trimmed to the used range.
|
||||
fn parse_range(wb: &Workbook, t: &str, cmd: &str) -> Result<(usize, RangeRef)> {
|
||||
pub(crate) fn parse_range(wb: &Workbook, t: &str, cmd: &str) -> Result<(usize, RangeRef)> {
|
||||
let (sh, body) = split_sheet(t);
|
||||
let si = sheet_named(wb, sh, wb.active_sheet, cmd)?;
|
||||
let r = RangeRef::parse(body.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{t}`")))?;
|
||||
|
||||
@@ -10,11 +10,13 @@ use gridcraft_numfmt::{Formatted, NumberFormat, format_value};
|
||||
/// Parsed number formats are cached by code.
|
||||
fn parsed(code: &str) -> NumberFormat {
|
||||
static CACHE: std::sync::LazyLock<Mutex<HashMap<String, NumberFormat>>> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
let mut m = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(f) = m.get(code) {
|
||||
let lock = || CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(f) = lock().get(code) {
|
||||
return f.clone();
|
||||
}
|
||||
// Parse outside the lock, so a slow code never blocks the other threads' lookups.
|
||||
let f = NumberFormat::parse(code);
|
||||
let mut m = lock();
|
||||
if m.len() > 4096 {
|
||||
m.clear();
|
||||
}
|
||||
@@ -31,6 +33,37 @@ pub fn format(v: &Value, code: &str, wb: &Workbook) -> Formatted {
|
||||
format_value(v, &parsed(code), wb.date_system)
|
||||
}
|
||||
|
||||
/// What the cell editor and the formula bar start from. Same as `Cell::input_text`, except that a
|
||||
/// constant number in a date or time format is shown as a date (as the grid shows it), not as its
|
||||
/// serial. When the formatted text would not read back as the same date (for example
|
||||
/// `dddd, mmmm d`), an ISO `yyyy-mm-dd` (with `hh:mm:ss` for a time of day; just `hh:mm:ss`
|
||||
/// for a time alone) is used instead, and if even that would not read back, the serial.
|
||||
pub fn edit_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
let raw = sheet.input_text(c);
|
||||
let Some(cell) = sheet.cell(c) else { return raw };
|
||||
let Value::Number(n) = &cell.value else { return raw };
|
||||
let code = wb.styles.get(cell.style).num_fmt.as_str();
|
||||
if cell.formula.is_some() || !parsed(code).is_date() {
|
||||
return raw;
|
||||
}
|
||||
let reads_back = |s: &str| matches!(gridcraft_core::parse::parse_input(s, wb.date_system).value, Value::Number(m) if (m - n).abs() < 1e-9);
|
||||
let shown = format(&cell.value, code, wb).text;
|
||||
if reads_back(&shown) {
|
||||
return shown;
|
||||
}
|
||||
let Some(dt) = gridcraft_core::date::datetime_from_serial(wb.date_system, *n) else { return raw };
|
||||
let time = format!("{:02}:{:02}:{:02}", dt.hour, dt.minute, dt.second);
|
||||
let date = format!("{:04}-{:02}-{:02}", dt.year, dt.month, dt.day);
|
||||
let iso = if *n < 1.0 {
|
||||
time
|
||||
} else if n.fract() == 0.0 {
|
||||
date
|
||||
} else {
|
||||
format!("{date} {time}")
|
||||
};
|
||||
if reads_back(&iso) { iso } else { raw }
|
||||
}
|
||||
|
||||
/// Whether `c` has a formula that must not be shown: its cell is formatted Hidden on a
|
||||
/// protected sheet. A spilled cell follows its anchor.
|
||||
pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool {
|
||||
@@ -49,15 +82,20 @@ pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool {
|
||||
|
||||
/// The text a cell shows (full precision General; the grid narrows General to fit the column).
|
||||
pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
let v = sheet.value(c);
|
||||
if sheet.show_formulas
|
||||
&& let Some(f) = sheet.cell(c).and_then(|x| x.formula.as_ref())
|
||||
&& !formula_hidden(wb, sheet, c)
|
||||
{
|
||||
return format!("={}", f.text);
|
||||
}
|
||||
value_text(wb, sheet, c)
|
||||
}
|
||||
|
||||
/// A cell's value with its number format applied, independent of column width: no `#####`
|
||||
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result.
|
||||
pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
let style = wb.styles.get(sheet.style_id(c));
|
||||
let f = format(&v, style.num_fmt.as_str(), wb);
|
||||
let f = format(&sheet.value(c), style.num_fmt.as_str(), wb);
|
||||
match f.fill {
|
||||
Some((_, pos)) => {
|
||||
let mut t = f.text;
|
||||
|
||||
+106
-16
@@ -6,6 +6,7 @@ use std::sync::Arc;
|
||||
use gridcraft_core::date::{MONTHS, WEEKDAYS, datetime_from_serial, days_in_month, serial_from_ymd};
|
||||
use gridcraft_core::{CellRef, RangeRef, Value};
|
||||
use gridcraft_model::{Cell, Formula};
|
||||
use gridcraft_numfmt::{FormatKind, NumberFormat};
|
||||
|
||||
use crate::Result;
|
||||
use crate::cmd::Ctx;
|
||||
@@ -13,6 +14,9 @@ use crate::cmd::Ctx;
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FillMode {
|
||||
Series,
|
||||
/// The Ctrl+drag fill: the opposite of a plain drag. A lone number fills a
|
||||
/// series stepping by 1; anything a plain drag would extend is copied.
|
||||
Alternate,
|
||||
Copy,
|
||||
Formats,
|
||||
ValuesOnly,
|
||||
@@ -62,20 +66,25 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F
|
||||
if forward { (src.end.col + 1..=target.end.col).collect() } else { (target.start.col..src.start.col).rev().collect() };
|
||||
cols.into_iter().map(|c| CellRef::new(lane, c)).collect()
|
||||
};
|
||||
let pattern = if mode == FillMode::Series {
|
||||
Pattern::detect(
|
||||
&src_cells,
|
||||
&custom,
|
||||
cx.wb.date_system,
|
||||
cx.wb.styles.get(src_cells.first().and_then(|c| c.1.as_ref()).map(|c| c.style).unwrap_or_default()).num_fmt.as_str(),
|
||||
)
|
||||
let fmt = |c: &(CellRef, Option<Cell>)| cx.wb.styles.get(c.1.as_ref().map(|c| c.style).unwrap_or_default()).num_fmt.as_str();
|
||||
let pattern = if matches!(mode, FillMode::Series | FillMode::Alternate) {
|
||||
let detected = Pattern::detect(&src_cells, &custom, cx.wb.date_system, src_cells.first().map(fmt).unwrap_or_default());
|
||||
if mode == FillMode::Alternate { detected.alternate(&src_cells) } else { detected }
|
||||
} else {
|
||||
Pattern::Copy
|
||||
};
|
||||
// A source with no common pattern (`Product 1`, `On backorder`): each cell continues its
|
||||
// own series, one step per repeat of the source.
|
||||
let per_cell: Vec<Pattern> = if mode == FillMode::Series && matches!(pattern, Pattern::Copy) && src_cells.len() > 1 {
|
||||
src_cells.iter().map(|c| Pattern::detect(std::slice::from_ref(c), &custom, cx.wb.date_system, fmt(c))).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for (k, t) in targets.iter().enumerate() {
|
||||
let step = k as i64 + 1;
|
||||
let idx = k % src_cells.len().max(1);
|
||||
let (sc, scell) = src_cells.get(if forward { idx } else { src_cells.len() - 1 - idx }).cloned().unwrap_or((src.start, None));
|
||||
let src_i = if forward { idx } else { src_cells.len() - 1 - idx };
|
||||
let (sc, scell) = src_cells.get(src_i).cloned().unwrap_or((src.start, None));
|
||||
let mut cell = scell.clone().unwrap_or_default();
|
||||
match mode {
|
||||
FillMode::Formats => {
|
||||
@@ -84,7 +93,7 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F
|
||||
writes.push((*t, Some(existing)));
|
||||
continue;
|
||||
}
|
||||
FillMode::ValuesOnly | FillMode::Series | FillMode::Copy => {
|
||||
FillMode::ValuesOnly | FillMode::Series | FillMode::Alternate | FillMode::Copy => {
|
||||
let style = if mode == FillMode::ValuesOnly { sh.cell(*t).map(|c| c.style).unwrap_or_default() } else { cell.style };
|
||||
if let Some(f) = &cell.formula {
|
||||
if let Some(e) = f.expr() {
|
||||
@@ -92,7 +101,10 @@ pub fn fill(cx: &mut Ctx, sheet: usize, src: RangeRef, target: RangeRef, mode: F
|
||||
cell.formula = Some(Arc::new(Formula::from_expr(shifted)));
|
||||
cell.value = Value::Empty;
|
||||
}
|
||||
} else if let Some(v) = pattern.value(step, forward, src_cells.len()) {
|
||||
} else if let Some(v) = match per_cell.get(src_i) {
|
||||
Some(p) => p.value(k as i64 / src_cells.len() as i64 + 1, forward, 1),
|
||||
None => pattern.value(step, forward, src_cells.len()),
|
||||
} {
|
||||
cell.value = v;
|
||||
}
|
||||
cell.style = style;
|
||||
@@ -169,8 +181,14 @@ impl Pattern {
|
||||
let last = nums.last().copied().unwrap_or(0.0);
|
||||
let is_date = fmt.contains('d') || fmt.contains('y') || (fmt.contains('m') && !fmt.contains('h'));
|
||||
if nums.len() == 1 {
|
||||
// A single number copies; a single date increments by a day.
|
||||
return if is_date { Pattern::Linear { last, first, step: 1.0 } } else { Pattern::Copy };
|
||||
// A single number copies; a single date increments by a day, a single time by an hour.
|
||||
return if is_date {
|
||||
Pattern::Linear { last, first, step: 1.0 }
|
||||
} else if NumberFormat::parse(fmt).kind() == FormatKind::Time {
|
||||
Pattern::Linear { last, first, step: 1.0 / 24.0 }
|
||||
} else {
|
||||
Pattern::Copy
|
||||
};
|
||||
}
|
||||
// Dates that differ by whole months.
|
||||
if is_date && nums.len() >= 2 {
|
||||
@@ -231,6 +249,19 @@ impl Pattern {
|
||||
Pattern::Copy
|
||||
}
|
||||
|
||||
/// The pattern of a Ctrl+drag, which swaps copying and extending: a single
|
||||
/// number (which a plain drag copies) counts up by 1, and every series a
|
||||
/// plain drag would extend (numbers, dates, lists, `Item 1`) is copied.
|
||||
fn alternate(self, cells: &[(CellRef, Option<Cell>)]) -> Pattern {
|
||||
match (self, cells) {
|
||||
(Pattern::Copy, [(_, Some(cell))]) if cell.formula.is_none() => match cell.value.as_f64() {
|
||||
Some(n) if cell.value.is_number() => Pattern::Linear { last: n, first: n, step: 1.0 },
|
||||
_ => Pattern::Copy,
|
||||
},
|
||||
_ => Pattern::Copy,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value `k` steps beyond the source (forward) or before it (backward).
|
||||
fn value(&self, k: i64, forward: bool, _len: usize) -> Option<Value> {
|
||||
let sign = if forward { 1 } else { -1 };
|
||||
@@ -243,8 +274,12 @@ impl Pattern {
|
||||
Pattern::TextNum { prefix, suffix, last, first, step, width } => {
|
||||
let base = if forward { *last } else { *first };
|
||||
let n = base + step * k * sign;
|
||||
let n = n.abs();
|
||||
Some(Value::text(format!("{prefix}{n:0width$}{suffix}", width = *width)))
|
||||
// `Qtr3`, `Quarter 3` wrap after 4 like `Q3`.
|
||||
let quarter = suffix.is_empty()
|
||||
&& (1..=4).contains(&base)
|
||||
&& ["q", "qtr", "quarter"].contains(&prefix.trim_end().to_ascii_lowercase().as_str());
|
||||
let n = if quarter { (n - 1).rem_euclid(4) + 1 } else { n.abs() };
|
||||
Some(Value::text(format!("{prefix}{n:0width$}{}", ordinal_suffix(n, suffix), width = *width)))
|
||||
}
|
||||
Pattern::List { list, last, first, step, upper, lower } => {
|
||||
let len = list.len() as i64;
|
||||
@@ -292,6 +327,23 @@ fn round15(x: f64) -> f64 {
|
||||
if !p.is_finite() || p == 0.0 { x } else { (x * p).round() / p }
|
||||
}
|
||||
|
||||
/// `1st Period` → `2nd Period`: an English ordinal ending is rewritten to suit the new number.
|
||||
fn ordinal_suffix(n: i64, suffix: &str) -> String {
|
||||
let (Some(end), Some(rest)) = (suffix.get(..2), suffix.get(2..)) else { return suffix.to_string() };
|
||||
if !["st", "nd", "rd", "th"].contains(&end.to_ascii_lowercase().as_str()) || rest.starts_with(char::is_alphanumeric) {
|
||||
return suffix.to_string();
|
||||
}
|
||||
let new = match (n % 10, n % 100) {
|
||||
(_, 11..=13) => "th",
|
||||
(1, _) => "st",
|
||||
(2, _) => "nd",
|
||||
(3, _) => "rd",
|
||||
_ => "th",
|
||||
};
|
||||
let new = if end.chars().all(|c| c.is_ascii_uppercase()) { new.to_ascii_uppercase() } else { new.to_string() };
|
||||
format!("{new}{rest}")
|
||||
}
|
||||
|
||||
/// `Item 007` → ("Item ", 7, "", 3); `3rd` style leading numbers → ("", 3, "rd", 1).
|
||||
fn split_num(t: &str) -> Option<(String, i64, String, usize)> {
|
||||
let chars: Vec<char> = t.chars().collect();
|
||||
@@ -321,6 +373,7 @@ pub fn series(cx: &mut Ctx, sheet: usize, r: RangeRef, rows: bool, kind: &str, s
|
||||
let style = sh.style_id(first_cell);
|
||||
let mut v = start;
|
||||
for i in 1..len {
|
||||
let prev = v;
|
||||
v = match kind {
|
||||
"growth" => v * step,
|
||||
"date" => {
|
||||
@@ -333,7 +386,10 @@ pub fn series(cx: &mut Ctx, sheet: usize, r: RangeRef, rows: bool, kind: &str, s
|
||||
let mut left = step.abs() as i64;
|
||||
while left > 0 {
|
||||
n += step.signum();
|
||||
if datetime_from_serial(sys, n).is_some_and(|d| d.weekday != 0 && d.weekday != 6) {
|
||||
let Some(day) = datetime_from_serial(sys, n) else {
|
||||
return Err(crate::EngineError::Other("The weekday series runs past the supported date range.".into()));
|
||||
};
|
||||
if day.weekday != 0 && day.weekday != 6 {
|
||||
left -= 1;
|
||||
}
|
||||
}
|
||||
@@ -344,8 +400,9 @@ pub fn series(cx: &mut Ctx, sheet: usize, r: RangeRef, rows: bool, kind: &str, s
|
||||
}
|
||||
_ => v + step,
|
||||
};
|
||||
// The stop value bounds the series in the direction it runs (a growth by 0.5 falls).
|
||||
if let Some(s) = stop
|
||||
&& ((step >= 0.0 && v > s) || (step < 0.0 && v < s))
|
||||
&& ((v >= prev && v > s) || (v < prev && v < s))
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -562,4 +619,37 @@ mod tests {
|
||||
assert_eq!(split_num("Q003x"), Some(("Q".into(), 3, "x".into(), 3)));
|
||||
assert_eq!(split_num("abc"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times_quarters_ordinals_and_mixed_sources() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
let mut fill = |values: serde_json::Value, source: &str, target: &str| {
|
||||
s.execute("range.setValues", serde_json::json!({"range": source.get(..2).unwrap(), "values": values})).unwrap();
|
||||
s.execute("edit.autoFill", serde_json::json!({"source": source, "target": target})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
let r = RangeRef::parse(target).unwrap();
|
||||
r.iter().map(|c| crate::display::cell_text(&s.doc().unwrap().wb, sh, c)).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(fill(serde_json::json!([["9:00"]]), "A1", "A1:A3"), ["9:00", "10:00", "11:00"]);
|
||||
assert_eq!(fill(serde_json::json!([["Qtr3"]]), "B1", "B1:B3"), ["Qtr3", "Qtr4", "Qtr1"]);
|
||||
assert_eq!(fill(serde_json::json!([["Quarter 4"]]), "C1", "C1:C2"), ["Quarter 4", "Quarter 1"]);
|
||||
assert_eq!(fill(serde_json::json!([["1st Period"]]), "D1", "D1:D4"), ["1st Period", "2nd Period", "3rd Period", "4th Period"]);
|
||||
assert_eq!(
|
||||
fill(serde_json::json!([["Product 1"], ["On backorder"]]), "E1:E2", "E1:E6"),
|
||||
["Product 1", "On backorder", "Product 2", "On backorder", "Product 3", "On backorder"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falling_growth_series_stops_at_its_stop_value() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", serde_json::json!({"cell": "A1", "input": "5"})).unwrap();
|
||||
s.execute("edit.fillSeries", serde_json::json!({"range": "A1:A6", "type": "growth", "step": 0.5, "stop": 1})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
let growth: Vec<String> = (1..6).map(|r| crate::display::cell_text(&d.wb, sh, CellRef::new(r, 0))).collect();
|
||||
assert_eq!(growth, ["2.5", "1.25", "", "", ""]);
|
||||
}
|
||||
}
|
||||
|
||||
+372
-27
@@ -1,4 +1,4 @@
|
||||
//! Opening and saving files: XLSX, XLSB and ODS data import, CSV/TSV, JSON (debug), HTML export.
|
||||
//! Opening and saving files: XLSX, legacy XLS import, XLSB and ODS data import, CSV/TSV, JSON (debug), HTML export.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
@@ -11,6 +11,8 @@ use crate::{EngineError, Result};
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FileKind {
|
||||
Xlsx,
|
||||
/// Excel 97-2003 workbook (import only).
|
||||
Xls,
|
||||
Xlsb,
|
||||
Ods,
|
||||
Csv,
|
||||
@@ -24,6 +26,7 @@ impl FileKind {
|
||||
let ext = std::path::Path::new(path).extension()?.to_str()?.to_ascii_lowercase();
|
||||
Some(match ext.as_str() {
|
||||
"xlsx" | "xlsm" | "xltx" | "xltm" => FileKind::Xlsx,
|
||||
"xls" | "xlt" => FileKind::Xls,
|
||||
"xlsb" => FileKind::Xlsb,
|
||||
"ods" => FileKind::Ods,
|
||||
"csv" => FileKind::Csv,
|
||||
@@ -35,19 +38,90 @@ impl FileKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an encrypted workbook opened without a password contains this. The interface
|
||||
/// asks for the password when it sees it; programmatic callers pass `password` instead.
|
||||
pub const PASSWORD_REQUIRED: &str = "is password-protected. Enter its password to open it.";
|
||||
/// The error for a wrong password contains this.
|
||||
pub const WRONG_PASSWORD: &str = "The password is incorrect.";
|
||||
/// The first open warning of a workbook decrypted with its password.
|
||||
pub const DECRYPTED_NOTICE: &str = "This workbook was password-protected. GridCraft saves it without the password.";
|
||||
|
||||
/// Parses a file's bytes into a workbook. `name` picks the format by extension when the bytes
|
||||
/// don't say.
|
||||
/// don't say. An encrypted workbook needs [`open_bytes_with_password`].
|
||||
pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
|
||||
open_bytes_with_password(name, bytes, None)
|
||||
}
|
||||
|
||||
/// [`open_bytes`], first decrypting a password-protected workbook with `password`. Errors never
|
||||
/// quote the password.
|
||||
pub fn open_bytes_with_password(name: &str, bytes: &[u8], password: Option<&str>) -> Result<(Workbook, Vec<String>)> {
|
||||
if gridcraft_xlsx::sniff(bytes) != gridcraft_xlsx::Format::Encrypted {
|
||||
let (mut wb, warnings) = open_plain(name, bytes)?;
|
||||
fit_imported_rows(&mut wb);
|
||||
return Ok((wb, warnings));
|
||||
}
|
||||
// A scheme no password opens is said straight away, rather than after asking for one.
|
||||
let decrypt_error = |e: gridcraft_xlsx::DecryptError| EngineError::Other(decrypt_message(name, e));
|
||||
let Some(password) = password else {
|
||||
gridcraft_xlsx::check_encryption(bytes).map_err(decrypt_error)?;
|
||||
return Err(EngineError::Other(format!("'{name}' {PASSWORD_REQUIRED}")));
|
||||
};
|
||||
let plain = gridcraft_xlsx::decrypt(bytes, password).map_err(decrypt_error)?;
|
||||
if gridcraft_xlsx::sniff(&plain) == gridcraft_xlsx::Format::Encrypted {
|
||||
return Err(EngineError::Other(format!("We can't open '{name}': the encrypted file is damaged (it holds another encrypted file).")));
|
||||
}
|
||||
let (mut wb, mut warnings) = open_plain(name, &plain)?;
|
||||
fit_imported_rows(&mut wb);
|
||||
warnings.insert(0, DECRYPTED_NOTICE.into());
|
||||
Ok((wb, warnings))
|
||||
}
|
||||
|
||||
/// Excel auto-fits rows to their tallest font when opening a file: rows without a user-set
|
||||
/// height grow to fit their content. Rows the file made taller keep their height — our
|
||||
/// line-height estimate can differ from Excel's, and shrinking files that already look
|
||||
/// right would be a visible regression. Custom-height rows are left alone entirely.
|
||||
fn fit_imported_rows(wb: &mut Workbook) {
|
||||
for si in 0..wb.sheets.len() {
|
||||
let Some(sh) = wb.sheet(si) else { continue };
|
||||
let mut rows: Vec<u32> = sh.cells.iter().map(|(c, _)| c.row).collect();
|
||||
rows.sort_unstable();
|
||||
rows.dedup();
|
||||
for row in rows {
|
||||
let before = wb.sheet(si).and_then(|sh| sh.rows.get(&row)).and_then(|i| i.size);
|
||||
crate::cmd::auto_row_height(wb, si, row);
|
||||
let Some(before) = before else { continue };
|
||||
let after = wb.sheet(si).and_then(|sh| sh.rows.get(&row)).and_then(|i| i.size);
|
||||
if after.is_none_or(|a| before > a + 0.5)
|
||||
&& let Some(sh) = wb.sheet_mut(si)
|
||||
{
|
||||
sh.rows.entry(row).or_default().size = Some(before);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What to tell the user when an encrypted workbook can't be decrypted. Never quotes the password.
|
||||
fn decrypt_message(name: &str, e: gridcraft_xlsx::DecryptError) -> String {
|
||||
match e {
|
||||
gridcraft_xlsx::DecryptError::WrongPassword => format!("{WRONG_PASSWORD} Check that Caps Lock is off and try again."),
|
||||
gridcraft_xlsx::DecryptError::Unsupported(scheme) => {
|
||||
format!("'{name}' uses {scheme} encryption, which GridCraft can't open yet. Remove the password in Excel and try again.")
|
||||
}
|
||||
gridcraft_xlsx::DecryptError::Malformed(detail) => format!("We can't open '{name}': the encrypted file is damaged ({detail})."),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses bytes that aren't encrypted.
|
||||
fn open_plain(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
|
||||
let kind = FileKind::from_path(name);
|
||||
let sniffed = gridcraft_xlsx::sniff(bytes);
|
||||
if sniffed == gridcraft_xlsx::Format::Encrypted {
|
||||
return Err(EngineError::Other(format!(
|
||||
"'{name}' is password-protected. GridCraft can't open encrypted workbooks yet; remove the password in Excel and try again."
|
||||
)));
|
||||
if sniffed == gridcraft_xlsx::Format::Xls {
|
||||
let (wb, report) = gridcraft_xlsx::read_xls(bytes).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?;
|
||||
return Ok((wb, report.warnings));
|
||||
}
|
||||
if sniffed == gridcraft_xlsx::Format::LegacyBinary {
|
||||
return Err(EngineError::Other(format!(
|
||||
"'{name}' is an Excel 97-2003 (.xls) workbook or another legacy binary file. GridCraft doesn't open these yet; save it as .xlsx in Excel and try again."
|
||||
"'{name}' is a legacy binary file but not an Excel workbook (no workbook stream). GridCraft can't open it."
|
||||
)));
|
||||
}
|
||||
// Content wins over the extension: an ODS or XLSB package is imported as what it is,
|
||||
@@ -55,6 +129,8 @@ pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
|
||||
let import = match sniffed {
|
||||
gridcraft_xlsx::Format::Ods => Some(FileKind::Ods),
|
||||
gridcraft_xlsx::Format::Xlsb => Some(FileKind::Xlsb),
|
||||
// An XLSX package is never read as ODS/XLSB just because of its name.
|
||||
gridcraft_xlsx::Format::Xlsx => None,
|
||||
_ => kind.filter(|k| matches!(k, FileKind::Ods | FileKind::Xlsb)),
|
||||
};
|
||||
if let Some(import) = import {
|
||||
@@ -62,7 +138,8 @@ pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
|
||||
let (wb, report) = read(bytes).map_err(|e| EngineError::Other(format!("We can't import '{name}': {e}")))?;
|
||||
return Ok((wb, report.warnings));
|
||||
}
|
||||
if sniffed == gridcraft_xlsx::Format::Xlsx || kind == Some(FileKind::Xlsx) {
|
||||
// Text named `.xlsx` is read as text.
|
||||
if sniffed == gridcraft_xlsx::Format::Xlsx || (kind == Some(FileKind::Xlsx) && sniffed != gridcraft_xlsx::Format::Csv) {
|
||||
let (wb, report) = gridcraft_xlsx::read_xlsx(bytes).map_err(|e| EngineError::Other(format!("We can't open '{name}': {e}")))?;
|
||||
return Ok((wb, report.warnings));
|
||||
}
|
||||
@@ -78,6 +155,8 @@ pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<(Workbook, Vec<String>)> {
|
||||
Some(FileKind::Tsv) => {
|
||||
let opts = gridcraft_xlsx::CsvOptions { delimiter: b'\t', ..Default::default() };
|
||||
let mut wb = gridcraft_xlsx::read_csv(bytes, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// Tab is what makes it a .tsv/.txt; saved as .csv it gets the CSV default.
|
||||
wb.csv_delimiter = None;
|
||||
rename_first_sheet(&mut wb, name);
|
||||
Ok((wb, vec![]))
|
||||
}
|
||||
@@ -95,7 +174,9 @@ fn rename_first_sheet(wb: &mut Workbook, path: &str) {
|
||||
let stem = std::path::Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or("Sheet1");
|
||||
let clean: String = stem.chars().filter(|c| !matches!(c, ':' | '\\' | '/' | '?' | '*' | '[' | ']')).take(31).collect();
|
||||
let clean = clean.trim_matches('\'').to_string();
|
||||
// "History" is reserved (see `Workbook::check_sheet_name`): keep the default name instead.
|
||||
if !clean.is_empty()
|
||||
&& !clean.eq_ignore_ascii_case("History")
|
||||
&& let Some(sh) = wb.sheet_mut(0)
|
||||
{
|
||||
sh.name = clean;
|
||||
@@ -104,18 +185,68 @@ fn rename_first_sheet(wb: &mut Workbook, path: &str) {
|
||||
|
||||
/// Encodes a workbook in the format chosen by `path`'s extension.
|
||||
pub fn save_bytes(wb: &Workbook, path: &str) -> Result<Vec<u8>> {
|
||||
// An unknown or missing extension is refused rather than written as an XLSX under that name:
|
||||
// a typo like `.cvs` would otherwise produce a file no other app recognises.
|
||||
let Some(kind) = FileKind::from_path(path) else {
|
||||
let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path);
|
||||
return Err(EngineError::Other(format!("{name}: unknown file format. Save as .xlsx, .csv, .tsv, .json or .html.")));
|
||||
};
|
||||
save_bytes_as(wb, path, kind)
|
||||
}
|
||||
|
||||
/// Encodes a workbook as `kind`, whatever `path`'s extension says.
|
||||
pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result<Vec<u8>> {
|
||||
let sheet = wb.active_sheet;
|
||||
match FileKind::from_path(path).unwrap_or(FileKind::Xlsx) {
|
||||
FileKind::Xlsx => gridcraft_xlsx::write_xlsx(wb).map_err(|e| EngineError::Other(e.to_string())),
|
||||
match kind {
|
||||
// The extension picks the package kind; only the macro-enabled kinds (.xlsm, .xltm) carry
|
||||
// the VBA project, so any other name saves without it, as Excel does.
|
||||
FileKind::Xlsx => gridcraft_xlsx::write_xlsx_as(wb, gridcraft_xlsx::XlsxKind::from_path(path)).map_err(|e| EngineError::Other(e.to_string())),
|
||||
FileKind::Xls => {
|
||||
Err(EngineError::Other("Excel 97-2003 (.xls) is supported for import only. Save as .xlsx or another supported export format.".into()))
|
||||
}
|
||||
FileKind::Xlsb => Err(EngineError::Other("XLSB is supported for data import only. Save as .xlsx or another supported export format.".into())),
|
||||
FileKind::Ods => Err(EngineError::Other("ODS is supported for data import only. Save as .xlsx or another supported export format.".into())),
|
||||
FileKind::Csv => Ok(wb.sheet(sheet).map(|sh| gridcraft_xlsx::write_csv(sh, wb, b',')).unwrap_or_default()),
|
||||
FileKind::Tsv => Ok(wb.sheet(sheet).map(|sh| gridcraft_xlsx::write_csv(sh, wb, b'\t')).unwrap_or_default()),
|
||||
// A workbook read from CSV keeps the separator it was read with (a `;` file stays `;`).
|
||||
FileKind::Csv => wb.sheet(sheet).map(|sh| csv(wb, sh, wb.csv_delimiter.unwrap_or(b','))).transpose().map(Option::unwrap_or_default),
|
||||
FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, b'\t')).transpose().map(Option::unwrap_or_default),
|
||||
FileKind::Json => serde_json::to_vec_pretty(wb).map_err(|e| EngineError::Other(e.to_string())),
|
||||
FileKind::Html => Ok(to_html(wb, sheet).into_bytes()),
|
||||
FileKind::Html => to_html(wb, sheet).map(String::into_bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`save_bytes`] for the file at `path`: relative paths to linked workbooks are rewritten for
|
||||
/// its folder, so they still name the same files.
|
||||
pub fn save_file_bytes(wb: &Workbook, path: &str) -> Result<Vec<u8>> {
|
||||
match source_dir(path).and_then(|f| gridcraft_xlsx::rebase_links(wb, &f)) {
|
||||
Some(rebased) => save_bytes(&rebased, path),
|
||||
None => save_bytes(wb, path),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder of the file at `path`, which relative paths to linked workbooks are relative to.
|
||||
pub fn source_dir(path: &str) -> Option<std::path::PathBuf> {
|
||||
std::path::absolute(path).ok()?.parent().map(std::path::Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all
|
||||
/// characters in each cell" (Microsoft Support, *Excel formatting and features that are not
|
||||
/// transferred to other file formats*): number formats applied, never column-width `#####`.
|
||||
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
|
||||
gridcraft_xlsx::write_csv(sh, delimiter, |c| {
|
||||
// General's grid-width formatting rounds large identifiers to scientific notation.
|
||||
// Delimited files have no column width, so preserve the whole numeric value instead.
|
||||
if wb.styles.get(sh.style_id(c)).num_fmt.as_str().eq_ignore_ascii_case("General")
|
||||
&& let gridcraft_core::Value::Number(number) = sh.value(c)
|
||||
&& number.is_finite()
|
||||
{
|
||||
number.to_string()
|
||||
} else {
|
||||
crate::display::value_text(wb, sh, c)
|
||||
}
|
||||
})
|
||||
.map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
|
||||
}
|
||||
@@ -223,9 +354,12 @@ impl std::fmt::Write for ClipboardHtml {
|
||||
}
|
||||
}
|
||||
|
||||
/// Most rows Save as Web Page writes. A sheet whose used range is taller fails instead of losing cells.
|
||||
const HTML_EXPORT_MAX_ROWS: u32 = 100_001;
|
||||
|
||||
/// A sheet as a standalone HTML table (Save as Web Page).
|
||||
pub fn to_html(wb: &Workbook, sheet: usize) -> String {
|
||||
let Some(sh) = wb.sheet(sheet) else { return String::new() };
|
||||
pub fn to_html(wb: &Workbook, sheet: usize) -> Result<String> {
|
||||
let Some(sh) = wb.sheet(sheet) else { return Ok(String::new()) };
|
||||
let mut out = String::new();
|
||||
let _ = write!(
|
||||
out,
|
||||
@@ -233,7 +367,13 @@ pub fn to_html(wb: &Workbook, sheet: usize) -> String {
|
||||
esc(&sh.name)
|
||||
);
|
||||
if let Some(r) = sh.used_range() {
|
||||
for row in r.start.row..=r.end.row.min(r.start.row + 100_000) {
|
||||
if r.height() > HTML_EXPORT_MAX_ROWS {
|
||||
return Err(EngineError::Other(format!(
|
||||
"the sheet is too tall for a web page ({} rows, at most {HTML_EXPORT_MAX_ROWS}). Save as .xlsx or CSV instead.",
|
||||
r.height()
|
||||
)));
|
||||
}
|
||||
for row in r.start.row..=r.end.row {
|
||||
if sh.is_row_hidden(row) {
|
||||
continue;
|
||||
}
|
||||
@@ -256,7 +396,7 @@ pub fn to_html(wb: &Workbook, sheet: usize) -> String {
|
||||
}
|
||||
}
|
||||
out.push_str("</table></body></html>");
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -277,8 +417,12 @@ pub fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
// Write to a temporary file, then rename: a crash never leaves a half-written workbook.
|
||||
let tmp = format!("{path}.sctmp");
|
||||
std::fs::write(&tmp, bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
std::fs::rename(&tmp, path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)).map_err(|e| {
|
||||
// A write or rename that fails (full disk, the workbook locked by another app) leaves
|
||||
// no temporary file beside the user's workbook.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -356,6 +500,67 @@ pub fn image_size(data: &[u8]) -> Option<(u32, u32)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn html_export_fails_instead_of_dropping_cells_past_the_row_limit() {
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("near"));
|
||||
sh.set_value(CellRef::new(149_999, 0), gridcraft_core::Value::text("far"));
|
||||
assert!(save_bytes(&wb, "book.html").is_err());
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.remove_cell(CellRef::new(149_999, 0));
|
||||
sh.set_value(CellRef::new(100_000, 0), gridcraft_core::Value::text("far"));
|
||||
let html = String::from_utf8(save_bytes(&wb, "book.html").unwrap()).unwrap();
|
||||
assert!(html.contains(">near</td>") && html.contains(">far</td>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macros_are_saved_only_into_xlsm() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.vba_project = Some(b"vba".to_vec());
|
||||
let has_macros = |path: &str| {
|
||||
let bytes = save_bytes(&wb, path).unwrap();
|
||||
gridcraft_xlsx::read_xlsx(&bytes).unwrap().0.vba_project.is_some()
|
||||
};
|
||||
assert!(has_macros("book.xlsm"));
|
||||
assert!(has_macros("BOOK.XLSM"));
|
||||
assert!(!has_macros("book.xlsx"), "an .xlsx never carries a VBA project");
|
||||
assert!(has_macros("book.xltm"), "a macro-enabled template keeps the VBA project");
|
||||
assert!(!has_macros("book.xltx"), "a macro-free template never carries a VBA project");
|
||||
assert!(wb.vba_project.is_some(), "the open workbook keeps its macros");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_named_history_does_not_get_the_reserved_sheet_name() {
|
||||
for file in ["History.csv", "hIsToRy.csv", "history.tsv"] {
|
||||
let (wb, _) = open_bytes(file, b"1\n").unwrap();
|
||||
let name = wb.sheets[0].name.clone();
|
||||
assert!(wb.check_sheet_name(&name, Some(0)).is_ok(), "{file} opened as {name:?}");
|
||||
}
|
||||
let (wb, _) = open_bytes("Sales.csv", b"1\n").unwrap();
|
||||
assert_eq!(wb.sheets[0].name, "Sales");
|
||||
}
|
||||
|
||||
/// A save that can't be put in place (here a folder already has the workbook's name, as
|
||||
/// with a file another app holds locked) fails without leaving `<name>.sctmp` behind.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn failed_save_leaves_no_temporary_file() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-write-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let blocked = dir.join("Book1.xlsx");
|
||||
std::fs::create_dir(&blocked).unwrap();
|
||||
assert!(write_file(blocked.to_str().unwrap(), b"workbook").is_err());
|
||||
assert!(!dir.join("Book1.xlsx.sctmp").exists(), "the temporary file is removed");
|
||||
// An ordinary save still works and leaves only the workbook.
|
||||
let ok = dir.join("Book2.xlsx");
|
||||
write_file(ok.to_str().unwrap(), b"workbook").unwrap();
|
||||
assert_eq!(std::fs::read(&ok).unwrap(), b"workbook");
|
||||
assert!(!dir.join("Book2.xlsx.sctmp").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A minimal compound (CFB/OLE2) file — FAT in sector 0, directory in sector 1 — holding a
|
||||
/// root entry and the given stream names.
|
||||
fn cfb(streams: &[&str]) -> Vec<u8> {
|
||||
@@ -379,19 +584,159 @@ mod tests {
|
||||
b
|
||||
}
|
||||
|
||||
/// Cut-list rows as a CAD/CAM program exports them: `;`-separated, CRLF, part codes in the last
|
||||
/// two columns, a part name containing a comma.
|
||||
const CUT_LIST: &str = "1;511;184;P3_L1_led;2162PE;16;1MM_2162PE;1MM_2162PE;;;1244121406FB;\r\n\
|
||||
1;562.5;510;Komoda, lijevo;2162PE;19;1MM_2162PE;;;;12441214071A;124412140710\r\n";
|
||||
|
||||
#[test]
|
||||
fn encrypted_workbook_is_reported_not_misread() {
|
||||
let err = open_bytes("secret.xlsx", &cfb(&["EncryptionInfo", "EncryptedPackage"])).unwrap_err();
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains("password-protected"), "got: {msg}");
|
||||
assert!(!msg.contains("zip"), "must not surface the zip error: {msg}");
|
||||
fn csv_save_keeps_the_separator_it_was_opened_with() {
|
||||
let (wb, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap();
|
||||
assert_eq!(wb.csv_delimiter, Some(b';'));
|
||||
assert_eq!(String::from_utf8(save_bytes(&wb, "cut list.csv").unwrap()).unwrap(), CUT_LIST);
|
||||
// Save As another .csv name keeps it too; a comma file stays a comma file (quoting only
|
||||
// fields that contain the separator in use).
|
||||
assert_eq!(String::from_utf8(save_bytes(&wb, "copy.CSV").unwrap()).unwrap(), CUT_LIST);
|
||||
let commas = "\"Komoda, lijevo\",b\r\n1,x;y\r\n";
|
||||
let (wb, _) = open_bytes("plain.csv", commas.as_bytes()).unwrap();
|
||||
assert_eq!(String::from_utf8(save_bytes(&wb, "plain.csv").unwrap()).unwrap(), commas);
|
||||
// A tab-separated file named .csv round-trips with tabs.
|
||||
let tabs = "a\tb\r\n1\t2\r\n";
|
||||
let (wb, _) = open_bytes("tabs.csv", tabs.as_bytes()).unwrap();
|
||||
assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_xls_is_not_called_encrypted() {
|
||||
let err = open_bytes("old.xls", &cfb(&["Workbook", "\u{5}SummaryInformation"])).unwrap_err();
|
||||
fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() {
|
||||
let mut wb = Workbook::new();
|
||||
if let Some(sh) = wb.sheet_mut(0) {
|
||||
sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("a"));
|
||||
sh.set_value(CellRef::new(0, 1), gridcraft_core::Value::Number(1.0));
|
||||
}
|
||||
assert_eq!(save_bytes(&wb, "new.csv").unwrap(), b"a,1\r\n");
|
||||
// Through .xlsx the CSV origin is gone, as in Excel.
|
||||
let (from_csv, _) = open_bytes("cut list.csv", CUT_LIST.as_bytes()).unwrap();
|
||||
let (reopened, _) = open_bytes("book.xlsx", &save_bytes(&from_csv, "book.xlsx").unwrap()).unwrap();
|
||||
assert_eq!(reopened.csv_delimiter, None);
|
||||
assert!(String::from_utf8(save_bytes(&reopened, "again.csv").unwrap()).unwrap().starts_with("1,511,184,"));
|
||||
// A .tsv/.txt saved as .csv gets commas; as .tsv it keeps tabs.
|
||||
let (tsv, _) = open_bytes("list.txt", b"a\tb\r\n").unwrap();
|
||||
assert_eq!(save_bytes(&tsv, "list.csv").unwrap(), b"a,b\r\n");
|
||||
assert_eq!(save_bytes(&tsv, "list.tsv").unwrap(), b"a\tb\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_workbook_is_reported_not_misread() {
|
||||
let file = gridcraft_xlsx::testing::encrypt_workbook(b"package", "pw");
|
||||
let msg = open_bytes("secret.xlsx", &file).unwrap_err().to_string();
|
||||
assert!(msg.contains(PASSWORD_REQUIRED), "got: {msg}");
|
||||
assert!(!msg.contains("zip"), "must not surface the zip error: {msg}");
|
||||
// A compound file naming the streams but unreadable is damage: no password is asked for,
|
||||
// and none helps.
|
||||
let file = cfb(&["EncryptionInfo", "EncryptedPackage"]);
|
||||
for password in [None, Some("pw")] {
|
||||
let msg = open_bytes_with_password("secret.xlsx", &file, password).unwrap_err().to_string();
|
||||
assert!(msg.contains("damaged") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encryption_no_password_opens_is_reported_without_asking_for_one() {
|
||||
let info: &[u8] = &[3, 0, 2, 0, 4, 0, 0, 0]; // Standard header flags: RC4, not AES
|
||||
let file = gridcraft_xlsx::testing::compound_file(&[("EncryptionInfo", info), ("EncryptedPackage", &[0; 8])]);
|
||||
let msg = open_bytes("rc4.xlsx", &file).unwrap_err().to_string();
|
||||
assert!(msg.contains("RC4") && !msg.contains(PASSWORD_REQUIRED), "got: {msg}");
|
||||
let irm = gridcraft_xlsx::testing::compound_file(&[("EncryptedPackage", &[0; 8])]);
|
||||
let msg = open_bytes("irm.xlsx", &irm).unwrap_err().to_string();
|
||||
assert!(msg.contains("rights-management") && !msg.contains("damaged"), "got: {msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_compound_files_are_not_called_encrypted() {
|
||||
let err = open_bytes("old.doc", &cfb(&["WordDocument", "\u{5}SummaryInformation"])).unwrap_err();
|
||||
let msg = err.to_string();
|
||||
assert!(msg.contains("97-2003") && msg.contains(".xlsx"), "got: {msg}");
|
||||
assert!(msg.contains("not an Excel workbook"), "got: {msg}");
|
||||
assert!(!msg.contains("password"), "got: {msg}");
|
||||
}
|
||||
|
||||
/// Save As CSV/TSV writes cells as displayed: number formats applied, formula results,
|
||||
/// whole values in narrow columns (never `#####`), quoting unchanged.
|
||||
#[test]
|
||||
fn csv_writes_displayed_text() {
|
||||
use gridcraft_core::{CellError, Value};
|
||||
use gridcraft_model::{Cell, Formula, LineInfo, NumFmt, StyleId};
|
||||
let mut wb = Workbook::new();
|
||||
let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code));
|
||||
let (date, money, pct, frac, text, fixed, thousands) =
|
||||
(styled("yyyy-mm-dd"), styled("$#,##0.00"), styled("0.0%"), styled("# ?/?"), styled("@"), styled("0.00"), styled("#,##0"));
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let cells = [
|
||||
("A1", Cell { value: Value::Number(46023.0), formula: None, style: date }),
|
||||
("B1", Cell { value: Value::Number(1234.5), formula: None, style: money }),
|
||||
("C1", Cell { value: Value::Number(0.125), formula: None, style: pct }),
|
||||
("D1", Cell { value: Value::Number(1.5), formula: None, style: frac }),
|
||||
("E1", Cell { value: Value::text("007"), formula: None, style: text }),
|
||||
("F1", Cell { value: Value::Error(CellError::NA), formula: None, style: money }),
|
||||
("G1", Cell { value: Value::Bool(true), formula: None, style: StyleId::DEFAULT }),
|
||||
("A2", Cell { value: Value::Number(46024.0), style: date, ..Cell::formula(Formula::new("A1+1")) }),
|
||||
("B2", Cell { value: Value::Number(12345678.9), formula: None, style: fixed }),
|
||||
("C2", Cell { value: Value::Number(-0.25), formula: None, style: StyleId::DEFAULT }),
|
||||
("D2", Cell { value: Value::Number(1234567.0), formula: None, style: thousands }),
|
||||
];
|
||||
for (a, c) in cells {
|
||||
sh.set_cell(CellRef::parse(a).unwrap(), c);
|
||||
}
|
||||
// Column B is far too narrow for its numbers: the grid shows #####, the file must not.
|
||||
sh.cols.insert(1, LineInfo { size: Some(1.0), ..Default::default() });
|
||||
sh.show_formulas = true;
|
||||
let csv = String::from_utf8(save_bytes(&wb, "out.csv").unwrap()).unwrap();
|
||||
assert_eq!(csv, "2026-01-01,\"$1,234.50\",12.5%,1 1/2,007,#N/A,TRUE\r\n2026-01-02,12345678.90,-0.25,\"1,234,567\",,,\r\n");
|
||||
let tsv = String::from_utf8(save_bytes(&wb, "out.tsv").unwrap()).unwrap();
|
||||
assert!(tsv.starts_with("2026-01-01\t$1,234.50\t12.5%\t"), "{tsv}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delimited_exports_preserve_general_precision_and_explicit_number_formats() {
|
||||
use gridcraft_core::Value;
|
||||
use gridcraft_model::{Cell, NumFmt, StyleId};
|
||||
let mut workbook = Workbook::new();
|
||||
let scientific = workbook.styles.derive(StyleId::DEFAULT, |style| style.num_fmt = NumFmt::new("0.00E+00"));
|
||||
let sheet = workbook.sheet_mut(0).unwrap();
|
||||
sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() });
|
||||
sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() });
|
||||
sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() });
|
||||
for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] {
|
||||
let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap();
|
||||
assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_extension_saves_template_content_type() {
|
||||
let bytes = save_bytes(&Workbook::new(), "Budget.xltx").unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut types = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("[Content_Types].xml").unwrap(), &mut types).unwrap();
|
||||
assert!(
|
||||
types.contains(
|
||||
r#"PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml""#
|
||||
),
|
||||
"{types}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_wins_over_a_mismatched_extension() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Number(7.0));
|
||||
let package = save_bytes(&wb, "book.xlsx").unwrap();
|
||||
for name in ["book.xlsx", "book.ods", "book.xlsb", "book.csv"] {
|
||||
let (opened, _) = open_bytes(name, &package).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!(opened.sheet(0).unwrap().value(CellRef::new(0, 0)), gridcraft_core::Value::Number(7.0), "{name}");
|
||||
}
|
||||
for name in ["data.xlsx", "data.csv"] {
|
||||
let (opened, _) = open_bytes(name, b"a,b\n1,2\n").unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!(opened.sheet(0).unwrap().value(CellRef::new(0, 1)), gridcraft_core::Value::text("b"), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,16 @@
|
||||
|
||||
pub mod catalog;
|
||||
pub mod cf;
|
||||
mod clip_html;
|
||||
pub mod cmd;
|
||||
pub mod display;
|
||||
pub mod fill;
|
||||
pub mod io;
|
||||
pub mod links;
|
||||
pub mod outline;
|
||||
pub mod paper;
|
||||
pub mod pivot;
|
||||
pub mod pivot_calc;
|
||||
pub mod sample;
|
||||
pub mod selection;
|
||||
pub mod tables;
|
||||
@@ -25,7 +30,7 @@ use gridcraft_model::Workbook;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as Json;
|
||||
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command, register_test_command};
|
||||
pub use gridcraft_calc as calc;
|
||||
pub use gridcraft_core as core;
|
||||
pub use gridcraft_formula as formula;
|
||||
@@ -65,11 +70,17 @@ pub struct Clipboard {
|
||||
pub wb: Arc<Workbook>,
|
||||
pub sheet: usize,
|
||||
pub range: RangeRef,
|
||||
/// The range as copied, before whole rows/columns were trimmed to the used range
|
||||
/// (Insert Copied Cells inserts whole lines for a row or column copy).
|
||||
pub selected: RangeRef,
|
||||
pub cut: bool,
|
||||
/// Document uid of the source (a cut only moves within the same workbook).
|
||||
pub doc_uid: u64,
|
||||
/// Plain text (tab-separated) for the system clipboard.
|
||||
pub text: String,
|
||||
/// A multi-area copy: the areas as selected (for the marquee). `wb` then holds them slid
|
||||
/// together into one block at `range`. Empty for a single-range copy.
|
||||
pub areas: Vec<RangeRef>,
|
||||
}
|
||||
|
||||
/// In-cell edit mode as shown in the status bar.
|
||||
@@ -96,6 +107,11 @@ pub struct DocState {
|
||||
pub title: String,
|
||||
/// Per-sheet selection memory.
|
||||
pub sheet_selections: Vec<Selection>,
|
||||
/// Allow Edit Ranges unlocked with their password in this session: (sheet name, title).
|
||||
pub unlocked_ranges: Vec<(String, String)>,
|
||||
/// The format `path`'s content was recognised as when its extension doesn't name one (an
|
||||
/// XLSX called `budget.dat`): Save writes it back in that format.
|
||||
pub content_kind: Option<io::FileKind>,
|
||||
}
|
||||
|
||||
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -119,6 +135,8 @@ impl DocState {
|
||||
uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
title,
|
||||
sheet_selections: vec![],
|
||||
unlocked_ranges: vec![],
|
||||
content_kind: None,
|
||||
}
|
||||
}
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
@@ -127,6 +145,35 @@ impl DocState {
|
||||
pub fn sheet_index(&self) -> usize {
|
||||
self.wb.active_sheet
|
||||
}
|
||||
/// Records the view state that is saved with the file (`sheetView topLeftCell`, the active
|
||||
/// cell): the first visible cell of the scrolling area per sheet index in `tops`, and the
|
||||
/// active sheet's active cell. View state never makes the workbook dirty.
|
||||
pub fn store_view(&mut self, tops: &[(usize, CellRef)]) {
|
||||
let active = self.selection.active;
|
||||
let si = self.wb.active_sheet;
|
||||
let changed = tops.iter().any(|(i, c)| self.wb.sheets.get(*i).is_some_and(|sh| sh.view_top_left != *c))
|
||||
|| self.wb.sheets.get(si).is_some_and(|sh| sh.view_active != active);
|
||||
if !changed {
|
||||
return;
|
||||
}
|
||||
let dirty = self.is_dirty();
|
||||
let wb = Arc::make_mut(&mut self.wb);
|
||||
for (i, c) in tops {
|
||||
if let Some(sh) = wb.sheets.get_mut(*i)
|
||||
&& sh.view_top_left != *c
|
||||
{
|
||||
Arc::make_mut(sh).view_top_left = *c;
|
||||
}
|
||||
}
|
||||
if let Some(sh) = wb.sheets.get_mut(si)
|
||||
&& sh.view_active != active
|
||||
{
|
||||
Arc::make_mut(sh).view_active = active;
|
||||
}
|
||||
if !dirty {
|
||||
self.saved = self.wb.clone();
|
||||
}
|
||||
}
|
||||
pub fn display_title(&self) -> String {
|
||||
self.path
|
||||
.as_deref()
|
||||
@@ -150,6 +197,8 @@ pub struct Prefs {
|
||||
pub r1c1: bool,
|
||||
/// Words added with Add to Dictionary.
|
||||
pub user_dictionary: Vec<String>,
|
||||
/// View › Show › Formula Bar (an application option in Excel, not saved in the file).
|
||||
pub formula_bar: bool,
|
||||
}
|
||||
|
||||
impl Default for Prefs {
|
||||
@@ -163,6 +212,7 @@ impl Default for Prefs {
|
||||
sheets_in_new_workbook: 1,
|
||||
r1c1: false,
|
||||
user_dictionary: vec![],
|
||||
formula_bar: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,14 +234,15 @@ pub struct Session {
|
||||
pub clipboard: Option<Clipboard>,
|
||||
pub prefs: Prefs,
|
||||
pub mode: Mode,
|
||||
/// Commands run so far, without their passwords ([`cmd::journal_params`]).
|
||||
pub journal: Vec<(String, Json)>,
|
||||
pub ui_requests: Vec<UiRequest>,
|
||||
/// Format painter source style (sticky when double-clicked).
|
||||
pub format_painter: Option<(Arc<Workbook>, usize, RangeRef, bool)>,
|
||||
/// Find state (last search).
|
||||
pub last_find: Option<Json>,
|
||||
/// Workbook view: normal, pageLayout or pageBreakPreview.
|
||||
pub view_mode: String,
|
||||
/// View › Show › Ruler is off (rulers in Page Layout view; an application option).
|
||||
pub hide_ruler: bool,
|
||||
/// Journal position where action recording started.
|
||||
pub recording: Option<usize>,
|
||||
/// Windows hidden with View › Hide.
|
||||
@@ -200,6 +251,11 @@ pub struct Session {
|
||||
pub draw_tool: String,
|
||||
pub draw_color: String,
|
||||
pub draw_width: f32,
|
||||
/// Review › Show Comments: the Comments pane is open.
|
||||
pub comments_pane: bool,
|
||||
/// Review › Notes › Show All Notes: every note is displayed. An application display setting
|
||||
/// (like Excel's comment indicator option), so it's not saved in the file.
|
||||
pub show_all_notes: bool,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -284,7 +340,7 @@ impl Session {
|
||||
}
|
||||
};
|
||||
if spec.journal && result.is_ok() {
|
||||
self.journal.push((id.to_string(), params.clone()));
|
||||
self.journal.push((id.to_string(), cmd::journal_params(¶ms)));
|
||||
if self.journal.len() > 10_000 {
|
||||
self.journal.drain(..5_000);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Which hyperlink targets may be opened. A cell's link comes from the document (often a file
|
||||
//! somebody sent), so it is hostile input: only `http`, `https` and `mailto` ever leave the
|
||||
//! workbook for the system; `file:`, `smb:`, UNC paths, custom URL handlers, `javascript:` and
|
||||
//! the like are refused. Everything without a scheme stays an in-workbook reference.
|
||||
|
||||
use gridcraft_core::RangeRef;
|
||||
|
||||
/// What a link target is.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LinkKind {
|
||||
/// A cell, range, name or table of the workbook (`Sheet2!A1`, `Total`).
|
||||
Internal(String),
|
||||
/// An address to hand to the system, trimmed: `http`, `https` or `mailto` only.
|
||||
External(String),
|
||||
/// Refused, with the reason to show.
|
||||
Refused(String),
|
||||
}
|
||||
|
||||
const ALLOWED: [&str; 3] = ["http", "https", "mailto"];
|
||||
|
||||
/// Classifies a link target. Never panics; the single place that decides what may be opened.
|
||||
pub fn classify(target: &str) -> LinkKind {
|
||||
let t = target.trim();
|
||||
if t.chars().any(char::is_control) {
|
||||
return LinkKind::Refused("The link contains control characters.".into());
|
||||
}
|
||||
if t.starts_with("\\\\") || t.starts_with("//") {
|
||||
return LinkKind::Refused("Links to network locations aren't opened.".into());
|
||||
}
|
||||
if RangeRef::parse(t).is_some() {
|
||||
return LinkKind::Internal(t.to_string());
|
||||
}
|
||||
let Some((scheme, rest)) = t.split_once(':') else { return LinkKind::Internal(t.to_string()) };
|
||||
let scheme_like = scheme.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
|
||||
if !scheme_like {
|
||||
return LinkKind::Internal(t.to_string());
|
||||
}
|
||||
let lower = scheme.to_ascii_lowercase();
|
||||
if ALLOWED.contains(&lower.as_str()) && !rest.trim().is_empty() {
|
||||
LinkKind::External(t.to_string())
|
||||
} else {
|
||||
LinkKind::Refused(format!("Links of type \"{lower}:\" aren't opened. Only http, https and mailto links are allowed."))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_http_https_and_mailto_leave_the_workbook() {
|
||||
for ok in ["http://a.example/x", "HTTPS://A.example", " https://a.example ", "MailTo:[email protected]"] {
|
||||
assert!(matches!(classify(ok), LinkKind::External(_)), "{ok}");
|
||||
}
|
||||
assert_eq!(classify(" https://a.example "), LinkKind::External("https://a.example".into()));
|
||||
for bad in [
|
||||
"javascript:alert(1)",
|
||||
"JaVaScRiPt:alert(1)",
|
||||
"file:///etc/passwd",
|
||||
"smb://host/share",
|
||||
"ms-excel:ofe|u|http://x",
|
||||
"\\\\host\\share\\x.exe",
|
||||
"//host/share",
|
||||
"C:\\Windows\\calc.exe",
|
||||
"\tjavascript:1",
|
||||
"java\nscript:1",
|
||||
"\u{1}http://a.example",
|
||||
"http:",
|
||||
"mailto:",
|
||||
"x-custom://a",
|
||||
] {
|
||||
assert!(matches!(classify(bad), LinkKind::Refused(_)), "{bad:?} -> {:?}", classify(bad));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_stay_internal() {
|
||||
for r in ["Sheet2!A1", "'My Sheet'!B2:C3", "A1:B2", "#Sheet1!A1", "Total", "", " "] {
|
||||
assert!(matches!(classify(r), LinkKind::Internal(_)), "{r:?} -> {:?}", classify(r));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Outline groups (Data ▸ Group) of a sheet's rows or columns: the runs of lines at or above
|
||||
//! each outline level, as the grid draws them (brackets, − / + buttons, level buttons) and the
|
||||
//! Show / Hide Detail commands act on them. Summary rows sit below their detail and summary
|
||||
//! columns right of it (Excel's defaults; the model has no setting for the other way round).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use gridcraft_model::LineInfo;
|
||||
|
||||
/// The deepest outline level XLSX allows.
|
||||
pub const MAX_LEVEL: u8 = 7;
|
||||
|
||||
/// One group: lines `start..=end` at outline level `level` or deeper, with its summary line
|
||||
/// just after `end`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct OutlineGroup {
|
||||
pub level: u8,
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
/// Every detail line is hidden: the button shows +.
|
||||
pub collapsed: bool,
|
||||
}
|
||||
|
||||
impl OutlineGroup {
|
||||
/// The summary line, where the − / + button sits.
|
||||
pub fn summary(&self) -> u32 {
|
||||
self.end.saturating_add(1)
|
||||
}
|
||||
pub fn contains(&self, line: u32) -> bool {
|
||||
line >= self.start && line <= self.end
|
||||
}
|
||||
}
|
||||
|
||||
/// The deepest outline level used by these lines (0 = no outline).
|
||||
pub fn max_level(lines: &BTreeMap<u32, LineInfo>) -> u8 {
|
||||
lines.values().map(|l| l.outline.min(MAX_LEVEL)).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Every group, ordered by where it ends (inner groups before the group around them).
|
||||
pub fn groups(lines: &BTreeMap<u32, LineInfo>) -> Vec<OutlineGroup> {
|
||||
let mut out = Vec::new();
|
||||
// Open group per level (index level - 1): start line and whether all its lines are hidden.
|
||||
let mut open: [Option<(u32, bool)>; MAX_LEVEL as usize] = [None; MAX_LEVEL as usize];
|
||||
let mut prev: Option<u32> = None;
|
||||
let close_from = |open: &mut [Option<(u32, bool)>; MAX_LEVEL as usize], from: u8, end: u32, out: &mut Vec<OutlineGroup>| {
|
||||
for level in (from..=MAX_LEVEL).rev() {
|
||||
if let Some(slot) = open.get_mut(level as usize - 1)
|
||||
&& let Some((start, hidden)) = slot.take()
|
||||
{
|
||||
out.push(OutlineGroup { level, start, end, collapsed: hidden });
|
||||
}
|
||||
}
|
||||
};
|
||||
for (&i, info) in lines.iter().filter(|(_, l)| l.outline > 0) {
|
||||
let level = info.outline.min(MAX_LEVEL);
|
||||
match prev {
|
||||
// A gap ends every group.
|
||||
Some(p) if p.checked_add(1) != Some(i) => close_from(&mut open, 1, p, &mut out),
|
||||
Some(p) if level < MAX_LEVEL => close_from(&mut open, level + 1, p, &mut out),
|
||||
_ => {}
|
||||
}
|
||||
for slot in open.iter_mut().take(level as usize) {
|
||||
match slot {
|
||||
Some((_, hidden)) => *hidden &= info.hidden,
|
||||
None => *slot = Some((i, info.hidden)),
|
||||
}
|
||||
}
|
||||
prev = Some(i);
|
||||
}
|
||||
if let Some(p) = prev {
|
||||
close_from(&mut open, 1, p, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The group at `level` that holds `line`.
|
||||
pub fn group_at(lines: &BTreeMap<u32, LineInfo>, line: u32, level: u8) -> Option<OutlineGroup> {
|
||||
groups(lines).into_iter().find(|g| g.level == level && g.contains(line))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn lines(spec: &[(u32, u8, bool)]) -> BTreeMap<u32, LineInfo> {
|
||||
spec.iter().map(|&(i, outline, hidden)| (i, LineInfo { outline, hidden, ..Default::default() })).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_outline_has_no_groups() {
|
||||
let l = lines(&[(3, 0, true)]);
|
||||
assert_eq!(max_level(&l), 0);
|
||||
assert!(groups(&l).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_and_separate_groups() {
|
||||
// Rows 5..8 at level 1 with 6..7 at level 2; rows 12..13 at level 1 after a gap.
|
||||
let l = lines(&[(4, 1, false), (5, 2, false), (6, 2, false), (7, 1, false), (11, 1, true), (12, 1, true)]);
|
||||
assert_eq!(max_level(&l), 2);
|
||||
let g = groups(&l);
|
||||
assert_eq!(
|
||||
g,
|
||||
vec![
|
||||
OutlineGroup { level: 2, start: 5, end: 6, collapsed: false },
|
||||
OutlineGroup { level: 1, start: 4, end: 7, collapsed: false },
|
||||
OutlineGroup { level: 1, start: 11, end: 12, collapsed: true },
|
||||
]
|
||||
);
|
||||
assert_eq!(g[1].summary(), 8);
|
||||
assert_eq!(group_at(&l, 6, 1).map(|g| g.start), Some(4));
|
||||
assert_eq!(group_at(&l, 4, 2), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_groups_at_one_level_split_by_a_shallower_line() {
|
||||
// Two level-2 groups inside one level-1 group, separated by a level-1 line.
|
||||
let l = lines(&[(0, 2, true), (1, 2, true), (2, 1, false), (3, 2, false)]);
|
||||
let g = groups(&l);
|
||||
assert_eq!(g.iter().filter(|g| g.level == 2).count(), 2);
|
||||
assert_eq!(g.iter().find(|g| g.level == 2 && g.start == 0).map(|g| g.collapsed), Some(true));
|
||||
assert_eq!(g.iter().find(|g| g.level == 1).map(|g| (g.start, g.end, g.collapsed)), Some((0, 3, false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deepest_level_and_last_line_do_not_overflow() {
|
||||
let l = lines(&[(u32::MAX - 1, 9, false), (u32::MAX, 7, false)]);
|
||||
let g = groups(&l);
|
||||
assert_eq!(g.len(), 7);
|
||||
assert!(g.iter().all(|g| g.start == u32::MAX - 1 && g.end == u32::MAX));
|
||||
assert_eq!(g[0].summary(), u32::MAX);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Page Layout view geometry: a sheet shown as printed pages side by side.
|
||||
//!
|
||||
//! The view uses the print pagination ([`crate::cmd::print::split_bands`]) over the sheet from
|
||||
//! A1, so its page edges are the printed ones whenever the print area starts at A1. Pages keep
|
||||
//! going right and down past the data ("Click to add data" pages), as far as the view needs.
|
||||
//!
|
||||
//! Coordinates are *layout units*: sheet pixels (96 dpi) at the print scale, so a cell keeps its
|
||||
//! sheet size and a page is `paper / scale` big. The UI multiplies by its zoom. Pages sit in a
|
||||
//! grid with a gap around each: page `(row band, column band)` starts at
|
||||
//! `(gap + j·(page_w + gap), gap + i·(page_h + gap))`, and its cells start at its top-left margin.
|
||||
|
||||
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef};
|
||||
use gridcraft_model::{LineIndex, Sheet, Workbook};
|
||||
|
||||
use crate::cmd::print::{self, PX_TO_PT, PrintOptions};
|
||||
|
||||
/// Gap between pages on screen, in pixels at 100% zoom.
|
||||
pub const PAGE_GAP: f32 = 14.0;
|
||||
|
||||
/// One sheet paginated for the Page Layout view.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PageGrid {
|
||||
/// Page size in layout units.
|
||||
pub page_w: f64,
|
||||
pub page_h: f64,
|
||||
/// Left, right, top, bottom, header and footer margins in layout units.
|
||||
pub margins: [f64; 6],
|
||||
/// Gap between pages in layout units.
|
||||
pub gap: f64,
|
||||
/// Print scale (1.0 = 100%): screen sizes of cells are `zoom × scale`.
|
||||
pub scale: f32,
|
||||
/// Paper size in points (after orientation), for the rulers.
|
||||
pub paper_pt: (f32, f32),
|
||||
pub row_bands: Vec<(u32, u32)>,
|
||||
pub col_bands: Vec<(u32, u32)>,
|
||||
/// The bands reach the sheet's last row / column.
|
||||
pub rows_complete: bool,
|
||||
pub cols_complete: bool,
|
||||
/// Bands holding printed data: `[first, last]` row bands and column bands.
|
||||
pub data_rows: (usize, usize),
|
||||
pub data_cols: (usize, usize),
|
||||
ri: LineIndex,
|
||||
ci: LineIndex,
|
||||
}
|
||||
|
||||
/// A header or footer zone of one page.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct HfZone {
|
||||
pub footer: bool,
|
||||
/// 0 left, 1 centre, 2 right.
|
||||
pub section: usize,
|
||||
}
|
||||
|
||||
impl PageGrid {
|
||||
/// Paginates sheet `si` far enough to cover row `need_row` and column `need_col` (and at
|
||||
/// least the printed area). `None` when the sheet doesn't exist.
|
||||
pub fn build(wb: &Workbook, si: usize, need_row: u32, need_col: u32) -> Option<PageGrid> {
|
||||
let sh = wb.sheet(si)?;
|
||||
let printed = print::layout_sheet(wb, si, &PrintOptions::default(), None)?;
|
||||
let mut lay = printed.clone();
|
||||
let end_row = need_row.max(printed.area.end.row).min(MAX_ROWS - 1);
|
||||
let end_col = need_col.max(printed.area.end.col).min(MAX_COLS - 1);
|
||||
lay.area = RangeRef::new(CellRef::new(0, 0), CellRef::new(end_row, end_col));
|
||||
let (row_bands, col_bands) = print::split_bands(sh, &lay, MAX_ROWS as usize);
|
||||
let s = f64::from(lay.scale.clamp(0.1, 4.0));
|
||||
let to_layout = |pt: f32| f64::from(pt) / f64::from(PX_TO_PT) / s;
|
||||
let margins = lay.margins.map(to_layout);
|
||||
let band_range = |bands: &[(u32, u32)], lo: u32, hi: u32| {
|
||||
let first = bands.iter().position(|b| b.1 >= lo).unwrap_or(0);
|
||||
let last = bands.iter().rposition(|b| b.0 <= hi).unwrap_or(first).max(first);
|
||||
(first, last)
|
||||
};
|
||||
let area = printed.area;
|
||||
let data_rows = band_range(&row_bands, area.start.row, area.end.row);
|
||||
let data_cols = band_range(&col_bands, area.start.col, area.end.col);
|
||||
Some(PageGrid {
|
||||
page_w: to_layout(lay.page_w),
|
||||
page_h: to_layout(lay.page_h),
|
||||
margins,
|
||||
gap: f64::from(PAGE_GAP) / s,
|
||||
scale: lay.scale,
|
||||
paper_pt: (lay.page_w, lay.page_h),
|
||||
rows_complete: row_bands.last().is_some_and(|b| b.1 >= MAX_ROWS - 1),
|
||||
cols_complete: col_bands.last().is_some_and(|b| b.1 >= MAX_COLS - 1),
|
||||
row_bands,
|
||||
col_bands,
|
||||
data_rows,
|
||||
data_cols,
|
||||
ri: LineIndex::new(&sh.rows, sh.default_row_height, MAX_ROWS),
|
||||
ci: LineIndex::new(&sh.cols, sh.default_col_width, MAX_COLS),
|
||||
})
|
||||
}
|
||||
|
||||
/// The grid covers row `r` and column `c` (else it needs a rebuild with more pages).
|
||||
pub fn covers(&self, r: u32, c: u32) -> bool {
|
||||
(self.rows_complete || self.row_bands.last().is_some_and(|b| b.1 >= r))
|
||||
&& (self.cols_complete || self.col_bands.last().is_some_and(|b| b.1 >= c))
|
||||
}
|
||||
|
||||
fn band_of(bands: &[(u32, u32)], line: u32) -> usize {
|
||||
bands.partition_point(|b| b.1 < line).min(bands.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Left edge of page column `j` / top edge of page row `i`.
|
||||
pub fn page_x(&self, j: usize) -> f64 {
|
||||
self.gap + j as f64 * (self.page_w + self.gap)
|
||||
}
|
||||
pub fn page_y(&self, i: usize) -> f64 {
|
||||
self.gap + i as f64 * (self.page_h + self.gap)
|
||||
}
|
||||
/// The page rectangle `(x, y, w, h)` of page `(i, j)`.
|
||||
pub fn page_rect(&self, i: usize, j: usize) -> (f64, f64, f64, f64) {
|
||||
(self.page_x(j), self.page_y(i), self.page_w, self.page_h)
|
||||
}
|
||||
/// Where the cells of page `(i, j)` go: inside the margins.
|
||||
pub fn content_rect(&self, i: usize, j: usize) -> (f64, f64, f64, f64) {
|
||||
let [l, r, t, b, ..] = self.margins;
|
||||
(self.page_x(j) + l, self.page_y(i) + t, (self.page_w - l - r).max(1.0), (self.page_h - t - b).max(1.0))
|
||||
}
|
||||
|
||||
/// Left edge of column `col`.
|
||||
pub fn col_x(&self, col: u32) -> f64 {
|
||||
let j = Self::band_of(&self.col_bands, col);
|
||||
let start = self.col_bands.get(j).map_or(0, |b| b.0);
|
||||
self.page_x(j) + self.margins[0] + (self.ci.start(col) - self.ci.start(start))
|
||||
}
|
||||
/// Top edge of row `row`.
|
||||
pub fn row_y(&self, row: u32) -> f64 {
|
||||
let i = Self::band_of(&self.row_bands, row);
|
||||
let start = self.row_bands.get(i).map_or(0, |b| b.0);
|
||||
self.page_y(i) + self.margins[2] + (self.ri.start(row) - self.ri.start(start))
|
||||
}
|
||||
|
||||
/// Page column under `x` (the nearest one in gaps).
|
||||
pub fn page_col_at(&self, x: f64) -> usize {
|
||||
let j = ((x - self.gap / 2.0) / (self.page_w + self.gap)).floor();
|
||||
(j.max(0.0) as usize).min(self.col_bands.len().saturating_sub(1))
|
||||
}
|
||||
pub fn page_row_at(&self, y: f64) -> usize {
|
||||
let i = ((y - self.gap / 2.0) / (self.page_h + self.gap)).floor();
|
||||
(i.max(0.0) as usize).min(self.row_bands.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Column under `x`, clamped to the page's columns (margins and gaps hit the nearest one).
|
||||
pub fn col_at(&self, x: f64) -> u32 {
|
||||
let j = self.page_col_at(x);
|
||||
let Some(&(a, b)) = self.col_bands.get(j) else { return 0 };
|
||||
let local = x - self.page_x(j) - self.margins[0];
|
||||
if local <= 0.0 { a } else { self.ci.at(self.ci.start(a) + local).clamp(a, b) }
|
||||
}
|
||||
pub fn row_at(&self, y: f64) -> u32 {
|
||||
let i = self.page_row_at(y);
|
||||
let Some(&(a, b)) = self.row_bands.get(i) else { return 0 };
|
||||
let local = y - self.page_y(i) - self.margins[2];
|
||||
if local <= 0.0 { a } else { self.ri.at(self.ri.start(a) + local).clamp(a, b) }
|
||||
}
|
||||
|
||||
/// The page `(i, j)` whose paper contains the point, if any.
|
||||
pub fn page_at(&self, x: f64, y: f64) -> Option<(usize, usize)> {
|
||||
let (i, j) = (self.page_row_at(y), self.page_col_at(x));
|
||||
let (px, py, w, h) = self.page_rect(i, j);
|
||||
(x >= px && x < px + w && y >= py && y < py + h).then_some((i, j))
|
||||
}
|
||||
|
||||
/// The point lies on cells (inside a page's margins, on a cell of that page).
|
||||
pub fn on_cells(&self, x: f64, y: f64) -> bool {
|
||||
let Some((i, j)) = self.page_at(x, y) else { return false };
|
||||
let (cx, cy, w, h) = self.content_rect(i, j);
|
||||
let (Some(&(_, c1)), Some(&(_, r1))) = (self.col_bands.get(j), self.row_bands.get(i)) else { return false };
|
||||
// Cells end where the band ends (the rest of the printable area stays blank).
|
||||
let right = (self.col_x(c1) + self.ci.start(c1 + 1) - self.ci.start(c1)).min(cx + w);
|
||||
let bottom = (self.row_y(r1) + self.ri.start(r1 + 1) - self.ri.start(r1)).min(cy + h);
|
||||
x >= cx && x < right && y >= cy && y < bottom
|
||||
}
|
||||
|
||||
/// The header or footer section under the point: the top or bottom margin of a page, split
|
||||
/// into thirds between the side margins.
|
||||
pub fn hf_zone_at(&self, x: f64, y: f64) -> Option<((usize, usize), HfZone)> {
|
||||
let (i, j) = self.page_at(x, y)?;
|
||||
let (px, py, _, _) = self.page_rect(i, j);
|
||||
let [l, r, t, b, ..] = self.margins;
|
||||
let footer = if y < py + t {
|
||||
false
|
||||
} else if y >= py + self.page_h - b {
|
||||
true
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let inner = (self.page_w - l - r).max(3.0);
|
||||
let section = (((x - px - l) / (inner / 3.0)).floor().max(0.0) as usize).min(2);
|
||||
Some(((i, j), HfZone { footer, section }))
|
||||
}
|
||||
|
||||
/// Page `(i, j)` holds printed data (others are "Click to add data" pages).
|
||||
pub fn is_data_page(&self, i: usize, j: usize) -> bool {
|
||||
(self.data_rows.0..=self.data_rows.1).contains(&i) && (self.data_cols.0..=self.data_cols.1).contains(&j)
|
||||
}
|
||||
/// Printed page number of page `(i, j)` (down, then over) and the printed page count.
|
||||
pub fn page_number(&self, i: usize, j: usize) -> Option<(usize, usize)> {
|
||||
if !self.is_data_page(i, j) {
|
||||
return None;
|
||||
}
|
||||
let rows = self.data_rows.1 - self.data_rows.0 + 1;
|
||||
let cols = self.data_cols.1 - self.data_cols.0 + 1;
|
||||
Some(((j - self.data_cols.0) * rows + (i - self.data_rows.0) + 1, rows * cols))
|
||||
}
|
||||
|
||||
/// Page rows and columns overlapping the layout rectangle `[x0, x1] × [y0, y1]`.
|
||||
pub fn pages_in(&self, x0: f64, y0: f64, x1: f64, y1: f64) -> ((usize, usize), (usize, usize)) {
|
||||
((self.page_row_at(y0), self.page_row_at(y1)), (self.page_col_at(x0), self.page_col_at(x1)))
|
||||
}
|
||||
|
||||
/// Width / height of everything laid out so far.
|
||||
pub fn extent(&self) -> (f64, f64) {
|
||||
(self.page_x(self.col_bands.len()), self.page_y(self.row_bands.len()))
|
||||
}
|
||||
|
||||
/// Rows `(first, last)` of a page row and columns of a page column.
|
||||
pub fn row_band(&self, i: usize) -> Option<(u32, u32)> {
|
||||
self.row_bands.get(i).copied()
|
||||
}
|
||||
pub fn col_band(&self, j: usize) -> Option<(u32, u32)> {
|
||||
self.col_bands.get(j).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sheet-wide helper: the bottom-right cell a page grid for this sheet must reach so that the
|
||||
/// layout rectangle up to `(x, y)` is covered. Layout coordinates never run ahead of sheet
|
||||
/// coordinates (pages only add margins and gaps), so the sheet position is a safe bound.
|
||||
pub fn need_for(sh: &Sheet, x: f64, y: f64) -> (u32, u32) {
|
||||
(sh.row_at(y.max(0.0)).saturating_add(1).min(MAX_ROWS - 1), sh.col_at(x.max(0.0)).saturating_add(1).min(MAX_COLS - 1))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gridcraft_model::{Orientation, Sheet};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn wb_with(rows: u32, cols: u32) -> Workbook {
|
||||
let mut wb = Workbook::new();
|
||||
if let Some(sh) = wb.sheet_mut(0) {
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
sh.set_value(CellRef::new(r, c), gridcraft_core::Value::Number(1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
wb
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_match_print_pagination_and_cells_map_both_ways() {
|
||||
let wb = wb_with(120, 14);
|
||||
let g = PageGrid::build(&wb, 0, 400, 40).unwrap();
|
||||
let printed = print::layout_sheet(&wb, 0, &PrintOptions::default(), None).unwrap();
|
||||
// The printed area starts at A1, so the view's page edges are the printed ones (the
|
||||
// last printed page simply ends with the data).
|
||||
let starts = |b: &[(u32, u32)], n: usize| b.iter().take(n).map(|x| x.0).collect::<Vec<_>>();
|
||||
assert!(printed.row_bands.len() > 1 && printed.col_bands.len() > 1);
|
||||
assert_eq!(starts(&g.row_bands, printed.row_bands.len()), starts(&printed.row_bands, usize::MAX));
|
||||
assert_eq!(starts(&g.col_bands, printed.col_bands.len()), starts(&printed.col_bands, usize::MAX));
|
||||
assert_eq!(g.data_rows, (0, printed.row_bands.len() - 1));
|
||||
assert!(g.covers(400, 40));
|
||||
// Every cell maps to a point inside its own page's margins and back.
|
||||
for (r, c) in [(0, 0), (5, 3), (60, 9), (119, 13), (300, 30)] {
|
||||
let (x, y) = (g.col_x(c) + 1.0, g.row_y(r) + 1.0);
|
||||
assert_eq!((g.row_at(y), g.col_at(x)), (r, c), "cell ({r},{c})");
|
||||
assert!(g.on_cells(x, y));
|
||||
let (i, j) = g.page_at(x, y).unwrap();
|
||||
let (cx, cy, _, _) = g.content_rect(i, j);
|
||||
assert!(x >= cx && y >= cy);
|
||||
}
|
||||
// The first row of the second page starts below the first page plus a gap.
|
||||
let (a, _) = g.row_bands[1];
|
||||
assert!((g.row_y(a) - (g.page_y(1) + g.margins[2])).abs() < 1e-6);
|
||||
assert!(g.row_y(a) > g.page_h + g.gap);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn margins_gaps_and_header_zones() {
|
||||
let mut wb = wb_with(10, 3);
|
||||
if let Some(sh) = wb.sheet_mut(0) {
|
||||
sh.print.orientation = Orientation::Landscape;
|
||||
}
|
||||
let g = PageGrid::build(&wb, 0, 50, 20).unwrap();
|
||||
assert!(g.page_w > g.page_h, "landscape pages are wider than tall");
|
||||
// A point in the top margin hits the header, thirds pick the section.
|
||||
let (px, py, w, h) = g.page_rect(0, 0);
|
||||
let mid_top = (px + w / 2.0, py + g.margins[2] / 2.0);
|
||||
assert_eq!(g.hf_zone_at(mid_top.0, mid_top.1), Some(((0, 0), HfZone { footer: false, section: 1 })));
|
||||
assert_eq!(g.hf_zone_at(px + g.margins[0] + 2.0, py + h - 2.0).map(|z| z.1), Some(HfZone { footer: true, section: 0 }));
|
||||
assert_eq!(g.hf_zone_at(px + w - g.margins[1] - 2.0, py + 3.0).map(|z| z.1.section), Some(2));
|
||||
assert!(!g.on_cells(mid_top.0, mid_top.1), "margins aren't cells");
|
||||
// The gap between pages is no page at all.
|
||||
assert_eq!(g.page_at(px + w + g.gap / 2.0, py + 10.0), None);
|
||||
assert_eq!(g.hf_zone_at(px - 1.0, py + 3.0), None);
|
||||
// Page numbers count printed pages only.
|
||||
assert_eq!(g.page_number(0, 0), Some((1, 1)));
|
||||
assert_eq!(g.page_number(0, 1), None);
|
||||
assert!(g.is_data_page(0, 0) && !g.is_data_page(1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_scale_and_hostile_settings_stay_bounded() {
|
||||
let mut wb = wb_with(3, 3);
|
||||
if let Some(sh) = wb.sheet_mut(0) {
|
||||
sh.print.scale = 50;
|
||||
sh.print.margins = [f32::NAN, 1e9, -4.0, f32::INFINITY, 0.0, 0.0];
|
||||
sh.print.row_breaks = vec![0, 1, 2, u32::MAX];
|
||||
}
|
||||
let g = PageGrid::build(&wb, 0, MAX_ROWS, MAX_COLS).unwrap();
|
||||
assert!(g.rows_complete && g.cols_complete);
|
||||
assert!(g.page_w.is_finite() && g.page_h.is_finite() && g.page_w > 0.0);
|
||||
let (ex, ey) = g.extent();
|
||||
assert!(ex.is_finite() && ey.is_finite());
|
||||
assert_eq!(g.row_at(ey * 2.0), MAX_ROWS - 1);
|
||||
assert_eq!(g.col_at(-5.0), 0);
|
||||
assert_eq!(need_for(&Sheet::new("S"), f64::MAX, f64::MAX), (MAX_ROWS - 1, MAX_COLS - 1));
|
||||
assert!(PageGrid::build(&wb, 7, 0, 0).is_none());
|
||||
}
|
||||
}
|
||||
+436
-40
@@ -12,6 +12,8 @@ use gridcraft_core::date::datetime_from_serial;
|
||||
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
|
||||
use gridcraft_model::*;
|
||||
|
||||
use crate::pivot_calc::CalcSet;
|
||||
|
||||
/// Largest source block read (cells).
|
||||
pub const MAX_SOURCE_CELLS: u64 = 10_000_000;
|
||||
/// Largest report written (cells).
|
||||
@@ -503,6 +505,12 @@ pub struct Output {
|
||||
/// Rows above the body (report filters plus a blank row).
|
||||
pub body_offset: u32,
|
||||
pub width: u32,
|
||||
/// Grid rows of the innermost (or collapsed) items: a PivotChart's categories.
|
||||
pub chart_rows: Vec<u32>,
|
||||
/// Grid columns of item (not total) values with their series names: a PivotChart's series.
|
||||
pub chart_cols: Vec<(u32, String)>,
|
||||
/// Grid column holding the innermost row labels (`None` without row fields).
|
||||
pub label_col: Option<u32>,
|
||||
}
|
||||
|
||||
impl Output {
|
||||
@@ -546,10 +554,14 @@ enum LineKind {
|
||||
|
||||
struct Line {
|
||||
kind: LineKind,
|
||||
/// A category of a PivotChart: an innermost (or collapsed) item.
|
||||
leaf: bool,
|
||||
path: Vec<u32>,
|
||||
values: bool,
|
||||
/// (column, value, indent, number format)
|
||||
labels: Vec<(usize, Value, u8, Option<String>)>,
|
||||
/// The value field of the line when Σ Values sits in Rows (`None`: one per data column).
|
||||
vi: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -569,6 +581,10 @@ struct Ctx<'a> {
|
||||
rows: Vec<&'a PivotField>,
|
||||
row_items: Vec<FieldItems>,
|
||||
row_fmts: Vec<String>,
|
||||
/// Depth of Σ Values among the row fields when it sits in Rows (two or more value fields).
|
||||
vpos: Option<usize>,
|
||||
/// Value field captions.
|
||||
val_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
@@ -578,26 +594,113 @@ impl Ctx<'_> {
|
||||
(it.value.clone(), fmt, it.label.clone())
|
||||
}
|
||||
|
||||
fn flatten(&self, nodes: &[Node], depth: usize, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
|
||||
/// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form.
|
||||
fn level_cell(&self, level: usize) -> (usize, u8) {
|
||||
if self.pt.layout == PivotLayout::Outline { (level, 0) } else { (0, level.min(250) as u8) }
|
||||
}
|
||||
|
||||
/// Σ Values comes right here, at row field depth `depth` (`vi`: the value field already chosen above).
|
||||
fn values_here(&self, depth: usize, vi: Option<usize>) -> bool {
|
||||
vi.is_none() && self.vpos == Some(depth)
|
||||
}
|
||||
|
||||
/// Per-value subtotal lines of an item with Σ Values below it ("East Sum of Sales").
|
||||
fn value_subtotals(&self, col: usize, indent: u8, label: &str, prefix: &[u32], out: &mut Vec<Line>) {
|
||||
for (vi, name) in self.val_names.iter().enumerate() {
|
||||
out.push(Line {
|
||||
kind: LineKind::Subtotal,
|
||||
leaf: false,
|
||||
path: prefix.to_vec(),
|
||||
values: true,
|
||||
labels: vec![(col, Value::text(format!("{label} {name}")), indent, None)],
|
||||
vi: Some(vi),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The Σ Values level at row field depth `depth`: one item per value field, each followed by
|
||||
/// the row fields below it (`nodes`) or, innermost, holding that value.
|
||||
fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
|
||||
let (col, indent) = self.level_cell(depth);
|
||||
for (vi, name) in self.val_names.iter().enumerate() {
|
||||
let labels = vec![(col, Value::text(name.as_str()), indent, None)];
|
||||
let leaf = nodes.is_empty();
|
||||
out.push(Line { kind: LineKind::Item(!leaf), leaf, path: prefix.clone(), values: leaf, labels, vi: Some(vi) });
|
||||
if !leaf {
|
||||
self.flatten(nodes, depth, Some(vi), prefix, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten(&self, nodes: &[Node], depth: usize, vi: Option<usize>, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
|
||||
if self.values_here(depth, vi) {
|
||||
self.flatten_values(nodes, depth, prefix, out);
|
||||
return;
|
||||
}
|
||||
let n = self.rows.len();
|
||||
let outline = self.pt.layout == PivotLayout::Outline;
|
||||
// Σ Values still to come below this level: totals need one line per value field.
|
||||
let values_below = vi.is_none() && self.vpos.is_some();
|
||||
let (col, indent) = self.level_cell(depth + usize::from(vi.is_some() && self.vpos.is_some()));
|
||||
for node in nodes {
|
||||
prefix.push(node.item);
|
||||
let (v, fmt, label) = self.label_cell(depth, node.item);
|
||||
let (col, indent) = if outline { (depth, 0) } else { (0, depth.min(250) as u8) };
|
||||
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
|
||||
if depth + 1 >= n || collapsed || node.children.is_empty() {
|
||||
out.push(Line { kind: LineKind::Item(depth + 1 < n), path: prefix.clone(), values: true, labels: vec![(col, v, indent, fmt)] });
|
||||
let leaf = depth + 1 >= n || collapsed || node.children.is_empty();
|
||||
if leaf && !values_below {
|
||||
out.push(Line {
|
||||
kind: LineKind::Item(depth + 1 < n),
|
||||
leaf: true,
|
||||
path: prefix.clone(),
|
||||
values: true,
|
||||
labels: vec![(col, v, indent, fmt)],
|
||||
vi,
|
||||
});
|
||||
} else if leaf {
|
||||
out.push(Line {
|
||||
kind: LineKind::Item(true),
|
||||
leaf: false,
|
||||
path: prefix.clone(),
|
||||
values: false,
|
||||
labels: vec![(col, v, indent, fmt)],
|
||||
vi,
|
||||
});
|
||||
// Outline gives each level its own column, so the captions go in the Values
|
||||
// column even when the levels between are collapsed away.
|
||||
let level = if self.pt.layout == PivotLayout::Outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 };
|
||||
self.flatten_values(&[], level, prefix, out);
|
||||
} else if values_below {
|
||||
// Subtotals per value field, below the group (one line can't hold them all).
|
||||
out.push(Line {
|
||||
kind: LineKind::Item(true),
|
||||
leaf: false,
|
||||
path: prefix.clone(),
|
||||
values: false,
|
||||
labels: vec![(col, v, indent, fmt)],
|
||||
vi,
|
||||
});
|
||||
self.flatten(&node.children, depth + 1, None, prefix, out);
|
||||
if self.pt.subtotals {
|
||||
self.value_subtotals(col, indent, &label, prefix, out);
|
||||
}
|
||||
} else {
|
||||
let top = self.pt.subtotals && self.pt.subtotals_top;
|
||||
out.push(Line { kind: LineKind::Item(true), path: prefix.clone(), values: top, labels: vec![(col, v, indent, fmt)] });
|
||||
self.flatten(&node.children, depth + 1, prefix, out);
|
||||
out.push(Line {
|
||||
kind: LineKind::Item(true),
|
||||
leaf: false,
|
||||
path: prefix.clone(),
|
||||
values: top,
|
||||
labels: vec![(col, v, indent, fmt)],
|
||||
vi,
|
||||
});
|
||||
self.flatten(&node.children, depth + 1, vi, prefix, out);
|
||||
if self.pt.subtotals && !self.pt.subtotals_top {
|
||||
out.push(Line {
|
||||
kind: LineKind::Subtotal,
|
||||
leaf: false,
|
||||
path: prefix.clone(),
|
||||
values: true,
|
||||
labels: vec![(col, Value::text(format!("{label} Total")), indent, None)],
|
||||
vi,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -605,7 +708,8 @@ impl Ctx<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten_tabular(
|
||||
/// Tabular form of [`Self::flatten_values`]: the first line also carries the parents' labels.
|
||||
fn flatten_tabular_values(
|
||||
&self,
|
||||
nodes: &[Node],
|
||||
depth: usize,
|
||||
@@ -613,23 +717,57 @@ impl Ctx<'_> {
|
||||
pending: &[(usize, Value, u8, Option<String>)],
|
||||
out: &mut Vec<Line>,
|
||||
) {
|
||||
for (vi, name) in self.val_names.iter().enumerate() {
|
||||
let mut labels: Vec<(usize, Value, u8, Option<String>)> = if vi == 0 { pending.to_vec() } else { vec![] };
|
||||
labels.push((depth, Value::text(name.as_str()), 0, None));
|
||||
if nodes.is_empty() {
|
||||
out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi: Some(vi) });
|
||||
} else {
|
||||
self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten_tabular(
|
||||
&self,
|
||||
nodes: &[Node],
|
||||
depth: usize,
|
||||
vi: Option<usize>,
|
||||
prefix: &mut Vec<u32>,
|
||||
pending: &[(usize, Value, u8, Option<String>)],
|
||||
out: &mut Vec<Line>,
|
||||
) {
|
||||
if self.values_here(depth, vi) {
|
||||
self.flatten_tabular_values(nodes, depth, prefix, pending, out);
|
||||
return;
|
||||
}
|
||||
let n = self.rows.len();
|
||||
let values_below = vi.is_none() && self.vpos.is_some();
|
||||
let col = depth + usize::from(vi.is_some() && self.vpos.is_some());
|
||||
for (i, node) in nodes.iter().enumerate() {
|
||||
prefix.push(node.item);
|
||||
let (v, fmt, label) = self.label_cell(depth, node.item);
|
||||
let mut labels: Vec<(usize, Value, u8, Option<String>)> = if i == 0 { pending.to_vec() } else { vec![] };
|
||||
labels.push((depth, v, 0, fmt));
|
||||
labels.push((col, v, 0, fmt));
|
||||
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
|
||||
if depth + 1 >= n || collapsed || node.children.is_empty() {
|
||||
out.push(Line { kind: LineKind::Item(false), path: prefix.clone(), values: true, labels });
|
||||
if values_below {
|
||||
self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, out);
|
||||
} else {
|
||||
out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi });
|
||||
}
|
||||
} else {
|
||||
self.flatten_tabular(&node.children, depth + 1, prefix, &labels, out);
|
||||
if self.pt.subtotals {
|
||||
self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, out);
|
||||
if self.pt.subtotals && values_below {
|
||||
self.value_subtotals(col, 0, &label, prefix, out);
|
||||
} else if self.pt.subtotals {
|
||||
out.push(Line {
|
||||
kind: LineKind::Subtotal,
|
||||
leaf: false,
|
||||
path: prefix.clone(),
|
||||
values: true,
|
||||
labels: vec![(depth, Value::text(format!("{label} Total")), 0, None)],
|
||||
labels: vec![(col, Value::text(format!("{label} Total")), 0, None)],
|
||||
vi,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -666,13 +804,50 @@ fn flatten_cols(
|
||||
|
||||
type AggMap = HashMap<(Vec<u32>, Vec<u32>), Vec<Acc>>;
|
||||
|
||||
/// Where a value field's numbers come from.
|
||||
#[derive(Clone, Copy)]
|
||||
enum ValSrc {
|
||||
/// A source column.
|
||||
Col(usize),
|
||||
/// A calculated field (index into the PivotTable's calculated fields).
|
||||
Calc(usize),
|
||||
}
|
||||
|
||||
/// True when `col_groups` distinct column leaves (plus the grand-total column) times `values` value fields
|
||||
/// (at least one data column per group) already exceed the sheet width. This is a lower bound on the final column count.
|
||||
fn data_cols_exceed_sheet(col_groups: usize, grand_total: bool, values: usize) -> bool {
|
||||
(col_groups + usize::from(grand_total)).saturating_mul(values.max(1)) > MAX_COLS as usize
|
||||
}
|
||||
|
||||
/// Computes a PivotTable report from the workbook.
|
||||
pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Output, String> {
|
||||
let src = read_source(wb, &pt.source, pivot_sheet)?;
|
||||
let fmt_of = |c: usize| src.formats.get(c).cloned().unwrap_or_else(|| "General".into());
|
||||
let rows: Vec<(usize, &PivotField)> = pt.rows.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect();
|
||||
let cols: Vec<(usize, &PivotField)> = pt.columns.iter().filter_map(|f| src.col(&f.source_col).map(|c| (c, f))).collect();
|
||||
let vals: Vec<(usize, &PivotValue)> = pt.values.iter().filter_map(|v| src.col(&v.source_col).map(|c| (c, v))).collect();
|
||||
// Value fields: a source column, or a calculated field evaluated on sums (see `pivot_calc`).
|
||||
let calc = CalcSet::new(pt, &src.headers);
|
||||
let vals: Vec<(ValSrc, &PivotValue)> = pt
|
||||
.values
|
||||
.iter()
|
||||
.filter_map(|v| match src.col(&v.source_col) {
|
||||
Some(c) => Some((ValSrc::Col(c), v)),
|
||||
None => calc.index(&v.source_col).map(|i| (ValSrc::Calc(i), v)),
|
||||
})
|
||||
.collect();
|
||||
// Source columns summed for the calculated fields, accumulated after the value fields.
|
||||
let mut extra: Vec<usize> = Vec::new();
|
||||
for (vs, _) in &vals {
|
||||
if let ValSrc::Calc(i) = vs {
|
||||
for name in calc.source_refs(*i) {
|
||||
if let Some(c) = src.col(&name)
|
||||
&& !extra.contains(&c)
|
||||
{
|
||||
extra.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if rows.len() + cols.len() > MAX_AXIS_FIELDS {
|
||||
return Err(format!("A PivotTable can have at most {MAX_AXIS_FIELDS} row and column fields."));
|
||||
}
|
||||
@@ -696,6 +871,14 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
|
||||
let k = vals.len();
|
||||
let empty = rows.is_empty() && cols.is_empty() && vals.is_empty();
|
||||
// Σ Values in Rows (it exists with two or more value fields): its depth among the row fields
|
||||
// found in the source.
|
||||
let vpos: Option<usize> = (pt.values_on_rows && k > 1).then(|| {
|
||||
let p = pt.values_position.unwrap_or(pt.rows.len());
|
||||
pt.rows.iter().take(p).filter(|f| src.col(&f.source_col).is_some()).count()
|
||||
});
|
||||
let on_rows = vpos.is_some();
|
||||
let row_levels = rows.len() + usize::from(on_rows);
|
||||
|
||||
// ---- aggregate
|
||||
let mut row_items: Vec<FieldItems> = rows.iter().map(|_| FieldItems::default()).collect();
|
||||
@@ -703,6 +886,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
let mut aggs: AggMap = HashMap::new();
|
||||
let mut row_set: HashSet<Vec<u32>> = HashSet::new();
|
||||
let mut col_set: HashSet<Vec<u32>> = HashSet::new();
|
||||
let mut col_leaves: HashSet<Vec<u32>> = HashSet::new();
|
||||
let filter_fmts: Vec<String> = filters.iter().map(|f| fmt_of(f.0)).collect();
|
||||
let row_fmts: Vec<String> = rows.iter().map(|(c, _)| fmt_of(*c)).collect();
|
||||
let col_fmts: Vec<String> = cols.iter().map(|(c, _)| fmt_of(*c)).collect();
|
||||
@@ -728,14 +912,33 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
}
|
||||
for a in 0..=rp.len() {
|
||||
for b in 0..=cp.len() {
|
||||
let e = aggs.entry((rp[..a].to_vec(), cp[..b].to_vec())).or_insert_with(|| vec![Acc::default(); k]);
|
||||
for (acc, (c, _)) in e.iter_mut().zip(vals.iter()) {
|
||||
let e = aggs.entry((rp[..a].to_vec(), cp[..b].to_vec())).or_insert_with(|| vec![Acc::default(); k + extra.len()]);
|
||||
for (acc, (vs, _)) in e.iter_mut().zip(vals.iter()) {
|
||||
if let ValSrc::Col(c) = vs {
|
||||
acc.add(rec.get(*c).unwrap_or(&Value::Empty));
|
||||
}
|
||||
}
|
||||
for (acc, c) in e.iter_mut().skip(k).zip(extra.iter()) {
|
||||
acc.add(rec.get(*c).unwrap_or(&Value::Empty));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The column leaf this record lands in: its path cut after the first collapsed item (as in `flatten_cols`).
|
||||
let shown = cols
|
||||
.iter()
|
||||
.zip(col_items.iter())
|
||||
.zip(cp.iter())
|
||||
.position(|(((_, f), fi), &it)| !f.collapsed_items.is_empty() && is_collapsed(f, &fi.label(it)))
|
||||
.map_or(cp.len(), |d| d + 1);
|
||||
if !col_leaves.contains(&cp[..shown]) {
|
||||
col_leaves.insert(cp[..shown].to_vec());
|
||||
}
|
||||
row_set.insert(rp);
|
||||
col_set.insert(cp);
|
||||
// Refuse a report that cannot fit before the accumulators for more column groups are allocated.
|
||||
if !cols.is_empty() && data_cols_exceed_sheet(col_leaves.len(), pt.grand_totals_rows, k) {
|
||||
return Err("The PivotTable report will not fit on the sheet.".into());
|
||||
}
|
||||
if aggs.len() > 5_000_000 {
|
||||
return Err("The PivotTable report is too large.".into());
|
||||
}
|
||||
@@ -752,18 +955,32 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
collect_siblings(&row_tree, &mut Vec::new(), &mut siblings);
|
||||
let level0: Vec<u32> = row_tree.iter().map(|n| n.item).collect();
|
||||
|
||||
let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone() };
|
||||
let val_names: Vec<String> = vals.iter().map(|(_, v)| v.name.clone()).collect();
|
||||
let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone(), vpos, val_names: val_names.clone() };
|
||||
let mut lines: Vec<Line> = Vec::new();
|
||||
if rows.is_empty() {
|
||||
lines.push(Line { kind: LineKind::Item(false), path: vec![], values: true, labels: vec![] });
|
||||
if row_levels == 0 {
|
||||
lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![], vi: None });
|
||||
} else {
|
||||
if pt.layout == PivotLayout::Tabular {
|
||||
ctx.flatten_tabular(&row_tree, 0, &mut Vec::new(), &[], &mut lines);
|
||||
ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines);
|
||||
} else {
|
||||
ctx.flatten(&row_tree, 0, &mut Vec::new(), &mut lines);
|
||||
ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut lines);
|
||||
}
|
||||
if pt.grand_totals_cols {
|
||||
lines.push(Line { kind: LineKind::Grand, path: vec![], values: true, labels: vec![(0, Value::text("Grand Total"), 0, None)] });
|
||||
// With only Σ Values in Rows its items are the totals already.
|
||||
if pt.grand_totals_cols && !rows.is_empty() {
|
||||
let grand = |text: String, vi: Option<usize>| Line {
|
||||
kind: LineKind::Grand,
|
||||
leaf: false,
|
||||
path: vec![],
|
||||
values: true,
|
||||
labels: vec![(0, Value::text(text), 0, None)],
|
||||
vi,
|
||||
};
|
||||
if on_rows {
|
||||
lines.extend(val_names.iter().enumerate().map(|(vi, name)| grand(format!("Total {name}"), Some(vi))));
|
||||
} else {
|
||||
lines.push(grand("Grand Total".into(), None));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut specs: Vec<ColSpec> = Vec::new();
|
||||
@@ -777,7 +994,10 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
}
|
||||
let mut data_cols: Vec<(usize, Option<usize>)> = Vec::new();
|
||||
for (si, _) in specs.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if on_rows {
|
||||
// Each line names its value field; one data column per column item.
|
||||
data_cols.push((si, None));
|
||||
} else if k == 0 {
|
||||
if !cols.is_empty() {
|
||||
data_cols.push((si, None));
|
||||
}
|
||||
@@ -792,12 +1012,12 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
}
|
||||
|
||||
let compact = pt.layout == PivotLayout::Compact;
|
||||
let l = if rows.is_empty() && cols.is_empty() {
|
||||
let l = if row_levels == 0 && cols.is_empty() {
|
||||
0
|
||||
} else if compact {
|
||||
1
|
||||
} else {
|
||||
rows.len().max(1)
|
||||
row_levels.max(1)
|
||||
};
|
||||
let mut width = l + data_cols.len();
|
||||
if !shown_filters.is_empty() {
|
||||
@@ -829,20 +1049,33 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
if empty {
|
||||
let r = g.push_row(RowKind::Placeholder)?;
|
||||
g.set(r, 0, Value::text(format!("{} — choose fields", pt.name)), CellKind::Placeholder, 0, None);
|
||||
return Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset });
|
||||
return Ok(Output {
|
||||
width: g.width as u32,
|
||||
grid: g.rows,
|
||||
row_kinds: g.kinds,
|
||||
body_offset,
|
||||
chart_rows: vec![],
|
||||
chart_cols: vec![],
|
||||
label_col: None,
|
||||
});
|
||||
}
|
||||
|
||||
let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default();
|
||||
let headers_on = pt.show_headers;
|
||||
let row_header = |g: &mut Grid, r: usize| {
|
||||
if rows.is_empty() || !headers_on {
|
||||
if row_levels == 0 || !headers_on {
|
||||
return;
|
||||
}
|
||||
if compact {
|
||||
g.set(r, 0, Value::text("Row Labels"), CellKind::Header, 0, None);
|
||||
} else {
|
||||
for (i, f) in row_fields.iter().enumerate() {
|
||||
g.set(r, i, Value::text(f.source_col.as_str()), CellKind::Header, 0, None);
|
||||
// One column per row field, Σ Values ("Values") at its place.
|
||||
let mut names: Vec<&str> = row_fields.iter().map(|f| f.source_col.as_str()).collect();
|
||||
if let Some(p) = vpos {
|
||||
names.insert(p.min(names.len()), "Values");
|
||||
}
|
||||
for (i, name) in names.into_iter().enumerate() {
|
||||
g.set(r, i, Value::text(name), CellKind::Header, 0, None);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -852,8 +1085,11 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
let r = g.push_row(RowKind::Header)?;
|
||||
row_header(&mut g, r);
|
||||
for (j, (_, vi)) in data_cols.iter().enumerate() {
|
||||
if let Some(vi) = vi {
|
||||
g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None);
|
||||
match vi {
|
||||
Some(vi) => g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None),
|
||||
// Values on rows, no column field: the one data column is the grand total.
|
||||
None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -865,7 +1101,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() };
|
||||
g.set(cap, l, Value::text(caption), CellKind::Header, 0, None);
|
||||
}
|
||||
let levels = cols.len() + usize::from(k > 1);
|
||||
let levels = cols.len() + usize::from(k > 1 && !on_rows);
|
||||
let first_level = g.rows.len();
|
||||
for _ in 0..levels {
|
||||
g.push_row(RowKind::Header)?;
|
||||
@@ -915,8 +1151,21 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
|
||||
// ---- body
|
||||
let get = |rp: &[u32], cp: &[u32], vi: usize| -> Option<Value> {
|
||||
let (_, v) = vals.get(vi)?;
|
||||
aggs.get(&(rp.to_vec(), cp.to_vec())).and_then(|a| a.get(vi)).map(|a| a.result(v.func))
|
||||
let (vs, v) = vals.get(vi)?;
|
||||
let accs = aggs.get(&(rp.to_vec(), cp.to_vec()))?;
|
||||
match vs {
|
||||
ValSrc::Col(_) => accs.get(vi).map(|a| a.result(v.func)),
|
||||
ValSrc::Calc(i) => {
|
||||
let sum = |name: &str| -> Value {
|
||||
src.col(name)
|
||||
.and_then(|c| extra.iter().position(|x| *x == c))
|
||||
.and_then(|j| accs.get(k + j))
|
||||
.map(|a| a.result(PivotFunc::Sum))
|
||||
.unwrap_or(Value::Number(0.0))
|
||||
};
|
||||
Some(calc.value(wb, *i, &sum))
|
||||
}
|
||||
}
|
||||
};
|
||||
let num = |v: &Option<Value>| v.as_ref().and_then(Value::as_f64);
|
||||
let ratio = |a: Value, b: Option<Value>| -> Value {
|
||||
@@ -935,7 +1184,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
};
|
||||
let data_fmt: Vec<Option<String>> = vals
|
||||
.iter()
|
||||
.map(|(c, v)| match v.show_as {
|
||||
.map(|(vs, v)| match v.show_as {
|
||||
PivotShowAs::PercentOfGrandTotal | PivotShowAs::PercentOfColumnTotal | PivotShowAs::PercentOfRowTotal => {
|
||||
Some(v.number_format.clone().unwrap_or_else(|| "0.00%".into()))
|
||||
}
|
||||
@@ -943,12 +1192,44 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
_ => v.number_format.clone().or_else(|| match v.func {
|
||||
PivotFunc::Count | PivotFunc::CountNumbers => None,
|
||||
_ => {
|
||||
let f = fmt_of(*c);
|
||||
let f = match vs {
|
||||
ValSrc::Col(c) => fmt_of(*c),
|
||||
ValSrc::Calc(_) => "General".to_string(),
|
||||
};
|
||||
(f != "General").then_some(f)
|
||||
}
|
||||
}),
|
||||
})
|
||||
.collect();
|
||||
let mut chart_rows: Vec<u32> = Vec::new();
|
||||
let chart_cols: Vec<(u32, String)> = data_cols
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(j, (si, vi))| {
|
||||
let spec = specs.get(*si)?;
|
||||
if spec.kind != ColKind::Leaf {
|
||||
return None;
|
||||
}
|
||||
let mut parts: Vec<String> =
|
||||
spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.label(*it)).unwrap_or_default()).collect();
|
||||
if let Some(vi) = vi
|
||||
&& (k > 1 || parts.is_empty())
|
||||
{
|
||||
parts.push(val_name(*vi));
|
||||
} else if parts.is_empty() {
|
||||
parts.push("Total".into());
|
||||
}
|
||||
Some(((l + j) as u32, parts.join(" - ")))
|
||||
})
|
||||
.filter(|_| k > 0)
|
||||
.collect();
|
||||
let label_col = if row_levels == 0 {
|
||||
None
|
||||
} else if compact {
|
||||
Some(0)
|
||||
} else {
|
||||
Some(row_levels.saturating_sub(1) as u32)
|
||||
};
|
||||
for line in &lines {
|
||||
let rk = match line.kind {
|
||||
LineKind::Item(b) => RowKind::Item(b),
|
||||
@@ -961,6 +1242,9 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
LineKind::Grand => (CellKind::GrandTotal, CellKind::GrandTotal),
|
||||
};
|
||||
let r = g.push_row(rk)?;
|
||||
if line.leaf && k > 0 {
|
||||
chart_rows.push(r as u32);
|
||||
}
|
||||
for (c, v, indent, fmt) in &line.labels {
|
||||
g.set(r, *c, v.clone(), ck.0, *indent, fmt.clone());
|
||||
}
|
||||
@@ -968,8 +1252,9 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
continue;
|
||||
}
|
||||
let rp = line.path.as_slice();
|
||||
for (j, (si, vi)) in data_cols.iter().enumerate() {
|
||||
let (Some(spec), Some(vi)) = (specs.get(*si), vi) else { continue };
|
||||
for (j, (si, col_vi)) in data_cols.iter().enumerate() {
|
||||
let line_vi = col_vi.or(line.vi);
|
||||
let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue };
|
||||
let Some((_, vdef)) = vals.get(*vi) else { continue };
|
||||
let cp = spec.path.as_slice();
|
||||
let Some(raw) = get(rp, cp, *vi) else { continue };
|
||||
@@ -1015,7 +1300,7 @@ pub fn compute(wb: &Workbook, pt: &PivotTable, pivot_sheet: usize) -> Result<Out
|
||||
g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten());
|
||||
}
|
||||
}
|
||||
Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset })
|
||||
Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- styling and writing
|
||||
@@ -1205,9 +1490,106 @@ pub fn refresh(wb: &mut Workbook, sheet: usize, idx: usize, replace: bool) -> Re
|
||||
if let Some(p) = shm.pivots.get_mut(idx) {
|
||||
p.last_range = Some(area);
|
||||
}
|
||||
let sheet_name = shm.name.clone();
|
||||
rebind_charts(wb, &sheet_name, &pt.name, origin, &out);
|
||||
Ok(area)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- PivotCharts
|
||||
|
||||
/// The link a PivotChart stores to its PivotTable: `Sheet2!PivotTable1`.
|
||||
pub fn chart_link(sheet: &str, pivot: &str) -> String {
|
||||
format!("{}!{pivot}", quote_sheet(sheet))
|
||||
}
|
||||
|
||||
/// (sheet, PivotTable name) of a PivotChart link; a leading `[Book.xlsx]` is ignored.
|
||||
pub fn parse_chart_link(link: &str) -> Option<(String, String)> {
|
||||
let t = link.trim();
|
||||
let t = match t.strip_prefix('[') {
|
||||
Some(rest) => rest.split_once(']').map(|(_, r)| r).unwrap_or(rest),
|
||||
None => t,
|
||||
};
|
||||
let (sheet, name) = t.rsplit_once('!')?;
|
||||
let sheet = sheet.trim();
|
||||
let sheet = sheet.strip_prefix('\'').and_then(|x| x.strip_suffix('\'')).map(|x| x.replace("''", "'")).unwrap_or_else(|| sheet.to_string());
|
||||
let name = name.trim();
|
||||
if sheet.is_empty() || name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((sheet, name.to_string()))
|
||||
}
|
||||
|
||||
/// Whether a PivotChart link points at `pivot` on `sheet`.
|
||||
pub fn links_to(link: &str, sheet: &str, pivot: &str) -> bool {
|
||||
parse_chart_link(link).is_some_and(|(s, n)| s.eq_ignore_ascii_case(sheet) && n.eq_ignore_ascii_case(pivot))
|
||||
}
|
||||
|
||||
/// An absolute reference to `col` over grid `rows` (contiguous runs joined into a union).
|
||||
fn rows_ref(sheet: &str, origin: CellRef, col: u32, rows: &[u32]) -> Option<String> {
|
||||
let q = quote_sheet(sheet);
|
||||
let c = origin.col.checked_add(col)?;
|
||||
let letters = gridcraft_core::col_to_letters(c);
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
while let Some(&start) = rows.get(i) {
|
||||
let mut end = start;
|
||||
while rows.get(i + 1).is_some_and(|n| Some(*n) == end.checked_add(1)) {
|
||||
end += 1;
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
let (a, b) = (origin.row.checked_add(start)? + 1, origin.row.checked_add(end)? + 1);
|
||||
parts.push(if a == b { format!("{q}!${letters}${a}") } else { format!("{q}!${letters}${a}:${letters}${b}") });
|
||||
}
|
||||
match parts.len() {
|
||||
0 => None,
|
||||
1 => parts.pop(),
|
||||
_ => Some(format!("({})", parts.join(","))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Most category rows a PivotChart plots.
|
||||
const MAX_CHART_ROWS: usize = 10_000;
|
||||
|
||||
/// A PivotChart's series for a report written at `origin`: categories are the innermost row
|
||||
/// items, one series per item column (column items × value fields); totals are left out.
|
||||
pub fn chart_series(sheet: &str, origin: CellRef, out: &Output) -> Vec<Series> {
|
||||
let rows: Vec<u32> = out.chart_rows.iter().copied().take(MAX_CHART_ROWS).collect();
|
||||
let categories = out.label_col.and_then(|c| rows_ref(sheet, origin, c, &rows));
|
||||
out.chart_cols
|
||||
.iter()
|
||||
.filter_map(|(c, name)| {
|
||||
Some(Series {
|
||||
name: Some(format!("\"{}\"", name.replace('"', "\"\""))),
|
||||
categories: categories.clone(),
|
||||
values: rows_ref(sheet, origin, *c, &rows)?,
|
||||
bubble_sizes: None,
|
||||
color: None,
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rebuilds the series of every PivotChart of a PivotTable after its report was written.
|
||||
fn rebind_charts(wb: &mut Workbook, sheet: &str, pivot: &str, origin: CellRef, out: &Output) {
|
||||
let linked = |ch: &Chart| ch.pivot.as_deref().is_some_and(|l| links_to(l, sheet, pivot));
|
||||
let hits: Vec<usize> = (0..wb.sheets.len()).filter(|i| wb.sheet(*i).is_some_and(|sh| sh.charts.iter().any(linked))).collect();
|
||||
if hits.is_empty() {
|
||||
return;
|
||||
}
|
||||
let series = chart_series(sheet, origin, out);
|
||||
for i in hits {
|
||||
let Some(sh) = wb.sheet_mut(i) else { continue };
|
||||
for ch in sh.charts.iter_mut().filter(|c| linked(c)) {
|
||||
ch.series = series.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a pivot's last output area.
|
||||
pub fn clear_output(wb: &mut Workbook, sheet: usize, idx: usize) {
|
||||
let Some(shm) = wb.sheet_mut(sheet) else { return };
|
||||
@@ -1217,3 +1599,17 @@ pub fn clear_output(wb: &mut Workbook, sheet: usize, idx: usize) {
|
||||
p.last_range = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fit_tests {
|
||||
use super::data_cols_exceed_sheet;
|
||||
|
||||
#[test]
|
||||
fn column_budget_counts_value_fields_and_grand_total() {
|
||||
assert!(!data_cols_exceed_sheet(64, true, 128));
|
||||
assert!(data_cols_exceed_sheet(64, true, 256));
|
||||
assert!(!data_cols_exceed_sheet(64, false, 256));
|
||||
assert!(!data_cols_exceed_sheet(16_384, false, 0));
|
||||
assert!(data_cols_exceed_sheet(16_385, false, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
//! Calculated PivotTable fields: a formula over other fields (`=Sales*0.1`,
|
||||
//! `='Unit Price'*Units`, `=IF(Units>0,Sales/Units,0)`).
|
||||
//!
|
||||
//! As Microsoft documents for Excel, the formula operates on the *sums* of the fields it names
|
||||
//! for each report cell (items, subtotals and grand totals alike), not record by record: for
|
||||
//! `=Sales*1.2` a cell shows 1.2 × the sum of Sales of that cell's records. Fields are written
|
||||
//! bare (`Sales`) or in single quotes (`'Unit Price'`); cell references and defined names are not
|
||||
//! allowed. A calculated field may use other calculated fields; a cycle evaluates to `#REF!`.
|
||||
|
||||
use gridcraft_core::{CellError, CellRef, Value};
|
||||
use gridcraft_formula::Expr;
|
||||
use gridcraft_model::{PivotTable, Workbook};
|
||||
|
||||
/// Longest formula accepted.
|
||||
pub const MAX_FORMULA_LEN: usize = 8_192;
|
||||
/// Most calculated fields per PivotTable.
|
||||
pub const MAX_CALC_FIELDS: usize = 256;
|
||||
/// Deepest chain of calculated fields using calculated fields.
|
||||
const MAX_DEPTH: usize = 64;
|
||||
const PREFIX: &str = "__pcf";
|
||||
|
||||
fn placeholder(i: usize) -> String {
|
||||
format!("{PREFIX}{i}")
|
||||
}
|
||||
|
||||
/// A parsed formula: field names replaced by placeholder names `__pcf0`, `__pcf1`, … in the
|
||||
/// order of `refs`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Compiled {
|
||||
pub body: Expr,
|
||||
/// Canonical names of the fields used.
|
||||
pub refs: Vec<String>,
|
||||
}
|
||||
|
||||
/// Parses a calculated-field formula. `field` maps a written name to the canonical name of a
|
||||
/// source or calculated field.
|
||||
pub fn compile(formula: &str, field: &dyn Fn(&str) -> Option<String>) -> Result<Compiled, String> {
|
||||
let text = formula.trim();
|
||||
let text = text.strip_prefix('=').unwrap_or(text).trim();
|
||||
if text.is_empty() {
|
||||
return Err("The formula is empty.".into());
|
||||
}
|
||||
if text.len() > MAX_FORMULA_LEN {
|
||||
return Err("The formula is too long.".into());
|
||||
}
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let at = |i: usize| chars.get(i).copied();
|
||||
let mut out = String::with_capacity(text.len() + 16);
|
||||
let mut refs: Vec<String> = Vec::new();
|
||||
let slot = |name: String, refs: &mut Vec<String>| -> String {
|
||||
let i = refs.iter().position(|r| r.eq_ignore_ascii_case(&name)).unwrap_or_else(|| {
|
||||
refs.push(name);
|
||||
refs.len() - 1
|
||||
});
|
||||
placeholder(i)
|
||||
};
|
||||
let mut i = 0;
|
||||
while let Some(c) = at(i) {
|
||||
match c {
|
||||
'"' => {
|
||||
out.push('"');
|
||||
i += 1;
|
||||
loop {
|
||||
match at(i) {
|
||||
None => return Err("The formula has an unterminated text value.".into()),
|
||||
Some('"') if at(i + 1) == Some('"') => {
|
||||
out.push_str("\"\"");
|
||||
i += 2;
|
||||
}
|
||||
Some('"') => {
|
||||
out.push('"');
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
Some(x) => {
|
||||
out.push(x);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
'\'' => {
|
||||
let mut name = String::new();
|
||||
i += 1;
|
||||
loop {
|
||||
match at(i) {
|
||||
None => return Err("The formula has an unterminated field name.".into()),
|
||||
Some('\'') if at(i + 1) == Some('\'') => {
|
||||
name.push('\'');
|
||||
i += 2;
|
||||
}
|
||||
Some('\'') => {
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
Some(x) => {
|
||||
name.push(x);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let canon = field(&name).ok_or_else(|| format!("There's no field named '{name}'."))?;
|
||||
out.push_str(&slot(canon, &mut refs));
|
||||
}
|
||||
c if c.is_ascii_digit() || (c == '.' && at(i + 1).is_some_and(|d| d.is_ascii_digit())) => {
|
||||
while at(i).is_some_and(|d| d.is_ascii_digit() || d == '.') {
|
||||
out.push(at(i).unwrap_or('0'));
|
||||
i += 1;
|
||||
}
|
||||
if matches!(at(i), Some('e' | 'E')) {
|
||||
let sign = usize::from(matches!(at(i + 1), Some('+' | '-')));
|
||||
if at(i + 1 + sign).is_some_and(|d| d.is_ascii_digit()) {
|
||||
for _ in 0..=sign {
|
||||
out.push(at(i).unwrap_or('0'));
|
||||
i += 1;
|
||||
}
|
||||
while at(i).is_some_and(|d| d.is_ascii_digit()) {
|
||||
out.push(at(i).unwrap_or('0'));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c if c.is_alphabetic() || c == '_' => {
|
||||
let start = i;
|
||||
while at(i).is_some_and(|d| d.is_alphanumeric() || d == '_' || d == '.') {
|
||||
i += 1;
|
||||
}
|
||||
let word: String = chars.get(start..i).map(|w| w.iter().collect()).unwrap_or_default();
|
||||
let mut j = i;
|
||||
while at(j).is_some_and(char::is_whitespace) {
|
||||
j += 1;
|
||||
}
|
||||
let is_call = at(j) == Some('(');
|
||||
match field(&word) {
|
||||
Some(canon) if !is_call => out.push_str(&slot(canon, &mut refs)),
|
||||
_ => out.push_str(&word),
|
||||
}
|
||||
}
|
||||
c => {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let body = gridcraft_formula::parse(&out).map_err(|_| "The formula contains an error.".to_string())?;
|
||||
let mut problem: Option<String> = None;
|
||||
body.walk(&mut |e| {
|
||||
if problem.is_some() {
|
||||
return;
|
||||
}
|
||||
match e {
|
||||
Expr::Name(n) if n.starts_with(PREFIX) => {}
|
||||
Expr::Name(n) => problem = Some(format!("There's no field named '{n}'.")),
|
||||
Expr::Ref(_) | Expr::Struct(_) => problem = Some("A calculated field can't refer to cells or tables; use field names.".into()),
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
match problem {
|
||||
Some(p) => Err(p),
|
||||
None => Ok(Compiled { body, refs }),
|
||||
}
|
||||
}
|
||||
|
||||
fn literal(v: &Value) -> Expr {
|
||||
match v {
|
||||
Value::Number(n) => Expr::Number(*n),
|
||||
Value::Error(e) => Expr::Error(*e),
|
||||
Value::Text(t) => Expr::Text(t.clone()),
|
||||
Value::Bool(b) => Expr::Bool(*b),
|
||||
Value::Empty => Expr::Number(0.0),
|
||||
Value::Array(_) => literal(&v.scalar()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a compiled formula with the given field values (in `refs` order).
|
||||
pub fn eval(wb: &Workbook, c: &Compiled, args: &[Value]) -> Value {
|
||||
let expr = if c.refs.is_empty() {
|
||||
c.body.clone()
|
||||
} else {
|
||||
let mut call = Vec::with_capacity(c.refs.len() * 2 + 1);
|
||||
for i in 0..c.refs.len() {
|
||||
call.push(Expr::Name(placeholder(i)));
|
||||
call.push(literal(args.get(i).unwrap_or(&Value::Empty)));
|
||||
}
|
||||
call.push(c.body.clone());
|
||||
Expr::Call("LET".into(), call)
|
||||
};
|
||||
match gridcraft_calc::recalc::evaluate_expr(wb, 0, CellRef::default(), &expr).scalar() {
|
||||
Value::Empty => Value::Number(0.0),
|
||||
v => v,
|
||||
}
|
||||
}
|
||||
|
||||
/// A PivotTable's calculated fields, compiled against its source headers.
|
||||
pub struct CalcSet {
|
||||
names: Vec<String>,
|
||||
compiled: Vec<Result<Compiled, String>>,
|
||||
}
|
||||
|
||||
impl CalcSet {
|
||||
pub fn new(pt: &PivotTable, headers: &[String]) -> CalcSet {
|
||||
let names: Vec<String> = pt.calculated_fields.iter().take(MAX_CALC_FIELDS).map(|c| c.name.clone()).collect();
|
||||
let lookup = |n: &str| -> Option<String> {
|
||||
let n = n.trim();
|
||||
headers.iter().chain(names.iter()).find(|h| h.trim().eq_ignore_ascii_case(n)).cloned()
|
||||
};
|
||||
let compiled = pt.calculated_fields.iter().take(MAX_CALC_FIELDS).map(|c| compile(&c.formula, &lookup)).collect();
|
||||
CalcSet { names, compiled }
|
||||
}
|
||||
|
||||
pub fn index(&self, name: &str) -> Option<usize> {
|
||||
self.names.iter().position(|n| n.eq_ignore_ascii_case(name.trim()))
|
||||
}
|
||||
|
||||
/// The compile error of a calculated field, if any.
|
||||
pub fn error(&self, i: usize) -> Option<&str> {
|
||||
self.compiled.get(i).and_then(|c| c.as_ref().err()).map(String::as_str)
|
||||
}
|
||||
|
||||
/// Source fields a calculated field needs, directly or through other calculated fields.
|
||||
pub fn source_refs(&self, i: usize) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut seen = vec![false; self.names.len()];
|
||||
let mut stack = vec![i];
|
||||
while let Some(j) = stack.pop() {
|
||||
if !seen.get(j).copied().unwrap_or(true) {
|
||||
if let Some(s) = seen.get_mut(j) {
|
||||
*s = true;
|
||||
}
|
||||
if let Some(Ok(c)) = self.compiled.get(j) {
|
||||
for r in &c.refs {
|
||||
match self.index(r) {
|
||||
Some(k) => stack.push(k),
|
||||
None => {
|
||||
if !out.iter().any(|o| o.eq_ignore_ascii_case(r)) {
|
||||
out.push(r.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a calculated field reaches itself through the fields it uses.
|
||||
pub fn is_cyclic(&self, i: usize) -> bool {
|
||||
let mut seen = vec![false; self.names.len()];
|
||||
let mut stack: Vec<usize> = match self.compiled.get(i) {
|
||||
Some(Ok(c)) => c.refs.iter().filter_map(|r| self.index(r)).collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
while let Some(j) = stack.pop() {
|
||||
if j == i {
|
||||
return true;
|
||||
}
|
||||
if seen.get(j).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = seen.get_mut(j) {
|
||||
*s = true;
|
||||
}
|
||||
if let Some(Ok(c)) = self.compiled.get(j) {
|
||||
stack.extend(c.refs.iter().filter_map(|r| self.index(r)));
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The value of calculated field `i` for one report cell; `sum` gives a source field's sum
|
||||
/// over that cell's records.
|
||||
pub fn value(&self, wb: &Workbook, i: usize, sum: &dyn Fn(&str) -> Value) -> Value {
|
||||
let mut memo: Vec<Option<Value>> = vec![None; self.names.len()];
|
||||
let mut active = vec![false; self.names.len()];
|
||||
self.value_in(wb, i, sum, &mut memo, &mut active, 0)
|
||||
}
|
||||
|
||||
fn value_in(&self, wb: &Workbook, i: usize, sum: &dyn Fn(&str) -> Value, memo: &mut [Option<Value>], active: &mut [bool], depth: usize) -> Value {
|
||||
if let Some(Some(v)) = memo.get(i) {
|
||||
return v.clone();
|
||||
}
|
||||
if depth > MAX_DEPTH || active.get(i).copied().unwrap_or(true) {
|
||||
return Value::Error(CellError::Ref);
|
||||
}
|
||||
let Some(Ok(c)) = self.compiled.get(i) else { return Value::Error(CellError::Name) };
|
||||
if let Some(a) = active.get_mut(i) {
|
||||
*a = true;
|
||||
}
|
||||
let args: Vec<Value> = c
|
||||
.refs
|
||||
.iter()
|
||||
.map(|r| match self.index(r) {
|
||||
Some(j) => self.value_in(wb, j, sum, memo, active, depth + 1),
|
||||
None => sum(r),
|
||||
})
|
||||
.collect();
|
||||
let v = eval(wb, c, &args);
|
||||
if let Some(a) = active.get_mut(i) {
|
||||
*a = false;
|
||||
}
|
||||
if let Some(m) = memo.get_mut(i) {
|
||||
*m = Some(v.clone());
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fields(n: &str) -> Option<String> {
|
||||
["Sales", "Units", "Unit Price", "Q1"].iter().find(|f| f.eq_ignore_ascii_case(n)).map(|f| f.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compiles_field_names() {
|
||||
let c = compile("= Sales*0.1 + 'Unit Price'/units - Sales", &fields).unwrap();
|
||||
assert_eq!(c.refs, vec!["Sales", "Unit Price", "Units"]);
|
||||
// A field named like a cell reference is still a field; functions stay functions.
|
||||
let c = compile("=ROUND(Q1*1.5E2,0)", &fields).unwrap();
|
||||
assert_eq!(c.refs, vec!["Q1"]);
|
||||
let wb = Workbook::new();
|
||||
assert_eq!(eval(&wb, &c, &[Value::Number(2.0)]), Value::Number(300.0));
|
||||
assert!(compile("=Sales*Bogus", &fields).unwrap_err().contains("Bogus"));
|
||||
assert!(compile("=A1*2", &fields).is_err());
|
||||
assert!(compile("='Nope'*2", &fields).is_err());
|
||||
assert!(compile("=Sales*(", &fields).is_err());
|
||||
assert!(compile("=", &fields).is_err());
|
||||
assert!(compile(&format!("={}", "1+".repeat(MAX_FORMULA_LEN)), &fields).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_and_cyclic_chains_are_bounded() {
|
||||
// 300 calculated fields, each using the previous one, and a two-field cycle.
|
||||
let mut pt = PivotTable::default();
|
||||
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: "C0".into(), formula: "=Sales+1".into() });
|
||||
for i in 1..300 {
|
||||
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: format!("C{i}"), formula: format!("=C{}+1", i - 1) });
|
||||
}
|
||||
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: "P".into(), formula: "=Q".into() });
|
||||
pt.calculated_fields.push(gridcraft_model::PivotCalcField { name: "Q".into(), formula: "=P*2".into() });
|
||||
let set = CalcSet::new(&pt, &["Sales".to_string()]);
|
||||
let wb = Workbook::new();
|
||||
let sum = |_: &str| Value::Number(10.0);
|
||||
assert_eq!(set.value(&wb, 0, &sum), Value::Number(11.0));
|
||||
assert_eq!(set.value(&wb, 10, &sum), Value::Number(21.0));
|
||||
// Past the depth bound (the list itself is capped at MAX_CALC_FIELDS).
|
||||
assert_eq!(set.value(&wb, 200, &sum), Value::Error(CellError::Ref));
|
||||
assert_eq!(set.index("P"), None, "P is past the cap of {MAX_CALC_FIELDS} fields");
|
||||
// A small cycle within the cap.
|
||||
let mut small = PivotTable::default();
|
||||
small.calculated_fields.push(gridcraft_model::PivotCalcField { name: "P".into(), formula: "=Q".into() });
|
||||
small.calculated_fields.push(gridcraft_model::PivotCalcField { name: "Q".into(), formula: "=P*2".into() });
|
||||
let set = CalcSet::new(&small, &["Sales".to_string()]);
|
||||
assert!(set.is_cyclic(0));
|
||||
assert_eq!(set.value(&wb, 0, &sum), Value::Error(CellError::Ref));
|
||||
assert_eq!(set.source_refs(0), Vec::<String>::new());
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,7 @@ fn sales(s: &mut Session) -> bool {
|
||||
secondary: false,
|
||||
kind: None,
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +43,13 @@ impl Selection {
|
||||
pub fn is_single_cell(&self) -> bool {
|
||||
self.ranges.len() == 1 && self.current().is_single()
|
||||
}
|
||||
/// The corner of the current area opposite the anchor: the end that Shift+arrows move.
|
||||
pub fn moving_end(&self) -> CellRef {
|
||||
let r = self.current();
|
||||
let row = if self.anchor.row == r.start.row { r.end.row } else { r.start.row };
|
||||
let col = if self.anchor.col == r.start.col { r.end.col } else { r.start.col };
|
||||
CellRef::new(row, col)
|
||||
}
|
||||
/// Extends the current area from the anchor to `to` (Shift+click / Shift+arrows).
|
||||
pub fn extend_to(&mut self, to: CellRef) {
|
||||
let r = RangeRef::new(self.anchor, to);
|
||||
|
||||
@@ -176,8 +176,15 @@ pub(crate) fn sync_headers(cx: &mut crate::cmd::Ctx) {
|
||||
let Some(t) = sh.tables.get(ti) else { continue };
|
||||
let col = (c.col - t.range.start.col) as usize;
|
||||
let Some(old) = t.columns.get(col).map(|x| x.name.clone()) else { continue };
|
||||
let text = crate::display::cell_text(&cx.wb, sh, c);
|
||||
let is_text = sh.value(c).is_text();
|
||||
// A text header names its column as it is: a number format only changes how it looks (an
|
||||
// accounting format pads text with spaces), and the file writes the name into the cell.
|
||||
let value = sh.value(c);
|
||||
let text = match value.as_text() {
|
||||
Some(t) => t.to_string(),
|
||||
None => crate::display::cell_text(&cx.wb, sh, c),
|
||||
};
|
||||
// Headers hold constant text: a formula (or a spilled value) there becomes its text.
|
||||
let is_text = value.is_text() && sh.cell(c).is_some_and(|x| x.formula.is_none());
|
||||
if text == old && is_text {
|
||||
continue;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,102 @@
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn table() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1", "values":[["Quarterly Revenue"], ["1"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"A1:A2", "header":true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn fit(s: &mut Session) -> f32 {
|
||||
s.execute("home.autofitColumnWidth", json!({"cols":"A:A"})).unwrap();
|
||||
s.doc().unwrap().wb.active().unwrap().col_width(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_reserves_room_for_table_filter_button() {
|
||||
let mut s = table();
|
||||
s.execute("selection.set", json!({"cell":"A1"})).unwrap();
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
let plain = fit(&mut s);
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
let filtered = fit(&mut s);
|
||||
assert!(filtered >= plain + 16.0, "filter button obscures heading: plain={plain}, filtered={filtered}");
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)).display(), "Quarterly Revenue");
|
||||
}
|
||||
|
||||
fn sheet_mut(s: &mut Session) -> &mut gridcraft_engine::model::Sheet {
|
||||
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb).sheet_mut(0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_skips_disabled_buttons_and_hidden_table_headers() {
|
||||
let mut s = table();
|
||||
sheet_mut(&mut s).tables[0].filter_button = false;
|
||||
let plain = fit(&mut s);
|
||||
sheet_mut(&mut s).tables[0].filter_button = true;
|
||||
sheet_mut(&mut s).tables[0].header_row = false;
|
||||
assert_eq!(fit(&mut s), plain);
|
||||
sheet_mut(&mut s).tables[0].header_row = true;
|
||||
assert!(fit(&mut s) > plain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_matches_excel_filter_allowance_across_zoom_and_row_heights() {
|
||||
for (zoom, allowance) in [(50, 12.5 * 96.0 / 72.0 * 2.0), (100, 12.5 * 96.0 / 72.0), (200, 12.5 * 96.0 / 72.0)] {
|
||||
for height in [12.0_f32, 20.0, 60.0] {
|
||||
let mut s = table();
|
||||
s.execute("view.zoom", json!({"percent":zoom})).unwrap();
|
||||
s.execute("home.rowHeight", json!({"rows":"1:1", "height":height})).unwrap();
|
||||
sheet_mut(&mut s).tables[0].filter_button = false;
|
||||
let plain = fit(&mut s);
|
||||
sheet_mut(&mut s).tables[0].filter_button = true;
|
||||
let filtered = fit(&mut s);
|
||||
assert!((filtered - plain - allowance).abs() < 1.0, "zoom={zoom}, height={height}, plain={plain}, filtered={filtered}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_supports_ordinary_autofilters_without_double_counting_table_buttons() {
|
||||
let mut s = table();
|
||||
let table_width = fit(&mut s);
|
||||
sheet_mut(&mut s).autofilter =
|
||||
Some(gridcraft_engine::model::AutoFilter { range: gridcraft_engine::core::RangeRef::parse("A1:A2").unwrap(), criteria: vec![] });
|
||||
assert_eq!(fit(&mut s), table_width, "overlapping filters occupy one button slot");
|
||||
sheet_mut(&mut s).tables.clear();
|
||||
assert_eq!(fit(&mut s), table_width, "ordinary filter headers reserve the same space");
|
||||
sheet_mut(&mut s).autofilter = None;
|
||||
assert!(fit(&mut s) < table_width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_leaves_longer_body_cells_and_unfiltered_columns_unchanged() {
|
||||
let mut s = table();
|
||||
s.execute("cell.set", json!({"cell":"A2", "input":"A body value much longer than the short table header above"})).unwrap();
|
||||
let filtered = fit(&mut s);
|
||||
sheet_mut(&mut s).tables[0].filter_button = false;
|
||||
assert_eq!(fit(&mut s), filtered);
|
||||
s.execute("cell.set", json!({"cell":"B1", "input":"Quarterly Revenue"})).unwrap();
|
||||
s.execute("home.autofitColumnWidth", json!({"cols":"B:B"})).unwrap();
|
||||
let plain = s.doc().unwrap().wb.active().unwrap().col_width(1);
|
||||
sheet_mut(&mut s).tables[0].filter_button = true;
|
||||
s.execute("home.autofitColumnWidth", json!({"cols":"B:B"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().col_width(1), plain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_filter_width_is_undoable_without_changing_selection() {
|
||||
let mut s = table();
|
||||
s.execute("home.columnWidth", json!({"cols":"A:A", "width":80})).unwrap();
|
||||
s.execute("selection.set", json!({"range":"A:A"})).unwrap();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
s.active_mut().unwrap().undo.clear();
|
||||
fit(&mut s);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
assert_eq!(s.doc().unwrap().undo.len(), 1);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().col_width(0), 80.0);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
//! CSV and TSV export is capped: two cells far apart in a sheet would otherwise make a file as
|
||||
//! big as the whole rectangle between them. A refused export is an error and writes nothing.
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn two_far_cells() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "a"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "XFD1048576", "input": "b"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sparse_sheet_spanning_the_grid_is_refused_not_expanded() {
|
||||
let mut s = two_far_cells();
|
||||
for format in ["csv", "tsv"] {
|
||||
let err = s.execute("file.saveBytes", json!({"format": format})).unwrap_err().to_string();
|
||||
assert!(err.contains("1048576 rows by 16384 columns") && err.contains("MiB"), "{format}: {err}");
|
||||
}
|
||||
// Save As and Export write no file, and the document stays as it was.
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-csv-budget-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("big.csv");
|
||||
let err = s.execute("file.exportCsv", json!({"path": path.to_str().unwrap()})).unwrap_err().to_string();
|
||||
assert!(err.contains("over the limit"), "{err}");
|
||||
assert!(!path.exists(), "nothing is written for a refused export");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
// Other formats are unaffected, and so is a small export from the same session.
|
||||
assert!(s.execute("file.saveBytes", json!({"format": "xlsx"})).is_ok());
|
||||
s.execute("cell.set", json!({"cell": "XFD1048576", "input": ""})).unwrap();
|
||||
assert_eq!(s.execute("file.saveBytes", json!({"format": "csv"})).unwrap()["bytes"], 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_below_the_cap_keep_their_positions() {
|
||||
for (corner, bytes) in [("C3", 14), ("Z10", 272), ("XFD8", 131_082)] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "a"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": corner, "input": "b"})).unwrap();
|
||||
assert_eq!(s.execute("file.saveBytes", json!({"format": "csv"})).unwrap()["bytes"], bytes, "{corner}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn freeze(s: &Session) -> Option<(u32, u32)> {
|
||||
s.doc().unwrap().wb.active().unwrap().freeze
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn showing_a_custom_view_restores_its_frozen_panes() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("view.freezePanes", json!({"cell": "B2"})).unwrap();
|
||||
s.execute("view.customViews", json!({"save": "Frozen"})).unwrap();
|
||||
s.execute("view.unfreezePanes", json!({})).unwrap();
|
||||
assert_eq!(freeze(&s), None);
|
||||
s.execute("view.customViews", json!({"show": "Frozen"})).unwrap();
|
||||
assert_eq!(freeze(&s), Some((1, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn showing_an_unfrozen_custom_view_clears_current_panes() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("view.customViews", json!({"save": "Plain"})).unwrap();
|
||||
s.execute("view.freezePanes", json!({"cell": "B2"})).unwrap();
|
||||
s.execute("view.customViews", json!({"show": "Plain"})).unwrap();
|
||||
assert_eq!(freeze(&s), None);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS};
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn selection_move_clamps_extreme_displacements() {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
for (dr, dc, expected) in [
|
||||
(i64::MAX, 0, CellRef::new(MAX_ROWS - 1, 1)),
|
||||
(0, i64::MAX, CellRef::new(1, MAX_COLS - 1)),
|
||||
(i64::MAX, i64::MAX, CellRef::new(MAX_ROWS - 1, MAX_COLS - 1)),
|
||||
(i64::MIN, i64::MIN, CellRef::new(0, 0)),
|
||||
(i64::MAX, i64::MIN, CellRef::new(MAX_ROWS - 1, 0)),
|
||||
(i64::MIN, i64::MAX, CellRef::new(0, MAX_COLS - 1)),
|
||||
(2, -1, CellRef::new(3, 0)),
|
||||
] {
|
||||
session.execute("selection.set", json!({"cell": "B2"})).unwrap();
|
||||
session.execute("selection.move", json!({"dr": dr, "dc": dc})).unwrap();
|
||||
assert_eq!(session.doc().unwrap().selection.active, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_move_from_a_merged_cell_clamps_extreme_displacements() {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("selection.set", json!({"range": "B2:C3"})).unwrap();
|
||||
session.execute("home.mergeCells", json!({})).unwrap();
|
||||
for (dr, dc, expected) in [
|
||||
(i64::MAX, 0, CellRef::new(MAX_ROWS - 1, 1)),
|
||||
(0, i64::MAX, CellRef::new(1, MAX_COLS - 1)),
|
||||
(4_294_967_297, 0, CellRef::new(MAX_ROWS - 1, 1)),
|
||||
(1, 0, CellRef::new(3, 1)),
|
||||
] {
|
||||
session.execute("selection.set", json!({"cell": "B2"})).unwrap();
|
||||
session.execute("selection.move", json!({"dr": dr, "dc": dc})).unwrap();
|
||||
assert_eq!(session.doc().unwrap().selection.active, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Native ink remains editable after XLSX saves, including a save after an unrelated cell edit.
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::cmd::draw::{ink_points, ink_width};
|
||||
use gridcraft_engine::core::{CellRef, Value};
|
||||
use gridcraft_engine::model::{Shape, ShapeKind};
|
||||
use serde_json::json;
|
||||
|
||||
fn workbook() -> Session {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session
|
||||
}
|
||||
|
||||
fn reopen(session: &mut Session) -> Session {
|
||||
let saved = session.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
let mut reopened = Session::new();
|
||||
reopened.execute("file.open", json!({"name": "ink.xlsx", "base64": saved["base64"]})).unwrap();
|
||||
reopened
|
||||
}
|
||||
|
||||
fn shapes(session: &Session) -> &[Shape] {
|
||||
&session.doc().unwrap().wb.active().unwrap().shapes
|
||||
}
|
||||
|
||||
fn assert_anchor(actual: &Shape, expected: &Shape) {
|
||||
assert_eq!(actual.anchor.cell, expected.anchor.cell);
|
||||
assert_eq!(actual.anchor.mode, expected.anchor.mode);
|
||||
for (name, actual, expected) in [
|
||||
("dx", actual.anchor.dx, expected.anchor.dx),
|
||||
("dy", actual.anchor.dy, expected.anchor.dy),
|
||||
("width", actual.anchor.width, expected.anchor.width),
|
||||
("height", actual.anchor.height, expected.anchor.height),
|
||||
] {
|
||||
assert!((actual - expected).abs() < 0.001, "anchor {name}: {actual} != {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_ink(actual: &Shape, expected: &Shape) {
|
||||
assert_eq!(actual.kind, ShapeKind::Ink);
|
||||
let actual_points = ink_points(actual);
|
||||
let expected_points = ink_points(expected);
|
||||
assert_eq!(actual_points.len(), expected_points.len());
|
||||
for (actual, expected) in actual_points.iter().zip(&expected_points) {
|
||||
for axis in 0..2 {
|
||||
// DrawingML quantizes coordinates to integer EMUs (9,525 per model unit).
|
||||
assert!((actual[axis] - expected[axis]).abs() < 0.001, "point {actual:?} != {expected:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(actual.line, expected.line);
|
||||
assert_eq!(ink_width(actual), ink_width(expected));
|
||||
assert_anchor(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ink_geometry_and_style_survive_two_saves_and_a_cell_edit() {
|
||||
let mut session = workbook();
|
||||
session
|
||||
.execute("draw.stroke", json!({"points": [[130.5, 45.25], [172.5, 86.25], [151.5, 112.25], [215.5, 59.25]], "color": "#A12BCD", "width": 3}))
|
||||
.unwrap();
|
||||
session
|
||||
.execute("draw.stroke", json!({"points": [[300, 180], [360, 180], [360, 230], [300, 230], [300, 180]], "color": "#16843B", "width": 7}))
|
||||
.unwrap();
|
||||
let expected = shapes(&session).to_vec();
|
||||
assert_eq!(expected.len(), 2);
|
||||
|
||||
for pass in 0..2 {
|
||||
session = reopen(&mut session);
|
||||
assert_eq!(shapes(&session).len(), expected.len());
|
||||
for (actual, expected) in shapes(&session).iter().zip(&expected) {
|
||||
assert_ink(actual, expected);
|
||||
}
|
||||
if pass == 0 {
|
||||
session.execute("cell.set", json!({"cell": "Z30", "input": "42"})).unwrap();
|
||||
}
|
||||
}
|
||||
assert_eq!(session.doc().unwrap().wb.active().unwrap().value(CellRef::parse("Z30").unwrap()), Value::Number(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopened_ink_can_still_be_converted_to_a_shape() {
|
||||
for (points, expected_kind, expected_name) in [
|
||||
(vec![[100, 100], [200, 100], [200, 180], [100, 180], [100, 100]], ShapeKind::Rectangle, "Rectangle"),
|
||||
(vec![[100, 100], [140, 110], [220, 130]], ShapeKind::Line, "Line"),
|
||||
] {
|
||||
let mut session = workbook();
|
||||
session.execute("draw.stroke", json!({"points": points, "color": "#A12BCD", "width": 5})).unwrap();
|
||||
let original = shapes(&session)[0].clone();
|
||||
session = reopen(&mut session);
|
||||
let id = shapes(&session)[0].id;
|
||||
let converted = session.execute("draw.inkToShape", json!({"id": id})).unwrap();
|
||||
assert_eq!(converted["kind"], expected_name);
|
||||
let shape = &shapes(&session)[0];
|
||||
assert_eq!(shape.kind, expected_kind);
|
||||
assert_eq!(shape.line, original.line);
|
||||
assert!(shape.text.is_empty());
|
||||
assert_anchor(shape, &original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_shape_text_is_not_mistaken_for_ink_points() {
|
||||
let mut session = workbook();
|
||||
session
|
||||
.execute(
|
||||
"insert.shape",
|
||||
json!({"kind": "rectangle", "at": "D6", "width": 120, "height": 60, "fill": "#112233", "line": "#A12BCD", "text": "0.0,0.0;50.0,20.0"}),
|
||||
)
|
||||
.unwrap();
|
||||
let original = shapes(&session)[0].clone();
|
||||
for _ in 0..2 {
|
||||
session = reopen(&mut session);
|
||||
assert_eq!(shapes(&session).len(), 1);
|
||||
let shape = &shapes(&session)[0];
|
||||
assert_eq!(shape.kind, ShapeKind::Rectangle);
|
||||
assert_eq!(shape.text, original.text);
|
||||
assert_eq!(shape.fill, original.fill);
|
||||
assert_eq!(shape.line, original.line);
|
||||
assert_anchor(shape, &original);
|
||||
assert!(session.execute("draw.inkToShape", json!({})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_vertical_and_signed_highlighter_strokes_survive_reopening() {
|
||||
for points in [vec![[25.1, 50.2], [140.3, 50.2]], vec![[40.2, 10.1], [40.2, 100.3]], vec![[-12.3, -4.2], [20.1, 10.2], [80.3, -1.4]]] {
|
||||
let mut session = workbook();
|
||||
session.execute("draw.stroke", json!({"points": points, "color": "#16843B", "width": 12})).unwrap();
|
||||
let expected = shapes(&session)[0].clone();
|
||||
for _ in 0..2 {
|
||||
session = reopen(&mut session);
|
||||
assert_ink(&shapes(&session)[0], &expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use gridcraft_engine::{EngineError, Session};
|
||||
use serde_json::json;
|
||||
|
||||
fn new_session() -> Session {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_with_an_out_of_range_count_is_a_normal_error() {
|
||||
for (id, key, at) in [("home.insertRows", "rows", "3:3"), ("home.insertColumns", "cols", "C:C")] {
|
||||
let mut session = new_session();
|
||||
let err = session.execute(id, json!({ key: at, "count": u32::MAX })).unwrap_err();
|
||||
assert!(matches!(err, EngineError::BadParams { .. }), "{id}: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_after_a_formatted_line_with_an_out_of_range_count_is_a_normal_error() {
|
||||
// A custom size on the preceding line and no cells: the used-range guard has nothing to check.
|
||||
let mut session = new_session();
|
||||
session.execute("home.rowHeight", json!({"rows": "2:2", "height": 30})).unwrap();
|
||||
let err = session.execute("home.insertRows", json!({"rows": "3:3", "count": u32::MAX})).unwrap_err();
|
||||
assert!(matches!(err, EngineError::BadParams { .. }), "{err:?}");
|
||||
|
||||
let mut session = new_session();
|
||||
session.execute("home.columnWidth", json!({"cols": "B:B", "width": 100})).unwrap();
|
||||
let err = session.execute("home.insertColumns", json!({"cols": "C:C", "count": u32::MAX})).unwrap_err();
|
||||
assert!(matches!(err, EngineError::BadParams { .. }), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_with_an_out_of_range_count_does_not_panic() {
|
||||
for (id, key, at) in [("home.deleteRows", "rows", "3:3"), ("home.deleteColumns", "cols", "C:C")] {
|
||||
let mut session = new_session();
|
||||
let res = session.execute(id, json!({ key: at, "count": u32::MAX }));
|
||||
assert!(!matches!(res, Err(EngineError::Internal(..))), "{id}: {res:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_and_delete_with_a_small_count_still_work() {
|
||||
let mut session = new_session();
|
||||
session.execute("home.insertRows", json!({"rows": "1:1", "count": 3})).unwrap();
|
||||
session.execute("home.deleteRows", json!({"rows": "1:1", "count": 3})).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use gridcraft_core::{CellError, CellRef, Value};
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn cell_set_offset_extreme_arguments_return_ref() {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
for formula in [
|
||||
"=OFFSET(B2,1E300,0)",
|
||||
"=OFFSET(B2,0,1E300)",
|
||||
"=OFFSET(B2,0,0,1E300,1)",
|
||||
"=OFFSET(B2,0,0,1,1E300)",
|
||||
"=OFFSET(B2,-1E300,0)",
|
||||
"=OFFSET(B2,0,-1E300)",
|
||||
"=OFFSET(B2,0,0,-1E300,1)",
|
||||
"=OFFSET(B2,0,0,1,-1E300)",
|
||||
"=OFFSET(B2,1E300,0,-1E300,1)",
|
||||
"=OFFSET(B2,0,1E300,1,-1E300)",
|
||||
] {
|
||||
session.execute("cell.set", json!({"cell": "D1", "input": formula})).unwrap();
|
||||
assert_eq!(session.doc().unwrap().wb.sheet(0).unwrap().value(CellRef::new(0, 3)), Value::Error(CellError::Ref), "{formula}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Whole-row and whole-column formatting must re-fit row heights (issue #833).
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
fn sheet_mut(s: &mut gridcraft_engine::Session) -> &mut gridcraft_engine::model::Sheet {
|
||||
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb).sheet_mut(0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_row_font_format_grows_row_height_and_undoes() {
|
||||
let mut s = gridcraft_engine::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A5", "values": [["plain big bold"]]})).unwrap();
|
||||
let before = s.doc().unwrap().wb.active().unwrap().row_height(4);
|
||||
s.execute("home.fontSize", json!({"range": "5:5", "size": 20})).unwrap();
|
||||
let after = s.doc().unwrap().wb.active().unwrap().row_height(4);
|
||||
assert!(after > before + 10.0, "20pt whole-row format should grow the row: before={before}, after={after}");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().row_height(4), before, "undo must restore the height");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_column_font_format_grows_only_rows_with_cells() {
|
||||
let mut s = gridcraft_engine::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["a"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A50", "values": [["b"]]})).unwrap();
|
||||
s.execute("home.fontSize", json!({"range": "A:A", "size": 20})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(sh.row_height(0) > 30.0 && sh.row_height(49) > 30.0, "rows with cells grow");
|
||||
assert!(sh.rows.len() <= 3, "full-column format must fit only rows that have cells, rows map has {} entries", sh.rows.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_row_format_does_not_resize_custom_height_rows() {
|
||||
let mut s = gridcraft_engine::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A5", "values": [["plain big bold"]]})).unwrap();
|
||||
{
|
||||
let sh = sheet_mut(&mut s);
|
||||
let e = sh.rows.entry(4).or_default();
|
||||
e.custom = true;
|
||||
e.size = Some(25.0);
|
||||
}
|
||||
s.execute("home.fontSize", json!({"range": "5:5", "size": 20})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().row_height(4), 25.0, "custom-height rows keep their height");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_row_format_keeps_hidden_rows_hidden() {
|
||||
let mut s = gridcraft_engine::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A5", "values": [["plain big bold"]]})).unwrap();
|
||||
let before = s.doc().unwrap().wb.active().unwrap().row_height(4);
|
||||
sheet_mut(&mut s).rows.entry(4).or_default().hidden = true;
|
||||
s.execute("home.fontSize", json!({"range": "5:5", "size": 20})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
let info = sh.rows.get(&4).unwrap();
|
||||
assert!(info.size.unwrap_or(before) > before + 10.0, "hidden row still grows to its font: before={before}, size={:?}", info.size);
|
||||
assert!(info.hidden, "formatting a hidden row must not unhide it");
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
const NOT_OBJECTS: [&str; 4] = ["\"[1,2]\"", "\"7\"", "\"true\"", "\"\"\"hi\"\"\""];
|
||||
|
||||
fn with_name(name: &str, refers_to: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("formulas.defineName", json!({"name": name, "refersTo": refers_to})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_view_works_when_stored_list_is_not_an_object() {
|
||||
for text in NOT_OBJECTS {
|
||||
let mut s = with_name("_sc_custom_views", text);
|
||||
let out = s.execute("view.customViews", json!({"save": "v"})).unwrap();
|
||||
assert!(out.get("v").is_some(), "{text}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_view_keeps_the_keys_of_a_stored_object() {
|
||||
let mut s = with_name("_sc_custom_views", "\"{\"\"a\"\":1}\"");
|
||||
let out = s.execute("view.customViews", json!({"save": "v"})).unwrap();
|
||||
assert!(out.get("a").is_some() && out.get("v").is_some(), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creating_a_script_works_when_stored_list_is_not_an_object() {
|
||||
for text in NOT_OBJECTS {
|
||||
let mut s = with_name("_sc_scripts", text);
|
||||
s.execute("automate.newScript", json!({"name": "s1", "commands": []})).unwrap();
|
||||
let list = s.execute("automate.allScripts", json!({})).unwrap();
|
||||
assert!(list.to_string().contains("s1"), "{text}: {list}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_a_recording_works_when_stored_list_is_not_an_object() {
|
||||
for text in NOT_OBJECTS {
|
||||
let mut s = with_name("_sc_scripts", text);
|
||||
s.execute("automate.recordActions", json!({})).unwrap();
|
||||
s.execute("automate.recordActions", json!({"stop": true, "name": "s1"})).unwrap();
|
||||
let list = s.execute("automate.allScripts", json!({})).unwrap();
|
||||
assert!(list.to_string().contains("s1"), "{text}: {list}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn table() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1", "values":[["Item", "Qty"], ["x", "7"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"A1:B2", "header":true, "name":"T"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn table_range(s: &Session) -> String {
|
||||
s.doc().unwrap().wb.active().unwrap().tables[0].range.a1()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_to_disjoint_range_is_rejected_and_keeps_table() {
|
||||
let mut s = table();
|
||||
assert!(s.execute("table.resize", json!({"table":"T", "range":"D1:E2"})).is_err());
|
||||
assert_eq!(table_range(&s), "A1:B2");
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().tables[0].columns[1].name, "Qty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_to_overlapping_range_still_works() {
|
||||
let mut s = table();
|
||||
s.execute("table.resize", json!({"table":"T", "range":"B1:C2"})).unwrap();
|
||||
assert_eq!(table_range(&s), "B1:C2");
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use gridcraft_core::{CellRef, MAX_ROWS};
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn refused(range: &str) {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("insert.table", json!({"range": range, "header": true})).unwrap();
|
||||
let before = s.doc().unwrap().wb.active().unwrap().tables[0].clone();
|
||||
assert!(s.execute("table.totalRow", json!({"on": true, "table": &before.name})).is_err(), "{range}");
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.tables[0].range, before.range, "{range}");
|
||||
assert_eq!(sh.tables[0].range.end.row, MAX_ROWS - 1, "{range}");
|
||||
assert!(!sh.tables[0].totals_row, "{range}");
|
||||
assert!(sh.value(CellRef::new(MAX_ROWS, 0)).is_empty(), "{range}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn total_row_is_refused_on_a_table_ending_at_the_last_worksheet_row() {
|
||||
refused("A1048575:B1048576");
|
||||
refused("A1048576:B1048576");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn total_row_still_grows_an_ordinary_table() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Item", "Amount"], ["a", 2], ["b", 3]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:B3", "header": true})).unwrap();
|
||||
s.execute("table.totalRow", json!({"on": true, "table": "Table1"})).unwrap();
|
||||
let t = &s.doc().unwrap().wb.active().unwrap().tables[0];
|
||||
assert!(t.totals_row);
|
||||
assert_eq!(t.range.end.row, 3);
|
||||
}
|
||||
@@ -16,6 +16,35 @@ pub fn shift_relative(e: Expr, dr: i64, dc: i64) -> Expr {
|
||||
})
|
||||
}
|
||||
|
||||
/// Defined names: relative parts move by `(dr, dc)`, wrapping around the sheet's edges. Files
|
||||
/// store a name's relative references as seen from A1 (a name for "the cell to the left" defined
|
||||
/// in B1 is `Sheet1!XFD1`), and a use in another cell moves them by that cell's offset from A1.
|
||||
pub fn shift_relative_wrapping(e: Expr, dr: i64, dc: i64) -> Expr {
|
||||
let wrap = |v: u32, abs: bool, d: i64, max: u32| if abs { v } else { (v as i64 + d).rem_euclid(max as i64) as u32 };
|
||||
let anchor = |a: Anchor| Anchor { row: wrap(a.row, a.row_abs, dr, MAX_ROWS), col: wrap(a.col, a.col_abs, dc, MAX_COLS), ..a };
|
||||
e.map(&mut |x| match x {
|
||||
Expr::Ref(r) => {
|
||||
let kind = match r.kind {
|
||||
RefKind::Cell(a) => RefKind::Cell(anchor(a)),
|
||||
RefKind::Range(a, b) => RefKind::Range(anchor(a), anchor(b)),
|
||||
RefKind::Rows(r0, a0, r1, a1) => RefKind::Rows(wrap(r0, a0, dr, MAX_ROWS), a0, wrap(r1, a1, dr, MAX_ROWS), a1),
|
||||
RefKind::Cols(c0, a0, c1, a1) => RefKind::Cols(wrap(c0, a0, dc, MAX_COLS), a0, wrap(c1, a1, dc, MAX_COLS), a1),
|
||||
};
|
||||
Expr::Ref(Reference { sheet: r.sheet, kind })
|
||||
}
|
||||
other => other,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the formula has a relative (no `$`) row or column anywhere.
|
||||
pub fn has_relative_refs(e: &Expr) -> bool {
|
||||
e.references().iter().any(|r| match r.kind {
|
||||
RefKind::Cell(a) => !a.row_abs || !a.col_abs,
|
||||
RefKind::Range(a, b) => !a.row_abs || !a.col_abs || !b.row_abs || !b.col_abs,
|
||||
RefKind::Rows(_, a0, _, a1) | RefKind::Cols(_, a0, _, a1) => !a0 || !a1,
|
||||
})
|
||||
}
|
||||
|
||||
fn shift_anchor(a: &Anchor, dr: i64, dc: i64) -> Option<Anchor> {
|
||||
let row = if a.row_abs { a.row as i64 } else { a.row as i64 + dr };
|
||||
let col = if a.col_abs { a.col as i64 } else { a.col as i64 + dc };
|
||||
@@ -195,17 +224,6 @@ fn adjust_ref(r: &Reference, edit: &Edit) -> Option<Reference> {
|
||||
let kind = match &r.kind {
|
||||
RefKind::Cell(a) => RefKind::Cell(mv(a)?),
|
||||
RefKind::Range(a, b) => RefKind::Range(mv(a)?, mv(b)?),
|
||||
k => k.clone(),
|
||||
};
|
||||
Some(Reference { sheet: r.sheet.clone(), kind })
|
||||
}
|
||||
Edit::MoveToSheet { from, to_sheet, to_row, to_col } => {
|
||||
if !from.contains_range(&r.range()) {
|
||||
return Some(r.clone());
|
||||
}
|
||||
let mut moved = adjust_ref(r, &Edit::Move { from: *from, to_row: *to_row, to_col: *to_col })?;
|
||||
// Whole-row/column references have no anchors, but their indices must move too.
|
||||
moved.kind = match &r.kind {
|
||||
RefKind::Rows(a, aa, b, ba) => {
|
||||
let dr = *to_row as i64 - from.start.row as i64;
|
||||
RefKind::Rows(shift_line(*a, false, dr, MAX_ROWS)?, *aa, shift_line(*b, false, dr, MAX_ROWS)?, *ba)
|
||||
@@ -214,8 +232,14 @@ fn adjust_ref(r: &Reference, edit: &Edit) -> Option<Reference> {
|
||||
let dc = *to_col as i64 - from.start.col as i64;
|
||||
RefKind::Cols(shift_line(*a, false, dc, MAX_COLS)?, *aa, shift_line(*b, false, dc, MAX_COLS)?, *ba)
|
||||
}
|
||||
_ => moved.kind,
|
||||
};
|
||||
Some(Reference { sheet: r.sheet.clone(), kind })
|
||||
}
|
||||
Edit::MoveToSheet { from, to_sheet, to_row, to_col } => {
|
||||
if !from.contains_range(&r.range()) {
|
||||
return Some(r.clone());
|
||||
}
|
||||
let mut moved = adjust_ref(r, &Edit::Move { from: *from, to_row: *to_row, to_col: *to_col })?;
|
||||
moved.sheet = SheetSel::Named(to_sheet.clone());
|
||||
Some(moved)
|
||||
}
|
||||
@@ -240,11 +264,10 @@ pub fn rename_sheet(e: Expr, old: &str, new: &str) -> Expr {
|
||||
}
|
||||
Expr::Ref(r)
|
||||
}
|
||||
// Sheet-qualified defined name `Old!MyName` is stored as one string.
|
||||
// Sheet-qualified defined name `Old!MyName` is stored as one string, with the bare sheet name as the parser
|
||||
// stores it (the printer adds the quotes).
|
||||
Expr::Name(n) => match n.split_at_checked(old.len()) {
|
||||
Some((head, rest)) if head.eq_ignore_ascii_case(old) && rest.starts_with('!') => {
|
||||
Expr::Name(format!("{}{rest}", crate::printer::quote_sheet(new)))
|
||||
}
|
||||
Some((head, rest)) if head.eq_ignore_ascii_case(old) && rest.starts_with('!') => Expr::Name(format!("{new}{rest}")),
|
||||
_ => Expr::Name(n),
|
||||
},
|
||||
other => other,
|
||||
|
||||
@@ -91,6 +91,38 @@ pub enum UnOp {
|
||||
/// Spill range operator `A1#`: the whole spill range of the dynamic array anchored at the
|
||||
/// cell (`ANCHORARRAY` in files).
|
||||
Spill,
|
||||
/// Trim reference `A1.:E10` / `A1:.E10` / `A1.:.E10` around a range: the range without its
|
||||
/// blank leading, trailing or outer rows and columns (`TRIMRANGE` with both trim codes set).
|
||||
Trim(TrimMode),
|
||||
}
|
||||
|
||||
/// Which blank edges a trim reference drops.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum TrimMode {
|
||||
/// `.:` — leading blank rows and columns.
|
||||
Leading,
|
||||
/// `:.` — trailing blank rows and columns.
|
||||
Trailing,
|
||||
/// `.:.` — both.
|
||||
All,
|
||||
}
|
||||
|
||||
impl TrimMode {
|
||||
pub fn symbol(self) -> &'static str {
|
||||
match self {
|
||||
TrimMode::Leading => ".:",
|
||||
TrimMode::Trailing => ":.",
|
||||
TrimMode::All => ".:.",
|
||||
}
|
||||
}
|
||||
/// The equivalent `TRIMRANGE` trim_rows / trim_cols code.
|
||||
pub fn code(self) -> u8 {
|
||||
match self {
|
||||
TrimMode::Leading => 1,
|
||||
TrimMode::Trailing => 2,
|
||||
TrimMode::All => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
use gridcraft_core::CellError;
|
||||
|
||||
use crate::ast::TrimMode;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Tok {
|
||||
Number(f64),
|
||||
@@ -27,6 +29,8 @@ pub enum Tok {
|
||||
Comma,
|
||||
Semicolon,
|
||||
Colon,
|
||||
/// Trim reference range operator `.:`, `:.` or `.:.`.
|
||||
Trim(TrimMode),
|
||||
Space,
|
||||
Eof,
|
||||
}
|
||||
@@ -49,6 +53,20 @@ fn is_word_char(c: char) -> bool {
|
||||
c.is_alphanumeric() || matches!(c, '_' | '.' | '$' | '\\' | '?')
|
||||
}
|
||||
|
||||
/// `A1`, `$A$1`, `A`, `$A`, `1`, `$1`: a word that can end a range, so `A1.:` is a trim
|
||||
/// reference and not a name ending in a dot.
|
||||
fn is_range_end(w: &str) -> bool {
|
||||
let s = w.strip_prefix('$').unwrap_or(w);
|
||||
let (letters, rest) = s.split_at(s.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(s.len()));
|
||||
let digits = if letters.is_empty() { rest } else { rest.strip_prefix('$').unwrap_or(rest) };
|
||||
letters.len() <= 3 && if digits.is_empty() { !letters.is_empty() && rest.is_empty() } else { digits.bytes().all(|b| b.is_ascii_digit()) }
|
||||
}
|
||||
|
||||
/// Whether `c` can start the second end of a range after `:.` (`A1:.E10`, `A:.$C`, `1:.5`).
|
||||
fn starts_range_end(c: Option<char>) -> bool {
|
||||
c.is_some_and(|c| c.is_ascii_alphanumeric() || c == '$')
|
||||
}
|
||||
|
||||
/// Tokenizes formula text (without the leading `=`).
|
||||
pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
|
||||
tokenize_locale(src, crate::FormulaLocale::En)
|
||||
@@ -178,6 +196,16 @@ pub fn tokenize_locale(src: &str, locale: crate::FormulaLocale) -> Result<Vec<To
|
||||
push(&mut out, Tok::Struct(inner), j);
|
||||
i = j;
|
||||
}
|
||||
'.' if ch(i + 1) == Some(':') => {
|
||||
// Trim reference `A1.:E10` / `A1.:.E10` (the word before stopped at the dot).
|
||||
if ch(i + 2) == Some('.') && starts_range_end(ch(i + 3)) {
|
||||
push(&mut out, Tok::Trim(TrimMode::All), i + 3);
|
||||
i += 3;
|
||||
} else {
|
||||
push(&mut out, Tok::Trim(TrimMode::Leading), i + 2);
|
||||
i += 2;
|
||||
}
|
||||
}
|
||||
c if c.is_ascii_digit() || (c == locale.decimal_separator() && ch(i + 1).is_some_and(|d| d.is_ascii_digit())) => {
|
||||
// Number, unless it is a row range like 1:3 (handled by parser via Word) — numbers
|
||||
// followed by ':' and digits are row refs: lex as Word.
|
||||
@@ -185,12 +213,22 @@ pub fn tokenize_locale(src: &str, locale: crate::FormulaLocale) -> Result<Vec<To
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
j += 1;
|
||||
}
|
||||
let is_row_ref = ch(j) == Some(':') && {
|
||||
let mut k = j + 1;
|
||||
if ch(k) == Some('$') {
|
||||
// Row ranges `1:3`, and the trim forms `1.:3`, `1:.3`, `1.:.3`.
|
||||
let is_row_ref = {
|
||||
let mut k = j;
|
||||
if ch(k) == Some('.') && ch(k + 1) == Some(':') {
|
||||
k += 1;
|
||||
}
|
||||
ch(k).is_some_and(|d| d.is_ascii_digit())
|
||||
ch(k) == Some(':') && {
|
||||
k += 1;
|
||||
if ch(k) == Some('.') {
|
||||
k += 1;
|
||||
}
|
||||
if ch(k) == Some('$') {
|
||||
k += 1;
|
||||
}
|
||||
ch(k).is_some_and(|d| d.is_ascii_digit())
|
||||
}
|
||||
};
|
||||
// A word like "1A" can't happen in valid formulas; numbers then.
|
||||
if is_row_ref {
|
||||
@@ -252,8 +290,13 @@ pub fn tokenize_locale(src: &str, locale: crate::FormulaLocale) -> Result<Vec<To
|
||||
i += 1;
|
||||
}
|
||||
':' => {
|
||||
push(&mut out, Tok::Colon, i + 1);
|
||||
i += 1;
|
||||
if ch(i + 1) == Some('.') && starts_range_end(ch(i + 2)) {
|
||||
push(&mut out, Tok::Trim(TrimMode::Trailing), i + 2);
|
||||
i += 2;
|
||||
} else {
|
||||
push(&mut out, Tok::Colon, i + 1);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'+' | '-' | '*' | '/' | '^' | '&' | '%' | '@' | '=' => {
|
||||
let op = match c {
|
||||
@@ -315,6 +358,11 @@ pub fn tokenize_locale(src: &str, locale: crate::FormulaLocale) -> Result<Vec<To
|
||||
} else if w.eq_ignore_ascii_case("FALSE") && ch(j) != Some('[') {
|
||||
push(&mut out, Tok::Bool(false), j);
|
||||
i = j;
|
||||
} else if w.len() > 1 && w.ends_with('.') && ch(j) == Some(':') && is_range_end(w.get(..w.len() - 1).unwrap_or("")) {
|
||||
// `A1.:E10`: the dot belongs to the trim operator, lexed next.
|
||||
let w = w.get(..w.len() - 1).unwrap_or("").to_string();
|
||||
push(&mut out, Tok::Word(w), j - 1);
|
||||
i = j - 1;
|
||||
} else {
|
||||
push(&mut out, Tok::Word(w), j);
|
||||
i = j;
|
||||
|
||||
@@ -10,7 +10,7 @@ pub mod lexer;
|
||||
pub mod parser;
|
||||
pub mod printer;
|
||||
|
||||
pub use ast::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, UnOp};
|
||||
pub use ast::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, StructItem, StructRef, TrimMode, UnOp};
|
||||
pub use input::{FormulaLocale, parse_input, print_input};
|
||||
pub use parser::{ParseError, normalize_function_name, parse};
|
||||
pub use printer::{print, print_r1c1, quote_sheet};
|
||||
|
||||
+123
-35
@@ -50,8 +50,9 @@ fn significant_spaces(toks: Vec<Token>) -> Vec<Token> {
|
||||
let mut out: Vec<Token> = Vec::with_capacity(toks.len());
|
||||
for (i, t) in toks.iter().enumerate() {
|
||||
if t.tok == Tok::Space {
|
||||
let prev_end = out.last().is_some_and(|p| matches!(p.tok, Tok::Word(_) | Tok::RParen | Tok::Struct(_)));
|
||||
let next_start = toks.get(i + 1).is_some_and(|n| matches!(n.tok, Tok::Word(_) | Tok::Sheet(..) | Tok::LParen | Tok::Func(_)));
|
||||
let prev_end = out.last().is_some_and(|p| matches!(p.tok, Tok::Word(_) | Tok::RParen | Tok::Struct(_) | Tok::Error(_)));
|
||||
let next_start =
|
||||
toks.get(i + 1).is_some_and(|n| matches!(n.tok, Tok::Word(_) | Tok::Sheet(..) | Tok::LParen | Tok::Func(_) | Tok::Error(_)));
|
||||
if prev_end && next_start {
|
||||
out.push(t.clone());
|
||||
}
|
||||
@@ -88,15 +89,19 @@ fn word_is_cell(w: &str) -> Option<Anchor> {
|
||||
Some(Anchor { row, col, row_abs, col_abs })
|
||||
}
|
||||
|
||||
/// `_xlfn.XLOOKUP` → `XLOOKUP`.
|
||||
/// `_xlfn.XLOOKUP` → `XLOOKUP`. `_xludf.` is kept (`_xludf.SUM`): it marks a user-defined
|
||||
/// function, never the built-in of the same name, and files need it back.
|
||||
pub fn normalize_function_name(name: &str) -> String {
|
||||
let u = name.to_ascii_uppercase();
|
||||
for p in ["_XLFN._XLWS.", "_XLFN.", "_XLWS.", "_XLUDF."] {
|
||||
for p in ["_XLFN._XLWS.", "_XLFN.", "_XLWS."] {
|
||||
if let Some(r) = u.strip_prefix(p) {
|
||||
return r.to_string();
|
||||
}
|
||||
}
|
||||
u
|
||||
match u.strip_prefix("_XLUDF.") {
|
||||
Some(r) => format!("_xludf.{r}"),
|
||||
None => u,
|
||||
}
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
@@ -174,6 +179,17 @@ impl Parser {
|
||||
lhs = Expr::Invoke(Box::new(lhs), args);
|
||||
continue;
|
||||
}
|
||||
if let Tok::Trim(mode) = *self.peek() {
|
||||
// A trim reference is the range operator with a modifier: same binding power.
|
||||
let bp = BinOp::Range.precedence();
|
||||
if bp < min_bp {
|
||||
break;
|
||||
}
|
||||
self.next();
|
||||
let rhs = self.expr(bp + 1, allow_union)?;
|
||||
lhs = Expr::Unary(UnOp::Trim(mode), Box::new(combine(BinOp::Range, lhs, rhs)));
|
||||
continue;
|
||||
}
|
||||
let Some(op) = self.binop(allow_union) else { break };
|
||||
let bp = op.precedence();
|
||||
if bp < min_bp {
|
||||
@@ -236,6 +252,26 @@ impl Parser {
|
||||
{
|
||||
return Ok(Expr::Unary(UnOp::Spill, Box::new(r)));
|
||||
}
|
||||
// Files write `@x` as `_xlfn.SINGLE(x)`.
|
||||
if name == "SINGLE"
|
||||
&& args.len() == 1
|
||||
&& let Some(x) = args.pop()
|
||||
{
|
||||
return Ok(Expr::Unary(UnOp::At, Box::new(x)));
|
||||
}
|
||||
// Files may spell a trim reference as a function call (`_xlfn._TRO_ALL(A1:E10)`).
|
||||
let trim = match name.as_str() {
|
||||
"_TRO_LEADING" => Some(TrimMode::Leading),
|
||||
"_TRO_TRAILING" => Some(TrimMode::Trailing),
|
||||
"_TRO_ALL" => Some(TrimMode::All),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(mode) = trim
|
||||
&& args.len() == 1
|
||||
&& let Some(x) = args.pop()
|
||||
{
|
||||
return Ok(Expr::Unary(UnOp::Trim(mode), Box::new(x)));
|
||||
}
|
||||
Ok(Expr::Call(name, args))
|
||||
}
|
||||
Tok::Sheet(a, b) => {
|
||||
@@ -253,27 +289,42 @@ impl Parser {
|
||||
if let Tok::Struct(_) = self.peek()
|
||||
&& word_is_cell(&w).is_none()
|
||||
{
|
||||
let pos = self.pos();
|
||||
let Tok::Struct(body) = self.next() else { return Err(self.err("internal")) };
|
||||
return Ok(Expr::Struct(parse_struct(&w, &body)));
|
||||
return parse_struct(&w, &body).map(Expr::Struct).map_err(|msg| ParseError { msg, pos });
|
||||
}
|
||||
self.reference_from_word(SheetSel::Current, &w)
|
||||
}
|
||||
Tok::Struct(body) => Ok(Expr::Struct(parse_struct("", &body))),
|
||||
Tok::Struct(body) => parse_struct("", &body).map(Expr::Struct).map_err(|msg| self.err(msg)),
|
||||
t => Err(self.err(format!("unexpected {}", describe(&t)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A word after an optional sheet: a cell, a column/row range (`A:C`, `3:5`) or a name.
|
||||
/// A word after an optional sheet: a cell, a column/row range (`A:C`, `3:5`) or a name. A
|
||||
/// trim operator (`A1:.E10`, `A:.A`) in place of the colon wraps the range in
|
||||
/// [`UnOp::Trim`].
|
||||
fn reference_from_word(&mut self, sheet: SheetSel, w: &str) -> Result<Expr, ParseError> {
|
||||
let trim = match self.peek() {
|
||||
Tok::Colon => Some(None),
|
||||
Tok::Trim(mode) => Some(Some(*mode)),
|
||||
_ => None,
|
||||
};
|
||||
let wrap = |kind: RefKind, sheet: SheetSel| {
|
||||
let r = Expr::Ref(Reference { sheet, kind });
|
||||
match trim {
|
||||
Some(Some(mode)) => Expr::Unary(UnOp::Trim(mode), Box::new(r)),
|
||||
_ => r,
|
||||
}
|
||||
};
|
||||
if let Some(a) = word_is_cell(w) {
|
||||
// Cell, possibly `A1:B2` (merged here so the sheet applies to both ends).
|
||||
if *self.peek() == Tok::Colon
|
||||
if trim.is_some()
|
||||
&& let Tok::Word(w2) = self.peek_at(1)
|
||||
&& let Some(b) = word_is_cell(w2)
|
||||
{
|
||||
self.next();
|
||||
self.next();
|
||||
return Ok(Expr::Ref(Reference { sheet, kind: RefKind::Range(a, b) }));
|
||||
return Ok(wrap(RefKind::Range(a, b), sheet));
|
||||
}
|
||||
let cell = Expr::Ref(Reference { sheet, kind: RefKind::Cell(a) });
|
||||
if *self.peek() == Tok::Op("#") {
|
||||
@@ -287,18 +338,18 @@ impl Parser {
|
||||
Tok::Number(n) if n.fract() == 0.0 && *n >= 1.0 => Some(format!("{n}")),
|
||||
_ => None,
|
||||
};
|
||||
if *self.peek() == Tok::Colon
|
||||
if trim.is_some()
|
||||
&& let Some(w2) = second
|
||||
{
|
||||
if let (Some((c0, a0)), Some((c1, a1))) = (word_is_cols(w), word_is_cols(&w2)) {
|
||||
self.next();
|
||||
self.next();
|
||||
return Ok(Expr::Ref(Reference { sheet, kind: RefKind::Cols(c0, a0, c1, a1) }));
|
||||
return Ok(wrap(RefKind::Cols(c0, a0, c1, a1), sheet));
|
||||
}
|
||||
if let (Some((r0, a0)), Some((r1, a1))) = (word_is_row(w), word_is_row(&w2)) {
|
||||
self.next();
|
||||
self.next();
|
||||
return Ok(Expr::Ref(Reference { sheet, kind: RefKind::Rows(r0, a0, r1, a1) }));
|
||||
return Ok(wrap(RefKind::Rows(r0, a0, r1, a1), sheet));
|
||||
}
|
||||
}
|
||||
if sheet != SheetSel::Current {
|
||||
@@ -311,6 +362,10 @@ impl Parser {
|
||||
if w.chars().next().is_some_and(|c| c.is_ascii_digit()) {
|
||||
return Err(self.err(format!("unexpected `{w}`")));
|
||||
}
|
||||
// A function passed by name is saved as `_xleta.SUM`.
|
||||
if let Some(f) = w.get(..7).filter(|p| p.eq_ignore_ascii_case("_xleta.")).and_then(|_| w.get(7..)) {
|
||||
return Ok(Expr::Name(f.to_ascii_uppercase()));
|
||||
}
|
||||
Ok(Expr::Name(w.to_string()))
|
||||
}
|
||||
|
||||
@@ -365,10 +420,15 @@ fn combine(op: BinOp, lhs: Expr, rhs: Expr) -> Expr {
|
||||
Expr::Binary(op, Box::new(lhs), Box::new(rhs))
|
||||
}
|
||||
|
||||
/// Parses the inside of `Table[...]`.
|
||||
pub fn parse_struct(table: &str, body: &str) -> StructRef {
|
||||
/// Parses the inside of `Table[...]`. Text between the bracketed items may only be the `,` and
|
||||
/// `:` separators, except one unbracketed column after `[#This Row],` (`[[#This Row],Units]`,
|
||||
/// how some writers spell `[@Units]`); anything else is an error rather than dropped.
|
||||
pub fn parse_struct(table: &str, body: &str) -> Result<StructRef, String> {
|
||||
let mut specifiers = Vec::new();
|
||||
let mut cols: Vec<String> = Vec::new();
|
||||
// Spaces at the edges of a column name are part of it (`Table1[Qty ]` names `Qty `), so the
|
||||
// untrimmed body is what a lone column is read from.
|
||||
let raw = body;
|
||||
let body = body.trim();
|
||||
let unescape = |s: &str| {
|
||||
let mut out = String::new();
|
||||
@@ -394,24 +454,41 @@ pub fn parse_struct(table: &str, body: &str) -> StructRef {
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let unexpected = |gap: &str| format!("unexpected `{gap}` in structured reference");
|
||||
// A column name may hold `[` and `]` only when escaped with `'`.
|
||||
let column = |s: &str| -> Result<String, String> {
|
||||
let mut esc = false;
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
_ if esc => esc = false,
|
||||
'\'' => esc = true,
|
||||
'[' | ']' => return Err(unexpected(s)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(unescape(s))
|
||||
};
|
||||
if !body.starts_with('[') {
|
||||
// Simple: [Col], [@Col], [#Headers], [@]
|
||||
if let Some(rest) = body.strip_prefix('@') {
|
||||
specifiers.push(StructItem::ThisRow);
|
||||
let rest = rest.trim().trim_start_matches('[').trim_end_matches(']');
|
||||
let rest = rest.trim();
|
||||
let rest = rest.strip_prefix('[').and_then(|r| r.strip_suffix(']')).unwrap_or(rest);
|
||||
if !rest.is_empty() {
|
||||
cols.push(unescape(rest));
|
||||
cols.push(column(rest)?);
|
||||
}
|
||||
} else if let Some(i) = item(body) {
|
||||
specifiers.push(i);
|
||||
} else if !body.is_empty() {
|
||||
cols.push(unescape(body));
|
||||
cols.push(column(raw)?);
|
||||
}
|
||||
} else {
|
||||
// [[#Headers],[Col1]:[Col3]] or [@[Col 1]]
|
||||
// [[#Headers],[Col1]:[Col3]], [[#This Row],[Col 1]] or [[#This Row],Col1]
|
||||
let mut parts = Vec::new();
|
||||
let mut depth = 0;
|
||||
let mut cur = String::new();
|
||||
// Text between bracketed items.
|
||||
let mut gap = String::new();
|
||||
let mut esc = false;
|
||||
for c in body.chars() {
|
||||
if esc {
|
||||
@@ -420,17 +497,26 @@ pub fn parse_struct(table: &str, body: &str) -> StructRef {
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'\'' => {
|
||||
'\'' if depth > 0 => {
|
||||
cur.push(c);
|
||||
esc = true;
|
||||
}
|
||||
'[' => {
|
||||
if depth == 0 {
|
||||
if !matches!(gap.trim(), "" | "," | ":") {
|
||||
return Err(unexpected(gap.trim()));
|
||||
}
|
||||
gap.clear();
|
||||
}
|
||||
depth += 1;
|
||||
if depth > 1 {
|
||||
cur.push(c);
|
||||
}
|
||||
}
|
||||
']' => {
|
||||
if depth == 0 {
|
||||
return Err(unexpected("]"));
|
||||
}
|
||||
depth -= 1;
|
||||
if depth > 0 {
|
||||
cur.push(c);
|
||||
@@ -438,33 +524,35 @@ pub fn parse_struct(table: &str, body: &str) -> StructRef {
|
||||
parts.push(std::mem::take(&mut cur));
|
||||
}
|
||||
}
|
||||
',' if depth == 0 => {}
|
||||
':' if depth == 0 => parts.push(":".into()),
|
||||
_ if depth > 0 => cur.push(c),
|
||||
_ => {}
|
||||
_ => gap.push(c),
|
||||
}
|
||||
}
|
||||
let mut range_next = false;
|
||||
if depth > 0 {
|
||||
return Err("unclosed `[` in structured reference".to_string());
|
||||
}
|
||||
for p in parts {
|
||||
if p == ":" {
|
||||
range_next = true;
|
||||
continue;
|
||||
}
|
||||
if let Some(i) = item(&p) {
|
||||
specifiers.push(i);
|
||||
} else if range_next {
|
||||
cols.push(unescape(&p));
|
||||
range_next = false;
|
||||
} else {
|
||||
cols.push(unescape(&p));
|
||||
cols.push(column(&p)?);
|
||||
}
|
||||
}
|
||||
if body.starts_with("@") {
|
||||
specifiers.push(StructItem::ThisRow);
|
||||
let tail = gap.trim();
|
||||
if !tail.is_empty() {
|
||||
let bare = tail.strip_prefix(',').map(str::trim).unwrap_or("");
|
||||
let simple = !bare.is_empty() && !bare.chars().any(|c| matches!(c, '[' | ']' | '#' | '\'' | ',' | ':'));
|
||||
if !(simple && specifiers == [StructItem::ThisRow] && cols.is_empty()) {
|
||||
return Err(unexpected(tail));
|
||||
}
|
||||
cols.push(bare.to_string());
|
||||
}
|
||||
}
|
||||
if cols.len() > 2 {
|
||||
return Err("a structured reference names at most two columns".to_string());
|
||||
}
|
||||
let mut it = cols.into_iter();
|
||||
let col_start = it.next();
|
||||
let col_end = it.next();
|
||||
StructRef { table: table.to_string(), specifiers, col_start, col_end }
|
||||
Ok(StructRef { table: table.to_string(), specifiers, col_start, col_end })
|
||||
}
|
||||
|
||||
@@ -39,12 +39,17 @@ fn anchor_a1(a: &Anchor) -> String {
|
||||
}
|
||||
|
||||
pub fn reference_a1(r: &Reference) -> String {
|
||||
range_a1(r, ":")
|
||||
}
|
||||
|
||||
/// A1 text with `sep` between the two ends of a range (`:` or a trim operator).
|
||||
fn range_a1(r: &Reference, sep: &str) -> String {
|
||||
let body = match &r.kind {
|
||||
RefKind::Cell(a) => anchor_a1(a),
|
||||
RefKind::Range(a, b) => format!("{}:{}", anchor_a1(a), anchor_a1(b)),
|
||||
RefKind::Rows(r0, a0, r1, a1) => format!("{}{}:{}{}", if *a0 { "$" } else { "" }, r0 + 1, if *a1 { "$" } else { "" }, r1 + 1),
|
||||
RefKind::Range(a, b) => format!("{}{sep}{}", anchor_a1(a), anchor_a1(b)),
|
||||
RefKind::Rows(r0, a0, r1, a1) => format!("{}{}{sep}{}{}", if *a0 { "$" } else { "" }, r0 + 1, if *a1 { "$" } else { "" }, r1 + 1),
|
||||
RefKind::Cols(c0, a0, c1, a1) => {
|
||||
format!("{}{}:{}{}", if *a0 { "$" } else { "" }, col_to_letters(*c0), if *a1 { "$" } else { "" }, col_to_letters(*c1))
|
||||
format!("{}{}{sep}{}{}", if *a0 { "$" } else { "" }, col_to_letters(*c0), if *a1 { "$" } else { "" }, col_to_letters(*c1))
|
||||
}
|
||||
};
|
||||
format!("{}{}", sheet_prefix(&r.sheet), body)
|
||||
@@ -64,22 +69,38 @@ fn anchor_r1c1(a: &Anchor, at: CellRef) -> String {
|
||||
}
|
||||
|
||||
pub fn reference_r1c1(r: &Reference, at: CellRef) -> String {
|
||||
range_r1c1(r, at, ":")
|
||||
}
|
||||
|
||||
/// R1C1 text with `sep` between the two ends of a range; a trim operator never collapses
|
||||
/// `R1:R1` to `R1`.
|
||||
fn range_r1c1(r: &Reference, at: CellRef, sep: &str) -> String {
|
||||
let body = match &r.kind {
|
||||
RefKind::Cell(a) => anchor_r1c1(a, at),
|
||||
RefKind::Range(a, b) => format!("{}:{}", anchor_r1c1(a, at), anchor_r1c1(b, at)),
|
||||
RefKind::Range(a, b) => format!("{}{sep}{}", anchor_r1c1(a, at), anchor_r1c1(b, at)),
|
||||
RefKind::Rows(r0, a0, r1, a1) => {
|
||||
let (x, y) = (r1c1_part('R', *r0, *a0, at.row), r1c1_part('R', *r1, *a1, at.row));
|
||||
if x == y { x } else { format!("{x}:{y}") }
|
||||
if x == y && sep == ":" { x } else { format!("{x}{sep}{y}") }
|
||||
}
|
||||
RefKind::Cols(c0, a0, c1, a1) => {
|
||||
let (x, y) = (r1c1_part('C', *c0, *a0, at.col), r1c1_part('C', *c1, *a1, at.col));
|
||||
if x == y { x } else { format!("{x}:{y}") }
|
||||
if x == y && sep == ":" { x } else { format!("{x}{sep}{y}") }
|
||||
}
|
||||
};
|
||||
format!("{}{}", sheet_prefix(&r.sheet), body)
|
||||
}
|
||||
|
||||
pub fn struct_ref(s: &StructRef) -> String {
|
||||
write_struct_ref(s, true)
|
||||
}
|
||||
|
||||
/// Structured reference as files spell it: `[@Col]` is only Excel's display shorthand, files
|
||||
/// hold `[[#This Row],[Col]]` (and `[#This Row]` for `[@]`).
|
||||
pub fn struct_ref_file(s: &StructRef) -> String {
|
||||
write_struct_ref(s, false)
|
||||
}
|
||||
|
||||
fn write_struct_ref(s: &StructRef, at_shorthand: bool) -> String {
|
||||
let esc = |c: &str| c.replace('\'', "''").replace('[', "'[").replace(']', "']").replace('#', "'#");
|
||||
let item = |i: &StructItem| match i {
|
||||
StructItem::All => "#All",
|
||||
@@ -88,7 +109,7 @@ pub fn struct_ref(s: &StructRef) -> String {
|
||||
StructItem::Totals => "#Totals",
|
||||
StructItem::ThisRow => "#This Row",
|
||||
};
|
||||
let this_row = s.specifiers == [StructItem::ThisRow];
|
||||
let this_row = at_shorthand && s.specifiers == [StructItem::ThisRow];
|
||||
let mut out = s.table.clone();
|
||||
let simple_col = |c: &str| !c.chars().any(|ch| matches!(ch, ' ' | '[' | ']' | '#' | '\'' | ',' | ':'));
|
||||
match (&s.col_start, &s.col_end) {
|
||||
@@ -98,7 +119,12 @@ pub fn struct_ref(s: &StructRef) -> String {
|
||||
let _ = write!(out, "[{}]", s.specifiers.first().map(item).unwrap_or(""));
|
||||
}
|
||||
(Some(c), None) if s.specifiers.is_empty() => {
|
||||
let _ = write!(out, "[{}]", esc(c));
|
||||
// Excel writes a name with spaces at its edges in the double-bracket form.
|
||||
if c.trim() == c {
|
||||
let _ = write!(out, "[{}]", esc(c));
|
||||
} else {
|
||||
let _ = write!(out, "[[{}]]", esc(c));
|
||||
}
|
||||
}
|
||||
(Some(c), None) if this_row => {
|
||||
if simple_col(c) {
|
||||
@@ -167,7 +193,15 @@ fn write_expr(s: &mut String, e: &Expr, r1c1: Option<CellRef>) {
|
||||
Some(at) => s.push_str(&reference_r1c1(r, at)),
|
||||
None => s.push_str(&reference_a1(r)),
|
||||
},
|
||||
Expr::Name(n) => s.push_str(n),
|
||||
Expr::Name(n) => match n.rsplit_once('!') {
|
||||
// A sheet-qualified name is stored with the bare sheet name (`My Sheet!Total`): quote it so it parses back.
|
||||
Some((sheet, name)) => {
|
||||
s.push_str("e_sheet(sheet));
|
||||
s.push('!');
|
||||
s.push_str(name);
|
||||
}
|
||||
_ => s.push_str(n),
|
||||
},
|
||||
Expr::Struct(st) => s.push_str(&struct_ref(st)),
|
||||
Expr::Unary(op, x) => match op {
|
||||
UnOp::Neg => {
|
||||
@@ -193,11 +227,40 @@ fn write_expr(s: &mut String, e: &Expr, r1c1: Option<CellRef>) {
|
||||
s.push('#');
|
||||
}
|
||||
}
|
||||
UnOp::Trim(mode) => match &**x {
|
||||
Expr::Ref(r) if !matches!(r.kind, RefKind::Cell(_)) => match r1c1 {
|
||||
Some(at) => s.push_str(&range_r1c1(r, at, mode.symbol())),
|
||||
None => s.push_str(&range_a1(r, mode.symbol())),
|
||||
},
|
||||
Expr::Binary(BinOp::Range, a, b) => {
|
||||
write_expr(s, a, r1c1);
|
||||
s.push_str(mode.symbol());
|
||||
write_expr(s, b, r1c1);
|
||||
}
|
||||
// A reference that became #REF! stays `#REF!`.
|
||||
Expr::Error(_) => write_expr(s, x, r1c1),
|
||||
// No operator form (e.g. a range shrunk to one cell): the equivalent call.
|
||||
other => {
|
||||
s.push_str("TRIMRANGE(");
|
||||
write_expr(s, other, r1c1);
|
||||
let _ = write!(s, ",{0},{0})", mode.code());
|
||||
}
|
||||
},
|
||||
},
|
||||
Expr::Binary(op, a, b) => {
|
||||
write_expr(s, a, r1c1);
|
||||
s.push_str(op.symbol());
|
||||
write_expr(s, b, r1c1);
|
||||
Expr::Binary(..) => {
|
||||
// Walk the left spine iteratively: a flat chain such as `1+1+1+...` parses into a
|
||||
// tree one level deeper per operator, and recursing on it could exhaust the stack.
|
||||
let mut rest: Vec<(&BinOp, &Expr)> = Vec::new();
|
||||
let mut first = e;
|
||||
while let Expr::Binary(op, a, b) = first {
|
||||
rest.push((op, b));
|
||||
first = a;
|
||||
}
|
||||
write_expr(s, first, r1c1);
|
||||
for (op, right) in rest.into_iter().rev() {
|
||||
s.push_str(op.symbol());
|
||||
write_expr(s, right, r1c1);
|
||||
}
|
||||
}
|
||||
Expr::Call(name, args) => {
|
||||
s.push_str(name);
|
||||
|
||||
@@ -5,6 +5,29 @@ fn rt(src: &str) -> String {
|
||||
print(&parse(src).unwrap_or_else(|e| panic!("{src}: {e}")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_sheet_qualified_name_keeps_quotes() {
|
||||
assert_eq!(rt("'My Sheet'!Total"), "'My Sheet'!Total");
|
||||
assert_eq!(rt("'Data'!Total"), "Data!Total");
|
||||
assert_eq!(rt("'It''s'!Total+1"), "'It''s'!Total+1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intersection_with_deleted_operand_reparses() {
|
||||
// Deleting the columns of an intersection operand prints `A1:B2 #REF!`; that text must parse back.
|
||||
assert_eq!(rt("A1:B2 #REF!"), "A1:B2 #REF!");
|
||||
assert_eq!(rt("#REF! A1:B2"), "#REF! A1:B2");
|
||||
assert_eq!(parse("A1:B2 #REF!"), parse("A1:B2 (#REF!)").map(|e| strip_paren(&e)));
|
||||
}
|
||||
|
||||
fn strip_paren(e: &Expr) -> Expr {
|
||||
match e {
|
||||
Expr::Binary(op, a, b) => Expr::Binary(*op, Box::new(strip_paren(a)), Box::new(strip_paren(b))),
|
||||
Expr::Paren(x) => strip_paren(x),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrips() {
|
||||
for f in [
|
||||
@@ -48,6 +71,8 @@ fn normalises() {
|
||||
assert_eq!(rt("=sum(a1:b2)"), "SUM(A1:B2)");
|
||||
assert_eq!(rt("= 1 + 2"), "1+2");
|
||||
assert_eq!(rt("_xlfn.XLOOKUP(1,A:A,B:B)"), "XLOOKUP(1,A:A,B:B)");
|
||||
assert_eq!(rt("_xlfn.GROUPBY(A1:A3,B1:B3,_xleta.SUM)"), "GROUPBY(A1:A3,B1:B3,SUM)");
|
||||
assert_eq!(rt("_XLUDF.concat(\"a\",\"b\")"), "_xludf.CONCAT(\"a\",\"b\")");
|
||||
assert_eq!(rt("true"), "TRUE");
|
||||
assert_eq!(rt("'Sheet1'!A1"), "Sheet1!A1");
|
||||
}
|
||||
@@ -171,6 +196,8 @@ fn moves_and_renames() {
|
||||
let mv = Edit::Move { from: gridcraft_core::RangeRef::parse("A1:B2").unwrap(), to_row: 9, to_col: 3 };
|
||||
let e = parse("A1+B2+C3+SUM(A1:B2)").unwrap();
|
||||
assert_eq!(print(&adjust(e, "S", "S", &mv)), "D10+E11+C3+SUM(D10:E11)");
|
||||
let mv = Edit::Move { from: gridcraft_core::RangeRef::parse("B:C").unwrap(), to_row: 0, to_col: 4 };
|
||||
assert_eq!(print(&adjust(parse("SUM(B:B)+SUM($C:$C)+D1").unwrap(), "S", "S", &mv)), "SUM(E:E)+SUM($F:$F)+D1");
|
||||
let e = parse("Old!A1+'Old'!B2").unwrap();
|
||||
assert_eq!(print(&rename_sheet(e, "Old", "New Name")), "'New Name'!A1+'New Name'!B2");
|
||||
}
|
||||
@@ -181,6 +208,10 @@ fn rename_sheet_updates_qualified_names() {
|
||||
assert_eq!(print(&rename_sheet(e, "data", "Numbers")), "Numbers!MyName+MyName+Other!MyName");
|
||||
let e = parse("Data!MyName").unwrap();
|
||||
assert_eq!(print(&rename_sheet(e, "Data", "New Name")), "'New Name'!MyName");
|
||||
// Stored bare, like a parsed name, so the evaluator finds the sheet and a second rename still matches.
|
||||
let e = rename_sheet(parse("Data!MyName").unwrap(), "Data", "It's");
|
||||
assert_eq!(e, Expr::Name("It's!MyName".into()));
|
||||
assert_eq!(print(&rename_sheet(e, "It's", "Totals")), "Totals!MyName");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -218,3 +249,120 @@ fn spans() {
|
||||
let a1 = toks.iter().find(|t| t.tok == lexer::Tok::Word("A1".into())).unwrap();
|
||||
assert_eq!((a1.start, a1.end), (4, 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbracketed_this_row_column() {
|
||||
// Writers such as xlsxwriter spell `[@Units]` as `[[#This Row],Units]`.
|
||||
let p = |f: &str| parse(f).unwrap_or_else(|e| panic!("{f}: {e}"));
|
||||
let Expr::Binary(BinOp::Mul, a, _) = p("[[#This Row],Units]*[[#This Row],Price]") else { panic!() };
|
||||
let Expr::Struct(s) = *a else { panic!() };
|
||||
assert_eq!((s.specifiers.as_slice(), s.col_start.as_deref()), ([StructItem::ThisRow].as_slice(), Some("Units")));
|
||||
assert_eq!(rt("[[#This Row],Units]*[[#This Row],Price]"), "[@Units]*[@Price]");
|
||||
assert_eq!(rt("Sales[[#This Row],Units]"), "Sales[@Units]");
|
||||
assert_eq!(rt("Sales[[#This Row], Units ]"), "Sales[@Units]");
|
||||
assert_eq!(rt("[[#This Row],Units]+[@[Unit Price]]+Sales[[#This Row],[Qty]]"), "[@Units]+[@[Unit Price]]+Sales[@Qty]");
|
||||
// Unexpected text between the brackets is an error, never silently dropped.
|
||||
for bad in [
|
||||
"[[#This Row]x]",
|
||||
"[[#This Row],[A]]x",
|
||||
"[[#Data],Col]",
|
||||
"[[#This Row],A:B]",
|
||||
"[x[#This Row]]",
|
||||
"[[#This Row],]x",
|
||||
"Sales[[#All],[A]]junk",
|
||||
"Sales[[A],[B],[C]]",
|
||||
"Sales[@[A]x]",
|
||||
] {
|
||||
assert!(parse(bad).is_err(), "{bad} should fail");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn struct_column_keeps_edge_spaces() {
|
||||
// The spaces are part of the column name: `Table1[Qty ]` names `Qty `, never `Qty`.
|
||||
let Expr::Struct(s) = parse("Table1[Qty ]").unwrap() else { panic!() };
|
||||
assert_eq!(s.col_start.as_deref(), Some("Qty "));
|
||||
let Expr::Struct(s) = parse("Table1[ Qty]").unwrap() else { panic!() };
|
||||
assert_eq!(s.col_start.as_deref(), Some(" Qty"));
|
||||
// Excel writes such a column in the double-bracket form.
|
||||
assert_eq!(rt("Table1[Qty ]"), "Table1[[Qty ]]");
|
||||
for f in ["Table1[[Qty ]]", "Table1[[ Sum for Q2 ]]", "Table1[[#Totals],[Qty ]]", "Table1[@[Qty ]]", "Table1[Unit Price]"] {
|
||||
assert_eq!(rt(f), f);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_references() {
|
||||
for f in [
|
||||
"SUM(A1:.E10)",
|
||||
"SUM(A1.:E10)",
|
||||
"SUM(A1.:.E10)",
|
||||
"SUM(A:.A)",
|
||||
"SUM($A.:.$C)",
|
||||
"ROWS(1:.5)",
|
||||
"ROWS($1.:$5)",
|
||||
"ROWS(1.:.5)",
|
||||
"Sheet2!$A$1:.B9",
|
||||
"Q1.2026!A1.:.B2",
|
||||
"'Q1 2026'!A1:.B2",
|
||||
"SUM(A1:.A9,B1.:B9)",
|
||||
"A1:.A9*2",
|
||||
] {
|
||||
assert_eq!(rt(f), f, "round trip of {f}");
|
||||
}
|
||||
let Expr::Call(_, args) = parse("SUM(A1:.E10)").unwrap() else { panic!() };
|
||||
assert!(matches!(args.as_slice(), [Expr::Unary(UnOp::Trim(TrimMode::Trailing), r)] if matches!(**r, Expr::Ref(_))));
|
||||
// Decimals, row ranges and dotted names keep their meaning.
|
||||
assert_eq!(parse("1.5+.5").unwrap(), Expr::Binary(BinOp::Add, Box::new(Expr::Number(1.5)), Box::new(Expr::Number(0.5))));
|
||||
for f in ["SUM(1:5)", "Q1.2026!A1:B2", "my.name+1", "SUM(A1:B2)*1.5", "1.:5"] {
|
||||
assert_eq!(rt(f), f);
|
||||
}
|
||||
assert_eq!(rt("'Q1.2026'!A1:B2"), "Q1.2026!A1:B2");
|
||||
assert!(matches!(parse("Q1.2026!A1:B2").unwrap(), Expr::Ref(_)));
|
||||
// File call forms.
|
||||
assert_eq!(rt("SUM(_xlfn._TRO_TRAILING(A1:E10))"), "SUM(A1:.E10)");
|
||||
assert_eq!(rt("_xlfn._TRO_LEADING(A:A)"), "A.:A");
|
||||
assert_eq!(rt("_xlfn._TRO_ALL(Sheet1!A1:B2)"), "Sheet1!A1.:.B2");
|
||||
// Not a range: printed as the equivalent call.
|
||||
assert_eq!(rt("_xlfn._TRO_ALL(B2)"), "TRIMRANGE(B2,3,3)");
|
||||
for bad in ["A1.:", ".:A1", "A1:.:B2", "A1.:.:B2"] {
|
||||
assert!(parse(bad).is_err(), "{bad} should fail");
|
||||
}
|
||||
// R1C1 keeps the operator.
|
||||
assert_eq!(print_r1c1(&parse("SUM(A1:.B2)+ROWS(2.:2)").unwrap(), gridcraft_core::CellRef::new(0, 0)), "SUM(RC:.R[1]C[1])+ROWS(R[1].:R[1])");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_references_adjust() {
|
||||
let ins = Edit::Insert { axis: Axis::Rows, at: 2, count: 2 };
|
||||
let e = parse("SUM(A1:.A5)+SUM(B:.B)+ROWS(2.:.4)").unwrap();
|
||||
assert_eq!(print(&adjust(e, "S", "S", &ins)), "SUM(A1:.A7)+SUM(B:.B)+ROWS(2.:.6)");
|
||||
let del = Edit::Delete { axis: Axis::Cols, at: 0, count: 1 };
|
||||
let e = parse("SUM(A1.:C1)+SUM(A:.A)").unwrap();
|
||||
assert_eq!(print(&adjust(e, "S", "S", &del)), "SUM(A1.:B1)+SUM(#REF!)");
|
||||
assert_eq!(print(&shift_relative(parse("SUM(A1.:.B2)").unwrap(), 1, 1)), "SUM(B2.:.C3)");
|
||||
let refs: Vec<String> = parse("SUM(Sheet2!A1:.B5)").unwrap().references().iter().map(|r| printer::reference_a1(r)).collect();
|
||||
assert_eq!(refs, ["Sheet2!A1:B5"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_long_flat_chain_without_deep_recursion() {
|
||||
// Small stack: a recursive printer overflows long before 20000 levels.
|
||||
let handle = std::thread::Builder::new()
|
||||
.stack_size(256 * 1024)
|
||||
.spawn(|| {
|
||||
let mut e = Expr::Number(1.0);
|
||||
for _ in 0..20000 {
|
||||
e = Expr::Binary(BinOp::Add, Box::new(e), Box::new(Expr::Number(1.0)));
|
||||
}
|
||||
let text = print(&e);
|
||||
let r1c1 = print_r1c1(&e, gridcraft_core::CellRef { row: 0, col: 0 });
|
||||
// Dropping the deep tree recurses; leak it so only the printer is under test.
|
||||
std::mem::forget(e);
|
||||
(text, r1c1)
|
||||
})
|
||||
.expect("spawn");
|
||||
let (text, r1c1) = handle.join().expect("printer must not overflow the stack");
|
||||
assert_eq!(text, vec!["1"; 20001].join("+"));
|
||||
assert_eq!(r1c1, text);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,10 @@ use std::cmp::Ordering;
|
||||
use gridcraft_core::parse::parse_number_text;
|
||||
use gridcraft_core::{CellError, Value, compare_numbers, compare_text};
|
||||
|
||||
/// Longest text criterion COUNTIF and its relatives accept, in UTF-16 code units as Excel
|
||||
/// counts them (😀 is two units); a longer one is `#VALUE!`.
|
||||
const MAX_CRITERION_UTF16_UNITS: usize = 255;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Op {
|
||||
Eq,
|
||||
@@ -22,6 +26,15 @@ enum Operand {
|
||||
Error(CellError),
|
||||
/// Text (lower-cased chars kept for wildcard matching).
|
||||
Text(String),
|
||||
/// A criterion cut to its first 255 UTF-16 units in the middle of a surrogate pair: the
|
||||
/// complete characters before the cut, followed (in Excel) by a lone high surrogate.
|
||||
///
|
||||
/// No cell text holds a lone surrogate, so `=` matches nothing and `<>` everything, as
|
||||
/// Excel gives 0 for SUMIFS with a criterion of 128 emoji. For `<`, `<=`, `>` and `>=` the
|
||||
/// criterion sorts just above the kept text: a cell matches `>`/`>=` when it sorts above
|
||||
/// that text, and `<`/`<=` otherwise. This is an approximation (Excel wasn't checked) and
|
||||
/// only matters for comparison criteria over 255 units.
|
||||
CutText(String),
|
||||
/// Nothing after the operator (`"="`, `"<>"`) or an empty criterion.
|
||||
Blank,
|
||||
}
|
||||
@@ -48,25 +61,52 @@ impl Criterion {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_text(t: &str) -> Criterion {
|
||||
let (op, rest) = if let Some(r) = t.strip_prefix(">=") {
|
||||
(Op::Ge, r)
|
||||
} else if let Some(r) = t.strip_prefix("<=") {
|
||||
(Op::Le, r)
|
||||
} else if let Some(r) = t.strip_prefix("<>") {
|
||||
(Op::Ne, r)
|
||||
} else if let Some(r) = t.strip_prefix('=') {
|
||||
(Op::Eq, r)
|
||||
} else if let Some(r) = t.strip_prefix('>') {
|
||||
(Op::Gt, r)
|
||||
} else if let Some(r) = t.strip_prefix('<') {
|
||||
(Op::Lt, r)
|
||||
} else {
|
||||
if t.is_empty() {
|
||||
return Criterion { op: Op::Eq, operand: Operand::Blank, bare_empty: true };
|
||||
/// Parses the criteria argument of COUNTIF, SUMIF, AVERAGEIF and the single-pair *IFS
|
||||
/// functions: like `parse`, but text longer than 255 UTF-16 code units is `#VALUE!`, as in
|
||||
/// Excel (checked on Excel 2016 and Microsoft 365: `"a"×254 & "😀"` is 255 characters but
|
||||
/// 256 units, and is `#VALUE!`).
|
||||
pub(crate) fn parse_arg(v: &Value) -> Result<Criterion, CellError> {
|
||||
match v {
|
||||
Value::Array(a) => Criterion::parse_arg(a.data.first().unwrap_or(&Value::Empty)),
|
||||
// A UTF-8 string has at least as many bytes as UTF-16 units, so short text skips the count.
|
||||
Value::Text(t) if t.len() > MAX_CRITERION_UTF16_UNITS && t.encode_utf16().nth(MAX_CRITERION_UTF16_UNITS).is_some() => {
|
||||
Err(CellError::Value)
|
||||
}
|
||||
(Op::Eq, t)
|
||||
};
|
||||
other => Ok(Criterion::parse(other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a criteria argument of an *IFS function with two or more criteria pairs. Excel
|
||||
/// doesn't reject a longer text criterion there: it matches its first 255 UTF-16 code units
|
||||
/// (checked on Excel 2016 and Microsoft 365 with COUNTIFS, SUMIFS, AVERAGEIFS, MAXIFS and
|
||||
/// MINIFS). A cut through a surrogate pair matches nothing; see `Operand::CutText`.
|
||||
pub(crate) fn parse_arg_truncated(v: &Value) -> Criterion {
|
||||
match v {
|
||||
Value::Array(a) => Criterion::parse_arg_truncated(a.data.first().unwrap_or(&Value::Empty)),
|
||||
Value::Text(t) if t.len() > MAX_CRITERION_UTF16_UNITS => {
|
||||
let mut units = 0;
|
||||
for (i, c) in t.char_indices() {
|
||||
if units + c.len_utf16() > MAX_CRITERION_UTF16_UNITS {
|
||||
if units == MAX_CRITERION_UTF16_UNITS {
|
||||
return Criterion::parse_text(&t[..i]);
|
||||
}
|
||||
// The cut falls between the two halves of `c`.
|
||||
let (op, rest) = split_op(&t[..i]);
|
||||
return Criterion { op, operand: Operand::CutText(rest.to_string()), bare_empty: false };
|
||||
}
|
||||
units += c.len_utf16();
|
||||
}
|
||||
Criterion::parse_text(t)
|
||||
}
|
||||
other => Criterion::parse(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_text(t: &str) -> Criterion {
|
||||
if t.is_empty() {
|
||||
return Criterion { op: Op::Eq, operand: Operand::Blank, bare_empty: true };
|
||||
}
|
||||
let (op, rest) = split_op(t);
|
||||
let operand = if rest.is_empty() {
|
||||
Operand::Blank
|
||||
} else if let Some(n) = parse_number_text(rest) {
|
||||
@@ -98,9 +138,10 @@ impl Criterion {
|
||||
match self.op {
|
||||
Op::Eq => blank,
|
||||
Op::Ne => !blank,
|
||||
// "<" / ">" with nothing: Excel compares against "" for text cells.
|
||||
// "<" / ">" with nothing: Excel compares against "" for text cells, but an
|
||||
// empty string never matches ("<=" and ">=" count it in neither).
|
||||
_ => match &v {
|
||||
Value::Text(t) => cmp_op(self.op, compare_text(t, "")),
|
||||
Value::Text(t) if !t.is_empty() => cmp_op(self.op, compare_text(t, "")),
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
@@ -127,9 +168,9 @@ impl Criterion {
|
||||
},
|
||||
Operand::Text(pat) => match self.op {
|
||||
Op::Eq | Op::Ne => {
|
||||
// Blank cells hold no text: `"*"` skips them and `"<>*"` counts them.
|
||||
let cell_text = match &v {
|
||||
Value::Text(t) => Some(t.to_string()),
|
||||
Value::Empty => Some(String::new()),
|
||||
_ => None,
|
||||
};
|
||||
let m = cell_text.is_some_and(|t| wildcard_match(pat, &t));
|
||||
@@ -140,10 +181,35 @@ impl Criterion {
|
||||
_ => false,
|
||||
},
|
||||
},
|
||||
Operand::CutText(kept) => match self.op {
|
||||
Op::Eq => false,
|
||||
Op::Ne => true,
|
||||
Op::Lt | Op::Le => matches!(&v, Value::Text(t) if compare_text(t, kept) != Ordering::Greater),
|
||||
Op::Gt | Op::Ge => matches!(&v, Value::Text(t) if compare_text(t, kept) == Ordering::Greater),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits a leading comparison operator (`=` when there is none) off a text criterion.
|
||||
fn split_op(t: &str) -> (Op, &str) {
|
||||
if let Some(r) = t.strip_prefix(">=") {
|
||||
(Op::Ge, r)
|
||||
} else if let Some(r) = t.strip_prefix("<=") {
|
||||
(Op::Le, r)
|
||||
} else if let Some(r) = t.strip_prefix("<>") {
|
||||
(Op::Ne, r)
|
||||
} else if let Some(r) = t.strip_prefix('=') {
|
||||
(Op::Eq, r)
|
||||
} else if let Some(r) = t.strip_prefix('>') {
|
||||
(Op::Gt, r)
|
||||
} else if let Some(r) = t.strip_prefix('<') {
|
||||
(Op::Lt, r)
|
||||
} else {
|
||||
(Op::Eq, t)
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp_op(op: Op, o: Ordering) -> bool {
|
||||
match op {
|
||||
Op::Eq => o == Ordering::Equal,
|
||||
@@ -168,19 +234,25 @@ fn tokenize(pattern: &str) -> Vec<Tok> {
|
||||
while let Some(c) = it.next() {
|
||||
match c {
|
||||
'~' => match it.next() {
|
||||
Some(n) => out.extend(n.to_lowercase().map(Tok::Char)),
|
||||
Some(n) => out.extend(std::iter::once(lower_char(n)).map(Tok::Char)),
|
||||
None => out.push(Tok::Char('~')),
|
||||
},
|
||||
'*' => out.push(Tok::Star),
|
||||
'?' => out.push(Tok::Any),
|
||||
c => out.extend(c.to_lowercase().map(Tok::Char)),
|
||||
c => out.extend(std::iter::once(lower_char(c)).map(Tok::Char)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Lowercase one char to exactly one char, so positions in the lowered text match the original
|
||||
/// (U+0130 `İ` folds to `i`, like `fold` in text.rs).
|
||||
fn lower_char(c: char) -> char {
|
||||
c.to_lowercase().next().unwrap_or(c)
|
||||
}
|
||||
|
||||
fn lower_chars(s: &str) -> Vec<char> {
|
||||
s.chars().flat_map(char::to_lowercase).collect()
|
||||
s.chars().map(lower_char).collect()
|
||||
}
|
||||
|
||||
/// Whether the pattern contains an unescaped wildcard.
|
||||
@@ -290,6 +362,9 @@ mod tests {
|
||||
assert!(m("<>", Value::from("a")));
|
||||
assert!(!m("<>", Value::Empty));
|
||||
assert!(m("TRUE", Value::Bool(true)));
|
||||
// A bare "<=" or ">=" never matches an empty string (Excel 365: COUNTIF(="", "<=") is 0).
|
||||
assert!(!m("<=", Value::from("")));
|
||||
assert!(!m(">=", Value::from("")));
|
||||
assert!(m("<b", Value::from("apple")));
|
||||
assert!(!m("<b", Value::Number(1.0)));
|
||||
assert!(m("#N/A", Value::Error(CellError::NA)));
|
||||
@@ -298,6 +373,13 @@ mod tests {
|
||||
assert!(lookup_equal(&Value::Number(0.3), &Value::Number(0.1 + 0.2), false));
|
||||
assert!(m("<>a*", Value::from("bcd")));
|
||||
assert!(m(">1/1/2020", Value::Number(44000.0)));
|
||||
// Text patterns never match blank cells, but an empty string is text.
|
||||
assert!(!m("*", Value::Empty));
|
||||
assert!(m("*", Value::from("")));
|
||||
assert!(m("<>*", Value::Empty));
|
||||
assert!(!m("<>*", Value::from("")));
|
||||
assert!(!m("?*", Value::Empty));
|
||||
assert!(m("<>a*", Value::Empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -310,6 +392,8 @@ mod tests {
|
||||
assert_eq!(wildcard_find("b?d", "abxxd bcd", 0), Some(6));
|
||||
assert_eq!(wildcard_find("c*", "abcd", 0), Some(2));
|
||||
assert_eq!(wildcard_find("z", "abcd", 0), None);
|
||||
assert_eq!(wildcard_find("b", "a\u{130}bc", 0), Some(2));
|
||||
assert!(wildcard_match("i*", "\u{130}stanbul"));
|
||||
assert!(has_wildcards("a*"));
|
||||
assert!(!has_wildcards("abc"));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user