mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-27 21:40:01 +00:00
Compare commits
768
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9797c2bedb | ||
|
|
97f2754c1d | ||
|
|
6357908c69 | ||
|
|
3bed16aea8 | ||
|
|
dd6a17d239 | ||
|
|
296a4bf9a6 | ||
|
|
8cc5022abb | ||
|
|
4d5c8f2a4d | ||
|
|
1af87a37c5 | ||
|
|
401041f00c | ||
|
|
959497cad6 | ||
|
|
c10f94fcd3 | ||
|
|
5c4fcc65bd | ||
|
|
86a0c41e8f | ||
|
|
c159362b95 | ||
|
|
93d8e97d16 | ||
|
|
55d6879a94 | ||
|
|
791beee9f4 | ||
|
|
5aa0bd29e2 | ||
|
|
94cb40be98 | ||
|
|
ed881a564f | ||
|
|
33e37398fd | ||
|
|
d88f56be7b | ||
|
|
269eb10bed | ||
|
|
90ec7db3b5 | ||
|
|
7807aaed67 | ||
|
|
565b4ea705 | ||
|
|
364e967e69 | ||
|
|
b55ea8acd3 | ||
|
|
6fba6d3688 | ||
|
|
16c9ef0b76 | ||
|
|
996c7ba467 | ||
|
|
9e8fdbc2df | ||
|
|
088f9193a8 | ||
|
|
2f7ac98c44 | ||
|
|
89bf004226 | ||
|
|
59f6b6c14a | ||
|
|
604cdf03f0 | ||
|
|
279c530efd | ||
|
|
abee6d6926 | ||
|
|
79285118ca | ||
|
|
072493baec | ||
|
|
707091be3f | ||
|
|
3852c2335a | ||
|
|
5bc7f92680 | ||
|
|
04720627bd | ||
|
|
91f9b87070 | ||
|
|
396c794844 | ||
|
|
93e42af30d | ||
|
|
cf9a1aba48 | ||
|
|
b5386047d9 | ||
|
|
b8cd3891fb | ||
|
|
2469308bf6 | ||
|
|
c5e735410a | ||
|
|
728f639332 | ||
|
|
6f57f7f4ae | ||
|
|
6ec2bab62b | ||
|
|
eb73335d12 | ||
|
|
4b35af1609 | ||
|
|
2fbd3585af | ||
|
|
e3f897ce7e | ||
|
|
2514c099b1 | ||
|
|
34da5683a6 | ||
|
|
24a0ce5a67 | ||
|
|
a5039ec907 | ||
|
|
a09a6ac3c8 | ||
|
|
f70dcc0e2e | ||
|
|
c08f843218 | ||
|
|
a99895c037 | ||
|
|
41b8ec1218 | ||
|
|
5fbc21b2b3 | ||
|
|
f53f8ede73 | ||
|
|
55a9a23d04 | ||
|
|
dbc919b3f7 | ||
|
|
916371a2b1 | ||
|
|
e59e03cd9e | ||
|
|
eda1871f36 | ||
|
|
74b93f3766 | ||
|
|
1dbd8db607 | ||
|
|
501fca9eb5 | ||
|
|
23d0784b11 | ||
|
|
6842aee683 | ||
|
|
22b85c371f | ||
|
|
271ece082d | ||
|
|
cc92d8a941 | ||
|
|
c9b822b858 | ||
|
|
ceaa6c129f | ||
|
|
7c5fec1a69 | ||
|
|
d5ebe99cd7 | ||
|
|
3dd804da3f | ||
|
|
dc5db3ccde | ||
|
|
8efbabf8e9 | ||
|
|
f27f874e3c | ||
|
|
b6dd901fe6 | ||
|
|
a2ac77711d | ||
|
|
d731fef146 | ||
|
|
77a569cf91 | ||
|
|
85d6d048d9 | ||
|
|
c2ddc94c0d | ||
|
|
17e94d26d2 | ||
|
|
5c89c4adc2 | ||
|
|
62c4cb3cb7 | ||
|
|
4744b591d1 | ||
|
|
0887efd788 | ||
|
|
2983959016 | ||
|
|
203b41a0c2 | ||
|
|
40dbdd23c6 | ||
|
|
bd050fc833 | ||
|
|
dbe301d9bb | ||
|
|
b22fa1d193 | ||
|
|
35ea16aa63 | ||
|
|
23fe90cd42 | ||
|
|
545ed706a9 | ||
|
|
abda1fe767 | ||
|
|
508caac2d1 | ||
|
|
313f50a96b | ||
|
|
ac5bfaf3a6 | ||
|
|
b38b2f8900 | ||
|
|
3ac1f3746f | ||
|
|
8c911f0f25 | ||
|
|
0d32f7a504 | ||
|
|
aa2d0d1f17 | ||
|
|
09d25ecaf6 | ||
|
|
2c28d0fc7e | ||
|
|
62aacb3e7e | ||
|
|
9120829df1 | ||
|
|
21df25dbed | ||
|
|
167f25f405 | ||
|
|
bfe8dd24f9 | ||
|
|
ab445c1f7b | ||
|
|
3352b90f1e | ||
|
|
e1b87cab01 | ||
|
|
86a539e22b | ||
|
|
b5766097e8 | ||
|
|
404c71b9c3 | ||
|
|
8cee925a0b | ||
|
|
c1bc906ee7 | ||
|
|
7cff2527df | ||
|
|
b6ef428a89 | ||
|
|
8f0ac5ad69 | ||
|
|
03fcfaa33b | ||
|
|
4884d635a7 | ||
|
|
ed4230f8b9 | ||
|
|
4a0d24013f | ||
|
|
4ef9f58ecc | ||
|
|
a79a50120c | ||
|
|
8de700ad93 | ||
|
|
cbefffe721 | ||
|
|
2bb8f32254 | ||
|
|
fa6c397a44 | ||
|
|
def333fe42 | ||
|
|
d57bbabe76 | ||
|
|
c3ff583280 | ||
|
|
4318d0e82e | ||
|
|
1c9a8ae835 | ||
|
|
47a382c3e0 | ||
|
|
3e888103c1 | ||
|
|
0f36a7aee3 | ||
|
|
1eff34e69d | ||
|
|
2d97c9c629 | ||
|
|
01be559f9d | ||
|
|
062c34b69a | ||
|
|
2798b67d09 | ||
|
|
7360e8c50b | ||
|
|
4870243e3f | ||
|
|
5f9b38946b | ||
|
|
014e0583b7 | ||
|
|
8105980843 | ||
|
|
0a785c7f12 | ||
|
|
60e424ee52 | ||
|
|
b876c97212 | ||
|
|
4e8562a9a4 | ||
|
|
66610a7a16 | ||
|
|
628b2c99f3 | ||
|
|
e716c268ee | ||
|
|
d4b8aae4d4 | ||
|
|
1e6c3f2a61 | ||
|
|
168370bc2a | ||
|
|
9934dfd0b3 | ||
|
|
37c5dbf021 | ||
|
|
00bed75921 | ||
|
|
1b95f93b30 | ||
|
|
6d12ac6720 | ||
|
|
7538c56868 | ||
|
|
bd943295a8 | ||
|
|
4097668066 | ||
|
|
a53b23d470 | ||
|
|
8466440421 | ||
|
|
531989a2e5 | ||
|
|
fe30de8f7f | ||
|
|
55222b8814 | ||
|
|
3f8d3930bf | ||
|
|
fde057f8c2 | ||
|
|
45181a217f | ||
|
|
86a7d5e0c0 | ||
|
|
4d0333367b | ||
|
|
7436c503a9 | ||
|
|
5149a85932 | ||
|
|
c068f77254 | ||
|
|
45ac58cf03 | ||
|
|
aab0a9c385 | ||
|
|
ccbf56c05c | ||
|
|
a5709e22e0 | ||
|
|
8fc8aa7857 | ||
|
|
aab64fdebc | ||
|
|
5fb3b44f69 | ||
|
|
9c7fc39563 | ||
|
|
6144228f45 | ||
|
|
dddc649a78 | ||
|
|
731c90dcc1 | ||
|
|
8bbc760f5d | ||
|
|
cfc0922126 | ||
|
|
e9449b55ab | ||
|
|
7f2ae3cff8 | ||
|
|
5682daedc1 | ||
|
|
c41535a75c | ||
|
|
1175b54e65 | ||
|
|
5e2bca0ae7 | ||
|
|
d23654cdf0 | ||
|
|
dd86b43150 | ||
|
|
f9b39debd2 | ||
|
|
637e7809f0 | ||
|
|
7486d1021b | ||
|
|
35ca6435a8 | ||
|
|
8d6e207f04 | ||
|
|
0d23a0b12c | ||
|
|
d4c97a3329 | ||
|
|
e16b5fa179 | ||
|
|
7d0f153f9d | ||
|
|
d5c8c079cb | ||
|
|
30013b349c | ||
|
|
a1b96711b6 | ||
|
|
2f4b702530 | ||
|
|
fdb96edf1f | ||
|
|
b8dcf17039 | ||
|
|
ed6ab029e8 | ||
|
|
086a464792 | ||
|
|
d8e5faee9b | ||
|
|
9d9c9cdf83 | ||
|
|
c00fb9b67e | ||
|
|
e86b2ef0ef | ||
|
|
1e087adf28 | ||
|
|
50a6ea444a | ||
|
|
7bd4c2d17b | ||
|
|
51ab33dbe3 | ||
|
|
dec0e1a6c0 | ||
|
|
c2a0cae3fe | ||
|
|
7f57431b57 | ||
|
|
06c16b3c8d | ||
|
|
169f5660c3 | ||
|
|
9e40767a60 | ||
|
|
a730bbe78a | ||
|
|
bdf7d657a4 | ||
|
|
3f3199fcbb | ||
|
|
427cfad27e | ||
|
|
3c22a5fd7a | ||
|
|
5236d8e4ba | ||
|
|
5b59dbf73f | ||
|
|
9e1abd22a2 | ||
|
|
0a642f86eb | ||
|
|
7e05f4e57e | ||
|
|
0329de4388 | ||
|
|
1da7c3ae92 | ||
|
|
cff2302172 | ||
|
|
0ed3425179 | ||
|
|
81daff425b | ||
|
|
1cf5054de4 | ||
|
|
ad45897ec5 | ||
|
|
93bb7443b2 | ||
|
|
cb08a89917 | ||
|
|
595a2ee0a8 | ||
|
|
f5737157a0 | ||
|
|
53fafbf5d5 | ||
|
|
f06ecfaceb | ||
|
|
0980f3aa2f | ||
|
|
06247bf36c | ||
|
|
f8892ee1c1 | ||
|
|
a87983891f | ||
|
|
f7fd68e709 | ||
|
|
7cf59c0a5a | ||
|
|
93378f27bb | ||
|
|
b189d8f7df | ||
|
|
f187179552 | ||
|
|
b92f45b004 | ||
|
|
46a8525585 | ||
|
|
ce12e9f7f8 | ||
|
|
b75b155848 | ||
|
|
0a6e534676 | ||
|
|
0f2c32d1a8 | ||
|
|
d89a3afd22 | ||
|
|
5e75ffe429 | ||
|
|
67bea056d5 | ||
|
|
e6f5de7e42 | ||
|
|
14bc675778 | ||
|
|
e59c6dfda2 | ||
|
|
ef124ce4a9 | ||
|
|
e4d0388944 | ||
|
|
384e6189e7 | ||
|
|
80897d8bd4 | ||
|
|
7299661159 | ||
|
|
dea77f4811 | ||
|
|
187f88aa1c | ||
|
|
6429399f20 | ||
|
|
fe730ad3fc | ||
|
|
e435c58930 | ||
|
|
710ece507c | ||
|
|
43bf785515 | ||
|
|
d977856457 | ||
|
|
a05d381c5c | ||
|
|
e7177f4948 | ||
|
|
c395f2d60b | ||
|
|
fc4701104c | ||
|
|
2537e5ff0a | ||
|
|
ba59c101c4 | ||
|
|
3d38b86232 | ||
|
|
4091ad6fe7 | ||
|
|
5f73d9787c | ||
|
|
7d571db2d0 | ||
|
|
7c3b4e288a | ||
|
|
4d5ff9dc6a | ||
|
|
3f6de52269 | ||
|
|
a7ae5a8668 | ||
|
|
111fc70b75 | ||
|
|
cf6e4a57a8 | ||
|
|
7853f14449 | ||
|
|
f678a3f99c | ||
|
|
3316bac277 | ||
|
|
fe07dbc654 | ||
|
|
8b9f9527f1 | ||
|
|
7769efdbb9 | ||
|
|
c46a90c8c8 | ||
|
|
2ae710e65b | ||
|
|
f32fefddcf | ||
|
|
35996c6e2e | ||
|
|
d56e3638fd | ||
|
|
f17f730887 | ||
|
|
a4aee78391 | ||
|
|
815627264f | ||
|
|
b98a7c43de | ||
|
|
ad7ec8d775 | ||
|
|
28086016fe | ||
|
|
8aa01a7750 | ||
|
|
512bf992f5 | ||
|
|
322cc7e93a | ||
|
|
045f938332 | ||
|
|
61a3a47940 | ||
|
|
7cd04cd023 | ||
|
|
8cb34cd312 | ||
|
|
292a0e1e8e | ||
|
|
60ec576e0c | ||
|
|
c0feebc9b4 | ||
|
|
cb42d58c54 | ||
|
|
04c30b4901 | ||
|
|
349fb760b1 | ||
|
|
7e8ffc7474 | ||
|
|
21306e150f | ||
|
|
82397d57ac | ||
|
|
cd4ea7b481 | ||
|
|
ff4d018290 | ||
|
|
edc9afad59 | ||
|
|
c4d0aa8773 | ||
|
|
6d02203e8f | ||
|
|
7ee5c5ef36 | ||
|
|
d70646adfc | ||
|
|
46dc11dc9f | ||
|
|
94fbd67d78 | ||
|
|
cea63e0611 | ||
|
|
ca5796662f | ||
|
|
ba605b4f69 | ||
|
|
bb91ea0410 | ||
|
|
f21dc313db | ||
|
|
fd664055df | ||
|
|
72778aba99 | ||
|
|
2a506bfc85 | ||
|
|
09d52cc7cd | ||
|
|
313fdef652 | ||
|
|
92b3ab1886 | ||
|
|
84e0a241b7 | ||
|
|
6315dacc9e | ||
|
|
0afc01aa1a | ||
|
|
57de9d5d6f | ||
|
|
f56753ddb7 | ||
|
|
19b8009d2a | ||
|
|
618ad0ba74 | ||
|
|
ed1f3964af | ||
|
|
ad380da0e9 | ||
|
|
094ce5ec8d | ||
|
|
1b128ffb24 | ||
|
|
1fb2dfd720 | ||
|
|
d5cdd4b335 | ||
|
|
23d2906408 | ||
|
|
d098a7dfc3 | ||
|
|
7984f0f2bd | ||
|
|
302019d815 | ||
|
|
2240950eb6 | ||
|
|
a7a319c5c7 | ||
|
|
30f24fd239 | ||
|
|
fe9162c9cf | ||
|
|
ee886d6db6 | ||
|
|
2829120d4d | ||
|
|
def4067247 | ||
|
|
51bc57b489 | ||
|
|
0622859f49 | ||
|
|
3b70b106ef | ||
|
|
c8ef1b8b1b | ||
|
|
9291c39687 | ||
|
|
8b0949f8ae | ||
|
|
5f0e1d1347 | ||
|
|
62899818be | ||
|
|
f90c2c0fe2 | ||
|
|
de3d3073e0 | ||
|
|
f33a2eb90a | ||
|
|
7fc0147965 | ||
|
|
5d578bef00 | ||
|
|
c3969a34c9 | ||
|
|
8fbd9ea4ab | ||
|
|
c3c7ac378d | ||
|
|
1ec173a087 | ||
|
|
d16e311b8c | ||
|
|
5c9f1b757a | ||
|
|
3ca82dd1e6 | ||
|
|
f0de6913d1 | ||
|
|
1baac9125c | ||
|
|
c01eb6cd2a | ||
|
|
3131f30f5c | ||
|
|
b2cb4eb91f | ||
|
|
baff2e50cc | ||
|
|
335109beb5 | ||
|
|
4b65b85b23 | ||
|
|
155d254977 | ||
|
|
6fb9b5cc3d | ||
|
|
3fb6f4334e | ||
|
|
b1a1eee435 | ||
|
|
7a19af93dd | ||
|
|
68d54cc1b6 | ||
|
|
5b6c4a0739 | ||
|
|
839c35635a | ||
|
|
a8e5fdcb75 | ||
|
|
d2e97a485c | ||
|
|
ed365d9502 | ||
|
|
73037efbc5 | ||
|
|
e5c66c0c56 | ||
|
|
6856c3cfdf | ||
|
|
25715e77c3 | ||
|
|
493ceae678 | ||
|
|
b346a5fcce | ||
|
|
e1ae4d55ce | ||
|
|
2be4be9dd2 | ||
|
|
dd55a1f4ce | ||
|
|
d8be9537ac | ||
|
|
58f4a5d6f3 | ||
|
|
a4094cc173 | ||
|
|
7b758ef1c3 | ||
|
|
2de9f32d4b | ||
|
|
e27bb51c58 | ||
|
|
c69969fbfc | ||
|
|
475019d69c | ||
|
|
a7b39a0ed3 | ||
|
|
379c6e2265 | ||
|
|
f81a8d84b2 | ||
|
|
5168a1c9c7 | ||
|
|
1ac75eb858 | ||
|
|
5f4f5ce4c5 | ||
|
|
1e8541d050 | ||
|
|
5aac662668 | ||
|
|
d9d9e3c628 | ||
|
|
8516e5fd0d | ||
|
|
b4beded739 | ||
|
|
9c5b6b2dbe | ||
|
|
78f0b47b43 | ||
|
|
6e2bf00b14 | ||
|
|
eb94d99326 | ||
|
|
d2a608c750 | ||
|
|
25b01d9497 | ||
|
|
2f7e6bf878 | ||
|
|
a738b160db | ||
|
|
be0b6232e8 | ||
|
|
a1fc982132 | ||
|
|
8c0f60ec96 | ||
|
|
8e0d621a0f | ||
|
|
6d3c10bbf2 | ||
|
|
5f55b755fa | ||
|
|
1f3c7a3390 | ||
|
|
a97d858b9e | ||
|
|
5f1e609a69 | ||
|
|
e69515aff1 | ||
|
|
6c447a8082 | ||
|
|
c9e5cdbf7d | ||
|
|
fb68684795 | ||
|
|
6b34b6c6a8 | ||
|
|
c122e5f893 | ||
|
|
80f29610ee | ||
|
|
4595d8dace | ||
|
|
9fbd95e037 | ||
|
|
0de56624d5 | ||
|
|
af4f17184c | ||
|
|
921cdc974f | ||
|
|
6aa6a9cee8 | ||
|
|
73999fcd89 | ||
|
|
bcac6859e3 | ||
|
|
210b8c9cd6 | ||
|
|
1668d576a8 | ||
|
|
478e21a988 | ||
|
|
7eb044921b | ||
|
|
7047dca872 | ||
|
|
a5e03454a4 | ||
|
|
b3b0ceabae | ||
|
|
f3b88ae36b | ||
|
|
787b12069d | ||
|
|
1836cd83a1 | ||
|
|
ab6a4b4030 | ||
|
|
a5d6efab4d | ||
|
|
b5e831d461 | ||
|
|
17abd46b97 | ||
|
|
9187049f7f | ||
|
|
946b98c375 | ||
|
|
14fbd977b7 | ||
|
|
26b9dec45b | ||
|
|
53228adb7d | ||
|
|
743865a836 | ||
|
|
364e48dcab | ||
|
|
a0a2627894 | ||
|
|
47c5e3b816 | ||
|
|
9777459eb6 | ||
|
|
91e6a41a63 | ||
|
|
5378f80672 | ||
|
|
437b7f2df0 | ||
|
|
8893ead179 | ||
|
|
cd6fe4f8bd | ||
|
|
a276e2f21d | ||
|
|
496aa28ed3 | ||
|
|
2506ba3ddb | ||
|
|
15eef6b434 | ||
|
|
3b8daf900c | ||
|
|
2295cc71c6 | ||
|
|
2c976a6e6b | ||
|
|
4efd8fc0db | ||
|
|
40268a3c67 | ||
|
|
cc2229a08b | ||
|
|
2c6ba8a658 | ||
|
|
1396236440 | ||
|
|
6531650600 | ||
|
|
c998ff1ffb | ||
|
|
dac313337d | ||
|
|
2c4f471566 | ||
|
|
6a15912b06 | ||
|
|
96ae211258 | ||
|
|
04f8797ee4 | ||
|
|
9680794bc4 | ||
|
|
3adf662578 | ||
|
|
a6f9b80e43 | ||
|
|
4d0d3bdbfa | ||
|
|
4550a1eba7 | ||
|
|
8e81dade33 | ||
|
|
b4b89a4e36 | ||
|
|
6fe8a65c5c | ||
|
|
5846f59081 | ||
|
|
a2312fff8b | ||
|
|
92dcd308c2 | ||
|
|
2a8cc47a3f | ||
|
|
10bbee4047 | ||
|
|
cc3858a394 | ||
|
|
cf17534e7b | ||
|
|
7e643e2930 | ||
|
|
dbacb4cc80 | ||
|
|
7b83509a93 | ||
|
|
f3c214b2dd | ||
|
|
a2e3f265c0 | ||
|
|
10115f41ed | ||
|
|
d57d5cf267 | ||
|
|
be8efa6d0b | ||
|
|
2cdffc6282 | ||
|
|
2e1a744c6c | ||
|
|
8ec8445b5a | ||
|
|
0b31398c0d | ||
|
|
fb19a4fb87 | ||
|
|
d479ff2f4b | ||
|
|
843e09fb77 | ||
|
|
f4e7a1e33f | ||
|
|
d853b05dbd | ||
|
|
73d36eef04 | ||
|
|
7a3f75d7c3 | ||
|
|
db21e558d1 | ||
|
|
8211e218ce | ||
|
|
2f744078ec | ||
|
|
ef732f04ce | ||
|
|
f300a41236 | ||
|
|
f4049f9e49 | ||
|
|
5c987d1eae | ||
|
|
4d0074e5cf | ||
|
|
af3b87e965 | ||
|
|
9dae419df2 | ||
|
|
f0397d5f5b | ||
|
|
e1a5244c0c | ||
|
|
19bc9660ff | ||
|
|
b7547111f3 | ||
|
|
a19b16f211 | ||
|
|
1fcaffe7b7 | ||
|
|
a7a708d0f6 | ||
|
|
01da1806d1 | ||
|
|
2fbe96820c | ||
|
|
abf93c2e23 | ||
|
|
9bbcb7ce90 | ||
|
|
7155ced916 | ||
|
|
571bdf68ad | ||
|
|
c4920c463b | ||
|
|
0ddd8684ef | ||
|
|
15661dc973 | ||
|
|
1053b66a0e | ||
|
|
b023410ca4 | ||
|
|
7a8b2261f8 | ||
|
|
dacff8ff97 | ||
|
|
c708afad34 | ||
|
|
4081acd660 | ||
|
|
712a17f1e6 | ||
|
|
077533edb8 | ||
|
|
260b84d093 | ||
|
|
9bd604aa12 | ||
|
|
cfcde5bfbd | ||
|
|
2f86b52706 | ||
|
|
e3fa42607f | ||
|
|
4b86dc9dc9 | ||
|
|
1fe4f79db6 | ||
|
|
1e3fc9ee37 | ||
|
|
de8f36ee33 | ||
|
|
06c2b1440b | ||
|
|
f7380202fe | ||
|
|
4fa40fb932 | ||
|
|
a53483874e | ||
|
|
dd136062f5 | ||
|
|
6f63c784bc | ||
|
|
a98f290ec0 | ||
|
|
d5b23a5e79 | ||
|
|
870e2658ae | ||
|
|
18f11876e3 | ||
|
|
80b8786969 | ||
|
|
d0ad5ba6dc | ||
|
|
a5b1415c9e | ||
|
|
ce64da3286 | ||
|
|
87f9c4b12d | ||
|
|
ceca4b151e | ||
|
|
70fb318377 | ||
|
|
14c81bfdd6 | ||
|
|
5a035ac5c6 | ||
|
|
81a8abc12b | ||
|
|
8b17f1e779 | ||
|
|
6cfd7d83aa | ||
|
|
a327501fb1 | ||
|
|
516b19c151 | ||
|
|
fded60a325 | ||
|
|
c693db2b9f | ||
|
|
a2caeedcd9 | ||
|
|
2a10509d65 | ||
|
|
38fa0dc050 | ||
|
|
ae50127952 | ||
|
|
95c0800c22 | ||
|
|
707ce9e14c | ||
|
|
b97c27f2b3 | ||
|
|
2d65676f5d | ||
|
|
79324b6c17 | ||
|
|
d2506c03d9 | ||
|
|
214ad97372 | ||
|
|
46bdd416bb | ||
|
|
3d923f3b30 | ||
|
|
937634a31a | ||
|
|
d07795efae | ||
|
|
591b97aede | ||
|
|
c506178922 | ||
|
|
a6b73d11e9 | ||
|
|
5e0fe2d28d | ||
|
|
fb38290e45 | ||
|
|
b107dedf7e | ||
|
|
9b7c5ca1f6 | ||
|
|
ec77c810f8 | ||
|
|
8471ccace5 | ||
|
|
bf9531954d | ||
|
|
41a1a3f8bc | ||
|
|
10c023754e | ||
|
|
fa17a79cba | ||
|
|
154273a7d8 | ||
|
|
2a59d7f15d | ||
|
|
818c97a632 | ||
|
|
c4ef580a22 | ||
|
|
17aae2da04 | ||
|
|
aea9a02bce | ||
|
|
a4309846b2 | ||
|
|
fd6d6cee88 | ||
|
|
852b1a4bfb | ||
|
|
a6bedd5153 | ||
|
|
3aa8727fd6 | ||
|
|
1d0360153f | ||
|
|
df2b24dbfd | ||
|
|
db2fffa9be | ||
|
|
1da552fc9f | ||
|
|
42ad67ab13 | ||
|
|
b21dd9151f | ||
|
|
b9324d9179 | ||
|
|
edd64e9afc | ||
|
|
81e523e431 | ||
|
|
60c758af66 | ||
|
|
6ce1ce9c6d | ||
|
|
9b594efc67 | ||
|
|
db2ff17229 | ||
|
|
2681d7b6df | ||
|
|
f30c206a05 | ||
|
|
3d82a9cf4e | ||
|
|
5b8c2cde8d | ||
|
|
78cf72ae0f | ||
|
|
0a659997ee | ||
|
|
a6870d0e3f | ||
|
|
38696b93a4 | ||
|
|
744c6cde44 | ||
|
|
8338a35da6 | ||
|
|
4e85a1fd21 | ||
|
|
d51a6de104 | ||
|
|
9424a96d9b | ||
|
|
4f92fc417b | ||
|
|
f3a7c72bb6 | ||
|
|
b56c2ddc7e | ||
|
|
12c08d7e9d | ||
|
|
7bce227ed6 | ||
|
|
32b2bbe471 | ||
|
|
2b297cd194 | ||
|
|
727c727ff5 | ||
|
|
1f6adbe382 | ||
|
|
c29f282712 | ||
|
|
c0ae95f721 | ||
|
|
601cc60cfc | ||
|
|
132bd4e9a8 | ||
|
|
fdad356fd2 | ||
|
|
a8810d7a7a | ||
|
|
0c78ddf79f | ||
|
|
1af4d38e71 | ||
|
|
4215f07bb3 | ||
|
|
9f127b5b80 | ||
|
|
480b8a88b5 | ||
|
|
b82c4fbd30 | ||
|
|
6421731f9a | ||
|
|
df97bf8445 | ||
|
|
cdb3c163ec | ||
|
|
5a72aff0c5 | ||
|
|
43ccb39ba3 | ||
|
|
e24a8631b4 | ||
|
|
df34dac2d1 | ||
|
|
8d90b1ea03 | ||
|
|
921405fa02 | ||
|
|
f066fe994e | ||
|
|
8732325b58 | ||
|
|
ec3666f913 | ||
|
|
20a85b2caf | ||
|
|
7fe89ba872 | ||
|
|
1ba5d323d0 | ||
|
|
ef6776db8b | ||
|
|
766b6d3a93 | ||
|
|
0739f71fac | ||
|
|
b60d37e4e9 | ||
|
|
fadcec3683 | ||
|
|
e16b95eb82 | ||
|
|
df4599d2cd | ||
|
|
374ab0f127 | ||
|
|
add4ebf5d8 | ||
|
|
8fc6aa7082 | ||
|
|
ce8f5fca22 | ||
|
|
bf15f965ae | ||
|
|
cde1dbb2e4 | ||
|
|
7d3516ab33 | ||
|
|
a7e1a4a99b | ||
|
|
4972675b1b |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408285582,
|
||||
"producer_workflow_id": 429713469,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "3dee18226ed28134896f69fb8b280fff9247ec7f",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@3dee18226ed28134896f69fb8b280fff9247ec7f",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "3dee18226ed28134896f69fb8b280fff9247ec7f",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -12,6 +12,7 @@ workflows:
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/nix.yml': []
|
||||
'.github/workflows/notify-services.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: 3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: gridcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
@@ -50,8 +50,6 @@ jobs:
|
||||
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 }}
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: 3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: gridcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -81,4 +81,5 @@ Paths and conventions:
|
||||
- Test corpora live in a separate corpus repository, pinned and sha256-verified. Test workbooks are built in code.
|
||||
- Progress log: `ROADMAP.md`. `plan/` is an optional gitignored notebook.
|
||||
- Run with a control channel: `cargo run --release -p gridcraft -- --sample sales --control 7979`. Drive it with `gridcraft-cli send 7979 <method> '<json>'`; methods are in `crates/ui-egui/src/control.rs`, the protocol in `docs/control-protocol.md`. Offscreen render: `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli mcp`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog id `headless: yes` only when the engine registry (what `gridcraft-cli` and the MCP server load) has it. A missing id takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs`, or reads `unknown`. When a command lands, delete its mark; the check fails on a stale one.
|
||||
- Docs: `ROADMAP.md`, `docs/gaps.md` (ranked work), `docs/architecture.md`, `docs/target-app-parity.md`, `docs/roadmap.md`, `docs/contributors.md`.
|
||||
|
||||
Generated
+30
-50
@@ -211,15 +211,6 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -236,7 +227,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -923,6 +914,15 @@ version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie-factory"
|
||||
version = "0.3.3"
|
||||
@@ -1601,7 +1601,7 @@ dependencies = [
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip 9.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1709,7 +1709,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259e
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1843,17 +1843,6 @@ version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dify"
|
||||
version = "0.8.0"
|
||||
@@ -1907,7 +1896,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2314,7 +2303,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2912,7 +2901,7 @@ dependencies = [
|
||||
"log",
|
||||
"quick-xml 0.41.0",
|
||||
"serde_json",
|
||||
"zip 3.0.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2949,7 +2938,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"unicode-segmentation",
|
||||
"web-time",
|
||||
"zip 3.0.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2998,6 +2987,7 @@ dependencies = [
|
||||
"gridcraft-math",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -3105,7 +3095,7 @@ dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zip 3.0.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4845,7 +4835,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]]
|
||||
@@ -5334,7 +5324,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5775,7 +5765,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5834,7 +5824,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6654,7 +6644,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7749,7 +7739,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8494,32 +8484,22 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "3.0.0"
|
||||
version = "9.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704"
|
||||
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
|
||||
dependencies = [
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"indexmap",
|
||||
"libc",
|
||||
"memchr",
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+3
-1
@@ -65,8 +65,10 @@ web-time = "1.1.0"
|
||||
rayon = "1"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`).
|
||||
sha1 = { version = "0.11", default-features = false }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
|
||||
# equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is
|
||||
|
||||
+29
-1
@@ -2,9 +2,10 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **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.
|
||||
This page is the summary. The detail is in:
|
||||
@@ -151,10 +152,15 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) |
|
||||
| 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used |
|
||||
| 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged |
|
||||
| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 |
|
||||
| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) |
|
||||
| 2026-10-25 | Charts: 100% Stacked Line and 100% Stacked Line with Markers (`insert.chart` `{type: "line", subtype: "stacked100"}` and `"stacked100Markers"`), drawn as each value's share of its category's total; XLSX `percentStacked` line charts open as 100% stacked instead of stacked |
|
||||
| 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently |
|
||||
| 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export |
|
||||
| 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority |
|
||||
| 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks |
|
||||
| 2026-10-26 | `cargo xtask bench`: ten fixed in-code workbooks (100k rows) time edits, formula entry, Calculate Now, sort and XLSX save/open, check their results and compare with a saved baseline. On an M2 Pro a 100k-dependent edit recalculates in 90–106 ms and 300k formulas in 395–455 ms |
|
||||
| 2026-10-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) |
|
||||
| 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before |
|
||||
| 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step |
|
||||
| 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) |
|
||||
@@ -165,6 +171,9 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does |
|
||||
| 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share |
|
||||
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
|
||||
| 2026-10-24 | XLSX charts keep what GridCraft doesn't model on save: an embedded chart that was not edited (moving or resizing aside) is written back from its original chart part, with its style, colour and user-shape parts, while every sheet its formulas name still exists; an edited chart is written from the model as before (#1668) |
|
||||
| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) |
|
||||
| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel |
|
||||
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
|
||||
| 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row |
|
||||
| 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) |
|
||||
@@ -184,14 +193,20 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change |
|
||||
| 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS |
|
||||
| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) |
|
||||
| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root), with known differences in some `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) |
|
||||
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
|
||||
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
|
||||
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
|
||||
| 2026-10-15 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it |
|
||||
| 2026-10-15 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends it |
|
||||
| 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it |
|
||||
| 2026-10-14 | SORT, SORTBY and Data > Sort order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison |
|
||||
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
|
||||
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
|
||||
| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate |
|
||||
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
|
||||
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
|
||||
| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning |
|
||||
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
|
||||
| 2026-10-14 | XLSX: formulas opened with dynamic-array metadata (`cm`) keep it on save, with `xl/metadata.xml`. Before, a formula returning one value lost it (11 of 40 corpus files that have the part lost it entirely), and Excel recalculated some of them with implicit intersection (`SUMPRODUCT(IFERROR(...))` changed value) |
|
||||
| 2026-10-14 | Recalculation: a dynamic array's anchor given a new formula that reads its old spill area (`A1` was `=SEQUENCE(3)`, becomes `=SUM(A2:A3)+1` or `=SEQUENCE(1,A2+1)`) sees that area empty instead of the old values |
|
||||
@@ -209,6 +224,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
|
||||
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
|
||||
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
|
||||
| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) |
|
||||
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
|
||||
| 2026-10-12 | PDF writer: objects are written straight to the output, identical pictures are stored once, style operators are emitted only when they change, `q` nesting is limited to 28 and polyline joins no longer leak into later strokes (#816) |
|
||||
| 2026-10-12 | Insert › Text › WordArt (`insert.wordArt`, `wordArt.set`): floating decorative text with 10 original styles, outline and shadow, in-place editing, XLSX and print (#784) |
|
||||
@@ -281,6 +297,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) |
|
||||
| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; the roadmap qualifies XIRR's known `#NUM!` differences |
|
||||
| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) |
|
||||
| 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update |
|
||||
| 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row |
|
||||
@@ -296,13 +313,17 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories |
|
||||
| 2026-10-31 | minor | Progress log: Function Library |
|
||||
| 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles |
|
||||
| 2026-10-26 | minor | Progress log: Excel open check |
|
||||
| 2026-10-26 | minor | Progress log: PDF reading direction and RTL sheets |
|
||||
| 2026-10-26 | minor | Progress log: Arabic PDF text |
|
||||
| 2026-10-26 | minor | Progress log: Arabic bidi display and editing |
|
||||
| 2026-10-26 | minor | Progress log: Arabic font fallback |
|
||||
| 2026-10-26 | minor | Progress log: `cargo xtask bench` |
|
||||
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
|
||||
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
|
||||
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
|
||||
| 2026-10-24 | trivial | Progress log: unedited embedded charts keep their XML on save (#1668) |
|
||||
| 2026-10-24 | minor | Progress log: password to modify (#921) |
|
||||
| 2026-10-23 | minor | Progress log: accounting negatives in number text |
|
||||
| 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! |
|
||||
| 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) |
|
||||
@@ -315,14 +336,21 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
|
||||
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
|
||||
| 2026-10-19 | trivial | Progress log: desktop theme portal read timeout |
|
||||
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) |
|
||||
| 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes |
|
||||
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
|
||||
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
|
||||
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
|
||||
| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers |
|
||||
| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save |
|
||||
| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes |
|
||||
| 2026-10-14 | minor | Progress log: sorts order numbers exactly |
|
||||
| 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) |
|
||||
| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting |
|
||||
| 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook kept on save |
|
||||
| 2026-10-14 | minor | Progress log: lookups compare numbers exactly |
|
||||
| 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references |
|
||||
| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save |
|
||||
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
|
||||
| 2026-10-14 | minor | Progress log: spill anchor reading its old spill area |
|
||||
| 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict |
|
||||
|
||||
@@ -65,6 +65,13 @@ fn cond_format_list(s: &Sheet) -> Vec<String> {
|
||||
cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect()
|
||||
}
|
||||
|
||||
/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is
|
||||
/// in another workbook, a data connection or the Data Model).
|
||||
fn pivot_count(s: &Sheet) -> usize {
|
||||
let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count());
|
||||
s.pivots.len() + kept
|
||||
}
|
||||
|
||||
fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) {
|
||||
if a != b {
|
||||
d.push(|| format!("{sheet}: {a} → {b}"));
|
||||
@@ -154,7 +161,7 @@ pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec<Categor
|
||||
}
|
||||
diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len());
|
||||
diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len());
|
||||
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
|
||||
diff_count(&mut pivots, &name, pivot_count(sa), pivot_count(sb));
|
||||
}
|
||||
let mut names = Diffs::new("names", m);
|
||||
let name_list = |wb: &Workbook| -> BTreeSet<String> {
|
||||
|
||||
@@ -110,12 +110,20 @@ fn resolve_target(source_dir: &str, target: &str) -> String {
|
||||
|
||||
type Zip<'a> = zip::ZipArchive<Cursor<&'a [u8]>>;
|
||||
|
||||
fn zip_names(zip: &mut Zip<'_>) -> Vec<String> {
|
||||
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| f.name().to_string())).collect()
|
||||
/// `(index, name)` of every file entry. Parts are read by index: two entries can decode to the
|
||||
/// same name, and looking up a CP437 name scans the whole archive.
|
||||
fn zip_names(zip: &mut Zip<'_>) -> Vec<(usize, String)> {
|
||||
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| (i, entry_name(&f)))).collect()
|
||||
}
|
||||
|
||||
fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
|
||||
let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
|
||||
/// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode
|
||||
/// is listed with its raw bytes made lossy, so the entry is still checked and reported.
|
||||
fn entry_name<R: std::io::Read>(f: &zip::read::ZipFile<'_, R>) -> String {
|
||||
f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned())
|
||||
}
|
||||
|
||||
fn read_zip_part(zip: &mut Zip<'_>, index: usize, name: &str) -> Result<Vec<u8>, String> {
|
||||
let f = zip.by_index(index).map_err(|e| format!("{name}: {e}"))?;
|
||||
let mut buf = Vec::new();
|
||||
f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?;
|
||||
Ok(buf)
|
||||
@@ -128,8 +136,8 @@ enum PartError {
|
||||
}
|
||||
|
||||
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
|
||||
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
|
||||
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
|
||||
fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Result<Vec<u8>, PartError> {
|
||||
let f = zip.by_index(index).map_err(|_| PartError::Unreadable)?;
|
||||
// One byte past what is left shows that the part doesn't fit.
|
||||
let limit = MAX_XML_PART.min(budget.saturating_add(1));
|
||||
let mut buf = Vec::new();
|
||||
@@ -150,10 +158,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Resu
|
||||
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
let Ok(mut zip) = zip::ZipArchive::new(Cursor::new(bytes)) else { return false };
|
||||
let names = zip_names(&mut zip);
|
||||
let find = |key: &str| names.iter().find(|n| part_key(n) == key).cloned();
|
||||
let find = |key: &str| names.iter().find(|(_, n)| part_key(n) == key).cloned();
|
||||
let mut workbook = "xl/workbook.xml".to_string();
|
||||
if let Some(rels) = find("_rels/.rels")
|
||||
&& let Ok(xml) = read_zip_part(&mut zip, &rels)
|
||||
if let Some((i, rels)) = find("_rels/.rels")
|
||||
&& let Ok(xml) = read_zip_part(&mut zip, i, &rels)
|
||||
&& let Ok(els) = xml_elements(&xml)
|
||||
&& let Some(target) = els
|
||||
.iter()
|
||||
@@ -162,8 +170,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
{
|
||||
workbook = resolve_target("", target);
|
||||
}
|
||||
let Some(name) = find(&part_key(&workbook)) else { return false };
|
||||
let Ok(xml) = read_zip_part(&mut zip, &name) else { return false };
|
||||
let Some((i, name)) = find(&part_key(&workbook)) else { return false };
|
||||
let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false };
|
||||
xml_elements(&xml)
|
||||
.ok()
|
||||
.into_iter()
|
||||
@@ -177,15 +185,15 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
|
||||
let names = zip_names(&mut zip);
|
||||
let parts: HashSet<String> = names.iter().map(|n| part_key(n)).collect();
|
||||
let mut read_part = |name: &str| read_zip_part(&mut zip, name);
|
||||
let parts: HashSet<String> = names.iter().map(|(_, n)| part_key(n)).collect();
|
||||
let mut read_part = |index: usize, name: &str| read_zip_part(&mut zip, index, name);
|
||||
let mut issues = Vec::new();
|
||||
let ct_name = names.iter().find(|n| part_key(n) == "[content_types].xml").cloned();
|
||||
let ct_name = names.iter().find(|(_, n)| part_key(n) == "[content_types].xml").cloned();
|
||||
let (mut defaults, mut overrides) = (HashSet::new(), HashSet::new());
|
||||
match ct_name {
|
||||
None => issues.push("no [Content_Types].xml".to_string()),
|
||||
Some(n) => {
|
||||
for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
|
||||
Some((i, n)) => {
|
||||
for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
|
||||
match el.as_str() {
|
||||
"Default" => {
|
||||
if let Some(x) = attr(&attrs, "Extension") {
|
||||
@@ -202,9 +210,9 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sorted: Vec<&String> = names.iter().collect();
|
||||
sorted.sort();
|
||||
for n in &sorted {
|
||||
let mut sorted: Vec<&(usize, String)> = names.iter().collect();
|
||||
sorted.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
|
||||
for (_, n) in &sorted {
|
||||
let key = part_key(n);
|
||||
if key == "[content_types].xml" {
|
||||
continue;
|
||||
@@ -219,7 +227,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
for p in missing_overrides {
|
||||
issues.push(format!("content type override for missing part /{p}"));
|
||||
}
|
||||
for n in sorted {
|
||||
for (i, n) in sorted {
|
||||
let key = part_key(n);
|
||||
let Some(rels_file) = key.strip_suffix(".rels") else { continue };
|
||||
// `dir/_rels/name.rels` describes `dir/name`; `_rels/.rels` the package itself.
|
||||
@@ -233,7 +241,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
issues.push(format!("{n} describes missing part {source}"));
|
||||
}
|
||||
let mut ids = HashSet::new();
|
||||
for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? {
|
||||
for (el, attrs) in xml_elements(&read_part(*i, n)?).map_err(|e| format!("{n}: {e}"))? {
|
||||
if el != "Relationship" {
|
||||
continue;
|
||||
}
|
||||
@@ -268,17 +276,17 @@ pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String
|
||||
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
|
||||
let names = zip_names(&mut zip);
|
||||
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
|
||||
let by_key: HashMap<String, &(usize, String)> = names.iter().map(|e| (part_key(&e.1), e)).collect();
|
||||
// Several relationships name the same part; each fresh check decompressed it again, so
|
||||
// repeated references to one highly compressible part multiplied the work. The verdict is
|
||||
// remembered per (part, named content) and the decompression the package can cause is
|
||||
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
|
||||
// would otherwise each spend a full per-part allowance.
|
||||
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
|
||||
let mut verdicts: HashMap<(usize, &'static str), bool> = HashMap::new();
|
||||
let mut kinds = BTreeMap::new();
|
||||
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
|
||||
for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) {
|
||||
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
|
||||
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
|
||||
let xml = match read_zip_part_within(&mut zip, *i, &mut budget) {
|
||||
Ok(xml) => xml,
|
||||
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
|
||||
Err(PartError::Unreadable) => continue,
|
||||
@@ -292,8 +300,8 @@ fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<S
|
||||
}
|
||||
let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External"));
|
||||
if !external
|
||||
&& let Some(part) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
|
||||
&& !holds_something(&mut zip, part, kind, &mut verdicts, &mut budget)
|
||||
&& let Some((index, _)) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
|
||||
&& !holds_something(&mut zip, *index, kind, &mut verdicts, &mut budget)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -314,7 +322,7 @@ fn rels_source_dir(key: &str) -> Option<String> {
|
||||
/// comes first) a comment, for VML a shape. Read only as far as needed; an unreadable part counts.
|
||||
/// `verdicts` remembers the answer per (part, named content); `budget` is the decompression this
|
||||
/// package's remaining checks may cause, and once it is spent the part counts as having content.
|
||||
fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'static str), bool>, budget: &mut u64) -> bool {
|
||||
fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool {
|
||||
let wanted: Option<&'static [u8]> = match kind.to_ascii_lowercase().as_str() {
|
||||
"comments" => Some(b"comment"),
|
||||
"vmldrawing" => Some(b"shape"),
|
||||
@@ -325,17 +333,17 @@ fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut Has
|
||||
Some(_) => "shape",
|
||||
None => "any",
|
||||
};
|
||||
if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) {
|
||||
if let Some(v) = verdicts.get(&(index, marker)) {
|
||||
return *v;
|
||||
}
|
||||
let v = holds_something_uncached(zip, name, marker, budget);
|
||||
verdicts.insert((name.to_ascii_lowercase(), marker), v);
|
||||
let v = holds_something_uncached(zip, index, marker, budget);
|
||||
verdicts.insert((index, marker), v);
|
||||
v
|
||||
}
|
||||
|
||||
fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool {
|
||||
fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool {
|
||||
use quick_xml::events::Event;
|
||||
let Ok(f) = zip.by_name(name) else { return true };
|
||||
let Ok(f) = zip.by_index(index) else { return true };
|
||||
if *budget == 0 {
|
||||
return true;
|
||||
}
|
||||
@@ -392,6 +400,57 @@ mod tests {
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// A package with two relationship parts whose names both read `xl/_rels/é.xml.rels`: the first
|
||||
/// stored as UTF-8 holding `first`, the second stored as CP437 (byte 0x82) holding `second`.
|
||||
fn same_name_rels(first: &str, second: &str) -> Vec<u8> {
|
||||
const PLACEHOLDER: &[u8] = b"xl/_rels/Q.xml.rels";
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
z.start_file("xl/_rels/\u{e9}.xml.rels", opts).unwrap();
|
||||
z.write_all(first.as_bytes()).unwrap();
|
||||
z.start_file(String::from_utf8(PLACEHOLDER.to_vec()).unwrap(), opts).unwrap();
|
||||
z.write_all(second.as_bytes()).unwrap();
|
||||
let mut bytes = z.finish().unwrap().into_inner();
|
||||
// The name sits in the local header and in the central directory; both get the CP437 byte.
|
||||
let mut at = 0;
|
||||
let mut patched = 0;
|
||||
while let Some(i) = bytes.get(at..).and_then(|rest| rest.windows(PLACEHOLDER.len()).position(|w| w == PLACEHOLDER)) {
|
||||
bytes[at + i + 9] = 0x82;
|
||||
at += i + PLACEHOLDER.len();
|
||||
patched += 1;
|
||||
}
|
||||
assert_eq!(patched, 2);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn rels_xml(rels: &[(&str, &str)]) -> String {
|
||||
let body: String = rels
|
||||
.iter()
|
||||
.map(|(id, kind)| {
|
||||
format!(
|
||||
r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}" Target="https://example.com" TargetMode="External"/>"#
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
format!(r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{body}</Relationships>"#)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_with_the_same_decoded_name_are_each_validated() {
|
||||
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "custom"), ("rId1", "custom")]));
|
||||
let issues = validate_package(&bytes).unwrap();
|
||||
let duplicates = issues.iter().filter(|i| i.ends_with("duplicate relationship id rId1")).count();
|
||||
assert_eq!(duplicates, 1, "{issues:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_kinds_read_parts_with_the_same_decoded_name() {
|
||||
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "audio")]));
|
||||
let kinds = relationship_kinds(&bytes).unwrap();
|
||||
assert!(kinds.contains_key("custom"), "{kinds:?}");
|
||||
assert!(kinds.contains_key("audio"), "{kinds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_parts_count_against_the_decompression_budget() {
|
||||
// Each part fits the per-part allowance, but together they need more than the budget.
|
||||
|
||||
@@ -344,7 +344,7 @@ fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec
|
||||
let mut pending: Vec<(&str, &str)> = rels.to_vec();
|
||||
for i in 0..src.len() {
|
||||
let mut f = src.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut body = String::new();
|
||||
f.read_to_string(&mut body).unwrap();
|
||||
if let Some(at) = pending.iter().position(|(r, _)| *r == name) {
|
||||
|
||||
+138
-29
@@ -268,14 +268,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell a desktop user why a nightly launch was refused. A headless form (`--version` on a runner)
|
||||
/// never gets here: the version query is answered before this and before any profile work.
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// Tell a desktop user why a nightly launch was refused, in a native box where one renders without the
|
||||
/// app's event loop (Windows, X11/Wayland), and on standard error always. A headless form (`--version`
|
||||
/// on a runner) never gets here: the version query is answered before this and before any profile work.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("GridCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("GridCraft launch profile: {error}");
|
||||
return;
|
||||
@@ -330,6 +339,55 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
|
||||
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
|
||||
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
|
||||
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
|
||||
/// opened as a file.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct DesktopArgs {
|
||||
control_port: Option<u16>,
|
||||
control_token: Option<String>,
|
||||
sample: Option<String>,
|
||||
files: Vec<String>,
|
||||
}
|
||||
|
||||
fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Option<String>) -> DesktopArgs {
|
||||
let mut parsed = DesktopArgs { control_port, control_token, ..DesktopArgs::default() };
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--" => {
|
||||
parsed.files.extend(args[i + 1..].iter().cloned());
|
||||
break;
|
||||
}
|
||||
"--control" => {
|
||||
i += 1;
|
||||
parsed.control_port = args.get(i).and_then(|p| p.parse().ok());
|
||||
}
|
||||
"--control-token" => {
|
||||
i += 1;
|
||||
parsed.control_token = args.get(i).cloned();
|
||||
}
|
||||
"--sample" => {
|
||||
i += 1;
|
||||
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
|
||||
}
|
||||
a if a.starts_with("-psn_") => {}
|
||||
a => parsed.files.push(a.to_string()),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
/// A nightly owns no control channel, and only options count: everything after `--` is a file, so a
|
||||
/// document named `--control` is opened rather than read as a flag.
|
||||
fn nightly_control_refused(nightly: bool, args: &[String]) -> bool {
|
||||
let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len());
|
||||
nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token")
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
// A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from
|
||||
// this same executable) comes before everything else: it opens no window, writes no log, and
|
||||
@@ -392,34 +450,14 @@ fn main() -> eframe::Result<()> {
|
||||
}
|
||||
// The control channel is a stable-only service: a nightly window owns no port, writes no
|
||||
// token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`.
|
||||
if nightly && args.iter().any(|a| a == "--control" || a == "--control-token") {
|
||||
if nightly_control_refused(nightly, &args) {
|
||||
eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let mut control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
|
||||
let mut control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
|
||||
let mut sample: Option<String> = None;
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--control" => {
|
||||
i += 1;
|
||||
control_port = args.get(i).and_then(|p| p.parse().ok());
|
||||
}
|
||||
"--control-token" => {
|
||||
i += 1;
|
||||
control_token = args.get(i).cloned();
|
||||
}
|
||||
"--sample" => {
|
||||
i += 1;
|
||||
sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
|
||||
}
|
||||
a if a.starts_with("-psn_") => {}
|
||||
a => files.push(a.to_string()),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
|
||||
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
|
||||
let parsed = desktop_args(&args, control_port, control_token);
|
||||
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
|
||||
// The log file lives in the settings folder, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
// first. Runs without preferences (agents' test runs) log to standard error only, so they
|
||||
@@ -449,7 +487,6 @@ fn main() -> eframe::Result<()> {
|
||||
if !nightly {
|
||||
app.start_update_check();
|
||||
}
|
||||
let control_port = control_port;
|
||||
load_prefs(&mut app);
|
||||
// Stamp the startup workbook's author from the persisted user name.
|
||||
if app.session.documents().is_empty() {
|
||||
@@ -616,3 +653,75 @@ mod packaging_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod launch_separator_tests {
|
||||
use super::*;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
|
||||
/// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive
|
||||
/// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too.
|
||||
fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
|
||||
}
|
||||
|
||||
/// The argv the Launcher starts a nightly with, extended by `tail`, as the start then reads it.
|
||||
fn launcher_argv(tail: &[&str]) -> Vec<String> {
|
||||
let mut argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_platforms_root_spelling_is_refused_as_relative() {
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
|
||||
let argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launchers_separator_is_never_a_file() {
|
||||
let parsed = desktop_args(&launcher_argv(&[]), None, None);
|
||||
assert_eq!(parsed, DesktopArgs::default(), "the separator must not reach the file list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_after_the_separator_are_opened_in_order() {
|
||||
assert_eq!(desktop_args(&launcher_argv(&["a.file"]), None, None).files, ["a.file"]);
|
||||
let parsed = desktop_args(&launcher_argv(&["a.file", "--version", "--sample"]), None, None);
|
||||
assert_eq!(parsed.files, ["a.file", "--version", "--sample"], "after -- every word is a file");
|
||||
assert_eq!((parsed.sample, parsed.control_port), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_flag_after_the_separator_is_a_file_not_a_refusal() {
|
||||
let argv = launcher_argv(&["--control"]);
|
||||
assert!(!nightly_control_refused(true, &argv), "a document named --control must open, not refuse");
|
||||
let parsed = desktop_args(&argv, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_flag_before_the_separator_still_names_the_port() {
|
||||
let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()];
|
||||
assert!(nightly_control_refused(true, &with_file));
|
||||
let parsed = desktop_args(&with_file, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (Some(7979), vec!["a.file".to_string()]));
|
||||
let plain = vec!["--control".to_string(), "7979".to_string()];
|
||||
assert!(nightly_control_refused(true, &plain));
|
||||
let parsed = desktop_args(&plain, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (Some(7979), Vec::<String>::new()));
|
||||
assert!(!nightly_control_refused(false, &plain), "the stable app keeps its control channel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,3 +118,9 @@ sync_github_name = true
|
||||
|
||||
[people.RockerHX]
|
||||
sync_github_name = true
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
|
||||
[people.alosslessdev]
|
||||
real_name = "Francisco Herrera"
|
||||
|
||||
@@ -62,6 +62,28 @@ pub struct Lambda {
|
||||
pub env: Vec<(String, Ev)>,
|
||||
}
|
||||
|
||||
/// What the tail of a LAMBDA body came to.
|
||||
enum Tail {
|
||||
Done(Ev),
|
||||
/// A call to make in place of the current one, its arguments evaluated.
|
||||
Call(Arc<Lambda>, Vec<(String, Ev)>),
|
||||
}
|
||||
|
||||
/// A tail call can pass a closure that captures the previous one, thousands deep. Releasing the
|
||||
/// chain is a loop, not a recursion, so it cannot overflow the native stack.
|
||||
impl Drop for Lambda {
|
||||
fn drop(&mut self) {
|
||||
let mut pending = std::mem::take(&mut self.env);
|
||||
while let Some((_, ev)) = pending.pop() {
|
||||
if let Ev::L(l) = ev
|
||||
&& let Ok(mut inner) = Arc::try_unwrap(l)
|
||||
{
|
||||
pending.append(&mut inner.env);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Ev {
|
||||
V(Value),
|
||||
@@ -84,6 +106,11 @@ fn err(e: CellError) -> Ev {
|
||||
/// calls in progress, so it still runs.
|
||||
const MAX_LAMBDA_CALLS: usize = 140;
|
||||
|
||||
/// Tail calls one LAMBDA call may chain. They run in a loop on one native frame, so this only keeps
|
||||
/// an endless tail recursion finite. Excel computes a tail countdown to 5,459 and answers `#NUM!`
|
||||
/// for 5,460, which is 5,460 invocations in the chain.
|
||||
const MAX_TAIL_CALLS: usize = 5460;
|
||||
|
||||
/// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it,
|
||||
/// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames
|
||||
/// above the formula. A cell that another cell's formula computes on demand shares the budget of the
|
||||
|
||||
@@ -216,13 +216,7 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste
|
||||
}
|
||||
}),
|
||||
BinOp::Concat => match (a.to_text(), b.to_text()) {
|
||||
(Ok(x), Ok(y)) => {
|
||||
if x.len() + y.len() > 32767 * 4 {
|
||||
Value::Error(CellError::Value)
|
||||
} else {
|
||||
Value::text(x + &y)
|
||||
}
|
||||
}
|
||||
(Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)),
|
||||
(Err(e), _) | (_, Err(e)) => Value::Error(e),
|
||||
},
|
||||
BinOp::Eq => Value::Bool(compare(a, b) == Equal),
|
||||
|
||||
@@ -5,6 +5,17 @@ use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, Lambda, Pip
|
||||
use std::sync::Arc;
|
||||
|
||||
impl<'h> Evaluator<'h> {
|
||||
/// `IF` with an array condition: element-wise.
|
||||
pub(super) fn if_elementwise(&mut self, arr: &Array, args: &[Expr]) -> Ev {
|
||||
let t = self.arg_val(args, 1).unwrap_or(Value::Bool(true));
|
||||
let f = if args.len() > 2 { self.arg_val(args, 2).unwrap_or(Value::Bool(false)) } else { Value::Bool(false) };
|
||||
Ev::V(zip3(arr, &t, &f, |c, t, f| match c.to_bool() {
|
||||
Ok(true) => t.clone(),
|
||||
Ok(false) => f.clone(),
|
||||
Err(e) => Value::Error(e),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn call(&mut self, name: &str, args: &[Expr]) -> Ev {
|
||||
match name {
|
||||
"IF" => self.if_call(args),
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
use super::MAX_LAMBDA_CALLS;
|
||||
use super::array::{broadcast_len, single};
|
||||
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, Value, err};
|
||||
use super::special::is_special;
|
||||
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
|
||||
use std::sync::Arc;
|
||||
|
||||
impl<'h> Evaluator<'h> {
|
||||
pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev {
|
||||
match self.bind_args(l, args) {
|
||||
Ok(bound) => self.call_lambda_values(l, bound),
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments of a call to `l`, evaluated in the current scope.
|
||||
fn bind_args(&mut self, l: &Lambda, args: &[Expr]) -> Result<Vec<(String, Ev)>, Ev> {
|
||||
// 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);
|
||||
return Err(err(CellError::Value));
|
||||
}
|
||||
let mut bound = Vec::with_capacity(l.params.len());
|
||||
for (i, p) in l.params.iter().enumerate() {
|
||||
@@ -21,7 +30,56 @@ impl<'h> Evaluator<'h> {
|
||||
};
|
||||
bound.push((p.clone(), v));
|
||||
}
|
||||
self.call_lambda_values(l, bound)
|
||||
Ok(bound)
|
||||
}
|
||||
|
||||
/// Follows `e` through the positions whose value is the value of a LAMBDA call (`IF` branches,
|
||||
/// parentheses), and returns the call with its arguments evaluated instead of making it, so
|
||||
/// that `call_lambda_values` can loop. Anything else is evaluated here.
|
||||
fn tail_step(&mut self, e: &Expr) -> Tail {
|
||||
match e {
|
||||
Expr::Paren(x) => self.tail_step(x),
|
||||
Expr::Call(name, args) if name == "IF" && (2..=3).contains(&args.len()) => {
|
||||
let c = self.arg_val(args, 0).unwrap_or_default();
|
||||
if let Value::Array(arr) = &c {
|
||||
return Tail::Done(self.if_elementwise(arr, args));
|
||||
}
|
||||
match c.to_bool() {
|
||||
Ok(true) => self.tail_step_branch(args.get(1)),
|
||||
Ok(false) => match args.get(2) {
|
||||
Some(_) => self.tail_step_branch(args.get(2)),
|
||||
None => Tail::Done(Ev::V(Value::Bool(false))),
|
||||
},
|
||||
Err(x) => Tail::Done(err(x)),
|
||||
}
|
||||
}
|
||||
Expr::Call(name, args) if gridcraft_functions::lookup(name).is_none() && !is_special(name) => match self.name(name) {
|
||||
Ev::L(l) => self.tail_call(l, args),
|
||||
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
|
||||
_ => Tail::Done(err(CellError::Name)),
|
||||
},
|
||||
Expr::Invoke(callee, args) => match self.eval(callee) {
|
||||
Ev::L(l) => self.tail_call(l, args),
|
||||
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
|
||||
_ => Tail::Done(err(CellError::Value)),
|
||||
},
|
||||
_ => Tail::Done(self.eval(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// An `IF` branch; an omitted one (`IF(c,,1)`) is 0.
|
||||
fn tail_step_branch(&mut self, branch: Option<&Expr>) -> Tail {
|
||||
match branch {
|
||||
Some(Expr::Missing) | None => Tail::Done(Ev::V(Value::Number(0.0))),
|
||||
Some(b) => self.tail_step(b),
|
||||
}
|
||||
}
|
||||
|
||||
fn tail_call(&mut self, l: Arc<Lambda>, args: &[Expr]) -> Tail {
|
||||
match self.bind_args(&l, args) {
|
||||
Ok(bound) => Tail::Call(l, bound),
|
||||
Err(e) => Tail::Done(e),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev {
|
||||
@@ -38,7 +96,29 @@ impl<'h> Evaluator<'h> {
|
||||
self.calls += 1;
|
||||
let saved = std::mem::replace(&mut self.env, l.env.clone());
|
||||
self.env.extend(bound);
|
||||
let r = self.eval(&l.body);
|
||||
// A call in tail position replaces this one instead of nesting under it, so a tail recursion
|
||||
// uses no more native stack at 5,000 deep than at 5. Each link still spends fuel.
|
||||
let mut tails = 0;
|
||||
let mut step = self.tail_step(&l.body);
|
||||
let r = loop {
|
||||
match step {
|
||||
Tail::Done(v) => break v,
|
||||
Tail::Call(next, bound) => {
|
||||
tails += 1;
|
||||
if tails >= MAX_TAIL_CALLS {
|
||||
break err(CellError::Num);
|
||||
}
|
||||
self.fuel = match self.fuel.checked_sub(1) {
|
||||
Some(f) => f,
|
||||
None => break err(CellError::Calc),
|
||||
};
|
||||
self.env.clear();
|
||||
self.env.extend(next.env.iter().cloned());
|
||||
self.env.extend(bound);
|
||||
step = self.tail_step(&next.body);
|
||||
}
|
||||
}
|
||||
};
|
||||
self.env = saved;
|
||||
self.calls -= 1;
|
||||
r
|
||||
|
||||
@@ -195,7 +195,7 @@ impl Precedents<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_special(n: &str) -> bool {
|
||||
pub(super) fn is_special(n: &str) -> bool {
|
||||
matches!(
|
||||
n,
|
||||
"IF" | "IFS"
|
||||
|
||||
@@ -12,7 +12,7 @@ mod trimrange;
|
||||
|
||||
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
|
||||
pub use precision::DisplayedPrecision;
|
||||
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial};
|
||||
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, evaluate_expr, now_serial};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -718,7 +718,7 @@ impl Calc {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
|
||||
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing, array.data.len());
|
||||
if !blocked {
|
||||
for (o, r) in outranked {
|
||||
for c in r.iter() {
|
||||
@@ -785,6 +785,7 @@ fn spill_is_blocked(
|
||||
range: RangeRef,
|
||||
end: CellRef,
|
||||
standing: &Standing,
|
||||
array_len: usize,
|
||||
) -> bool {
|
||||
let outranked = |cell: CellRef| {
|
||||
sheet
|
||||
@@ -796,7 +797,7 @@ fn spill_is_blocked(
|
||||
|| end.col >= gridcraft_core::MAX_COLS
|
||||
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
|
||||
|| sheet.merges.iter().any(|merge| merge.intersects(&range))
|
||||
|| sheet.tables.iter().any(|table| table.range.contains(anchor.1))
|
||||
|| (array_len > 1 && sheet.tables.iter().any(|table| table.range.contains(anchor.1)))
|
||||
}
|
||||
|
||||
fn fill_spill(sheet: &mut gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, array: &Array) {
|
||||
|
||||
@@ -162,7 +162,8 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
|
||||
/// Whether an array result at `k` can't spill: it is in a table (a one-value result is shown
|
||||
/// there, as in Excel), or its area runs off the sheet,
|
||||
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
|
||||
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
|
||||
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
|
||||
@@ -188,7 +189,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
|
||||
end.row >= gridcraft_core::MAX_ROWS
|
||||
|| end.col >= gridcraft_core::MAX_COLS
|
||||
|| sh.merges.iter().any(|m| m.intersects(&range))
|
||||
|| sh.tables.iter().any(|t| t.range.contains(anchor))
|
||||
|| (a.data.len() > 1 && sh.tables.iter().any(|t| t.range.contains(anchor)))
|
||||
|| sh.cells.iter_range(range).any(|(c, cell)| c != anchor && (!cell.value.is_empty() || cell.formula.is_some()))
|
||||
|| sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c) && spilled_over(*c))
|
||||
}
|
||||
@@ -200,7 +201,7 @@ pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef,
|
||||
CellRef::new(anchor.row.saturating_add((arr.rows as u32).saturating_sub(1)), anchor.col.saturating_add((arr.cols as u32).saturating_sub(1)));
|
||||
RangeRef::new(anchor, end) == range
|
||||
&& !sheet.merges.iter().any(|m| m.intersects(&range))
|
||||
&& !sheet.tables.iter().any(|t| t.range.contains(anchor))
|
||||
&& (arr.data.len() <= 1 || !sheet.tables.iter().any(|t| t.range.contains(anchor)))
|
||||
&& range
|
||||
.iter()
|
||||
.enumerate()
|
||||
|
||||
+161
-3
@@ -820,6 +820,42 @@ fn arrays_do_not_spill_in_tables() {
|
||||
assert_eq!(t.num("E4"), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_value_array_in_a_table_is_not_a_spill() {
|
||||
// Excel shows a one-value dynamic-array result in a table column; two or more is #SPILL! (#2335).
|
||||
let table = |range: &str| gridcraft_model::Table {
|
||||
id: 1,
|
||||
name: "Table1".into(),
|
||||
range: gridcraft_core::RangeRef::parse(range).unwrap(),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![],
|
||||
style: String::new(),
|
||||
banded_rows: false,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: false,
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
};
|
||||
let mut t = T::new();
|
||||
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
|
||||
t.set("A1", "7");
|
||||
t.set("A2", "8");
|
||||
t.set("C4", "=FILTER(A1:A2,A1:A2>7)");
|
||||
t.set("C5", "=FILTER(A1:A2,A1:A2>0)");
|
||||
t.set("H4", "=FILTER(A1:A2,A1:A2>7)");
|
||||
t.set("D4", "=ROWS(C4#)");
|
||||
assert_eq!((t.num("C4"), t.num("H4"), t.num("D4")), (8.0, 8.0, 1.0));
|
||||
assert_eq!(t.get("C5"), Value::Error(CellError::Spill));
|
||||
// Recalculating again keeps the one-value result.
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.num("C4"), 8.0);
|
||||
assert_eq!(t.num("D4"), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ifs_and_lazy() {
|
||||
let mut t = T::new();
|
||||
@@ -1181,17 +1217,67 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() {
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
// F(F,n) has n + 1 calls in progress at its deepest; W adds one more call per step.
|
||||
// W's call to `f` is a tail call, so a wrapped call level costs one call in progress, not two. A tail call reuses its frame, so the tail chain is bounded by `MAX_TAIL_CALLS`, as in Excel
|
||||
// (5,459 ok, 5,460 #NUM!). F(F,n) otherwise has n + 1 calls in progress at its deepest; W adds
|
||||
// one more call per step.
|
||||
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
|
||||
let wrapped = |n: u32| format!("=LET(W,LAMBDA(f,k,f(f,k)),F,LAMBDA(me,n,IF(n<=0,0,1+W(me,n-1))),F(F,{n}))");
|
||||
[tail(139), tail(140), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
|
||||
[tail(5459), tail(5460), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("recursion must not overflow the stack")
|
||||
};
|
||||
let small = run(1 << 20);
|
||||
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]);
|
||||
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Number(70.0), Value::Number(131.0)]);
|
||||
assert_eq!(run(64 << 20), small);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tail_recursive_lambda_reaches_excels_depth_on_a_small_stack() {
|
||||
// Excel (measured): a tail countdown is 0 at 5,000 and 5,459 and #NUM! at 5,460 and 10,000.
|
||||
let run = |stack: usize| {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(stack)
|
||||
.spawn(|| {
|
||||
let mut wb = Workbook::new();
|
||||
wb.names.push(gridcraft_model::DefinedName {
|
||||
name: "TAILN".into(),
|
||||
scope: None,
|
||||
formula: "LAMBDA(n,IF(n=0,0,TAILN(n-1)))".into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
|
||||
// The same chain through parentheses and an applied lambda, and one that returns the base case's value.
|
||||
let paren = "=LET(F,LAMBDA(me,n,IF(n=0,7,(me(me,n-1)))),F(F,5000))".to_string();
|
||||
let invoke = "=LET(F,LAMBDA(me,n,IF(n=0,7,LAMBDA(a,b,me(me,a))(n-1,0))),F(F,2000))".to_string();
|
||||
let endless = "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))".to_string();
|
||||
// Each call passes a closure that captures the last, 5,000 deep: releasing them must not recurse.
|
||||
let closures = "=LET(F,LAMBDA(me,n,acc,IF(n=0,0,me(me,n-1,LAMBDA(x,acc)))),F(F,5000,0))".to_string();
|
||||
[tail(5000), tail(5459), tail(5460), tail(10000), paren, invoke, endless, "=TAILN(5000)".to_string(), closures]
|
||||
.map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("tail recursion must not overflow the stack")
|
||||
};
|
||||
let num = Value::Error(CellError::Num);
|
||||
let small = run(1 << 20);
|
||||
assert_eq!(
|
||||
small,
|
||||
[
|
||||
Value::Number(0.0),
|
||||
Value::Number(0.0),
|
||||
num.clone(),
|
||||
num.clone(),
|
||||
Value::Number(7.0),
|
||||
Value::Number(7.0),
|
||||
num,
|
||||
Value::Number(0.0),
|
||||
Value::Number(0.0)
|
||||
]
|
||||
);
|
||||
assert_eq!(run(64 << 20), small);
|
||||
}
|
||||
|
||||
@@ -2035,6 +2121,65 @@ fn offset_extreme_arguments_return_ref() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorting and ranking compare numbers exactly while `=` and COUNTIF compare them at 15
|
||||
/// significant digits. Every expectation was observed in Excel 365 with these fixtures
|
||||
/// (`=0.1+0.2` is 0.30000000000000004): 0.3 sorts first whatever the input order.
|
||||
#[test]
|
||||
fn sorts_and_ranks_compare_numbers_exactly() {
|
||||
let mut t = T::new();
|
||||
for (at, input) in [
|
||||
// The noisy value first, then the exact one first.
|
||||
("A1", "=0.1+0.2"),
|
||||
("B1", "e"),
|
||||
("A2", "0.3"),
|
||||
("B2", "t"),
|
||||
("D1", "0.3"),
|
||||
("E1", "t"),
|
||||
("D2", "=0.1+0.2"),
|
||||
("E2", "e"),
|
||||
("G1", "=100+1E-14"),
|
||||
("H1", "e"),
|
||||
("G2", "100"),
|
||||
("H2", "t"),
|
||||
] {
|
||||
t.set(at, input);
|
||||
}
|
||||
let e = 0.1 + 0.2;
|
||||
let n = Value::Number;
|
||||
let s = |x: &str| Value::from(x);
|
||||
let cases: Vec<(&str, Value)> = vec![
|
||||
("=A1=A2", Value::Bool(true)),
|
||||
("=COUNTIF(A1:A2,0.3)", n(2.0)),
|
||||
("=INDEX(SORT(A1:B2),1,2)", s("t")),
|
||||
("=INDEX(SORT(D1:E2),1,2)", s("t")),
|
||||
("=INDEX(SORT(A1:B2,1,-1),1,2)", s("e")),
|
||||
("=INDEX(SORT(D1:E2,1,-1),1,2)", s("e")),
|
||||
("=INDEX(SORT(G1:H2),1,2)", s("t")),
|
||||
("=INDEX(SORT(G1:H2,1,-1),1,2)", s("e")),
|
||||
("=INDEX(SORTBY(B1:B2,A1:A2),1,1)", s("t")),
|
||||
("=INDEX(SORTBY(E1:E2,D1:D2),1,1)", s("t")),
|
||||
("=INDEX(SORTBY(B1:B2,A1:A2,-1),1,1)", s("e")),
|
||||
("=INDEX(SORTBY(E1:E2,D1:D2,-1),1,1)", s("e")),
|
||||
// Already exact: UNIQUE, RANK, LARGE/SMALL, MODE.
|
||||
("=ROWS(UNIQUE(A1:A2))", n(2.0)),
|
||||
("=RANK.EQ(0.3,A1:A2)", n(2.0)),
|
||||
("=RANK.EQ(0.3,A1:A2,1)", n(1.0)),
|
||||
("=RANK.AVG(0.3,A1:A2)", n(2.0)),
|
||||
("=RANK.EQ(0.3,A1)", Value::Error(CellError::NA)),
|
||||
("=LARGE(A1:A2,1)", n(e)),
|
||||
("=SMALL(A1:A2,1)", n(0.3)),
|
||||
("=MODE.SNGL(A1:A2,5)", Value::Error(CellError::NA)),
|
||||
];
|
||||
let mut wrong = Vec::new();
|
||||
for (formula, expected) in cases {
|
||||
let got = crate::evaluate(&t.wb, 0, c("Z1"), formula);
|
||||
if got != expected {
|
||||
wrong.push(format!("{formula}: got {got:?}, Excel {expected:?}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
|
||||
}
|
||||
|
||||
/// `@` intersects a reference with the formula's row (a column range) or column (a row range);
|
||||
/// a 2D range both (circular when it includes the formula's cell); a range the formula does not
|
||||
/// line up with gives #VALUE!. An array gives its top-left value. Legacy formulas read from files use it where Excel intersects implicitly.
|
||||
@@ -2617,6 +2762,19 @@ fn loan_schedule_residue_keeps_excels_sign() {
|
||||
assert_eq!(t.get("P7"), Value::Text("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concat_operator_cuts_at_the_cell_limit() {
|
||||
// Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767.
|
||||
let mut t = T::new();
|
||||
t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))");
|
||||
t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")");
|
||||
t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))");
|
||||
t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")");
|
||||
t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))");
|
||||
assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0));
|
||||
assert_eq!(t.get("A5"), Value::Error(CellError::Value));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() {
|
||||
let mut t = T::new();
|
||||
|
||||
@@ -16,6 +16,7 @@ enum Fam {
|
||||
Col100,
|
||||
Line,
|
||||
LineStack,
|
||||
Line100,
|
||||
Area,
|
||||
AreaStack,
|
||||
Area100,
|
||||
@@ -31,6 +32,7 @@ fn family(k: ChartKind) -> Fam {
|
||||
ColumnStacked100 | BarStacked100 => Fam::Col100,
|
||||
Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line,
|
||||
LineStacked => Fam::LineStack,
|
||||
LineStacked100 | LineStacked100Markers => Fam::Line100,
|
||||
Area => Fam::Area,
|
||||
AreaStacked => Fam::AreaStack,
|
||||
AreaStacked100 => Fam::Area100,
|
||||
@@ -40,7 +42,7 @@ fn family(k: ChartKind) -> Fam {
|
||||
|
||||
/// Families stacked to 100%: each category's values are shares of its total.
|
||||
fn is_100(f: Fam) -> bool {
|
||||
matches!(f, Fam::Col100 | Fam::Area100)
|
||||
matches!(f, Fam::Col100 | Fam::Line100 | Fam::Area100)
|
||||
}
|
||||
|
||||
fn is_col(f: Fam) -> bool {
|
||||
@@ -48,7 +50,21 @@ fn is_col(f: Fam) -> bool {
|
||||
}
|
||||
|
||||
fn is_line(f: Fam) -> bool {
|
||||
matches!(f, Fam::Line | Fam::LineStack)
|
||||
matches!(f, Fam::Line | Fam::LineStack | Fam::Line100)
|
||||
}
|
||||
|
||||
/// Line kinds that draw a marker at each point.
|
||||
fn has_markers(k: ChartKind) -> bool {
|
||||
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
|
||||
}
|
||||
|
||||
/// Stroke widths for explicitly selected Excel chart styles.
|
||||
fn line_style_width(style: u32) -> f32 {
|
||||
match style {
|
||||
1 => 3.0,
|
||||
9 => 5.0,
|
||||
_ => 2.25,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
|
||||
@@ -64,6 +80,7 @@ struct BarRun {
|
||||
}
|
||||
|
||||
impl BarRun {
|
||||
/// Starts a single-bar run at `pos` spanning `lo..hi`.
|
||||
fn new(pos: f32, lo: f32, hi: f32) -> Self {
|
||||
BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi, merged: false }
|
||||
}
|
||||
@@ -71,6 +88,7 @@ impl BarRun {
|
||||
fn touches(&self, lo: f32, hi: f32) -> bool {
|
||||
lo <= self.hi && hi >= self.lo
|
||||
}
|
||||
/// Extends the merged run to cover `pos` and `lo..hi`.
|
||||
fn add(&mut self, pos: f32, lo: f32, hi: f32) {
|
||||
self.merged = true;
|
||||
self.a0 = self.a0.min(pos);
|
||||
@@ -105,13 +123,15 @@ struct BarSink {
|
||||
bw: f32,
|
||||
horizontal: bool,
|
||||
color: Rgba,
|
||||
stroke: Option<(Rgba, f32)>,
|
||||
nslots: f32,
|
||||
k: f32,
|
||||
}
|
||||
|
||||
impl BarSink {
|
||||
fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self {
|
||||
BarSink { run: None, bw, horizontal, color, nslots, k }
|
||||
/// Creates a bar emitter for series slot `k` of `nslots`.
|
||||
fn new(bw: f32, horizontal: bool, color: Rgba, stroke: Option<(Rgba, f32)>, nslots: f32, k: f32) -> Self {
|
||||
BarSink { run: None, bw, horizontal, color, stroke, nslots, k }
|
||||
}
|
||||
/// Start of this series' slot along the category axis, for the category centered at `c`.
|
||||
fn pos(&self, c: f32) -> f32 {
|
||||
@@ -131,11 +151,10 @@ impl BarSink {
|
||||
let pos = self.pos(c);
|
||||
let band = self.band();
|
||||
if !merge {
|
||||
if self.horizontal {
|
||||
ctx.rect(lo, pos, len, self.bw, self.color, None);
|
||||
} else {
|
||||
ctx.rect(pos, lo, self.bw, len, self.color, None);
|
||||
}
|
||||
let (x, y, w, h) = if self.horizontal { (lo, pos, len, self.bw) } else { (pos, lo, self.bw, len) };
|
||||
// Omit the outline when a bar is no wider/taller than the stroke, so the inner fill never disappears.
|
||||
let stroke = self.stroke.filter(|(_, sw)| w > *sw && h > *sw);
|
||||
ctx.rect(x, y, w, h, self.color, stroke);
|
||||
return;
|
||||
}
|
||||
match &mut self.run {
|
||||
@@ -147,6 +166,7 @@ impl BarSink {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Flushes any pending hairline bar run at the end of the series.
|
||||
fn finish(self, ctx: &mut Ctx) {
|
||||
let band = self.band();
|
||||
if let Some(m) = self.run {
|
||||
@@ -156,7 +176,7 @@ impl BarSink {
|
||||
}
|
||||
|
||||
fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec<Vec<Option<(f64, f64)>>> {
|
||||
// Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart).
|
||||
// Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart).
|
||||
let mut totals: Vec<((bool, Fam), Vec<f64>)> = Vec::new();
|
||||
for (i, s) in data.series.iter().enumerate() {
|
||||
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
|
||||
@@ -187,7 +207,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
|
||||
for (i, s) in data.series.iter().enumerate() {
|
||||
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
|
||||
let a = sec.get(i).copied().unwrap_or(false);
|
||||
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100);
|
||||
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::Line100 | Fam::AreaStack | Fam::Area100);
|
||||
let key = (a, fam);
|
||||
let si = if stacked {
|
||||
match stacks.iter().position(|(k, _, _)| *k == key) {
|
||||
@@ -216,7 +236,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
|
||||
}),
|
||||
(Some((_, pos, _)), _) => {
|
||||
let v = v.unwrap_or(0.0);
|
||||
let v = if fam == Fam::Area100 { share(key, j, v) } else { v };
|
||||
let v = if is_100(fam) { share(key, j, v) } else { v };
|
||||
pos.get_mut(j).map(|acc| {
|
||||
let base = *acc;
|
||||
*acc = clean(*acc + v);
|
||||
@@ -287,6 +307,12 @@ fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec<usize>, f32) {
|
||||
(slot_of, slot_keys.len().max(1) as f32)
|
||||
}
|
||||
|
||||
/// Renders Cartesian column, bar, line, area, and combination charts.
|
||||
///
|
||||
/// Resolves series families and their axes, calculates stacking and
|
||||
/// category positions, and draws the corresponding primitives.
|
||||
/// Explicit chart style 9 adds white outlines to column and bar
|
||||
/// rectangles, including stacked and 100%-stacked variants.
|
||||
pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) {
|
||||
let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS);
|
||||
if ncat == 0 {
|
||||
@@ -385,7 +411,8 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
let k = slot_of.get(i).copied().unwrap_or(0) as f32;
|
||||
// Hairline bars are merged per pixel column (their envelope is what shows).
|
||||
let cull = merge_hairlines(bw, labels_on);
|
||||
let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k);
|
||||
let stroke = (chart.style == 9).then_some((WHITE, 1.0));
|
||||
let mut sink = BarSink::new(bw, horizontal, s.color, stroke, nslots, k);
|
||||
for (j, sp) in row.iter().enumerate() {
|
||||
let Some((b, t)) = sp else { continue };
|
||||
let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc));
|
||||
@@ -422,9 +449,9 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
}
|
||||
_ => {
|
||||
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
|
||||
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
|
||||
draw_runs(ctx, &pts, s.color, line_style_width(chart.style), s.smooth.then_some(plot));
|
||||
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
|
||||
if k == ChartKind::LineMarkers && cw >= 3.0 {
|
||||
if has_markers(k) && cw >= 3.0 {
|
||||
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
|
||||
}
|
||||
if labels_on {
|
||||
|
||||
@@ -57,8 +57,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
|
||||
.clone()
|
||||
.map(|s| {
|
||||
let sw = match s.kind {
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
|
||||
ChartKind::LineMarkers => Swatch::LineMarker,
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => {
|
||||
Swatch::Line
|
||||
}
|
||||
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
|
||||
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
|
||||
_ => Swatch::Box,
|
||||
};
|
||||
|
||||
@@ -71,8 +71,8 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay
|
||||
let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 };
|
||||
if settings.show_keys {
|
||||
let swatch = match series.kind {
|
||||
ChartKind::Line | ChartKind::LineStacked => Swatch::Line,
|
||||
ChartKind::LineMarkers => Swatch::LineMarker,
|
||||
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 => Swatch::Line,
|
||||
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
|
||||
_ => Swatch::Box,
|
||||
};
|
||||
draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color);
|
||||
|
||||
+90
-11
@@ -39,6 +39,28 @@ pub fn series_color(theme: &Theme, i: usize) -> Rgba {
|
||||
[r, g, b, 0xFF]
|
||||
}
|
||||
|
||||
/// Excel reference colours for explicit styles 1 and 9.
|
||||
///
|
||||
/// These palettes cover measured default-theme examples.
|
||||
/// Other counts still use the existing theme-based fallback.
|
||||
fn chart_style_series_color(theme: &Theme, style: u32, index: usize, count: usize) -> Rgba {
|
||||
if !matches!(style, 1 | 9) {
|
||||
return series_color(theme, index);
|
||||
}
|
||||
|
||||
const SMALL: [u8; 4] = [0x61, 0xB3, 0x81, 0x50];
|
||||
const MEDIUM: [u8; 8] = [0x55, 0x9E, 0x72, 0x46, 0x83, 0xC1, 0x9A, 0xC8];
|
||||
const LARGE: [u8; 16] = [0x4F, 0x93, 0x6A, 0x40, 0x7A, 0xB4, 0x61, 0xB3, 0x81, 0x50, 0x95, 0xDA, 0xAF, 0xD2, 0xBA, 0xAA];
|
||||
|
||||
let shades: &[u8] = match count {
|
||||
1..=4 => &SMALL,
|
||||
5..=8 => &MEDIUM,
|
||||
9..=16 => &LARGE,
|
||||
_ => return series_color(theme, index),
|
||||
};
|
||||
|
||||
shades.get(index).map_or_else(|| series_color(theme, index), |shade| [*shade, *shade, *shade, 0xFF])
|
||||
}
|
||||
/// The first `n` series colours for `theme`.
|
||||
pub fn default_palette(theme: &Theme, n: usize) -> Vec<Rgba> {
|
||||
(0..n.min(4096)).map(|i| series_color(theme, i)).collect()
|
||||
@@ -360,7 +382,7 @@ fn category_label(wb: &Workbook, src: Option<(&gridcraft_model::Sheet, RangeRef)
|
||||
/// the outer levels of a multi-level axis: a category range wider than a column of values (or
|
||||
/// taller than a row of values) groups its innermost labels, year beside month. Each outer level
|
||||
/// has one entry per category, non-empty where a group starts, as the cells are.
|
||||
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize) -> (Vec<String>, Vec<Vec<String>>) {
|
||||
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize, innermost: bool) -> (Vec<String>, Vec<Vec<String>>) {
|
||||
let cells: Option<(usize, RangeRef)> = parse_ref(wb, sheet, formula);
|
||||
let value_range = parse_ref(wb, sheet, values).map(|(_, r)| r);
|
||||
// Bound the category dimension by `limit` and read only the cells the levels use (the
|
||||
@@ -419,12 +441,21 @@ fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limi
|
||||
let at = |row: usize, col: usize| texts.get(row * w + col).cloned().unwrap_or_default();
|
||||
let column = |c: usize| (0..h).map(|row| at(row, c)).collect::<Vec<String>>();
|
||||
let row = |rr: usize| (0..w).map(|c| at(rr, c)).collect::<Vec<String>>();
|
||||
let outer = levels.outer as usize;
|
||||
if levels.by_columns {
|
||||
let value_count = eval_list_in(wb, sheet, values, limit, 0).len();
|
||||
let by_columns = if value_count == h && w > 1 && h != w {
|
||||
true
|
||||
} else if value_count == w && h > 1 && h != w {
|
||||
false
|
||||
} else {
|
||||
levels.by_columns
|
||||
};
|
||||
let outer = if by_columns { w.saturating_sub(1).min(3) } else { h.saturating_sub(1).min(3) };
|
||||
let result = if by_columns {
|
||||
(column(w - 1), (1..=outer).filter_map(|k| (w - 1).checked_sub(k)).map(column).collect())
|
||||
} else {
|
||||
(row(h - 1), (1..=outer).filter_map(|k| (h - 1).checked_sub(k)).map(row).collect())
|
||||
}
|
||||
};
|
||||
if innermost { (result.0, vec![]) } else { result }
|
||||
}
|
||||
|
||||
/// Whether `t` names a defined name seen from `sheet` (`Name`, or `Sheet1!Name` looked up on
|
||||
@@ -461,8 +492,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() {
|
||||
let values = nums(wb, sheet, &s.values, limit);
|
||||
let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1));
|
||||
let color =
|
||||
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
|
||||
let color = s
|
||||
.color
|
||||
.as_ref()
|
||||
.and_then(|c| c.resolve(&wb.theme))
|
||||
.map(|[r, g, b]| [r, g, b, 0xFF])
|
||||
.unwrap_or_else(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES)));
|
||||
let kind = chart.series_kind(i);
|
||||
let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) {
|
||||
// X values with text in them (labels) are ignored: the points are numbered 1..n.
|
||||
@@ -474,7 +509,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
if categories.is_none()
|
||||
&& let Some(f) = &s.categories
|
||||
{
|
||||
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit);
|
||||
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit, s.innermost_categories);
|
||||
c.truncate(limit);
|
||||
if !c.is_empty() {
|
||||
categories = Some(c);
|
||||
@@ -502,15 +537,59 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
secondary: s.secondary,
|
||||
smooth: s.smooth,
|
||||
trendlines,
|
||||
number_format: ref_format(wb, sheet, &s.values),
|
||||
number_format: match &s.number_format {
|
||||
Some(code) if s.values.trim_start().starts_with('{') => code.clone(),
|
||||
_ => 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());
|
||||
let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE));
|
||||
let palette = if matches!(chart.style, 1 | 9) {
|
||||
(0..n.min(PALETTE_CYCLE)).map(|i| chart_style_series_color(&wb.theme, chart.style, i, n)).collect()
|
||||
} else {
|
||||
default_palette(&wb.theme, n.min(PALETTE_CYCLE))
|
||||
};
|
||||
ChartData { categories, category_levels, series, palette }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod explicit_style_palette_tests {
|
||||
use super::*;
|
||||
|
||||
/// Verifies grayscale palette selection and fallback boundaries for explicit styles 1 and 9.
|
||||
#[test]
|
||||
fn explicit_style_palette_boundaries() {
|
||||
let theme = Workbook::default().theme;
|
||||
|
||||
for style in [1, 9] {
|
||||
for count in [0, 17, 255] {
|
||||
for index in [0, 1, 4, 8, 16] {
|
||||
assert_eq!(chart_style_series_color(&theme, style, index, count), series_color(&theme, index));
|
||||
}
|
||||
}
|
||||
|
||||
for (count, expected_first) in [(1, 0x61), (4, 0x61), (5, 0x55), (8, 0x55), (9, 0x4F), (16, 0x4F)] {
|
||||
assert_eq!(
|
||||
chart_style_series_color(&theme, style, 0, count),
|
||||
[expected_first, expected_first, expected_first, 255],
|
||||
"style {style}, count {count}",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
chart_style_series_color(&theme, style, 16, count),
|
||||
series_color(&theme, 16),
|
||||
"out-of-range index for style {style}, count {count}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for style in [0, 2, 10, 48] {
|
||||
assert_eq!(chart_style_series_color(&theme, style, 0, 4), series_color(&theme, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod label_budget_tests {
|
||||
use gridcraft_model::Workbook;
|
||||
@@ -521,7 +600,7 @@ mod label_budget_tests {
|
||||
#[test]
|
||||
fn category_labels_share_one_byte_budget() {
|
||||
let wb = Workbook::new();
|
||||
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS);
|
||||
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS, false);
|
||||
assert_eq!(texts.len(), 100_000);
|
||||
assert_eq!(texts.first().map(String::len), Some(super::MAX_LABEL_CHARS));
|
||||
assert!(texts.iter().map(String::len).sum::<usize>() <= super::MAX_CATEGORY_BYTES);
|
||||
@@ -544,7 +623,7 @@ mod label_budget_tests {
|
||||
}
|
||||
}
|
||||
// Five columns: column A is a fourth outer level and is discarded.
|
||||
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS);
|
||||
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS, false);
|
||||
assert_eq!(outer.len(), 3);
|
||||
assert_eq!(inner.last().map(String::len), Some(super::MAX_LABEL_CHARS));
|
||||
assert_eq!(outer.first().and_then(|l| l.last()).map(String::len), Some(super::MAX_LABEL_CHARS));
|
||||
|
||||
+345
-1
@@ -8,7 +8,7 @@ use crate::*;
|
||||
mod budget;
|
||||
mod data_table;
|
||||
|
||||
const ALL_KINDS: [ChartKind; 26] = [
|
||||
const ALL_KINDS: [ChartKind; 28] = [
|
||||
ChartKind::ColumnClustered,
|
||||
ChartKind::ColumnStacked,
|
||||
ChartKind::ColumnStacked100,
|
||||
@@ -18,6 +18,8 @@ const ALL_KINDS: [ChartKind; 26] = [
|
||||
ChartKind::Line,
|
||||
ChartKind::LineMarkers,
|
||||
ChartKind::LineStacked,
|
||||
ChartKind::LineStacked100,
|
||||
ChartKind::LineStacked100Markers,
|
||||
ChartKind::Pie,
|
||||
ChartKind::Doughnut,
|
||||
ChartKind::Area,
|
||||
@@ -549,6 +551,9 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
// References use their cells' format, whatever the series says.
|
||||
number_format: Some("0%".into()),
|
||||
innermost_categories: false,
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -561,6 +566,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
},
|
||||
Series {
|
||||
name: Some("Literal".into()),
|
||||
@@ -573,6 +580,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: Some("0.0%".into()),
|
||||
innermost_categories: false,
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -592,6 +601,7 @@ fn resolve_from_workbook() {
|
||||
assert!(s1.secondary);
|
||||
assert_eq!(d.series[2].name, "Literal");
|
||||
assert_eq!(d.series[2].values.len(), 4);
|
||||
assert_eq!(d.series[2].number_format, "0.0%");
|
||||
|
||||
// Default categories.
|
||||
c.series.remove(0);
|
||||
@@ -612,6 +622,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
},
|
||||
Series {
|
||||
name: None,
|
||||
@@ -624,6 +636,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
},
|
||||
];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
@@ -641,6 +655,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
|
||||
@@ -659,6 +675,8 @@ fn resolve_from_workbook() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
}];
|
||||
let d = resolve(&wb, 7, &c);
|
||||
assert_eq!(d.series.len(), 1);
|
||||
@@ -1364,6 +1382,8 @@ fn pie_points_follow_workbook_theme() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
let expected = vec![series_color(&wb.theme, 0), series_color(&wb.theme, 1)];
|
||||
@@ -1419,6 +1439,47 @@ fn area_charts_draw_source_value_labels_only_when_enabled() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_level_category_block_draws_its_innermost_level() {
|
||||
// A PivotChart's two levels of row labels in A1:B4, the outer one (country) on the left:
|
||||
// one label per point, from the innermost column.
|
||||
let mut wb = Workbook::new();
|
||||
{
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
s.name = "Graph".into();
|
||||
for (r, (outer, inner)) in [("Canada", "Ottawa"), ("", "Toronto"), ("USA", "Boston"), ("", "NYC")].iter().enumerate() {
|
||||
if !outer.is_empty() {
|
||||
s.set_value(CellRef::new(r as u32, 0), Value::from(*outer));
|
||||
}
|
||||
s.set_value(CellRef::new(r as u32, 1), Value::from(*inner));
|
||||
s.set_value(CellRef::new(r as u32, 2), Value::Number(r as f64 + 1.0));
|
||||
s.set_value(CellRef::new(5, r as u32), Value::from(*inner));
|
||||
s.set_value(CellRef::new(6, r as u32), Value::from(*outer));
|
||||
}
|
||||
}
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.series = vec![Series {
|
||||
categories: Some("Graph!$A$1:$B$4".into()),
|
||||
values: "Graph!$C$1:$C$4".into(),
|
||||
innermost_categories: true,
|
||||
..Series::default()
|
||||
}];
|
||||
let data = resolve(&wb, 0, &c);
|
||||
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
|
||||
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
|
||||
// A block with a column per point: its last row is the innermost level.
|
||||
c.series[0].categories = Some("Graph!$A$6:$D$7".into());
|
||||
let data = resolve(&wb, 0, &c);
|
||||
assert_eq!(data.categories, vec!["Canada", "", "USA", ""]);
|
||||
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
|
||||
// Without the flag, every cell is a label, as for any other chart.
|
||||
c.series[0].categories = Some("Graph!$A$1:$B$4".into());
|
||||
c.series[0].innermost_categories = false;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
|
||||
assert_eq!(data.category_levels, vec![vec!["Canada", "", "USA", ""]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_and_resolving_agree_on_the_combo_plot_kind() {
|
||||
// Resolved series carry `Chart::series_kind`, the kind drawing uses: for every chart kind,
|
||||
@@ -1491,6 +1552,62 @@ fn hundred_percent_stacked_areas_fill_each_category_to_its_total() {
|
||||
assert!(frac(top(south, 2)).abs() < 1e-3, "Q3: South reaches {}", frac(top(south, 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hundred_percent_stacked_lines_end_each_category_at_its_total() {
|
||||
let (north_color, south_color) = ([20, 96, 130, 255], [25, 107, 36, 255]);
|
||||
for kind in [ChartKind::LineStacked100, ChartKind::LineStacked100Markers] {
|
||||
let d = ChartData {
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"].iter().map(|s| s.to_string()).collect(),
|
||||
series: vec![series("North", &[10.0, 30.0, 0.0, 5.0], north_color, kind), series("South", &[30.0, 10.0, 0.0, 15.0], south_color, kind)],
|
||||
};
|
||||
let mut c = chart(kind);
|
||||
c.data_labels = false;
|
||||
let p = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
|
||||
let t = texts(&p);
|
||||
assert!(t.contains(&"100%") && t.contains(&"0%"), "{kind:?}: {t:?}");
|
||||
assert!(!t.contains(&"40"), "{kind:?}: {t:?}");
|
||||
// The value axis labels sit on their gridlines.
|
||||
let label_y = |s: &str| {
|
||||
p.iter()
|
||||
.find_map(|p| match p {
|
||||
Prim::Text { text, y, .. } if text == s => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(f32::NAN)
|
||||
};
|
||||
let (y0, y100) = (label_y("0%"), label_y("100%"));
|
||||
assert!(y0 > y100, "{kind:?}: {y0} {y100}");
|
||||
let frac = |y: f32| (y0 - y) / (y0 - y100);
|
||||
let line = |color: Rgba| {
|
||||
p.iter()
|
||||
.find_map(|p| match p {
|
||||
// The series line is 2.25 wide; its legend swatch is 2.0.
|
||||
Prim::Line { pts, color: c, width, .. } if *c == color && *width > 2.1 => {
|
||||
Some(pts.iter().map(|q| frac(q[1])).collect::<Vec<f32>>())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let (north, south) = (line(north_color), line(south_color));
|
||||
assert_eq!((north.len(), south.len()), (4, 4), "{kind:?}: {north:?} {south:?}");
|
||||
// A category whose total is zero stays on the baseline.
|
||||
for (j, (n, s)) in [(0.25, 1.0), (0.75, 1.0), (0.0, 0.0), (0.25, 1.0)].into_iter().enumerate() {
|
||||
assert!((north[j] - n).abs() < 1e-3 && (south[j] - s).abs() < 1e-3, "{kind:?} Q{}: {} {}", j + 1, north[j], south[j]);
|
||||
}
|
||||
// Point markers have a white outline; the legend's marker swatches have none.
|
||||
let circles = |outlined: bool| {
|
||||
p.iter()
|
||||
.filter(|p| matches!(p, Prim::Circle { fill: Some(f), stroke, .. } if (*f == north_color || *f == south_color) && stroke.is_some() == outlined))
|
||||
.count()
|
||||
};
|
||||
let with_markers = kind == ChartKind::LineStacked100Markers;
|
||||
assert_eq!((circles(true), circles(false)), if with_markers { (8, 2) } else { (0, 0) }, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_level_categories_resolve_and_draw() {
|
||||
let years = ["2023", "", "", "2024", "", ""];
|
||||
@@ -1565,6 +1682,22 @@ fn two_level_categories_resolve_and_draw() {
|
||||
assert!(d.category_levels.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn square_category_blocks_keep_their_declared_orientation_on_ties() {
|
||||
let mut wb = Workbook::new();
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
s.name = "Data".into();
|
||||
for (i, value) in ["A1", "B1", "A2", "B2", "A3", "B3"].iter().enumerate() {
|
||||
s.set_value(CellRef::parse(value).unwrap(), Value::from(*value));
|
||||
s.set_value(CellRef::new(3, i as u32), Value::Number(i as f64 + 1.0));
|
||||
}
|
||||
let mut c = chart(ChartKind::Line);
|
||||
c.series = vec![Series { categories: Some("Data!$A$1:$B$2".into()), values: "Data!$A$3:$B$3".into(), ..Series::default() }];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.categories, vec!["A2", "B2"]);
|
||||
assert_eq!(d.category_levels, vec![vec!["A1", "B1"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_trendline_forecast_does_not_collapse_the_columns() {
|
||||
let m = ApproxMeasure;
|
||||
@@ -1610,6 +1743,7 @@ fn box_whisker_draws_each_series_quartile_method() {
|
||||
assert!((heights[0] / heights[1] - 1.4).abs() < 0.001);
|
||||
}
|
||||
|
||||
/// Defined-name series titles on sheets with apostrophes resolve properly.
|
||||
#[test]
|
||||
fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
|
||||
// #2012: `'Bob''s'!Title` kept the doubled quote, so the sheet wasn't found and the series
|
||||
@@ -1641,11 +1775,13 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
..Series::default()
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
|
||||
}
|
||||
|
||||
/// Defined-name series titles on sheets whose names contain `!` resolve properly.
|
||||
#[test]
|
||||
fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
|
||||
// `'a!b'!Title`: the sheet name holds a `!`, so the evaluator must split the parsed name at
|
||||
@@ -1677,11 +1813,13 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
..Series::default()
|
||||
}];
|
||||
let d = resolve(&wb, 0, &c);
|
||||
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
|
||||
}
|
||||
|
||||
/// Volatile functions in series values or names mark the chart as volatile.
|
||||
#[test]
|
||||
fn volatile_series_formulas_are_detected() {
|
||||
let wb = Workbook::new();
|
||||
@@ -1698,6 +1836,8 @@ fn volatile_series_formulas_are_detected() {
|
||||
smooth: false,
|
||||
quartiles: Default::default(),
|
||||
trendlines: vec![],
|
||||
innermost_categories: false,
|
||||
number_format: None,
|
||||
});
|
||||
c
|
||||
};
|
||||
@@ -1712,6 +1852,7 @@ fn volatile_series_formulas_are_detected() {
|
||||
assert!(!has_volatile_series(&wb, 0, &chart(ChartKind::Line)));
|
||||
}
|
||||
|
||||
/// Defined names referenced by series formulas are followed for volatility checks.
|
||||
#[test]
|
||||
fn volatile_defined_names_are_followed() {
|
||||
let with = |values: &str| {
|
||||
@@ -1727,6 +1868,8 @@ fn volatile_defined_names_are_followed() {
|
||||
smooth: false,
|
||||
quartiles: Default::default(),
|
||||
trendlines: vec![],
|
||||
innermost_categories: false,
|
||||
number_format: None,
|
||||
});
|
||||
c
|
||||
};
|
||||
@@ -1774,3 +1917,204 @@ fn volatile_defined_names_are_followed() {
|
||||
assert!(!has_volatile_series(&wb, 1, &with("=Dice")));
|
||||
assert!(has_volatile_series(&wb, 1, &with("=FreshClock")));
|
||||
}
|
||||
|
||||
/// Explicit Excel chart styles should affect default series colours,
|
||||
/// without changing the workbook theme.
|
||||
#[test]
|
||||
fn explicit_chart_styles_use_distinct_default_colors() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.series.push(Series { values: "{10,20,30}".into(), ..Series::default() });
|
||||
|
||||
c.style = 2;
|
||||
let style2 = resolve(&wb, 0, &c).series[0].color;
|
||||
assert_eq!(style2, series_color(&wb.theme, 0));
|
||||
|
||||
c.style = 1;
|
||||
let style1 = resolve(&wb, 0, &c).series[0].color;
|
||||
|
||||
c.style = 9;
|
||||
let style9 = resolve(&wb, 0, &c).series[0].color;
|
||||
|
||||
assert_ne!(style1, style2, "style 1 should differ from style 2");
|
||||
assert_ne!(style9, style2, "style 9 should differ from style 2");
|
||||
}
|
||||
|
||||
/// Excel chart styles must not override explicitly assigned series colours.
|
||||
#[test]
|
||||
fn explicit_chart_styles_preserve_custom_series_colors() {
|
||||
let wb = Workbook::default();
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
|
||||
c.series.push(Series { values: "{10,20,30}".into(), color: Some(Color::rgb(12, 34, 56)), ..Series::default() });
|
||||
|
||||
for style in [1, 2, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(data.series[0].color, [12, 34, 56, 255], "explicit series colour changed under chart style {style}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the first four point colours measured in Excel for styles 1 and 9.
|
||||
#[test]
|
||||
fn excel_chart_styles_use_measured_point_palette() {
|
||||
let wb = Workbook::default();
|
||||
let mut c = chart(ChartKind::Pie);
|
||||
|
||||
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
|
||||
|
||||
let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]];
|
||||
|
||||
for style in [1, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(&data.palette[..4], &expected);
|
||||
assert_eq!(data.series[0].color, expected[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Excel's default-theme chart colours depend on the total series count.
|
||||
#[test]
|
||||
fn excel_chart_styles_depend_on_series_count() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
let base_series = Series { values: "{10,20,30,40}".into(), ..Series::default() };
|
||||
|
||||
let cases: &[(usize, [[u8; 4]; 3])] = &[
|
||||
(6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]),
|
||||
(12, [[0x4F, 0x4F, 0x4F, 0xFF], [0x93, 0x93, 0x93, 0xFF], [0x6A, 0x6A, 0x6A, 0xFF]]),
|
||||
];
|
||||
|
||||
for (count, expected) in cases {
|
||||
for style in [1, 9] {
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.style = style;
|
||||
c.series = vec![base_series.clone(); *count];
|
||||
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(data.series.len(), *count);
|
||||
|
||||
for (i, color) in expected.iter().enumerate() {
|
||||
assert_eq!(data.series[i].color, *color, "style {style}, {count} series, index {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Style 9 uses white outlines on column and bar data rectangles.
|
||||
#[test]
|
||||
fn explicit_style_nine_draws_white_column_outlines() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
for kind in [
|
||||
ChartKind::ColumnClustered,
|
||||
ChartKind::BarClustered,
|
||||
ChartKind::ColumnStacked,
|
||||
ChartKind::BarStacked,
|
||||
ChartKind::ColumnStacked100,
|
||||
ChartKind::BarStacked100,
|
||||
] {
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
|
||||
|
||||
for style in [1, 2, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
let color = data.series[0].color;
|
||||
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
|
||||
|
||||
let outlines: Vec<_> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Rect { fill: Some(fill), stroke, .. } if *fill == color => Some(*stroke),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert!(!outlines.is_empty(), "No data rectangles for {kind:?}, style {style}");
|
||||
|
||||
let expected = if style == 9 { Some(([255, 255, 255, 255], 1.0)) } else { None };
|
||||
|
||||
assert!(outlines.iter().all(|stroke| *stroke == expected), "Unexpected outline for {kind:?}, style {style}: {outlines:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Excel's default line weights are 3 pt for style 1 and 5 pt for style 9.
|
||||
/// Other styles retain GridCraft's existing stroke width.
|
||||
#[test]
|
||||
fn explicit_excel_styles_set_line_stroke_width() {
|
||||
let color: Rgba = [17, 73, 131, 255];
|
||||
|
||||
for kind in [ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked] {
|
||||
let data = ChartData {
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"].map(String::from).to_vec(),
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
series: vec![series("North", &[12.0, 19.0, 25.0, 30.0], color, kind)],
|
||||
};
|
||||
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
|
||||
for (style, expected_width) in [(0, 2.25_f32), (1, 3.0), (2, 2.25), (9, 5.0), (48, 2.25)] {
|
||||
c.style = style;
|
||||
|
||||
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
|
||||
|
||||
let widths: Vec<f32> = prims
|
||||
.iter()
|
||||
.filter_map(|primitive| match primitive {
|
||||
Prim::Line { color: line_color, width, .. } if *line_color == color => Some(*width),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(widths, vec![expected_width], "Unexpected stroke width for {kind:?}, style {style}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrow style 9 bars (at or below the 1 px outline width) omit the white stroke so their gray fill stays visible.
|
||||
#[test]
|
||||
fn narrow_style_9_bars_retain_visible_fill() {
|
||||
let fill_color: Rgba = [0x61, 0x61, 0x61, 0xFF];
|
||||
// Stay within MAX_LABELS (200) so data labels remain active on the direct unmerged path,
|
||||
// while keeping each single-series slot <= 0.88 px inside the 220 px chart.
|
||||
let count = 100usize;
|
||||
let categories: Vec<String> = (0..count).map(|i| format!("C{i}")).collect();
|
||||
let values = vec![50.0; count];
|
||||
|
||||
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] {
|
||||
let data = ChartData {
|
||||
categories: categories.clone(),
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
series: vec![series("S1", &values, fill_color, kind)],
|
||||
};
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
// Data labels keep bars on the unmerged direct path even when narrower than 1 px.
|
||||
c.data_labels = true;
|
||||
c.gridlines = false;
|
||||
c.style = 9;
|
||||
|
||||
let prims = render(&c, &data, 220.0, 220.0, &ApproxMeasure);
|
||||
let narrow_bars: Vec<_> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Rect { w, h, fill: Some(fill), stroke, .. } if *fill == fill_color && (*w <= 1.0 || *h <= 1.0) => Some(*stroke),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(narrow_bars.len(), count, "Direct unmerged path must emit all {count} bars individually for {kind:?}");
|
||||
assert!(narrow_bars.iter().all(Option::is_none), "Narrow style 9 bars must omit the 1 px white outline: {narrow_bars:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,3 +148,32 @@ fn dense_and_tiny_tables_are_bounded_and_explicit() {
|
||||
assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_keys_for_100_percent_stacked_lines_use_line_swatches() {
|
||||
for (kind, marker) in [(ChartKind::LineStacked100, false), (ChartKind::LineStacked100Markers, true)] {
|
||||
let mut c = chart(kind);
|
||||
c.title = Some(String::new());
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
c.data_table = Some(ChartDataTable::default());
|
||||
let color = [1, 2, 3, 255];
|
||||
let d = ChartData {
|
||||
categories: ["Jan", "Feb"].map(String::from).to_vec(),
|
||||
series: vec![series("Rate", &[1.0, 3.0], color, kind)],
|
||||
..Default::default()
|
||||
};
|
||||
let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure);
|
||||
let header_y = p
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
Prim::Text { text, y, .. } if text == "Jan" => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let key_circles = p.iter().filter(|p| matches!(p, Prim::Circle { cy, fill: Some(f), .. } if *f == color && *cy > header_y)).count();
|
||||
assert_eq!(key_circles, usize::from(marker), "{kind:?}");
|
||||
let key_box = p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y));
|
||||
assert!(!key_box, "{kind:?} key is a line swatch");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,6 +162,43 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
|
||||
Some(serial as f64)
|
||||
}
|
||||
|
||||
/// The calendar date a pivot cache's ISO 8601 date items (`<d>`, `minDate`, `startDate`…) give
|
||||
/// a date of a date system's calendar, as [`datetime_from_serial`] returns it. Those dates count
|
||||
/// real days: from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to
|
||||
/// February 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious
|
||||
/// 1900-02-29, runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30,
|
||||
/// serial 1 is 1899-12-31 and serial 60 is 1900-02-28. Excel writes its caches that way.
|
||||
pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) {
|
||||
if sys == DateSystem::D1900 && year == 1900 && month <= 2 {
|
||||
let serial = if month <= 1 { day } else { 31 + day };
|
||||
return civil_from_days(i64::from(serial) + UNIX_1899_12_30);
|
||||
}
|
||||
(year, month, day)
|
||||
}
|
||||
|
||||
/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`]
|
||||
/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid.
|
||||
/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the
|
||||
/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date,
|
||||
/// or one before the epoch or after 9999-12-31.
|
||||
pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option<f64> {
|
||||
let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?);
|
||||
match (sys, y, m, d) {
|
||||
(DateSystem::D1900, 1900, 2, 29) => return Some(60.0),
|
||||
(DateSystem::D1904, 1899, 12, 30) => return Some(0.0),
|
||||
_ => {}
|
||||
}
|
||||
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) {
|
||||
return None;
|
||||
}
|
||||
let base = match sys {
|
||||
DateSystem::D1900 => UNIX_1899_12_30,
|
||||
DateSystem::D1904 => UNIX_1904_01_01,
|
||||
};
|
||||
let serial = days_from_civil(y, m, d) - base;
|
||||
(0..=max_serial(sys)).contains(&serial).then_some(serial as f64)
|
||||
}
|
||||
|
||||
/// 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..max_serial(sys) as f64 + 1.0).contains(&serial) {
|
||||
@@ -384,4 +421,32 @@ mod tests {
|
||||
assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_dates_count_real_days() {
|
||||
let s = DateSystem::D1900;
|
||||
// Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31.
|
||||
for (serial, ymd) in
|
||||
[(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))]
|
||||
{
|
||||
let d = datetime_from_serial(s, serial as f64).unwrap();
|
||||
assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}");
|
||||
assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}");
|
||||
}
|
||||
assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None);
|
||||
assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None);
|
||||
// The 1904 system has no offset; 1899-12-30 stands for a time's date part there too.
|
||||
let s = DateSystem::D1904;
|
||||
let d = datetime_from_serial(s, 0.5).unwrap();
|
||||
assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0));
|
||||
assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,4 +16,4 @@ pub use addr::{
|
||||
};
|
||||
pub use date::DateSystem;
|
||||
pub use region::Region;
|
||||
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
|
||||
pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
|
||||
|
||||
@@ -49,6 +49,19 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option<f64> {
|
||||
parse_numeric(s.trim(), sys).map(|(n, _)| n)
|
||||
}
|
||||
|
||||
/// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users
|
||||
/// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5,
|
||||
/// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse
|
||||
/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. So does `+`
|
||||
/// before a time (`+1:30`), while `-1:30` is a formula (rows 1 to 30), as Excel for the web does.
|
||||
pub fn starts_formula(input: &str) -> bool {
|
||||
input.starts_with('=')
|
||||
|| (input.len() > 1
|
||||
&& input.starts_with(['+', '-'])
|
||||
&& parse_number_text(input).is_none()
|
||||
&& !input.strip_prefix('+').is_some_and(|time| time.contains(':') && parse_number_text(time).is_some()))
|
||||
}
|
||||
|
||||
/// Text that Excel's "Number Stored as Text" check flags: it would be a number if typed (signs,
|
||||
/// thousands separators, currency, percent, exponent, a parenthesised negative). Dates, times and
|
||||
/// fractions kept as text are not flagged, as in Excel.
|
||||
@@ -577,6 +590,19 @@ mod tests {
|
||||
assert_eq!(p("1.2.3.4").value, Value::text("1.2.3.4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() {
|
||||
// #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did.
|
||||
for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--", "-1:30", "+1/30", "-1/30"] {
|
||||
assert!(starts_formula(s), "{s}");
|
||||
}
|
||||
// Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or
|
||||
// apostrophe, `+` before a time and other text stay text.
|
||||
for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b", "+1:30", "+0:30:15"] {
|
||||
assert!(!starts_formula(s), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_and_times() {
|
||||
assert_eq!(p("10/7/2026").value, Value::Number(46302.0));
|
||||
|
||||
@@ -434,12 +434,16 @@ fn secondary_weights(s: &str) -> impl Iterator<Item = u16> + '_ {
|
||||
}
|
||||
|
||||
/// Sorting order used by Sort (ascending): numbers, text, booleans, errors, then blanks last.
|
||||
/// Numbers compare exactly, not at the 15 digits of [`compare`]. Observed in Excel 365: SORT,
|
||||
/// SORTBY, Data > Sort, the AutoFilter sort and table sort all put 0.3 before `=0.1+0.2`
|
||||
/// (0.30000000000000004) ascending and after it descending, whatever the input order.
|
||||
pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
|
||||
match (a, b) {
|
||||
(Value::Empty, Value::Empty) => Ordering::Equal,
|
||||
(Value::Empty, _) => Ordering::Greater,
|
||||
(_, Value::Empty) => Ordering::Less,
|
||||
(Value::Error(_), Value::Error(_)) => Ordering::Equal,
|
||||
(Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
_ => compare(a, b),
|
||||
}
|
||||
}
|
||||
@@ -497,6 +501,31 @@ pub fn sci_text(n: f64, sig: usize) -> String {
|
||||
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
|
||||
}
|
||||
|
||||
/// Longest text a cell can hold, in UTF-16 code units.
|
||||
pub const MAX_TEXT_CHARS: usize = 32_767;
|
||||
|
||||
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
|
||||
pub fn cap_text(mut s: String) -> String {
|
||||
if s.len() > MAX_TEXT_CHARS {
|
||||
let mut units = 0;
|
||||
if let Some((i, _)) = s.char_indices().find(|(_, c)| {
|
||||
units += c.len_utf16();
|
||||
units > MAX_TEXT_CHARS
|
||||
}) {
|
||||
s.truncate(i);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through.
|
||||
pub fn cap_value(v: Value) -> Value {
|
||||
match v {
|
||||
Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())),
|
||||
v => v,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -580,6 +609,16 @@ mod tests {
|
||||
assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() {
|
||||
let face = "😀";
|
||||
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS));
|
||||
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS));
|
||||
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face));
|
||||
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1));
|
||||
assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arabic_diacritics_sort_with_their_base_letter() {
|
||||
assert_eq!(compare_text("بَاب", "بيت"), Ordering::Less);
|
||||
@@ -775,6 +814,19 @@ mod tests {
|
||||
assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_orders_numbers_exactly() {
|
||||
let num = Value::Number;
|
||||
let e = 0.1 + 0.2;
|
||||
assert_eq!(sort_compare(&num(0.3), &num(e)), Ordering::Less);
|
||||
assert_eq!(sort_compare(&num(e), &num(0.3)), Ordering::Greater);
|
||||
assert_eq!(sort_compare(&num(100.0), &num(100.0 + 1e-14)), Ordering::Less);
|
||||
assert_eq!(sort_compare(&num(0.0), &num(-0.0)), Ordering::Equal);
|
||||
assert_eq!(sort_compare(&num(1.0), &Value::from("a")), Ordering::Less);
|
||||
// `=` keeps its 15-digit comparison.
|
||||
assert_eq!(compare(&num(0.3), &num(e)), Ordering::Equal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrays() -> Result<(), std::io::Error> {
|
||||
let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).ok_or_else(|| std::io::Error::other("valid array"))?;
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
//! Calculation benchmarks on fixed workbooks built in code (release build). Run through
|
||||
//! `cargo xtask bench`, which builds this in release and compares against a saved baseline, or
|
||||
//! directly: `cargo run --release -p gridcraft-engine --example bench -- [--quick] [--rows N]
|
||||
//! [--reps N] [--filter NAME] [--json PATH]`.
|
||||
//!
|
||||
//! Every scenario builds its workbook untimed, runs one warm-up, then times `reps` runs of one
|
||||
//! operation through `Session::execute` (so a timing includes what an edit costs the user: undo
|
||||
//! history, graph update and recalculation). Results are checked so a scenario that silently
|
||||
//! stopped recalculating fails instead of getting fast.
|
||||
|
||||
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
struct Cfg {
|
||||
rows: usize,
|
||||
reps: usize,
|
||||
filter: Option<String>,
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
name: &'static str,
|
||||
what: String,
|
||||
times: Vec<Duration>,
|
||||
cells: usize,
|
||||
}
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
/// A scenario: its name and the function that runs it.
|
||||
type Scenario = (&'static str, fn(&Cfg) -> R<Outcome>);
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
match run() {
|
||||
Ok(()) => std::process::ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("bench: {e}");
|
||||
std::process::ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> R<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
|
||||
let quick = args.iter().any(|a| a == "--quick");
|
||||
let cfg = Cfg {
|
||||
rows: count(flag("--rows"), "--rows")?.unwrap_or(if quick { 10_000 } else { 100_000 }).max(200),
|
||||
reps: count(flag("--reps"), "--reps")?.unwrap_or(if quick { 3 } else { 7 }).max(1),
|
||||
filter: flag("--filter"),
|
||||
};
|
||||
let scenarios: [Scenario; 10] = [
|
||||
("edit.chain", edit_chain),
|
||||
("edit.fanout", edit_fanout),
|
||||
("edit.sliding", edit_sliding),
|
||||
("edit.sumifs", edit_sumifs),
|
||||
("edit.lookup", edit_lookup),
|
||||
("enter.formulas", enter_formulas),
|
||||
("recalc.full", recalc_full),
|
||||
("data.sort", data_sort),
|
||||
("xlsx.save", xlsx_save),
|
||||
("xlsx.open", xlsx_open),
|
||||
];
|
||||
println!("GridCraft calc bench: {} rows, {} reps (median / min)\n", cfg.rows, cfg.reps);
|
||||
println!("{:<16} {:>10} {:>10} {:>9} workload", "scenario", "median", "min", "cells");
|
||||
let mut results = Vec::new();
|
||||
// A failed scenario is reported and the others still run, so one regression doesn't hide
|
||||
// the numbers for everything else.
|
||||
let mut failed = Vec::new();
|
||||
let selected: Vec<_> = scenarios.into_iter().filter(|(name, _)| cfg.filter.as_deref().is_none_or(|p| name.contains(p))).collect();
|
||||
if selected.is_empty() {
|
||||
// An empty run would otherwise save as a baseline with nothing in it.
|
||||
return Err(format!("--filter {} matches no scenario", cfg.filter.as_deref().unwrap_or("")));
|
||||
}
|
||||
for (name, f) in selected {
|
||||
let o = match f(&cfg) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
println!("{name:<16} {:>10} {e}", "FAILED");
|
||||
failed.push(name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let (med, min) = stats(&o.times);
|
||||
let cells = if o.cells == 0 { "-".to_string() } else { o.cells.to_string() };
|
||||
println!("{:<16} {:>10} {:>10} {:>9} {}", o.name, ms(med), ms(min), cells, o.what);
|
||||
results.push(json!({"name": o.name, "what": o.what, "median_ms": med, "min_ms": min, "cells": o.cells}));
|
||||
}
|
||||
if let Some(path) = flag("--json") {
|
||||
let out = json!({"rows": cfg.rows, "reps": cfg.reps, "results": results, "failed": failed});
|
||||
let text = serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&path, text).map_err(|e| format!("{path}: {e}"))?;
|
||||
}
|
||||
if failed.is_empty() { Ok(()) } else { Err(format!("{} scenario(s) failed: {}", failed.len(), failed.join(", "))) }
|
||||
}
|
||||
|
||||
fn stats(times: &[Duration]) -> (f64, f64) {
|
||||
let mut v: Vec<f64> = times.iter().map(|d| d.as_secs_f64() * 1000.0).collect();
|
||||
v.sort_by(f64::total_cmp);
|
||||
// An even count averages the two middle samples.
|
||||
let mid = v.len() / 2;
|
||||
let med = match (v.len() % 2, v.get(mid.wrapping_sub(1)), v.get(mid)) {
|
||||
(0, Some(a), Some(b)) => (a + b) / 2.0,
|
||||
(_, _, Some(m)) => *m,
|
||||
_ => 0.0,
|
||||
};
|
||||
(med, v.first().copied().unwrap_or(0.0))
|
||||
}
|
||||
|
||||
fn ms(v: f64) -> String {
|
||||
if v >= 100.0 { format!("{v:.0} ms") } else { format!("{v:.2} ms") }
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Json) -> R<Json> {
|
||||
s.execute(cmd, p).map_err(|e| format!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// A count flag's value; one that isn't a number is an error, not the default.
|
||||
fn count(v: Option<String>, name: &str) -> R<Option<usize>> {
|
||||
v.map(|s| s.parse().map_err(|_| format!("{name}: `{s}` is not a count"))).transpose()
|
||||
}
|
||||
|
||||
fn session() -> R<Session> {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// Writes `rows` rows starting at `col` row 1, `make(i)` giving row i (0-based), in chunks.
|
||||
fn fill(s: &mut Session, col: &str, rows: usize, make: impl Fn(usize) -> Json) -> R<()> {
|
||||
let chunk = 10_000;
|
||||
let mut r = 0;
|
||||
while r < rows {
|
||||
let n = chunk.min(rows - r);
|
||||
let vals: Vec<Json> = (r..r + n).map(&make).collect();
|
||||
exec(s, "range.setValues", json!({"range": format!("{col}{}", r + 1), "values": vals}))?;
|
||||
r += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn num(s: &Session, at: &str) -> R<f64> {
|
||||
let c = CellRef::parse(at).ok_or_else(|| format!("bad ref {at}"))?;
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
match d.wb.sheet(0).map(|sh| sh.value(c)) {
|
||||
Some(Value::Number(n)) => Ok(n),
|
||||
other => Err(format!("{at} = {other:?}, expected a number")),
|
||||
}
|
||||
}
|
||||
|
||||
fn expect(s: &Session, at: &str, want: f64) -> R<()> {
|
||||
let got = num(s, at)?;
|
||||
if (got - want).abs() <= 1e-6 * want.abs().max(1.0) { Ok(()) } else { Err(format!("{at} = {got}, expected {want}")) }
|
||||
}
|
||||
|
||||
fn recalc_cells(s: &Session) -> usize {
|
||||
s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Runs a warm-up then `reps` timed calls of `op(rep)`, then `check(rep)` (untimed) after each.
|
||||
fn time(
|
||||
cfg: &Cfg,
|
||||
s: &mut Session,
|
||||
op: impl FnMut(&mut Session, usize) -> R<()>,
|
||||
check: impl Fn(&Session, usize) -> R<()>,
|
||||
) -> R<(Vec<Duration>, usize)> {
|
||||
time_prepared(cfg, s, |_| Ok(()), op, check)
|
||||
}
|
||||
|
||||
/// [`time`] with `prep` run (untimed) before each call, to put back the state `op` starts from.
|
||||
fn time_prepared(
|
||||
cfg: &Cfg,
|
||||
s: &mut Session,
|
||||
mut prep: impl FnMut(&mut Session) -> R<()>,
|
||||
mut op: impl FnMut(&mut Session, usize) -> R<()>,
|
||||
check: impl Fn(&Session, usize) -> R<()>,
|
||||
) -> R<(Vec<Duration>, usize)> {
|
||||
let mut times = Vec::with_capacity(cfg.reps);
|
||||
let mut cells = 0;
|
||||
for rep in 0..=cfg.reps {
|
||||
prep(s)?;
|
||||
let t = Instant::now();
|
||||
op(s, rep)?;
|
||||
let dt = t.elapsed();
|
||||
check(s, rep)?;
|
||||
cells = recalc_cells(s);
|
||||
if rep > 0 {
|
||||
times.push(dt);
|
||||
}
|
||||
}
|
||||
Ok((times, cells))
|
||||
}
|
||||
|
||||
/// Value typed into A1 on rep `r`: alternates so every rep changes something.
|
||||
fn a1(r: usize) -> f64 {
|
||||
(r % 2 + 2) as f64
|
||||
}
|
||||
|
||||
/// A running sum `B[n] = B[n-1] + A[n]`: one edit at the top recalculates a dependency chain
|
||||
/// `rows` deep.
|
||||
fn edit_chain(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |_| json!([1]))?;
|
||||
fill(&mut s, "B", n, |i| json!([if i == 0 { "=A1".to_string() } else { format!("=B{i}+A{}", i + 1) }]))?;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, &format!("B{n}"), (n - 1) as f64 + a1(r)),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.chain", what: format!("edit A1 under a {n}-deep running sum"), times, cells })
|
||||
}
|
||||
|
||||
/// `rows` formulas that each read `$A$1`: one edit, a wide and shallow dirty set.
|
||||
fn edit_fanout(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
exec(&mut s, "cell.set", json!({"cell": "A1", "input": "1"}))?;
|
||||
fill(&mut s, "B", n, |i| json!([format!("=$A$1*{}", i + 1)]))?;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, &format!("B{n}"), a1(r) * n as f64),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.fanout", what: format!("edit $A$1 read by {n} formulas"), times, cells })
|
||||
}
|
||||
|
||||
/// `rows` overlapping 100-row window sums; an edit in the middle dirties ~100 of them, so this
|
||||
/// measures the range index lookup, not evaluation.
|
||||
fn edit_sliding(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n + 99, |_| json!([1]))?;
|
||||
fill(&mut s, "B", n, |i| json!([format!("=SUM(A{}:A{})", i + 1, i + 100)]))?;
|
||||
let mid = n / 2;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": format!("A{mid}"), "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, &format!("B{mid}"), 99.0 + a1(r)),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.sliding", what: format!("edit one cell under {n} 100-row SUM windows"), times, cells })
|
||||
}
|
||||
|
||||
/// 100 whole-column SUMIFS over `rows` rows of data, all dirtied by one data edit.
|
||||
fn edit_sumifs(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([1, (i % 100) as f64]))?;
|
||||
fill(&mut s, "D", 100, |k| json!([format!("=SUMIFS(A:A,B:B,{k})")]))?;
|
||||
// Rows whose category is 0 (i % 100 == 0), A1 among them.
|
||||
let per = n.div_ceil(100) as f64;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|
||||
|s, r| expect(s, "D1", per - 1.0 + a1(r)),
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.sumifs", what: format!("edit data under 100 SUMIFS(A:A,B:B,k) over {n} rows"), times, cells })
|
||||
}
|
||||
|
||||
/// 100 exact-match XLOOKUPs over whole columns of `rows` keys, all dirtied by one key edit.
|
||||
fn edit_lookup(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([(i + 1) as f64, (2 * (i + 1)) as f64]))?;
|
||||
let step = n / 100;
|
||||
fill(&mut s, "D", 100, |k| json!([format!("=XLOOKUP({},A:A,B:B,0)", (k + 1) * step)]))?;
|
||||
let last = (2 * 100 * step) as f64;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
// D1 looks up the key in A{step}: removing it (-step) makes D1 fall back to 0, putting it
|
||||
// back finds it again. Every lookup reads A:A, so all 100 recalculate either way.
|
||||
|s, r| {
|
||||
let key = if r % 2 == 0 { format!("-{step}") } else { step.to_string() };
|
||||
exec(s, "cell.set", json!({"cell": format!("A{step}"), "input": key})).map(drop)
|
||||
},
|
||||
|s, r| {
|
||||
expect(s, "D1", if r % 2 == 0 { 0.0 } else { (2 * step) as f64 })?;
|
||||
expect(s, "D100", last)
|
||||
},
|
||||
)?;
|
||||
Ok(Outcome { name: "edit.lookup", what: format!("edit a key under 100 XLOOKUPs over {n} rows"), times, cells })
|
||||
}
|
||||
|
||||
/// Entering `rows` formulas in one command: parse, graph insertion and first evaluation.
|
||||
fn enter_formulas(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([(i % 97) as f64]))?;
|
||||
let vals: Vec<Json> = (0..n).map(|i| json!([format!("=A{}*2+1", i + 1)])).collect();
|
||||
let (times, cells) = time_prepared(
|
||||
cfg,
|
||||
&mut s,
|
||||
// Each run enters the formulas into empty cells, not over the previous run's.
|
||||
|s| exec(s, "edit.clearAll", json!({"range": format!("B1:B{n}")})).map(drop),
|
||||
|s, _| exec(s, "range.setValues", json!({"range": "B1", "values": vals})).map(drop),
|
||||
|s, _| expect(s, &format!("B{n}"), ((n - 1) % 97) as f64 * 2.0 + 1.0),
|
||||
)?;
|
||||
Ok(Outcome { name: "enter.formulas", what: format!("enter {n} formulas =An*2+1 in one paste"), times, cells })
|
||||
}
|
||||
|
||||
/// A model with 3 formulas per row (arithmetic and a row SUM), recalculated in full.
|
||||
fn model(n: usize) -> R<Session> {
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([(i % 97) as f64, format!("=A{}*2", i + 1), format!("=B{0}+A{0}", i + 1), format!("=SUM(A{0}:C{0})", i + 1)]))?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn recalc_full(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = model(n)?;
|
||||
// Manual calculation, and A[n] changed (untimed) before each run, so D[n] is stale until
|
||||
// Calculate Now recalculates: a Calculate Now that did nothing fails the check.
|
||||
exec(&mut s, "formulas.calculationOptions", json!({"mode": "manual"}))?;
|
||||
let mut rep = 0;
|
||||
let (times, cells) = time_prepared(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s| {
|
||||
rep += 1;
|
||||
exec(s, "cell.set", json!({"cell": format!("A{n}"), "input": (100 + rep).to_string()})).map(drop)
|
||||
},
|
||||
|s, _| exec(s, "formulas.calculateNow", json!({})).map(drop),
|
||||
|s, r| expect(s, &format!("D{n}"), (101 + r) as f64 * 6.0),
|
||||
)?;
|
||||
Ok(Outcome { name: "recalc.full", what: format!("Calculate Now, {} formulas (3 per row)", 3 * n), times, cells })
|
||||
}
|
||||
|
||||
fn data_sort(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = session()?;
|
||||
fill(&mut s, "A", n, |i| json!([format!("Item {i}"), (i % 97) as f64, ((i * 7919) % 1000) as f64]))?;
|
||||
let (times, _) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, r| {
|
||||
let cmd = if r % 2 == 0 { "data.sortDescending" } else { "data.sortAscending" };
|
||||
exec(s, cmd, json!({"range": format!("A1:C{n}"), "column": "B"})).map(drop)
|
||||
},
|
||||
|s, r| expect(s, "B1", if r % 2 == 0 { 96.0 } else { 0.0 }),
|
||||
)?;
|
||||
// A sort with no formulas recalculates nothing; 0 shows as "-".
|
||||
Ok(Outcome { name: "data.sort", what: format!("sort {n} rows x 3 columns by a numeric key"), times, cells: 0 })
|
||||
}
|
||||
|
||||
fn save_bytes(s: &mut Session) -> R<String> {
|
||||
let r = exec(s, "file.saveBytes", json!({"format": "xlsx"}))?;
|
||||
r.get("base64").and_then(Json::as_str).map(str::to_string).ok_or_else(|| "file.saveBytes: no base64".to_string())
|
||||
}
|
||||
|
||||
fn xlsx_save(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = model(n)?;
|
||||
let (times, _) = time(cfg, &mut s, |s, _| save_bytes(s).map(drop), |_, _| Ok(()))?;
|
||||
Ok(Outcome { name: "xlsx.save", what: format!("save the {n}-row model as XLSX"), times, cells: 0 })
|
||||
}
|
||||
|
||||
fn xlsx_open(cfg: &Cfg) -> R<Outcome> {
|
||||
let n = cfg.rows;
|
||||
let mut s = model(n)?;
|
||||
let b64 = save_bytes(&mut s)?;
|
||||
let last = ((n - 1) % 97) as f64 * 6.0;
|
||||
let (times, cells) = time(
|
||||
cfg,
|
||||
&mut s,
|
||||
|s, _| exec(s, "file.open", json!({"name": "bench.xlsx", "base64": b64})).map(drop),
|
||||
|s, _| expect(s, &format!("D{n}"), last),
|
||||
)?;
|
||||
Ok(Outcome { name: "xlsx.open", what: format!("open the {n}-row model from XLSX (with full recalc)"), times, cells })
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
//! Performance scenarios on large workbooks (release build):
|
||||
//! `cargo run --release -p gridcraft-engine --example perf -- [rows]`
|
||||
|
||||
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
fn main() {
|
||||
let rows: usize = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(100_000);
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
// Data: rows × 6 numeric columns, built through range.setValues in chunks.
|
||||
let t = Instant::now();
|
||||
let chunk = 10_000;
|
||||
let mut r = 0;
|
||||
while r < rows {
|
||||
let n = chunk.min(rows - r);
|
||||
let vals: Vec<serde_json::Value> = (0..n)
|
||||
.map(|i| json!([format!("Item {}", r + i), (r + i) as f64, ((r + i) % 97) as f64, ((r + i) % 13) as f64 * 1.5, 1.0, 2.0]))
|
||||
.collect();
|
||||
s.execute("range.setValues", json!({"range": format!("A{}", r + 1), "values": vals})).expect("set");
|
||||
r += n;
|
||||
}
|
||||
println!("fill {rows}x6 values: {:?}", t.elapsed());
|
||||
// Formulas: G = B*C+D, H = running sum of G (chain).
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "G1", "input": "=B1*C1+D1"})).expect("g1");
|
||||
s.execute("edit.autoFill", json!({"source": "G1", "target": format!("G1:G{rows}")})).expect("fill g");
|
||||
println!("fill {rows} formulas G=B*C+D: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "H1", "input": "=G1"})).expect("h1");
|
||||
s.execute("cell.set", json!({"cell": "H2", "input": "=H1+G2"})).expect("h2");
|
||||
s.execute("edit.autoFill", json!({"source": "H2", "target": format!("H2:H{rows}")})).expect("fill h");
|
||||
println!("fill {rows} chained running-sum formulas: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "J1", "input": format!("=SUM(G1:G{rows})")})).expect("sum");
|
||||
s.execute("cell.set", json!({"cell": "J2", "input": "=SUMIFS(B:B,C:C,\">50\")"})).expect("sumifs");
|
||||
s.execute("cell.set", json!({"cell": "J3", "input": "=XLOOKUP(\"Item 77777\",A:A,B:B)"})).expect("xlookup");
|
||||
println!("aggregate formulas: {:?}", t.elapsed());
|
||||
// Edit at the top: everything below recalculates.
|
||||
let t = Instant::now();
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": "5"})).expect("edit");
|
||||
println!("edit B1 → recalc {} cells: {:?}", s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0), t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("data.sortDescending", json!({"range": format!("A1:F{rows}"), "column": "C"})).expect("sort");
|
||||
println!("sort {rows} rows: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).expect("save");
|
||||
let b64 = r["base64"].as_str().unwrap_or("").to_string();
|
||||
println!("save xlsx ({} bytes): {:?}", r["bytes"], t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("file.open", json!({"name": "big.xlsx", "base64": b64})).expect("open");
|
||||
println!("open xlsx + full recalc: {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
s.execute("edit.undo", json!({})).ok();
|
||||
println!("undo: {:?}", t.elapsed());
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub mod macros;
|
||||
pub mod pivot;
|
||||
pub mod print;
|
||||
pub mod python;
|
||||
pub mod quick_analysis;
|
||||
pub mod review;
|
||||
pub mod sheet;
|
||||
pub mod slicer;
|
||||
@@ -187,6 +188,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(forecast::specs());
|
||||
v.extend(analysis::specs());
|
||||
v.extend(print::specs());
|
||||
v.extend(quick_analysis::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -23,8 +23,10 @@ mod sort;
|
||||
mod tools;
|
||||
mod validation;
|
||||
|
||||
pub use filter::filter_values;
|
||||
pub(crate) use filter::{apply_filter, grow_autofilter};
|
||||
pub use filter::{
|
||||
FilterChoice, filter_by_cell_params, filter_choices, filter_choices_params, filter_choices_selection, filter_selection, filter_values,
|
||||
};
|
||||
pub(crate) use filter::{apply_filter, grow_autofilter, migrate_loaded_autofilters, slicer_identity_token, slicer_tile_text};
|
||||
use filter::{clear_filter, filter_by, reapply, toggle_filter};
|
||||
use grouping::{detail, group, outline_settings, show_levels, subtotal};
|
||||
pub use sort::sort_context;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@ fn filter_blanks_include_empty_text_and_formula_results() {
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["id", "f"], ["e", null], ["ef", "=\"\""], ["sp", " "], ["z", 0]]})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B5"})).unwrap();
|
||||
let r = s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap();
|
||||
assert_eq!(r["hiddenRows"], json!(2));
|
||||
assert_eq!(r["hiddenRows"], json!(1));
|
||||
let vals = filter_values(&s.doc().unwrap().wb, 0, 1);
|
||||
// The `=""` result joins (Blanks) instead of showing as its own empty entry.
|
||||
assert!(!vals.iter().any(|(t, _)| t.is_empty()), "{vals:?}");
|
||||
@@ -557,6 +557,64 @@ fn a_rule_with_an_unknown_type_operator_or_error_style_is_refused() {
|
||||
assert_eq!(sh.validations.len(), 3);
|
||||
assert!(check_validation(&s.doc().unwrap().wb, 0, CellRef::parse("A2").unwrap(), "0").is_some());
|
||||
}
|
||||
/// Excel AutoFilter ignores surrounding spaces when matching text values.
|
||||
#[test]
|
||||
fn autofilter_value_lists_and_equality_ignore_surrounding_spaces() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Name"],
|
||||
["Card"],
|
||||
["Card "],
|
||||
[" Card"],
|
||||
[" Card "],
|
||||
["card"],
|
||||
["CARD"],
|
||||
["Cardx"],
|
||||
["Ca rd"],
|
||||
[" "],
|
||||
[""]
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:A11"})).unwrap();
|
||||
|
||||
let assert_rows = |session: &Session| {
|
||||
let sh = session.doc().unwrap().wb.active().unwrap();
|
||||
for row in 1..=6 {
|
||||
assert!(!sh.is_row_hidden(row), "row {row} should be visible");
|
||||
}
|
||||
for row in 7..=10 {
|
||||
assert!(sh.is_row_hidden(row), "row {row} should be hidden");
|
||||
}
|
||||
};
|
||||
|
||||
for value in ["Card", " Card"] {
|
||||
let result = s.execute("data.filterBy", json!({"column": "A", "values": [value]})).unwrap();
|
||||
assert_eq!(result["hiddenRows"], json!(4), "{value:?}");
|
||||
assert_rows(&s);
|
||||
|
||||
let choices = filter_values(&s.doc().unwrap().wb, 0, 0);
|
||||
let card_entries: Vec<_> = choices.iter().filter(|(text, _)| text.trim().eq_ignore_ascii_case("Card")).collect();
|
||||
assert_eq!(card_entries.len(), 1, "{choices:?}");
|
||||
assert!(card_entries[0].1, "{choices:?}");
|
||||
assert!(!choices.iter().any(|(text, _)| text.trim().is_empty()), "{choices:?}");
|
||||
assert_eq!(choices.iter().filter(|(text, _)| text == "(Blanks)").count(), 1, "{choices:?}");
|
||||
assert!(choices.iter().any(|(text, on)| text == "(Blanks)" && !on), "{choices:?}");
|
||||
}
|
||||
|
||||
for value in ["Card", " Card"] {
|
||||
let result = s.execute("data.filterBy", json!({"column": "A", "custom": {"op": "=", "value": value}})).unwrap();
|
||||
assert_eq!(result["hiddenRows"], json!(4));
|
||||
assert_rows(&s);
|
||||
}
|
||||
}
|
||||
|
||||
fn finds(item: &str, typed: &str) -> bool {
|
||||
search_matches(&search_fold(item), &search_term(typed))
|
||||
|
||||
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"AutoFill",
|
||||
[],
|
||||
None,
|
||||
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday)",
|
||||
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years|linearTrend|growthTrend}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday; linearTrend, growthTrend = Linear Trend, Growth Trend: the targets continue the least-squares line or the exponential curve fitted to each row or column of source numbers, and the source keeps its values; an error when a source cell is not a number or holds a formula, or for growthTrend when a row or column mixes signs or holds zero)",
|
||||
has_doc,
|
||||
auto_fill
|
||||
),
|
||||
@@ -206,6 +206,7 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.selection = e.selection;
|
||||
// Step by step: a rename and a new sheet undone together match up only one step apart.
|
||||
super::extra::keep_view_modes(d, &cur_wb);
|
||||
super::view::keep_zoom(d, &cur_wb);
|
||||
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
@@ -227,6 +228,7 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
d.wb = e.wb;
|
||||
d.selection = e.selection;
|
||||
super::extra::keep_view_modes(d, &cur_wb);
|
||||
super::view::keep_zoom(d, &cur_wb);
|
||||
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
|
||||
}
|
||||
super::extra::keep_watch_list(&now, &mut d.wb);
|
||||
|
||||
@@ -8,14 +8,12 @@ use super::{
|
||||
/// Typing `=PY(` doesn't make a Python cell; this says what does.
|
||||
pub(crate) const PY_FORMULA: &str = "Python cells are made with the python.set command (the code as `code`), not by typing =PY(…).";
|
||||
|
||||
/// Whether typing `input` into a cell enters a formula: `=…`, or `+…`/`-…` followed by a name or
|
||||
/// a parenthesis (not a number), as Excel takes `+SUM(1)`.
|
||||
/// Whether typing `input` into a cell is meant as a formula: `=…`, or `+…`/`-…` when the entry
|
||||
/// isn't a number on its own, as Excel takes `+5+4` and `+SUM(1)` (see
|
||||
/// [`gridcraft_core::parse::starts_formula`]). A `+…`/`-…` entry that doesn't parse as a formula
|
||||
/// still enters as text (`--`), see [`input_to_cell`].
|
||||
pub(crate) fn is_formula_input(input: &str) -> bool {
|
||||
input.starts_with('=')
|
||||
|| (input.len() > 1
|
||||
&& (input.starts_with('+') || input.starts_with('-'))
|
||||
&& gridcraft_core::parse::parse_number_text(input).is_none()
|
||||
&& input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '('))
|
||||
gridcraft_core::parse::starts_formula(input)
|
||||
}
|
||||
|
||||
/// What typing `input` into a cell produces (constant or formula, plus an automatic number
|
||||
@@ -29,13 +27,21 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
|
||||
}
|
||||
let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@";
|
||||
if fmt_is_text {
|
||||
return Ok(Some(Cell { value: Value::text(input), formula: None, style, py: None }));
|
||||
return Ok(Some(Cell { value: gridcraft_core::cap_value(Value::text(input)), formula: None, style, py: None }));
|
||||
}
|
||||
let is_formula = is_formula_input(input);
|
||||
if is_formula && gridcraft_model::python::is_py_formula(input) {
|
||||
return Err(EngineError::Other(PY_FORMULA.into()));
|
||||
}
|
||||
if is_formula {
|
||||
// As in Excel, a `+` or `-` entry is a formula when it reads as one (`+5+4` enters `=+5+4`)
|
||||
// and text when it doesn't (`--`, `+49 170 1234567`); only `=` entries are refused.
|
||||
if is_formula
|
||||
&& !input.starts_with('=')
|
||||
&& let Ok(cell) = input_to_cell(&format!("={input}"), sheet, at, wb)
|
||||
{
|
||||
return Ok(cell);
|
||||
}
|
||||
if input.starts_with('=') {
|
||||
let body = input.strip_prefix('=').unwrap_or(input);
|
||||
let expr = wb.name_call_case(parse_typed_formula(body)?);
|
||||
check_arg_counts(&expr)?;
|
||||
@@ -65,6 +71,8 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri
|
||||
return Ok(Some(cell));
|
||||
}
|
||||
let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system);
|
||||
// Excel cuts typed text to 32,767 characters (after any leading apostrophe is dropped).
|
||||
parsed.value = gridcraft_core::cap_value(parsed.value);
|
||||
// Like Excel's automatic percent entry: a bare number of 1 or more typed into a cell already
|
||||
// formatted as a percentage is a percent (3 -> 3%); smaller numbers are taken as fractions.
|
||||
if parsed.format.is_none()
|
||||
@@ -143,24 +151,66 @@ pub(super) fn cell_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
// 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) };
|
||||
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
|
||||
// Excel forms no array from a constant: every cell of the selection takes the value.
|
||||
if cell.formula.is_none() && !range.is_single() {
|
||||
if range.count() > crate::fill::MAX_FILL_CELLS {
|
||||
return Err(EngineError::Other("That selection is too large to fill.".into()));
|
||||
}
|
||||
let mut by_style: std::collections::HashMap<StyleId, Option<Cell>> = std::collections::HashMap::new();
|
||||
for c in range.iter() {
|
||||
let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(c)).unwrap_or_default();
|
||||
let filled = match by_style.get(&style) {
|
||||
Some(filled) => filled.clone(),
|
||||
None => {
|
||||
let filled = input_to_cell(&input, sheet, c, &mut cx.wb)?;
|
||||
by_style.insert(style, filled.clone());
|
||||
filled
|
||||
}
|
||||
};
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
match filled {
|
||||
Some(f) => {
|
||||
sh.set_cell(c, f);
|
||||
crate::cmd::data::grow_autofilter(sh, c);
|
||||
}
|
||||
None => {
|
||||
sh.remove_cell(c);
|
||||
}
|
||||
}
|
||||
cx.touch(sheet, c);
|
||||
}
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// The array takes the whole range: other cells in it lose their contents.
|
||||
for c in range.iter().skip(1).take(1_000_000) {
|
||||
if let Some(old) = sh.cells.get(c).filter(|x| x.has_content()) {
|
||||
let style = old.style;
|
||||
sh.set_cell(c, Cell { style, ..Cell::default() });
|
||||
}
|
||||
// The array takes the whole range: other cells in it lose their contents. Walk the
|
||||
// cells the sheet holds rather than every address, so a whole-column array clears
|
||||
// all of its area, and mark each cleared cell so formulas reading it recalculate.
|
||||
let cleared: Vec<(CellRef, StyleId)> =
|
||||
sh.cells.iter_range(range).filter(|(c, x)| *c != range.start && x.has_content()).map(|(c, x)| (c, x.style)).collect();
|
||||
for &(c, style) in &cleared {
|
||||
sh.set_cell(c, Cell { style, ..Cell::default() });
|
||||
}
|
||||
sh.set_cell(range.start, cell);
|
||||
cx.touch(sheet, range.start);
|
||||
// The array's results land in every cell of the range, stored or not, so readers of
|
||||
// an empty result cell need the touch too. A huge range marks only the cells it held.
|
||||
if range.count() <= 1_000_000 {
|
||||
for c in range.iter() {
|
||||
cx.touch(sheet, c);
|
||||
}
|
||||
} else {
|
||||
for (c, _) in cleared {
|
||||
cx.touch(sheet, c);
|
||||
}
|
||||
}
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
let cell = input_to_cell(&input, sheet, at, &mut cx.wb)?;
|
||||
@@ -269,7 +319,7 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if text.contains('\n') && !cx.wb.styles.get(style).align.wrap {
|
||||
style = cx.wb.styles.derive(style, |s| s.align.wrap = true);
|
||||
}
|
||||
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style, py: None })
|
||||
Some(Cell { value: gridcraft_core::cap_value(Value::Text(text.as_str().into())), formula: None, style, py: None })
|
||||
}
|
||||
}
|
||||
_ => input_to_cell(&input, sheet, at, &mut cx.wb)?,
|
||||
|
||||
@@ -52,6 +52,8 @@ pub(super) fn auto_fill(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"weekdays" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Weekday),
|
||||
"months" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Month),
|
||||
"years" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Year),
|
||||
"linearTrend" => crate::fill::FillMode::LinearTrend,
|
||||
"growthTrend" => crate::fill::FillMode::GrowthTrend,
|
||||
_ => crate::fill::FillMode::Series,
|
||||
};
|
||||
if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS {
|
||||
|
||||
@@ -76,7 +76,34 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(EngineError::Other("Too many cells to paste as links at once.".into()));
|
||||
}
|
||||
let same_doc = s.doc()?.uid == clip.doc_uid;
|
||||
let cut_move = clip.cut && same_doc && what == What::All;
|
||||
// A cut in this workbook moves its cells: the source is emptied before the destination is
|
||||
// written. As in Excel, it moves only as a plain Paste onto one cell or an area of its own size
|
||||
// and shape. Every other way (a Paste Special option, tiling over a larger or differently shaped
|
||||
// area, a row the filter hides) would write the cut cells somewhere other than one place, or not
|
||||
// at all, after their source was gone, so it is refused here, before anything changes, and the
|
||||
// cut stays pending.
|
||||
let cut_move = clip.cut && same_doc;
|
||||
if cut_move {
|
||||
let plain = what == What::All && !link && !skip_blanks && !transpose && op == "none";
|
||||
if !plain {
|
||||
return Err(EngineError::Other("Cut cells can only be pasted with Paste. To use Paste Special, copy them instead.".into()));
|
||||
}
|
||||
let anchored = cell_param_on(s, p, "at", dest_sheet)?.is_some() || sel.is_single();
|
||||
if !anchored && (sel.height() != h || sel.width() != w) {
|
||||
return Err(EngineError::Other(
|
||||
"The cut cells and the paste area aren't the same size and shape: select one cell, or an area the size of the cut cells.".into(),
|
||||
));
|
||||
}
|
||||
// The rows the cut itself would land on, whatever the paste would skip: an anchored or
|
||||
// taller block is pasted straight down, so `skip_rows` (which only a tiled single row uses)
|
||||
// can't tell whether it would write into a hidden row.
|
||||
if let Some(end) = at.offset(i64::from(h) - 1, i64::from(w) - 1) {
|
||||
let dest = RangeRef::new(at, end);
|
||||
if s.doc()?.wb.sheet(dest_sheet).is_some_and(|sh| !super::filtered_rows(sh, dest).is_empty()) {
|
||||
return Err(EngineError::Other("The cut area can't be pasted into rows the filter hides.".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let src_wb = clip.wb.clone();
|
||||
let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) };
|
||||
// The source sheet's name now: a cut whose sheet was renamed after it moves its cells,
|
||||
@@ -208,7 +235,12 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
moved.dynamic = f.dynamic;
|
||||
return Some(std::sync::Arc::new(moved));
|
||||
}
|
||||
let moved = gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64);
|
||||
let moved = if transpose {
|
||||
// A transposed paste turns the references instead of shifting them (#2450).
|
||||
gridcraft_formula::adjust::transpose_relative(e, sc, dest)
|
||||
} else {
|
||||
gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64)
|
||||
};
|
||||
Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) }))
|
||||
};
|
||||
let moved_py = |cell: &Cell| -> Result<Option<std::sync::Arc<gridcraft_model::PyCode>>> {
|
||||
@@ -389,6 +421,11 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let (Some(a), Some(b)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) {
|
||||
let nm = RangeRef::new(a, b);
|
||||
let sh = cx.sheet_mut(dest_sheet)?;
|
||||
// A table can't hold merged cells (Excel removes the table on open): the
|
||||
// cells are pasted there unmerged.
|
||||
if sh.tables.iter().any(|t| t.range.intersects(&nm)) {
|
||||
continue;
|
||||
}
|
||||
sh.merges.retain(|x| !x.intersects(&nm));
|
||||
sh.merges.push(nm);
|
||||
}
|
||||
|
||||
@@ -52,6 +52,13 @@ impl crate::DocState {
|
||||
// View state: set in place, so the workbook is neither copied nor made dirty.
|
||||
self.wb.set_active_sheet(i);
|
||||
self.selection = self.sheet_selections.get(i).cloned().unwrap_or_default();
|
||||
// A sheet's first visit starts at A1, which may be part of a merged cell: take it whole,
|
||||
// as a click would (#1348). A selection the sheet remembers comes back as it was.
|
||||
if self.selection == crate::Selection::default()
|
||||
&& let Some(sh) = self.wb.sheet(i)
|
||||
{
|
||||
self.selection.expand_merges(sh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -148,6 +148,27 @@ fn go_to_keeps_the_references_entered_newest_first() {
|
||||
assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_set_cuts_text_to_32767_characters() {
|
||||
// Excel cuts a 40,000-character entry to 32,767; a formula is left alone.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap();
|
||||
// An apostrophe prefix isn't text, and a text-formatted cell takes `=` as text.
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": format!("'{}", "x".repeat(40_000))})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "C1", "code": "@"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C1", "input": format!("={}", "x".repeat(40_000))})).unwrap();
|
||||
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone();
|
||||
for at in ["B1", "C1"] {
|
||||
assert_eq!(get(&mut s, at).as_str().map(|t| t.chars().count()), Some(32_767), "{at}");
|
||||
}
|
||||
assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767));
|
||||
assert_eq!(get(&mut s, "A2"), json!(32767.0));
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "😀".repeat(16_384)})).unwrap();
|
||||
assert_eq!(get(&mut s, "D1").as_str().map(|t| t.encode_utf16().count()), Some(32_766));
|
||||
}
|
||||
|
||||
#[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.
|
||||
@@ -208,6 +229,15 @@ fn set_values_can_store_strings_as_the_text_they_are() {
|
||||
assert!(s.execute("range.setValues", json!({"range": "A8", "parse": 0, "values": [["x"]]})).is_err());
|
||||
// A line break still turns on Wrap Text.
|
||||
s.execute("range.setValues", json!({"range": "A9", "parse": false, "values": [["one\ntwo"]]})).unwrap();
|
||||
// Text stored as given still stops at Excel's 32,767-character cell limit.
|
||||
let long = "x".repeat(40_000);
|
||||
s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap();
|
||||
let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count()));
|
||||
assert_eq!(len.flatten(), Some(32_767));
|
||||
s.execute("range.setValues", json!({"range": "B10", "parse": false, "values": [["😀".repeat(16_384)]]})).unwrap();
|
||||
let emoji_len =
|
||||
s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("B10").unwrap()).map(|c| c.value.as_text().map(|t| t.encode_utf16().count()));
|
||||
assert_eq!(emoji_len.flatten(), Some(32_766));
|
||||
assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo"));
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
@@ -314,6 +344,137 @@ fn an_array_entered_outside_the_selection_covers_only_its_cell() {
|
||||
assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep"));
|
||||
}
|
||||
|
||||
/// The value a full recalculation from scratch gives `a1` on the active sheet.
|
||||
fn fully_recalculated(s: &Session, a1: &str) -> Value {
|
||||
let mut fresh = (*s.doc().unwrap().wb).clone();
|
||||
gridcraft_calc::Calc::new().recalc_all(&mut fresh);
|
||||
fresh.active().unwrap().value(CellRef::parse(a1).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_entering_a_constant_recalculates_readers_of_the_cells_it_fills() {
|
||||
// Found by the command-sequence fuzzer (seeds 4, 1213): only the array's first cell was
|
||||
// marked changed, so formulas reading the cells it cleared kept their old values.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[5, 6, "=B1+1"]]})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "7", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
// Excel fills both cells with the constant and forms no array.
|
||||
for a in ["A1", "B1"] {
|
||||
let c = sh.cell(CellRef::parse(a).unwrap()).unwrap();
|
||||
assert_eq!(c.value, Value::number(7.0));
|
||||
assert!(c.formula.is_none());
|
||||
}
|
||||
assert_eq!(sh.value(CellRef::parse("C1").unwrap()), Value::number(8.0));
|
||||
|
||||
// The fuzzer's minimal repro on the budget sample.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": "budget"})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "C5", "range": "C5:D5"})).unwrap();
|
||||
s.execute("cell.set", json!({"array": true, "cell": "C5", "input": "7"})).unwrap();
|
||||
let in_memory = s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D15").unwrap());
|
||||
assert_eq!(in_memory, fully_recalculated(&s, "D15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_entering_a_constant_grows_an_autofilter_below_it() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1:B3", "values": [["Name", "Qty"], ["a", 1], ["b", 2]]})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B3"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A4:A5"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A4", "input": "new", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.autofilter.as_ref().map(|f| f.range.a1()), Some("A1:B5".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_entering_a_formula_fills_every_cell_as_an_array() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "5"})).unwrap();
|
||||
for (input, want) in [("=1", 1.0), ("=A2", 5.0)] {
|
||||
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": input, "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
for a in ["A1", "B1"] {
|
||||
assert_eq!(sh.value(CellRef::parse(a).unwrap()), Value::number(want), "{input} {a}");
|
||||
}
|
||||
let f = sh.cell(CellRef::parse("A1").unwrap()).and_then(|c| c.formula.clone()).unwrap();
|
||||
assert_eq!(f.array, Some(RangeRef::parse("A1:B1").unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readers_of_an_empty_array_result_cell_see_its_result() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=B1+1"})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "=5", "array": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D1").unwrap()), Value::number(6.0));
|
||||
assert_eq!(fully_recalculated(&s, "D1"), Value::number(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_column_constant_fills_its_whole_area() {
|
||||
// The loop stopped after a million addresses, so cells further down the column kept
|
||||
// their old content (and their readers weren't recalculated).
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
|
||||
s.execute("selection.set", json!({"active": "D1", "range": "D:D"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "1", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::number(1.0));
|
||||
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(2.0));
|
||||
assert_eq!(fully_recalculated(&s, "F1"), Value::number(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_more_than_a_million_cells_recalculates_readers_of_all_of_them() {
|
||||
// Clear marked only the first million addresses of the range as changed, so formulas
|
||||
// reading a cleared cell further down kept its old value.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
|
||||
s.execute("edit.clearContents", json!({"range": "D:D"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::Empty);
|
||||
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_spill_recalculates_readers_of_its_spilled_cells() {
|
||||
// Clear marks only the cells the sheet holds; a spill's other cells go with its anchor.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(5)"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C1", "input": "=A3+1"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(4.0));
|
||||
s.execute("edit.clearContents", json!({"range": "A1:A5"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(1.0));
|
||||
assert_eq!(fully_recalculated(&s, "C1"), Value::number(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readers_of_an_array_formulas_cells_see_its_results() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "B2", "values": [[1], [2]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C3", "input": "100"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E1", "input": "=C3+C4+1"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "C2:C4"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C2", "input": "=B2:B3*2", "array": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.value(CellRef::parse("E1").unwrap()), fully_recalculated(&s, "E1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcards() {
|
||||
assert!(wildcard("hello", "h*o"));
|
||||
@@ -475,6 +636,39 @@ fn cut_paste_that_overflows_the_grid_moves_nothing() {
|
||||
assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transposed_paste_turns_the_formula_with_the_cell_that_carries_it() {
|
||||
// #2450: the values moved but the formula kept the offset it had in the source column,
|
||||
// so it read the cell above instead of the cell to its left.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A3", "input": "2025-10-31"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A4", "input": "=A3+1"})).unwrap();
|
||||
s.execute("edit.copy", json!({"range": "A3:A4"})).unwrap();
|
||||
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C3"})).unwrap();
|
||||
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
|
||||
let date = get(&mut s, "C3")["value"].as_f64().expect("the date pastes as its serial");
|
||||
assert_eq!(date, get(&mut s, "A3")["value"].as_f64().unwrap());
|
||||
assert_eq!(get(&mut s, "D3")["formula"], "=C3+1", "the formula reads the cell to its left, as Excel's does");
|
||||
assert_eq!(get(&mut s, "D3")["value"].as_f64().unwrap(), date + 1.0, "and shows the day after it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transposed_paste_turns_every_kind_of_reference_the_way_excel_does() {
|
||||
// Observed from Excel 16: relative parts turn a quarter turn, a reference pinned with $
|
||||
// is left standing, and a whole column comes back as a range open to the sheet's edge.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["=B1+1"], ["=$B$1"], ["=SUM(B1:C3)"], ["=SUM(B:D)"]]})).unwrap();
|
||||
s.execute("edit.copy", json!({"range": "A1:A4"})).unwrap();
|
||||
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C10"})).unwrap();
|
||||
let formula = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["formula"].clone();
|
||||
assert_eq!(formula(&mut s, "C10"), "=C11+1");
|
||||
assert_eq!(formula(&mut s, "D10"), "=$B$1");
|
||||
assert_eq!(formula(&mut s, "E10"), "=SUM(C11:E12)");
|
||||
assert_eq!(formula(&mut s, "F10"), "=SUM($C11:$XFD13)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drag_and_drop_asks_before_replacing_data() {
|
||||
// #3136: dragging column B's border onto column A replaced A without asking.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range};
|
||||
use gridcraft_model::Cell;
|
||||
|
||||
pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?;
|
||||
@@ -11,30 +12,85 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
.ok_or_else(|| bad("table.resize", "select a cell in a table"))?;
|
||||
edit(s, |cx| {
|
||||
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();
|
||||
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap another table.".into()));
|
||||
}
|
||||
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
|
||||
let wb = &cx.wb;
|
||||
let sheet = wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
let t = sheet.tables.get(ti).ok_or_else(|| bad("table", "gone"))?;
|
||||
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(),
|
||||
));
|
||||
}
|
||||
let mut cols = Vec::new();
|
||||
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,
|
||||
unique_name: None,
|
||||
xml: None,
|
||||
}));
|
||||
// Like Excel, the new range can't take in another table, a merged area, a PivotTable or a
|
||||
// multi-cell array formula (a spill is fine: it shows #SPILL! inside the table).
|
||||
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap another table.".into()));
|
||||
}
|
||||
if sheet.merges.iter().any(|m| m.intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap merged cells.".into()));
|
||||
}
|
||||
if sheet.pivots.iter().any(|pt| pt.last_range.unwrap_or_else(|| RangeRef::new(pt.anchor, pt.anchor)).intersects(&r)) {
|
||||
return Err(EngineError::Other("A table can't overlap a PivotTable report.".into()));
|
||||
}
|
||||
if sheet.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r))) {
|
||||
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
|
||||
}
|
||||
// Header text per new column (`None`: empty). Without a header row, a column that stays
|
||||
// keeps its name.
|
||||
let texts: Vec<Option<String>> = (r.start.col..=r.end.col)
|
||||
.map(|c| {
|
||||
if !t.header_row {
|
||||
return c.checked_sub(t.range.start.col).and_then(|i| t.columns.get(i as usize)).map(|x| x.name.clone());
|
||||
}
|
||||
let at = CellRef::new(r.start.row, c);
|
||||
let v = sheet.value(at);
|
||||
let text = match v.as_text() {
|
||||
Some(x) => x.to_string(),
|
||||
None => crate::display::value_text(wb, sheet, at),
|
||||
};
|
||||
(!text.trim().is_empty()).then_some(text)
|
||||
})
|
||||
.collect();
|
||||
let names = resized_column_names(&texts);
|
||||
let old = t.range;
|
||||
let old_cols = t.columns.clone();
|
||||
let header_row = t.header_row;
|
||||
let mut cols = Vec::with_capacity(names.len());
|
||||
for (c, name) in (r.start.col..=r.end.col).zip(&names) {
|
||||
// A column that stays keeps its settings (totals, calculated formula): with a header
|
||||
// row it's found by name, without one by position.
|
||||
let existing = if header_row {
|
||||
// A header that was normalized into a generated name keeps the settings of the
|
||||
// column at its address, not of whichever column already has that name.
|
||||
let raw = texts.get((c - r.start.col) as usize).and_then(|x| x.as_deref());
|
||||
if c >= old.start.col && c <= old.end.col && raw != Some(name.as_str()) {
|
||||
old_cols.get((c - old.start.col) as usize)
|
||||
} else {
|
||||
old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
} else if c >= old.start.col && c <= old.end.col {
|
||||
old_cols.get((c - old.start.col) as usize)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
cols.push(match existing {
|
||||
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
|
||||
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
|
||||
});
|
||||
}
|
||||
let sheet = cx.sheet_mut(si)?;
|
||||
if header_row {
|
||||
// Headers hold constant text: a generated or de-duplicated name is written into its
|
||||
// cell, so the header row and the column names never disagree.
|
||||
for (c, col) in (r.start.col..=r.end.col).zip(&cols) {
|
||||
let at = CellRef::new(r.start.row, c);
|
||||
let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none());
|
||||
if !constant_text {
|
||||
let style = sheet.style_id(at);
|
||||
sheet.set_cell(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
|
||||
t.columns = cols;
|
||||
t.range = r;
|
||||
cx.structural = true;
|
||||
@@ -42,6 +98,56 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Unique column names for a resized table, from each column's header text (`None` = empty), the
|
||||
/// way Excel names them: a repeated header gets the lowest free suffix (`Qty`, `Qty2`, `Qty3`,
|
||||
/// compared without case), and an empty header continues a `ColumnN` neighbour on its left
|
||||
/// (`Column3` → `Column4`, or `Column32` when `Column4` is taken) or else takes the lowest free
|
||||
/// `ColumnN`.
|
||||
fn resized_column_names(texts: &[Option<String>]) -> Vec<String> {
|
||||
use std::collections::{HashMap, HashSet};
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
let mut next_suffix: HashMap<String, u64> = HashMap::new();
|
||||
// The lowest `ColumnN` not yet tried, so many empty headers stay linear.
|
||||
let mut lowest = 1u64;
|
||||
let mut names: Vec<String> = Vec::with_capacity(texts.len());
|
||||
let dedupe = |base: &str, taken: &HashSet<String>, next_suffix: &mut HashMap<String, u64>| {
|
||||
let k = next_suffix.entry(base.to_lowercase()).or_insert(2);
|
||||
let mut n = base.to_string();
|
||||
while taken.contains(&n.to_lowercase()) {
|
||||
n = format!("{base}{k}");
|
||||
*k = k.saturating_add(1);
|
||||
}
|
||||
n
|
||||
};
|
||||
for text in texts {
|
||||
let name = match text {
|
||||
Some(t) => dedupe(t, &taken, &mut next_suffix),
|
||||
None => {
|
||||
let left = names.last().and_then(|l| {
|
||||
l.strip_prefix("Column")
|
||||
.filter(|d| !d.starts_with('0') && !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|d| d.parse::<u64>().ok())
|
||||
});
|
||||
match left {
|
||||
Some(n) => {
|
||||
let cand = format!("Column{}", n.saturating_add(1));
|
||||
if taken.contains(&cand.to_lowercase()) { dedupe(&format!("Column{n}"), &taken, &mut next_suffix) } else { cand }
|
||||
}
|
||||
None => {
|
||||
while taken.contains(&format!("column{lowest}")) {
|
||||
lowest = lowest.saturating_add(1);
|
||||
}
|
||||
format!("Column{lowest}")
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
taken.insert(name.to_lowercase());
|
||||
names.push(name);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Most cells (rows × columns, blanks included) Get Data imports. The rows are built densely
|
||||
/// before they are written, so a few sparse records or one far-away CSV cell must not expand
|
||||
/// into a rectangle of billions of slots.
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param};
|
||||
use crate::DocState;
|
||||
use crate::{DocState, EngineError};
|
||||
|
||||
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}, plus {password} for a password-protected workbook and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open),
|
||||
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook, {modifyPassword} for one with a password to modify (or {readOnly: true} to open it without; Save then asks for a new file), and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (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),
|
||||
@@ -59,6 +59,19 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted;
|
||||
let (mut wb, warnings) = crate::io::open_bytes_with(&name, &bytes, str_param(p, "password"), bool_param(p, "csvAsText").unwrap_or(false))?;
|
||||
// A password to modify: the right one or a read-only open, or the workbook doesn't open.
|
||||
let mut read_only = false;
|
||||
if let Some(hash) = wb.write_reservation.as_ref().and_then(|r| r.password.as_ref()) {
|
||||
read_only = bool_param(p, "readOnly").unwrap_or(false);
|
||||
match str_param(p, "modifyPassword") {
|
||||
_ if read_only => {}
|
||||
None => return Err(EngineError::Other(format!("'{name}' {}", crate::io::MODIFY_PASSWORD_REQUIRED))),
|
||||
Some(pw) if !hash.verify(pw).map_err(|e| bad("file.open", e))? => {
|
||||
return Err(EngineError::Other(crate::io::WRONG_PASSWORD.into()));
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
wb.source_dir = str_param(p, "path").and_then(crate::io::source_dir);
|
||||
// What `CELL("filename")` reports (#1489). A workbook opened from bytes knows its name but
|
||||
// never a folder, so it reports `[name]Sheet` with none; an import reports the file it came
|
||||
@@ -78,7 +91,7 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
// 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);
|
||||
let path = str_param(p, "path").filter(|_| !imported && !encrypted && !read_only).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()))
|
||||
@@ -87,6 +100,9 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
// Someone else may have made the file: its active content asks before it runs.
|
||||
let mut doc = DocState::new(wb, path, title, crate::Trust::FromFile);
|
||||
if read_only {
|
||||
doc.read_only_source = str_param(p, "path").map(str::to_string);
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -106,6 +122,14 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether two paths name one file, whatever their spelling (`./book.xlsx`, a symlink).
|
||||
fn same_file(a: &str, b: &str) -> bool {
|
||||
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
|
||||
(Ok(x), Ok(y)) => x == y,
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let path = match str_param(p, "path").map(str::to_string).or_else(|| s.active().and_then(|d| d.path.clone())) {
|
||||
Some(p) => p,
|
||||
@@ -114,6 +138,9 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return ok();
|
||||
}
|
||||
};
|
||||
if s.active().and_then(|d| d.read_only_source.as_deref()).is_some_and(|src| same_file(src, &path)) {
|
||||
return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file."));
|
||||
}
|
||||
// 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(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
|
||||
|
||||
@@ -439,6 +439,8 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
})
|
||||
.collect();
|
||||
sheet.charts.push(Chart {
|
||||
|
||||
@@ -553,7 +553,12 @@ fn format_cells(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
{
|
||||
*st = new;
|
||||
}
|
||||
})
|
||||
})?;
|
||||
// A number format set here widens columns as the ribbon's do (observed: Excel 16.0).
|
||||
if patch.get("num_fmt").is_some() {
|
||||
widen_for_numbers(s, p)?;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The style patch with camelCase keys (`numFmt`, `diagDown`, as documented) renamed to the
|
||||
@@ -637,6 +642,11 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let how =
|
||||
if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how };
|
||||
// Excel has no merged cells in a table (a file with one loses the table when Excel opens it):
|
||||
// merging there is refused, unmerging is still allowed.
|
||||
if how != "unmerge" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| ranges.iter().any(|r| t.range.intersects(r)))) {
|
||||
return Err(EngineError::Other("You can't merge cells in a table.".into()));
|
||||
}
|
||||
edit(s, |cx| {
|
||||
let mut touched = Vec::new();
|
||||
// Areas whose merging changes: a merged cell blocks a dynamic array's spill.
|
||||
@@ -732,9 +742,95 @@ fn number_format(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
set_fmt(s, p, &code)
|
||||
}
|
||||
|
||||
/// How many stored cells [`widen_for_numbers`] looks at in one command.
|
||||
const MAX_WIDEN_CELLS: usize = 1_000_000;
|
||||
|
||||
fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result<Json> {
|
||||
let nf = NumFmt::new(code);
|
||||
apply_style(s, p, |st| st.num_fmt = nf.clone())
|
||||
apply_style(s, p, |st| st.num_fmt = nf.clone())?;
|
||||
widen_for_numbers(s, p)
|
||||
}
|
||||
|
||||
/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…) or
|
||||
/// Format Cells, a column nobody sized by hand widens so the formatted numbers in the target fit,
|
||||
/// instead of showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or
|
||||
/// widened this way before widens to the widest number in the range, also with Wrap Text and a large
|
||||
/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden
|
||||
/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen,
|
||||
/// and columns never narrow.
|
||||
fn widen_for_numbers(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let measure = s.text_width.clone();
|
||||
edit(s, |cx| {
|
||||
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) };
|
||||
let Some(used) = sh.used_range() else { return Ok(Json::Null) };
|
||||
if sh.show_formulas {
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
let targets: Vec<RangeRef> = ranges.iter().filter_map(|r| r.intersection(&used)).collect();
|
||||
// Merged areas over the targets as sorted row intervals per column, so each cell is checked
|
||||
// with a binary search rather than a scan of every merge.
|
||||
let mut merged: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
|
||||
for m in sh.merges.iter().filter(|m| !m.is_single()) {
|
||||
for x in targets.iter().filter_map(|r| m.intersection(r)) {
|
||||
for col in x.start.col..=x.end.col {
|
||||
merged.entry(col).or_default().push((m.start.row, m.end.row));
|
||||
}
|
||||
}
|
||||
}
|
||||
for v in merged.values_mut() {
|
||||
v.sort_unstable();
|
||||
v.dedup();
|
||||
}
|
||||
let in_merge = |c: CellRef| {
|
||||
merged.get(&c.col).is_some_and(|v| {
|
||||
let i = v.partition_point(|&(r0, _)| r0 <= c.row);
|
||||
i > 0 && v.get(i - 1).is_some_and(|&(_, r1)| c.row <= r1)
|
||||
})
|
||||
};
|
||||
let mut need: std::collections::BTreeMap<u32, f32> = std::collections::BTreeMap::new();
|
||||
// Measured as AutoFit Column Width measures (the UI's font when it supplies one).
|
||||
let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default();
|
||||
// The stored cells looked at are capped, not the area: a sparse target as tall as the sheet
|
||||
// still widens for the numbers it holds. Spilled values count as the grid shows them.
|
||||
let mut budget = MAX_WIDEN_CELLS;
|
||||
for r in &targets {
|
||||
let spilled = sh.spill.range(r.start..=r.end).map(|(c, _)| *c).filter(|c| r.contains(*c));
|
||||
for c in sh.cells.iter_range(*r).map(|(c, _)| c).chain(spilled) {
|
||||
if budget == 0 {
|
||||
break;
|
||||
}
|
||||
budget -= 1;
|
||||
if !matches!(sh.value_ref(c), Some(gridcraft_core::Value::Number(_)))
|
||||
|| sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden)
|
||||
|| in_merge(c)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let id = sh.style_id(c);
|
||||
let st = cx.wb.styles.get(id);
|
||||
if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill {
|
||||
continue;
|
||||
}
|
||||
let text = crate::display::cell_text(&cx.wb, sh, c);
|
||||
let exact = measured.len() < EXACT_TEXT_WIDTHS;
|
||||
let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure {
|
||||
Some(m) => m(t, &st.font, exact),
|
||||
None => approx_text_width(t, st.font.size, st.font.bold),
|
||||
});
|
||||
let w = w + 6.0 + st.align.indent as f32 * 9.0;
|
||||
let e = need.entry(c.col).or_insert(0.0);
|
||||
*e = e.max(w);
|
||||
}
|
||||
}
|
||||
let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect();
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
for (c, w) in widen {
|
||||
sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0));
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds or removes one decimal place in the number format (Increase/Decrease Decimal).
|
||||
@@ -819,8 +915,8 @@ mod sizes;
|
||||
|
||||
use cell_styles::cell_style;
|
||||
pub use cell_styles::{CELL_STYLE_NAMES, builtin_cell_style};
|
||||
use sizes::{EXACT_TEXT_WIDTHS, autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
|
||||
pub use sizes::{approx_text_width, chars_to_points};
|
||||
use sizes::{autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -856,6 +952,112 @@ mod tests {
|
||||
assert_eq!(adjust_decimals("0%", &v, 1), "0.0%");
|
||||
}
|
||||
|
||||
fn col(s: &crate::Session, c: u32) -> (f32, bool) {
|
||||
let sh = s.active().unwrap().wb.active().unwrap();
|
||||
(sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom))
|
||||
}
|
||||
|
||||
/// #1077: Increase Decimal widened the format but not the column, so the number turned into ####.
|
||||
#[test]
|
||||
fn increase_decimal_widens_a_column_nobody_sized() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap();
|
||||
let (default, _) = col(&s, 0);
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
let (w, custom) = col(&s, 0);
|
||||
let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert_eq!(text, "3.141592650");
|
||||
assert!(w > default, "the column widens for {text}: {w} vs {default}");
|
||||
assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it");
|
||||
assert!(!custom, "it isn't a width set by hand, so it can widen again");
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
assert!(col(&s, 0).0 > w, "one more decimal, a little wider again");
|
||||
let wide = col(&s, 0).0;
|
||||
s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap();
|
||||
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap();
|
||||
assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand");
|
||||
s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap();
|
||||
for a in ["A1", "B1", "D1"] {
|
||||
s.execute("home.comma", json!({"range": a})).unwrap();
|
||||
}
|
||||
s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap();
|
||||
let (default, _) = col(&s, 4);
|
||||
assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel");
|
||||
assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89");
|
||||
assert_eq!(col(&s, 2).0, default, "General rounds to fit instead");
|
||||
assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden");
|
||||
// AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening.
|
||||
s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap();
|
||||
assert!(!col(&s, 0).1);
|
||||
s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
|
||||
let fitted = col(&s, 0).0;
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
|
||||
assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again");
|
||||
}
|
||||
|
||||
fn book() -> (crate::Session, f32) {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
let (default, _) = col(&s, 0);
|
||||
(s, default)
|
||||
}
|
||||
|
||||
/// Whole columns as tall as the sheet with two numbers: the cells are looked at, not the area.
|
||||
#[test]
|
||||
fn a_sparse_target_widens_for_the_numbers_it_holds() {
|
||||
let (mut s, default) = book();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E1000000", "input": "1234567.891"})).unwrap();
|
||||
s.execute("home.comma", json!({"range": "A:E"})).unwrap();
|
||||
assert!(col(&s, 4).0 > default, "E widens for 1,234,567.89 a million rows down");
|
||||
}
|
||||
|
||||
/// A spilled number counts as the grid shows it: G1's formula spills 1,234,567.891 into H1.
|
||||
#[test]
|
||||
fn a_spilled_number_widens_its_column() {
|
||||
let (mut s, default) = book();
|
||||
s.execute("cell.set", json!({"cell": "G1", "input": "=SEQUENCE(1,2,1,1234566.891)"})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "H1", "code": "#,##0.000"})).unwrap();
|
||||
assert!(col(&s, 7).0 > default, "H widens for the value it shows");
|
||||
}
|
||||
|
||||
/// A merged area keeps its columns; the cell beside it widens.
|
||||
#[test]
|
||||
fn a_merged_area_keeps_its_columns() {
|
||||
let (mut s, default) = book();
|
||||
s.execute("range.setValues", json!({"range": "J1", "values": [[1234567.891, null, 1234567.891]]})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "J1:K1"})).unwrap();
|
||||
s.execute("home.comma", json!({"range": "J1:L1"})).unwrap();
|
||||
assert_eq!((col(&s, 9).0, col(&s, 10).0), (default, default), "the merged J1:K1 doesn't widen J or K");
|
||||
assert!(col(&s, 11).0 > default, "L does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_cells_widens_for_a_number_format_only() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891]]})).unwrap();
|
||||
let (default, _) = col(&s, 0);
|
||||
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"bold": true}}})).unwrap();
|
||||
assert_eq!(col(&s, 1).0, default, "no number format, no widening");
|
||||
s.execute("home.formatCells", json!({"range": "A1", "style": {"numFmt": "#,##0.000000"}})).unwrap();
|
||||
assert!(col(&s, 0).0 > default, "A widens for 1,234,567.891000, as Excel's Format Cells does");
|
||||
assert!(!col(&s, 0).1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_cells_takes_the_documented_keys() {
|
||||
let mut s = crate::Session::new();
|
||||
@@ -870,6 +1072,47 @@ mod tests {
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00");
|
||||
}
|
||||
|
||||
/// A table draws its header row bold; AutoFit measures that, not the cell's own plain font.
|
||||
#[test]
|
||||
fn autofit_measures_a_table_header_in_the_table_style_font() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
let heading = "Quarterly Revenue by Region";
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[heading, heading], [1, 1]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:A2", "header": true})).unwrap();
|
||||
s.execute("home.autofitColumnWidth", json!({"cols": "A:B"})).unwrap();
|
||||
let sh = s.active().unwrap().wb.active().unwrap();
|
||||
let (table, plain) = (sh.col_width(0) - sh.filter_button_space(CellRef::new(0, 0)), sh.col_width(1));
|
||||
assert!(table > plain, "the bold table header is wider than the same plain text: {table} vs {plain}");
|
||||
}
|
||||
|
||||
/// Outlined letters have no Font-group command; Format Cells' style JSON sets and clears them.
|
||||
#[test]
|
||||
fn format_cells_sets_outlined_letters() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": true}}})).unwrap();
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], true);
|
||||
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": false}}})).unwrap();
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], false);
|
||||
}
|
||||
|
||||
/// The Format Cells dialog sends the active cell's whole style to every selected cell, so a
|
||||
/// non-outlined active cell must clear outline on the others, as it does bold.
|
||||
#[test]
|
||||
fn format_cells_whole_style_clears_outline_on_the_selection() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "plain"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": "hollow"})).unwrap();
|
||||
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"outline": true, "bold": true}}})).unwrap();
|
||||
let style = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"].clone();
|
||||
s.execute("home.formatCells", json!({"range": "A1:B1", "style": style})).unwrap();
|
||||
let font = s.execute("cell.get", json!({"cell": "B1"})).unwrap()["style"]["font"].clone();
|
||||
assert_eq!((font["bold"].clone(), font["outline"].clone()), (json!(false), json!(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arabic_vowel_and_direction_marks_add_no_width() {
|
||||
let plain = approx_text_width("محمد يدرس في المدرسة", 11.0, false);
|
||||
|
||||
@@ -107,6 +107,7 @@ pub(super) fn col_width(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let e = sh.cols.entry(c).or_default();
|
||||
e.size = Some(w as f32);
|
||||
e.hidden = w == 0.0;
|
||||
e.custom = true;
|
||||
}
|
||||
}
|
||||
Ok(Json::Null)
|
||||
@@ -187,14 +188,15 @@ fn arabic_em(c: char) -> Option<f32> {
|
||||
|
||||
/// Distinct texts AutoFit measures exactly; past this many, `Session::text_width` is asked for a
|
||||
/// quick measure so a huge column doesn't lay out every value.
|
||||
const EXACT_TEXT_WIDTHS: usize = 2_000;
|
||||
pub(super) const EXACT_TEXT_WIDTHS: usize = 2_000;
|
||||
|
||||
pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, lines) = line_targets(s, p, false)?;
|
||||
let measure = s.text_width.clone();
|
||||
edit(s, |cx| {
|
||||
let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) };
|
||||
let mut measured: std::collections::HashMap<StyleId, std::collections::HashMap<String, f32>> = Default::default();
|
||||
// Keyed by style and boldness: a table's style can make a cell bold (its header row).
|
||||
let mut measured: std::collections::HashMap<(StyleId, bool), std::collections::HashMap<String, f32>> = Default::default();
|
||||
let mut distinct = 0usize;
|
||||
// Selected columns, then one pass over the populated cells (the store is row-oriented, so a
|
||||
// scan per column would revisit every row for each selected column, empty or not).
|
||||
@@ -228,22 +230,26 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
let id = sh.style_id(cell);
|
||||
let st = cx.wb.styles.get(id);
|
||||
// The font as the grid draws the cell: in a table, the table style's (a bold
|
||||
// header row), not only the cell's own.
|
||||
let table_font = sh.table_at(cell).map(|t| crate::tables::table_cell_style(&cx.wb, si, t, cell).font);
|
||||
let font = table_font.as_ref().unwrap_or(&st.font);
|
||||
let text = crate::display::cell_text(&cx.wb, sh, cell);
|
||||
for line in text.lines() {
|
||||
let w = match &measure {
|
||||
Some(m) => {
|
||||
let known = measured.entry(id).or_default();
|
||||
let known = measured.entry((id, font.bold)).or_default();
|
||||
match known.get(line) {
|
||||
Some(w) => *w,
|
||||
None => {
|
||||
let w = m(line, &st.font, distinct < EXACT_TEXT_WIDTHS);
|
||||
let w = m(line, font, distinct < EXACT_TEXT_WIDTHS);
|
||||
known.insert(line.to_owned(), w);
|
||||
distinct += 1;
|
||||
w
|
||||
}
|
||||
}
|
||||
}
|
||||
None => approx_text_width(line, st.font.size, st.font.bold),
|
||||
None => approx_text_width(line, font.size, font.bold),
|
||||
};
|
||||
let w = w + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell);
|
||||
let max = maxes.entry(cell.col).or_insert(0.0);
|
||||
@@ -258,6 +264,7 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let e = sh.cols.entry(c).or_default();
|
||||
e.size = Some(w.ceil());
|
||||
e.hidden = false;
|
||||
e.custom = false; // AutoFit makes a width set by hand automatic again (Excel).
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Insert Chart",
|
||||
["Insert", "Charts"],
|
||||
None,
|
||||
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers, title?, at?: \"H2\", width?, height?}",
|
||||
"{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
|
||||
has_doc,
|
||||
insert_chart
|
||||
),
|
||||
@@ -217,7 +217,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Conditional Formatting",
|
||||
["Home", "Styles"],
|
||||
None,
|
||||
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
|
||||
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], stops?: [{type: min|max|num|percent|percentile|formula, value?, color}], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
|
||||
has_doc,
|
||||
add_cf
|
||||
),
|
||||
@@ -227,7 +227,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Manage Rules…",
|
||||
["Home", "Styles", "Conditional Formatting"],
|
||||
None,
|
||||
"{delete?: index, moveUp?: index, moveDown?: index}",
|
||||
"{delete?: index, moveUp?: index, moveDown?: index, edit?: index, rule?: {...} (with edit)}",
|
||||
has_doc,
|
||||
manage_cf
|
||||
),
|
||||
@@ -496,4 +496,302 @@ mod tests {
|
||||
s.execute("table.rename", json!({"table": "Table1", "name": "Table1"})).unwrap();
|
||||
s.execute("table.rename", json!({"table": "Table1", "name": "Rates"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_thresholds_are_clamped_to_the_percent_range() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "percent", "value": -5, "color": "#112233"},
|
||||
{"type": "percentile", "value": 150, "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
|
||||
assert_eq!(
|
||||
stops,
|
||||
vec![
|
||||
(CfValueKind::Percent(0.0), Color::Rgb(0x112233)),
|
||||
(CfValueKind::Percentile(100.0), Color::Rgb(0x445566)),
|
||||
(CfValueKind::Max, Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_stops_reject_empty_formulas_and_unknown_types() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let with_stops = |stops: Json| json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}});
|
||||
let err = s
|
||||
.execute(
|
||||
"home.conditionalFormat",
|
||||
with_stops(json!([
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "formula", "value": " ", "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
])),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{err}");
|
||||
assert!(err.contains("formula"), "{err}");
|
||||
|
||||
let err = s
|
||||
.execute(
|
||||
"home.conditionalFormat",
|
||||
with_stops(json!([
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "median", "value": 50, "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
])),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("unknown stop type `median`"), "{err}");
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_rejects_a_stops_value_that_is_not_an_array() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
// `stops` present but misshapen used to fall back to the default scale instead of erroring.
|
||||
for stops in [json!({}), json!(null), json!("min")] {
|
||||
let err = s
|
||||
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{err}");
|
||||
assert!(err.contains("`stops` must be an array"), "{err}");
|
||||
}
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "an invalid `stops` creates no rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_formulas_are_stored_verbatim() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "formula", "value": "=$Z$1", "color": "#445566"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
|
||||
assert_eq!(stops[1].0, CfValueKind::Formula("=$Z$1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_rejects_a_non_index_edit() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
|
||||
for bad in [json!("0"), json!(1.5), json!(-1), json!(true)] {
|
||||
let err = s
|
||||
.execute("home.manageRules", json!({"edit": bad, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("`edit` must be a rule index"), "{err}");
|
||||
}
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_rejects_an_edit_past_the_last_rule() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
|
||||
let err = s
|
||||
.execute("home.manageRules", json!({"edit": 1, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
assert!(err.contains("index 1"), "{err}");
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1), "the failed edit leaves the rule alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_rejects_an_edit_index_that_does_not_fit_a_usize() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
|
||||
// On a 32-bit target this used to cast to zero and replace the rule at index 0.
|
||||
let err =
|
||||
s.execute("home.manageRules", json!({"edit": 4294967296u64, "rule": {"type": "expression", "formula": "A1>3"}})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
assert!(err.contains("index 4294967296"), "{err}");
|
||||
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
|
||||
assert_eq!(formula, "A1>2", "the failed edit leaves the rule alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_names_itself_in_a_style_error() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
|
||||
// A style shared by both commands must name the one that was called.
|
||||
let rule = json!({"type": "cellIs", "operator": "greater", "value": 1, "style": {"nope": 1}});
|
||||
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": rule.clone()})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
assert!(!err.contains("home.conditionalFormat"), "{err}");
|
||||
let err = s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": rule})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rules_names_itself_in_a_stop_count_error() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let err = s
|
||||
.execute(
|
||||
"home.manageRules",
|
||||
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_formula_rule_needs_a_formula_that_parses() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
// An empty box used to create a rule that never applies.
|
||||
let err =
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": ""}})).unwrap_err().to_string();
|
||||
assert!(err.contains("formula is empty"), "{err}");
|
||||
// `=C1>` used to be written as `<formula>C1></formula>`, which Excel refuses to open.
|
||||
let err = s
|
||||
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=C1>"}}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("invalid"), "{err}");
|
||||
assert!(err.contains("does not parse"), "{err}");
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "a refused rule is not stored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_formula_on_edit_leaves_the_rule_alone() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
|
||||
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": {"type": "expression", "formula": "=C1>"}})).unwrap_err().to_string();
|
||||
assert!(err.contains("home.manageRules"), "{err}");
|
||||
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
|
||||
assert_eq!(formula, "A1>2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_stop_value_must_be_a_number() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
for ty in ["num", "percent", "percentile"] {
|
||||
let err = s
|
||||
.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": ty, "value": "5", "color": "#112233"},
|
||||
{"type": "max", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("home.conditionalFormat"), "{ty}: {err}");
|
||||
assert!(err.contains(&format!("`{ty}` stop's `value` must be a number")), "{ty}: {err}");
|
||||
}
|
||||
// A refused scale stores nothing.
|
||||
let rules = s.execute("home.manageRules", json!({})).unwrap();
|
||||
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_omitted_stop_value_is_zero() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "num", "color": "#112233"},
|
||||
{"type": "percent", "color": "#445566"},
|
||||
{"type": "percentile", "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
|
||||
assert_eq!(
|
||||
stops,
|
||||
vec![
|
||||
(CfValueKind::Number(0.0), Color::Rgb(0x112233)),
|
||||
(CfValueKind::Percent(0.0), Color::Rgb(0x445566)),
|
||||
(CfValueKind::Percentile(0.0), Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_stops_keep_their_thresholds_and_can_be_edited() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "min", "color": "#112233"},
|
||||
{"type": "num", "value": 5, "color": "#445566"},
|
||||
{"type": "percentile", "value": 90, "color": "#778899"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let stops = match rule {
|
||||
CfRule::ColorScale { stops } => stops,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
stops,
|
||||
vec![
|
||||
(CfValueKind::Min, Color::Rgb(0x112233)),
|
||||
(CfValueKind::Number(5.0), Color::Rgb(0x445566)),
|
||||
(CfValueKind::Percentile(90.0), Color::Rgb(0x778899)),
|
||||
]
|
||||
);
|
||||
|
||||
s.execute(
|
||||
"home.manageRules",
|
||||
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
|
||||
{"type": "formula", "value": "$B$1", "color": "#ABCABC"},
|
||||
{"type": "max", "color": "#DEFDEF"},
|
||||
]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let list = s.execute("home.manageRules", json!({})).unwrap();
|
||||
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
|
||||
let stops = match rule {
|
||||
CfRule::ColorScale { stops } => stops,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
assert_eq!(stops, vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,8 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind {
|
||||
("bar", _) => ChartKind::BarClustered,
|
||||
("line", "markers") => ChartKind::LineMarkers,
|
||||
("line", "stacked") => ChartKind::LineStacked,
|
||||
("line", "stacked100") => ChartKind::LineStacked100,
|
||||
("line", "stacked100Markers") => ChartKind::LineStacked100Markers,
|
||||
("line", _) => ChartKind::Line,
|
||||
("pie", _) => ChartKind::Pie,
|
||||
("doughnut", _) => ChartKind::Doughnut,
|
||||
@@ -106,6 +108,8 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -122,6 +126,8 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,9 +46,9 @@ fn is_string_literal(v: &str) -> bool {
|
||||
/// written as `format_range` takes it (`"#RRGGBB"`, `{theme, tint}`, `"auto"`) and `fill` may be a
|
||||
/// colour alone (a solid fill) or `"none"` (no fill). An unknown key is an error rather than
|
||||
/// dropped: dropped, it left a rule with an empty format that matches and shows nothing.
|
||||
fn cf_style_json(st: &Json) -> Result<Json> {
|
||||
fn cf_style_json(st: &Json, cmd: &str) -> Result<Json> {
|
||||
const KEYS: [&str; 6] = ["font", "fill", "borders", "align", "num_fmt", "protection"];
|
||||
let err = |m: String| bad("home.conditionalFormat", m);
|
||||
let err = |m: String| bad(cmd, m);
|
||||
let Some(obj) = st.as_object() else { return Err(err("`style` must be an object, e.g. {\"fill\": \"#FFC7CE\"}".into())) };
|
||||
let mut st = obj.clone();
|
||||
if let Some(k) = st.keys().find(|k| !KEYS.contains(&k.as_str())) {
|
||||
@@ -103,36 +103,40 @@ fn cf_style_json(st: &Json) -> Result<Json> {
|
||||
fn check_cf_formula(cmd: &str, what: &str, formula: &str) -> Result<()> {
|
||||
// Strip exactly one leading '=', the way the XLSX writer does: a value like '===A1'
|
||||
// only parses after several strips and would still be saved unparseable. (#1999 review)
|
||||
if gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).is_err() {
|
||||
let parsed = formula.strip_prefix('=').unwrap_or(formula);
|
||||
// A rule with no formula never applies; the dialog also keeps OK disabled for it.
|
||||
if parsed.trim().is_empty() {
|
||||
return Err(bad(cmd, format!("the {what} formula is empty")));
|
||||
}
|
||||
if gridcraft_formula::parse(parsed).is_err() {
|
||||
return Err(bad(cmd, format!("invalid {what} formula `{formula}` — it does not parse; Excel would reject the saved file")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_cf_value(what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
|
||||
fn check_cf_value(cmd: &str, what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
|
||||
if let gridcraft_model::features::CfValueKind::Formula(f) = v {
|
||||
check_cf_formula("home.conditionalFormat", what, f)?;
|
||||
check_cf_formula(cmd, what, f)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_cf_rule(rule: &CfRule) -> Result<()> {
|
||||
const CMD: &str = "home.conditionalFormat";
|
||||
fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> {
|
||||
match rule {
|
||||
CfRule::CellIs { a, b, .. } => {
|
||||
check_cf_formula(CMD, "comparison value", a)?;
|
||||
check_cf_formula(cmd, "comparison value", a)?;
|
||||
if let Some(b) = b {
|
||||
check_cf_formula(CMD, "second comparison value", b)?;
|
||||
check_cf_formula(cmd, "second comparison value", b)?;
|
||||
}
|
||||
}
|
||||
CfRule::Expression { formula, .. } => check_cf_formula(CMD, "rule", formula)?,
|
||||
CfRule::Expression { formula, .. } => check_cf_formula(cmd, "rule", formula)?,
|
||||
CfRule::DataBar { min, max, .. } => {
|
||||
check_cf_value("data bar minimum", min)?;
|
||||
check_cf_value("data bar maximum", max)?;
|
||||
check_cf_value(cmd, "data bar minimum", min)?;
|
||||
check_cf_value(cmd, "data bar maximum", max)?;
|
||||
}
|
||||
CfRule::ColorScale { stops } => {
|
||||
for (kind, _) in stops {
|
||||
check_cf_value("color scale threshold", kind)?;
|
||||
check_cf_value(cmd, "color scale threshold", kind)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -140,41 +144,53 @@ fn check_cf_rule(rule: &CfRule) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let Some(rule) = p.get("rule") else {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
|
||||
return ok();
|
||||
};
|
||||
fn cf_style(rule: &Json, cmd: &str) -> Result<Style> {
|
||||
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
|
||||
let style = Box::new(match rule.get("style") {
|
||||
match rule.get("style") {
|
||||
Some(st) if !st.is_null() => {
|
||||
let st = cf_style_json(st)?;
|
||||
let st = cf_style_json(st, cmd)?;
|
||||
let base = serde_json::to_value(Style::default()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad("home.conditionalFormat", e.to_string()))?
|
||||
Ok(serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad(cmd, e.to_string()))?)
|
||||
}
|
||||
_ => preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText")),
|
||||
});
|
||||
let kind = g("type").unwrap_or_else(|| "cellIs".into());
|
||||
let value_kind = |v: Option<&Json>, default: CfValueKind| -> CfValueKind {
|
||||
match v {
|
||||
Some(Json::Object(o)) => {
|
||||
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
|
||||
let val = o.get("value").and_then(Json::as_f64).unwrap_or(0.0);
|
||||
match t {
|
||||
"min" => CfValueKind::Min,
|
||||
"max" => CfValueKind::Max,
|
||||
"percent" => CfValueKind::Percent(val),
|
||||
"percentile" => CfValueKind::Percentile(val),
|
||||
"formula" => CfValueKind::Formula(o.get("value").and_then(Json::as_str).unwrap_or("").into()),
|
||||
_ => CfValueKind::Number(val),
|
||||
}
|
||||
}
|
||||
_ => default,
|
||||
_ => Ok(preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn cf_value_kind(v: Option<&Json>, default: CfValueKind, cmd: &str) -> Result<CfValueKind> {
|
||||
let Some(Json::Object(o)) = v else { return Ok(default) };
|
||||
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
|
||||
// A value that is given must be a number: a string used to be read as 0 without a word.
|
||||
// Only an omitted `value` defaults to zero.
|
||||
let number = || -> Result<f64> {
|
||||
match o.get("value") {
|
||||
None => Ok(0.0),
|
||||
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("the `{t}` stop's `value` must be a number, not {v}"))),
|
||||
}
|
||||
};
|
||||
let rule = match kind.as_str() {
|
||||
Ok(match t {
|
||||
"min" => CfValueKind::Min,
|
||||
"max" => CfValueKind::Max,
|
||||
// The dialog clamps these to 0-100; engine callers get the same range.
|
||||
"percent" => CfValueKind::Percent(number()?.clamp(0.0, 100.0)),
|
||||
"percentile" => CfValueKind::Percentile(number()?.clamp(0.0, 100.0)),
|
||||
"formula" => {
|
||||
let f = o.get("value").and_then(Json::as_str).unwrap_or("");
|
||||
if f.trim().is_empty() {
|
||||
return Err(bad(cmd, "a formula stop needs a formula"));
|
||||
}
|
||||
// Stored exactly: the evaluator takes the formula as written.
|
||||
CfValueKind::Formula(f.into())
|
||||
}
|
||||
"num" => CfValueKind::Number(number()?),
|
||||
other => return Err(bad(cmd, format!("unknown stop type `{other}`"))),
|
||||
})
|
||||
}
|
||||
|
||||
fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
|
||||
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
|
||||
let style = Box::new(cf_style(rule, cmd)?);
|
||||
let kind = g("type").unwrap_or_else(|| "cellIs".into());
|
||||
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") {
|
||||
@@ -186,7 +202,7 @@ pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual,
|
||||
"lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual,
|
||||
"greater" | "greaterThan" => CfOperator::Greater,
|
||||
other => return Err(bad("home.conditionalFormat", format!("unknown operator `{other}`"))),
|
||||
other => return Err(bad(cmd, format!("unknown operator `{other}`"))),
|
||||
};
|
||||
let a = rule.get("value").map(crate::cmd::edit::json_to_input).unwrap_or_default();
|
||||
let b = rule.get("value2").map(crate::cmd::edit::json_to_input);
|
||||
@@ -201,59 +217,85 @@ pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
format!("\"{}\"", v.replace('"', "\"\""))
|
||||
}
|
||||
};
|
||||
CfRule::CellIs { op, a: quote(a), b: b.map(quote), style }
|
||||
Ok(CfRule::CellIs { op, a: quote(a), b: b.map(quote), style })
|
||||
}
|
||||
"expression" => CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style },
|
||||
"containsText" => CfRule::ContainsText { text: g("text").unwrap_or_default(), style },
|
||||
"notContainsText" => CfRule::NotContainsText { text: g("text").unwrap_or_default(), style },
|
||||
"beginsWith" => CfRule::BeginsWith { text: g("text").unwrap_or_default(), style },
|
||||
"endsWith" => CfRule::EndsWith { text: g("text").unwrap_or_default(), style },
|
||||
"blanks" => CfRule::Blanks { style },
|
||||
"noBlanks" => CfRule::NoBlanks { style },
|
||||
"errors" => CfRule::Errors { style },
|
||||
"noErrors" => CfRule::NoErrors { style },
|
||||
"duplicate" => CfRule::Duplicate { style },
|
||||
"unique" => CfRule::Unique { style },
|
||||
"top10" => CfRule::Top10 {
|
||||
"expression" => Ok(CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style }),
|
||||
"containsText" => Ok(CfRule::ContainsText { text: g("text").unwrap_or_default(), style }),
|
||||
"notContainsText" => Ok(CfRule::NotContainsText { text: g("text").unwrap_or_default(), style }),
|
||||
"beginsWith" => Ok(CfRule::BeginsWith { text: g("text").unwrap_or_default(), style }),
|
||||
"endsWith" => Ok(CfRule::EndsWith { text: g("text").unwrap_or_default(), style }),
|
||||
"blanks" => Ok(CfRule::Blanks { style }),
|
||||
"noBlanks" => Ok(CfRule::NoBlanks { style }),
|
||||
"errors" => Ok(CfRule::Errors { style }),
|
||||
"noErrors" => Ok(CfRule::NoErrors { style }),
|
||||
"duplicate" => Ok(CfRule::Duplicate { style }),
|
||||
"unique" => Ok(CfRule::Unique { style }),
|
||||
"top10" => Ok(CfRule::Top10 {
|
||||
bottom: rule.get("bottom").and_then(Json::as_bool).unwrap_or(false),
|
||||
percent: rule.get("percent").and_then(Json::as_bool).unwrap_or(false),
|
||||
rank: rule.get("rank").and_then(Json::as_u64).unwrap_or(10) as u32,
|
||||
style,
|
||||
},
|
||||
"aboveAverage" => CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style },
|
||||
"timePeriod" => CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style },
|
||||
"colorScale" => {
|
||||
let cols: Vec<Color> = rule
|
||||
.get("colors")
|
||||
.and_then(Json::as_array)
|
||||
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
|
||||
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
|
||||
let stops = match cols.len() {
|
||||
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
|
||||
_ => vec![
|
||||
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
|
||||
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
|
||||
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
|
||||
],
|
||||
};
|
||||
CfRule::ColorScale { stops }
|
||||
}),
|
||||
"aboveAverage" => {
|
||||
Ok(CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style })
|
||||
}
|
||||
"dataBar" => CfRule::DataBar {
|
||||
min: value_kind(rule.get("min"), CfValueKind::Min),
|
||||
max: value_kind(rule.get("max"), CfValueKind::Max),
|
||||
"timePeriod" => Ok(CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style }),
|
||||
"colorScale" => {
|
||||
let stops = if let Some(stops) = rule.get("stops") {
|
||||
// A present but misshapen `stops` is a mistake, not a request for `colors`.
|
||||
let list = stops.as_array().ok_or_else(|| bad(cmd, "`stops` must be an array"))?;
|
||||
let mut out = Vec::with_capacity(list.len().min(3));
|
||||
for stop in list {
|
||||
let color = crate::cmd::format::color_param(stop.get("color")).ok_or_else(|| bad(cmd, "a colour-scale stop needs a colour"))?;
|
||||
out.push((cf_value_kind(Some(stop), CfValueKind::Min, cmd)?, color));
|
||||
}
|
||||
if !(2..=3).contains(&out.len()) {
|
||||
return Err(bad(cmd, "a colour scale needs two or three stops"));
|
||||
}
|
||||
out
|
||||
} else {
|
||||
let cols: Vec<Color> = rule
|
||||
.get("colors")
|
||||
.and_then(Json::as_array)
|
||||
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
|
||||
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
|
||||
match cols.len() {
|
||||
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
|
||||
_ => vec![
|
||||
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
|
||||
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
|
||||
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
|
||||
],
|
||||
}
|
||||
};
|
||||
Ok(CfRule::ColorScale { stops })
|
||||
}
|
||||
"dataBar" => Ok(CfRule::DataBar {
|
||||
min: cf_value_kind(rule.get("min"), CfValueKind::Min, cmd)?,
|
||||
max: cf_value_kind(rule.get("max"), CfValueKind::Max, cmd)?,
|
||||
color: crate::cmd::format::color_param(rule.get("color")).unwrap_or(Color::rgb(0x63, 0x8E, 0xC6)),
|
||||
gradient: rule.get("gradient").and_then(Json::as_bool).unwrap_or(true),
|
||||
show_value: true,
|
||||
},
|
||||
"iconSet" => CfRule::IconSet {
|
||||
}),
|
||||
"iconSet" => Ok(CfRule::IconSet {
|
||||
set: g("set").unwrap_or_else(|| "3TrafficLights1".into()),
|
||||
thresholds: vec![],
|
||||
reverse: rule.get("reverse").and_then(Json::as_bool).unwrap_or(false),
|
||||
show_value: true,
|
||||
},
|
||||
other => return Err(bad("home.conditionalFormat", format!("unknown rule type `{other}`"))),
|
||||
}),
|
||||
other => Err(bad(cmd, format!("unknown rule type `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let ranges = target_ranges(s, p)?;
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let Some(rule) = p.get("rule") else {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
|
||||
return ok();
|
||||
};
|
||||
check_cf_rule(&rule)?;
|
||||
let rule = cf_rule(rule, "home.conditionalFormat")?;
|
||||
check_cf_rule("home.conditionalFormat", &rule)?;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let priority = sh.cond_formats.iter().map(|c| c.priority).max().unwrap_or(0) + 1;
|
||||
@@ -295,17 +337,33 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
|
||||
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() && p.get("edit").is_none() {
|
||||
let list: Vec<Json> = s
|
||||
.doc()?
|
||||
.wb
|
||||
.sheet(sheet)
|
||||
.map(|sh| {
|
||||
sh.cond_formats.iter().map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule})).collect()
|
||||
sh.cond_formats
|
||||
.iter()
|
||||
.map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule, "priority": c.priority}))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
return Ok(json!({"rules": list}));
|
||||
}
|
||||
let edited = match (p.get("edit"), p.get("rule")) {
|
||||
(None, _) => None,
|
||||
(Some(_), None) => return Err(bad("home.manageRules", "missing `rule` for an edit")),
|
||||
(Some(e), Some(rule)) => {
|
||||
let i = e.as_u64().ok_or_else(|| bad("home.manageRules", "`edit` must be a rule index"))?;
|
||||
// A number too large for `usize` on this target names no rule: casting it would
|
||||
// wrap to a real index and replace that rule instead of reporting out of range.
|
||||
let i = usize::try_from(i).map_err(|_| bad("home.manageRules", format!("no conditional format at index {i}")))?;
|
||||
let rule = cf_rule(rule, "home.manageRules")?;
|
||||
check_cf_rule("home.manageRules", &rule)?;
|
||||
Some((i, rule))
|
||||
}
|
||||
};
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// The count is taken again after each step: a delete shortens the list.
|
||||
@@ -314,6 +372,10 @@ pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
{
|
||||
sh.cond_formats.remove(i);
|
||||
}
|
||||
if let Some((i, rule)) = edited {
|
||||
let cf = sh.cond_formats.get_mut(i).ok_or_else(|| bad("home.manageRules", format!("no conditional format at index {i}")))?;
|
||||
cf.rule = rule;
|
||||
}
|
||||
if let Some(i) = u32_param(p, "moveUp").map(|v| v as usize)
|
||||
&& i > 0
|
||||
&& i < sh.cond_formats.len()
|
||||
|
||||
@@ -56,10 +56,10 @@ pub(super) fn open_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
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 {
|
||||
let Some(h) = crate::links::cell_link(&s.doc()?.wb, sheet, at) else {
|
||||
return Err(EngineError::Other("There's no hyperlink in this cell.".into()));
|
||||
};
|
||||
h.target.clone()
|
||||
h.target
|
||||
}
|
||||
};
|
||||
match crate::links::classify(&target) {
|
||||
|
||||
@@ -74,6 +74,13 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col))
|
||||
};
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// As in Excel, the table unmerges the merged cells it covers: a table can't hold them.
|
||||
let merged = sh.merges.len();
|
||||
sh.merges.retain(|m| !m.intersects(&r));
|
||||
if sh.merges.len() != merged {
|
||||
cx.structural = true;
|
||||
}
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
// Lower-case names taken, and the next suffix for each header, so that thousands of equal
|
||||
// headers don't take cubic time.
|
||||
|
||||
@@ -136,7 +136,7 @@ fn cell_get(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"style": style,
|
||||
"merge": sh.merge_at(c).map(|m| m.a1()),
|
||||
"comment": sh.comments.get(&c),
|
||||
"hyperlink": sh.hyperlinks.get(&c),
|
||||
"hyperlink": crate::links::cell_link(&d.wb, sheet, c),
|
||||
"python": cell.and_then(|x| x.py.as_deref()).map(|py| json!({
|
||||
"code": py.code,
|
||||
"output": if py.object { "object" } else { "value" },
|
||||
|
||||
@@ -118,7 +118,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
value_settings
|
||||
),
|
||||
cmd!("pivot.filter", "Filter Items", [], None, "{pivot?, field, selected: [\"East\", ..] | null (all), replace?}", has_doc, filter),
|
||||
cmd!("pivot.sort", "Sort Field", [], None, "{pivot?, field, order: asc|desc|none, replace?}", has_doc, sort),
|
||||
cmd!(
|
||||
"pivot.sort",
|
||||
"Sort Field",
|
||||
[],
|
||||
None,
|
||||
"{pivot?, field, order: asc|desc|none, by?: \"Sum of Sales\" (sort by a value field), replace?}",
|
||||
has_doc,
|
||||
sort
|
||||
),
|
||||
cmd!(
|
||||
"pivot.group",
|
||||
"Group Field",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::fields::{AreaPlacement, add_to_area, in_axes};
|
||||
use super::params::{func_name, func_param, group_name, group_param, layout_name, show_as_name, sort_name};
|
||||
use super::{
|
||||
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook, bad,
|
||||
bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
|
||||
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotField, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook,
|
||||
bad, bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- insert
|
||||
@@ -327,6 +327,18 @@ pub(super) fn summarize_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
// ---------------------------------------------------------------- queries
|
||||
|
||||
fn field_json(f: &PivotField) -> Json {
|
||||
json!({
|
||||
"field": f.source_col,
|
||||
"caption": f.caption,
|
||||
"sort": sort_name(f.sort),
|
||||
"sortBy": f.sort_by,
|
||||
"group": group_name(f.date_group),
|
||||
"numberFormat": f.number_format,
|
||||
"collapsed": f.collapsed_items,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
|
||||
json!({
|
||||
"id": pt.id,
|
||||
@@ -335,8 +347,8 @@ pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
|
||||
"anchor": pt.anchor.a1(),
|
||||
"range": pt.last_range.map(|r| r.a1()),
|
||||
"source": pt.source,
|
||||
"rows": pt.rows.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::<Vec<_>>(),
|
||||
"columns": pt.columns.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::<Vec<_>>(),
|
||||
"rows": pt.rows.iter().map(field_json).collect::<Vec<_>>(),
|
||||
"columns": pt.columns.iter().map(field_json).collect::<Vec<_>>(),
|
||||
"values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": func_name(v.func), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::<Vec<_>>(),
|
||||
"filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::<Vec<_>>(),
|
||||
"layout": layout_name(pt.layout),
|
||||
|
||||
@@ -551,6 +551,12 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
None => {}
|
||||
}
|
||||
let name = v.name.clone();
|
||||
// Fields sorted by this value field follow its new caption.
|
||||
for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) {
|
||||
if f.sort_by.as_deref().is_some_and(|b| b.eq_ignore_ascii_case(&cur.name)) {
|
||||
f.sort_by = Some(name.clone());
|
||||
}
|
||||
}
|
||||
if let Some(slot) = pt.values.get_mut(i) {
|
||||
*slot = v;
|
||||
}
|
||||
|
||||
@@ -71,8 +71,24 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
"none" | "manual" | "source" => PivotSort::None,
|
||||
o => return Err(bad(C, format!("unknown order `{o}` (asc|desc|none)"))),
|
||||
};
|
||||
// Sort by a value field (its caption or source field) instead of by the item labels.
|
||||
let by = str_param(p, "by").map(str::to_string);
|
||||
update(s, p, |pt, _, _| {
|
||||
axis_field(C, pt, &field)?.sort = order;
|
||||
let by = match by {
|
||||
Some(b) => Some(
|
||||
pt.values
|
||||
.iter()
|
||||
.find(|v| v.name.eq_ignore_ascii_case(&b))
|
||||
.or_else(|| pt.values.iter().find(|v| v.source_col.eq_ignore_ascii_case(&b)))
|
||||
.map(|v| v.name.clone())
|
||||
.ok_or_else(|| bad(C, format!("`{b}` isn't in the values area")))?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let f = axis_field(C, pt, &field)?;
|
||||
f.sort = order;
|
||||
f.sort_by = by;
|
||||
f.sort_scope.clear();
|
||||
Ok(json!({}))
|
||||
})
|
||||
}
|
||||
@@ -164,7 +180,11 @@ pub(super) fn layout(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
if let Some((on, top)) = subtotals {
|
||||
// Design › Subtotals applies to every field, replacing per-field settings.
|
||||
pt.subtotals = on;
|
||||
for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) {
|
||||
f.subtotal = None;
|
||||
}
|
||||
if let Some(t) = top {
|
||||
pt.subtotals_top = t;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use gridcraft_core::{CellError, CellRef, Value};
|
||||
use gridcraft_model::{PivotLayout, PivotSort};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use crate::Session;
|
||||
@@ -317,6 +318,10 @@ fn assert_values_on_rows_tabular(s: &mut Session) {
|
||||
assert_eq!(text(s, "A3"), "Region");
|
||||
assert_eq!(text(s, "B3"), "Values");
|
||||
assert_eq!(text(s, "C3"), "Total");
|
||||
// The Values field's caption heads its column, as in Excel's saved reports.
|
||||
edit_pt(s, |p| p.data_caption = Some("Data".into()));
|
||||
assert_eq!(text(s, "B3"), "Data");
|
||||
edit_pt(s, |p| p.data_caption = None);
|
||||
}
|
||||
|
||||
fn assert_values_on_rows_position(s: &mut Session) {
|
||||
@@ -501,6 +506,231 @@ fn refresh_after_source_edits() {
|
||||
s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
|
||||
}
|
||||
|
||||
/// Edits the active sheet's last PivotTable in the model (settings only a file sets) and
|
||||
/// refreshes it.
|
||||
fn edit_pt(s: &mut Session, f: impl FnOnce(&mut gridcraft_model::PivotTable)) {
|
||||
let d = s.doc_mut().unwrap();
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
let si = wb.active_sheet();
|
||||
f(wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap());
|
||||
s.execute("pivot.refresh", json!({})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_by_value_within_each_parent() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
|
||||
// East 415, West 285, North 135.
|
||||
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
|
||||
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Sum of Sales"));
|
||||
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["East", "West", "North"]);
|
||||
s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Sales"})).unwrap();
|
||||
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["North", "West", "East"]);
|
||||
assert!(s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Nope"})).is_err());
|
||||
// The sort follows a renamed value field; sorting without `by` sorts by label again.
|
||||
s.execute("pivot.valueSettings", json!({"field": "Sum of Sales", "name": "Revenue"})).unwrap();
|
||||
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Revenue"));
|
||||
assert_eq!(text(&s, "A4"), "North");
|
||||
s.execute("pivot.sort", json!({"field": "Region", "order": "desc"})).unwrap();
|
||||
assert_eq!(pt(&s).rows[0].sort_by, None);
|
||||
assert_eq!(text(&s, "A4"), "West");
|
||||
// Inner items sort within their parent; subtotals stay with their group.
|
||||
s.execute("pivot.addField", json!({"field": "Product", "area": "rows"})).unwrap();
|
||||
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
|
||||
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Revenue"})).unwrap();
|
||||
s.execute("pivot.sort", json!({"field": "Product", "order": "desc", "by": "Revenue"})).unwrap();
|
||||
// East: Pears 195, Apples 160, Plums 60.
|
||||
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "B5"), text(&s, "B6"), text(&s, "A7")], ["East", "Pears", "Apples", "Plums", "East Total"]);
|
||||
assert_eq!(val(&s, "C4"), Value::Number(195.0));
|
||||
// West: Apples 170, Plums 70, Pears 45.
|
||||
assert_eq!([text(&s, "A8"), text(&s, "B8"), text(&s, "B9"), text(&s, "B10")], ["West", "Apples", "Plums", "Pears"]);
|
||||
// Columns sort by their row totals.
|
||||
s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap();
|
||||
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4")], ["East", "West", "North"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captions_renamed_items_and_manual_order() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
|
||||
edit_pt(&mut s, |p| {
|
||||
p.row_header_caption = Some("Area".into());
|
||||
p.col_header_caption = Some("Fruit".into());
|
||||
p.grand_total_caption = Some("Everything".into());
|
||||
p.rows[0].item_captions = vec![("East".into(), "Eastern".into())];
|
||||
p.columns[0].sort = PivotSort::None;
|
||||
p.columns[0].item_order = vec!["Plums".into(), "Pears".into()];
|
||||
});
|
||||
assert_eq!(text(&s, "A4"), "Area");
|
||||
assert_eq!(text(&s, "B3"), "Fruit");
|
||||
// Listed items first, the rest after.
|
||||
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4"), text(&s, "E4")], ["Plums", "Pears", "Apples", "Everything"]);
|
||||
assert_eq!(text(&s, "A5"), "Eastern");
|
||||
assert_eq!(text(&s, "A8"), "Everything");
|
||||
// A renamed item sorts by its label still, and a filter still names it by its label.
|
||||
s.execute("pivot.filter", json!({"field": "Region", "selected": ["East"]})).unwrap();
|
||||
assert_eq!(text(&s, "A5"), "Eastern");
|
||||
assert_eq!(val(&s, "E5"), Value::Number(415.0));
|
||||
// Outline layout: the field's custom name heads its column.
|
||||
edit_pt(&mut s, |p| {
|
||||
p.layout = PivotLayout::Outline;
|
||||
p.rows[0].caption = Some("Sales area".into());
|
||||
p.columns[0].caption = Some("Kind".into());
|
||||
});
|
||||
assert_eq!(text(&s, "A4"), "Sales area");
|
||||
assert_eq!(text(&s, "B3"), "Kind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_subtotals_repeat_labels_and_values_row() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
|
||||
assert_eq!(text(&s, "A7"), "East Total");
|
||||
// Region without subtotals although the table has them; labels repeated on every row.
|
||||
edit_pt(&mut s, |p| {
|
||||
p.rows[0].subtotal = Some(false);
|
||||
p.rows[0].repeat_labels = true;
|
||||
});
|
||||
assert_eq!(pt(&s).last_range.unwrap().height(), 1 + 9 + 1);
|
||||
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6"), text(&s, "A7")], ["East", "East", "East", "North"]);
|
||||
assert_eq!(text(&s, "B7"), "Apples");
|
||||
// Outline repeats the labels too.
|
||||
s.execute("pivot.layout", json!({"layout": "outline"})).unwrap();
|
||||
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "A5"), text(&s, "B5")], ["East", "", "East", "Apples"]);
|
||||
// Two values without a column field: the Values row (Outline/Tabular) holds the caption.
|
||||
s.execute("pivot.removeField", json!({"field": "Product"})).unwrap();
|
||||
s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap();
|
||||
assert_eq!(text(&s, "B3"), "Values");
|
||||
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "C4")], ["Region", "Sum of Sales", "Sum of Units"]);
|
||||
edit_pt(&mut s, |p| p.data_caption = Some("Data".into()));
|
||||
assert_eq!(text(&s, "B3"), "Data");
|
||||
edit_pt(&mut s, |p| p.show_values_row = false);
|
||||
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Region", "Sum of Sales"]);
|
||||
// Compact layout never shows it.
|
||||
edit_pt(&mut s, |p| {
|
||||
p.show_values_row = true;
|
||||
p.layout = PivotLayout::Compact;
|
||||
});
|
||||
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Row Labels", "Sum of Sales"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_cell_caption_classic_layout_and_date_order() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Units"], "values": ["Sales"]})).unwrap();
|
||||
// East has no record with 1 unit: blank, or the "For empty cells show" caption.
|
||||
assert_eq!([text(&s, "A5"), text(&s, "B4"), text(&s, "B5")], ["East", "1", ""]);
|
||||
edit_pt(&mut s, |p| p.empty_caption = Some("0".into()));
|
||||
assert_eq!(text(&s, "B5"), "0");
|
||||
// Classic layout, one value and no column field: the value caption above the row
|
||||
// headers and a "Total" column.
|
||||
s.execute("pivot.removeField", json!({"field": "Units"})).unwrap();
|
||||
edit_pt(&mut s, |p| {
|
||||
p.layout = PivotLayout::Tabular;
|
||||
p.classic_layout = true;
|
||||
});
|
||||
assert_eq!([text(&s, "A3"), text(&s, "A4"), text(&s, "B4"), text(&s, "A5")], ["Sum of Sales", "Region", "Total", "East"]);
|
||||
assert_eq!(pt(&s).last_range.unwrap().height(), 2 + 3 + 1);
|
||||
// A field number format applies to the item labels; date items sort after text, as in
|
||||
// Excel.
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
|
||||
s.execute("pivot.removeField", json!({"field": "Region"})).unwrap();
|
||||
s.execute("pivot.addField", json!({"field": "Date", "area": "rows"})).unwrap();
|
||||
edit_pt(&mut s, |p| p.rows[0].number_format = Some("m/d/yyyy".into()));
|
||||
assert_eq!(text(&s, "A5"), "NA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_date_formatted_cells_sort_as_dates() {
|
||||
// The two mixed columns of ClosedXML's VariousDataTypesInTableColumns, in source order.
|
||||
// Excel caches each date-formatted cell as `<d>` and each General one as `<n>`, and its
|
||||
// saved items list numbers first and dates after errors, whatever the first cell is.
|
||||
let mixed = ["", "TRUE", "14.5", "10", "ABC", "=1/0", "8/10/2020", "16:30"];
|
||||
// 1 and 1.52… are 12/31/1899 and 12/31/1899 12:30, which typed input reads as text.
|
||||
let with_num = ["1", "1.5208333333333333", "12/24/2020", "16:30", "0.1", "45000", ""];
|
||||
let order = |inputs: &[&str], dates: Option<&str>| -> Vec<String> {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "K"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": "V"})).unwrap();
|
||||
for (i, input) in inputs.iter().enumerate() {
|
||||
s.execute("cell.set", json!({"cell": format!("A{}", i + 2), "input": input})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": format!("B{}", i + 2), "input": "1"})).unwrap();
|
||||
}
|
||||
if let Some(range) = dates {
|
||||
s.execute("home.formatCells", json!({"range": range, "style": {"num_fmt": "m/d/yyyy h:mm"}})).unwrap();
|
||||
}
|
||||
s.execute("selection.set", json!({"range": "A1"})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"]})).unwrap();
|
||||
edit_pt(&mut s, |p| p.rows[0].sort = PivotSort::Asc);
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let si = wb.active_sheet();
|
||||
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
|
||||
out.grid.iter().skip(1).filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l != "Grand Total").collect()
|
||||
};
|
||||
// Excel's saved <items> order for each field.
|
||||
let excel_mixed = ["10", "14.5", "ABC", "TRUE", "#DIV/0!", "0.6875", "44053", "(blank)"];
|
||||
let excel_with_num = ["0.1", "45000", "0.6875", "1", "1.52083333333333", "44189", "(blank)"];
|
||||
assert_eq!(order(&mixed, None), excel_mixed);
|
||||
assert_eq!(order(&with_num, Some("A2:A3")), excel_with_num);
|
||||
// One number in a date cell and in a General cell is one item, which sorts as a number
|
||||
// whichever cell comes first.
|
||||
let number = ["5", "44053", "ABC"];
|
||||
assert_eq!(order(&["5", "8/10/2020", "44053", "ABC"], None), number);
|
||||
assert_eq!(order(&["5", "44053", "8/10/2020", "ABC"], None), number);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_general_cell_filtered_out_still_makes_its_number_sort_as_a_number() {
|
||||
// 3/15/2023 is 45000: the General 45000 in row 3 makes that item a number, as in Excel's
|
||||
// cache, even when the report filter leaves only the date cell.
|
||||
let order = |filter: bool| -> Vec<String> {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
for (cell, input) in [("A1", "K"), ("B1", "V"), ("C1", "R"), ("A2", "3/15/2023"), ("A3", "45000"), ("A4", "ABC")] {
|
||||
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
|
||||
}
|
||||
for (row, r) in [(2, "a"), (3, "b"), (4, "a")] {
|
||||
s.execute("cell.set", json!({"cell": format!("B{row}"), "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": format!("C{row}"), "input": r})).unwrap();
|
||||
}
|
||||
s.execute("selection.set", json!({"range": "A1"})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"], "filters": ["R"]})).unwrap();
|
||||
s.execute("pivot.sort", json!({"field": "K", "order": "asc"})).unwrap();
|
||||
if filter {
|
||||
s.execute("pivot.filter", json!({"field": "R", "selected": ["a"]})).unwrap();
|
||||
}
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let si = wb.active_sheet();
|
||||
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
|
||||
out.grid.iter().filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l == "45000" || l == "ABC").collect()
|
||||
};
|
||||
assert_eq!(order(false), ["45000", "ABC"]);
|
||||
assert_eq!(order(true), ["45000", "ABC"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_sort_after_logicals_and_errors() {
|
||||
// Excel's ascending item order: numbers, text, logicals, errors, dates, blanks.
|
||||
let mut s = sales();
|
||||
s.execute("cell.set", json!({"cell": "C11", "input": "TRUE"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C12", "input": "=1/0"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
|
||||
edit_pt(&mut s, |p| {
|
||||
p.rows[0].number_format = None;
|
||||
p.rows[0].sort = PivotSort::Asc;
|
||||
});
|
||||
let p = pt(&s);
|
||||
let r = p.last_range.unwrap();
|
||||
let labels: Vec<String> = (r.start.row + 1..=r.end.row).map(|row| text(&s, &CellRef::new(row, r.start.col).a1())).collect();
|
||||
// 46037 is 1/15/2026, the first date.
|
||||
assert_eq!(labels[..4], ["NA", "TRUE", "#DIV/0!", "46037"]);
|
||||
}
|
||||
|
||||
fn pivot_chart(s: &Session) -> gridcraft_model::Chart {
|
||||
s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone()
|
||||
}
|
||||
@@ -1153,12 +1383,289 @@ fn collapsed_column_items_count_as_one_column_group() {
|
||||
s.execute("pivot.addField", json!({"field": "Sub", "area": "columns"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn design_subtotals_replace_field_settings() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
|
||||
// A file's field can override the table default (`defaultSubtotal`).
|
||||
edit_pt(&mut s, |p| {
|
||||
p.subtotals = false;
|
||||
p.rows[0].subtotal = Some(true);
|
||||
});
|
||||
assert!(find_row(&s, "East Total").is_some());
|
||||
// Design › Subtotals › Do Not Show Subtotals applies to every field.
|
||||
s.execute("pivot.subtotals", json!({"mode": "none"})).unwrap();
|
||||
assert!(pt(&s).rows.iter().all(|f| f.subtotal.is_none()));
|
||||
assert_eq!(find_row(&s, "East Total"), None);
|
||||
edit_pt(&mut s, |p| p.rows[0].subtotal = Some(false));
|
||||
s.execute("pivot.subtotals", json!({"mode": "bottom"})).unwrap();
|
||||
assert!(find_row(&s, "East Total").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_empty_cell_caption_is_a_number() {
|
||||
let mut s = sales();
|
||||
s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
|
||||
// South has no Apples: the cell shows the caption, a number as Excel stores it.
|
||||
edit_pt(&mut s, |p| p.empty_caption = Some("0".into()));
|
||||
let south = find_row(&s, "South").unwrap();
|
||||
let apples = CellRef::new(south, 1);
|
||||
assert_eq!(text(&s, &CellRef::new(south - 3, 1).a1()), "Apples");
|
||||
assert_eq!(val(&s, &apples.a1()), Value::Number(0.0));
|
||||
edit_pt(&mut s, |p| p.empty_caption = Some("n/a".into()));
|
||||
assert_eq!(val(&s, &apples.a1()), Value::text("n/a"));
|
||||
}
|
||||
|
||||
/// Saves the active workbook, applies `patch` to the first PivotTable part and reopens it.
|
||||
fn reopen_patched(s: &Session, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec<String>) {
|
||||
reopen_patched_part(s, "xl/pivotTables/pivotTable1.xml", patch)
|
||||
}
|
||||
/// Saves the active workbook, applies `patch` to `part` and reopens it.
|
||||
fn reopen_patched_part(s: &Session, part: &str, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec<String>) {
|
||||
use std::io::{Read, Write};
|
||||
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
if name == part {
|
||||
b = patch(&String::from_utf8(b).unwrap()).into_bytes();
|
||||
}
|
||||
out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
out.write_all(&b).unwrap();
|
||||
}
|
||||
let bytes = out.finish().unwrap().into_inner();
|
||||
crate::io::open_bytes("t.xlsx", &bytes).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_by_value_in_a_column_keeps_its_scope() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
|
||||
// Excel's "sort by the values in the Apples column": the scope also names Product's
|
||||
// item 0 (Apples). Apples: East 160, West 170, North 90; totals East 415, West 285.
|
||||
let one = "<references count=\"1\"><reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
|
||||
let values_ref = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
|
||||
let two = format!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>");
|
||||
let (wb, _) = reopen_patched(&s, |x| {
|
||||
assert!(x.contains(one), "{x}");
|
||||
x.replace(one, &two)
|
||||
});
|
||||
let si = wb.active_sheet();
|
||||
let p = wb.sheet(si).unwrap().pivots.last().unwrap();
|
||||
let apples = gridcraft_model::PivotScopeItem { source_col: "Product".into(), item: "Apples".into(), ..Default::default() };
|
||||
assert_eq!(p.rows[0].sort_scope, vec![apples]);
|
||||
let out = crate::pivot::compute(&wb, p, si).unwrap();
|
||||
let labels: Vec<String> = out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).collect();
|
||||
let order: Vec<&str> = labels.iter().map(String::as_str).filter(|l| ["East", "West", "North"].contains(l)).collect();
|
||||
assert_eq!(order, ["West", "East", "North"]);
|
||||
// Saving writes the scope back.
|
||||
let again = crate::io::save_bytes(&wb, "t.xlsx").unwrap();
|
||||
let (back, _) = crate::io::open_bytes("t.xlsx", &again).unwrap();
|
||||
assert_eq!(back.sheet(si).unwrap().pivots.last().unwrap().rows[0].sort_scope, p.rows[0].sort_scope);
|
||||
// A scope GridCraft can't represent (two Product items) loads as a sort by label, with
|
||||
// a warning, instead of as a sort by the grand total.
|
||||
let bad = format!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"2\" selected=\"0\"><x v=\"0\"/><x v=\"1\"/></reference>");
|
||||
let (wb2, warnings) = reopen_patched(&s, |x| x.replace(one, &bad));
|
||||
let p2 = wb2.sheet(wb2.active_sheet()).unwrap().pivots.last().unwrap();
|
||||
assert_eq!(p2.rows[0].sort_by, None);
|
||||
assert!(p2.rows[0].sort_scope.is_empty());
|
||||
assert!(warnings.iter().any(|w| w.contains("scope")), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// Saves and reopens a workbook.
|
||||
fn reopen_wb(wb: &gridcraft_model::Workbook) -> gridcraft_model::Workbook {
|
||||
let bytes = crate::io::save_bytes(wb, "t.xlsx").unwrap();
|
||||
crate::io::open_bytes("t.xlsx", &bytes).unwrap().0
|
||||
}
|
||||
/// The labels in the report's first column, as computed from `wb`, keeping only `keep`.
|
||||
fn first_col(wb: &gridcraft_model::Workbook, keep: &[&str]) -> Vec<String> {
|
||||
let si = wb.active_sheet();
|
||||
let p = wb.sheet(si).unwrap().pivots.last().unwrap();
|
||||
let out = crate::pivot::compute(wb, p, si).unwrap();
|
||||
out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).filter(|l| keep.contains(&l.as_str())).collect()
|
||||
}
|
||||
const VALUES_REF: &str = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
|
||||
/// The Values-only sort scope the writer emits, as a `<references>` opening.
|
||||
fn values_only() -> String {
|
||||
format!("<references count=\"1\">{VALUES_REF}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_scope_tells_date_levels_of_one_column_apart() {
|
||||
use gridcraft_model::{PivotDateGroup, PivotField};
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Date"], "values": ["Sales"]})).unwrap();
|
||||
edit_pt(&mut s, |p| {
|
||||
let date = p.columns[0].clone();
|
||||
p.columns =
|
||||
vec![PivotField { date_group: PivotDateGroup::Years, ..date.clone() }, PivotField { date_group: PivotDateGroup::Quarters, ..date }];
|
||||
});
|
||||
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
|
||||
// Sort by the values in the 2026 › Qtr2 column: Years is cache field 5 (item 1 = 2026,
|
||||
// after "<1/15/2026"), Quarters the Date field 2 (item 2 = Qtr2). Qtr2 holds West 70,
|
||||
// East 60, North 30; the totals are East 415, West 285, North 135.
|
||||
let refs = format!(
|
||||
"<references count=\"3\">{VALUES_REF}<reference field=\"5\" count=\"1\" selected=\"0\"><x v=\"1\"/></reference><reference field=\"2\" count=\"1\" selected=\"0\"><x v=\"2\"/></reference>"
|
||||
);
|
||||
let (wb, _) = reopen_patched(&s, |x| {
|
||||
assert!(x.contains(&values_only()), "{x}");
|
||||
x.replace(&values_only(), &refs)
|
||||
});
|
||||
let regions = ["East", "West", "North"];
|
||||
assert_eq!(first_col(&wb, ®ions), ["West", "East", "North"]);
|
||||
// Saving writes both references back.
|
||||
let back = reopen_wb(&wb);
|
||||
let scope = |wb: &gridcraft_model::Workbook| wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.clone();
|
||||
assert_eq!(scope(&back).len(), 2);
|
||||
assert_eq!(scope(&back), scope(&wb));
|
||||
assert_eq!(first_col(&back, ®ions), ["West", "East", "North"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_subtotal_functions_keep_the_subtotal_rows() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
|
||||
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
|
||||
// Field Settings › Subtotals › Custom (Sum and Count) on Product, as Excel stores it.
|
||||
let (wb, warnings) = reopen_patched(&s, |x| {
|
||||
let start = x.match_indices("<pivotField ").nth(1).unwrap().0;
|
||||
let end = start + x[start..].find("</pivotField>").unwrap();
|
||||
let field = x[start..end]
|
||||
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" countSubtotal=\"1\" ", 1)
|
||||
.replace("<item t=\"default\"/>", "<item t=\"sum\"/><item t=\"count\"/>");
|
||||
assert!(field.contains("t=\"sum\""), "{field}");
|
||||
format!("{}{field}{}", &x[..start], &x[end..])
|
||||
});
|
||||
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
|
||||
assert_ne!(p.rows[1].subtotal, Some(false));
|
||||
// Shown with the automatic subtotal, with a warning.
|
||||
let plain = reopen_wb(&s.doc().unwrap().wb);
|
||||
let all = |wb: &gridcraft_model::Workbook| {
|
||||
let si = wb.active_sheet();
|
||||
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
|
||||
out.grid.iter().map(|r| r.iter().map(|c| c.value.display()).collect::<Vec<_>>()).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(all(&wb), all(&plain));
|
||||
assert!(warnings.iter().any(|w| w.contains("subtotal")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_subtotals_on_the_first_field_keep_the_table_default() {
|
||||
use std::io::Read;
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
|
||||
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
|
||||
// Custom Sum subtotal on Region (cache field 0, the first axis field), no xpdl extension.
|
||||
let (wb, _) = reopen_patched(&s, |x| {
|
||||
assert!(!x.contains("pivotTableDefinition16"), "{x}");
|
||||
let start = x.find("<pivotField ").unwrap();
|
||||
let end = start + x[start..].find("</pivotField>").unwrap();
|
||||
let field = x[start..end]
|
||||
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" ", 1)
|
||||
.replace("<item t=\"default\"/>", "<item t=\"sum\"/>");
|
||||
assert!(field.contains("t=\"sum\""), "{field}");
|
||||
format!("{}{field}{}", &x[..start], &x[end..])
|
||||
});
|
||||
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
|
||||
assert!(p.subtotals);
|
||||
assert_eq!([p.rows[0].subtotal, p.rows[1].subtotal], [None, None]);
|
||||
// Saving doesn't add a table default of "off" the file never had.
|
||||
let bytes = crate::io::save_bytes(&wb, "t.xlsx").unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
z.by_name("xl/pivotTables/pivotTable1.xml").unwrap().read_to_string(&mut xml).unwrap();
|
||||
assert!(!xml.contains("EnabledSubtotalsDefault=\"0\""), "{xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sort_scope_on_a_vanished_item_sorts_as_after_saving() {
|
||||
let mut s = sales();
|
||||
s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
|
||||
// Sorted by the values in the Kiwis column (Product item 3)…
|
||||
let refs = format!("<references count=\"2\">{VALUES_REF}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"3\"/></reference>");
|
||||
let (mut wb, _) = reopen_patched(&s, |x| x.replace(&values_only(), &refs));
|
||||
assert_eq!(wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.len(), 1);
|
||||
// …then Kiwis leaves the source: the rows sort by the grand total, before and after saving.
|
||||
let src = wb.sheets.iter().position(|sh| sh.name == "Sheet1").unwrap();
|
||||
wb.sheet_mut(src).unwrap().set_value(CellRef::parse("B14").unwrap(), Value::text("Apples"));
|
||||
let regions = ["East", "West", "North", "South"];
|
||||
let total_order = ["East", "West", "North", "South"];
|
||||
assert_eq!(first_col(&wb, ®ions), total_order);
|
||||
assert_eq!(first_col(&reopen_wb(&wb), ®ions), total_order);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_groups_not_sorted_are_in_date_order() {
|
||||
let mut s = sales();
|
||||
// The first record is in Qtr4.
|
||||
s.execute("cell.set", json!({"cell": "C2", "input": "12/1/2026"})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.group", json!({"field": "Date", "by": "quarters"})).unwrap();
|
||||
s.execute("pivot.sort", json!({"field": "Date", "order": "none"})).unwrap();
|
||||
let quarters = ["Qtr1", "Qtr2", "Qtr3", "Qtr4"];
|
||||
assert_eq!(first_col(&s.doc().unwrap().wb, &quarters), quarters);
|
||||
let back = reopen_wb(&s.doc().unwrap().wb);
|
||||
assert_eq!(first_col(&back, &quarters), quarters);
|
||||
// A reordered list still wins; items it doesn't name follow in date order.
|
||||
let mut wb = back;
|
||||
let si = wb.active_sheet();
|
||||
wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap().rows[0].item_order = vec!["Qtr3".into()];
|
||||
assert_eq!(first_col(&wb, &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
|
||||
assert_eq!(first_col(&reopen_wb(&wb), &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_order_of_time_items_from_an_excel_cache() {
|
||||
// Excel caches times as `<d v="1899-12-30T08:00:00"/>`: those items must name the
|
||||
// report's 8:00 and 9:30, or a refresh puts the blank ahead of them.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
for (cell, input) in [("A1", "Shift"), ("B1", "Sales"), ("A2", "8:00"), ("B2", "10"), ("A3", "9:30"), ("B3", "20"), ("B4", "5")] {
|
||||
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
|
||||
}
|
||||
s.execute("selection.set", json!({"range": "A1"})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"rows": ["Shift"], "values": ["Sales"]})).unwrap();
|
||||
s.execute("pivot.sort", json!({"field": "Shift", "order": "none"})).unwrap();
|
||||
// The report's first column: times as minutes, and the blank item.
|
||||
let shifts = |wb: &gridcraft_model::Workbook| -> Vec<String> {
|
||||
let si = wb.active_sheet();
|
||||
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
|
||||
out.grid
|
||||
.iter()
|
||||
.filter_map(|r| match &r.first()?.value {
|
||||
Value::Number(n) => Some(format!("{}", (n * 1440.0).round())),
|
||||
v if v.display() == "(blank)" => Some(v.display()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let order = ["480", "570", "(blank)"];
|
||||
assert_eq!(shifts(&s.doc().unwrap().wb), order);
|
||||
let excel_items = "<d v=\"1899-12-30T08:00:00\"/><d v=\"1899-12-30T09:30:00\"/><m/>";
|
||||
let (back, _) = reopen_patched_part(&s, "xl/pivotCache/pivotCacheDefinition1.xml", |x| {
|
||||
let ours = "<n v=\"0.3333333333333333\"/><n v=\"0.3958333333333333\"/><m/>";
|
||||
assert!(x.contains(ours), "{x}");
|
||||
x.replace(ours, excel_items)
|
||||
});
|
||||
assert_eq!(shifts(&back), order);
|
||||
// Saving writes that order back.
|
||||
assert_eq!(shifts(&reopen_wb(&back)), order);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
|
||||
let mut s = sales();
|
||||
s.execute("insert.pivotTable", json!({"source": "Sheet1!A1:E13", "destination": "Sheet1!H10", "rows": ["Region"], "values": ["Sales"]})).unwrap();
|
||||
assert_eq!(pt(&s).last_range.unwrap().a1(), "H10:I14");
|
||||
// Rows above the report (and below the source) move the report only.
|
||||
s.execute("home.insertRows", json!({"rows": "16:17"})).unwrap();
|
||||
s.execute("home.insertRows", json!({"rows": "6:7"})).unwrap();
|
||||
assert_eq!(text(&s, "H12"), "Row Labels");
|
||||
@@ -1166,7 +1673,6 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
|
||||
assert_eq!(l[0]["anchor"], "H12");
|
||||
assert_eq!(l[0]["range"], "H12:I16");
|
||||
assert_eq!(l[0]["source"], "Sheet1!A1:E15");
|
||||
// A row above the source moves both.
|
||||
s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap();
|
||||
let p = pt(&s);
|
||||
assert_eq!(p.source, "Sheet1!A2:E16");
|
||||
@@ -1175,12 +1681,10 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
|
||||
assert_eq!(pt(&s).last_range.unwrap().a1(), "H13:I17");
|
||||
assert_eq!(text(&s, "H13"), "Row Labels");
|
||||
assert_eq!(val(&s, "I17"), Value::Number(TOTAL));
|
||||
// Deleting a column left of the report moves it left.
|
||||
s.execute("home.deleteColumns", json!({"cols": "F:F"})).unwrap();
|
||||
let p = pt(&s);
|
||||
assert_eq!(p.anchor.a1(), "G13");
|
||||
assert_eq!(p.last_range.unwrap().a1(), "G13:H17");
|
||||
// Deleting rows above moves it up.
|
||||
s.execute("home.deleteRows", json!({"rows": "1:1"})).unwrap();
|
||||
assert_eq!(pt(&s).source, "Sheet1!A1:E15");
|
||||
assert_eq!(pt(&s).anchor.a1(), "G12");
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
|
||||
#[cfg(test)]
|
||||
use gridcraft_model::{Alignment, Image, SheetViewMode};
|
||||
use gridcraft_model::{Alignment, CellPicture, Image, SheetViewMode};
|
||||
use gridcraft_model::{
|
||||
Anchor, BorderLine, BorderStyle, Borders, Color, HAlign, Orientation, PageOrder, PatternType, PrintSettings, ReadingOrder, ShapeKind, Sheet,
|
||||
Style, StyleId, StyleTable, Underline, VAlign, Visibility, Workbook,
|
||||
@@ -34,49 +34,6 @@ use header_footer::draw_header_footer;
|
||||
pub use header_footer::{
|
||||
HF_FIELDS, HfContext, HfSection, codes_to_fields, expand_header_footer, fields_to_codes, hf_date_time, join_header_footer, split_header_footer,
|
||||
};
|
||||
type DecodedPicture = (Vec<u8>, u32, u32);
|
||||
|
||||
/// What one PDF render shares across the pages an object spans.
|
||||
#[derive(Default)]
|
||||
struct PicCache {
|
||||
/// Decoded pictures (bytes, width, height) keyed by (sheet, picture); `None` = undecodable.
|
||||
decoded: std::collections::HashMap<(usize, usize), Option<DecodedPicture>>,
|
||||
/// Laid-out charts (with their [`chart_cost`]) keyed by (sheet, chart), rendered once however
|
||||
/// many pages they touch. Only charts that can still be drawn are kept.
|
||||
charts: std::collections::HashMap<(usize, usize), (Vec<gridcraft_chart::Prim>, usize)>,
|
||||
/// Charts too big for what was left of the budget: never drawn, so not rendered again.
|
||||
rejected_charts: std::collections::HashSet<(usize, usize)>,
|
||||
/// Bytes of picture pixels embedded so far, and chart cost units emitted so far. Each page an
|
||||
/// object touches gets its own copy in the PDF, so a workbook-controlled anchor over thousands
|
||||
/// of pages would multiply them without bound.
|
||||
image_bytes: usize,
|
||||
chart_prims: usize,
|
||||
}
|
||||
|
||||
impl PicCache {
|
||||
/// The chart's primitives for one more page, or `None` once they no longer fit
|
||||
/// [`MAX_CHART_PRIMS`]. `render` runs at most once per chart; a chart that doesn't fit is
|
||||
/// dropped at once and remembered, so its vectors are never retained.
|
||||
fn chart(&mut self, key: (usize, usize), render: impl FnOnce() -> Vec<gridcraft_chart::Prim>) -> Option<&[gridcraft_chart::Prim]> {
|
||||
if self.rejected_charts.contains(&key) {
|
||||
return None;
|
||||
}
|
||||
let (prims, cost) = match self.charts.remove(&key) {
|
||||
Some(cached) => cached,
|
||||
None => {
|
||||
let prims = render();
|
||||
let cost = chart_cost(&prims);
|
||||
(prims, cost)
|
||||
}
|
||||
};
|
||||
if self.chart_prims.saturating_add(cost) > MAX_CHART_PRIMS {
|
||||
self.rejected_charts.insert(key);
|
||||
return None;
|
||||
}
|
||||
self.chart_prims += cost;
|
||||
Some(&self.charts.entry(key).or_insert((prims, cost)).0)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a chart's drawing costs in the PDF: one unit per primitive plus one per path point (a
|
||||
/// smoothed line holds thousands of points, each written out) and per point of a wedge's outline.
|
||||
@@ -93,8 +50,6 @@ fn chart_cost(prims: &[gridcraft_chart::Prim]) -> usize {
|
||||
.fold(0, usize::saturating_add)
|
||||
}
|
||||
|
||||
/// Most picture pixel bytes (RGBA, before PDF packing) one render embeds across all pages.
|
||||
const MAX_EMBEDDED_IMAGE_BYTES: usize = 512 * 1024 * 1024;
|
||||
/// Most chart cost units (primitives and path points, see [`chart_cost`]) one render draws across all pages.
|
||||
const MAX_CHART_PRIMS: usize = 4_000_000;
|
||||
|
||||
@@ -102,8 +57,8 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
|
||||
use layout::bands;
|
||||
pub(crate) use layout::split_bands;
|
||||
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
|
||||
use layout::{known_paper, seg_size, segments};
|
||||
use objects::draw_objects;
|
||||
use layout::{seg_size, segments};
|
||||
use objects::{PicCache, draw_objects};
|
||||
#[cfg(test)]
|
||||
use text::{center_across_width, wrap_lines};
|
||||
|
||||
@@ -114,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export as PDF",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{path?, sheets?: active|all, range?: \"A1:F40\" (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.",
|
||||
"{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.",
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
@@ -141,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Page Setup…",
|
||||
["Page Layout", "Page Setup"],
|
||||
None,
|
||||
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings",
|
||||
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings",
|
||||
has_doc,
|
||||
page_setup
|
||||
),
|
||||
@@ -164,7 +119,14 @@ const MISSING_ARABIC_FONT: &str = "Some Arabic text could not be drawn in this P
|
||||
|
||||
/// Renders laid-out sheets to a PDF.
|
||||
pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str) -> Result<RenderedPdf> {
|
||||
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES)
|
||||
}
|
||||
|
||||
/// [`render_pdf`] keeping at most `image_bytes` of picture data in the document (tests lower it
|
||||
/// to exercise the cap without building gigabytes of pictures).
|
||||
fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str, image_bytes: u64) -> Result<RenderedPdf> {
|
||||
let mut doc = PdfDoc::new();
|
||||
doc.set_image_budget(image_bytes);
|
||||
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();
|
||||
@@ -173,7 +135,8 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
|
||||
let mut pending_links = Vec::new();
|
||||
let mut printed_blocks = Vec::new();
|
||||
// Decoded pictures are reused across the pages their anchor covers: a floating picture
|
||||
// spanning 40 pages was decoded (and pushed into the PDF) 40 times (#2389).
|
||||
// spanning 40 pages was decoded 40 times (#2389). Each page still keeps its own copy in the
|
||||
// PDF, within the document's image budget.
|
||||
let mut pics = PicCache::default();
|
||||
for lay in layouts {
|
||||
let Some(sh) = wb.sheet(lay.sheet) else { continue };
|
||||
@@ -197,7 +160,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
|
||||
let mut x = ox + lay.heading_w * k;
|
||||
for (csi, cs) in csegs.iter().enumerate() {
|
||||
let b = make_block(wb, lay.sheet, sh, *rs, *cs, (x, y), lay);
|
||||
draw_block(pg, &b, lay.settings.gridlines, &mut cf);
|
||||
draw_block(pg, &b, lay.settings.gridlines, &mut cf, &mut pics);
|
||||
draw_block_links(pg, &b, page_index, &mut pending_links);
|
||||
printed_blocks.push(PrintedBlock {
|
||||
page: page_index,
|
||||
@@ -346,8 +309,9 @@ fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let paper = match str_param(p, "paper") {
|
||||
None => None,
|
||||
Some(name) => {
|
||||
known_paper(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?;
|
||||
Some(name.trim().to_string())
|
||||
// Stored under its table name, which every file format knows.
|
||||
let paper = gridcraft_model::paper::canonical(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?;
|
||||
Some(paper.to_string())
|
||||
}
|
||||
};
|
||||
let margin_src = p.get("margins").filter(|m| m.is_object()).unwrap_or(p);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::layout::{DENSE_BLOCK, SheetLayout};
|
||||
use super::objects::draw_cell_picture;
|
||||
use super::objects::{PicCache, draw_cell_picture};
|
||||
use super::text::{TextPlacement, draw_text};
|
||||
use super::{
|
||||
BorderLine, BorderStyle, Borders, CellRef, Color, Font, Page, PatternType, Point, RangeRef, Rgb, Sheet, Style, StyleId, Underline, Value,
|
||||
@@ -319,7 +319,7 @@ impl<'a> Covered<'a> {
|
||||
}
|
||||
|
||||
/// Draws the cells of a block: fills, gridlines, data bars, borders and text.
|
||||
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) {
|
||||
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache, pics: &mut PicCache) {
|
||||
let (bx, by) = (b.xs.first().copied().unwrap_or(0.0), b.ys.first().copied().unwrap_or(0.0));
|
||||
let (bw, bh) = (b.xs.last().copied().unwrap_or(bx) - bx, b.ys.last().copied().unwrap_or(by) - by);
|
||||
if bw <= 0.0 || bh <= 0.0 {
|
||||
@@ -434,7 +434,7 @@ pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut cra
|
||||
continue;
|
||||
}
|
||||
if let Some(picture) = sh.cell_pictures.get(c) {
|
||||
draw_cell_picture(pg, &picture.data, (b.text_x(x, w), y, w, h), b.k);
|
||||
draw_cell_picture(pg, pics, (b.si, *c), &picture.data, (b.text_x(x, w), y, w, h), b.k);
|
||||
} else if let Some(on) = checkbox_state(l, &sh.value(*c)) {
|
||||
draw_checkbox(pg, (b.text_x(x, w), y, w, h), b.k, on);
|
||||
} else {
|
||||
|
||||
@@ -9,43 +9,10 @@ pub(super) const DENSE_BLOCK: u64 = 60_000;
|
||||
|
||||
// ---------------------------------------------------------------- paper
|
||||
|
||||
/// Paper size in points (portrait) for a paper name; unknown names fall back to Letter.
|
||||
/// Paper size in points, as named (see `gridcraft_model::paper`); unknown names, and the empty
|
||||
/// name of a file that stated no paper, fall back to Letter.
|
||||
pub fn paper_size(name: &str) -> (f32, f32) {
|
||||
known_paper(name).unwrap_or((612.0, 792.0))
|
||||
}
|
||||
|
||||
/// Paper sizes in points, portrait. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel and its
|
||||
/// e-mail attachments use (257×364, 182×257 and 128×182 mm); the ISO B series stays reachable as
|
||||
/// `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and envelopes are the JIS ones too.
|
||||
pub(super) fn known_paper(name: &str) -> Option<(f32, f32)> {
|
||||
// Spaces, hyphens, underscores and parentheses don't matter: `B5 (JIS)`, `b5-jis` and `b5`
|
||||
// are one name.
|
||||
let n = name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], "");
|
||||
Some(match n.as_str() {
|
||||
"letter" | "usletter" => (612.0, 792.0),
|
||||
"legal" | "uslegal" => (612.0, 1008.0),
|
||||
"a4" => (595.28, 841.89),
|
||||
"a3" => (841.89, 1190.55),
|
||||
"a5" => (419.53, 595.28),
|
||||
"a6" => (297.64, 419.53),
|
||||
"tabloid" | "11x17" => (792.0, 1224.0),
|
||||
"ledger" => (1224.0, 792.0),
|
||||
"executive" => (522.0, 756.0),
|
||||
"b4" | "b4jis" => (728.50, 1031.81),
|
||||
"b5" | "b5jis" => (515.91, 728.50),
|
||||
"b6" | "b6jis" => (362.83, 515.91),
|
||||
"b4iso" => (708.66, 1000.63),
|
||||
"b5iso" => (498.90, 708.66),
|
||||
"b6iso" => (354.33, 498.90),
|
||||
"japanesepostcard" | "postcard" => (283.46, 419.53),
|
||||
"japanesedoublepostcard" | "doublepostcard" => (419.53, 566.93),
|
||||
"japaneseenvelope#3" | "chou#3" => (340.16, 666.14),
|
||||
// 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out.
|
||||
"japaneseenvelope#4" | "chou#4" => (255.12, 581.10),
|
||||
"japaneseenvelopekaku#2" | "kaku#2" => (680.31, 941.10),
|
||||
"japaneseenvelopekaku#3" | "kaku#3" => (612.28, 785.20),
|
||||
_ => return None,
|
||||
})
|
||||
gridcraft_model::paper::size_pt(name).unwrap_or((612.0, 792.0))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- layout
|
||||
@@ -103,7 +70,8 @@ impl SheetLayout {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PrintOptions {
|
||||
pub all_sheets: bool,
|
||||
pub range: Option<RangeRef>,
|
||||
/// Areas of the active sheet to print instead of its print area, in order (Print Selection).
|
||||
pub ranges: Vec<RangeRef>,
|
||||
pub fit_to_page: Option<bool>,
|
||||
}
|
||||
|
||||
@@ -114,14 +82,35 @@ impl PrintOptions {
|
||||
Some("all") | Some("workbook") => true,
|
||||
Some(other) => return Err(bad(cmd, format!("`sheets` must be active or all, not `{other}`"))),
|
||||
};
|
||||
let range = match str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) {
|
||||
Some(r) => Some(RangeRef::parse(split_sheet(r).1).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?),
|
||||
None => None,
|
||||
};
|
||||
Ok(PrintOptions { all_sheets, range, fit_to_page: bool_param(p, "fitToPage") })
|
||||
let mut ranges = Vec::new();
|
||||
if let Some(r) = str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) {
|
||||
for part in split_areas(r) {
|
||||
ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?);
|
||||
}
|
||||
}
|
||||
Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") })
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits a multi-area reference at the commas outside quoted sheet names, so each area keeps
|
||||
/// its own optional `Sheet!` prefix.
|
||||
fn split_areas(r: &str) -> Vec<&str> {
|
||||
let mut parts = Vec::new();
|
||||
let (mut start, mut quoted) = (0, false);
|
||||
for (i, c) in r.char_indices() {
|
||||
match c {
|
||||
'\'' => quoted = !quoted,
|
||||
',' if !quoted => {
|
||||
parts.push(&r[start..i]);
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
parts.push(&r[start..]);
|
||||
parts
|
||||
}
|
||||
|
||||
/// The range a sheet prints: its print area, else the used range grown to cover drawing
|
||||
/// objects. `None` when there is nothing to print.
|
||||
pub fn print_range(sh: &Sheet) -> Option<RangeRef> {
|
||||
@@ -354,14 +343,20 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
if pages >= MAX_PAGES {
|
||||
break;
|
||||
}
|
||||
let ovr = if si == wb.active_sheet() { opts.range } else { None };
|
||||
if opts.all_sheets && ovr.is_none() && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) {
|
||||
let areas: Vec<Option<RangeRef>> =
|
||||
if si == wb.active_sheet() && !opts.ranges.is_empty() { opts.ranges.iter().copied().map(Some).collect() } else { vec![None] };
|
||||
if opts.all_sheets && areas == [None] && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(mut l) = layout_sheet(wb, si, opts, ovr) {
|
||||
l.pages.truncate(MAX_PAGES - pages);
|
||||
pages += l.pages.len();
|
||||
out.push(l);
|
||||
for ovr in areas {
|
||||
if pages >= MAX_PAGES {
|
||||
break;
|
||||
}
|
||||
if let Some(mut l) = layout_sheet(wb, si, opts, ovr) {
|
||||
l.pages.truncate(MAX_PAGES - pages);
|
||||
pages += l.pages.len();
|
||||
out.push(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.is_empty() && opts.all_sheets {
|
||||
|
||||
@@ -1,9 +1,94 @@
|
||||
use super::draw::{Block, PdfMeasure, Xf, draw_prims, rgb_of};
|
||||
use super::text::wrap_lines;
|
||||
use super::{Anchor, Baseline, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
|
||||
use super::{Anchor, Baseline, CellRef, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::hash_map::Entry;
|
||||
|
||||
/// A decoded picture: RGBA pixels, width, height.
|
||||
type Decoded = (Vec<u8>, u32, u32);
|
||||
|
||||
/// Most bytes of decoded pictures one render memoizes; a picture decoded past it is used once
|
||||
/// and dropped (and decoded again on the next page that prints it).
|
||||
const MAX_PIC_CACHE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum PicKey {
|
||||
/// A floating picture: sheet index and position in `Sheet::images`.
|
||||
Floating(usize, usize),
|
||||
/// A cell picture: sheet index, cell and the thumbnail size it is decoded at.
|
||||
Cell(usize, CellRef, u32, u32),
|
||||
}
|
||||
|
||||
/// Decoded pictures reused across the pages (and repeated title rows) that print them, so a
|
||||
/// picture is decoded once per render instead of once per page (#2389).
|
||||
#[derive(Default)]
|
||||
pub(super) struct PicCache {
|
||||
map: std::collections::HashMap<PicKey, Option<Decoded>>,
|
||||
/// Bytes of pixels in `map`.
|
||||
bytes: u64,
|
||||
/// Laid-out charts (with their [`chart_cost`](super::chart_cost)) keyed by (sheet, chart),
|
||||
/// rendered once however many pages they touch. Only charts that can still be drawn are kept.
|
||||
pub(super) charts: std::collections::HashMap<(usize, usize), (Vec<gridcraft_chart::Prim>, usize)>,
|
||||
/// Charts too big for what was left of the budget: never drawn, so not rendered again.
|
||||
pub(super) rejected_charts: std::collections::HashSet<(usize, usize)>,
|
||||
/// Chart cost units emitted so far. Each page a chart touches gets its own copy in the PDF,
|
||||
/// so a workbook-controlled anchor over thousands of pages would multiply them without bound.
|
||||
pub(super) chart_prims: usize,
|
||||
}
|
||||
|
||||
impl PicCache {
|
||||
/// The decoded picture for `key`, running `decode` the first time. A failed decode is
|
||||
/// remembered too; a decode that does not fit in the cache is returned without being kept.
|
||||
fn get(&mut self, key: PicKey, decode: impl FnOnce() -> Option<Decoded>) -> Option<Cow<'_, Decoded>> {
|
||||
let slot = match self.map.entry(key) {
|
||||
Entry::Occupied(e) => e.into_mut(),
|
||||
Entry::Vacant(e) => {
|
||||
let decoded = decode();
|
||||
let size = decoded.as_ref().map_or(0, |d| d.0.len() as u64);
|
||||
if self.bytes.saturating_add(size) > MAX_PIC_CACHE_BYTES {
|
||||
return decoded.map(Cow::Owned);
|
||||
}
|
||||
self.bytes = self.bytes.saturating_add(size);
|
||||
e.insert(decoded)
|
||||
}
|
||||
};
|
||||
slot.as_ref().map(Cow::Borrowed)
|
||||
}
|
||||
|
||||
/// The chart's primitives for one more page, or `None` once they no longer fit
|
||||
/// [`MAX_CHART_PRIMS`](super::MAX_CHART_PRIMS). `render` runs at most once per chart; a chart
|
||||
/// that doesn't fit is dropped at once and remembered, so its vectors are never retained.
|
||||
pub(super) fn chart(&mut self, key: (usize, usize), render: impl FnOnce() -> Vec<gridcraft_chart::Prim>) -> Option<&[gridcraft_chart::Prim]> {
|
||||
if self.rejected_charts.contains(&key) {
|
||||
return None;
|
||||
}
|
||||
let (prims, cost) = match self.charts.remove(&key) {
|
||||
Some(cached) => cached,
|
||||
None => {
|
||||
let prims = render();
|
||||
let cost = super::chart_cost(&prims);
|
||||
(prims, cost)
|
||||
}
|
||||
};
|
||||
if self.chart_prims.saturating_add(cost) > super::MAX_CHART_PRIMS {
|
||||
self.rejected_charts.insert(key);
|
||||
return None;
|
||||
}
|
||||
self.chart_prims += cost;
|
||||
Some(&self.charts.entry(key).or_insert((prims, cost)).0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a picture decoded into at most `max_w`×`max_h` pixels can still be kept by the PDF.
|
||||
/// The document's image room only shrinks while it is built, so a picture refused here would be
|
||||
/// refused on every later page too and is not decoded at all.
|
||||
fn fits(room: u64, max_w: u32, max_h: u32) -> bool {
|
||||
u64::from(max_w).saturating_mul(u64::from(max_h)).saturating_mul(4) <= room
|
||||
}
|
||||
|
||||
/// Cell pictures fit the current cell (or merged-cell) rectangle without changing aspect ratio.
|
||||
pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32, f32), k: f32) {
|
||||
/// `at` (sheet index and cell) keys the decode in `pics`.
|
||||
pub(super) fn draw_cell_picture(pg: &mut Page, pics: &mut PicCache, at: (usize, CellRef), data: &[u8], rect: (f32, f32, f32, f32), k: f32) {
|
||||
let (x, y, w, h) = rect;
|
||||
let pad = 2.0 * k;
|
||||
let (w, h) = ((w - 2.0 * pad).max(0.0), (h - 2.0 * pad).max(0.0));
|
||||
@@ -14,18 +99,30 @@ pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32
|
||||
if iw == 0 || ih == 0 || iw > 8192 || ih > 8192 || u64::from(iw) * u64::from(ih) > 16_000_000 {
|
||||
return;
|
||||
}
|
||||
let Ok(mut reader) = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format() else { return };
|
||||
let (tw, th) = (((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32);
|
||||
let room = pg.image_room();
|
||||
let Some(image) = pics.get(PicKey::Cell(at.0, at.1, tw, th), || decode_cell_picture(data, tw, th, room)) else { return };
|
||||
let (px, px_w, px_h) = &*image;
|
||||
let fit = (w / iw as f32).min(h / ih as f32);
|
||||
let (pw, ph) = (iw as f32 * fit, ih as f32 * fit);
|
||||
pg.image_rgba(Rect::new(x + pad + (w - pw) / 2.0, y + pad + (h - ph) / 2.0, pw, ph), px, [*px_w, *px_h]);
|
||||
}
|
||||
|
||||
/// Decodes a cell picture to RGBA scaled to fit `tw`×`th` pixels, unless the PDF has no `room`
|
||||
/// left for it.
|
||||
fn decode_cell_picture(data: &[u8], tw: u32, th: u32, room: u64) -> Option<Decoded> {
|
||||
if !fits(room, tw, th) {
|
||||
return None;
|
||||
}
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(8192);
|
||||
limits.max_image_height = Some(8192);
|
||||
limits.max_alloc = Some(64 * 1024 * 1024);
|
||||
reader.limits(limits);
|
||||
let Ok(image) = reader.decode() else { return };
|
||||
let image =
|
||||
image.thumbnail(((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32).to_rgba8();
|
||||
let fit = (w / iw as f32).min(h / ih as f32);
|
||||
let (pw, ph) = (iw as f32 * fit, ih as f32 * fit);
|
||||
pg.image_rgba(Rect::new(x + pad + (w - pw) / 2.0, y + pad + (h - ph) / 2.0, pw, ph), image.as_raw(), [image.width(), image.height()]);
|
||||
let image = reader.decode().ok()?.thumbnail(tw, th).to_rgba8();
|
||||
let (pw, ph) = (image.width(), image.height());
|
||||
Some((image.into_raw(), pw, ph))
|
||||
}
|
||||
|
||||
/// Sheet pixel rectangle of an anchor.
|
||||
@@ -53,10 +150,11 @@ fn anchor_rect(sh: &Sheet, a: &Anchor) -> (f64, f64, f64, f64) {
|
||||
(sh.col_left(a.cell.col) + a.dx as f64, sh.row_top(a.cell.row) + a.dy as f64, a.width.max(0.0) as f64, a.height.max(0.0) as f64)
|
||||
}
|
||||
|
||||
/// Decodes an embedded picture to RGBA, downscaled to at most `max_w`×`max_h` pixels.
|
||||
fn decode_image(data: &[u8], max_w: u32, max_h: u32) -> Option<(Vec<u8>, u32, u32)> {
|
||||
/// Decodes an embedded picture to RGBA, downscaled to at most `max_w`×`max_h` pixels, unless the
|
||||
/// PDF has no `room` left for it.
|
||||
fn decode_image(data: &[u8], max_w: u32, max_h: u32, room: u64) -> Option<Decoded> {
|
||||
let (w, h) = crate::io::image_size(data)?;
|
||||
if w == 0 || h == 0 || w as u64 * h as u64 > 60_000_000 {
|
||||
if w == 0 || h == 0 || w as u64 * h as u64 > 60_000_000 || !fits(room, w.min(max_w.max(1)), h.min(max_h.max(1))) {
|
||||
return None;
|
||||
}
|
||||
let img = image::load_from_memory(data).ok()?;
|
||||
@@ -69,7 +167,7 @@ fn decode_image(data: &[u8], max_w: u32, max_h: u32) -> Option<(Vec<u8>, u32, u3
|
||||
/// Draws charts, pictures, shapes and sparklines overlapping the body block of a page.
|
||||
/// `pics` memoizes decoded pictures for the whole render (one page at a time draws each
|
||||
/// picture again, but the decode happens once).
|
||||
pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block, pics: &mut super::PicCache) {
|
||||
pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block, pics: &mut PicCache) {
|
||||
let block = b.range();
|
||||
let (sx0, sy0) = (sh.col_left(block.start.col), sh.row_top(block.start.row));
|
||||
let (sx1, sy1) = (sh.col_left(block.end.col.saturating_add(1)), sh.row_top(block.end.row.saturating_add(1)));
|
||||
@@ -90,14 +188,10 @@ pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet,
|
||||
let (x, y, w, h) = place(r);
|
||||
// About 150 dpi is plenty for print.
|
||||
let (mw, mh) = (((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32);
|
||||
let decoded = pics.decoded.entry((si, imi)).or_insert_with(|| decode_image(&im.data, mw, mh));
|
||||
if let Some((px, pw, ph)) = decoded.as_ref() {
|
||||
// Every page the picture touches embeds its own copy: past the budget it is left out.
|
||||
let bytes = px.len();
|
||||
if pics.image_bytes.saturating_add(bytes) <= super::MAX_EMBEDDED_IMAGE_BYTES {
|
||||
pics.image_bytes += bytes;
|
||||
pg.image_rgba(Rect::new(x, y, w, h), px, [*pw, *ph]);
|
||||
}
|
||||
let room = pg.image_room();
|
||||
if let Some(decoded) = pics.get(PicKey::Floating(si, imi), || decode_image(&im.data, mw, mh, room)) {
|
||||
let (px, pw, ph) = &*decoded;
|
||||
pg.image_rgba(Rect::new(x, y, w, h), px, [*pw, *ph]);
|
||||
}
|
||||
}
|
||||
for shp in &sh.shapes {
|
||||
|
||||
@@ -248,7 +248,7 @@ fn rtl_sheet_sparkline_reflects_with_cell_geometry() {
|
||||
color: Color::rgb(255, 0, 0),
|
||||
markers: false,
|
||||
});
|
||||
let options = PrintOptions { range: RangeRef::parse("A1:B2"), ..PrintOptions::default() };
|
||||
let options = PrintOptions { ranges: RangeRef::parse("A1:B2").into_iter().collect(), ..PrintOptions::default() };
|
||||
let ltr = render_pdf(&wb, &layouts(&wb, &options), "", "").unwrap().bytes;
|
||||
wb.sheet_mut(0).unwrap().right_to_left = true;
|
||||
let rtl = render_pdf(&wb, &layouts(&wb, &options), "", "").unwrap().bytes;
|
||||
@@ -779,6 +779,98 @@ fn charts_and_images_are_drawn() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of pixel data the pages of a PDF hold: 3 per RGB pixel plus 1 per soft-mask pixel, for
|
||||
/// every image each page references. The writer shares identical images across pages, but each
|
||||
/// page kept its own copy while the document was built, so a shared image counts once per page.
|
||||
fn image_bytes(pdf: &[u8]) -> u64 {
|
||||
let text = String::from_utf8_lossy(pdf);
|
||||
let num_after = |s: &str, key: &str| -> u64 {
|
||||
let at = s.find(key).unwrap() + key.len();
|
||||
s[at..].split_whitespace().next().unwrap().parse().unwrap()
|
||||
};
|
||||
// Object id → (pixel bytes, soft mask id).
|
||||
let mut images = std::collections::HashMap::new();
|
||||
let mut pages = vec![];
|
||||
for obj in text.split("endobj").filter(|o| o.contains(" 0 obj")) {
|
||||
let head = &obj[..obj.find(" 0 obj").unwrap()];
|
||||
let id: u64 = head.split_whitespace().last().unwrap().parse().unwrap();
|
||||
let dict = &obj[..obj.find(">>").unwrap_or(obj.len())];
|
||||
if dict.contains("/Subtype /Image") {
|
||||
let bytes = num_after(dict, "/Width ") * num_after(dict, "/Height ") * if dict.contains("/DeviceRGB") { 3 } else { 1 };
|
||||
let smask = dict.contains("/SMask ").then(|| num_after(dict, "/SMask "));
|
||||
images.insert(id, (bytes, smask));
|
||||
} else if obj.contains("/Type /Page /Parent") {
|
||||
pages.push(obj);
|
||||
}
|
||||
}
|
||||
let with_mask = |id: u64| -> u64 {
|
||||
let (bytes, smask) = images[&id];
|
||||
bytes + smask.map_or(0, |m| images[&m].0)
|
||||
};
|
||||
pages
|
||||
.iter()
|
||||
.filter_map(|page| page.find("/XObject << ").map(|at| &page[at + "/XObject << ".len()..]))
|
||||
.map(|refs| {
|
||||
let refs = &refs[..refs.find(">>").unwrap()];
|
||||
let tokens: Vec<&str> = refs.split_whitespace().collect();
|
||||
tokens.chunks(4).map(|c| with_mask(c[1].parse().unwrap())).sum::<u64>()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// A picture anchored across many pages keeps no more copies in the PDF than the image budget
|
||||
/// allows, and the export still succeeds.
|
||||
#[test]
|
||||
fn picture_copies_across_pages_stay_within_the_image_budget() {
|
||||
// Each page a picture overlaps kept its own decoded copy in the PDF with no document-wide
|
||||
// bound: a 3 KB workbook with one tall picture reached 2 GiB before running out of pages.
|
||||
let mut s = s();
|
||||
let mut png = Vec::new();
|
||||
let img = image::RgbaImage::from_pixel(64, 64, image::Rgba([10, 120, 200, 255]));
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "Title"})).unwrap();
|
||||
s.execute("pageLayout.pageSetup", json!({"titleRows": "1:1"})).unwrap();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
let id = wb.next_object_id();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
// A floating picture over some 20 pages, and a cell picture in the title row on every page.
|
||||
sh.images.push(Image {
|
||||
id,
|
||||
anchor: Anchor { cell: CellRef::new(1, 1), dx: 0.0, dy: 0.0, width: 200.0, height: 19_990.0, mode: gridcraft_model::AnchorMode::MoveAndSize },
|
||||
data: std::sync::Arc::new(png.clone()),
|
||||
mime: "image/png".into(),
|
||||
alt: String::new(),
|
||||
});
|
||||
// `set_picture` gives C1 the cell value `draw_block` needs to reach the picture at all.
|
||||
sh.set_picture(CellRef::new(0, 2), std::sync::Arc::new(CellPicture { data: png, mime: "image/png".into(), alt: String::new() }));
|
||||
let d = s.doc().unwrap();
|
||||
let lays = layouts(&d.wb, &PrintOptions::from_params(&json!({}), "file.exportPdf").unwrap());
|
||||
|
||||
let RenderedPdf { bytes: full, pages, .. } = render_pdf(&d.wb, &lays, "t", "").unwrap();
|
||||
assert!(pages >= 15, "{pages} pages");
|
||||
// Within the default budget every page draws (and holds while the PDF is built) its own copy.
|
||||
// Identical copies are written to the file once, so the draws are what to count.
|
||||
let draws = |pdf: &[u8]| String::from_utf8_lossy(pdf).matches(" Do Q").count();
|
||||
let full_draws = draws(&full);
|
||||
// The cell picture, on its own: the same render without it draws one picture fewer per page.
|
||||
let mut floating_only = (*d.wb).clone();
|
||||
floating_only.sheet_mut(0).unwrap().cell_pictures.clear();
|
||||
let floating_draws = draws(&render_pdf(&floating_only, &lays, "t", "").unwrap().bytes);
|
||||
assert!(floating_draws >= pages - 1, "{floating_draws} floating picture draws on {pages} pages");
|
||||
assert_eq!(full_draws - floating_draws, pages, "the title-row cell picture draws once on each of {pages} pages");
|
||||
|
||||
// 64×64 RGB is 12,288 bytes: a 64 KiB budget holds a handful of page copies, not one per page.
|
||||
let budget = 64 * 1024;
|
||||
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget).unwrap();
|
||||
assert_eq!(capped_pages, pages, "pages past the budget still print, without the pictures");
|
||||
let capped_draws = draws(&capped);
|
||||
assert!((1..full_draws / 2).contains(&capped_draws), "{capped_draws} of {full_draws} picture draws kept with a {budget}-byte budget");
|
||||
let kept = image_bytes(&capped);
|
||||
assert!((1..=budget).contains(&kept), "{kept} bytes of images kept with a {budget}-byte budget");
|
||||
assert!(contains(&capped, "%%EOF"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_setup_edits_settings() {
|
||||
let mut s = s();
|
||||
@@ -882,6 +974,48 @@ fn page_setup_paper_sizes_reach_the_pdf_page() {
|
||||
assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err());
|
||||
}
|
||||
|
||||
/// An empty paper name means no paper is stated; it prints on Letter.
|
||||
#[test]
|
||||
fn an_unstated_paper_prints_on_letter() {
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[0]).set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into()));
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[0]).print.paper = String::new();
|
||||
let layouts = super::layout::layouts(&wb, &super::layout::PrintOptions::default());
|
||||
let l = &layouts[0];
|
||||
assert_eq!((l.page_w, l.page_h), (612.0, 792.0));
|
||||
assert_eq!(paper_size(""), (612.0, 792.0));
|
||||
}
|
||||
|
||||
/// Both commands that set the paper store a known one under its table name, so every file
|
||||
/// format finds it.
|
||||
#[test]
|
||||
fn paper_size_commands_store_the_table_name() {
|
||||
let mut s = s();
|
||||
s.execute("pageLayout.size", json!({"paper": "b5-jis"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "B5");
|
||||
s.execute("pageLayout.pageSetup", json!({"paper": "11x17"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "Tabloid");
|
||||
// Statement and the envelopes XLSX names are accepted by both commands (Page Setup refused
|
||||
// them before), stored under their table name and printed on their own size.
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["x"]]})).unwrap();
|
||||
let close = |v: &Json, want: f64| (v.as_f64().unwrap() - want).abs() < 0.01;
|
||||
for (cmd, given, stored, w, h) in [
|
||||
("pageLayout.pageSetup", "statement", "Statement", 396.0, 612.0),
|
||||
("pageLayout.pageSetup", "envelope #10", "Envelope #10", 297.0, 684.0),
|
||||
("pageLayout.pageSetup", "Envelope-DL", "Envelope DL", 311.81, 623.62),
|
||||
("pageLayout.size", "Statement", "Statement", 396.0, 612.0),
|
||||
("pageLayout.size", "envelope dl", "Envelope DL", 311.81, 623.62),
|
||||
] {
|
||||
s.execute(cmd, json!({"paper": given})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, stored, "{cmd} {given}");
|
||||
let pv = s.execute("file.printPreview", json!({})).unwrap();
|
||||
let page = &pv["pageList"][0];
|
||||
assert!(close(&page["width"], w) && close(&page["height"], h), "{cmd} {given}: {page}");
|
||||
}
|
||||
// A new workbook still prints on Letter.
|
||||
assert_eq!(gridcraft_model::Workbook::new().sheets[0].print.paper, "Letter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_settings_never_panic_and_cap_pages() {
|
||||
let mut s = s();
|
||||
@@ -1234,7 +1368,8 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
|
||||
// A smoothed line is its points, not one unit.
|
||||
assert_eq!(chart_cost(&[line(4000), Prim::Circle { cx: 0.0, cy: 0.0, r: 1.0, fill: None, stroke: None }]), 4002);
|
||||
// Room for exactly two copies of a 1,000-point chart.
|
||||
let mut pics = PicCache { chart_prims: MAX_CHART_PRIMS - 2002, ..Default::default() };
|
||||
let mut pics = PicCache::default();
|
||||
pics.chart_prims = MAX_CHART_PRIMS - 2002;
|
||||
let mut renders = 0;
|
||||
for expect in [true, true, false, false] {
|
||||
let got = pics.chart((0, 0), || {
|
||||
@@ -1246,7 +1381,76 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
|
||||
assert_eq!(renders, 1, "a rejected chart is not rendered again");
|
||||
assert!(pics.charts.is_empty(), "and its primitives are not kept");
|
||||
// A chart too big for what is left is dropped without being cached at all.
|
||||
let mut pics = PicCache { chart_prims: MAX_CHART_PRIMS - 10, ..Default::default() };
|
||||
let mut pics = PicCache::default();
|
||||
pics.chart_prims = MAX_CHART_PRIMS - 10;
|
||||
assert!(pics.chart((0, 1), || vec![line(1000)]).is_none());
|
||||
assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1)));
|
||||
}
|
||||
|
||||
fn preview_ranges(s: &mut Session, p: Json) -> Vec<String> {
|
||||
let r = s.execute("file.printPreview", p).unwrap();
|
||||
r["pageList"].as_array().unwrap().iter().map(|pg| pg["range"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "H20", "input": "y"})).unwrap();
|
||||
s.execute("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap();
|
||||
assert_eq!(preview_ranges(&mut s, json!({})), ["F10:H20"]);
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]);
|
||||
// Several areas, like a multi-area selection: one run of pages each, in the order given.
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]);
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"}));
|
||||
assert_eq!(pages, 2);
|
||||
for bad in ["A1:B2,", "A1:B2,nope", ","] {
|
||||
assert!(s.execute("file.printPreview", json!({"range": bad})).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_qualifier_on_a_later_area_does_not_swallow_the_earlier_ones() {
|
||||
let mut s = s();
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
// A comma inside a quoted sheet name is not an area separator.
|
||||
assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,'a,b'!D4:E5"})), ["A1:B2", "D4:E5"]);
|
||||
}
|
||||
|
||||
/// XLSX id 34 is ISO B5 (176 × 250 mm), not the Letter fallback of the old name.
|
||||
#[test]
|
||||
fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() {
|
||||
use std::io::{Cursor, Read, Write};
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into()));
|
||||
wb.sheet_mut(0).unwrap().print.paper = "Legal".into();
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap();
|
||||
let mut input = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap();
|
||||
let mut output = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..input.len() {
|
||||
let mut part = input.by_index(i).unwrap();
|
||||
let mut data = Vec::new();
|
||||
part.read_to_end(&mut data).unwrap();
|
||||
let name = part.name().unwrap().to_string();
|
||||
if name == "xl/worksheets/sheet1.xml" {
|
||||
let xml = String::from_utf8(data).unwrap();
|
||||
assert!(xml.contains(r#"paperSize="5""#));
|
||||
// Set the input id independently of the shared paper-name mapping under test.
|
||||
data = xml.replace(r#"paperSize="5""#, r#"paperSize="34""#).into_bytes();
|
||||
}
|
||||
output.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||
output.write_all(&data).unwrap();
|
||||
}
|
||||
let bytes = output.finish().unwrap().into_inner();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.open", json!({"name": "iso-b5.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap();
|
||||
let preview = s.execute("file.printPreview", json!({})).unwrap();
|
||||
let page = &preview["pageList"][0];
|
||||
assert!((page["width"].as_f64().unwrap() - 498.90).abs() < 0.01, "{page}");
|
||||
assert!((page["height"].as_f64().unwrap() - 708.66).abs() < 0.01, "{page}");
|
||||
let (pdf, pages) = pdf_of(&mut s, json!({}));
|
||||
assert_eq!(pages, 1);
|
||||
assert!(contains(&pdf, "/MediaBox [0 0 498.9 708.66]"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! Quick Analysis › Totals: appends totals (or per-cell percentages / running totals) next to a
|
||||
//! block of numbers as ordinary formulas, in one undoable edit. The popup in the UI
|
||||
//! (`ui.quickAnalysis`) is a thin front end for this command; the control channel, CLI and MCP
|
||||
//! call it directly. The layout is GridCraft's own: aggregates go in the row below the block (or
|
||||
//! the column to its right), per-cell results in a block of the same shape next to it.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef};
|
||||
use gridcraft_model::{Color, NumFmt, Sparkline, SparklineKind};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, PROTECTED, Result, Session, bad, bool_param, cmd, edit, has_doc, str_param, target_range, target_sheet};
|
||||
|
||||
const CMD: &str = "analysis.addTotal";
|
||||
const SPARK: &str = "analysis.addSparklines";
|
||||
/// Most sparklines one call may add.
|
||||
const MAX_SPARKLINES: u64 = 10_000;
|
||||
/// Most cells one call may write (a per-cell block on a huge selection is refused).
|
||||
const MAX_OUTPUT_CELLS: u64 = 200_000;
|
||||
/// Largest block (after clipping to the used range) the command scans for numbers.
|
||||
const MAX_SCAN_CELLS: u64 = 5_000_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"analysis.addTotal",
|
||||
"Add Totals",
|
||||
[],
|
||||
None,
|
||||
"{function?: sum|average|count|min|max|percentTotal|runningTotal (default sum), direction?: columns|rows (default columns: one result per column, below the block; rows: one per row, right of it; percentTotal and runningTotal write a block of the same shape to the right (columns) or below (rows)), range?: \"A1:C9\" (default: the selection; limited to the used range), overwrite?: bool (else non-empty output cells are refused)} → {function, direction, output, cells}. Quick Analysis › Totals. A header row (columns) or label column (rows) is skipped; columns without numbers get no total. One undo step.",
|
||||
has_doc,
|
||||
add_total
|
||||
),
|
||||
cmd!(
|
||||
"analysis.addSparklines",
|
||||
"Add Sparklines",
|
||||
[],
|
||||
None,
|
||||
"{type?: line|column|winLoss (default line), direction?: rows|columns (default rows: one sparkline per row, in the column right of the block; columns: one per column, in the row below), markers?: bool, range?: \"A1:F9\" (default: the selection; limited to the used range), overwrite?: bool} → {output, sparklines}. Quick Analysis › Sparklines. A header row (columns) or label column (rows) is skipped; lines without numbers get none. One undo step.",
|
||||
has_doc,
|
||||
add_sparklines
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Func {
|
||||
Aggregate(&'static str),
|
||||
Percent,
|
||||
Running,
|
||||
}
|
||||
|
||||
fn parse_func(name: &str) -> Result<Func> {
|
||||
Ok(match name.to_ascii_lowercase().replace(['_', '-', ' ', '%'], "").as_str() {
|
||||
"sum" => Func::Aggregate("SUM"),
|
||||
"average" | "avg" => Func::Aggregate("AVERAGE"),
|
||||
"count" => Func::Aggregate("COUNT"),
|
||||
"min" => Func::Aggregate("MIN"),
|
||||
"max" => Func::Aggregate("MAX"),
|
||||
"percenttotal" | "percent" => Func::Percent,
|
||||
"runningtotal" | "running" => Func::Running,
|
||||
_ => return Err(bad(CMD, format!("unknown function `{name}` (use sum, average, count, min, max, percentTotal or runningTotal)"))),
|
||||
})
|
||||
}
|
||||
|
||||
/// The block a Quick Analysis result is computed from.
|
||||
struct Block {
|
||||
sheet: usize,
|
||||
/// The selection clipped to the used range.
|
||||
range: RangeRef,
|
||||
/// `range` without its header row (columns) or label column (rows).
|
||||
data: RangeRef,
|
||||
/// The columns (or, `by_rows`, the rows) of `data` that hold numbers.
|
||||
lines: BTreeSet<u32>,
|
||||
by_rows: bool,
|
||||
/// Last row / column the results must stay clear of: the selection's own far edge, so a
|
||||
/// selection reaching past the data still gets its results outside it. Whole rows or columns
|
||||
/// (reaching the sheet limit) fall back to the clipped range.
|
||||
edge: CellRef,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn cell_at(&self, line: u32, i: u32) -> CellRef {
|
||||
if self.by_rows { CellRef::new(line, i) } else { CellRef::new(i, line) }
|
||||
}
|
||||
/// First and last position along a line of `data`.
|
||||
fn span_of_line(&self) -> (u32, u32) {
|
||||
if self.by_rows { (self.data.start.col, self.data.end.col) } else { (self.data.start.row, self.data.end.row) }
|
||||
}
|
||||
fn line_range(&self, line: u32, from: u32, to: u32) -> RangeRef {
|
||||
RangeRef::new(self.cell_at(line, from), self.cell_at(line, to))
|
||||
}
|
||||
}
|
||||
|
||||
fn block(s: &Session, p: &Json, by_rows: bool, cmd: &str) -> Result<Block> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
let sel = match str_param(p, "range") {
|
||||
Some(_) => target_range(s, p)?,
|
||||
None => {
|
||||
// Never guess from the current area of a multi-area selection.
|
||||
if s.doc()?.selection.ranges.len() > 1 {
|
||||
return Err(bad(cmd, "select a single contiguous range"));
|
||||
}
|
||||
s.doc()?.selection.current()
|
||||
}
|
||||
};
|
||||
if sel.is_single() {
|
||||
return Err(bad(cmd, "select at least two cells"));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
// Whole rows / columns are limited to what holds data.
|
||||
let used = sh.cells.used_range().ok_or_else(|| EngineError::Other("There is no data to analyse.".into()))?;
|
||||
let r = sel.intersection(&used).ok_or_else(|| EngineError::Other("There is no data to analyse in the selection.".into()))?;
|
||||
if r.count() > MAX_SCAN_CELLS {
|
||||
return Err(bad(cmd, "selection too large to analyse"));
|
||||
}
|
||||
let is_num = |c: CellRef| sh.value(c).is_number();
|
||||
let is_text = |c: CellRef| sh.value(c).is_text();
|
||||
// Header row (columns) / label column (rows): text only, with at least one entry.
|
||||
let lead: Vec<CellRef> = if by_rows {
|
||||
(r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect()
|
||||
} else {
|
||||
(r.start.col..=r.end.col).map(|c| CellRef::new(r.start.row, c)).collect()
|
||||
};
|
||||
let longer_than_one = if by_rows { r.width() > 1 } else { r.height() > 1 };
|
||||
let has_label = longer_than_one && lead.iter().any(|c| is_text(*c)) && !lead.iter().any(|c| is_num(*c));
|
||||
let data = if by_rows {
|
||||
RangeRef::new(CellRef::new(r.start.row, r.start.col + u32::from(has_label)), r.end)
|
||||
} else {
|
||||
RangeRef::new(CellRef::new(r.start.row + u32::from(has_label), r.start.col), r.end)
|
||||
};
|
||||
let mut lines: BTreeSet<u32> = BTreeSet::new();
|
||||
for (c, _) in sh.cells.iter_range(data) {
|
||||
if is_num(c) {
|
||||
lines.insert(if by_rows { c.row } else { c.col });
|
||||
}
|
||||
}
|
||||
if lines.is_empty() {
|
||||
return Err(EngineError::Other("The selection holds no numbers.".into()));
|
||||
}
|
||||
let edge = CellRef::new(
|
||||
if sel.end.row >= MAX_ROWS - 1 { r.end.row } else { sel.end.row.max(r.end.row) },
|
||||
if sel.end.col >= MAX_COLS - 1 { r.end.col } else { sel.end.col.max(r.end.col) },
|
||||
);
|
||||
Ok(Block { sheet, range: r, data, lines, by_rows, edge })
|
||||
}
|
||||
|
||||
fn add_total(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let func = parse_func(str_param(p, "function").unwrap_or("sum"))?;
|
||||
let by_rows = match str_param(p, "direction") {
|
||||
None | Some("columns") => false,
|
||||
Some("rows") => true,
|
||||
Some(other) => return Err(bad(CMD, format!("direction must be columns or rows, not `{other}`"))),
|
||||
};
|
||||
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
|
||||
let b = block(s, p, by_rows, CMD)?;
|
||||
let (r, sheet) = (b.range, b.sheet);
|
||||
let (lo, hi) = b.span_of_line();
|
||||
let out_cells = match func {
|
||||
Func::Aggregate(_) => b.lines.len() as u64,
|
||||
_ => b.lines.len() as u64 * (u64::from(hi - lo) + 1),
|
||||
};
|
||||
if out_cells > MAX_OUTPUT_CELLS {
|
||||
return Err(bad(CMD, "selection too large for this result"));
|
||||
}
|
||||
// `$` pins a part of a reference like a hand-written formula would.
|
||||
let abs = |c: CellRef, row: bool, col: bool| {
|
||||
let a = c.a1();
|
||||
let letters: String = a.chars().take_while(|ch| ch.is_ascii_alphabetic()).collect();
|
||||
let digits = &a[letters.len()..];
|
||||
format!("{}{letters}{}{digits}", if col { "$" } else { "" }, if row { "$" } else { "" })
|
||||
};
|
||||
// (target, formula) pairs.
|
||||
let mut writes: Vec<(CellRef, String)> = Vec::with_capacity(out_cells as usize);
|
||||
let (height, width) = (b.edge.row - r.start.row + 1, b.edge.col - r.start.col + 1);
|
||||
for &line in &b.lines {
|
||||
match func {
|
||||
Func::Aggregate(name) => {
|
||||
let target =
|
||||
if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
|
||||
writes.push((target, format!("={name}({})", b.line_range(line, lo, hi).a1())));
|
||||
}
|
||||
Func::Percent | Func::Running => {
|
||||
for i in lo..=hi {
|
||||
let src = b.cell_at(line, i);
|
||||
let target = if by_rows {
|
||||
CellRef::new(src.row.saturating_add(height), src.col)
|
||||
} else {
|
||||
CellRef::new(src.row, src.col.saturating_add(width))
|
||||
};
|
||||
let formula = if func == Func::Percent {
|
||||
// The summed block is locked on the axis the formula is filled along.
|
||||
let (a, z) = (b.cell_at(line, lo), b.cell_at(line, hi));
|
||||
format!("={}/SUM({}:{})", src.a1(), abs(a, !by_rows, by_rows), abs(z, !by_rows, by_rows))
|
||||
} else {
|
||||
format!("=SUM({}:{})", abs(b.cell_at(line, lo), !by_rows, by_rows), src.a1())
|
||||
};
|
||||
writes.push((target, formula));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Everything has to fit on the sheet and may not overwrite data.
|
||||
if writes.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
|
||||
return Err(EngineError::Other("There's no room next to the selection for the result.".into()));
|
||||
}
|
||||
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
if !overwrite && writes.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.cells.get(*t).is_some_and(|c| c.formula.is_some())) {
|
||||
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
|
||||
}
|
||||
let out = writes.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
|
||||
let percent = func == Func::Percent;
|
||||
let count = writes.len();
|
||||
edit(s, |cx| {
|
||||
for (t, f) in &writes {
|
||||
let cell = super::edit::input_to_cell(f, sheet, *t, &mut cx.wb)?.unwrap_or_default();
|
||||
cx.sheet_mut(sheet)?.set_cell(*t, cell);
|
||||
if percent {
|
||||
let cur = cx.wb.sheet(sheet).map(|sh| sh.style_id(*t)).unwrap_or_default();
|
||||
let new = cx.wb.styles.derive(cur, |st| st.num_fmt = NumFmt::new("0.0%"));
|
||||
cx.sheet_mut(sheet)?.set_style(*t, new);
|
||||
}
|
||||
cx.touch(sheet, *t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let name = match func {
|
||||
Func::Aggregate(n) => n.to_ascii_lowercase(),
|
||||
Func::Percent => "percentTotal".into(),
|
||||
Func::Running => "runningTotal".into(),
|
||||
};
|
||||
Ok(json!({"function": name, "direction": if by_rows { "rows" } else { "columns" }, "output": out.map(|o| o.a1()), "cells": count}))
|
||||
}
|
||||
|
||||
fn add_sparklines(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let by_rows = match str_param(p, "direction") {
|
||||
None | Some("rows") => true,
|
||||
Some("columns") => false,
|
||||
Some(other) => return Err(bad(SPARK, format!("direction must be rows or columns, not `{other}`"))),
|
||||
};
|
||||
let kind = match str_param(p, "type") {
|
||||
None | Some("line") => SparklineKind::Line,
|
||||
Some("column") => SparklineKind::Column,
|
||||
Some("winLoss") => SparklineKind::WinLoss,
|
||||
Some(other) => return Err(bad(SPARK, format!("type must be line, column or winLoss, not `{other}`"))),
|
||||
};
|
||||
let markers = bool_param(p, "markers").unwrap_or(false);
|
||||
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
|
||||
let b = block(s, p, by_rows, SPARK)?;
|
||||
if b.lines.len() as u64 > MAX_SPARKLINES {
|
||||
return Err(bad(SPARK, "selection too large for this result"));
|
||||
}
|
||||
let (lo, hi) = b.span_of_line();
|
||||
let sparks: Vec<(CellRef, String)> = b
|
||||
.lines
|
||||
.iter()
|
||||
.map(|&line| {
|
||||
let at = if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
|
||||
(at, b.line_range(line, lo, hi).a1())
|
||||
})
|
||||
.collect();
|
||||
if sparks.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
|
||||
return Err(EngineError::Other("There's no room next to the selection for the sparklines.".into()));
|
||||
}
|
||||
let sheet = b.sheet;
|
||||
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
// Sparklines are not cell content, so the commit-time protection check does not see them.
|
||||
if sh.is_protected() {
|
||||
return Err(EngineError::Other(PROTECTED.into()));
|
||||
}
|
||||
if !overwrite && sparks.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.sparklines.iter().any(|x| x.cell == *t)) {
|
||||
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
|
||||
}
|
||||
let out = sparks.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
|
||||
let count = sparks.len();
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
for (cell, source) in sparks {
|
||||
sh.sparklines.retain(|x| x.cell != cell);
|
||||
sh.sparklines.push(Sparkline { cell, source, kind, color: Color::Theme(4, 0), markers });
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"output": out.map(|o| o.a1()), "sparklines": count}))
|
||||
}
|
||||
@@ -161,7 +161,7 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
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 };
|
||||
let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_protection_hash(d, &what, pw)), ..prot };
|
||||
edit(s, |cx| {
|
||||
// FORMULATEXT reads a sheet's protection: its results are recalculated.
|
||||
cx.recalc_all = true;
|
||||
@@ -192,13 +192,25 @@ 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.
|
||||
/// A new hash of a sheet's or the workbook's protection password, in every form a file keeps
|
||||
/// (Excel's salted SHA-512 and OpenDocument's SHA-256 digest), so it survives saving in either
|
||||
/// format.
|
||||
fn new_protection_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
|
||||
PasswordHash::new_for_files(pw, &new_salt(d, what))
|
||||
}
|
||||
|
||||
/// A new Excel-compatible (SHA-512, salted) hash of `pw`: edit ranges only have this form.
|
||||
fn new_password_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
|
||||
PasswordHash::new_sha512(pw, &new_salt(d, what))
|
||||
}
|
||||
|
||||
/// A salt mixing `what` is protected with the document, a counter and the clock, so equal
|
||||
/// passwords get different hashes.
|
||||
fn new_salt(d: &DocState, what: &str) -> [u8; 16] {
|
||||
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()))
|
||||
gridcraft_model::password::salt_from(seed.as_bytes())
|
||||
}
|
||||
|
||||
fn range_text(r: &EditRange) -> String {
|
||||
@@ -317,7 +329,7 @@ fn protect_workbook(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
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))
|
||||
str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_protection_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)?
|
||||
@@ -449,7 +461,10 @@ mod tests {
|
||||
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"));
|
||||
// Kept in both forms: Excel's salted SHA-512 and OpenDocument's SHA-256 digest.
|
||||
let password = prot.password.as_ref().unwrap();
|
||||
assert!(matches!(password.excel(), Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512"));
|
||||
assert_eq!(password.odf_key(), PasswordHash::new_sha256_digest("pa55").odf_key());
|
||||
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.
|
||||
|
||||
@@ -51,12 +51,11 @@ pub fn column_values(wb: &Workbook, sheet: usize, table: &str, column: &str) ->
|
||||
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() {
|
||||
let Some(tile) = super::data::slicer_tile_text(wb, sh, CellRef::new(row, col)) else {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(text.to_lowercase()) {
|
||||
out.push(text);
|
||||
};
|
||||
if seen.insert(tile.to_lowercase()) {
|
||||
out.push(tile);
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -70,7 +69,7 @@ pub fn slicer_items(wb: &Workbook, sheet: usize, sl: &Slicer) -> Vec<(String, bo
|
||||
.map(|v| {
|
||||
let on = match &sl.selected {
|
||||
None => true,
|
||||
Some(set) => set.iter().any(|x| x.eq_ignore_ascii_case(&v)),
|
||||
Some(set) => set.iter().any(|x| x.trim().to_lowercase() == v.trim().to_lowercase()),
|
||||
};
|
||||
(v, on)
|
||||
})
|
||||
@@ -92,7 +91,8 @@ fn reapply_slicer(wb: &mut Workbook, sheet: usize, id: u32) {
|
||||
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 }));
|
||||
let identities = values.iter().map(|v| super::data::slicer_identity_token(v)).collect();
|
||||
af.criteria.push((off, FilterCriterion::Values { values, blanks: false, identities }));
|
||||
}
|
||||
}
|
||||
super::data::apply_filter(wb, sheet);
|
||||
@@ -174,24 +174,40 @@ fn slicer_toggle(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
(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)) {
|
||||
let trimmed_val = value.trim();
|
||||
if !all.iter().any(|v| v.trim().to_lowercase() == trimmed_val.to_lowercase()) {
|
||||
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);
|
||||
let dedup_tiles = |items: Vec<String>| -> Vec<String> {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for item in items {
|
||||
let t = item.trim();
|
||||
if !t.is_empty() && seen.insert(t.to_lowercase()) {
|
||||
out.push(t.to_string());
|
||||
}
|
||||
None => set.push(value.clone()),
|
||||
}
|
||||
out
|
||||
};
|
||||
let normalized_current = current.map(dedup_tiles);
|
||||
let new_selected: Option<Vec<String>> = if multi {
|
||||
let mut set: Vec<String> = normalized_current.unwrap_or_else(|| all.clone());
|
||||
let before = set.len();
|
||||
set.retain(|x| x.trim().to_lowercase() != trimmed_val.to_lowercase());
|
||||
if set.len() == before {
|
||||
set.push(trimmed_val.to_string());
|
||||
}
|
||||
// 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) }
|
||||
if set.len() == all.len() && all.iter().all(|a| set.iter().any(|x| x.trim().to_lowercase() == a.trim().to_lowercase())) {
|
||||
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()]),
|
||||
match &normalized_current {
|
||||
Some(set) if set.len() == 1 && set.iter().any(|x| x.trim().to_lowercase() == trimmed_val.to_lowercase()) => None,
|
||||
_ => Some(vec![trimmed_val.to_string()]),
|
||||
}
|
||||
};
|
||||
edit(s, |cx| {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! View tab (sheet view state that's saved with the file) and Page Layout settings.
|
||||
|
||||
use gridcraft_core::RangeRef;
|
||||
use gridcraft_model::Orientation;
|
||||
use gridcraft_model::{Orientation, Workbook};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use super::{
|
||||
@@ -62,8 +62,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
workbook_view_flag(s, p, "vertical")
|
||||
}),
|
||||
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!(noundo "view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom),
|
||||
cmd!(noundo "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}))
|
||||
@@ -77,14 +77,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
status_bar
|
||||
),
|
||||
cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection),
|
||||
cmd!(noundo "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|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes)}",
|
||||
"{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
|
||||
has_doc,
|
||||
paper
|
||||
),
|
||||
@@ -274,6 +274,34 @@ fn zoom(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Ok(json!({"zoom": z}))
|
||||
}
|
||||
|
||||
/// Zoom belongs to the window, not to the edits (Excel doesn't undo it, #2313): undo and redo keep
|
||||
/// each sheet's current zoom when they swap in another snapshot of the workbook. Back at the saved
|
||||
/// state, the zoom alone doesn't make the workbook dirty, as with `view.zoom`.
|
||||
pub(crate) fn keep_zoom(d: &mut crate::DocState, now: &Workbook) {
|
||||
// Sheets have no stable id. A name missing from `now` is a rename being undone or redone, which
|
||||
// keeps the sheet count and position: the sheet is the one at the same index, under a name the
|
||||
// restored snapshot doesn't have.
|
||||
let renamed = |i: usize| {
|
||||
(now.sheets.len() == d.wb.sheets.len()).then(|| now.sheets.get(i)).flatten().filter(|sh| !d.wb.sheets.iter().any(|s| s.name == sh.name))
|
||||
};
|
||||
let current = |i: usize, name: &str| now.sheets.iter().find(|sh| sh.name == name).or_else(|| renamed(i)).map(|sh| sh.zoom);
|
||||
let changed: Vec<(usize, u16)> =
|
||||
d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(i, &sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect();
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let saved = std::sync::Arc::ptr_eq(&d.wb, &d.saved);
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
for (i, z) in changed {
|
||||
if let Some(sh) = wb.sheet_mut(i) {
|
||||
sh.zoom = z;
|
||||
}
|
||||
}
|
||||
if saved {
|
||||
d.saved = d.wb.clone();
|
||||
}
|
||||
}
|
||||
|
||||
fn zoom_selection(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
@@ -296,7 +324,9 @@ fn orientation(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn paper(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let paper = str_param(p, "paper").unwrap_or("Letter").to_string();
|
||||
// A known paper is stored under its table name; any other name is kept (it prints on Letter).
|
||||
let name = str_param(p, "paper").unwrap_or("Letter");
|
||||
let paper = gridcraft_model::paper::canonical(name).unwrap_or(name).to_string();
|
||||
edit(s, |cx| {
|
||||
let si = cx.sheet_index();
|
||||
cx.sheet_mut(si)?.print.paper = paper.clone();
|
||||
@@ -535,6 +565,7 @@ fn theme(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gridcraft_core::CellRef;
|
||||
|
||||
#[test]
|
||||
fn zoom_100_resets_the_active_sheet_zoom() {
|
||||
@@ -545,6 +576,94 @@ mod tests {
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().zoom, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zooming_is_not_an_undo_step() {
|
||||
// Excel keeps zoom on the window, not in the edit history (#2313): wheel, slider, dialog,
|
||||
// 100% and Zoom to Selection leave Undo and Redo alone.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "y"})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let (undo, redo) = s.doc().map(|d| (d.undo.len(), d.redo.len())).unwrap();
|
||||
for (id, params, zoom) in [
|
||||
("view.zoom", json!({"percent": 150}), 150),
|
||||
("view.zoomToSelection", json!({"viewWidth": 1200, "viewHeight": 700}), 400),
|
||||
("view.zoom100", json!({}), 100),
|
||||
] {
|
||||
s.execute(id, params).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.wb.active().unwrap().zoom, zoom, "{id}");
|
||||
assert_eq!((d.undo.len(), d.redo.len()), (undo, redo), "{id} touched the history");
|
||||
}
|
||||
let a1 = CellRef::parse("A1").unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().value(a1).is_empty(), "Ctrl+Z after zooming undoes the last edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_redo_keep_the_current_zoom() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let zoom = |s: &Session| s.doc().unwrap().wb.active().unwrap().zoom;
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 200})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty());
|
||||
assert_eq!(zoom(&s), 200, "undo keeps the zoom");
|
||||
// Back at the state on disk: the zoom alone doesn't make the workbook dirty, as in `zoom`.
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("view.zoom", json!({"percent": 50})).unwrap();
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty());
|
||||
assert_eq!(zoom(&s), 50, "redo keeps the zoom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undoing_a_rename_keeps_the_current_zoom() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let active = |s: &Session| {
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
(sh.name.clone(), sh.zoom)
|
||||
};
|
||||
let before = active(&s).0;
|
||||
s.execute("sheet.rename", json!({"name": "Data"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 150})).unwrap();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(active(&s), (before, 150), "undoing the rename keeps the zoom");
|
||||
s.execute("view.zoom", json!({"percent": 75})).unwrap();
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(active(&s), ("Data".to_string(), 75), "redoing the rename keeps the zoom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undoing_several_steps_keeps_each_sheet_its_own_zoom() {
|
||||
// Adding C then deleting B leaves as many sheets as before under other names: across both
|
||||
// steps at once, that looks like B renamed to C, and C's zoom used to land on B.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let zoom = |s: &Session, name: &str| {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
wb.sheet(wb.sheet_index(name).unwrap()).unwrap().zoom
|
||||
};
|
||||
let names = |s: &Session| s.doc().unwrap().wb.sheets.iter().map(|sh| sh.name.clone()).collect::<Vec<_>>();
|
||||
let first = names(&s)[0].clone();
|
||||
s.execute("home.insertSheet", json!({"name": "B", "before": 1})).unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "C", "before": 2})).unwrap();
|
||||
s.execute("home.deleteSheet", json!({"sheet": "B"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": "C"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 150})).unwrap();
|
||||
s.execute("edit.undo", json!({"steps": 2})).unwrap();
|
||||
assert_eq!(names(&s), [first.clone(), "B".to_string()]);
|
||||
assert_eq!(zoom(&s, "B"), 100, "B never had C's zoom");
|
||||
s.execute("sheet.activate", json!({"sheet": "B"})).unwrap();
|
||||
s.execute("view.zoom", json!({"percent": 80})).unwrap();
|
||||
s.execute("edit.redo", json!({"steps": 2})).unwrap();
|
||||
assert_eq!(names(&s), [first, "C".to_string()]);
|
||||
assert_eq!(zoom(&s, "C"), 150, "C gets its own zoom back, not B's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -51,12 +51,16 @@ fn text_needs_quote_prefix(t: &str, sys: gridcraft_core::date::DateSystem) -> bo
|
||||
if t.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut chars = t.chars();
|
||||
let (first, second) = (chars.next(), chars.next());
|
||||
let first = t.chars().next();
|
||||
if matches!(first, Some('=' | '\'')) {
|
||||
return true;
|
||||
}
|
||||
if matches!(first, Some('+' | '-')) && second.is_some_and(|c| c.is_ascii_alphabetic() || c == '(') {
|
||||
// A `+` or `-` entry that reads as a formula becomes one (`+5+4`, `-abc`); one that doesn't
|
||||
// stays text (`--`, `+49 170 1234567`), as `input_to_cell` decides it.
|
||||
if matches!(first, Some('+' | '-'))
|
||||
&& gridcraft_core::parse::starts_formula(t)
|
||||
&& crate::cmd::edit::parse_typed_formula(t).is_ok_and(|e| crate::cmd::edit::check_arg_counts(&e).is_ok())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
!matches!(gridcraft_core::parse::parse_input(t, sys).value, Value::Text(ref x) if x.as_ref() == t)
|
||||
|
||||
+216
-21
@@ -28,6 +28,12 @@ pub enum FillMode {
|
||||
/// counted in that unit (one unit when they fall in the same one). A source that isn't dates
|
||||
/// extends like a plain drag.
|
||||
Dates(DateUnit),
|
||||
/// Linear Trend: the targets continue the least-squares line (y = mx + b) through the source's
|
||||
/// numbers. The source keeps its values.
|
||||
LinearTrend,
|
||||
/// Growth Trend: the targets continue the exponential curve (y = b·m^x) fitted to the source's
|
||||
/// numbers. The source keeps its values.
|
||||
GrowthTrend,
|
||||
}
|
||||
|
||||
/// The step of a [`FillMode::Dates`] fill.
|
||||
@@ -47,6 +53,87 @@ impl FillMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fill from `src` to `target` runs down or up the sheet rather than across it.
|
||||
fn fills_vertically(src: RangeRef, target: RangeRef) -> bool {
|
||||
target.height() != src.height() || target.width() == src.width()
|
||||
}
|
||||
|
||||
/// The numbers in each lane of `src` that a fill to `target` continues, or `None` when a source
|
||||
/// cell is empty or holds text, a logical value, an error, a formula or Python code.
|
||||
fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> Option<Vec<Vec<f64>>> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
lane_cells(src, target).map(|lane| lane.map(|c| trend_number(sh, c)).collect()).collect()
|
||||
}
|
||||
|
||||
/// The cells of each lane of `src` that a fill to `target` continues: each column when the fill
|
||||
/// runs down or up the sheet, each row when it runs across.
|
||||
fn lane_cells(src: RangeRef, target: RangeRef) -> impl Iterator<Item = impl Iterator<Item = CellRef>> {
|
||||
let vertical = fills_vertically(src, target);
|
||||
let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) };
|
||||
lanes.map(move |lane| (0..len).map(move |i| if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }))
|
||||
}
|
||||
|
||||
/// The sign Growth Trend fits a lane's numbers by: 1 when they are all above zero, -1 when they
|
||||
/// are all below zero, and `None` otherwise.
|
||||
fn growth_sign(nums: impl IntoIterator<Item = f64>) -> Option<f64> {
|
||||
let (mut above, mut below) = (true, true);
|
||||
for y in nums {
|
||||
above &= y > 0.0;
|
||||
below &= y < 0.0;
|
||||
}
|
||||
if above {
|
||||
Some(1.0)
|
||||
} else if below {
|
||||
Some(-1.0)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The number a trend fill reads from source cell `c`, or `None` when it is empty or holds text, a
|
||||
/// logical value, an error, a formula or Python code.
|
||||
fn trend_number(sh: &gridcraft_model::Sheet, c: CellRef) -> Option<f64> {
|
||||
let cell = sh.cell(c)?;
|
||||
if cell.formula.is_some() || cell.py.is_some() || !cell.value.is_number() {
|
||||
return None;
|
||||
}
|
||||
cell.value.as_f64()
|
||||
}
|
||||
|
||||
/// Whether the fill menu offers Linear Trend (`growth` false) or Growth Trend (`growth` true) for a
|
||||
/// fill from `src` to `target`: every source cell holds a number, and for Growth Trend the numbers
|
||||
/// of each lane are all above zero or all below zero. A source or target larger than
|
||||
/// [`MAX_FILL_CELLS`], or a target that doesn't hold the source in a corner, is refused by
|
||||
/// `edit.autoFill`, so neither trend applies to it and no source cell is read.
|
||||
pub fn trend_applies(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef, growth: bool) -> bool {
|
||||
let (linear, growth_fits) = trends_that_apply(wb, sheet, src, target);
|
||||
if growth { growth_fits } else { linear }
|
||||
}
|
||||
|
||||
/// [`trend_applies`] for both trends from one read of the source: (Linear Trend, Growth Trend). It
|
||||
/// checks each cell's number and sign and fits nothing, so the menu does not wait on a fit.
|
||||
pub fn trends_that_apply(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> (bool, bool) {
|
||||
if src.count() > MAX_FILL_CELLS || target.count() > MAX_FILL_CELLS || !holds_source_in_corner(src, target) {
|
||||
return (false, false);
|
||||
}
|
||||
let Some(sh) = wb.sheet(sheet) else { return (false, false) };
|
||||
let mut growth = true;
|
||||
// The lanes and the sign rule are the ones the fill uses (`numeric_lanes`, `Pattern::growth`).
|
||||
for lane in lane_cells(src, target) {
|
||||
let mut missing = false;
|
||||
let sign = growth_sign(lane.map_while(|c| {
|
||||
let y = trend_number(sh, c);
|
||||
missing |= y.is_none();
|
||||
y
|
||||
}));
|
||||
if missing {
|
||||
return (false, false);
|
||||
}
|
||||
growth &= sign.is_some();
|
||||
}
|
||||
(true, growth)
|
||||
}
|
||||
|
||||
/// Whether a number format shows a calendar date (`YYYY-MM-DD` and `m/d/yyyy h:mm` do; `0 "days"`
|
||||
/// and `h:mm` don't).
|
||||
fn is_date_format(fmt: &str) -> bool {
|
||||
@@ -102,7 +189,7 @@ pub fn fill_except(
|
||||
let custom = cx.wb.custom_lists.clone();
|
||||
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) };
|
||||
// Direction: down/up if target extends rows, else right/left.
|
||||
let vertical = target.height() != src.height() || target.width() == src.width();
|
||||
let vertical = fills_vertically(src, target);
|
||||
let forward = if vertical {
|
||||
target.end.row > src.end.row || target.start.row == src.start.row
|
||||
} else {
|
||||
@@ -120,11 +207,25 @@ pub fn fill_except(
|
||||
if u64::from(lane_count).saturating_mul(u64::from(steps)) > MAX_FILL_CELLS {
|
||||
return Err(crate::EngineError::Other("The fill is too large.".into()));
|
||||
}
|
||||
// Linear Trend and Growth Trend fit each lane's numbers.
|
||||
let trends: Vec<Pattern> = match mode {
|
||||
FillMode::LinearTrend | FillMode::GrowthTrend => {
|
||||
let Some(lanes) = numeric_lanes(&cx.wb, sheet, src, target) else {
|
||||
return Err(crate::EngineError::Other("Linear Trend and Growth Trend need a number in every source cell.".into()));
|
||||
};
|
||||
let fit = |nums: &Vec<f64>| if mode == FillMode::GrowthTrend { Pattern::growth(nums) } else { Some(Pattern::linear(nums)) };
|
||||
let Some(trends) = lanes.iter().map(fit).collect() else {
|
||||
return Err(crate::EngineError::Other("Growth Trend needs numbers that are all above zero or all below zero.".into()));
|
||||
};
|
||||
trends
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let lanes: Vec<u32> = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() };
|
||||
let src_len = if vertical { src.height() } else { src.width() };
|
||||
let mut writes: Vec<(CellRef, Option<Cell>)> = Vec::new();
|
||||
let mut pictures = Vec::new();
|
||||
for lane in lanes {
|
||||
for (lane_i, lane) in lanes.into_iter().enumerate() {
|
||||
let src_cells: Vec<(CellRef, Option<Cell>)> = (0..src_len)
|
||||
.map(|i| {
|
||||
let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) };
|
||||
@@ -142,7 +243,9 @@ pub fn fill_except(
|
||||
};
|
||||
targets.retain(|t| !skip_rows.contains(&t.row));
|
||||
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 mode.extends_series() || mode == FillMode::Alternate {
|
||||
let pattern = if let Some(trend) = trends.get(lane_i) {
|
||||
trend.clone()
|
||||
} else if mode.extends_series() || mode == FillMode::Alternate {
|
||||
let first_fmt = src_cells.first().map(fmt).unwrap_or_default();
|
||||
let dates = match mode {
|
||||
FillMode::Dates(unit) => Pattern::dates(&src_cells, unit, cx.wb.date_system, first_fmt),
|
||||
@@ -176,7 +279,14 @@ pub fn fill_except(
|
||||
writes.push((*t, Some(existing)));
|
||||
continue;
|
||||
}
|
||||
FillMode::ValuesOnly | FillMode::Series | FillMode::Alternate | FillMode::Copy | FillMode::Extend | FillMode::Dates(_) => {
|
||||
FillMode::ValuesOnly
|
||||
| FillMode::Series
|
||||
| FillMode::Alternate
|
||||
| FillMode::Copy
|
||||
| FillMode::Extend
|
||||
| FillMode::Dates(_)
|
||||
| FillMode::LinearTrend
|
||||
| FillMode::GrowthTrend => {
|
||||
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() {
|
||||
@@ -259,9 +369,42 @@ enum Pattern {
|
||||
step: i64,
|
||||
sys: gridcraft_core::DateSystem,
|
||||
},
|
||||
/// Growth Trend, kept as logarithms so that a value the curve reaches is not lost to an
|
||||
/// overflow or underflow on the way: the logarithms of the fitted magnitudes at the source's
|
||||
/// last and first cells, the logarithm of the factor between neighboring cells, and the sign
|
||||
/// of every value (1 or -1).
|
||||
Growth {
|
||||
last: f64,
|
||||
first: f64,
|
||||
step: f64,
|
||||
sign: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
/// Linear Trend: the least-squares line through `nums`. A lone number is copied unchanged.
|
||||
fn linear(nums: &[f64]) -> Pattern {
|
||||
if nums.len() == 1 {
|
||||
return Pattern::Copy;
|
||||
}
|
||||
let (first, last, step) = least_squares(nums);
|
||||
Pattern::Linear { last, first, step }
|
||||
}
|
||||
|
||||
/// The exponential curve y = b·m^x fitted to `nums` at positions 0, 1, 2… by least squares on
|
||||
/// the logarithms, as the GROWTH function fits positive numbers. Numbers below zero are fitted
|
||||
/// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or
|
||||
/// all below zero. A lone number, or the same number repeated, is copied unchanged.
|
||||
fn growth(nums: &[f64]) -> Option<Pattern> {
|
||||
let sign = growth_sign(nums.iter().copied())?;
|
||||
if nums.windows(2).all(|w| w.first() == w.last()) {
|
||||
return Some(Pattern::Copy);
|
||||
}
|
||||
let logs: Vec<f64> = nums.iter().map(|y| (y * sign).ln()).collect();
|
||||
let (first, last, step) = least_squares(&logs);
|
||||
Some(Pattern::Growth { last, first, step, sign })
|
||||
}
|
||||
|
||||
/// The pattern of Fill Days, Fill Weekdays, Fill Months or Fill Years, or `None` when the
|
||||
/// source isn't all dates (numbers, not formulas, under a date format in its first cell).
|
||||
fn dates(cells: &[(CellRef, Option<Cell>)], unit: DateUnit, sys: gridcraft_core::DateSystem, fmt: &str) -> Option<Pattern> {
|
||||
@@ -344,19 +487,7 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
// Least-squares step for 2+ values (Excel uses a linear trend).
|
||||
let n = nums.len() as f64;
|
||||
let mean_x = (n - 1.0) / 2.0;
|
||||
let mean_y = nums.iter().sum::<f64>() / n;
|
||||
let mut num = 0.0;
|
||||
let mut den = 0.0;
|
||||
for (i, y) in nums.iter().enumerate() {
|
||||
num += (i as f64 - mean_x) * (y - mean_y);
|
||||
den += (i as f64 - mean_x).powi(2);
|
||||
}
|
||||
let step = if den == 0.0 { 0.0 } else { num / den };
|
||||
let fitted_last = mean_y + step * (n - 1.0 - mean_x);
|
||||
let fitted_first = mean_y - step * mean_x;
|
||||
return Pattern::Linear { last: fitted_last, first: fitted_first, step };
|
||||
return Pattern::linear(&nums);
|
||||
}
|
||||
// Text.
|
||||
if !vals.is_empty() && vals.iter().all(|v| v.is_text()) {
|
||||
@@ -450,10 +581,45 @@ impl Pattern {
|
||||
let base = if forward { *last } else { *first };
|
||||
Some(Value::number(add_weekdays(*sys, base, step.checked_mul(k)?.checked_mul(sign)?)?))
|
||||
}
|
||||
Pattern::Growth { last, first, step, sign: growth_sign } => {
|
||||
let base = if forward { *last } else { *first };
|
||||
Some(Value::number(round15(growth_sign * (base + step * (k * sign) as f64).exp())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 2^600 and 2^-600, both exact.
|
||||
const TWO_POW_600: f64 = f64::from_bits((1023 + 600) << 52);
|
||||
const TWO_POW_MINUS_600: f64 = f64::from_bits((1023 - 600) << 52);
|
||||
|
||||
/// The least-squares line through `nums` at positions 0, 1, 2…: its values at the first and last
|
||||
/// positions, and its step. A lone number gives a step of zero. When a number is larger than 2^600,
|
||||
/// the fit runs on the numbers multiplied by 2^-600 and its results are multiplied by 2^600, so the
|
||||
/// sums stay finite for numbers up to the largest double. When every number is smaller than 2^-600,
|
||||
/// the fit runs on the numbers multiplied by 2^600 and its results are multiplied by 2^-600, so
|
||||
/// subnormal numbers keep their step instead of rounding it to zero.
|
||||
fn least_squares(nums: &[f64]) -> (f64, f64, f64) {
|
||||
let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) {
|
||||
(TWO_POW_MINUS_600, TWO_POW_600)
|
||||
} else if nums.iter().all(|y| y.abs() < TWO_POW_MINUS_600) {
|
||||
(TWO_POW_600, TWO_POW_MINUS_600)
|
||||
} else {
|
||||
(1.0, 1.0)
|
||||
};
|
||||
let n = nums.len() as f64;
|
||||
let mean_x = (n - 1.0) / 2.0;
|
||||
let mean_y = nums.iter().map(|y| y * down).sum::<f64>() / n;
|
||||
let mut num = 0.0;
|
||||
let mut den = 0.0;
|
||||
for (i, y) in nums.iter().enumerate() {
|
||||
num += (i as f64 - mean_x) * (y * down - mean_y);
|
||||
den += (i as f64 - mean_x).powi(2);
|
||||
}
|
||||
let step = if den == 0.0 { 0.0 } else { num / den };
|
||||
((mean_y - step * mean_x) * up, (mean_y + step * (n - 1.0 - mean_x)) * up, step * up)
|
||||
}
|
||||
|
||||
/// Whether `serial` falls on Monday to Friday; `None` outside the supported date range.
|
||||
fn is_weekday(sys: gridcraft_core::DateSystem, serial: f64) -> Option<bool> {
|
||||
datetime_from_serial(sys, serial).map(|d| d.weekday != 0 && d.weekday != 6)
|
||||
@@ -514,13 +680,27 @@ fn add_months_clamped(sys: gridcraft_core::DateSystem, serial: f64, months: i64)
|
||||
serial_from_ymd(sys, year, month, (d.day as i64).min(last as i64)).map(|day| day + serial - serial.floor())
|
||||
}
|
||||
|
||||
/// `x` rounded to 15 significant digits through its exact decimal expansion, so a number that
|
||||
/// already has 15 or fewer digits comes back unchanged at any size. A number near the largest
|
||||
/// double whose rounding would pass it keeps its value. A whole number below 10^15 is returned
|
||||
/// as it is, and other numbers are written to a buffer on the stack, so a fill does not allocate
|
||||
/// for each cell.
|
||||
fn round15(x: f64) -> f64 {
|
||||
if x == 0.0 || !x.is_finite() {
|
||||
use std::io::Write;
|
||||
if x == 0.0 || !x.is_finite() || (x.fract() == 0.0 && x.abs() < 1e15) {
|
||||
return x;
|
||||
}
|
||||
let mag = x.abs().log10().floor() as i32;
|
||||
let p = 10f64.powi(14 - mag);
|
||||
if !p.is_finite() || p == 0.0 { x } else { (x * p).round() / p }
|
||||
// "-1.23456789012345e-308" is the longest expansion: 22 bytes.
|
||||
let mut buf = [0u8; 32];
|
||||
let mut out = &mut buf[..];
|
||||
if write!(out, "{x:.14e}").is_err() {
|
||||
return x;
|
||||
}
|
||||
let len = 32 - out.len();
|
||||
match buf.get(..len).and_then(|b| std::str::from_utf8(b).ok()).and_then(|s| s.parse::<f64>().ok()) {
|
||||
Some(r) if r.is_finite() => r,
|
||||
_ => x,
|
||||
}
|
||||
}
|
||||
|
||||
/// `1st Period` → `2nd Period`: an English ordinal ending is rewritten to suit the new number.
|
||||
@@ -811,6 +991,21 @@ mod tests {
|
||||
assert_eq!(sh.value(CellRef::new(1, 1)), Value::from("03/12/2023"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round15_matches_the_decimal_expansion_without_allocating() {
|
||||
let by_string = |x: f64| match format!("{x:.14e}").parse::<f64>() {
|
||||
Ok(r) if r.is_finite() => r,
|
||||
_ => x,
|
||||
};
|
||||
let tiny = f64::from_bits(1);
|
||||
let whole = [1.0, -7.0, 999_999_999_999_999.0, 1e15, 1e15 + 1.0, 123_456_789_012_345_680.0];
|
||||
let other = [0.1 + 0.2, -1.0 / 3.0, tiny, -tiny, 1e-308, f64::MAX, -f64::MAX, 1.7976931348623e308];
|
||||
for x in whole.into_iter().chain(other) {
|
||||
assert_eq!(round15(x).to_bits(), by_string(x).to_bits(), "{x:e}");
|
||||
}
|
||||
assert_eq!(round15(-0.0).to_bits(), (-0.0f64).to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn series_keeps_value_equal_to_stop_after_float_drift() {
|
||||
let mut s = crate::Session::new();
|
||||
|
||||
+18
-36
@@ -53,6 +53,10 @@ 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 workbook with a password to modify, opened with neither that password
|
||||
/// (`modifyPassword`) nor `readOnly`, contains this. The interface asks for the password or a
|
||||
/// read-only open when it sees it.
|
||||
pub const MODIFY_PASSWORD_REQUIRED: &str = "is reserved by its author. Enter the password to modify it, or open it read-only.";
|
||||
/// 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.
|
||||
@@ -144,6 +148,7 @@ fn open_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
|
||||
crate::cmd::controls::load_action_names(&mut wb);
|
||||
warnings.extend(adopt_python(&mut wb));
|
||||
warnings.extend(enforce_python_limits(&mut wb));
|
||||
crate::cmd::data::migrate_loaded_autofilters(&mut wb);
|
||||
Ok((wb, warnings))
|
||||
}
|
||||
|
||||
@@ -528,8 +533,8 @@ pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result<Vec<u8
|
||||
Err(EngineError::Other("SYLK (.slk) is supported for import only. Save as .xlsx or another supported export format.".into()))
|
||||
}
|
||||
// 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::Csv => wb.sheet(sheet).map(|sh| csv(wb, sh, Some(wb.csv_delimiter.unwrap_or(b',')))).transpose().map(Option::unwrap_or_default),
|
||||
FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, None)).transpose().map(Option::unwrap_or_default),
|
||||
FileKind::Json => crate::macros::json_bytes(wb),
|
||||
FileKind::Html => to_html(wb, sheet).map(String::into_bytes),
|
||||
}
|
||||
@@ -563,8 +568,14 @@ pub fn source_path(path: &str) -> Option<std::path::PathBuf> {
|
||||
/// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as
|
||||
/// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers
|
||||
/// that `&` writes in scientific notation as their 15 digits in full.
|
||||
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
|
||||
gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string()))
|
||||
/// `delimiter` `None` writes a tab-separated file (`.tsv`, `.txt`).
|
||||
fn csv(wb: &Workbook, sh: &Sheet, delimiter: Option<u8>) -> Result<Vec<u8>> {
|
||||
let text = |c| crate::display::value_text(wb, sh, c);
|
||||
match delimiter {
|
||||
Some(d) => gridcraft_xlsx::write_csv(sh, d, text),
|
||||
None => gridcraft_xlsx::write_tsv(sh, text),
|
||||
}
|
||||
.map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and
|
||||
@@ -1143,43 +1154,14 @@ pub fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
|
||||
Err(EngineError::Other(format!("{path}: no file system in the browser")))
|
||||
}
|
||||
|
||||
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
|
||||
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
|
||||
for i in 0..4 {
|
||||
if i <= chunk.len() {
|
||||
out.push(B64[((n >> (18 - 6 * i)) & 63) as usize] as char);
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
gridcraft_model::b64::encode(data)
|
||||
}
|
||||
|
||||
/// Base64, or a `data:` URL's base64 payload.
|
||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let s = s.split_once(',').filter(|(h, _)| h.starts_with("data:")).map(|(_, b)| b).unwrap_or(s);
|
||||
let mut out = Vec::with_capacity(s.len() / 4 * 3);
|
||||
let mut buf = 0u32;
|
||||
let mut bits = 0;
|
||||
for c in s.bytes() {
|
||||
if c == b'=' || c.is_ascii_whitespace() {
|
||||
continue;
|
||||
}
|
||||
let v = B64.iter().position(|&x| x == c)? as u32;
|
||||
buf = (buf << 6) | v;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push((buf >> bits) as u8);
|
||||
buf &= (1 << bits) - 1;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
gridcraft_model::b64::decode(s)
|
||||
}
|
||||
|
||||
/// Pixel size of a PNG or JPEG from its header.
|
||||
|
||||
@@ -518,6 +518,64 @@ fn csv_save_keeps_the_separator_it_was_opened_with() {
|
||||
assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs);
|
||||
}
|
||||
|
||||
/// #1446: File › Open honours Excel's `sep=` first line; saved again, the file opens in the same
|
||||
/// columns. A `.txt` file is read with tabs, so its `sep=` line stays data.
|
||||
#[test]
|
||||
fn csv_open_honours_a_sep_line_and_saves_a_file_that_reopens_in_columns() {
|
||||
let (wb, _) = open_bytes("parts.csv", b"sep=|\r\nPart|Note\r\n1|a,b\r\n").unwrap();
|
||||
let sh = wb.sheet(0).unwrap();
|
||||
let text = |a: &str| sh.value(CellRef::parse(a).unwrap()).as_text().map(str::to_string);
|
||||
assert_eq!((text("A1"), text("B1"), text("B2")), (Some("Part".into()), Some("Note".into()), Some("a,b".into())));
|
||||
let saved = save_bytes(&wb, "parts.csv").unwrap();
|
||||
assert_eq!(String::from_utf8(saved.clone()).unwrap(), "Part,Note\r\n1,\"a,b\"\r\n");
|
||||
let (again, _) = open_bytes("parts.csv", &saved).unwrap();
|
||||
assert_eq!(again.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()).as_text(), Some("a,b"));
|
||||
// `sep=;` keeps its semicolons, as a semicolon file does.
|
||||
let (semi, _) = open_bytes("semi.csv", b"sep=;\r\na;b\r\n").unwrap();
|
||||
assert_eq!(save_bytes(&semi, "semi.csv").unwrap(), b"a;b\r\n");
|
||||
let (txt, _) = open_bytes("list.txt", b"sep=|\r\na\tb\r\n").unwrap();
|
||||
assert_eq!(txt.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=|"));
|
||||
}
|
||||
|
||||
/// A first cell that reads like a `sep=` line needs one of its own only in a CSV. A `.tsv` is read
|
||||
/// with tabs given, so a `sep=` line there would come back as an extra row above the data.
|
||||
#[test]
|
||||
fn csv_save_names_its_delimiter_when_reopening_would_pick_another() {
|
||||
let cells = |wb: &Workbook| {
|
||||
let sh = wb.sheet(0).unwrap();
|
||||
(0..2).map(|c| sh.value(CellRef::new(0, c)).as_text().map(str::to_string)).collect::<Vec<_>>()
|
||||
};
|
||||
// Read with `;`; saved, `a,b` loses its quotes and the line has one comma and one semicolon,
|
||||
// which detection alone would read as comma-separated.
|
||||
let (wb, _) = open_bytes("tie.csv", b"sep=;\r\n\"a,b\";x\r\n").unwrap();
|
||||
let saved = save_bytes(&wb, "tie.csv").unwrap();
|
||||
assert_eq!(saved, b"sep=;\r\na,b;x\r\n");
|
||||
assert_eq!(cells(&open_bytes("tie.csv", &saved).unwrap().0), [Some("a,b".into()), Some("x".into())]);
|
||||
// `|` is saved as commas; semicolons in the values would make detection pick `;`.
|
||||
let (wb, _) = open_bytes("pipe.csv", b"sep=|\r\na;b;c|d;e;f\r\n").unwrap();
|
||||
let saved = save_bytes(&wb, "pipe.csv").unwrap();
|
||||
assert_eq!(saved, b"sep=,\r\na;b;c,d;e;f\r\n");
|
||||
assert_eq!(cells(&open_bytes("pipe.csv", &saved).unwrap().0), [Some("a;b;c".into()), Some("d;e;f".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsv_save_writes_no_sep_line_and_reopens_in_place() {
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("sep=;"));
|
||||
sh.set_value(CellRef::new(1, 0), gridcraft_core::Value::text("x"));
|
||||
let saved = save_bytes(&wb, "list.tsv").unwrap();
|
||||
assert_eq!(saved, b"sep=;\r\nx\r\n");
|
||||
let (again, _) = open_bytes("list.tsv", &saved).unwrap();
|
||||
let text = |r: u32| again.sheet(0).unwrap().value(CellRef::new(r, 0)).as_text().map(str::to_string);
|
||||
assert_eq!((text(0), text(1)), (Some("sep=;".into()), Some("x".into())));
|
||||
// Saved as CSV, the same sheet keeps its protective line, which reading drops again.
|
||||
let csv = save_bytes(&wb, "list.csv").unwrap();
|
||||
assert_eq!(csv, b"sep=,\r\nsep=;\r\nx\r\n");
|
||||
let (again, _) = open_bytes("list.csv", &csv).unwrap();
|
||||
assert_eq!(again.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() {
|
||||
let mut wb = Workbook::new();
|
||||
|
||||
@@ -206,6 +206,9 @@ pub struct DocState {
|
||||
/// 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>,
|
||||
/// The file a read-only open came from (`readOnly` on a workbook with a password to modify).
|
||||
/// Save never writes over it, so the reservation holds; Save As to another file still works.
|
||||
pub read_only_source: Option<String>,
|
||||
/// Whether the scripts stored in this workbook may run (`automate.runScript`). A workbook
|
||||
/// that arrives already carrying scripts (opened from a file) starts untrusted until the
|
||||
/// user trusts it in this session (`automate.trustScripts`); one with no scripts starts
|
||||
@@ -345,7 +348,11 @@ impl DocState {
|
||||
wb.refresh_equations();
|
||||
let scripts_trusted = !cmd::extra::has_scripts(&wb);
|
||||
let wb = Arc::new(wb);
|
||||
let sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
|
||||
let mut sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
|
||||
// A merged active cell is selected whole, as a click on it selects it (#1348).
|
||||
if let Some(sh) = wb.active() {
|
||||
sel.expand_merges(sh);
|
||||
}
|
||||
DocState {
|
||||
saved: wb.clone(),
|
||||
wb,
|
||||
@@ -360,6 +367,7 @@ impl DocState {
|
||||
sheet_selections: vec![],
|
||||
unlocked_ranges: vec![],
|
||||
content_kind: None,
|
||||
read_only_source: None,
|
||||
scripts_trusted,
|
||||
trust,
|
||||
touched: None,
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
//! external addresses; only the host, after showing the address and getting OK from the user,
|
||||
//! opens one through [`crate::Session::open_confirmed_link`], which no command reaches.
|
||||
|
||||
use gridcraft_core::RangeRef;
|
||||
use gridcraft_core::{CellRef, RangeRef};
|
||||
use gridcraft_formula::Expr;
|
||||
use gridcraft_model::{Hyperlink, Workbook};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use crate::{EngineError, Result, Session, UiRequest};
|
||||
@@ -86,6 +88,50 @@ pub fn classify(target: &str) -> LinkKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// The link of a cell: the one stored with it, or, for a cell whose formula is `HYPERLINK(target, …)`,
|
||||
/// the target that formula currently evaluates to. A scheme-less web address (`google.com`) is
|
||||
/// opened over `https`, as Excel does.
|
||||
pub fn cell_link(wb: &Workbook, sheet: usize, at: CellRef) -> Option<Hyperlink> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
if let Some(h) = sh.hyperlinks.get(&at) {
|
||||
return Some(h.clone());
|
||||
}
|
||||
let expr = sh.cell(at)?.formula.as_ref()?.expr()?;
|
||||
let Expr::Call(name, args) = &expr else { return None };
|
||||
if name != "HYPERLINK" {
|
||||
return None;
|
||||
}
|
||||
let value = gridcraft_calc::evaluate_expr(wb, sheet, at, args.first()?);
|
||||
let target = value.display().trim().to_string();
|
||||
if target.is_empty() || matches!(value, gridcraft_core::Value::Error(_)) {
|
||||
return None;
|
||||
}
|
||||
// a defined name or a table of that spelling (`sales.data`) stays an internal target
|
||||
let internal_name = wb.name(&target, sheet).is_some() || wb.table(&target).is_some();
|
||||
let target = if looks_like_web_address(&target) && !internal_name { format!("https://{target}") } else { target };
|
||||
let external = !matches!(classify(&target), LinkKind::Internal(_));
|
||||
Some(Hyperlink { target, tooltip: None, external })
|
||||
}
|
||||
|
||||
fn looks_like_web_address(t: &str) -> bool {
|
||||
if t.contains(|c: char| c.is_whitespace() || matches!(c, '\\' | '!')) {
|
||||
return false;
|
||||
}
|
||||
// the host ends at the path, query or fragment (`google.com/x`, `google.com?q=1`, `google.com#top`)
|
||||
let host = t.split(['/', '?', '#']).next().unwrap_or(t);
|
||||
// with an optional port (`example.com:8443`); any other colon is a scheme or a sheet reference
|
||||
let host = match host.split_once(':') {
|
||||
Some((h, port)) if !port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit()) => h,
|
||||
Some(_) => return false,
|
||||
None => host,
|
||||
};
|
||||
let Some((_, tld)) = host.rsplit_once('.') else { return false };
|
||||
tld.len() >= 2
|
||||
&& tld.chars().all(|c| c.is_ascii_alphabetic())
|
||||
&& !["xlsx", "xlsm", "xlsb", "xls", "csv", "txt", "pdf", "doc", "docx"].contains(&tld.to_ascii_lowercase().as_str())
|
||||
&& RangeRef::parse(t).is_none()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::{HashMap, HashSet};
|
||||
|
||||
use gridcraft_core::date::datetime_from_serial;
|
||||
pub use gridcraft_core::quote_sheet;
|
||||
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, split_sheet};
|
||||
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, number_to_text, split_sheet};
|
||||
use gridcraft_model::{
|
||||
BorderLine, BorderStyle, Cell, Chart, Color, Fill, HAlign, NumFmt, PivotDataCell, PivotDateGroup, PivotField, PivotFilter, PivotFunc,
|
||||
PivotItemRef, PivotLayout, PivotLookup, PivotShowAs, PivotSort, PivotTable, PivotValue, Series, Style, StyleId, Workbook,
|
||||
@@ -32,7 +32,6 @@ pub use items::{distinct_labels, func_caption, item_label};
|
||||
use output::data_cols_exceed_sheet;
|
||||
pub use output::{CellKind, OutCell, Output, RowKind};
|
||||
use output::{cell_style, look};
|
||||
|
||||
/// Largest source block read (cells).
|
||||
pub const MAX_SOURCE_CELLS: u64 = 10_000_000;
|
||||
/// Largest report written (cells).
|
||||
@@ -61,12 +60,52 @@ pub struct Source {
|
||||
/// Numeric with a date number format.
|
||||
pub dates: Vec<bool>,
|
||||
pub rows: Vec<Vec<Value>>,
|
||||
/// The sheet row of each record (blank rows are skipped).
|
||||
pub record_rows: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub fn col(&self, name: &str) -> Option<usize> {
|
||||
self.headers.iter().position(|h| h.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// Per record: the column's cell is a number whose own format is a date (Excel caches such
|
||||
/// a number as `<d>` and sorts it after errors), and no cell of the column holds that number
|
||||
/// with a non-date format: a number in any General cell is a number item, whatever the row
|
||||
/// order or report filter. Looks up each distinct style once.
|
||||
pub fn date_cells(&self, wb: &Workbook, col: usize) -> Vec<bool> {
|
||||
let (Some(sh), Ok(off)) = (wb.sheet(self.sheet), u32::try_from(col)) else {
|
||||
return vec![false; self.rows.len()];
|
||||
};
|
||||
let c = self.range.start.col + off;
|
||||
let mut memo: HashMap<StyleId, bool> = HashMap::new();
|
||||
let mut dates: Vec<bool> = self
|
||||
.rows
|
||||
.iter()
|
||||
.zip(&self.record_rows)
|
||||
.map(|(rec, &row)| {
|
||||
rec.get(col).is_some_and(Value::is_number)
|
||||
&& *memo
|
||||
.entry(sh.style_id(CellRef::new(row, c)))
|
||||
.or_insert_with_key(|id| crate::display::number_format(wb.styles.get(*id).num_fmt.as_str()).is_date())
|
||||
})
|
||||
.collect();
|
||||
if !dates.contains(&true) {
|
||||
return dates;
|
||||
}
|
||||
let number = |rec: &Vec<Value>| match rec.get(col) {
|
||||
Some(Value::Number(n)) => Some(n.to_bits()),
|
||||
_ => None,
|
||||
};
|
||||
let general: HashSet<u64> = dates.iter().zip(&self.rows).filter(|(d, _)| !**d).filter_map(|(_, rec)| number(rec)).collect();
|
||||
if !general.is_empty() {
|
||||
for (d, rec) in dates.iter_mut().zip(&self.rows) {
|
||||
if *d && number(rec).is_some_and(|n| general.contains(&n)) {
|
||||
*d = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
dates
|
||||
}
|
||||
}
|
||||
|
||||
/// Absolute reference text for a range on a sheet: `Sheet1!$A$1:$E$20`.
|
||||
@@ -159,6 +198,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
|
||||
}
|
||||
let w = headers.len();
|
||||
let mut rows = Vec::new();
|
||||
let mut record_rows = Vec::new();
|
||||
let mut numeric = vec![true; w];
|
||||
let mut any = vec![false; w];
|
||||
if r.end.row > r.start.row {
|
||||
@@ -179,6 +219,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
|
||||
}
|
||||
}
|
||||
}
|
||||
record_rows.push(row);
|
||||
rows.push(rec);
|
||||
}
|
||||
}
|
||||
@@ -186,7 +227,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
|
||||
*n = *n && *a;
|
||||
}
|
||||
let dates = numeric.iter().zip(formats.iter()).map(|(n, f)| *n && crate::display::parsed(f).is_date()).collect();
|
||||
Ok(Source { sheet: si, range: r, headers, formats, numeric, dates, rows })
|
||||
Ok(Source { sheet: si, range: r, headers, formats, numeric, dates, rows, record_rows })
|
||||
}
|
||||
|
||||
/// Computes a PivotTable report from the workbook.
|
||||
|
||||
@@ -81,6 +81,8 @@ pub fn chart_series(sheet: &str, origin: CellRef, out: &Output) -> Vec<Series> {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::items::{Acc, FieldItems, build_tree, collect_siblings, is_collapsed, item_label};
|
||||
use super::items::{Acc, ByValue, FieldItems, build_tree, collect_siblings, date_flags, is_collapsed, item_label};
|
||||
use super::output::{
|
||||
AggMap, CellKind, ColKind, ColSpec, Ctx, Grid, Line, LineKind, Output, RowKind, ValSrc, caption, data_cols_exceed_sheet, flatten_cols,
|
||||
};
|
||||
@@ -83,6 +83,8 @@ struct AggregateInput<'a> {
|
||||
filter_sets: &'a [Option<HashSet<String>>],
|
||||
row_fmts: &'a [String],
|
||||
col_fmts: &'a [String],
|
||||
row_dates: &'a [Vec<bool>],
|
||||
col_dates: &'a [Vec<bool>],
|
||||
empty: bool,
|
||||
}
|
||||
|
||||
@@ -119,12 +121,14 @@ fn aggregate_record(
|
||||
return Ok(());
|
||||
}
|
||||
let mut row_path = Vec::with_capacity(input.rows.len());
|
||||
for (((column, field), items), fmt) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts) {
|
||||
row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri));
|
||||
for ((((column, field), items), fmt), dates) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts).zip(input.row_dates) {
|
||||
let date = dates.get(ri).copied().unwrap_or(false);
|
||||
row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri));
|
||||
}
|
||||
let mut col_path = Vec::with_capacity(input.cols.len());
|
||||
for (((column, field), items), fmt) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts) {
|
||||
col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri));
|
||||
for ((((column, field), items), fmt), dates) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts).zip(input.col_dates) {
|
||||
let date = dates.get(ri).copied().unwrap_or(false);
|
||||
col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri));
|
||||
}
|
||||
for row_depth in 0..=row_path.len() {
|
||||
for col_depth in 0..=col_path.len() {
|
||||
@@ -197,23 +201,49 @@ struct HeaderInput<'a> {
|
||||
k: usize,
|
||||
l: usize,
|
||||
headers_on: bool,
|
||||
row_caption: Option<&'a str>,
|
||||
data_caption: Option<&'a str>,
|
||||
col_caption: Option<&'a str>,
|
||||
grand_caption: &'a str,
|
||||
classic: bool,
|
||||
show_values_row: bool,
|
||||
}
|
||||
|
||||
fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
|
||||
let HeaderInput { vals, row_fields, col_fields, col_items, col_fmts, vpos, data_cols, specs, row_levels, compact, on_rows, k, l, headers_on } =
|
||||
input;
|
||||
let HeaderInput {
|
||||
vals,
|
||||
row_fields,
|
||||
col_fields,
|
||||
col_items,
|
||||
col_fmts,
|
||||
vpos,
|
||||
data_cols,
|
||||
specs,
|
||||
row_levels,
|
||||
compact,
|
||||
on_rows,
|
||||
k,
|
||||
l,
|
||||
headers_on,
|
||||
row_caption,
|
||||
data_caption,
|
||||
col_caption,
|
||||
grand_caption,
|
||||
classic,
|
||||
show_values_row,
|
||||
} = input;
|
||||
let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default();
|
||||
let row_header = |g: &mut Grid, r: usize| {
|
||||
if row_levels == 0 || !headers_on {
|
||||
return;
|
||||
}
|
||||
if compact {
|
||||
g.set(r, 0, Value::text("Row Labels"), CellKind::Header, 0, None);
|
||||
g.set(r, 0, Value::text(row_caption.unwrap_or("Row Labels")), CellKind::Header, 0, None);
|
||||
} else {
|
||||
// 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();
|
||||
// One column per row field, Σ Values (its caption, "Values" by default) at its place.
|
||||
let mut names: Vec<&str> = row_fields.iter().map(|f| f.header()).collect();
|
||||
if let Some(p) = vpos {
|
||||
names.insert(p.min(names.len()), "Values");
|
||||
names.insert(p.min(names.len()), data_caption.unwrap_or("Values"));
|
||||
}
|
||||
for (i, name) in names.into_iter().enumerate() {
|
||||
g.set(r, i, Value::text(name), CellKind::Header, 0, None);
|
||||
@@ -223,12 +253,23 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
|
||||
|
||||
// ---- header rows
|
||||
if col_fields.is_empty() {
|
||||
let classic = classic && !compact && k == 1 && headers_on;
|
||||
if classic {
|
||||
let r = g.push_row(RowKind::Header)?;
|
||||
g.set(r, 0, Value::text(val_name(0)), CellKind::Header, 0, None);
|
||||
}
|
||||
if !compact && k > 1 && !on_rows && show_values_row && headers_on {
|
||||
let r = g.push_row(RowKind::Header)?;
|
||||
g.set(r, l, Value::text(data_caption.unwrap_or("Values")), CellKind::Header, 0, None);
|
||||
}
|
||||
let r = g.push_row(RowKind::Header)?;
|
||||
row_header(g, r);
|
||||
for (j, (_, vi)) in data_cols.iter().enumerate() {
|
||||
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.
|
||||
Some(vi) => {
|
||||
let caption = if classic { "Total".to_string() } else { val_name(*vi) };
|
||||
g.set(r, l + j, Value::text(caption), CellKind::Header, 0, None);
|
||||
}
|
||||
None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None),
|
||||
None => {}
|
||||
}
|
||||
@@ -239,7 +280,11 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
|
||||
g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None);
|
||||
}
|
||||
if headers_on {
|
||||
let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() };
|
||||
let caption = if compact {
|
||||
col_caption.unwrap_or("Column Labels").to_string()
|
||||
} else {
|
||||
col_fields.first().map(|f| f.header().to_string()).unwrap_or_default()
|
||||
};
|
||||
g.set(cap, l, Value::text(caption), CellKind::Header, 0, None);
|
||||
}
|
||||
let levels = col_fields.len() + usize::from(k > 1 && !on_rows);
|
||||
@@ -257,8 +302,8 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
|
||||
let same = prev.is_some_and(|p| p.kind != ColKind::Grand && p.path.get(..=lv) == spec.path.get(..=lv));
|
||||
if !same {
|
||||
let Some(item) = col_items.get(lv).and_then(|fi| fi.get(it)) else { continue };
|
||||
let fmt = if item.formatted { col_fmts.get(lv).cloned() } else { None };
|
||||
g.set(first_level + lv, c, item.value.clone(), CellKind::ColLabel, 0, fmt);
|
||||
let fmt = if item.formatted && item.caption.is_none() { col_fmts.get(lv).cloned() } else { None };
|
||||
g.set(first_level + lv, c, item.shown_value(), CellKind::ColLabel, 0, fmt);
|
||||
}
|
||||
}
|
||||
if k > 1
|
||||
@@ -269,7 +314,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
|
||||
}
|
||||
ColKind::Subtotal => {
|
||||
let lv = spec.path.len().saturating_sub(1);
|
||||
let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.label(*it))).unwrap_or_default();
|
||||
let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.shown_label(*it))).unwrap_or_default();
|
||||
let text = match vi {
|
||||
Some(vi) if k > 1 => caption(&label, &val_name(*vi)),
|
||||
_ => caption(&label, "Total"),
|
||||
@@ -279,7 +324,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
|
||||
ColKind::Grand => {
|
||||
let text = match vi {
|
||||
Some(vi) if k > 1 => format!("Total {}", val_name(*vi)),
|
||||
_ => "Grand Total".to_string(),
|
||||
_ => grand_caption.to_string(),
|
||||
};
|
||||
g.set(first_level, c, Value::text(text), CellKind::ColLabel, 0, None);
|
||||
}
|
||||
@@ -292,7 +337,6 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ValueLookup<'a> {
|
||||
wb: &'a Workbook,
|
||||
source: &'a Source,
|
||||
@@ -539,8 +583,11 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
let filter_fmts: Vec<String> = filters.iter().map(|f| fmt_of(f.0)).collect();
|
||||
let filter_sets: Vec<Option<HashSet<String>>> =
|
||||
filters.iter().map(|(_, field, _, _)| field.selected.as_ref().map(|s| s.iter().map(|v| v.to_ascii_lowercase()).collect())).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();
|
||||
let field_fmt = |c: usize, f: &PivotField| f.number_format.clone().unwrap_or_else(|| fmt_of(c));
|
||||
let row_fmts: Vec<String> = rows.iter().map(|(c, f)| field_fmt(*c, f)).collect();
|
||||
let col_fmts: Vec<String> = cols.iter().map(|(c, f)| field_fmt(*c, f)).collect();
|
||||
let row_dates: Vec<Vec<bool>> = rows.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect();
|
||||
let col_dates: Vec<Vec<bool>> = cols.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect();
|
||||
let aggregate = aggregate_source(
|
||||
AggregateInput {
|
||||
wb,
|
||||
@@ -555,33 +602,83 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
filter_sets: &filter_sets,
|
||||
row_fmts: &row_fmts,
|
||||
col_fmts: &col_fmts,
|
||||
row_dates: &row_dates,
|
||||
col_dates: &col_dates,
|
||||
empty,
|
||||
},
|
||||
&mut probe,
|
||||
)?;
|
||||
let AggregateData { row_items, col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate;
|
||||
let AggregateData { mut row_items, mut col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate;
|
||||
|
||||
for (fi, (_, f)) in row_items.iter_mut().zip(rows.iter()) {
|
||||
fi.apply(f);
|
||||
}
|
||||
for (fi, (_, f)) in col_items.iter_mut().zip(cols.iter()) {
|
||||
fi.apply(f);
|
||||
}
|
||||
|
||||
let get = |rp: &[u32], cp: &[u32], vi: usize| -> Option<Value> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ---- axes
|
||||
let row_fields: Vec<&PivotField> = rows.iter().map(|(_, f)| *f).collect();
|
||||
let col_fields: Vec<&PivotField> = cols.iter().map(|(_, f)| *f).collect();
|
||||
let row_paths: Vec<&[u32]> = row_set.iter().map(Vec::as_slice).collect();
|
||||
let col_paths: Vec<&[u32]> = col_set.iter().map(Vec::as_slice).collect();
|
||||
let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items);
|
||||
let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items);
|
||||
// The other-axis path a sort scope names: its items of the other axis's fields, outer first,
|
||||
// up to the first field it doesn't name. A scope naming an item that isn't there sorts by the
|
||||
// grand total, as the writer then drops it.
|
||||
let scope_path = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| -> Vec<u32> {
|
||||
let mut path = Vec::new();
|
||||
for ((_, o), oi) in others.iter().zip(other_items) {
|
||||
let Some(e) = f.sort_scope.iter().find(|e| e.is_of(o)) else { break };
|
||||
match oi.find(&e.item) {
|
||||
Some(i) => path.push(i),
|
||||
None => return Vec::new(),
|
||||
}
|
||||
}
|
||||
path
|
||||
};
|
||||
let sorting = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| {
|
||||
let vi = f.sort_by.as_deref().and_then(|n| vals.iter().position(|(_, v)| v.name.eq_ignore_ascii_case(n)))?;
|
||||
Some((vi, scope_path(f, others, other_items)))
|
||||
};
|
||||
let row_value = |p: &[u32], other: &[u32], vi: usize| get(p, other, vi).as_ref().and_then(Value::as_f64);
|
||||
let col_value = |p: &[u32], other: &[u32], vi: usize| get(other, p, vi).as_ref().and_then(Value::as_f64);
|
||||
let row_by = ByValue { fields: row_fields.iter().map(|f| sorting(f, &cols, &col_items)).collect(), value: &row_value };
|
||||
let col_by = ByValue { fields: col_fields.iter().map(|f| sorting(f, &rows, &row_items)).collect(), value: &col_value };
|
||||
let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items, &row_by);
|
||||
let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items, &col_by);
|
||||
let mut siblings: HashMap<Vec<u32>, Vec<u32>> = HashMap::new();
|
||||
collect_siblings(&row_tree, &mut Vec::new(), &mut siblings);
|
||||
let level0: Vec<u32> = row_tree.iter().map(|n| n.item).collect();
|
||||
|
||||
let val_names: Vec<String> = vals.iter().map(|(_, v)| v.name.clone()).collect();
|
||||
let grand_caption = pt.grand_total_caption.as_deref().unwrap_or("Grand Total");
|
||||
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 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, None, &mut Vec::new(), &[], &mut lines);
|
||||
ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut Vec::new(), &mut lines);
|
||||
} else {
|
||||
ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut lines);
|
||||
ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut Vec::new(), &mut lines);
|
||||
}
|
||||
// With only Σ Values in Rows its items are the totals already.
|
||||
if pt.grand_totals_cols && !rows.is_empty() {
|
||||
@@ -596,7 +693,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
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));
|
||||
lines.push(grand(grand_caption.into(), None));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -604,7 +701,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
if cols.is_empty() {
|
||||
specs.push(ColSpec { kind: ColKind::Leaf, path: vec![] });
|
||||
} else {
|
||||
flatten_cols(&col_tree, 0, &col_fields, &col_items, pt.subtotals, &mut Vec::new(), &mut specs);
|
||||
flatten_cols(&col_tree, 0, &col_fields, &col_items, pt, &mut Vec::new(), &mut specs);
|
||||
if pt.grand_totals_rows {
|
||||
specs.push(ColSpec { kind: ColKind::Grand, path: vec![] });
|
||||
}
|
||||
@@ -678,6 +775,12 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
k,
|
||||
l,
|
||||
headers_on: pt.show_headers,
|
||||
row_caption: pt.row_header_caption.as_deref(),
|
||||
data_caption: pt.data_caption.as_deref(),
|
||||
col_caption: pt.col_header_caption.as_deref(),
|
||||
grand_caption: pt.grand_total_caption.as_deref().unwrap_or("Grand Total"),
|
||||
classic: pt.classic_layout,
|
||||
show_values_row: pt.show_values_row,
|
||||
},
|
||||
)?;
|
||||
let val_name = |vi: usize| vals.get(vi).map(|(_, value)| value.name.clone()).unwrap_or_default();
|
||||
@@ -714,7 +817,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
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();
|
||||
spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.shown_label(*it)).unwrap_or_default()).collect();
|
||||
if let Some(vi) = vi
|
||||
&& (k > 1 || parts.is_empty())
|
||||
{
|
||||
@@ -733,15 +836,6 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
} else {
|
||||
Some(row_levels.saturating_sub(1) as u32)
|
||||
};
|
||||
let item_refs = |fields: &[&PivotField], items: &[FieldItems], path: &[u32]| -> Vec<PivotItemRef> {
|
||||
path.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(d, it)| {
|
||||
let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?);
|
||||
Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() })
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut data: Vec<PivotDataCell> = Vec::new();
|
||||
for line in &lines {
|
||||
let rk = match line.kind {
|
||||
@@ -764,40 +858,102 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
|
||||
if !line.values {
|
||||
continue;
|
||||
}
|
||||
let rp = line.path.as_slice();
|
||||
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) = lookup.get(rp, cp, *vi) else { continue };
|
||||
let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0: &level0, siblings: &siblings, cache: &show_cache };
|
||||
let shown = show_value(vdef, raw, &lookup, &context);
|
||||
// Every value cell of the report is indexed, so a report that needs more cells than
|
||||
// the index cap is rejected outright — never written with a truncated index that
|
||||
// would answer #REF! for the values the sheet shows.
|
||||
if data.len() >= MAX_INDEXED_CELLS {
|
||||
return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells."));
|
||||
}
|
||||
let mut items = item_refs(&ctx.rows, &ctx.row_items, rp);
|
||||
items.extend(item_refs(&col_fields, &col_items, cp));
|
||||
data.push(PivotDataCell {
|
||||
data_field: vdef.name.clone(),
|
||||
source_col: vdef.source_col.clone(),
|
||||
items,
|
||||
row: u32::try_from(r).unwrap_or(u32::MAX),
|
||||
col: u32::try_from(l + j).unwrap_or(u32::MAX),
|
||||
});
|
||||
if let Some(pr) = probe.as_deref_mut() {
|
||||
if pr.at == Some((r, l + j)) {
|
||||
pr.hit = Some((rp.to_vec(), cp.to_vec()));
|
||||
}
|
||||
if let Some(cells) = pr.cells.as_mut() {
|
||||
cells.insert((r, l + j));
|
||||
}
|
||||
}
|
||||
g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten());
|
||||
}
|
||||
fill_line_values(
|
||||
&mut g,
|
||||
r,
|
||||
line,
|
||||
&data_cols,
|
||||
&specs,
|
||||
&vals,
|
||||
&data_fmt,
|
||||
l,
|
||||
ck.1,
|
||||
pt,
|
||||
&ctx,
|
||||
&col_fields,
|
||||
&col_items,
|
||||
&lookup,
|
||||
&level0,
|
||||
&siblings,
|
||||
&show_cache,
|
||||
&mut probe,
|
||||
&mut data,
|
||||
)?;
|
||||
}
|
||||
Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col, data })
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn fill_line_values(
|
||||
g: &mut Grid,
|
||||
r: usize,
|
||||
line: &Line,
|
||||
data_cols: &[(usize, Option<usize>)],
|
||||
specs: &[ColSpec],
|
||||
vals: &[(ValSrc, &PivotValue)],
|
||||
data_fmt: &[Option<String>],
|
||||
l: usize,
|
||||
ck: CellKind,
|
||||
pt: &PivotTable,
|
||||
ctx: &Ctx<'_>,
|
||||
col_fields: &[&PivotField],
|
||||
col_items: &[FieldItems],
|
||||
lookup: &ValueLookup<'_>,
|
||||
level0: &[u32],
|
||||
siblings: &HashMap<Vec<u32>, Vec<u32>>,
|
||||
show_cache: &ShowCache,
|
||||
probe: &mut Option<&mut Probe>,
|
||||
data: &mut Vec<PivotDataCell>,
|
||||
) -> Result<(), String> {
|
||||
let rp = line.path.as_slice();
|
||||
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) = lookup.get(rp, cp, *vi) else {
|
||||
// No records: blank, or the "For empty cells show" caption (a number when it
|
||||
// reads as one, as Excel stores `missingCaption="0"`).
|
||||
if let Some(c) = &pt.empty_caption {
|
||||
let v = c.trim().parse::<f64>().ok().filter(|x| x.is_finite()).map(Value::number).unwrap_or_else(|| Value::text(c.as_str()));
|
||||
let fmt = if matches!(v, Value::Number(_)) { data_fmt.get(*vi).cloned().flatten() } else { None };
|
||||
g.set(r, l + j, v, ck, 0, fmt);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0, siblings, cache: show_cache };
|
||||
let shown = show_value(vdef, raw, lookup, &context);
|
||||
if data.len() >= MAX_INDEXED_CELLS {
|
||||
return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells."));
|
||||
}
|
||||
let mut items = item_refs(&ctx.rows, &ctx.row_items, rp);
|
||||
items.extend(item_refs(col_fields, col_items, cp));
|
||||
data.push(PivotDataCell {
|
||||
data_field: vdef.name.clone(),
|
||||
source_col: vdef.source_col.clone(),
|
||||
items,
|
||||
row: u32::try_from(r).unwrap_or(u32::MAX),
|
||||
col: u32::try_from(l + j).unwrap_or(u32::MAX),
|
||||
});
|
||||
if let Some(pr) = probe.as_deref_mut() {
|
||||
if pr.at == Some((r, l + j)) {
|
||||
pr.hit = Some((rp.to_vec(), cp.to_vec()));
|
||||
}
|
||||
if let Some(cells) = pr.cells.as_mut() {
|
||||
cells.insert((r, l + j));
|
||||
}
|
||||
}
|
||||
g.set(r, l + j, shown, ck, 0, data_fmt.get(*vi).cloned().flatten());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn item_refs(fields: &[&PivotField], items: &[FieldItems], path: &[u32]) -> Vec<PivotItemRef> {
|
||||
path.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(d, it)| {
|
||||
let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?);
|
||||
Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial};
|
||||
use super::{
|
||||
CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial,
|
||||
number_to_text,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- items
|
||||
|
||||
@@ -14,6 +17,20 @@ pub(super) struct Item {
|
||||
first: usize,
|
||||
/// The value is a number shown with the source format.
|
||||
pub(super) formatted: bool,
|
||||
/// The item's custom name (a renamed item).
|
||||
pub(super) caption: Option<String>,
|
||||
/// Position in the field's manual item order.
|
||||
rank: Option<usize>,
|
||||
}
|
||||
|
||||
impl Item {
|
||||
/// The value shown: the custom name, else the item's value.
|
||||
pub(super) fn shown_value(&self) -> Value {
|
||||
self.caption.as_deref().map(Value::text).unwrap_or_else(|| self.value.clone())
|
||||
}
|
||||
pub(super) fn shown_label(&self) -> &str {
|
||||
self.caption.as_deref().unwrap_or(&self.label)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -22,12 +39,15 @@ pub(super) struct FieldItems {
|
||||
index: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
/// Sort classes: numbers, text, logicals, errors, dates (a number whose own cell has a date
|
||||
/// format, which Excel caches as `<d>` and sorts after errors), blanks.
|
||||
fn cmp_items(a: &Item, b: &Item) -> Ordering {
|
||||
a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| gridcraft_core::compare_text(&a.text, &b.text))
|
||||
}
|
||||
|
||||
/// (identity key, item) for a source value under a field's date grouping.
|
||||
fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> (String, Item) {
|
||||
/// (identity key, item) for a source value under a field's date grouping; `date` marks a number
|
||||
/// whose cell has a date format.
|
||||
fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> (String, Item) {
|
||||
let it = |value: Value, label: String, class: u8, num: f64, formatted: bool| Item {
|
||||
text: label.to_lowercase(),
|
||||
value,
|
||||
@@ -36,9 +56,11 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first:
|
||||
num,
|
||||
first,
|
||||
formatted,
|
||||
caption: None,
|
||||
rank: None,
|
||||
};
|
||||
match v {
|
||||
Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)),
|
||||
Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 5, 0.0, false)),
|
||||
Value::Number(n) => {
|
||||
if group != PivotDateGroup::None
|
||||
&& let Some(dt) = datetime_from_serial(wb.date_system, *n)
|
||||
@@ -55,8 +77,9 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first:
|
||||
};
|
||||
return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false));
|
||||
}
|
||||
let label = crate::display::format(v, fmt, wb).text;
|
||||
(format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true))
|
||||
let shown = crate::display::format(v, fmt, wb);
|
||||
let class = if date { 4 } else { 0 };
|
||||
(format!("n{}", n.to_bits()), it(v.clone(), shown.text, class, *n, true))
|
||||
}
|
||||
Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)),
|
||||
Value::Bool(b) => {
|
||||
@@ -64,13 +87,13 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first:
|
||||
(format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false))
|
||||
}
|
||||
Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)),
|
||||
Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first),
|
||||
Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, date, first),
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldItems {
|
||||
pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> u32 {
|
||||
let (key, item) = make_item(wb, v, group, fmt, first);
|
||||
pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> u32 {
|
||||
let (key, item) = make_item(wb, v, group, fmt, date, first);
|
||||
if let Some(i) = self.index.get(&key) {
|
||||
return *i;
|
||||
}
|
||||
@@ -85,20 +108,50 @@ impl FieldItems {
|
||||
pub(super) fn label(&self, i: u32) -> String {
|
||||
self.get(i).map(|x| x.label.clone()).unwrap_or_default()
|
||||
}
|
||||
pub(super) fn shown_label(&self, i: u32) -> String {
|
||||
self.get(i).map(|x| x.shown_label().to_string()).unwrap_or_default()
|
||||
}
|
||||
/// The item a setting names by label (or, for a number item, its unformatted number text).
|
||||
pub(super) fn find(&self, label: &str) -> Option<u32> {
|
||||
let l = label.to_lowercase();
|
||||
let i = self.items.iter().position(|it| it.text == l || (it.formatted && number_to_text(it.num).to_lowercase() == l))?;
|
||||
u32::try_from(i).ok()
|
||||
}
|
||||
/// Applies a field's renamed items and manual item order. Settings name items by label; a
|
||||
/// number item also matches its unformatted number text (how a file's cache names it).
|
||||
pub(super) fn apply(&mut self, f: &PivotField) {
|
||||
if f.item_captions.is_empty() && f.item_order.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut order: HashMap<String, usize> = HashMap::new();
|
||||
for (i, l) in f.item_order.iter().enumerate() {
|
||||
order.entry(l.to_lowercase()).or_insert(i);
|
||||
}
|
||||
let mut captions: HashMap<String, &str> = HashMap::new();
|
||||
for (l, c) in &f.item_captions {
|
||||
captions.entry(l.to_lowercase()).or_insert(c.as_str());
|
||||
}
|
||||
for it in &mut self.items {
|
||||
let raw = if it.formatted { Some(number_to_text(it.num).to_lowercase()) } else { None };
|
||||
it.rank = order.get(&it.text).or_else(|| raw.as_ref().and_then(|r| order.get(r))).copied();
|
||||
it.caption = captions.get(&it.text).or_else(|| raw.as_ref().and_then(|r| captions.get(r))).map(|c| c.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The label of a source value under a date grouping (for filters and field lists).
|
||||
pub fn item_label(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str) -> String {
|
||||
make_item(wb, v, group, fmt, 0).1.label
|
||||
make_item(wb, v, group, fmt, false, 0).1.label
|
||||
}
|
||||
|
||||
/// Distinct item labels of a source column, sorted like the field list shows them.
|
||||
pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup, limit: usize) -> Vec<String> {
|
||||
let mut fi = FieldItems::default();
|
||||
let fmt = src.formats.get(col).map(String::as_str).unwrap_or("General");
|
||||
let dates = date_flags(wb, src, col, group);
|
||||
for (i, r) in src.rows.iter().enumerate() {
|
||||
if let Some(v) = r.get(col) {
|
||||
fi.intern(wb, v, group, fmt, i);
|
||||
fi.intern(wb, v, group, fmt, dates.get(i).copied().unwrap_or(false), i);
|
||||
}
|
||||
if fi.items.len() > 100_000 {
|
||||
break;
|
||||
@@ -109,6 +162,11 @@ pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDate
|
||||
items.into_iter().take(limit).map(|i| i.label).collect()
|
||||
}
|
||||
|
||||
/// [`Source::date_cells`] for an ungrouped field; a date-grouped field doesn't use them.
|
||||
pub(super) fn date_flags(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup) -> Vec<bool> {
|
||||
if group == PivotDateGroup::None { src.date_cells(wb, col) } else { Vec::new() }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- aggregation
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -252,7 +310,17 @@ pub(super) struct Node {
|
||||
pub(super) children: Vec<Node>,
|
||||
}
|
||||
|
||||
pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec<Node> {
|
||||
/// Sorting of an axis by value fields: per axis field, the value field it sorts by and the path
|
||||
/// on the other axis whose values it uses (empty = the total); and the value of an axis path at
|
||||
/// an other-axis path.
|
||||
pub(super) type ValueLookup<'a> = &'a dyn Fn(&[u32], &[u32], usize) -> Option<f64>;
|
||||
|
||||
pub(super) struct ByValue<'a> {
|
||||
pub(super) fields: Vec<Option<(usize, Vec<u32>)>>,
|
||||
pub(super) value: ValueLookup<'a>,
|
||||
}
|
||||
|
||||
pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems], by_value: &ByValue) -> Vec<Node> {
|
||||
let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] };
|
||||
let mut order: Vec<u32> = Vec::new();
|
||||
let mut groups: HashMap<u32, Vec<&[u32]>> = HashMap::new();
|
||||
@@ -265,23 +333,36 @@ pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField],
|
||||
g.push(p);
|
||||
}
|
||||
}
|
||||
let mut nodes: Vec<Node> = order
|
||||
let vi = by_value.fields.get(depth).and_then(Option::as_ref).filter(|_| field.sort != PivotSort::None);
|
||||
let mut nodes: Vec<(Option<f64>, Node)> = order
|
||||
.into_iter()
|
||||
.map(|it| {
|
||||
let ps = groups.remove(&it).unwrap_or_default();
|
||||
Node { item: it, children: build_tree(&ps, depth + 1, fields, items) }
|
||||
let key = vi.and_then(|(vi, other)| ps.first().and_then(|p| p.get(..=depth)).and_then(|p| (by_value.value)(p, other, *vi)));
|
||||
(key, Node { item: it, children: build_tree(&ps, depth + 1, fields, items, by_value) })
|
||||
})
|
||||
.collect();
|
||||
let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) {
|
||||
let by_label = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) {
|
||||
(Some(x), Some(y)) => match field.sort {
|
||||
PivotSort::Asc => cmp_items(x, y),
|
||||
PivotSort::Desc => cmp_items(y, x),
|
||||
PivotSort::None => x.first.cmp(&y.first),
|
||||
PivotSort::None => x.rank.unwrap_or(usize::MAX).cmp(&y.rank.unwrap_or(usize::MAX)).then_with(|| {
|
||||
// Date groups are in date order, like the groups Excel's cache lists.
|
||||
if field.date_group == PivotDateGroup::None { x.first.cmp(&y.first) } else { cmp_items(x, y) }
|
||||
}),
|
||||
},
|
||||
_ => Ordering::Equal,
|
||||
};
|
||||
nodes.sort_by(by);
|
||||
nodes
|
||||
// By value: numbers in the sort direction, then items without a number; ties by label.
|
||||
let by_key = |a: &Option<f64>, b: &Option<f64>| match (a, b) {
|
||||
(Some(x), Some(y)) if field.sort == PivotSort::Desc => y.total_cmp(x),
|
||||
(Some(x), Some(y)) => x.total_cmp(y),
|
||||
(Some(_), None) => Ordering::Less,
|
||||
(None, Some(_)) => Ordering::Greater,
|
||||
(None, None) => Ordering::Equal,
|
||||
};
|
||||
nodes.sort_by(|(ka, a), (kb, b)| by_key(ka, kb).then_with(|| by_label(a, b)));
|
||||
nodes.into_iter().map(|(_, n)| n).collect()
|
||||
}
|
||||
|
||||
pub(super) fn is_collapsed(field: &PivotField, label: &str) -> bool {
|
||||
|
||||
@@ -151,11 +151,22 @@ pub(super) struct Ctx<'a> {
|
||||
pub(super) val_names: Vec<String>,
|
||||
}
|
||||
|
||||
/// A label cell of a report line: (column, value, indent, number format).
|
||||
type Label = (usize, Value, u8, Option<String>);
|
||||
|
||||
/// Whether an axis field shows subtotals (its own setting, else the table's).
|
||||
pub(super) fn shows_subtotals(pt: &PivotTable, f: Option<&&PivotField>) -> bool {
|
||||
f.and_then(|f| f.subtotal).unwrap_or(pt.subtotals)
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
fn label_cell(&self, depth: usize, item: u32) -> (Value, Option<String>, String) {
|
||||
let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) };
|
||||
let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None };
|
||||
(it.value.clone(), fmt, it.label.clone())
|
||||
/// (shown value, number format, item label, shown label) of a row item.
|
||||
fn label_cell(&self, depth: usize, item: u32) -> (Value, Option<String>, String, String) {
|
||||
let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else {
|
||||
return (Value::Empty, None, String::new(), String::new());
|
||||
};
|
||||
let fmt = if it.formatted && it.caption.is_none() { self.row_fmts.get(depth).cloned() } else { None };
|
||||
(it.shown_value(), fmt, it.label.clone(), it.shown_label().to_string())
|
||||
}
|
||||
|
||||
/// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form.
|
||||
@@ -184,86 +195,87 @@ impl Ctx<'_> {
|
||||
|
||||
/// 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>) {
|
||||
fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec<u32>, repeat: &mut Vec<Label>, 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 mut labels = repeat.clone();
|
||||
labels.push((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);
|
||||
self.flatten(nodes, depth, Some(vi), prefix, repeat, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn flatten(&self, nodes: &[Node], depth: usize, vi: Option<usize>, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
|
||||
/// Compact and Outline rows. `repeat` holds the labels of enclosing items repeated on each
|
||||
/// row (Outline, Repeat Item Labels).
|
||||
pub(super) fn flatten(
|
||||
&self,
|
||||
nodes: &[Node],
|
||||
depth: usize,
|
||||
vi: Option<usize>,
|
||||
prefix: &mut Vec<u32>,
|
||||
repeat: &mut Vec<Label>,
|
||||
out: &mut Vec<Line>,
|
||||
) {
|
||||
if self.values_here(depth, vi) {
|
||||
self.flatten_values(nodes, depth, prefix, out);
|
||||
self.flatten_values(nodes, depth, prefix, repeat, out);
|
||||
return;
|
||||
}
|
||||
let n = self.rows.len();
|
||||
let outline = self.pt.layout == PivotLayout::Outline;
|
||||
let field = self.rows.get(depth);
|
||||
let subtotals = shows_subtotals(self.pt, field);
|
||||
// Σ 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 collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
|
||||
let (v, fmt, label, shown) = self.label_cell(depth, node.item);
|
||||
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
|
||||
let leaf = depth + 1 >= n || collapsed || node.children.is_empty();
|
||||
let mut labels = repeat.clone();
|
||||
labels.push((col, v.clone(), indent, fmt.clone()));
|
||||
let pushed = !leaf && outline && field.is_some_and(|f| f.repeat_labels);
|
||||
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,
|
||||
});
|
||||
out.push(Line { kind: LineKind::Item(depth + 1 < n), leaf: true, path: prefix.clone(), values: true, labels, 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,
|
||||
});
|
||||
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: false, labels, 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);
|
||||
let level = if outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 };
|
||||
self.flatten_values(&[], level, prefix, repeat, 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);
|
||||
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: false, labels, vi });
|
||||
if pushed {
|
||||
repeat.push((col, v, indent, fmt));
|
||||
}
|
||||
self.flatten(&node.children, depth + 1, None, prefix, repeat, out);
|
||||
if pushed {
|
||||
repeat.pop();
|
||||
}
|
||||
if subtotals {
|
||||
self.value_subtotals(col, indent, &shown, prefix, out);
|
||||
}
|
||||
} else {
|
||||
let top = self.pt.subtotals && self.pt.subtotals_top;
|
||||
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 {
|
||||
let top = subtotals && self.pt.subtotals_top;
|
||||
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: top, labels, vi });
|
||||
if pushed {
|
||||
repeat.push((col, v, indent, fmt));
|
||||
}
|
||||
self.flatten(&node.children, depth + 1, vi, prefix, repeat, out);
|
||||
if pushed {
|
||||
repeat.pop();
|
||||
}
|
||||
if subtotals && !self.pt.subtotals_top {
|
||||
out.push(Line {
|
||||
kind: LineKind::Subtotal,
|
||||
leaf: false,
|
||||
path: prefix.clone(),
|
||||
values: true,
|
||||
labels: vec![(col, Value::text(caption(&label, "Total")), indent, None)],
|
||||
labels: vec![(col, Value::text(caption(&shown, "Total")), indent, None)],
|
||||
vi,
|
||||
});
|
||||
}
|
||||
@@ -278,59 +290,73 @@ impl Ctx<'_> {
|
||||
nodes: &[Node],
|
||||
depth: usize,
|
||||
prefix: &mut Vec<u32>,
|
||||
pending: &[(usize, Value, u8, Option<String>)],
|
||||
pending: &[Label],
|
||||
repeat: &mut Vec<Label>,
|
||||
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![] };
|
||||
let mut labels: Vec<Label> = if vi == 0 { pending.to_vec() } else { repeat.clone() };
|
||||
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);
|
||||
self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, repeat, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tabular rows: an item's label sits on its first child's row (`pending`); `repeat` holds
|
||||
/// the labels of enclosing items repeated on the other rows (Repeat Item Labels).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn flatten_tabular(
|
||||
&self,
|
||||
nodes: &[Node],
|
||||
depth: usize,
|
||||
vi: Option<usize>,
|
||||
prefix: &mut Vec<u32>,
|
||||
pending: &[(usize, Value, u8, Option<String>)],
|
||||
pending: &[Label],
|
||||
repeat: &mut Vec<Label>,
|
||||
out: &mut Vec<Line>,
|
||||
) {
|
||||
if self.values_here(depth, vi) {
|
||||
self.flatten_tabular_values(nodes, depth, prefix, pending, out);
|
||||
self.flatten_tabular_values(nodes, depth, prefix, pending, repeat, out);
|
||||
return;
|
||||
}
|
||||
let n = self.rows.len();
|
||||
let field = self.rows.get(depth);
|
||||
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((col, v, 0, fmt));
|
||||
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
|
||||
let (v, fmt, label, shown) = self.label_cell(depth, node.item);
|
||||
let mut labels: Vec<Label> = if i == 0 { pending.to_vec() } else { repeat.clone() };
|
||||
labels.push((col, v.clone(), 0, fmt.clone()));
|
||||
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
|
||||
if depth + 1 >= n || collapsed || node.children.is_empty() {
|
||||
if values_below {
|
||||
self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, out);
|
||||
self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, repeat, 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, vi, prefix, &labels, out);
|
||||
if self.pt.subtotals && values_below {
|
||||
self.value_subtotals(col, 0, &label, prefix, out);
|
||||
} else if self.pt.subtotals {
|
||||
let pushed = field.is_some_and(|f| f.repeat_labels);
|
||||
if pushed {
|
||||
repeat.push((col, v, 0, fmt));
|
||||
}
|
||||
self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, repeat, out);
|
||||
if pushed {
|
||||
repeat.pop();
|
||||
}
|
||||
let subtotals = shows_subtotals(self.pt, field);
|
||||
if subtotals && values_below {
|
||||
self.value_subtotals(col, 0, &shown, prefix, out);
|
||||
} else if subtotals {
|
||||
out.push(Line {
|
||||
kind: LineKind::Subtotal,
|
||||
leaf: false,
|
||||
path: prefix.clone(),
|
||||
values: true,
|
||||
labels: vec![(col, Value::text(caption(&label, "Total")), 0, None)],
|
||||
labels: vec![(col, Value::text(caption(&shown, "Total")), 0, None)],
|
||||
vi,
|
||||
});
|
||||
}
|
||||
@@ -345,20 +371,21 @@ pub(super) fn flatten_cols(
|
||||
depth: usize,
|
||||
fields: &[&PivotField],
|
||||
items: &[FieldItems],
|
||||
subtotals: bool,
|
||||
pt: &PivotTable,
|
||||
prefix: &mut Vec<u32>,
|
||||
out: &mut Vec<ColSpec>,
|
||||
) {
|
||||
let n = fields.len();
|
||||
let field = fields.get(depth);
|
||||
for node in nodes {
|
||||
prefix.push(node.item);
|
||||
let label = items.get(depth).map(|fi| fi.label(node.item)).unwrap_or_default();
|
||||
let collapsed = depth + 1 < n && fields.get(depth).is_some_and(|f| is_collapsed(f, &label));
|
||||
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
|
||||
if depth + 1 >= n || collapsed || node.children.is_empty() {
|
||||
out.push(ColSpec { kind: ColKind::Leaf, path: prefix.clone() });
|
||||
} else {
|
||||
flatten_cols(&node.children, depth + 1, fields, items, subtotals, prefix, out);
|
||||
if subtotals {
|
||||
flatten_cols(&node.children, depth + 1, fields, items, pt, prefix, out);
|
||||
if shows_subtotals(pt, field) {
|
||||
out.push(ColSpec { kind: ColKind::Subtotal, path: prefix.clone() });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,7 +154,9 @@ mod tests {
|
||||
assert_eq!(functions_in_formula("+SUM(1)"), ["SUM"]);
|
||||
assert_eq!(functions_in_formula("-ABS(A1)"), ["ABS"]);
|
||||
assert!(functions_in_formula("-5").is_empty() && functions_in_formula("+1e3").is_empty(), "numbers");
|
||||
assert!(functions_in_formula("+").is_empty() && functions_in_formula("- SUM(1)").is_empty(), "not formulas");
|
||||
assert!(functions_in_formula("+").is_empty() && functions_in_formula("--").is_empty(), "not formulas");
|
||||
// A sign before a space still starts a formula, as Excel takes `- SUM(1)` (#2023).
|
||||
assert_eq!(functions_in_formula("- SUM(1)"), ["SUM"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -111,6 +111,8 @@ fn sales(s: &mut Session) -> bool {
|
||||
quartiles: Default::default(),
|
||||
smooth: false,
|
||||
trendlines: Vec::new(),
|
||||
number_format: None,
|
||||
innermost_categories: false,
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,7 +310,40 @@ pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef {
|
||||
|
||||
/// The contiguous data region around `c` (Ctrl+A / Ctrl+Shift+8, AutoSum, sort, tables).
|
||||
pub fn current_region(sheet: &Sheet, c: CellRef) -> RangeRef {
|
||||
let filled = |c: CellRef| sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c);
|
||||
region_where(sheet, c, |_| true)
|
||||
}
|
||||
|
||||
/// The data region a sheet AutoFilter takes from `c`, a cell outside any table: the current
|
||||
/// region, kept off the tables it reaches. Observed in Windows Excel 16 (table B4:C8, text in
|
||||
/// A1:A3, A5:A8 and B3; the current region of A1 is A1:C8): from A1 the filter covers A1:A3, from
|
||||
/// A6 A5:A8, from B3 A1:B3. So the region is cut to the columns on the cell's side of the table
|
||||
/// when the cell is left or right of it, else to the rows above or below, and grown again from
|
||||
/// the cell inside that window.
|
||||
pub fn current_region_outside_tables(sheet: &Sheet, c: CellRef) -> RangeRef {
|
||||
let (mut c0, mut c1, mut r0, mut r1) = (0, MAX_COLS - 1, 0, MAX_ROWS - 1);
|
||||
let mut region = current_region(sheet, c);
|
||||
for _ in 0..=sheet.tables.len() {
|
||||
let Some(t) = sheet.tables.iter().find(|t| t.range.intersects(®ion)) else { break };
|
||||
let t = t.range;
|
||||
if c.col < t.start.col {
|
||||
c1 = c1.min(t.start.col - 1);
|
||||
} else if c.col > t.end.col {
|
||||
c0 = c0.max(t.end.col + 1);
|
||||
} else if c.row < t.start.row {
|
||||
r1 = r1.min(t.start.row - 1);
|
||||
} else if c.row > t.end.row {
|
||||
r0 = r0.max(t.end.row + 1);
|
||||
} else {
|
||||
return RangeRef::cell(c);
|
||||
}
|
||||
region = region_where(sheet, c, |x| x.col >= c0 && x.col <= c1 && x.row >= r0 && x.row <= r1 && sheet.table_at(x).is_none());
|
||||
}
|
||||
region
|
||||
}
|
||||
|
||||
/// The current region around `c`, counting only filled cells that `counts` accepts.
|
||||
fn region_where(sheet: &Sheet, c: CellRef, counts: impl Fn(CellRef) -> bool) -> RangeRef {
|
||||
let filled = |c: CellRef| (sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c)) && counts(c);
|
||||
// Whether a row (or column) has a filled cell between two columns (rows), inclusive.
|
||||
let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col)));
|
||||
let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col)));
|
||||
|
||||
+838
-6
@@ -343,6 +343,84 @@ fn enter_values_and_formulas() {
|
||||
assert_eq!(crate::display::cell_text(&d.wb, sh, CellRef::parse("B1").unwrap()), "12%");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_plus_or_minus_starts_a_formula() {
|
||||
// #2023: like Excel (and Lotus 1-2-3 before it), typing `+5+4` enters the formula `=+5+4`.
|
||||
let mut s = s();
|
||||
let input = |s: &Session, a: &str| s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).map(|c| c.input_text());
|
||||
for (cell, typed, value) in [
|
||||
("A1", "+5+4", 9.0),
|
||||
("A2", "-5+4", -1.0),
|
||||
("A3", "--5", 5.0),
|
||||
("A4", "-3/4", -0.75),
|
||||
("A5", "+A1*2", 18.0),
|
||||
("A6", "-(A1)", -9.0),
|
||||
("A7", "+1/30", 1.0 / 30.0),
|
||||
("A8", "-1/30", -1.0 / 30.0),
|
||||
] {
|
||||
s.execute("cell.set", json!({"cell": cell, "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}"));
|
||||
assert_eq!(input(&s, cell), Some(format!("={typed}")), "{typed}");
|
||||
assert_eq!(v(&s, cell), Value::Number(value), "{typed}");
|
||||
}
|
||||
// A signed number is a number, a lone sign is text, and an apostrophe keeps the text.
|
||||
for (typed, value) in [
|
||||
("+5", Value::Number(5.0)),
|
||||
("-5", Value::Number(-5.0)),
|
||||
("-12%", Value::Number(-0.12)),
|
||||
("-$5", Value::Number(-5.0)),
|
||||
("-", Value::text("-")),
|
||||
("+", Value::text("+")),
|
||||
("'+5+4", Value::text("+5+4")),
|
||||
] {
|
||||
s.execute("cell.set", json!({"cell": "B1", "input": typed})).unwrap();
|
||||
assert_eq!(v(&s, "B1"), value, "{typed}");
|
||||
assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}");
|
||||
}
|
||||
// Text that would read as a formula is edited with its apostrophe, so confirming the editor
|
||||
// unchanged keeps it text; text that wouldn't is edited as it is.
|
||||
for (typed, shown) in [
|
||||
("'+5+4", "'+5+4"),
|
||||
("'-5+4", "'-5+4"),
|
||||
("'+1-555-1234", "'+1-555-1234"),
|
||||
("'-abc", "'-abc"),
|
||||
("--", "--"),
|
||||
("+49 170 1234567", "+49 170 1234567"),
|
||||
("+1:30", "+1:30"),
|
||||
] {
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": typed})).unwrap();
|
||||
let before = v(&s, "B2");
|
||||
let edit = {
|
||||
let d = s.doc().unwrap();
|
||||
crate::display::edit_text(&d.wb, d.wb.active().unwrap(), CellRef::parse("B2").unwrap())
|
||||
};
|
||||
assert_eq!(edit, shown, "{typed}");
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": edit})).unwrap();
|
||||
assert_eq!(v(&s, "B2"), before, "{typed} stays text after an unchanged edit");
|
||||
}
|
||||
// As observed in Excel for the web, an entry that doesn't read as a formula stays text, and
|
||||
// one that does but names nothing known is #NAME?. Only `=` entries are refused.
|
||||
for typed in ["--", "-----", "+5+", "+49 170 1234567", "+1:30"] {
|
||||
s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}"));
|
||||
assert_eq!(v(&s, "C1"), Value::text(typed), "{typed}");
|
||||
assert_eq!(input(&s, "C1").as_deref(), Some(typed), "{typed}");
|
||||
}
|
||||
s.execute("cell.set", json!({"cell": "C2", "input": "- item"})).unwrap();
|
||||
assert_eq!(v(&s, "C2"), Value::Error(gridcraft_core::CellError::Name));
|
||||
// Excel for the web keeps `+1:30` as text (above) but reads `-1:30` as a formula (rows 1 to 30).
|
||||
s.execute("cell.set", json!({"cell": "C40", "input": "-1:30"})).unwrap();
|
||||
assert_eq!(input(&s, "C40").as_deref(), Some("=-1:30"));
|
||||
let e = s.execute("cell.set", json!({"cell": "C1", "input": "=--"})).unwrap_err().to_string();
|
||||
assert!(e.contains("problem with this formula"), "{e}");
|
||||
assert_eq!(v(&s, "C1"), Value::text("+1:30"), "a refused entry keeps the cell");
|
||||
// Pasted or split by Text to Columns, the same rule applies.
|
||||
s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap();
|
||||
assert_eq!(v(&s, "D1"), Value::text("--"));
|
||||
assert_eq!(v(&s, "E1"), Value::Number(-1.0));
|
||||
s.execute("cell.set", json!({"cell": "F1", "input": "a,--,b"})).unwrap();
|
||||
s.execute("data.textToColumns", json!({"range": "F1", "delimiters": [","]})).unwrap();
|
||||
assert_eq!([v(&s, "F1"), v(&s, "G1"), v(&s, "H1")], [Value::text("a"), Value::text("--"), Value::text("b")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formulas_with_the_wrong_argument_count_are_refused_on_entry() {
|
||||
// #363: =DATEDIF(start, end) was stored and showed #VALUE!. Like Excel, entry refuses it and
|
||||
@@ -884,11 +962,13 @@ fn rich_clipboard_omits_html_for_large_ranges_without_truncating_text() {
|
||||
#[test]
|
||||
fn rich_clipboard_omits_html_when_escaping_exceeds_byte_budget() {
|
||||
let mut s = s();
|
||||
let text = "&".repeat(1_000_000);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[text]]})).unwrap();
|
||||
let copied = s.execute("edit.copy", json!({"range": "A1", "html": true})).unwrap();
|
||||
// Cells hold at most 32,767 characters, so 30 full cells of `&` (5 bytes each once escaped)
|
||||
// pass the 4 MiB HTML budget while the plain text stays far below it.
|
||||
let cell = "&".repeat(32_767);
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [vec![cell; 30]]})).unwrap();
|
||||
let copied = s.execute("edit.copy", json!({"range": "A1:AD1", "html": true})).unwrap();
|
||||
assert!(copied.get("html").is_none(), "an oversized escaped value must not produce partial HTML");
|
||||
assert_eq!(copied["text"].as_str().unwrap().len(), 1_000_001);
|
||||
assert_eq!(copied["text"].as_str().unwrap().len(), 30 * 32_767 + 30);
|
||||
assert!(copied["text"].as_str().unwrap().ends_with("&\n"));
|
||||
}
|
||||
|
||||
@@ -1271,6 +1351,177 @@ fn fill_days_weekdays_months_and_years_step_a_date_by_that_unit() {
|
||||
assert_eq!(v(&s, "J2"), Value::Number(46081.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_and_growth_trend_continue_the_fitted_line_or_curve() {
|
||||
let mut s = s();
|
||||
let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::<Vec<_>>();
|
||||
let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::<Vec<_>>();
|
||||
let fill =
|
||||
|s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode}));
|
||||
// The examples on Excel's "Project values in a series" page: 1, 2 and 1, 3 for both trends, 2, 3
|
||||
// for Growth Trend and 100, 95 for Linear Trend. 2, 3 gives 4, 5, 6 by Linear Trend.
|
||||
for (col, start, linear, growth) in [
|
||||
("A", [1.0, 2.0], [3.0, 4.0, 5.0], [4.0, 8.0, 16.0]),
|
||||
("B", [1.0, 3.0], [5.0, 7.0, 9.0], [9.0, 27.0, 81.0]),
|
||||
("C", [2.0, 3.0], [4.0, 5.0, 6.0], [4.5, 6.75, 10.125]),
|
||||
] {
|
||||
s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [[start[0]], [start[1]]]})).unwrap();
|
||||
let (src, target) = (format!("{col}1:{col}2"), format!("{col}1:{col}5"));
|
||||
let cells: Vec<String> = (3..=5).map(|r| format!("{col}{r}")).collect();
|
||||
let cells: Vec<&str> = cells.iter().map(String::as_str).collect();
|
||||
fill(&mut s, &src, &target, "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &cells), n(&linear), "Linear Trend from {start:?}");
|
||||
fill(&mut s, &src, &target, "growthTrend").unwrap();
|
||||
assert_eq!(nums(&s, &cells), n(&growth), "Growth Trend from {start:?}");
|
||||
}
|
||||
s.execute("range.setValues", json!({"range": "F1", "values": [[100], [95]]})).unwrap();
|
||||
fill(&mut s, "F1:F2", "F1:F4", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["F3", "F4"]), n(&[90.0, 85.0]));
|
||||
// Three numbers: the targets follow the best fit and the source keeps its values. 1, 3, 4 fit
|
||||
// y = 1.5x + 7/6; 1, 2, 8 fit y = 0.8909·2.8284^x.
|
||||
s.execute("range.setValues", json!({"range": "D1", "values": [[1, 1], [3, 2], [4, 8]]})).unwrap();
|
||||
fill(&mut s, "D1:D3", "D1:D5", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["D1", "D2", "D3", "D4", "D5"]), n(&[1.0, 3.0, 4.0, 5.66666666666667, 7.16666666666667]));
|
||||
fill(&mut s, "E1:E3", "E1:E4", "growthTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["E1", "E2", "E3", "E4"]), n(&[1.0, 2.0, 8.0, 20.158736798318]));
|
||||
// Upward and leftward the trend continues backward: 1, 2 gives 0 and -1, or 0.5 and 0.25.
|
||||
s.execute("range.setValues", json!({"range": "G3", "values": [[1], [2]]})).unwrap();
|
||||
fill(&mut s, "G3:G4", "G1:G4", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["G2", "G1"]), n(&[0.0, -1.0]));
|
||||
s.execute("range.setValues", json!({"range": "J1", "values": [[1, 2]]})).unwrap();
|
||||
fill(&mut s, "J1:K1", "H1:K1", "growthTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["I1", "H1"]), n(&[0.5, 0.25]));
|
||||
// Negative numbers grow away from zero: -2, -4 gives -8.
|
||||
s.execute("range.setValues", json!({"range": "L1", "values": [[-2], [-4]]})).unwrap();
|
||||
fill(&mut s, "L1:L2", "L1:L3", "growthTrend").unwrap();
|
||||
assert_eq!(v(&s, "L3"), Value::Number(-8.0));
|
||||
// A tiny start with a huge factor still reaches 1e300 without overflowing on the way.
|
||||
s.execute("range.setValues", json!({"range": "S1", "values": [[1e-200], [1e-100]]})).unwrap();
|
||||
fill(&mut s, "S1:S2", "S1:S6", "growthTrend").unwrap();
|
||||
let Value::Number(s6) = v(&s, "S6") else { panic!("S6 is {:?}", v(&s, "S6")) };
|
||||
assert!((s6 / 1e300 - 1.0).abs() < 1e-9, "S6 = {s6}");
|
||||
// Numbers near the largest double continue their line without a sum overflowing: two equal
|
||||
// numbers repeat, and 1e308 four times then 0 fit a step of -2e307 and continue at 2e307.
|
||||
s.execute("range.setValues", json!({"range": "T1", "values": [[1e308, 1e308], [1e308, 1e308], [0, 1e308], [0, 1e308], [0, 0]]})).unwrap();
|
||||
fill(&mut s, "T1:T2", "T1:T3", "linearTrend").unwrap();
|
||||
fill(&mut s, "U1:U5", "U1:U6", "linearTrend").unwrap();
|
||||
for (cell, want) in [("T3", 1e308), ("U6", 2e307)] {
|
||||
let Value::Number(got) = v(&s, cell) else { panic!("{cell} is {:?}", v(&s, cell)) };
|
||||
assert!((got / want - 1.0).abs() < 1e-9, "{cell} = {got}");
|
||||
}
|
||||
// A lone number repeats, and dates a month apart step by their days, not by months.
|
||||
s.execute("cell.set", json!({"cell": "M1", "input": "7"})).unwrap();
|
||||
fill(&mut s, "M1", "M1:M2", "linearTrend").unwrap();
|
||||
assert_eq!(v(&s, "M2"), Value::Number(7.0));
|
||||
// It repeats unchanged, with every digit and at any size, by either trend.
|
||||
s.execute("range.setValues", json!({"range": "V1", "values": [[1e308, 0.12345678901234567]]})).unwrap();
|
||||
fill(&mut s, "V1", "V1:V3", "growthTrend").unwrap();
|
||||
fill(&mut s, "W1", "W1:W3", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["V2", "V3", "W2", "W3"]), n(&[1e308, 1e308, 0.12345678901234567, 0.12345678901234567]));
|
||||
// The smallest double three times repeats rather than averaging to zero.
|
||||
let tiny = f64::from_bits(1);
|
||||
s.execute("range.setValues", json!({"range": "X1", "values": [[tiny], [tiny], [tiny]]})).unwrap();
|
||||
fill(&mut s, "X1:X3", "X1:X4", "linearTrend").unwrap();
|
||||
assert_eq!(v(&s, "X4"), Value::Number(tiny));
|
||||
// The two smallest doubles continue their step: 1 and 2 times the smallest give 3 and 4 times it.
|
||||
s.execute("range.setValues", json!({"range": "AD1", "values": [[tiny], [f64::from_bits(2)]]})).unwrap();
|
||||
fill(&mut s, "AD1:AD2", "AD1:AD4", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["AD3", "AD4"]), n(&[f64::from_bits(3), f64::from_bits(4)]));
|
||||
// Huge numbers three times repeat exactly: the largest double, and one with 14 digits.
|
||||
let (big, big14) = (f64::MAX, 1.7976931348623e308);
|
||||
s.execute("range.setValues", json!({"range": "Y1", "values": [[big, big14], [big, big14], [big, big14]]})).unwrap();
|
||||
fill(&mut s, "Y1:Z3", "Y1:Z4", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["Y4", "Z4"]), n(&[big, big14]));
|
||||
// Growth Trend repeats the same number exactly too, huge, tiny or below zero.
|
||||
s.execute("range.setValues", json!({"range": "AA1", "values": [[1e300, 1e-300, -0.3], [1e300, 1e-300, -0.3]]})).unwrap();
|
||||
fill(&mut s, "AA1:AC2", "AA1:AC4", "growthTrend").unwrap();
|
||||
assert_eq!(nums(&s, &["AA4", "AB4", "AC4"]), n(&[1e300, 1e-300, -0.3]));
|
||||
s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap();
|
||||
fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap();
|
||||
assert_eq!(v(&s, "N3"), Value::Number(46099.0), "2/15/2026 plus 31 days");
|
||||
// Text or an empty cell in the source, and zero or mixed signs for Growth Trend, are refused
|
||||
// and fill nothing.
|
||||
s.execute("range.setValues", json!({"range": "O1", "values": [[1, 1, 0], ["x", -2, 2]]})).unwrap();
|
||||
assert!(fill(&mut s, "O1:O2", "O1:O3", "linearTrend").is_err());
|
||||
assert!(fill(&mut s, "P1:P2", "P1:P3", "growthTrend").is_err());
|
||||
assert!(fill(&mut s, "Q1:Q2", "Q1:Q3", "growthTrend").is_err());
|
||||
assert!(fill(&mut s, "R1:R2", "R1:R3", "linearTrend").is_err());
|
||||
assert_eq!(nums(&s, &["O3", "P3", "Q3", "R3"]), [Value::Empty, Value::Empty, Value::Empty, Value::Empty]);
|
||||
fill(&mut s, "P1:P2", "P1:P3", "linearTrend").unwrap();
|
||||
assert_eq!(v(&s, "P3"), Value::Number(-5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trend_fills_are_offered_for_numbers_only() {
|
||||
let mut s = s();
|
||||
let offered = |s: &Session, src: &str, target: &str, growth: bool| {
|
||||
let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
|
||||
crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r(src), r(target), growth)
|
||||
};
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, -1, 1], [2, -3, "x"]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=A1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D2", "input": "5"})).unwrap();
|
||||
assert!(offered(&s, "A1:A2", "A1:A5", false) && offered(&s, "A1:A2", "A1:A5", true));
|
||||
// Down A1:B2, each column keeps one sign; across it, row 1 holds 1 and -1.
|
||||
assert!(offered(&s, "A1:B2", "A1:B5", true));
|
||||
assert!(offered(&s, "A1:B2", "A1:E2", false) && !offered(&s, "A1:B2", "A1:E2", true));
|
||||
let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
|
||||
assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:E2")), (true, false));
|
||||
assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:B5")), (true, true));
|
||||
assert!(!offered(&s, "C1:C2", "C1:C4", false), "text");
|
||||
assert!(!offered(&s, "D1:D2", "D1:D4", false), "a formula");
|
||||
assert!(!offered(&s, "E1:E2", "E1:E4", false), "empty cells");
|
||||
// A fill `edit.autoFill` refuses is not offered: five columns down to the last row is more than
|
||||
// MAX_FILL_CELLS cells, and a target that doesn't hold the source in a corner.
|
||||
s.execute("range.setValues", json!({"range": "F1", "values": [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]]})).unwrap();
|
||||
assert!(offered(&s, "F1:J2", "F1:J1000", false) && offered(&s, "F1:J2", "F1:J1000", true));
|
||||
assert!(!offered(&s, "F1:J2", "F1:J1048576", false) && !offered(&s, "F1:J2", "F1:J1048576", true), "too large");
|
||||
assert!(!offered(&s, "F1:J2", "F2:J5", false), "source outside the target");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trend_fills_fit_each_lane_of_a_two_dimensional_source() {
|
||||
let mut s = s();
|
||||
let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::<Vec<_>>();
|
||||
let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::<Vec<_>>();
|
||||
let fill =
|
||||
|s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode}));
|
||||
// Down: column A holds 1, 2 and column B 10, 20, and one command fits each column on its own.
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap();
|
||||
let down = ["A3", "A4", "A5", "B3", "B4", "B5"];
|
||||
fill(&mut s, "A1:B2", "A1:B5", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &down), n(&[3.0, 4.0, 5.0, 30.0, 40.0, 50.0]));
|
||||
fill(&mut s, "A1:B2", "A1:B5", "growthTrend").unwrap();
|
||||
assert_eq!(nums(&s, &down), n(&[4.0, 8.0, 16.0, 40.0, 80.0, 160.0]));
|
||||
// Across: row 1 holds 1, 10 and row 2 holds 2, 20, and each row is fitted on its own.
|
||||
s.execute("range.setValues", json!({"range": "H1", "values": [[1, 10], [2, 20]]})).unwrap();
|
||||
let across = ["J1", "K1", "L1", "J2", "K2", "L2"];
|
||||
fill(&mut s, "H1:I2", "H1:L2", "linearTrend").unwrap();
|
||||
assert_eq!(nums(&s, &across), n(&[19.0, 28.0, 37.0, 38.0, 56.0, 74.0]));
|
||||
fill(&mut s, "H1:I2", "H1:L2", "growthTrend").unwrap();
|
||||
assert_eq!(nums(&s, &across), n(&[100.0, 1000.0, 10000.0, 200.0, 2000.0, 20000.0]));
|
||||
// The sources keep their values.
|
||||
assert_eq!(nums(&s, &["A1", "A2", "B1", "B2", "H1", "I1", "H2", "I2"]), n(&[1.0, 2.0, 10.0, 20.0, 1.0, 10.0, 2.0, 20.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trend_fill_undoes_as_one_step() {
|
||||
let mut s = s();
|
||||
let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::<Vec<_>>();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A4", "input": "99"})).unwrap();
|
||||
s.execute("edit.autoFill", json!({"source": "A1:B2", "target": "A1:B5", "mode": "linearTrend"})).unwrap();
|
||||
assert_eq!(v(&s, "A4"), Value::Number(4.0));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
// The targets are back as they were (empty, and 99 in A4), and the source is unchanged.
|
||||
assert_eq!(
|
||||
nums(&s, &["A3", "A4", "A5", "B3", "B4", "B5"]),
|
||||
[Value::Empty, Value::Number(99.0), Value::Empty, Value::Empty, Value::Empty, Value::Empty]
|
||||
);
|
||||
assert_eq!(nums(&s, &["A1", "A2", "B1", "B2"]), [Value::Number(1.0), Value::Number(2.0), Value::Number(10.0), Value::Number(20.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_number_in_a_date_format_offers_the_date_fills() {
|
||||
let mut s = s();
|
||||
@@ -1739,6 +1990,27 @@ fn case_sensitive_sort_puts_lowercase_first() {
|
||||
assert_eq!(col, ["a", "A", "aB", "Ab", "b", "B"].map(Value::from));
|
||||
}
|
||||
|
||||
/// Data > Sort orders numbers exactly, like Excel 365: 0.3 sorts before `=0.1+0.2`
|
||||
/// (0.30000000000000004) ascending and after it descending, whatever the input order.
|
||||
#[test]
|
||||
fn sort_orders_numbers_exactly() {
|
||||
for first_noisy in [true, false] {
|
||||
let mut s = s();
|
||||
let (a1, a2, b1, b2) = if first_noisy { ("=0.1+0.2", "0.3", "e", "t") } else { ("0.3", "=0.1+0.2", "t", "e") };
|
||||
for (cell, input) in [("A1", a1), ("A2", a2), ("B1", b1), ("B2", b2)] {
|
||||
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
|
||||
}
|
||||
let labels = |s: &Session| [v(s, "B1"), v(s, "B2")];
|
||||
s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A"}]})).unwrap();
|
||||
assert_eq!(labels(&s), ["t", "e"].map(Value::from), "ascending, noisy first: {first_noisy}");
|
||||
s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A", "order": "desc"}]})).unwrap();
|
||||
assert_eq!(labels(&s), ["e", "t"].map(Value::from), "descending, noisy first: {first_noisy}");
|
||||
s.execute("selection.set", json!({"range": "A1:B2"})).unwrap();
|
||||
s.execute("data.sortAscending", json!({"range": "A1:B2", "column": "A"})).unwrap();
|
||||
assert_eq!(labels(&s), ["t", "e"].map(Value::from), "quick sort, noisy first: {first_noisy}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3949: Excel sorts values that are not in the custom list A to Z after the listed ones.
|
||||
#[test]
|
||||
fn custom_list_sort_puts_unlisted_values_after_the_list_in_order() {
|
||||
@@ -1894,7 +2166,7 @@ fn filter_with_a_sheet_prefix_toggles_the_table_at_the_range() {
|
||||
wb.sheet(wb.sheet_index("Prices").unwrap()).unwrap().clone()
|
||||
};
|
||||
assert!(prices(&s).tables[0].filter_button);
|
||||
s.execute("data.filter", json!({"range": "Prices!A2:B3"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "Prices!A1:B3"})).unwrap();
|
||||
assert!(!prices(&s).tables[0].filter_button);
|
||||
assert!(prices(&s).autofilter.is_none());
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none());
|
||||
@@ -5319,6 +5591,75 @@ fn encrypted_book(password: &str) -> Vec<u8> {
|
||||
gridcraft_xlsx::testing::encrypt_workbook(&xlsx, password)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_to_modify_asks_for_it_or_a_read_only_open() {
|
||||
const PW: &str = "synthetic-modify-pw";
|
||||
let mut src = s();
|
||||
src.execute("cell.set", json!({"cell": "A1", "input": "42"})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation {
|
||||
password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")),
|
||||
..Default::default()
|
||||
});
|
||||
let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap();
|
||||
let b64 = crate::io::base64_encode(&bytes);
|
||||
let open = |s: &mut Session, extra: serde_json::Value| {
|
||||
let mut p = json!({"name": "Reserved.xlsx", "base64": b64});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
s.execute("file.open", p)
|
||||
};
|
||||
let mut s = Session::new();
|
||||
let err = open(&mut s, json!({})).unwrap_err().to_string();
|
||||
assert!(err.contains(crate::io::MODIFY_PASSWORD_REQUIRED), "{err}");
|
||||
assert!(s.take_ui_requests().is_empty(), "programmatic calls never open dialogs");
|
||||
for wrong in ["not-it", ""] {
|
||||
let err = open(&mut s, json!({"modifyPassword": wrong})).unwrap_err().to_string();
|
||||
assert!(err.contains(crate::io::WRONG_PASSWORD), "{err}");
|
||||
}
|
||||
assert!(s.documents().is_empty());
|
||||
|
||||
// Read-only: opens, keeps the reservation, but has no file to save over.
|
||||
open(&mut s, json!({"readOnly": true})).unwrap();
|
||||
assert_eq!(v(&s, "A1"), Value::Number(42.0));
|
||||
assert!(s.doc().unwrap().wb.write_reservation.is_some());
|
||||
|
||||
// The password: opens, and the reservation survives a save.
|
||||
let mut s = Session::new();
|
||||
open(&mut s, json!({"modifyPassword": PW})).unwrap();
|
||||
assert_eq!(v(&s, "A1"), Value::Number(42.0));
|
||||
let saved = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap();
|
||||
let (back, _) = crate::io::open_bytes("book.xlsx", &saved).unwrap();
|
||||
assert!(back.write_reservation.and_then(|r| r.password).is_some_and(|h| h.verify(PW) == Ok(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_only_open_never_saves_over_its_reserved_file() {
|
||||
const PW: &str = "synthetic-modify-pw";
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-read-only-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("reserved.xlsx").to_string_lossy().into_owned();
|
||||
let copy = dir.join("copy.xlsx").to_string_lossy().into_owned();
|
||||
let mut src = s();
|
||||
std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation {
|
||||
password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")),
|
||||
..Default::default()
|
||||
});
|
||||
let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap();
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("file.open", json!({"path": path, "readOnly": true})).unwrap();
|
||||
let err = s.execute("file.save", json!({"path": path})).unwrap_err().to_string();
|
||||
assert!(err.contains("read-only"), "{err}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched");
|
||||
let dotted = dir.join(".").join("reserved.xlsx").to_string_lossy().into_owned();
|
||||
let err = s.execute("file.save", json!({"path": dotted})).unwrap_err().to_string();
|
||||
assert!(err.contains("read-only"), "the same file under another spelling: {err}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched");
|
||||
s.execute("file.saveAs", json!({"path": copy})).unwrap();
|
||||
assert!(std::fs::metadata(©).is_ok());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_workbooks_open_with_their_password() {
|
||||
const PW: &str = "synthetic-pw-5521";
|
||||
@@ -5381,6 +5722,140 @@ fn a_decrypted_workbook_never_overwrites_its_encrypted_original() {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
fn quick_analysis_block(s: &mut Session) {
|
||||
for (a, t) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] {
|
||||
s.execute("cell.set", json!({"cell": a, "input": t})).unwrap();
|
||||
}
|
||||
for (r, (q1, q2)) in [(1.0, 10.0), (2.0, 20.0), (3.0, 30.0)].into_iter().enumerate() {
|
||||
s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_add_total_writes_formulas_in_one_undo_step() {
|
||||
// Issue #791 (Quick Analysis › Totals).
|
||||
let mut s = s();
|
||||
quick_analysis_block(&mut s);
|
||||
let before = s.doc().unwrap().undo.len();
|
||||
// The header row and the text-only column are skipped; the selection is the default range.
|
||||
s.execute("selection.set", json!({"range": "A1:C4"})).unwrap();
|
||||
let r = s.execute("analysis.addTotal", json!({"function": "sum"})).unwrap();
|
||||
assert_eq!(r["output"], "B5:C5");
|
||||
assert_eq!(v(&s, "B5"), Value::Number(6.0));
|
||||
assert_eq!(v(&s, "C5"), Value::Number(60.0));
|
||||
assert_eq!(v(&s, "A5"), Value::Empty, "text columns get no total");
|
||||
s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "average", "direction": "rows"})).unwrap();
|
||||
assert_eq!(v(&s, "D2"), Value::Number(5.5));
|
||||
s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "runningTotal", "overwrite": true})).unwrap();
|
||||
assert_eq!(v(&s, "D4"), Value::Number(6.0), "running total down column B");
|
||||
assert_eq!(v(&s, "E4"), Value::Number(60.0));
|
||||
s.execute("analysis.addTotal", json!({"range": "B1:B4", "function": "percentTotal", "overwrite": true})).unwrap();
|
||||
assert_eq!(v(&s, "C4"), Value::Number(0.5), "overwrite replaces the C column cell next to B");
|
||||
assert_eq!(s.doc().unwrap().undo.len(), before + 4, "one undo step per call");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(v(&s, "C4"), Value::Number(30.0));
|
||||
// A second sum into the occupied row is refused rather than overwriting.
|
||||
assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_add_total_refuses_bad_and_huge_input() {
|
||||
let mut s = s();
|
||||
quick_analysis_block(&mut s);
|
||||
// Empty params on a single cell, unknown function, no numbers, whole columns, no room.
|
||||
assert!(s.execute("analysis.addTotal", json!({})).is_err());
|
||||
assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4", "function": "median"})).is_err());
|
||||
assert!(s.execute("analysis.addTotal", json!({"range": "A1:A4"})).is_err());
|
||||
let before = s.doc().unwrap().undo.len();
|
||||
let r = s.execute("analysis.addTotal", json!({"range": "B:C"})).unwrap();
|
||||
assert_eq!(r["output"], "B5:C5", "whole columns are clipped to the used range");
|
||||
assert_eq!(s.doc().unwrap().undo.len(), before + 1);
|
||||
s.execute("cell.set", json!({"cell": "B1048575", "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "B1048576", "input": "2"})).unwrap();
|
||||
assert!(s.execute("analysis.addTotal", json!({"range": "B1048575:C1048576"})).is_err(), "no row below the last one");
|
||||
assert!(s.execute("analysis.addTotal", json!({"range": "B1:C1048576", "function": "runningTotal"})).is_err(), "per-cell block over the cap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_results_stay_outside_a_selection_that_extends_past_the_data() {
|
||||
let mut s = s();
|
||||
quick_analysis_block(&mut s);
|
||||
// Data ends in row 4; the selection runs to row 10, so the sum goes in row 11.
|
||||
let r = s.execute("analysis.addTotal", json!({"range": "A1:C10"})).unwrap();
|
||||
assert_eq!(r["output"], "B11:C11");
|
||||
assert_eq!(v(&s, "B11"), Value::Number(6.0));
|
||||
assert_eq!(v(&s, "B5"), Value::Empty);
|
||||
// Per-row blocks and sparklines move out by the selection's size too.
|
||||
let r = s.execute("analysis.addTotal", json!({"range": "B1:C10", "function": "runningTotal", "direction": "rows"})).unwrap();
|
||||
assert_eq!(r["output"], "B12:C14", "per-row block lands below the selection, not inside it");
|
||||
let r = s.execute("analysis.addSparklines", json!({"range": "A1:F4"})).unwrap();
|
||||
assert_eq!(r["output"], "G2:G4");
|
||||
let r = s.execute("analysis.addSparklines", json!({"range": "A1:C8", "direction": "columns"})).unwrap();
|
||||
assert_eq!(r["output"], "B9:C9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_overwrite_keeps_the_target_cell_style() {
|
||||
let mut s = s();
|
||||
quick_analysis_block(&mut s);
|
||||
s.execute("cell.set", json!({"cell": "B5", "input": "1"})).unwrap();
|
||||
s.execute("selection.set", json!({"cell": "B5"})).unwrap();
|
||||
s.execute("home.bold", json!({})).unwrap();
|
||||
s.execute("analysis.addTotal", json!({"range": "A1:C4", "overwrite": true})).unwrap();
|
||||
assert_eq!(v(&s, "B5"), Value::Number(6.0));
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
assert!(d.wb.styles.get(sh.style_id(CellRef::parse("B5").unwrap())).font.bold, "bold survives the overwrite");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_commands_refuse_a_multi_area_selection_without_a_range() {
|
||||
let mut s = s();
|
||||
quick_analysis_block(&mut s);
|
||||
s.execute("selection.set", json!({"range": "A1:C4,E1:F4"})).unwrap();
|
||||
for c in ["analysis.addTotal", "analysis.addSparklines"] {
|
||||
let e = s.execute(c, json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("single contiguous range"), "{c}: {e}");
|
||||
}
|
||||
assert_eq!(v(&s, "B5"), Value::Empty);
|
||||
// An explicit range still works.
|
||||
s.execute("analysis.addTotal", json!({"range": "A1:C4"})).unwrap();
|
||||
assert_eq!(v(&s, "B5"), Value::Number(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_add_sparklines_one_per_row_in_one_undo_step() {
|
||||
let mut s = s();
|
||||
quick_analysis_block(&mut s);
|
||||
let before = s.doc().unwrap().undo.len();
|
||||
let r = s.execute("analysis.addSparklines", json!({"range": "A1:C4", "type": "column"})).unwrap();
|
||||
assert_eq!(r["output"], "D2:D4", "header row and label column are skipped");
|
||||
let sparks = s.doc().unwrap().wb.active().unwrap().sparklines.clone();
|
||||
assert_eq!(sparks.len(), 3);
|
||||
assert!(sparks.iter().any(|x| x.cell == CellRef::parse("D3").unwrap() && x.source == "B3:C3"));
|
||||
assert_eq!(s.doc().unwrap().undo.len(), before + 1);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().sparklines.is_empty());
|
||||
assert!(s.execute("analysis.addSparklines", json!({"range": "A1:A4"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_add_sparklines_refuses_a_protected_sheet() {
|
||||
let mut s = s();
|
||||
quick_analysis_block(&mut s);
|
||||
s.execute("analysis.addSparklines", json!({"range": "A1:C4"})).unwrap();
|
||||
s.execute("review.protectSheet", json!({})).unwrap();
|
||||
let (undo, sparks) = (s.doc().unwrap().undo.len(), s.doc().unwrap().wb.active().unwrap().sparklines.clone());
|
||||
for p in [json!({"range": "A1:C4", "overwrite": true}), json!({"range": "A1:B3", "direction": "columns"})] {
|
||||
assert!(s.execute("analysis.addSparklines", p).is_err());
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().undo.len(), undo, "a refused command leaves no undo step");
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().sparklines, sparks);
|
||||
s.execute("review.unprotectSheet", json!({})).unwrap();
|
||||
s.execute("analysis.addSparklines", json!({"range": "A1:C4", "overwrite": true})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_open_refuses_every_scheme_but_http_https_and_mailto() {
|
||||
let mut s = s();
|
||||
@@ -5901,6 +6376,58 @@ fn filtered_copy_with_many_runs_moves_notes_and_merges_with_their_rows() {
|
||||
assert_eq!(sh.merges.iter().filter(|m| m.start.col >= 7).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_level_pivot_chart_draws_one_label_per_point_after_saves() {
|
||||
use gridcraft_model::{Anchor, Chart, ChartKind, LegendPos, Series, Workbook};
|
||||
// Two levels of row labels in A4:B7, the outer one (country) on the left, as a PivotChart
|
||||
// opened from a file keeps them when the innermost column holds its cache.
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.name = "Graph".into();
|
||||
sh.set_value(CellRef::new(2, 2), Value::from("Total"));
|
||||
for (i, (outer, inner)) in [("Canada", "Ottawa"), ("", "Toronto"), ("USA", "Boston"), ("", "NYC")].iter().enumerate() {
|
||||
let r = 3 + i as u32;
|
||||
if !outer.is_empty() {
|
||||
sh.set_value(CellRef::new(r, 0), Value::from(*outer));
|
||||
}
|
||||
sh.set_value(CellRef::new(r, 1), Value::from(*inner));
|
||||
sh.set_value(CellRef::new(r, 2), Value::Number(i as f64 + 1.0));
|
||||
}
|
||||
sh.charts.push(Chart {
|
||||
id: 1,
|
||||
kind: ChartKind::ColumnClustered,
|
||||
anchor: Anchor { cell: CellRef::new(0, 5), width: 480.0, height: 300.0, ..Anchor::default() },
|
||||
title: None,
|
||||
series: vec![Series {
|
||||
name: Some("Graph!$C$3".into()),
|
||||
categories: Some("Graph!$A$4:$B$7".into()),
|
||||
values: "Graph!$C$4:$C$7".into(),
|
||||
innermost_categories: true,
|
||||
..Series::default()
|
||||
}],
|
||||
legend: LegendPos::Bottom,
|
||||
data_labels: false,
|
||||
data_table: None,
|
||||
gridlines: true,
|
||||
style: 2,
|
||||
x_title: None,
|
||||
y_title: None,
|
||||
source: None,
|
||||
by_rows: false,
|
||||
pivot: Some("Graph!PivotTable1".into()),
|
||||
first_slice_angle: 0,
|
||||
hole_size: 50,
|
||||
});
|
||||
let labels = ["Ottawa", "Toronto", "Boston", "NYC"];
|
||||
for _ in 0..2 {
|
||||
wb = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap().0;
|
||||
let ch = &wb.sheet(0).unwrap().charts[0];
|
||||
let s = &ch.series[0];
|
||||
assert_eq!((s.name.as_deref(), s.categories.as_deref(), s.innermost_categories), (Some("Graph!$C$3"), Some("Graph!$A$4:$B$7"), true));
|
||||
assert_eq!(gridcraft_chart::resolve(&wb, 0, ch).categories, labels);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_move_refuses_to_rotate_ink() {
|
||||
let mut s = s();
|
||||
@@ -5973,7 +6500,6 @@ fn editing_quote_prefixed_text_keeps_it_text() {
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(crate::display::edit_text(&d.wb, d.wb.active().unwrap(), CellRef::parse("B1").unwrap()), "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_as_text_keeps_identifier_columns_as_written() {
|
||||
let csv = "gtin,zip,flag,day\n8435392892278,01234,TRUE,2026-03-04\n";
|
||||
@@ -7197,6 +7723,45 @@ fn pivot_new_sheet_destination_respects_workbook_structure_protection() {
|
||||
assert!(s.execute("insert.pivotTable", json!({"source": "A1:B3", "location": "New"})).is_err());
|
||||
}
|
||||
|
||||
/// A password set in GridCraft is kept in every form a file stores; XLSX writes its Excel form,
|
||||
/// so a sheet or workbook password survives saving and reopening and still unprotects.
|
||||
#[test]
|
||||
fn passwords_set_in_gridcraft_survive_xlsx_saving() {
|
||||
let mut s = s();
|
||||
s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap();
|
||||
s.execute("review.protectWorkbook", json!({"on": true, "password": "b00k"})).unwrap();
|
||||
// The workbook password, like the sheet's, also keeps OpenDocument's SHA-256 digest.
|
||||
let book = s.doc().unwrap().wb.structure_password.clone().unwrap();
|
||||
assert_eq!(book.odf_key(), gridcraft_model::PasswordHash::new_sha256_digest("b00k").odf_key());
|
||||
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
let mut t = super::tests::s();
|
||||
t.execute("file.open", json!({"name": "book.xlsx", "base64": saved["base64"]})).unwrap();
|
||||
assert!(t.execute("review.unprotectSheet", json!({})).is_err());
|
||||
assert!(t.execute("review.unprotectSheet", json!({"password": "nope"})).is_err());
|
||||
t.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap();
|
||||
assert!(t.execute("review.protectWorkbook", json!({"on": false, "password": "nope"})).is_err());
|
||||
t.execute("review.protectWorkbook", json!({"on": false, "password": "b00k"})).unwrap();
|
||||
assert!(!t.doc().unwrap().wb.protected_structure);
|
||||
}
|
||||
|
||||
/// A password held only as a SHA-256 digest (as OpenDocument stores it) unprotects with the
|
||||
/// password; XLSX has no form for it, so saving keeps the protection without the password.
|
||||
#[test]
|
||||
fn sha256_digest_passwords_unprotect_and_save_to_xlsx_without_the_password() {
|
||||
let mut s = s();
|
||||
s.execute("review.protectSheet", json!({})).unwrap();
|
||||
let digest = gridcraft_model::PasswordHash::new_sha256_digest("pa55");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().protection.as_mut().unwrap().password = Some(digest);
|
||||
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
assert!(s.execute("review.unprotectSheet", json!({"password": "nope"})).is_err());
|
||||
s.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap();
|
||||
let mut t = super::tests::s();
|
||||
t.execute("file.open", json!({"name": "book.xlsx", "base64": saved["base64"]})).unwrap();
|
||||
let prot = t.doc().unwrap().wb.sheets[0].protection.clone().unwrap();
|
||||
assert_eq!(prot.password, None);
|
||||
t.execute("review.unprotectSheet", json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// Renaming a sheet renames a PivotTable's source to it, and the PivotTable still refreshes.
|
||||
#[test]
|
||||
fn sheet_rename_renames_a_pivot_source() {
|
||||
@@ -7657,3 +8222,270 @@ fn history_charges_the_storage_of_empty_comment_replies() {
|
||||
// 500 replies of no text are still 500 elements.
|
||||
assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_never_hold_merged_cells() {
|
||||
// Excel removes a table that contains a merged cell when it opens the file. Merging in a
|
||||
// table is refused; making or resizing a table over merged cells unmerges them; pasting into
|
||||
// a table skips the merges.
|
||||
let base = || {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1:D4", "values": [["A", "B", "C", "D"], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]}))
|
||||
.unwrap();
|
||||
s
|
||||
};
|
||||
let merges = |s: &Session| s.doc().unwrap().wb.active().unwrap().merges.clone();
|
||||
|
||||
let mut s = base();
|
||||
s.execute("insert.table", json!({"range": "A1:C4"})).unwrap();
|
||||
for id in ["home.mergeCells", "home.mergeCenter", "home.mergeAcross"] {
|
||||
for range in ["A2:B2", "A1:B1", "C3:D3"] {
|
||||
let e = s.execute(id, json!({"range": range})).unwrap_err().to_string();
|
||||
assert!(e.contains("can't merge cells in a table"), "{id} {range}: {e}");
|
||||
}
|
||||
}
|
||||
assert!(merges(&s).is_empty());
|
||||
s.execute("home.mergeCells", json!({"range": "E2:F2"})).unwrap();
|
||||
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F2").unwrap()]);
|
||||
|
||||
// A table over merged cells unmerges them; undo brings them back.
|
||||
let mut s = base();
|
||||
s.execute("home.mergeCells", json!({"range": "A2:B2"})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "C3:D4"})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "F1:G1"})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:C4"})).unwrap();
|
||||
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("F1:G1").unwrap()]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(merges(&s).len(), 3);
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
|
||||
// Resizing a table over merged cells is refused, as in Excel; the merge stays.
|
||||
let mut s = base();
|
||||
s.execute("insert.table", json!({"range": "A1:B4", "name": "T"})).unwrap();
|
||||
s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap_err().to_string();
|
||||
assert!(e.contains("can't overlap merged cells"), "{e}");
|
||||
s.execute("home.unmergeCells", json!({"range": "C2:D2"})).unwrap();
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap();
|
||||
|
||||
// Merged cells pasted into a table arrive unmerged; elsewhere they stay merged.
|
||||
s.execute("home.mergeCells", json!({"range": "E2:F3"})).unwrap();
|
||||
s.execute("edit.copy", json!({"range": "E2:F3"})).unwrap();
|
||||
s.execute("edit.paste", json!({"at": "A2"})).unwrap();
|
||||
s.execute("edit.paste", json!({"at": "H2"})).unwrap();
|
||||
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F3").unwrap(), gridcraft_core::RangeRef::parse("H2:I3").unwrap()]);
|
||||
|
||||
// The saved file has no merge inside the table.
|
||||
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
let bytes = crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap();
|
||||
let (back, _) = crate::io::open_bytes("t.xlsx", &bytes).unwrap();
|
||||
let sh = back.active().unwrap();
|
||||
assert_eq!(sh.tables.len(), 1);
|
||||
assert_eq!(sh.tables[0].range, gridcraft_core::RangeRef::parse("A1:C4").unwrap());
|
||||
assert!(sh.merges.iter().all(|m| sh.tables.iter().all(|t| !t.range.intersects(m))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hyperlink_function_makes_a_cell_link() {
|
||||
let mut s = s();
|
||||
s.link_policy = crate::links::LinkPolicy::Allow;
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "https://example.com/x"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": "=HYPERLINK(A1,\"Go\")"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C3", "input": "=HYPERLINK(\"google.com\")"})).unwrap();
|
||||
s.take_ui_requests();
|
||||
s.execute("link.open", json!({"cell": "B2"})).unwrap();
|
||||
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://example.com/x".into())]);
|
||||
s.execute("link.open", json!({"cell": "C3"})).unwrap();
|
||||
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://google.com".into())]);
|
||||
assert!(s.execute("link.open", json!({"cell": "A1"})).is_err());
|
||||
// a scheme-less address with a query, fragment or port opens over https too
|
||||
for (cell, input, url) in [
|
||||
("D1", "=HYPERLINK(\"google.com?q=rust\")", "https://google.com?q=rust"),
|
||||
("D2", "=HYPERLINK(\"google.com#results\")", "https://google.com#results"),
|
||||
("D3", "=HYPERLINK(\"example.com:8443/x\")", "https://example.com:8443/x"),
|
||||
] {
|
||||
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
|
||||
s.execute("link.open", json!({"cell": cell})).unwrap();
|
||||
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl(url.into())], "{input}");
|
||||
}
|
||||
// a table named like an address stays an internal target
|
||||
s.execute("range.setValues", json!({"range": "F1:G2", "values": [["a", "b"], [1, 2]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "F1:G2", "name": "sales.data"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D4", "input": "=HYPERLINK(\"sales.data\")"})).unwrap();
|
||||
let link = crate::links::cell_link(&s.doc().unwrap().wb, 0, gridcraft_core::CellRef::parse("D4").unwrap()).unwrap();
|
||||
assert_eq!(link.target, "sales.data");
|
||||
}
|
||||
|
||||
/// #1348: the selection a workbook opens with, and the one a sheet gets on its first visit, take
|
||||
/// a merged active cell whole, as a click on it does: a merge at A1 and one elsewhere. A
|
||||
/// selection the sheet remembers comes back as it was, even inside a merged cell.
|
||||
#[test]
|
||||
fn opening_and_switching_sheets_select_a_merged_active_cell_whole() {
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.set_value(CellRef::new(0, 0), Value::text("Timesheet"));
|
||||
sh.merges.push(gridcraft_core::RangeRef::parse("A1:AG1").unwrap());
|
||||
sh.merges.push(gridcraft_core::RangeRef::parse("C5:E6").unwrap());
|
||||
sh.view_active = CellRef::parse("C5").unwrap();
|
||||
let mut second = gridcraft_model::Sheet::new("Sheet2");
|
||||
second.merges.push(gridcraft_core::RangeRef::parse("A1:C2").unwrap());
|
||||
wb.sheets.push(std::sync::Arc::new(second));
|
||||
wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Sheet3")));
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap();
|
||||
let sel = |s: &Session| {
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
(sel.a1(), sel.active.a1())
|
||||
};
|
||||
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("file.open", json!({"name": "timesheet.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap();
|
||||
assert_eq!(sel(&s), pair("C5:E6", "C5"), "on open, a merge away from A1");
|
||||
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("A1:C2", "A1"), "first visit of a sheet, a merge at A1");
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet3"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("A1", "A1"), "an unmerged A1 stays a single cell");
|
||||
|
||||
// A remembered selection is not expanded again: set one inside Sheet2's merge directly.
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
|
||||
s.doc_mut().unwrap().selection = crate::Selection::at(CellRef::parse("B2").unwrap());
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("C5:E6", "C5"), "Sheet1's remembered selection");
|
||||
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("B2", "B2"), "a remembered selection comes back as it was");
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("B3", "B3"), "a remembered selection comes back as it was");
|
||||
}
|
||||
|
||||
/// Paste Link would write links to the cells a cut empties, losing them: a cut can't be pasted
|
||||
/// as links, and nothing changes.
|
||||
#[test]
|
||||
fn a_cut_is_not_pasted_as_links() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
|
||||
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "link": true, "at": "E1"})).is_err());
|
||||
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "E1")), (Value::Number(1.0), Value::Number(2.0), Value::Empty));
|
||||
}
|
||||
|
||||
/// A cut pasted into a row the filter hides would skip every cell it writes, so the cells would
|
||||
/// leave the sheet with the cut: it is refused and nothing changes. A visible row takes it.
|
||||
#[test]
|
||||
fn a_cut_is_not_pasted_into_filtered_rows() {
|
||||
let mut s = s();
|
||||
let mut rows = vec![json!(["Val", "Tag"])];
|
||||
for i in 2..=5 {
|
||||
rows.push(json!([format!("v{i}"), if i == 3 { "hide" } else { "keep" }]));
|
||||
}
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "E1", "values": [[1, 2]]})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A1:B1"})).unwrap();
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": ["keep"]})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "E1:F1"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A3:B3"})).unwrap();
|
||||
assert!(s.execute("edit.paste", json!({})).is_err());
|
||||
assert_eq!((v(&s, "E1"), v(&s, "F1")), (Value::Number(1.0), Value::Number(2.0)));
|
||||
assert_eq!(v(&s, "A3"), Value::from("v3"));
|
||||
s.execute("selection.set", json!({"range": "A4:B4"})).unwrap();
|
||||
s.execute("edit.paste", json!({})).unwrap();
|
||||
assert_eq!((v(&s, "A4"), v(&s, "B4"), v(&s, "E1")), (Value::Number(1.0), Value::Number(2.0), Value::Empty));
|
||||
}
|
||||
|
||||
/// A taller cut, or one pasted at an explicit cell, goes straight down: refused when a row the
|
||||
/// filter hides is among the rows it would land on, and nothing changes. A visible place takes it.
|
||||
#[test]
|
||||
fn an_anchored_cut_is_not_pasted_over_filtered_rows() {
|
||||
let mut s = s();
|
||||
let mut rows = vec![json!(["Val", "Tag"])];
|
||||
for i in 2..=5 {
|
||||
rows.push(json!([format!("v{i}"), if i == 3 { "hide" } else { "keep" }]));
|
||||
}
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A10", "values": [[1, 2], [3, 4]]})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A1:B1"})).unwrap();
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": ["keep"]})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "A10:B11"})).unwrap();
|
||||
assert!(s.execute("edit.paste", json!({"at": "A2"})).is_err());
|
||||
assert_eq!((v(&s, "A10"), v(&s, "B11")), (Value::Number(1.0), Value::Number(4.0)));
|
||||
assert_eq!((v(&s, "A2"), v(&s, "A3")), (Value::from("v2"), Value::from("v3")));
|
||||
s.execute("edit.paste", json!({"at": "A4"})).unwrap();
|
||||
assert_eq!((v(&s, "A4"), v(&s, "B5"), v(&s, "A10")), (Value::Number(1.0), Value::Number(4.0), Value::Empty));
|
||||
}
|
||||
|
||||
/// Skip Blanks would empty a cut's blank cells along with their note and format, then skip them:
|
||||
/// a cut takes no Paste Special option, and nothing changes.
|
||||
#[test]
|
||||
fn a_cut_is_not_pasted_skipping_blanks() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1]]})).unwrap();
|
||||
s.execute("review.newNote", json!({"cell": "B1", "text": "note", "author": "Example"})).unwrap();
|
||||
s.execute("home.bold", json!({"range": "B1"})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
|
||||
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "skipBlanks": true, "at": "E1"})).is_err());
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
let b1 = CellRef::parse("B1").unwrap();
|
||||
assert!(sh.comments.contains_key(&b1));
|
||||
assert!(d.wb.styles.get(sh.style_id(b1)).font.bold);
|
||||
assert_eq!((v(&s, "A1"), v(&s, "E1")), (Value::Number(1.0), Value::Empty));
|
||||
}
|
||||
|
||||
/// Transposing a cut would move references to it as if it were not transposed: refused, and a
|
||||
/// formula reading the cut cells still reads them.
|
||||
#[test]
|
||||
fn a_cut_is_not_pasted_transposed() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "H1", "input": "=B1"})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
|
||||
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E5"})).is_err());
|
||||
assert_eq!(formula_at(&s, "H1").as_deref(), Some("B1"));
|
||||
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "E5"), v(&s, "E6")), (Value::Number(1.0), Value::Number(2.0), Value::Empty, Value::Empty));
|
||||
}
|
||||
|
||||
/// A cut lands in one place: onto a larger or differently shaped selection it is refused, as in
|
||||
/// Excel, rather than tiled.
|
||||
#[test]
|
||||
fn a_cut_is_not_pasted_over_a_larger_area() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[5]]})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "A1"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "E1:E3"})).unwrap();
|
||||
assert!(s.execute("edit.paste", json!({})).is_err());
|
||||
assert_eq!((v(&s, "A1"), v(&s, "E1"), v(&s, "E2"), v(&s, "E3")), (Value::Number(5.0), Value::Empty, Value::Empty, Value::Empty));
|
||||
}
|
||||
|
||||
/// A paste operation or a partial paste (values only) of a cut would empty the cut cells and
|
||||
/// combine or keep only part of them: refused, and nothing changes.
|
||||
#[test]
|
||||
fn a_cut_is_not_pasted_with_an_operation_or_in_part() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[5]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "E1", "values": [[2]]})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "A1"})).unwrap();
|
||||
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "operation": "add", "at": "E1"})).is_err());
|
||||
assert!(s.execute("edit.pasteSpecial", json!({"what": "values", "at": "E1"})).is_err());
|
||||
assert_eq!((v(&s, "A1"), v(&s, "E1")), (Value::Number(5.0), Value::Number(2.0)));
|
||||
}
|
||||
|
||||
/// A refused paste leaves the cut pending: a plain Paste onto one cell, or onto an area of the cut's
|
||||
/// size, still moves it.
|
||||
#[test]
|
||||
fn a_refused_cut_paste_leaves_the_cut_to_paste_plainly() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
|
||||
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
|
||||
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E5"})).is_err());
|
||||
s.execute("selection.set", json!({"range": "E1"})).unwrap();
|
||||
s.execute("edit.paste", json!({})).unwrap();
|
||||
assert_eq!((v(&s, "A1"), v(&s, "E1"), v(&s, "F1")), (Value::Empty, Value::Number(1.0), Value::Number(2.0)));
|
||||
assert!(s.clipboard.is_none());
|
||||
s.execute("edit.cut", json!({"range": "E1:F1"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "C3:D3"})).unwrap();
|
||||
s.execute("edit.paste", json!({})).unwrap();
|
||||
assert_eq!((v(&s, "E1"), v(&s, "C3"), v(&s, "D3")), (Value::Empty, Value::Number(1.0), Value::Number(2.0)));
|
||||
}
|
||||
|
||||
@@ -531,7 +531,7 @@ fn edit_parts(bytes: &[u8], mut edit: impl FnMut(&str, String) -> String) -> Vec
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..zip.len() {
|
||||
let mut part = zip.by_index(i).unwrap();
|
||||
let name = part.name().to_string();
|
||||
let name = part.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
part.read_to_end(&mut data).unwrap();
|
||||
let data = match String::from_utf8(data) {
|
||||
|
||||
@@ -546,6 +546,18 @@ fn xl_references_follow_name_and_table_renames() {
|
||||
assert_eq!(code(&s, 0, "E1").as_deref(), Some("a = xl(\"Choices\")\nb = xl(\"Data[v]\")"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_python_cell_is_not_a_trend_source() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "2"})).unwrap();
|
||||
plant(&mut s, 0, "A1", "1");
|
||||
let offered = |s: &Session, growth: bool| {
|
||||
let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
|
||||
crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r("A1:A2"), r("A1:A5"), growth)
|
||||
};
|
||||
assert!(!offered(&s, false) && !offered(&s, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_a_link_without_text_preserves_an_empty_python_cell() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -56,7 +56,7 @@ fn with_parts(bytes: &[u8], edit: impl Fn(&str, &str) -> String, add: &[(&str, &
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
if let Ok(text) = std::str::from_utf8(&data) {
|
||||
@@ -250,7 +250,7 @@ fn with_damaged_part(bytes: &[u8], name: &str, marker: &str) -> Vec<u8> {
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let entry = f.name().to_string();
|
||||
let entry = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
let options = zip::write::SimpleFileOptions::default();
|
||||
|
||||
@@ -168,7 +168,8 @@
|
||||
"vert": "Baseline",
|
||||
"charset": null,
|
||||
"family": null,
|
||||
"minor": true
|
||||
"minor": true,
|
||||
"outline": false
|
||||
},
|
||||
"fill": {
|
||||
"pattern": "None",
|
||||
@@ -219,6 +220,7 @@
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"strike": false,
|
||||
"outline": false,
|
||||
"underline": false,
|
||||
"size": false,
|
||||
"name": false,
|
||||
@@ -238,7 +240,8 @@
|
||||
"vert": "Baseline",
|
||||
"charset": null,
|
||||
"family": null,
|
||||
"minor": true
|
||||
"minor": true,
|
||||
"outline": false
|
||||
},
|
||||
"fill": {
|
||||
"pattern": "None",
|
||||
@@ -289,6 +292,7 @@
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"strike": false,
|
||||
"outline": false,
|
||||
"underline": false,
|
||||
"size": false,
|
||||
"name": false,
|
||||
@@ -308,7 +312,8 @@
|
||||
"vert": "Baseline",
|
||||
"charset": null,
|
||||
"family": null,
|
||||
"minor": true
|
||||
"minor": true,
|
||||
"outline": false
|
||||
},
|
||||
"fill": {
|
||||
"pattern": "None",
|
||||
@@ -359,6 +364,7 @@
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"strike": false,
|
||||
"outline": false,
|
||||
"underline": false,
|
||||
"size": false,
|
||||
"name": false,
|
||||
|
||||
@@ -247,6 +247,7 @@
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"name": false,
|
||||
"outline": false,
|
||||
"protection": false,
|
||||
"scheme": null,
|
||||
"size": false,
|
||||
@@ -266,6 +267,7 @@
|
||||
"italic": false,
|
||||
"minor": true,
|
||||
"name": "Calibri",
|
||||
"outline": false,
|
||||
"size": 11.0,
|
||||
"strike": false,
|
||||
"underline": "None",
|
||||
@@ -317,6 +319,7 @@
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"name": false,
|
||||
"outline": false,
|
||||
"protection": false,
|
||||
"scheme": null,
|
||||
"size": false,
|
||||
@@ -336,6 +339,7 @@
|
||||
"italic": false,
|
||||
"minor": true,
|
||||
"name": "Calibri",
|
||||
"outline": false,
|
||||
"size": 11.0,
|
||||
"strike": false,
|
||||
"underline": "None",
|
||||
@@ -387,6 +391,7 @@
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"name": false,
|
||||
"outline": false,
|
||||
"protection": false,
|
||||
"scheme": null,
|
||||
"size": false,
|
||||
@@ -406,6 +411,7 @@
|
||||
"italic": false,
|
||||
"minor": true,
|
||||
"name": "Calibri",
|
||||
"outline": false,
|
||||
"size": 11.0,
|
||||
"strike": false,
|
||||
"underline": "None",
|
||||
|
||||
@@ -7,6 +7,9 @@ fn table() -> Session {
|
||||
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();
|
||||
// Bold in its own style too, so the table style's bold header row changes nothing here and
|
||||
// these tests compare only the filter button's room, with or without the table.
|
||||
s.execute("home.bold", json!({"range":"A1", "on": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use gridcraft_engine::{
|
||||
Session,
|
||||
cmd::data::{filter_selection, filter_values},
|
||||
core::{CellRef, Value},
|
||||
model::{Cell, Color, FilterCriterion, PyCode},
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn python_cells_offer_cached_results_without_exposing_or_changing_code() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Company", "Result"], ["East", 7], ["East", null], ["West", 99]]})).unwrap();
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
for (at, value) in [("B2", Value::Number(7.0)), ("B3", Value::Empty), ("B4", Value::Number(99.0))] {
|
||||
// A loaded workbook can keep Python code alongside a cached or empty result.
|
||||
sh.set_cell(CellRef::parse(at).unwrap(), Cell { value, py: Some(Arc::new(PyCode::new("secret_input * 2"))), ..Default::default() });
|
||||
}
|
||||
s.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let (before, revision, undo) = (doc.wb.clone(), doc.revision, doc.undo.len());
|
||||
assert_eq!(filter_values(&doc.wb, 0, 1), vec![("7".into(), true), ("(Blanks)".into(), true)]);
|
||||
assert_eq!(
|
||||
filter_selection(&doc.wb, 0, 1, &[("7".into(), false), ("(Blanks)".into(), false)]),
|
||||
vec![("7".into(), false), ("99".into(), true), ("(Blanks)".into(), false)],
|
||||
"eligible edits overlay the cached results; a hidden result keeps its checkbox"
|
||||
);
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(Arc::ptr_eq(&before, &doc.wb), "neither query mutates or evaluates the workbook");
|
||||
assert_eq!((doc.revision, doc.undo.len()), (revision, undo));
|
||||
assert_eq!(doc.wb.active().unwrap().cell(CellRef::parse("B3").unwrap()).unwrap().py.as_ref().unwrap().code, "secret_input * 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slicer_criteria_outside_the_sheet_filters_columns_are_still_applied() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Name"], ["one"], ["two"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "F1", "values": [["Region"], ["East"], ["West"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "F1:F3", "name": "Other", "header": true})).unwrap();
|
||||
s.execute("selection.set", json!({"cell": "A1"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:A3"})).unwrap();
|
||||
let id = s.execute("insert.slicer", json!({"table": "Other", "column": "Region"})).unwrap()["slicer"].as_u64().unwrap();
|
||||
|
||||
s.execute("slicer.toggle", json!({"slicer": id, "value": "East"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "A1:A3");
|
||||
assert!(!sh.is_row_hidden(1));
|
||||
assert!(sh.is_row_hidden(2));
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true)]);
|
||||
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2));
|
||||
s.execute("slicer.clear", json!({"slicer": id})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1));
|
||||
assert!(!sh.is_row_hidden(2));
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true), ("two".into(), true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() {
|
||||
for (criterion, expected, mid_checked) in [
|
||||
(json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"], true),
|
||||
(json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"], false),
|
||||
(json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"], false),
|
||||
(json!({"top": {"count": 2}}), vec!["high", "upper"], false),
|
||||
(json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"], true),
|
||||
(json!({"aboveAverage": true}), vec!["high"], false),
|
||||
(json!({"aboveAverage": false}), vec!["low", "mid", "upper"], true),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "A1", "values": [
|
||||
["Name", "Amount"], ["low", 10], ["mid", 20], ["upper", 30], ["high", 100], ["blank", null], ["text", "n/a"]
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B7"})).unwrap();
|
||||
let mut params = criterion.clone();
|
||||
params["column"] = json!("B");
|
||||
s.execute("data.filterBy", params).unwrap();
|
||||
let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect();
|
||||
assert_eq!(actual, expected, "{criterion}");
|
||||
// The current column's own criterion must not narrow its alternatives.
|
||||
s.execute("data.filterBy", json!({"column": "A", "values": ["mid"]})).unwrap();
|
||||
let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect();
|
||||
assert_eq!(actual, expected, "{criterion}, with the current column filtered");
|
||||
assert_eq!(
|
||||
filter_values(&s.doc().unwrap().wb, 0, 1),
|
||||
vec![("20".into(), mid_checked)],
|
||||
"the numeric column's criterion sets checkboxes without excluding alternatives: {criterion}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statistical_thresholds_use_the_original_range_not_other_columns_subset() {
|
||||
for (criterion, names, expected) in [
|
||||
(json!({"top": {"count": 2}}), vec!["low", "mid", "upper"], vec!["upper"]),
|
||||
(json!({"top": {"count": 50, "percent": true}}), vec!["low", "mid", "upper"], vec!["upper"]),
|
||||
(json!({"top": {"count": 2, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]),
|
||||
(json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]),
|
||||
(json!({"aboveAverage": true}), vec!["low", "mid", "upper"], vec![]),
|
||||
(json!({"aboveAverage": false}), vec!["low", "mid", "upper"], vec!["low", "mid", "upper"]),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "A1", "values": [
|
||||
["Name", "Amount", "Job"], ["low", 10, "low"], ["mid", 20, "mid"], ["upper", 30, "upper"], ["high", 100, "high"]
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:C5"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "A", "values": names})).unwrap();
|
||||
let mut params = criterion.clone();
|
||||
params["column"] = json!("B");
|
||||
s.execute("data.filterBy", params).unwrap();
|
||||
// A and B both remain active when enumerating C. Subset statistics produce different jobs.
|
||||
let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 2).into_iter().map(|(v, _)| v).collect();
|
||||
assert_eq!(actual, expected, "{criterion}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "B3", "values": [
|
||||
["Company", "Job", "Status"],
|
||||
["East", "Alpha", "Open"],
|
||||
["East", "Beta", "Open"],
|
||||
["East", "Closed job", "Closed"],
|
||||
["West", "Other company", "Open"],
|
||||
["East", null, "Open"],
|
||||
["East", "=\"\"", "Open"],
|
||||
["East", "Outside range", "Open"]
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range": "B3:D9"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "D", "values": ["Open"]})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "C", "values": ["Alpha"]})).unwrap();
|
||||
|
||||
let choices = |s: &Session| filter_values(&s.doc().unwrap().wb, 0, 2);
|
||||
let expected =
|
||||
|beta: bool, blanks: bool| -> Vec<(String, bool)> { vec![("Alpha".into(), !beta), ("Beta".into(), beta), ("(Blanks)".into(), blanks)] };
|
||||
assert_eq!(choices(&s), expected(false, false));
|
||||
s.execute("data.filterBy", json!({"column": "C", "values": ["Beta"], "blanks": true})).unwrap();
|
||||
assert_eq!(choices(&s), expected(true, true));
|
||||
s.execute("data.filterBy", json!({"column": "C", "clear": true})).unwrap();
|
||||
assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]);
|
||||
// Manual visibility is not a filter criterion, even when every eligible row is hidden.
|
||||
s.execute("home.hideRows", json!({"rows": "4:10"})).unwrap();
|
||||
assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]);
|
||||
assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty());
|
||||
assert!(filter_values(&s.doc().unwrap().wb, 0, 4).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_only_table_has_no_data_values_or_blank_choice() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "B3:C3"})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
assert!(sh.tables[0].header_row);
|
||||
assert_eq!(sh.tables[0].range.height(), 1);
|
||||
assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3");
|
||||
for col in [1, 2] {
|
||||
assert!(filter_values(&d.wb, 0, col).is_empty(), "headers are not values or blank data rows");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_respect_blank_and_formatted_value_criteria_on_other_columns() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "A1", "values": [
|
||||
["Name", "Value"], ["empty", null], ["formula", "=\"\""], ["spaces", " "], ["number", 12], ["other", 30]
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "B5:B6", "code": "0.00"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B6"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap();
|
||||
// Excel AutoFilter's (Blanks) group also matches whitespace-only text (#2911).
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".into(), true), ("spaces".into(), true)]);
|
||||
for value in ["12", "12.00"] {
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": [value]})).unwrap();
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("number".into(), true)]);
|
||||
}
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": ["absent"]})).unwrap();
|
||||
assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Name", "Color"], ["red", 1], ["plain", 2]]})).unwrap();
|
||||
s.execute("home.fillColor", json!({"range": "B2", "color": "#FF0000"})).unwrap();
|
||||
s.execute("home.fontColor", json!({"range": "B2", "color": "#FF0000"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B3"})).unwrap();
|
||||
for criterion in [FilterCriterion::FillColor(Color::Rgb(0xFF0000)), FilterCriterion::FontColor(Color::Rgb(0xFF0000))] {
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
sh.autofilter.as_mut().unwrap().criteria = vec![(1, criterion)];
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("red".into(), true)]);
|
||||
assert_eq!(filter_selection(&s.doc().unwrap().wb, 0, 1, &[]), vec![("1".into(), true), ("2".into(), false)]);
|
||||
}
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
sh.autofilter.as_mut().unwrap().criteria = vec![(1, FilterCriterion::Icon { set: "3Arrows".into(), id: Some(0) })];
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2), "reapply preserves imported icon visibility");
|
||||
assert_eq!(
|
||||
filter_values(&s.doc().unwrap().wb, 0, 0),
|
||||
vec![("plain".into(), true), ("red".into(), true)],
|
||||
"unsupported icon criteria cannot distinguish manual and current-column hiding"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_color_choices_keep_any_eligible_match() {
|
||||
for font in [false, true] {
|
||||
for matching_cell in ["B2", "B3"] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "A1", "values": [["Company", "Color"], ["East", "Same"], ["East", "Same"], ["West", "Same"]]}),
|
||||
)
|
||||
.unwrap();
|
||||
let command = if font { "home.fontColor" } else { "home.fillColor" };
|
||||
s.execute(command, json!({"range": "B4", "color": "#FF0000"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B4"})).unwrap();
|
||||
let color = if font { FilterCriterion::FontColor(Color::Rgb(0xFF0000)) } else { FilterCriterion::FillColor(Color::Rgb(0xFF0000)) };
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
sh.autofilter.as_mut().unwrap().criteria =
|
||||
vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] }), (1, color)];
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
assert_eq!(
|
||||
filter_values(&s.doc().unwrap().wb, 0, 1),
|
||||
vec![("Same".into(), false)],
|
||||
"an excluded red row cannot check an eligible choice"
|
||||
);
|
||||
|
||||
s.execute(command, json!({"range": matching_cell, "color": "#FF0000"})).unwrap();
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
let choices = filter_values(&s.doc().unwrap().wb, 0, 1);
|
||||
assert_eq!(choices, vec![("Same".into(), true)], "either eligible duplicate can supply the color match");
|
||||
let selected = filter_selection(&s.doc().unwrap().wb, 0, 1, &choices);
|
||||
assert_eq!(selected, vec![("Same".into(), true)]);
|
||||
let values: Vec<_> = selected.into_iter().filter_map(|(value, on)| on.then_some(value)).collect();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": values})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(CellRef::parse(matching_cell).unwrap().row), "unchanged Apply keeps the previously matching row");
|
||||
assert!(sh.is_row_hidden(3), "the other column still excludes West");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn querying_a_table_backed_sheet_filter_is_read_only_and_preserves_xlsx_criteria() {
|
||||
for table in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]}))
|
||||
.unwrap();
|
||||
if table {
|
||||
s.execute("insert.table", json!({"range": "B3:C6", "header": true})).unwrap();
|
||||
}
|
||||
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
|
||||
let before = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]);
|
||||
assert_eq!(before, gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap());
|
||||
let (reopened, _) = gridcraft_xlsx::read_xlsx(&before).unwrap();
|
||||
let sh = reopened.active().unwrap();
|
||||
let criteria = if table { &sh.tables[0].filter } else { &sh.autofilter.as_ref().unwrap().criteria };
|
||||
assert_eq!(criteria, &vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })]);
|
||||
assert!(!sh.is_row_hidden(3) && !sh.is_row_hidden(4) && sh.is_row_hidden(5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrelated_tables_criteria_do_not_restrict_the_sheet_filter_choices() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]}))
|
||||
.unwrap();
|
||||
s.execute("range.setValues", json!({"range": "F3", "values": [["Company", "Job"], ["West", "Unrelated"], ["East", "Separate"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "F3:G5", "header": true})).unwrap();
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
sh.tables[0].filter = vec![(0, FilterCriterion::Values { values: vec!["West".into()], blanks: false, identities: vec![] })];
|
||||
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "B3:C6"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty());
|
||||
assert!(filter_values(&s.doc().unwrap().wb, 99, 0).is_empty());
|
||||
s.execute("range.setValues", json!({"range": "B1048574", "values": [["Company", "Job"], ["West", "Before last"], ["East", "Last East"]]}))
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range": "B1048574:C1048576"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap();
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_filters_keep_choices_and_statistics_inside_the_grid() {
|
||||
use gridcraft_engine::core::{MAX_ROWS, RangeRef};
|
||||
use gridcraft_engine::model::AutoFilter;
|
||||
|
||||
for criterion in [FilterCriterion::Top10 { bottom: false, percent: false, count: 1 }, FilterCriterion::AboveAverage(true)] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let range = RangeRef::new(CellRef::new(MAX_ROWS - 3, 0), CellRef::new(MAX_ROWS + 1, 0));
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
// Model data loaded from a malformed workbook can extend beyond the grid.
|
||||
for (row, value) in [(MAX_ROWS - 2, 1.0), (MAX_ROWS - 1, 9.0), (MAX_ROWS, 100.0)] {
|
||||
sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Number(value), ..Default::default() });
|
||||
}
|
||||
sh.autofilter = Some(AutoFilter { range, criteria: vec![(0, criterion)] });
|
||||
let doc = s.doc().unwrap();
|
||||
let before = doc.wb.clone();
|
||||
let expected = vec![("1".into(), false), ("9".into(), true)];
|
||||
assert_eq!(filter_values(&doc.wb, 0, 0), expected, "out-of-grid data must not affect the choices or thresholds");
|
||||
assert_eq!(filter_selection(&doc.wb, 0, 0, &[]), expected);
|
||||
assert!(Arc::ptr_eq(&before, &s.doc().unwrap().wb), "queries must not trim the stored workbook");
|
||||
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(sh.is_row_hidden(MAX_ROWS - 2));
|
||||
assert!(!sh.is_row_hidden(MAX_ROWS - 1), "the valid maximum still matches Top 1 and Above Average");
|
||||
assert!(sh.rows.keys().all(|row| *row < MAX_ROWS), "no hidden-row entries may be created beyond the grid");
|
||||
assert_eq!(sh.autofilter.as_ref().unwrap().range, range, "the scan bound does not rewrite imported metadata");
|
||||
assert_eq!(sh.value(CellRef::new(MAX_ROWS, 0)), Value::Number(100.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merging_hidden_choices_preserves_the_active_criterion() {
|
||||
for (criterion, checked) in [
|
||||
(json!({"values": ["7"], "blanks": true}), [false, true, false, false, true]),
|
||||
(json!({"custom": {"op": ">=", "value": 7}}), [false, true, true, true, false]),
|
||||
(json!({"top": {"count": 2}}), [false, false, true, true, false]),
|
||||
(json!({"aboveAverage": true}), [false, false, false, true, false]),
|
||||
(json!({"aboveAverage": false}), [true, true, true, false, false]),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "A1", "values": [["Region", "Amount"], ["East", 1], ["East", 9], ["West", 7], ["West", 20], ["West", null]]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "B2:B6", "code": "0.00"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:B6"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap();
|
||||
let mut params = criterion.clone();
|
||||
params["column"] = json!("B");
|
||||
s.execute("data.filterBy", params).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let choices = filter_values(&doc.wb, 0, 1);
|
||||
let selection = filter_selection(&doc.wb, 0, 1, &choices);
|
||||
let expected: Vec<_> =
|
||||
["1.00", "7.00", "9.00", "20.00", "(Blanks)"].into_iter().zip(checked).map(|(label, on)| (label.to_string(), on)).collect();
|
||||
assert_eq!(selection, expected, "unchanged eligible choices must preserve hidden matches: {criterion}");
|
||||
let values: Vec<_> = selection.iter().filter(|(label, on)| *on && label != "(Blanks)").map(|(label, _)| label.clone()).collect();
|
||||
s.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": checked[4]})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column": "A", "clear": true})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
for (row, on) in [checked[0], checked[2], checked[1], checked[3], checked[4]].into_iter().enumerate() {
|
||||
assert_eq!(!sh.is_row_hidden(row as u32 + 1), on, "row after Apply and clearing the other filter: {criterion}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_values_criteria_preserve_unicode_case_and_blank_matching() {
|
||||
use gridcraft_engine::core::RangeRef;
|
||||
use gridcraft_engine::model::AutoFilter;
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap();
|
||||
let mut selected = Vec::new();
|
||||
for row in 1..=5_000 {
|
||||
sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Text(format!("item-{row}").into()), ..Default::default() });
|
||||
sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Number(f64::from(row)), ..Default::default() });
|
||||
selected.push(format!("ITEM-{row}"));
|
||||
}
|
||||
selected.extend(["ITEM-1".into(), "Ä".into()]);
|
||||
for (row, value, label) in [
|
||||
(5_001, Value::Text("Ä".into()), "unicode exact"),
|
||||
(5_002, Value::Text("ä".into()), "unicode case folded"),
|
||||
(5_003, Value::Empty, "blank row"),
|
||||
] {
|
||||
sh.set_cell(CellRef::new(row, 0), Cell { value, ..Default::default() });
|
||||
sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Text(label.into()), ..Default::default() });
|
||||
}
|
||||
sh.autofilter = Some(AutoFilter {
|
||||
range: RangeRef::new(CellRef::new(0, 0), CellRef::new(5_003, 1)),
|
||||
criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true, identities: vec![] })],
|
||||
});
|
||||
let choices = filter_values(&s.doc().unwrap().wb, 0, 1);
|
||||
let mut expected: Vec<_> = (1..=5_000).map(|n| (n.to_string(), true)).collect();
|
||||
expected.extend([("blank row".into(), true), ("unicode case folded".into(), true), ("unicode exact".into(), true)]);
|
||||
assert_eq!(choices, expected);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! The 100% stacked line charts: `insert.chart` and `chart.set` take type `line` with subtype
|
||||
//! `stacked100` or `stacked100Markers`.
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_model::ChartKind;
|
||||
use serde_json::json;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", "10", "30"], ["Q2", "30", "10"]]})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn kinds(s: &Session) -> Vec<ChartKind> {
|
||||
s.doc().unwrap().wb.sheet(0).unwrap().charts.iter().map(|c| c.kind).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_chart_makes_hundred_percent_stacked_lines() {
|
||||
let mut s = session();
|
||||
s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100"})).unwrap();
|
||||
s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100Markers"})).unwrap();
|
||||
assert_eq!(kinds(&s), [ChartKind::LineStacked100, ChartKind::LineStacked100Markers]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_set_changes_a_chart_to_a_hundred_percent_stacked_line_and_back() {
|
||||
let mut s = session();
|
||||
s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked"})).unwrap();
|
||||
assert_eq!(kinds(&s), [ChartKind::LineStacked]);
|
||||
s.execute("chart.set", json!({"type": "line", "subtype": "stacked100Markers"})).unwrap();
|
||||
assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]);
|
||||
s.execute("chart.set", json!({"type": "line", "subtype": "stacked100"})).unwrap();
|
||||
assert_eq!(kinds(&s), [ChartKind::LineStacked100]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]);
|
||||
}
|
||||
@@ -60,7 +60,7 @@ fn edit_chart(bytes: &[u8], edit: impl Fn(String) -> String) -> Vec<u8> {
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
if name == "xl/charts/chart1.xml" {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! and saving, reloading or recalculating never panics either;
|
||||
//! - a non-undoable command never changes cell content (it would be lost to undo);
|
||||
//! - the structure stays valid: active sheet in range, sheet and table names valid and unique,
|
||||
//! merges and tables on the sheet and not overlapping, legacy arrays anchored at their
|
||||
//! merges and tables on the sheet and not overlapping (nor a merge inside a table), legacy arrays anchored at their
|
||||
//! top-left cell, the selection on the sheet;
|
||||
//! - a full recalculation from scratch gives the values the incremental recalculation left
|
||||
//! (catches stale dependency graphs);
|
||||
@@ -442,6 +442,10 @@ fn structure_problem(wb: &Workbook, sel: &gridcraft_engine::Selection) -> Option
|
||||
if let Some(o) = sh.tables.iter().skip(k + 1).find(|o| overlaps(&t.range, &o.range)) {
|
||||
return Some(format!("{}: tables `{}` ({}) and `{}` ({}) overlap", sh.name, t.name, t.range, o.name, o.range));
|
||||
}
|
||||
// Excel removes a table that holds a merged cell when it opens the file.
|
||||
if let Some(m) = sh.merges.iter().find(|m| overlaps(&t.range, m)) {
|
||||
return Some(format!("{}: table `{}` ({}) holds merged cells {m}", sh.name, t.name, t.range));
|
||||
}
|
||||
}
|
||||
}
|
||||
if sel.ranges.is_empty() || !sel.active.is_valid() || sel.ranges.iter().any(|r| !r.start.is_valid() || !r.end.is_valid()) {
|
||||
@@ -525,9 +529,9 @@ fn watch_list(wb: &Workbook) -> Option<&str> {
|
||||
wb.names.iter().find(|n| n.name == WATCH_NAME).map(|n| n.formula.as_str())
|
||||
}
|
||||
|
||||
/// The workbook with view state (active sheet, scroll, active cell, Normal / Page Layout / Page
|
||||
/// Break Preview) and the Watch Window list reset: undo restores view state as it was, but
|
||||
/// switching sheets or views isn't an undoable edit.
|
||||
/// The workbook with view state (active sheet, scroll, active cell, zoom, Normal / Page Layout /
|
||||
/// Page Break Preview) and the Watch Window list reset: undo restores view state as it was, but
|
||||
/// switching sheets, zooming or switching views isn't an undoable edit.
|
||||
fn canonical(wb: &Workbook) -> Workbook {
|
||||
let mut wb = wb.clone();
|
||||
wb.set_active_sheet(0);
|
||||
@@ -536,6 +540,7 @@ fn canonical(wb: &Workbook) -> Workbook {
|
||||
let sh = Arc::make_mut(sh);
|
||||
sh.view_active = CellRef::default();
|
||||
sh.view_top_left = CellRef::default();
|
||||
sh.zoom = 100;
|
||||
sh.view = SheetViewMode::Normal;
|
||||
}
|
||||
wb
|
||||
|
||||
@@ -0,0 +1,715 @@
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
/// Value-list and equality criteria ignore leading and trailing spaces (#2911).
|
||||
#[test]
|
||||
fn autofilter_ignores_surrounding_spaces_2911() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Name"],
|
||||
["Card"],
|
||||
["Card "],
|
||||
[" Card"],
|
||||
[" Card "],
|
||||
["card"],
|
||||
["CARD"],
|
||||
["Cardx"],
|
||||
["Ca rd"],
|
||||
[" "],
|
||||
[""]
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
s.execute("data.filter", json!({"range": "A1:A11"})).unwrap();
|
||||
|
||||
for value in ["Card", " Card", "Card "] {
|
||||
let result = s.execute("data.filterBy", json!({"column": "A", "values": [value]})).unwrap();
|
||||
|
||||
assert_eq!(result["hiddenRows"], json!(4), "{value:?}");
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
|
||||
for row in 1..=6 {
|
||||
assert!(!sh.is_row_hidden(row), "row {row} should be visible for {value:?}");
|
||||
}
|
||||
|
||||
for row in 7..=10 {
|
||||
assert!(sh.is_row_hidden(row), "row {row} should be hidden for {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
for value in ["Card", " Card", "Card "] {
|
||||
let result = s
|
||||
.execute(
|
||||
"data.filterBy",
|
||||
json!({
|
||||
"column": "A",
|
||||
"custom": {"op": "=", "value": value}
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(result["hiddenRows"], json!(4), "{value:?}");
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
|
||||
for row in 1..=6 {
|
||||
assert!(!sh.is_row_hidden(row), "{value:?}: row {row}");
|
||||
}
|
||||
|
||||
for row in 7..=10 {
|
||||
assert!(sh.is_row_hidden(row), "{value:?}: row {row}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wildcard custom equality trims surrounding spaces before matching (#2911).
|
||||
#[test]
|
||||
fn filter_whitespace_wildcard_2911() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range":"A1", "parse":false,
|
||||
"values":[["Name"], [" Card "], ["Cardx"], ["Other"]]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range":"A1:A4"})).unwrap();
|
||||
|
||||
let r = s.execute("data.filterBy", json!({"column":"A", "custom":{"op":"=", "value":"Card*"}})).unwrap();
|
||||
assert_eq!(r["hiddenRows"], json!(1));
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1));
|
||||
assert!(!sh.is_row_hidden(2));
|
||||
assert!(sh.is_row_hidden(3));
|
||||
}
|
||||
|
||||
/// Custom `=` with spaces matches empty and whitespace-only cells as in Excel (#2911).
|
||||
#[test]
|
||||
fn filter_whitespace_custom_blank_distinction_2911() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range":"A1", "parse":false,
|
||||
"values":[["Name"], [null], [""], [" "], [" "], ["Card"]]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range":"A1:A6"})).unwrap();
|
||||
|
||||
let r = s.execute("data.filterBy", json!({"column":"A", "custom":{"op":"=", "value":" "}})).unwrap();
|
||||
assert_eq!(r["hiddenRows"], json!(1));
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
for row in 1..=4 {
|
||||
assert!(!sh.is_row_hidden(row), "row {row} should be visible");
|
||||
}
|
||||
assert!(sh.is_row_hidden(5));
|
||||
}
|
||||
|
||||
/// Custom `<>` trims surrounding spaces before excluding matching text (#2911).
|
||||
#[test]
|
||||
fn filter_whitespace_custom_not_equal_2911() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range":"A1", "parse":false,
|
||||
"values":[["Name"], [" Card "], ["Card"], ["Other"]]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("data.filter", json!({"range":"A1:A4"})).unwrap();
|
||||
|
||||
let r = s.execute("data.filterBy", json!({"column":"A", "custom":{"op":"<>", "value":"Card"}})).unwrap();
|
||||
assert_eq!(r["hiddenRows"], json!(2));
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(sh.is_row_hidden(1));
|
||||
assert!(sh.is_row_hidden(2));
|
||||
assert!(!sh.is_row_hidden(3));
|
||||
}
|
||||
|
||||
/// Empty and whitespace-only custom `=` and `<>` criteria match Excel Desktop behavior (#2911).
|
||||
#[test]
|
||||
fn filter_whitespace_empty_criteria_regression_2911() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Name"],
|
||||
[null],
|
||||
[""],
|
||||
[" "],
|
||||
[" "],
|
||||
["Card"]
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
s.execute("data.filter", json!({"range": "A1:A6"})).unwrap();
|
||||
|
||||
for (op, criterion, expected_visible) in [("=", "", vec![1, 2, 3, 4]), ("=", " ", vec![1, 2, 3, 4]), ("<>", "", vec![5]), ("<>", " ", vec![5])] {
|
||||
s.execute(
|
||||
"data.filterBy",
|
||||
json!({
|
||||
"column": "A",
|
||||
"custom": {
|
||||
"op": op,
|
||||
"value": criterion
|
||||
}
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
|
||||
let visible: Vec<_> = (1..=5).filter(|&row| !sh.is_row_hidden(row)).collect();
|
||||
|
||||
assert_eq!(visible, expected_visible, "op={op:?}, criterion={criterion:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Selecting `(Blanks)` in the AutoFilter dropdown includes whitespace-only text cells (#2943).
|
||||
#[test]
|
||||
fn filter_whitespace_dropdown_blanks_excel_2943() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Name"],
|
||||
[null],
|
||||
[""],
|
||||
[" "],
|
||||
[" "],
|
||||
["Card"]
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
s.execute("data.filter", json!({"range":"A1:A6"})).unwrap();
|
||||
|
||||
let result = s
|
||||
.execute(
|
||||
"data.filterBy",
|
||||
json!({
|
||||
"column": "A",
|
||||
"values": [],
|
||||
"blanks": true
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(result["hiddenRows"], json!(1));
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
|
||||
for row in 1..=4 {
|
||||
assert!(!sh.is_row_hidden(row), "Excel (Blanks) should include row {row}");
|
||||
}
|
||||
|
||||
assert!(sh.is_row_hidden(5));
|
||||
}
|
||||
|
||||
/// Filtering by a selected whitespace-only cell (`values: [" "]` with `blanks` omitted) keeps blank rows visible (#2943).
|
||||
#[test]
|
||||
fn filter_by_selected_whitespace_cell_keeps_blanks_visible_2943() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Name"],
|
||||
[null],
|
||||
[""],
|
||||
[" "],
|
||||
[" "],
|
||||
["Card"]
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
s.execute("data.filter", json!({"range": "A1:A6"})).unwrap();
|
||||
|
||||
// Simulates "Filter by Selected Cell's Value" (`values: [text]`, no `blanks` key).
|
||||
let result = s.execute("data.filterBy", json!({"column": "A", "values": [" "]})).unwrap();
|
||||
assert_eq!(result["hiddenRows"], json!(1));
|
||||
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
for row in 1..=4 {
|
||||
assert!(!sh.is_row_hidden(row), "whitespace/blank row {row} must stay visible");
|
||||
}
|
||||
assert!(sh.is_row_hidden(5));
|
||||
|
||||
// Explicit `blanks: false` from the dropdown overrides whitespace inference and hides blank/whitespace rows.
|
||||
let result = s.execute("data.filterBy", json!({"column": "A", "values": ["Card", " "], "blanks": false})).unwrap();
|
||||
assert_eq!(result["hiddenRows"], json!(4));
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
for row in 1..=4 {
|
||||
assert!(sh.is_row_hidden(row), "row {row} should be hidden when blanks: false");
|
||||
}
|
||||
assert!(!sh.is_row_hidden(5));
|
||||
}
|
||||
|
||||
/// Legacy saved criteria with whitespace-only `<filter val=" "/>` and `blanks: false` migrate on load and update row visibility immediately (#2943).
|
||||
#[test]
|
||||
fn restored_whitespace_only_criterion_keeps_rows_visible_on_reapply_2943() {
|
||||
use gridcraft_engine::cmd::data::{filter_choices, filter_choices_params};
|
||||
use gridcraft_model::{AutoFilter, FilterCriterion};
|
||||
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Name"],
|
||||
[null],
|
||||
[" "],
|
||||
["Card"]
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Simulate a legacy saved workbook whose filter stored `values: [" "]` with `blanks: false`,
|
||||
// and where the genuinely empty row (row 1 = A2) was hidden by the pre-fix blank branch.
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.autofilter = Some(AutoFilter {
|
||||
range: gridcraft_core::RangeRef::parse("A1:A4").unwrap(),
|
||||
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
|
||||
});
|
||||
sh.rows.entry(1).or_default().hidden = true;
|
||||
sh.rows.entry(3).or_default().hidden = true;
|
||||
}
|
||||
|
||||
// 1. XLSX save + reopen migrates `<filter val=" "/>` AND reapplies immediately on open so
|
||||
// the genuinely empty row A2 is visible before any user `data.reapply` command.
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
|
||||
let (reopened, _) = gridcraft_engine::io::open_bytes("legacy_filter.xlsx", &bytes).unwrap();
|
||||
{
|
||||
let sh = reopened.sheet(0).unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "genuinely empty row must be visible immediately on open");
|
||||
assert!(!sh.is_row_hidden(2), "whitespace-only row must be visible immediately on open");
|
||||
assert!(sh.is_row_hidden(3), "non-matching row must remain hidden on open");
|
||||
}
|
||||
s.active_mut().unwrap().wb = std::sync::Arc::new(reopened);
|
||||
|
||||
// 2. Direct in-memory legacy criterion (`blanks: false`, `values: [" "]`) also keeps blank rows visible on reapply.
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
wb.sheet_mut(0).unwrap().autofilter = Some(AutoFilter {
|
||||
range: gridcraft_core::RangeRef::parse("A1:A4").unwrap(),
|
||||
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
|
||||
});
|
||||
}
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "in-memory legacy empty row must stay visible after reapply");
|
||||
assert!(!sh.is_row_hidden(2), "in-memory legacy whitespace-only row must stay visible after reapply");
|
||||
assert!(sh.is_row_hidden(3), "non-matching row must be hidden after reapply");
|
||||
|
||||
// 3. Verify Show Formulas mode: distinct qualified labels, preserved checklist identity on Apply,
|
||||
// single label for ordinary whitespace variants, and literal `(Blanks)` vs `'(Blanks)'` separation.
|
||||
let mut s2 = Session::new();
|
||||
s2.new_workbook();
|
||||
s2.execute("cell.set", json!({"cell": "A1", "input": "Name"})).unwrap();
|
||||
s2.execute("cell.set", json!({"cell": "A2", "input": "=\" Card \""})).unwrap();
|
||||
s2.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A3",
|
||||
"parse": false,
|
||||
"values": [[" =\" Card \" "], ["Card"], [" Card "], ["(Blanks)"], ["'(Blanks)'"], [" "]]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
s2.execute("formulas.showFormulas", json!({"on": true})).unwrap();
|
||||
|
||||
// With no active criterion, ordinary whitespace variants `"Card"` and `" Card "` merge into one `"Card"` label,
|
||||
// while formula `=" Card "` and literal `" =\" Card \" "` have distinct qualified labels.
|
||||
s2.execute("data.filter", json!({"range": "A1:A8"})).unwrap();
|
||||
let initial_choices = filter_choices(&s2.doc().unwrap().wb, 0, 0);
|
||||
assert_eq!(initial_choices.iter().filter(|c| c.label == "Card").count(), 1, "{initial_choices:?}");
|
||||
let formula_like_labels: Vec<_> = initial_choices.iter().filter(|c| c.label.starts_with("=\" Card \"")).map(|c| c.label.as_str()).collect();
|
||||
assert_eq!(formula_like_labels.len(), 2, "{initial_choices:?}");
|
||||
assert_ne!(formula_like_labels[0], formula_like_labels[1], "colliding identities must have distinct labels: {initial_choices:?}");
|
||||
|
||||
// Filtering by `"Card"` checks `"Card"` and formula `=" Card "`, leaving literal `" =\" Card \" "` unchecked.
|
||||
s2.execute("data.filterBy", json!({"column": "A", "values": ["Card"], "blanks": false})).unwrap();
|
||||
let choices = filter_choices(&s2.doc().unwrap().wb, 0, 0);
|
||||
let formula_entry = choices.iter().find(|c| c.label == "=\" Card \" (result: Card)").expect("formula choice");
|
||||
let literal_entry = choices.iter().find(|c| c.label == "=\" Card \" (text)").expect("literal choice");
|
||||
assert!(formula_entry.checked, "{choices:?}");
|
||||
assert!(!literal_entry.checked, "{choices:?}");
|
||||
|
||||
// Clicking Apply without changing the checks keeps the literal `" =\" Card \" "` row hidden.
|
||||
let unchanged_checks: Vec<_> = choices.iter().map(|c| (c, c.checked)).collect();
|
||||
s2.execute("data.filterBy", filter_choices_params("A", &unchanged_checks)).unwrap();
|
||||
let sh2 = s2.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh2.is_row_hidden(1), "formula row A2 stays visible");
|
||||
assert!(sh2.is_row_hidden(2), "literal row A3 stays hidden");
|
||||
assert!(!sh2.is_row_hidden(3), "Card row A4 stays visible");
|
||||
assert!(!sh2.is_row_hidden(4), "whitespace Card row A5 stays visible");
|
||||
|
||||
// Selecting ONLY the formula checkbox leaves the literal row hidden (and vice versa).
|
||||
let only_formula: Vec<_> = choices.iter().map(|c| (c, c.label == "=\" Card \" (result: Card)")).collect();
|
||||
s2.execute("data.filterBy", filter_choices_params("A", &only_formula)).unwrap();
|
||||
let sh2 = s2.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh2.is_row_hidden(1), "formula row A2 visible");
|
||||
assert!(sh2.is_row_hidden(2), "literal row A3 hidden");
|
||||
assert!(sh2.is_row_hidden(3), "Card row A4 hidden");
|
||||
|
||||
let only_literal: Vec<_> = choices.iter().map(|c| (c, c.label == "=\" Card \" (text)")).collect();
|
||||
s2.execute("data.filterBy", filter_choices_params("A", &only_literal)).unwrap();
|
||||
let sh2 = s2.doc().unwrap().wb.active().unwrap();
|
||||
assert!(sh2.is_row_hidden(1), "formula row A2 hidden");
|
||||
assert!(!sh2.is_row_hidden(2), "literal row A3 visible");
|
||||
assert!(sh2.is_row_hidden(3), "Card row A4 hidden");
|
||||
|
||||
// Literal `(Blanks)`, literal `'(Blanks)'`, and the actual `(Blanks)` toggle all have distinct labels and values.
|
||||
assert!(choices.iter().any(|c| c.label == "(Blanks)" && c.value.is_none() && c.identity.is_none()), "{choices:?}");
|
||||
assert!(choices.iter().any(|c| c.label == "'(Blanks)'" && c.value.as_deref() == Some("(Blanks)")), "{choices:?}");
|
||||
assert!(choices.iter().any(|c| c.label == "''(Blanks)''" && c.value.as_deref() == Some("'(Blanks)'")), "{choices:?}");
|
||||
}
|
||||
|
||||
/// Nonblank cells formatted to display only spaces stay selectable in both dropdown and selected-cell actions (#2943).
|
||||
#[test]
|
||||
fn nonblank_space_formatted_cells_stay_selectable_2943() {
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_engine::cmd::data::{filter_by_cell_params, filter_choices, filter_choices_params};
|
||||
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [[null], [" "], ["Card"]]})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:A5"})).unwrap();
|
||||
|
||||
// 1. Dropdown checklist: selecting only the space-formatted `42` entry keeps row A2 visible and hides blanks.
|
||||
let choices = filter_choices(&s.doc().unwrap().wb, 0, 0);
|
||||
let num_choice = choices.iter().find(|c| c.value.as_deref() == Some("42")).expect("numeric 42 choice");
|
||||
assert_eq!(num_choice.label, "42");
|
||||
let only_42: Vec<_> = choices.iter().map(|c| (c, c.value.as_deref() == Some("42"))).collect();
|
||||
s.execute("data.filterBy", filter_choices_params("A", &only_42)).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "space-formatted 42 row A2 must stay visible");
|
||||
assert!(sh.is_row_hidden(2), "empty row A3 must be hidden");
|
||||
assert!(sh.is_row_hidden(3), "whitespace text row A4 must be hidden");
|
||||
assert!(sh.is_row_hidden(4), "Card row A5 must be hidden");
|
||||
|
||||
// 2. Selected-cell action (`filter_by_cell_params`): on A2 (`42` formatted as `" "`) selects `42`, not blanks;
|
||||
// on A4 (`" "` text) selects blanks, not `42`.
|
||||
s.execute("data.clearFilter", json!({})).unwrap();
|
||||
let params_a2 = {
|
||||
let d = s.doc().unwrap();
|
||||
filter_by_cell_params(&d.wb, d.wb.active().unwrap(), CellRef::parse("A2").unwrap(), "A")
|
||||
};
|
||||
s.execute("data.filterBy", params_a2).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "A2 selected-cell filter keeps 42 visible");
|
||||
assert!(sh.is_row_hidden(2), "A2 selected-cell filter hides empty row");
|
||||
assert!(sh.is_row_hidden(3), "A2 selected-cell filter hides whitespace text row");
|
||||
|
||||
let params_a4 = {
|
||||
let d = s.doc().unwrap();
|
||||
filter_by_cell_params(&d.wb, d.wb.active().unwrap(), CellRef::parse("A4").unwrap(), "A")
|
||||
};
|
||||
s.execute("data.filterBy", params_a4).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(sh.is_row_hidden(1), "A4 selected-cell filter hides 42");
|
||||
assert!(!sh.is_row_hidden(2), "A4 selected-cell filter keeps empty row visible");
|
||||
assert!(!sh.is_row_hidden(3), "A4 selected-cell filter keeps whitespace text row visible");
|
||||
|
||||
// 3. Formatted-blank number `42` vs formatted-blank text `"42"` (`;;;`) keep distinct qualified labels,
|
||||
// and a >11-digit General number (`1234567890123`) keeps its checklist identity across Show Formulas toggles.
|
||||
let mut s3 = Session::new();
|
||||
s3.new_workbook();
|
||||
s3.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
|
||||
s3.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
|
||||
s3.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
|
||||
s3.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [["42"]]})).unwrap();
|
||||
s3.execute("home.numberFormat", json!({"range": "A3", "format": ";;;"})).unwrap();
|
||||
s3.execute("cell.set", json!({"cell": "A4", "input": "1234567890123"})).unwrap();
|
||||
s3.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
|
||||
|
||||
let c3 = filter_choices(&s3.doc().unwrap().wb, 0, 0);
|
||||
assert!(c3.iter().any(|c| c.label == "42 (formatted blank, number)"), "{c3:?}");
|
||||
assert!(c3.iter().any(|c| c.label == "42 (formatted blank, text)"), "{c3:?}");
|
||||
|
||||
let only_big: Vec<_> = c3.iter().map(|c| (c, c.value.as_deref() == Some("1.23457E+12"))).collect();
|
||||
s3.execute("data.filterBy", filter_choices_params("A", &only_big)).unwrap();
|
||||
s3.execute("formulas.showFormulas", json!({"on": true})).unwrap();
|
||||
s3.execute("data.reapply", json!({})).unwrap();
|
||||
assert!(!s3.doc().unwrap().wb.active().unwrap().is_row_hidden(3), "1234567890123 stays visible across Show Formulas toggle");
|
||||
}
|
||||
|
||||
/// Checklist selections survive number-format changes, Show Formulas toggles, and XLSX save/reopen (#2943).
|
||||
#[test]
|
||||
fn checklist_identity_survives_format_change_show_formulas_and_xlsx_2943() {
|
||||
use gridcraft_engine::cmd::data::{filter_choices, filter_choices_params};
|
||||
|
||||
// 1. Numeric `42` selected under General stays selected after formatting as `" "` and running `data.reapply`,
|
||||
// without matching literal text `"42"`.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [["42"], ["Other"]]})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
|
||||
|
||||
let c1 = filter_choices(&s.doc().unwrap().wb, 0, 0);
|
||||
let only_num: Vec<_> = c1.iter().map(|c| (c, c.label == "42 (number)")).collect();
|
||||
s.execute("data.filterBy", filter_choices_params("A", &only_num)).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "numeric 42 must stay visible after formatting as space");
|
||||
assert!(sh.is_row_hidden(2), "literal text '42' must stay hidden");
|
||||
assert!(sh.is_row_hidden(3), "Other row must stay hidden");
|
||||
|
||||
// 2. Show Formulas ON -> select only formula `="Card"` -> turn Show Formulas OFF ->
|
||||
// checklist keeps `="Card"` checked and `"Card"`/`" Card "` merged & unchecked -> Apply keeps literal hidden.
|
||||
let mut sf = Session::new();
|
||||
sf.new_workbook();
|
||||
sf.execute("cell.set", json!({"cell": "A1", "input": "Name"})).unwrap();
|
||||
sf.execute("cell.set", json!({"cell": "A2", "input": "=\" Card \""})).unwrap();
|
||||
sf.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [["Card"], [" Card "], ["Other"]]})).unwrap();
|
||||
sf.execute("formulas.showFormulas", json!({"on": true})).unwrap();
|
||||
sf.execute("data.filter", json!({"range": "A1:A5"})).unwrap();
|
||||
|
||||
let on_choices = filter_choices(&sf.doc().unwrap().wb, 0, 0);
|
||||
let only_formula: Vec<_> = on_choices.iter().map(|c| (c, c.label.starts_with("=\" Card \""))).collect();
|
||||
sf.execute("data.filterBy", filter_choices_params("A", &only_formula)).unwrap();
|
||||
|
||||
// Save + reopen XLSX while formula identity is active, then `data.reapply` must still hide literal `"Card"`.
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&sf.doc().unwrap().wb).unwrap();
|
||||
let (reopened, _) = gridcraft_engine::io::open_bytes("formula_identity.xlsx", &bytes).unwrap();
|
||||
sf.active_mut().unwrap().wb = std::sync::Arc::new(reopened);
|
||||
sf.execute("data.reapply", json!({})).unwrap();
|
||||
{
|
||||
let sh = sf.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "formula row A2 stays visible after XLSX reopen + reapply");
|
||||
assert!(sh.is_row_hidden(2), "literal Card row A3 stays hidden after XLSX reopen + reapply");
|
||||
assert!(sh.is_row_hidden(3), "whitespace Card row A4 stays hidden after XLSX reopen + reapply");
|
||||
}
|
||||
|
||||
// Turn Show Formulas OFF: dropdown keeps formula `=" Card "` checked and literal `"Card"` + `" Card "` merged & unchecked.
|
||||
sf.execute("formulas.showFormulas", json!({"on": false})).unwrap();
|
||||
let off_choices = filter_choices(&sf.doc().unwrap().wb, 0, 0);
|
||||
assert_eq!(off_choices.len(), 3, "expected formula Card, merged literal Card, and Other: {off_choices:?}");
|
||||
assert_eq!(off_choices.iter().filter(|c| c.checked).count(), 1, "{off_choices:?}");
|
||||
|
||||
let unchanged_off: Vec<_> = off_choices.iter().map(|c| (c, c.checked)).collect();
|
||||
sf.execute("data.filterBy", filter_choices_params("A", &unchanged_off)).unwrap();
|
||||
let sh = sf.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "formula row A2 stays visible after Apply with Show Formulas off");
|
||||
assert!(sh.is_row_hidden(2), "literal Card row A3 stays hidden after Apply with Show Formulas off");
|
||||
assert!(sh.is_row_hidden(3), "whitespace Card row A4 stays hidden after Apply with Show Formulas off");
|
||||
assert!(sh.is_row_hidden(4), "Other row A5 stays hidden");
|
||||
}
|
||||
|
||||
/// Migration preserves manually hidden rows and respects sibling side-by-side table filters (#2943).
|
||||
#[test]
|
||||
fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
|
||||
use gridcraft_core::RangeRef;
|
||||
use gridcraft_model::{AutoFilter, FilterCriterion, Table, TableColumn, TotalsFn};
|
||||
|
||||
// 1. Manually hidden `"Card"` row stays hidden when `[" ", "Card"]` migrates on open,
|
||||
// while genuinely empty row excluded by old filter becomes visible.
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [["Name"], [null], ["Card"], ["Card"], ["Other"]]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.autofilter = Some(AutoFilter {
|
||||
range: RangeRef::parse("A1:A5").unwrap(),
|
||||
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into(), "Card".into()], blanks: false, identities: vec![] })],
|
||||
});
|
||||
// Row 1 (A2 = null) was hidden by old blank branch; Row 2 (A3 = "Card") was hidden manually;
|
||||
// Row 3 (A4 = "Card") is visible; Row 4 (A5 = "Other") was hidden by filter.
|
||||
sh.rows.entry(1).or_default().hidden = true;
|
||||
sh.rows.entry(2).or_default().hidden = true;
|
||||
sh.rows.entry(4).or_default().hidden = true;
|
||||
}
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
|
||||
let (reopened, _) = gridcraft_engine::io::open_bytes("manual_hidden.xlsx", &bytes).unwrap();
|
||||
let sh = reopened.sheet(0).unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "empty row A2 excluded by old filter becomes visible");
|
||||
assert!(sh.is_row_hidden(2), "manually hidden matching Card row A3 must remain hidden");
|
||||
assert!(!sh.is_row_hidden(3), "visible Card row A4 remains visible");
|
||||
assert!(sh.is_row_hidden(4), "non-matching Other row A5 remains hidden");
|
||||
|
||||
// 2. Two side-by-side tables sharing worksheet rows: migrating Table1 must not unhide a row excluded by Table2.
|
||||
let mut st = Session::new();
|
||||
st.new_workbook();
|
||||
st.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Item", "Region"],
|
||||
[null, "West"],
|
||||
[null, "East"],
|
||||
["Card", "East"]
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut st.active_mut().unwrap().wb);
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let col =
|
||||
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
|
||||
sh.tables.push(Table {
|
||||
id: 1,
|
||||
name: "LeftTable".into(),
|
||||
range: RangeRef::parse("A1:A4").unwrap(),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![col("Item")],
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: true,
|
||||
filter: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
});
|
||||
sh.tables.push(Table {
|
||||
id: 2,
|
||||
name: "RightTable".into(),
|
||||
range: RangeRef::parse("B1:B4").unwrap(),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: vec![col("Region")],
|
||||
style: "TableStyleMedium2".into(),
|
||||
banded_rows: true,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: true,
|
||||
filter: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
});
|
||||
sh.rows.entry(1).or_default().hidden = true;
|
||||
sh.rows.entry(2).or_default().hidden = true;
|
||||
sh.rows.entry(3).or_default().hidden = true;
|
||||
}
|
||||
let tbytes = gridcraft_xlsx::write_xlsx(&st.doc().unwrap().wb).unwrap();
|
||||
let (treopened, _) = gridcraft_engine::io::open_bytes("two_tables.xlsx", &tbytes).unwrap();
|
||||
let tsh = treopened.sheet(0).unwrap();
|
||||
assert!(tsh.is_row_hidden(1), "row 1 (West) is still excluded by RightTable and must stay hidden");
|
||||
assert!(!tsh.is_row_hidden(2), "row 2 (empty + East) passes both tables after migration and becomes visible");
|
||||
assert!(tsh.is_row_hidden(3), "row 3 (Card + East) is excluded by LeftTable blanks filter and stays hidden");
|
||||
}
|
||||
|
||||
/// Table slicers merge surrounding-whitespace variants into a single tile (#2943).
|
||||
#[test]
|
||||
fn slicer_groups_whitespace_variants_into_single_tile_2943() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [["Name"], [" Card "], ["Card"], ["Other"], [" "]]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:A5", "name": "Items"})).unwrap();
|
||||
let res = s.execute("insert.slicer", json!({"table": "Items", "column": "Name"})).unwrap();
|
||||
let id = res["slicer"].as_u64().unwrap() as u32;
|
||||
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let sl = wb.active().unwrap().slicers.iter().find(|x| x.id == id).unwrap();
|
||||
let tiles = gridcraft_engine::cmd::slicer::slicer_items(wb, 0, sl);
|
||||
assert_eq!(tiles, vec![("Card".to_string(), true), ("Other".to_string(), true)]);
|
||||
|
||||
s.execute("slicer.toggle", json!({"slicer": id, "value": "Card"})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "' Card ' row stays visible");
|
||||
assert!(!sh.is_row_hidden(2), "'Card' row stays visible");
|
||||
assert!(sh.is_row_hidden(3), "'Other' row hidden");
|
||||
assert!(sh.is_row_hidden(4), "whitespace-only row hidden");
|
||||
}
|
||||
|
||||
/// Table slicers merge non-ASCII Unicode case variants into a single tile and keep both visible (#2943).
|
||||
#[test]
|
||||
fn slicer_groups_unicode_case_variants_into_single_tile_2943() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A1",
|
||||
"parse": false,
|
||||
"values": [["School"], ["ÉCOLE"], ["école"], ["autre"]]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:A4", "name": "Schools"})).unwrap();
|
||||
let res = s.execute("insert.slicer", json!({"table": "Schools", "column": "School"})).unwrap();
|
||||
let id = res["slicer"].as_u64().unwrap() as u32;
|
||||
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let sl = wb.active().unwrap().slicers.iter().find(|x| x.id == id).unwrap();
|
||||
let tiles = gridcraft_engine::cmd::slicer::slicer_items(wb, 0, sl);
|
||||
// Unicode case variants 'ÉCOLE' and 'école' must share one tile.
|
||||
assert_eq!(tiles.len(), 2, "must produce 2 tiles: ÉCOLE and autre, but was {tiles:?}");
|
||||
assert!(tiles.iter().any(|(t, on)| (t == "ÉCOLE" || t == "école") && *on));
|
||||
assert!(tiles.iter().any(|(t, on)| t == "autre" && *on));
|
||||
|
||||
// Selecting the shared tile keeps both 'ÉCOLE' and 'école' visible.
|
||||
let tile_name = tiles.iter().find(|(t, _)| t == "ÉCOLE" || t == "école").unwrap().0.clone();
|
||||
s.execute("slicer.toggle", json!({"slicer": id, "value": tile_name})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "ÉCOLE row stays visible");
|
||||
assert!(!sh.is_row_hidden(2), "école row stays visible");
|
||||
assert!(sh.is_row_hidden(3), "autre row hidden");
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The crate's integration tests, one module per file, built as one test binary.
|
||||
|
||||
mod autofit_filter_buttons;
|
||||
mod cascading_filter_values;
|
||||
mod cf_formula_validate;
|
||||
mod chart_area_stacked100;
|
||||
mod chart_line_stacked100;
|
||||
mod chart_workbook_names;
|
||||
mod command_sequence_fuzz;
|
||||
mod cross_sheet_cut;
|
||||
@@ -12,6 +14,7 @@ mod custom_filter_blanks;
|
||||
mod custom_view_freeze;
|
||||
mod dynamicmetadata;
|
||||
mod extreme_selection_moves;
|
||||
mod filter_whitespace;
|
||||
mod font_scheme_minor;
|
||||
mod format_as_table_restyle;
|
||||
mod hidden_sheet_navigation;
|
||||
@@ -31,6 +34,7 @@ mod sheet_name_quoting;
|
||||
mod sparse_clear_invalidation;
|
||||
mod stored_list_shape;
|
||||
mod structural_edit_rewrite;
|
||||
mod subtotal_filter_roundtrip;
|
||||
mod table_resize_overlap;
|
||||
mod table_style_looks;
|
||||
mod table_total_row_last_row;
|
||||
|
||||
@@ -17,7 +17,7 @@ fn value(s: &Session, sheet: &str, cell: &str) -> Value {
|
||||
fn copied_sheet_keeps_spill_values_through_full_recalc() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"sample": "grades"}));
|
||||
run(&mut s, "home.mergeCells", json!({"range": "F:H"}));
|
||||
run(&mut s, "home.mergeCells", json!({"range": "F15:H20"}));
|
||||
run(&mut s, "cell.set", json!({"cell": "J54", "input": "=SEQUENCE(5)*C6"}));
|
||||
run(&mut s, "selection.set", json!({"range": "15:15"}));
|
||||
run(&mut s, "sheet.move", json!({"copy": true, "sheet": 0, "to": 1}));
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen.
|
||||
//!
|
||||
//! Excel (observed in Windows Excel 16 with synthetic workbooks) saves rows a filter hides as plain
|
||||
//! `hidden="1"` rows; a hidden row counts as filtered when it lies in an AutoFilter (sheet or table)
|
||||
//! that has criteria. Excel can't hold a sheet AutoFilter that overlaps a table, so GridCraft saves
|
||||
//! a table's filter in the table part and never creates a sheet AutoFilter over part of a table.
|
||||
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use gridcraft_engine::calc::Calc;
|
||||
use gridcraft_engine::model::Workbook;
|
||||
use gridcraft_engine::{Session, io};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
fn reopened(wb: &Workbook) -> Workbook {
|
||||
let bytes = io::save_bytes(wb, "t.xlsx").unwrap();
|
||||
let (mut back, _) = io::open_bytes("t.xlsx", &bytes).unwrap();
|
||||
Calc::new().recalc_all(&mut back);
|
||||
back
|
||||
}
|
||||
|
||||
/// Every formula value in memory against the same cell after a save and reopen.
|
||||
fn assert_values_survive(wb: &Workbook) {
|
||||
let back = reopened(wb);
|
||||
for (a, b) in wb.sheets.iter().zip(&back.sheets) {
|
||||
for (c, cell) in a.cells.iter() {
|
||||
if cell.formula.is_some() {
|
||||
assert_eq!(cell.value, b.value(c), "{}!{} ({:?})", a.name, c.a1(), cell.formula.as_ref().map(|f| &f.text));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session(sample: &str, steps: &[(&str, Json)]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": sample})).unwrap();
|
||||
for (id, p) in steps {
|
||||
// A refused step leaves the book as it was; the asserts check what survives.
|
||||
let _ = s.execute(id, p.clone());
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn wb(s: &Session) -> &Workbook {
|
||||
&s.doc().unwrap().wb
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bead_repro_filter_then_replace_on_the_sales_sample() {
|
||||
let s =
|
||||
session("sales", &[("data.filterBy", json!({"column":"G","top":{"count":2}})), ("edit.replace", json!({"all":true,"what":"1","with":""}))]);
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range))));
|
||||
assert_values_survive(wb(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bead_repro_subtotal_then_filter_on_the_grades_sample() {
|
||||
let s = session(
|
||||
"grades",
|
||||
&[
|
||||
("home.insertColumns", json!({})),
|
||||
("data.subtotal", json!({"columns":["G"],"function":"sum","groupBy":"J"})),
|
||||
("data.filterBy", json!({"column":"B","values":["x"]})),
|
||||
],
|
||||
);
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range))));
|
||||
assert_values_survive(wb(&s));
|
||||
}
|
||||
|
||||
/// A table A1:B7 (Name, Qty = 1, 10, 100...) with SUBTOTAL(9) and SUBTOTAL(109) beside it.
|
||||
fn table_book() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1","values":[["Name","Qty"],["a",1],["b",10],["c",100],["d",1000],["e",10000],["f",100000]]}))
|
||||
.unwrap();
|
||||
s.execute("insert.table", json!({"range":"A1:B7","header":true})).unwrap();
|
||||
s.execute("cell.set", json!({"cell":"E1","input":"=SUBTOTAL(9,B2:B7)"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell":"E2","input":"=SUBTOTAL(109,B2:B7)"})).unwrap();
|
||||
s.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn e1_e2(wb: &Workbook) -> (Value, Value) {
|
||||
let sh = wb.active().unwrap();
|
||||
(sh.value(CellRef::new(0, 4)), sh.value(CellRef::new(1, 4)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_filter_keeps_subtotal_and_criteria_through_save() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap();
|
||||
// Like Excel, a row hidden by hand inside an active filter range is left out by SUBTOTAL 9 too.
|
||||
s.execute("home.hideRows", json!({"rows":"6:6"})).unwrap();
|
||||
assert_eq!(e1_e2(wb(&s)), (Value::Number(100101.0), Value::Number(100101.0)));
|
||||
assert_values_survive(wb(&s));
|
||||
let back = reopened(wb(&s));
|
||||
assert_eq!(e1_e2(&back), (Value::Number(100101.0), Value::Number(100101.0)));
|
||||
let t = &back.active().unwrap().tables[0];
|
||||
assert_eq!(t.filter.len(), 1, "the criteria are saved with the table: {:?}", t.filter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_hidden_by_hand_without_a_filter_still_count_for_subtotal_9() {
|
||||
let mut s = table_book();
|
||||
s.execute("home.hideRows", json!({"rows":"3:3"})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows":"5:5"})).unwrap();
|
||||
assert_eq!(e1_e2(wb(&s)), (Value::Number(111111.0), Value::Number(110101.0)));
|
||||
let back = reopened(wb(&s));
|
||||
assert_eq!(e1_e2(&back), (Value::Number(111111.0), Value::Number(110101.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrower_range_inside_a_filtered_table_is_refused_not_dropped() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap();
|
||||
let back = reopened(wb(&s));
|
||||
let mut s = Session::new();
|
||||
s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s.execute("selection.set", json!({"cell":"D1"})).unwrap();
|
||||
assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err());
|
||||
assert_eq!(wb(&s).active().unwrap().tables[0].filter.len(), 1, "the table's criteria are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtering_a_reopened_table_again_keeps_both_criteria() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap();
|
||||
let back = reopened(wb(&s));
|
||||
let mut s = Session::new();
|
||||
s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column":"B","custom":{"op":">","value":"50"}})).unwrap();
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.tables[0].filter.is_empty(), "the table's criteria moved into the live filter");
|
||||
assert_eq!(sh.autofilter.as_ref().map(|af| af.criteria.len()), Some(2));
|
||||
assert_eq!(e1_e2(wb(&s)), (Value::Number(110100.0), Value::Number(110100.0)));
|
||||
assert_values_survive(wb(&s));
|
||||
assert_eq!(reopened(wb(&s)).active().unwrap().tables[0].filter.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_filter_from_outside_a_table_leaves_the_table_out() {
|
||||
// Excel: table B4:C8 with text in A1:A3, A5:A8 and B3. AutoFilter from A1 covers A1:A3, from
|
||||
// A6 A5:A8, from B3 A1:B3; an explicit range over part of the table is refused.
|
||||
let layout = || {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1","values":[["Title"],["x"],["y"]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell":"B3","input":"z"})).unwrap();
|
||||
s.execute("range.setValues", json!({"range":"B4","values":[["Name","Qty"],["n5","v5"],["n6","v6"],["n7","v7"],["n8","v8"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range":"A5","values":[["a5"],["a6"],["a7"],["a8"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"B4:C8","header":true})).unwrap();
|
||||
s
|
||||
};
|
||||
for (cell, want) in [("A1", "A1:A3"), ("A6", "A5:A8"), ("B3", "A1:B3")] {
|
||||
let mut s = layout();
|
||||
s.execute("selection.set", json!({"cell": cell})).unwrap();
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
let af = wb(&s).active().unwrap().autofilter.clone();
|
||||
assert_eq!(af.map(|a| a.range.a1()), Some(want.to_string()), "from {cell}");
|
||||
}
|
||||
let mut s = layout();
|
||||
assert!(s.execute("data.filter", json!({"range":"A1:C8"})).is_err());
|
||||
assert!(wb(&s).active().unwrap().autofilter.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_a_table_filter_off_keeps_rows_another_table_still_hides() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1","values":[["K","V"],["k1",1],["k2",2],["k3",3],["k4",4],["k5",5]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range":"D1","values":[["X","Y"],["x1",1],["x2",2],["x3",3],["x4",4],["x5",5]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"A1:B6","header":true})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"D1:E6","header":true})).unwrap();
|
||||
// The second table's criteria are saved with it, so both tables hold a filter after reopening.
|
||||
s.execute("selection.set", json!({"cell":"D2"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap();
|
||||
let mut s2 = Session::new();
|
||||
s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s2.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s2.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap();
|
||||
s2.execute("data.filter", json!({})).unwrap();
|
||||
let sh = wb(&s2).active().unwrap();
|
||||
assert!(!sh.is_row_hidden(2), "only the first table hid row 3");
|
||||
for row in 3..6 {
|
||||
assert!(sh.is_row_hidden(row), "row {} is still filtered out of the second table", row + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
for (col, keys) in [("A", "k"), ("D", "x"), ("G", "z")] {
|
||||
let mut values = vec![json!(["K", "V"])];
|
||||
values.extend((1..=5).map(|n| json!([format!("{keys}{n}"), n])));
|
||||
s.execute("range.setValues", json!({"range": format!("{col}1"), "values": values})).unwrap();
|
||||
}
|
||||
for range in ["A1:B6", "D1:E6", "G1:H6"] {
|
||||
s.execute("insert.table", json!({"range": range, "header": true})).unwrap();
|
||||
}
|
||||
// Each filtered table's criteria are saved with it: reopening leaves both holding a filter.
|
||||
s.execute("selection.set", json!({"cell":"D2"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap();
|
||||
let mut s2 = Session::new();
|
||||
s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s2.execute("selection.set", json!({"cell":"G2"})).unwrap();
|
||||
s2.execute("data.filterBy", json!({"column":"G","values":["z1","z3"]})).unwrap();
|
||||
let mut s3 = Session::new();
|
||||
s3.add_document(gridcraft_engine::DocState::new(reopened(wb(&s2)), None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s3.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s3.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap();
|
||||
s3.execute("data.filter", json!({})).unwrap();
|
||||
let sh = wb(&s3).active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1));
|
||||
for row in 2..6 {
|
||||
assert!(sh.is_row_hidden(row), "row {} is excluded by one of the two other tables", row + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtering_a_table_whose_buttons_were_turned_off_turns_them_back_on() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
assert!(!wb(&s).active().unwrap().tables[0].filter_button);
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap();
|
||||
assert!(wb(&s).active().unwrap().tables[0].filter_button);
|
||||
let back = reopened(wb(&s));
|
||||
assert_eq!(back.active().unwrap().tables[0].filter.len(), 1, "the criteria are saved with the table");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_range_inside_the_active_table_is_refused_not_a_toggle() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap();
|
||||
assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err());
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.tables[0].filter_button && sh.autofilter.is_some(), "the filter is untouched");
|
||||
}
|
||||
@@ -54,3 +54,168 @@ fn resize_next_to_another_table_still_works() {
|
||||
s.execute("table.resize", json!({"table":"T", "range":"A1:C3"})).unwrap();
|
||||
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
|
||||
}
|
||||
|
||||
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
|
||||
s.doc().unwrap().wb.active().unwrap()
|
||||
}
|
||||
|
||||
fn names(s: &Session, table: usize) -> Vec<String> {
|
||||
sheet(s).tables[table].columns.iter().map(|c| c.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn headers(s: &Session, table: usize) -> Vec<String> {
|
||||
let sh = sheet(s);
|
||||
let r = sh.tables[table].range;
|
||||
(r.start.col..=r.end.col).map(|c| sh.value(gridcraft_core::CellRef::new(r.start.row, c)).display()).collect()
|
||||
}
|
||||
|
||||
fn with_headers(range: &str, row: &[&str]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let rows = vec![row.iter().map(|h| json!(h)).collect::<Vec<_>>(), row.iter().map(|_| json!(1)).collect(), row.iter().map(|_| json!(2)).collect()];
|
||||
s.execute("range.setValues", json!({"range": range, "values": rows})).unwrap();
|
||||
s.execute("insert.table", json!({"range": range, "header": true, "name": "T"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_onto_another_table_is_rejected() {
|
||||
// From the sales sample, growing Table2 over Table1 used to leave two overlapping tables.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": "sales"})).unwrap();
|
||||
s.execute("insert.table", json!({"header": true, "range": "M2:N5"})).unwrap();
|
||||
s.execute("insert.table", json!({"header": true, "range": "P2:Q5"})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"range": "M2:Q5", "table": "Table2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("overlap another table"), "{e}");
|
||||
let ranges: Vec<String> = sheet(&s).tables.iter().map(|t| t.range.a1()).collect();
|
||||
assert!(ranges.contains(&"M2:N5".to_string()) && ranges.contains(&"P2:Q5".to_string()), "{ranges:?}");
|
||||
// Down over a table below, or around a whole table, is refused too; next to it is fine.
|
||||
let mut s = table();
|
||||
s.execute("range.setValues", json!({"range": "A5", "values": [["c"], ["1"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A5:A6", "header": true, "name": "U"})).unwrap();
|
||||
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:B5"})).is_err());
|
||||
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:C9"})).is_err());
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:B4"})).unwrap();
|
||||
assert_eq!(table_range(&s), "A1:B4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_onto_merged_cells_pivot_or_array_is_rejected() {
|
||||
let mut s = table();
|
||||
s.execute("home.mergeCenter", json!({"range": "D2:E2"})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("merged"), "{e}");
|
||||
assert_eq!(table_range(&s), "A1:B2");
|
||||
|
||||
let mut s = table();
|
||||
s.execute("selection.set", json!({"range": "D1:D2"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=ROW(1:2)", "array": true})).unwrap();
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("array"), "{e}");
|
||||
assert_eq!(table_range(&s), "A1:B2");
|
||||
|
||||
let mut s = table();
|
||||
s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap();
|
||||
s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D3", "filters": ["k"], "values": ["v"]})).unwrap();
|
||||
assert!(!sheet(&s).pivots.is_empty());
|
||||
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PivotTable"), "{e}");
|
||||
assert_eq!(table_range(&s), "A1:B2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_onto_a_spill_is_allowed() {
|
||||
// Excel lets a table take in a spilled formula (the spill then shows #SPILL!).
|
||||
let mut s = table();
|
||||
s.execute("cell.set", json!({"cell": "D2", "input": "=SEQUENCE(1,2)"})).unwrap();
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap();
|
||||
assert_eq!(table_range(&s), "A1:D2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_in_columns_get_excel_names_written_into_the_header_row() {
|
||||
// A resize whose new columns repeated a name left the header row and the column
|
||||
// names out of step ("Column3" in memory, "Column32" after reopening).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": "grades"})).unwrap();
|
||||
s.execute("home.formatAsTable", json!({"header": "x", "range": "I3:K9", "style": false})).unwrap();
|
||||
s.execute("table.resize", json!({"range": "K3:N7", "table": "Table1"})).unwrap();
|
||||
let ti = sheet(&s).tables.iter().position(|t| t.name == "Table1").unwrap();
|
||||
assert_eq!(names(&s, ti), headers(&s, ti));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
assert!(names(&s, ti).iter().all(|n| seen.insert(n.to_lowercase())), "{:?}", names(&s, ti));
|
||||
let bytes = gridcraft_engine::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
|
||||
let (back, _) = gridcraft_engine::io::open_bytes("t.xlsx", &bytes).unwrap();
|
||||
let t = back.active().unwrap().tables.iter().find(|t| t.name == "Table1").unwrap();
|
||||
assert_eq!(t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>(), names(&s, ti));
|
||||
|
||||
// Names Excel gives (observed): an empty header continues a ColumnN on its left, else takes
|
||||
// the lowest free ColumnN; a repeated header gets the next free suffix.
|
||||
let cases: [(&str, &[&str], &str, &[&str]); 5] = [
|
||||
("A1:B3", &["a", "b"], "A1:E3", &["a", "b", "Column1", "Column2", "Column3"]),
|
||||
("A1:C3", &["Column2", "b", "c"], "A1:F3", &["Column2", "b", "c", "Column1", "Column12", "Column13"]),
|
||||
("A1:B3", &["Column3", "b"], "A1:E3", &["Column3", "b", "Column1", "Column2", "Column22"]),
|
||||
("A1:B3", &["Column1", "b"], "A1:D3", &["Column1", "b", "Column2", "Column3"]),
|
||||
("A1:C3", &["Column1", "Column2", "Column3"], "C1:F3", &["Column3", "Column4", "Column5", "Column6"]),
|
||||
];
|
||||
for (range, row, to, want) in cases {
|
||||
let mut s = with_headers(range, row);
|
||||
s.execute("table.resize", json!({"table": "T", "range": to})).unwrap();
|
||||
assert_eq!(names(&s, 0), want.iter().map(|w| w.to_string()).collect::<Vec<_>>(), "{row:?} -> {to}");
|
||||
assert_eq!(headers(&s, 0), names(&s, 0), "{row:?} -> {to}");
|
||||
}
|
||||
|
||||
// Headers already in the new columns are kept, made unique and turned into text.
|
||||
let mut s = with_headers("A1:B3", &["x", "y"]);
|
||||
s.execute("range.setValues", json!({"range": "C1", "values": [["X", "x", 5]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F1", "input": "=1+1"})).unwrap();
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:F3"})).unwrap();
|
||||
assert_eq!(names(&s, 0), ["x", "y", "X2", "x3", "5", "2"]);
|
||||
assert_eq!(headers(&s, 0), names(&s, 0));
|
||||
assert!(sheet(&s).cell(gridcraft_core::CellRef::new(0, 5)).is_some_and(|c| c.formula.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() {
|
||||
let mut s = with_headers("A1:B3", &["a", "b"]);
|
||||
// As a file can have it: the table starts at its first data row (A2:B3), with no header row.
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
let t = &mut std::sync::Arc::make_mut(&mut wb.sheets[0]).tables[0];
|
||||
t.header_row = false;
|
||||
t.range.start.row = 1;
|
||||
}
|
||||
let r = sheet(&s).tables[0].range;
|
||||
assert!(!sheet(&s).tables[0].header_row);
|
||||
let to = gridcraft_core::RangeRef::new(r.start, gridcraft_core::CellRef::new(r.end.row, r.end.col + 1));
|
||||
let first = sheet(&s).value(r.start).display();
|
||||
s.execute("table.resize", json!({"table": "T", "range": to.a1()})).unwrap();
|
||||
assert_eq!(names(&s, 0), ["a", "b", "Column1"]);
|
||||
assert_eq!(sheet(&s).value(r.start).display(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_formula_header_is_named_by_its_value_when_formulas_show() {
|
||||
let mut s = with_headers("A1:B3", &["x", "y"]);
|
||||
s.execute("cell.set", json!({"cell": "C1", "input": "=1+1"})).unwrap();
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[0]).show_formulas = true;
|
||||
}
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
|
||||
assert_eq!(names(&s, 0), ["x", "y", "2"]);
|
||||
assert_eq!(headers(&s, 0), names(&s, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_picture_header_is_replaced_and_its_picture_removed() {
|
||||
let mut s = with_headers("A1:B3", &["x", "y"]);
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
let picture = gridcraft_engine::model::CellPicture { data: vec![1, 2, 3], mime: "image/png".into(), alt: String::new() };
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[0]).set_picture(gridcraft_core::CellRef::new(0, 2), std::sync::Arc::new(picture));
|
||||
}
|
||||
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
|
||||
assert!(!sheet(&s).cell_pictures.contains_key(&gridcraft_core::CellRef::new(0, 2)));
|
||||
assert_eq!(headers(&s, 0), names(&s, 0));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user