mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-26 21:30:19 +00:00
Compare commits
381
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e8fdbc2df | ||
|
|
088f9193a8 | ||
|
|
2f7ac98c44 | ||
|
|
89bf004226 | ||
|
|
59f6b6c14a | ||
|
|
604cdf03f0 | ||
|
|
279c530efd | ||
|
|
abee6d6926 | ||
|
|
79285118ca | ||
|
|
072493baec | ||
|
|
707091be3f | ||
|
|
3852c2335a | ||
|
|
5bc7f92680 | ||
|
|
04720627bd | ||
|
|
91f9b87070 | ||
|
|
396c794844 | ||
|
|
93e42af30d | ||
|
|
cf9a1aba48 | ||
|
|
b5386047d9 | ||
|
|
c5e735410a | ||
|
|
6f57f7f4ae | ||
|
|
6ec2bab62b | ||
|
|
eb73335d12 | ||
|
|
4b35af1609 | ||
|
|
2fbd3585af | ||
|
|
e3f897ce7e | ||
|
|
2514c099b1 | ||
|
|
34da5683a6 | ||
|
|
a5039ec907 | ||
|
|
a09a6ac3c8 | ||
|
|
f70dcc0e2e | ||
|
|
a99895c037 | ||
|
|
41b8ec1218 | ||
|
|
5fbc21b2b3 | ||
|
|
f53f8ede73 | ||
|
|
55a9a23d04 | ||
|
|
dbc919b3f7 | ||
|
|
916371a2b1 | ||
|
|
e59e03cd9e | ||
|
|
eda1871f36 | ||
|
|
501fca9eb5 | ||
|
|
23d0784b11 | ||
|
|
6842aee683 | ||
|
|
22b85c371f | ||
|
|
271ece082d | ||
|
|
cc92d8a941 | ||
|
|
c9b822b858 | ||
|
|
ceaa6c129f | ||
|
|
7c5fec1a69 | ||
|
|
3dd804da3f | ||
|
|
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 | ||
|
|
9120829df1 | ||
|
|
21df25dbed | ||
|
|
ab445c1f7b | ||
|
|
3352b90f1e | ||
|
|
b5766097e8 | ||
|
|
8cee925a0b | ||
|
|
c1bc906ee7 | ||
|
|
8f0ac5ad69 | ||
|
|
a79a50120c | ||
|
|
2bb8f32254 | ||
|
|
fa6c397a44 | ||
|
|
def333fe42 | ||
|
|
d57bbabe76 | ||
|
|
c3ff583280 | ||
|
|
0f36a7aee3 | ||
|
|
2d97c9c629 | ||
|
|
5f9b38946b | ||
|
|
014e0583b7 | ||
|
|
b876c97212 | ||
|
|
66610a7a16 | ||
|
|
628b2c99f3 | ||
|
|
37c5dbf021 | ||
|
|
00bed75921 | ||
|
|
1b95f93b30 | ||
|
|
531989a2e5 | ||
|
|
45181a217f | ||
|
|
86a7d5e0c0 | ||
|
|
4d0333367b | ||
|
|
d23654cdf0 | ||
|
|
637e7809f0 | ||
|
|
a1b96711b6 | ||
|
|
2f4b702530 | ||
|
|
fdb96edf1f | ||
|
|
06c16b3c8d | ||
|
|
9e40767a60 | ||
|
|
a730bbe78a | ||
|
|
9e1abd22a2 | ||
|
|
81daff425b | ||
|
|
ad45897ec5 | ||
|
|
93bb7443b2 | ||
|
|
cb08a89917 | ||
|
|
595a2ee0a8 | ||
|
|
f5737157a0 | ||
|
|
53fafbf5d5 | ||
|
|
f06ecfaceb | ||
|
|
0980f3aa2f | ||
|
|
06247bf36c | ||
|
|
f8892ee1c1 | ||
|
|
a87983891f | ||
|
|
f7fd68e709 | ||
|
|
7cf59c0a5a | ||
|
|
f187179552 | ||
|
|
b92f45b004 | ||
|
|
46a8525585 | ||
|
|
ce12e9f7f8 | ||
|
|
0a6e534676 | ||
|
|
187f88aa1c | ||
|
|
fc4701104c | ||
|
|
ba59c101c4 | ||
|
|
3d38b86232 | ||
|
|
4d5ff9dc6a | ||
|
|
3f6de52269 | ||
|
|
111fc70b75 | ||
|
|
cf6e4a57a8 | ||
|
|
f678a3f99c | ||
|
|
f32fefddcf | ||
|
|
35996c6e2e | ||
|
|
d56e3638fd | ||
|
|
f17f730887 | ||
|
|
a4aee78391 | ||
|
|
815627264f | ||
|
|
b98a7c43de | ||
|
|
ad7ec8d775 | ||
|
|
28086016fe | ||
|
|
8cb34cd312 | ||
|
|
82397d57ac | ||
|
|
edc9afad59 | ||
|
|
c4d0aa8773 | ||
|
|
46dc11dc9f | ||
|
|
cea63e0611 | ||
|
|
f21dc313db | ||
|
|
2a506bfc85 | ||
|
|
92b3ab1886 | ||
|
|
84e0a241b7 | ||
|
|
0afc01aa1a | ||
|
|
19b8009d2a | ||
|
|
618ad0ba74 | ||
|
|
ad380da0e9 | ||
|
|
094ce5ec8d | ||
|
|
23d2906408 | ||
|
|
30f24fd239 | ||
|
|
fe9162c9cf | ||
|
|
ee886d6db6 | ||
|
|
3b70b106ef | ||
|
|
9291c39687 | ||
|
|
8b0949f8ae | ||
|
|
5f0e1d1347 | ||
|
|
62899818be | ||
|
|
f33a2eb90a | ||
|
|
7fc0147965 | ||
|
|
5d578bef00 | ||
|
|
c3969a34c9 | ||
|
|
8fbd9ea4ab | ||
|
|
c3c7ac378d | ||
|
|
1ec173a087 | ||
|
|
d16e311b8c | ||
|
|
5c9f1b757a | ||
|
|
f0de6913d1 | ||
|
|
1baac9125c | ||
|
|
c01eb6cd2a | ||
|
|
b2cb4eb91f | ||
|
|
7a19af93dd | ||
|
|
68d54cc1b6 | ||
|
|
a8e5fdcb75 | ||
|
|
d2e97a485c | ||
|
|
ed365d9502 | ||
|
|
73037efbc5 | ||
|
|
e5c66c0c56 | ||
|
|
6856c3cfdf | ||
|
|
25715e77c3 | ||
|
|
493ceae678 | ||
|
|
b346a5fcce | ||
|
|
e1ae4d55ce | ||
|
|
2be4be9dd2 | ||
|
|
dd55a1f4ce | ||
|
|
58f4a5d6f3 | ||
|
|
a4094cc173 | ||
|
|
7b758ef1c3 | ||
|
|
e27bb51c58 | ||
|
|
c69969fbfc | ||
|
|
f81a8d84b2 | ||
|
|
5168a1c9c7 | ||
|
|
1ac75eb858 | ||
|
|
5f4f5ce4c5 | ||
|
|
1e8541d050 | ||
|
|
5aac662668 | ||
|
|
d9d9e3c628 | ||
|
|
9c5b6b2dbe | ||
|
|
6e2bf00b14 | ||
|
|
eb94d99326 | ||
|
|
a738b160db | ||
|
|
be0b6232e8 | ||
|
|
6d3c10bbf2 | ||
|
|
1f3c7a3390 | ||
|
|
5f1e609a69 | ||
|
|
e69515aff1 | ||
|
|
6c447a8082 | ||
|
|
c9e5cdbf7d | ||
|
|
6b34b6c6a8 | ||
|
|
4595d8dace | ||
|
|
9fbd95e037 | ||
|
|
0de56624d5 | ||
|
|
478e21a988 | ||
|
|
7047dca872 | ||
|
|
787b12069d | ||
|
|
1836cd83a1 | ||
|
|
ab6a4b4030 | ||
|
|
26b9dec45b | ||
|
|
743865a836 | ||
|
|
91e6a41a63 | ||
|
|
5378f80672 | ||
|
|
8893ead179 | ||
|
|
cd6fe4f8bd | ||
|
|
a276e2f21d | ||
|
|
496aa28ed3 | ||
|
|
2506ba3ddb | ||
|
|
15eef6b434 | ||
|
|
3b8daf900c | ||
|
|
2295cc71c6 | ||
|
|
2c976a6e6b | ||
|
|
4efd8fc0db | ||
|
|
40268a3c67 | ||
|
|
2c6ba8a658 | ||
|
|
1396236440 | ||
|
|
c998ff1ffb | ||
|
|
dac313337d | ||
|
|
04f8797ee4 | ||
|
|
9680794bc4 | ||
|
|
3adf662578 | ||
|
|
a6f9b80e43 | ||
|
|
4d0d3bdbfa | ||
|
|
4550a1eba7 | ||
|
|
8e81dade33 | ||
|
|
b4b89a4e36 | ||
|
|
92dcd308c2 | ||
|
|
cc3858a394 | ||
|
|
cf17534e7b | ||
|
|
7e643e2930 | ||
|
|
dbacb4cc80 | ||
|
|
7b83509a93 | ||
|
|
f3c214b2dd | ||
|
|
a2e3f265c0 | ||
|
|
10115f41ed | ||
|
|
d57d5cf267 | ||
|
|
be8efa6d0b | ||
|
|
2cdffc6282 | ||
|
|
2e1a744c6c | ||
|
|
8ec8445b5a | ||
|
|
0b31398c0d | ||
|
|
843e09fb77 | ||
|
|
f4e7a1e33f | ||
|
|
d853b05dbd | ||
|
|
73d36eef04 | ||
|
|
7a3f75d7c3 | ||
|
|
db21e558d1 | ||
|
|
8211e218ce | ||
|
|
f300a41236 | ||
|
|
f4049f9e49 | ||
|
|
5c987d1eae | ||
|
|
f0397d5f5b | ||
|
|
19bc9660ff | ||
|
|
b7547111f3 | ||
|
|
a19b16f211 | ||
|
|
1fcaffe7b7 | ||
|
|
a7a708d0f6 | ||
|
|
2fbe96820c | ||
|
|
9bbcb7ce90 | ||
|
|
7155ced916 | ||
|
|
571bdf68ad | ||
|
|
c4920c463b | ||
|
|
0ddd8684ef | ||
|
|
15661dc973 | ||
|
|
1053b66a0e | ||
|
|
b023410ca4 | ||
|
|
dacff8ff97 | ||
|
|
260b84d093 | ||
|
|
9bd604aa12 | ||
|
|
cfcde5bfbd | ||
|
|
2f86b52706 | ||
|
|
e3fa42607f | ||
|
|
4b86dc9dc9 | ||
|
|
1fe4f79db6 | ||
|
|
1e3fc9ee37 | ||
|
|
f7380202fe | ||
|
|
4fa40fb932 | ||
|
|
6f63c784bc | ||
|
|
d5b23a5e79 | ||
|
|
18f11876e3 | ||
|
|
a5b1415c9e | ||
|
|
ce64da3286 | ||
|
|
87f9c4b12d | ||
|
|
ceca4b151e | ||
|
|
70fb318377 | ||
|
|
14c81bfdd6 | ||
|
|
5a035ac5c6 | ||
|
|
81a8abc12b | ||
|
|
8b17f1e779 | ||
|
|
6cfd7d83aa | ||
|
|
a327501fb1 | ||
|
|
516b19c151 | ||
|
|
fded60a325 | ||
|
|
c693db2b9f | ||
|
|
38fa0dc050 | ||
|
|
ae50127952 | ||
|
|
95c0800c22 | ||
|
|
707ce9e14c | ||
|
|
b97c27f2b3 | ||
|
|
2d65676f5d | ||
|
|
79324b6c17 | ||
|
|
d2506c03d9 | ||
|
|
214ad97372 | ||
|
|
46bdd416bb | ||
|
|
3d923f3b30 | ||
|
|
937634a31a | ||
|
|
591b97aede | ||
|
|
5e0fe2d28d | ||
|
|
fb38290e45 | ||
|
|
b107dedf7e | ||
|
|
9b7c5ca1f6 | ||
|
|
ec77c810f8 | ||
|
|
8471ccace5 | ||
|
|
bf9531954d | ||
|
|
41a1a3f8bc | ||
|
|
10c023754e | ||
|
|
fa17a79cba | ||
|
|
154273a7d8 | ||
|
|
c4ef580a22 | ||
|
|
17aae2da04 | ||
|
|
a4309846b2 | ||
|
|
fd6d6cee88 | ||
|
|
852b1a4bfb | ||
|
|
a6bedd5153 | ||
|
|
1d0360153f | ||
|
|
df2b24dbfd | ||
|
|
db2fffa9be | ||
|
|
81e523e431 | ||
|
|
6ce1ce9c6d | ||
|
|
9b594efc67 | ||
|
|
f30c206a05 | ||
|
|
744c6cde44 | ||
|
|
f3a7c72bb6 | ||
|
|
c0ae95f721 | ||
|
|
cdb3c163ec | ||
|
|
5a72aff0c5 | ||
|
|
43ccb39ba3 | ||
|
|
e24a8631b4 | ||
|
|
8d90b1ea03 | ||
|
|
f066fe994e | ||
|
|
8732325b58 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408285582,
|
||||
"producer_workflow_id": 429713469,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "6bde9f8b9ba76635d00f6369d58313d1269b4191",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191",
|
||||
"producer_tooling_revision": "3dee18226ed28134896f69fb8b280fff9247ec7f",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@3dee18226ed28134896f69fb8b280fff9247ec7f",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "6bde9f8b9ba76635d00f6369d58313d1269b4191",
|
||||
"signer_tooling_revision": "3dee18226ed28134896f69fb8b280fff9247ec7f",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
with:
|
||||
tooling-revision: 6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
tooling-revision: 3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
app-name: gridcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
@@ -50,6 +50,8 @@ 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@6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
with:
|
||||
tooling-revision: 6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
tooling-revision: 3dee18226ed28134896f69fb8b280fff9247ec7f
|
||||
app-name: gridcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
Generated
+1
@@ -2987,6 +2987,7 @@ dependencies = [
|
||||
"gridcraft-math",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -67,6 +67,8 @@ regex = { version = "1", default-features = false, features = ["std", "unicode",
|
||||
quick-xml = "0.41"
|
||||
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
|
||||
|
||||
+22
-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,11 +152,14 @@ 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 |
|
||||
@@ -167,6 +171,8 @@ 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: 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) |
|
||||
@@ -186,15 +192,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 |
|
||||
@@ -285,6 +296,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 |
|
||||
@@ -300,13 +312,16 @@ 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 | 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) |
|
||||
@@ -319,15 +334,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> {
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2762,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,12 @@ 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)
|
||||
}
|
||||
|
||||
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
|
||||
@@ -156,7 +163,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 +194,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 +223,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);
|
||||
@@ -424,7 +431,7 @@ 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));
|
||||
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);
|
||||
|
||||
@@ -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,
|
||||
@@ -1491,6 +1493,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", "", ""];
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -501,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::*;
|
||||
@@ -584,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);
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -23,9 +23,9 @@ mod sort;
|
||||
mod tools;
|
||||
mod validation;
|
||||
|
||||
pub use filter::filter_values;
|
||||
pub(crate) use filter::{apply_filter, grow_autofilter};
|
||||
use filter::{clear_filter, filter_by, reapply, toggle_filter};
|
||||
pub use filter::{filter_selection, filter_values};
|
||||
use grouping::{detail, group, outline_settings, show_levels, subtotal};
|
||||
pub use sort::sort_context;
|
||||
use sort::{quick_sort, sort};
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use super::sort::sort_key;
|
||||
use super::{
|
||||
AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param,
|
||||
current_region, data_target, edit, json,
|
||||
data_target, edit, json,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
// ---------------------------------------------------------------- filter
|
||||
|
||||
@@ -14,14 +15,63 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let has = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.autofilter.is_some());
|
||||
let in_table = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.table_at(at).map(|t| t.name.clone()));
|
||||
if let Some(name) = in_table {
|
||||
// An explicit range over part of the table is refused, as when installing a filter on it.
|
||||
if p.get("range").is_some()
|
||||
&& let Some(sh) = s.doc()?.wb.sheet(sheet)
|
||||
&& let Some(t) = sh.tables.iter().find(|t| t.name == name)
|
||||
&& t.range.intersects(&r)
|
||||
&& !(t.header_row
|
||||
&& t.range.start.row == r.start.row
|
||||
&& t.range.contains(r.start)
|
||||
&& t.range.contains(r.end)
|
||||
&& r.start.col == t.range.start.col
|
||||
&& r.end.col == t.range.end.col
|
||||
&& t.data_range().is_none_or(|data| r.end.row >= data.end.row))
|
||||
{
|
||||
return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead"));
|
||||
}
|
||||
return edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let filtered: Vec<u32> = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect();
|
||||
let mut cleared = false;
|
||||
if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) {
|
||||
t.filter_button = !t.filter_button;
|
||||
if !t.filter_button {
|
||||
t.filter.clear();
|
||||
// The sheet AutoFilter hosted on this table's header row is the table's filter too.
|
||||
cleared = sh.autofilter.as_ref().is_some_and(|af| af.range.start.row == t.range.start.row && af.range.intersects(&t.range));
|
||||
}
|
||||
}
|
||||
if cleared {
|
||||
sh.autofilter = None;
|
||||
for r in filtered {
|
||||
if let Some(info) = sh.rows.get_mut(&r) {
|
||||
info.hidden = false;
|
||||
}
|
||||
}
|
||||
// Rows another table's criteria hide stay hidden: evaluate each such table's saved
|
||||
// criteria through the live filter, then hide the union once (a later table would
|
||||
// unhide what an earlier one excluded) and take the filter off again.
|
||||
let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> =
|
||||
sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect();
|
||||
let mut excluded: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
for (range, criteria) in others {
|
||||
if let Some(sh) = cx.wb.sheet_mut(sheet) {
|
||||
sh.autofilter = Some(AutoFilter { range, criteria });
|
||||
}
|
||||
apply_filter(&mut cx.wb, sheet);
|
||||
if let Some(sh) = cx.wb.sheet(sheet) {
|
||||
excluded.extend((range.start.row.saturating_add(1)..=range.end.row).filter(|r| sh.is_row_hidden(*r)));
|
||||
}
|
||||
}
|
||||
if let Some(sh) = cx.wb.sheet_mut(sheet) {
|
||||
sh.autofilter = None;
|
||||
for r in excluded {
|
||||
sh.rows.entry(r).or_default().hidden = true;
|
||||
}
|
||||
}
|
||||
cx.structural = true;
|
||||
}
|
||||
Ok(Json::Null)
|
||||
});
|
||||
}
|
||||
@@ -44,19 +94,58 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
/// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection.
|
||||
///
|
||||
/// A sheet AutoFilter never overlaps a table, because a file can't hold one (Excel refuses
|
||||
/// `Range("A1:C8").AutoFilter` over part of a table, and from a cell outside a table it leaves the
|
||||
/// table's cells out of the region). Inside a table the filter covers the table from its header
|
||||
/// row, which is saved as the table's own filter, and takes over the criteria the table already
|
||||
/// had so there is one filter to save.
|
||||
fn install_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (sheet, mut r) = data_target(s, p, "data.filter")?;
|
||||
// A selected header row filters the data below it (#201).
|
||||
if p.get("range").is_none() && r.height() == 1 {
|
||||
{
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let below = current_region(sh, r.start).end.row;
|
||||
if below > r.end.row {
|
||||
r = RangeRef::new(r.start, CellRef::new(below, r.end.col));
|
||||
if p.get("range").is_none() && sh.table_at(d.selection.active).is_none() && d.selection.current().is_single() {
|
||||
r = crate::selection::current_region_outside_tables(sh, d.selection.active);
|
||||
}
|
||||
// A selected header row filters the data below it (#201).
|
||||
if p.get("range").is_none() && r.height() == 1 {
|
||||
let region = match sh.table_at(r.start) {
|
||||
Some(t) => t.data_range().map(|dr| RangeRef::new(t.range.start, dr.end)).unwrap_or(t.range),
|
||||
None => crate::selection::current_region_outside_tables(sh, r.start),
|
||||
};
|
||||
if region.end.row > r.end.row {
|
||||
r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) };
|
||||
// The table whose header row the filter starts on, when it lies inside that table.
|
||||
let host =
|
||||
sh.tables.iter().position(|t| t.header_row && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end));
|
||||
if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) {
|
||||
return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead"));
|
||||
}
|
||||
// A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them.
|
||||
if let Some(t) = host.and_then(|i| sh.tables.get(i)) {
|
||||
if t.data_range().is_some_and(|data| r.end.row < data.end.row) {
|
||||
return Err(bad("data.filter", "filter the table's full data range"));
|
||||
}
|
||||
let shift = r.start.col.saturating_sub(t.range.start.col);
|
||||
if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) {
|
||||
return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width"));
|
||||
}
|
||||
}
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] });
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let mut criteria = vec![];
|
||||
if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) {
|
||||
// The criteria are saved with the table only while its filter buttons are on.
|
||||
t.filter_button = true;
|
||||
let shift = r.start.col.saturating_sub(t.range.start.col);
|
||||
criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect();
|
||||
}
|
||||
sh.autofilter = Some(AutoFilter { range: r, criteria });
|
||||
Ok(json!({"filter": true, "range": r.a1()}))
|
||||
})
|
||||
}
|
||||
@@ -181,19 +270,18 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hides rows of the autofilter range that fail any criterion.
|
||||
pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
let Some(sh) = wb.sheet(sheet) else { return };
|
||||
let Some(af) = sh.autofilter.clone() else { return };
|
||||
// An imported range can name rows past the grid; none of those exist to hide.
|
||||
let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col));
|
||||
let mut hide = Vec::new();
|
||||
/// Statistics use the original range within the grid, regardless of the other active criteria.
|
||||
fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap<usize, (Option<f64>, f64)> {
|
||||
let r = af.range;
|
||||
// Precompute per-criterion top10 threshold and average once, not per row.
|
||||
let mut col_stats: std::collections::HashMap<usize, (Option<f64>, f64)> = std::collections::HashMap::new();
|
||||
let mut col_stats = HashMap::new();
|
||||
for (i, (off, c)) in af.criteria.iter().enumerate() {
|
||||
if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) {
|
||||
let col = r.start.col + off;
|
||||
let mut nums: Vec<f64> = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect();
|
||||
let Some(col) = r.start.col.checked_add(*off) else { continue };
|
||||
// Keep main's imported-range bound after extracting statistics from apply_filter.
|
||||
let mut nums: Vec<f64> = (r.start.row.saturating_add(1)..=r.end.row.min(gridcraft_core::MAX_ROWS - 1))
|
||||
.filter_map(|row| sh.value(CellRef::new(row, col)).as_f64())
|
||||
.collect();
|
||||
let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::<f64>() / nums.len() as f64 };
|
||||
let thr = match c {
|
||||
FilterCriterion::Top10 { bottom, percent, count } => {
|
||||
@@ -207,59 +295,97 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
col_stats.insert(i, (thr, avg));
|
||||
}
|
||||
}
|
||||
for row in r.start.row + 1..=r.end.row {
|
||||
let mut visible = true;
|
||||
for (i, (off, crit)) in af.criteria.iter().enumerate() {
|
||||
let c = CellRef::new(row, r.start.col + off);
|
||||
let v = sh.value(c);
|
||||
let text = crate::display::cell_text(wb, sh, c);
|
||||
let ok = match crit {
|
||||
FilterCriterion::Values { values, blanks } => {
|
||||
if filter_blank(&v) {
|
||||
*blanks
|
||||
} else {
|
||||
values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display()))
|
||||
}
|
||||
}
|
||||
FilterCriterion::Custom { a, b, and } => {
|
||||
let x = custom_ok(&v, &text, &a.0, &a.1);
|
||||
match b {
|
||||
Some(b) => {
|
||||
let y = custom_ok(&v, &text, &b.0, &b.1);
|
||||
if *and { x && y } else { x || y }
|
||||
}
|
||||
None => x,
|
||||
}
|
||||
}
|
||||
FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) {
|
||||
(Some(n), Some((thr, _))) => {
|
||||
let thr = thr.unwrap_or(n);
|
||||
if *bottom { n <= thr } else { n >= thr }
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) {
|
||||
(Some(n), Some((_, avg))) => {
|
||||
if *above {
|
||||
n > *avg
|
||||
} else {
|
||||
n < *avg
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col,
|
||||
FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col,
|
||||
// Icons are not evaluated here: the row keeps its current visibility.
|
||||
FilterCriterion::Icon { .. } => !sh.is_row_hidden(row),
|
||||
};
|
||||
if !ok {
|
||||
visible = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
hide.push((row, !visible));
|
||||
col_stats
|
||||
}
|
||||
|
||||
/// Shared row and checkbox matching, with thresholds and Values lookups prepared once per query.
|
||||
struct FilterMatcher<'a> {
|
||||
wb: &'a Workbook,
|
||||
sh: &'a Sheet,
|
||||
af: &'a AutoFilter,
|
||||
stats: HashMap<usize, (Option<f64>, f64)>,
|
||||
values: HashMap<usize, HashSet<String>>,
|
||||
}
|
||||
|
||||
impl<'a> FilterMatcher<'a> {
|
||||
fn new(wb: &'a Workbook, sh: &'a Sheet, af: &'a AutoFilter) -> Self {
|
||||
let values = af
|
||||
.criteria
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, (_, crit))| match crit {
|
||||
FilterCriterion::Values { values, .. } => Some((i, values.iter().map(|v| v.to_ascii_lowercase()).collect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Self { wb, sh, af, stats: filter_stats(sh, af), values }
|
||||
}
|
||||
|
||||
fn row_matches(&self, row: u32, excluded_offset: Option<u32>) -> bool {
|
||||
self.af.criteria.iter().enumerate().all(|(i, (off, crit))| Some(*off) == excluded_offset || self.criterion_matches(row, i, *off, crit))
|
||||
}
|
||||
|
||||
fn criterion_matches(&self, row: u32, i: usize, off: u32, crit: &FilterCriterion) -> bool {
|
||||
let Some(col) = self.af.range.start.col.checked_add(off) else { return true };
|
||||
let c = CellRef::new(row, col);
|
||||
let v = self.sh.value(c);
|
||||
let text = crate::display::cell_text(self.wb, self.sh, c);
|
||||
match crit {
|
||||
FilterCriterion::Values { blanks, .. } => {
|
||||
if filter_blank(&v) {
|
||||
*blanks
|
||||
} else {
|
||||
self.values
|
||||
.get(&i)
|
||||
.is_some_and(|values| values.contains(&text.to_ascii_lowercase()) || values.contains(&v.display().to_ascii_lowercase()))
|
||||
}
|
||||
}
|
||||
FilterCriterion::Custom { a, b, and } => {
|
||||
let x = custom_ok(&v, &text, &a.0, &a.1);
|
||||
match b {
|
||||
Some(b) => {
|
||||
let y = custom_ok(&v, &text, &b.0, &b.1);
|
||||
if *and { x && y } else { x || y }
|
||||
}
|
||||
None => x,
|
||||
}
|
||||
}
|
||||
FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), self.stats.get(&i)) {
|
||||
(Some(n), Some((thr, _))) => {
|
||||
let thr = thr.unwrap_or(n);
|
||||
if *bottom { n <= thr } else { n >= thr }
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) {
|
||||
(Some(n), Some((_, avg))) => {
|
||||
if *above {
|
||||
n > *avg
|
||||
} else {
|
||||
n < *avg
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
FilterCriterion::FillColor(col) => self.wb.styles.get(self.sh.style_id(c)).fill.fg == *col,
|
||||
FilterCriterion::FontColor(col) => self.wb.styles.get(self.sh.style_id(c)).font.color == *col,
|
||||
// Icon criteria are retained from files but cannot be evaluated yet.
|
||||
FilterCriterion::Icon { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hides rows of the autofilter range that fail any criterion.
|
||||
pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
let Some(sh) = wb.sheet(sheet) else { return };
|
||||
let Some(af) = sh.autofilter.clone() else { return };
|
||||
// An imported range can name rows past the grid; none of those exist to hide.
|
||||
let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col));
|
||||
let matcher = FilterMatcher::new(wb, sh, &af);
|
||||
// Reapplying a retained icon filter preserves visibility until icons can be evaluated.
|
||||
let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. }));
|
||||
let hide: Vec<_> =
|
||||
(r.start.row + 1..=r.end.row).map(|row| (row, !matcher.row_matches(row, None) || (has_icon && sh.is_row_hidden(row)))).collect();
|
||||
let Some(shm) = wb.sheet_mut(sheet) else { return };
|
||||
for (row, h) in hide {
|
||||
if h {
|
||||
@@ -294,30 +420,52 @@ pub(super) fn reapply(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Distinct display values of a filter column (for the dropdown list).
|
||||
/// Distinct display values from rows matching the other columns' criteria.
|
||||
/// The current criterion only determines checkboxes, so its unchecked alternatives stay available.
|
||||
pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> {
|
||||
column_filter_values(wb, sheet, col, true)
|
||||
}
|
||||
|
||||
/// Applies edited eligible choices to the whole column's checkbox state, retaining choices hidden by other filters.
|
||||
pub fn filter_selection(wb: &Workbook, sheet: usize, col: u32, choices: &[(String, bool)]) -> Vec<(String, bool)> {
|
||||
let mut edited = std::collections::BTreeMap::new();
|
||||
for (value, on) in choices {
|
||||
*edited.entry(value.to_ascii_lowercase()).or_insert(false) |= *on;
|
||||
}
|
||||
let mut selection = column_filter_values(wb, sheet, col, false);
|
||||
for (value, on) in &mut selection {
|
||||
if let Some(checked) = edited.get(&value.to_ascii_lowercase()) {
|
||||
*on = *checked;
|
||||
}
|
||||
}
|
||||
selection
|
||||
}
|
||||
|
||||
fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bool) -> Vec<(String, bool)> {
|
||||
let Some(sh) = wb.sheet(sheet) else { return vec![] };
|
||||
let Some(af) = &sh.autofilter else { return vec![] };
|
||||
let off = col.saturating_sub(af.range.start.col);
|
||||
let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c);
|
||||
if col < af.range.start.col || col > af.range.end.col {
|
||||
return vec![];
|
||||
}
|
||||
let off = col - af.range.start.col;
|
||||
let selected = af.criteria.iter().enumerate().find(|(_, (o, _))| *o == off);
|
||||
let matcher = FilterMatcher::new(wb, sh, af);
|
||||
let mut seen = std::collections::BTreeMap::new();
|
||||
for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) {
|
||||
// Imported end rows cannot add choices beyond the grid either.
|
||||
for row in
|
||||
af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)).min(gridcraft_core::MAX_ROWS - 1)
|
||||
{
|
||||
if eligible_only && !matcher.row_matches(row, Some(off)) {
|
||||
continue;
|
||||
}
|
||||
let c = CellRef::new(row, col);
|
||||
let v = sh.value(c);
|
||||
let blank = filter_blank(&v);
|
||||
let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) };
|
||||
let on = match selected {
|
||||
Some(FilterCriterion::Values { values, blanks }) => {
|
||||
if blank {
|
||||
*blanks
|
||||
} else {
|
||||
values.iter().any(|x| x.eq_ignore_ascii_case(&t))
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit));
|
||||
let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) };
|
||||
seen.entry((key, t)).or_insert(on);
|
||||
// One choice can represent rows with different colors; keep any matching row checked.
|
||||
*seen.entry((key, t)).or_insert(false) |= on;
|
||||
}
|
||||
let mut values: Vec<_> = seen.into_iter().collect();
|
||||
values.sort_by(|((a, ta), _), ((b, tb), _)| {
|
||||
|
||||
@@ -27,7 +27,7 @@ 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) {
|
||||
@@ -71,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()
|
||||
@@ -317,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)?,
|
||||
|
||||
@@ -421,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);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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")) {
|
||||
|
||||
@@ -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,20 @@ 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() {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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]"));
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
@@ -324,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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -364,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::*;
|
||||
|
||||
@@ -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)));
|
||||
|
||||
+169
-5
@@ -962,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"));
|
||||
}
|
||||
|
||||
@@ -2164,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());
|
||||
@@ -5589,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";
|
||||
@@ -8101,6 +8172,99 @@ fn history_charges_the_storage_of_empty_comment_replies() {
|
||||
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.
|
||||
|
||||
@@ -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,427 @@
|
||||
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();
|
||||
assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".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 }), (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 })]);
|
||||
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 })];
|
||||
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_ascii_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 selected"),
|
||||
(5_002, Value::Text("ä".into()), "unicode excluded"),
|
||||
(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 })],
|
||||
});
|
||||
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 selected".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]);
|
||||
}
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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;
|
||||
@@ -31,6 +33,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));
|
||||
}
|
||||
|
||||
@@ -33,6 +33,98 @@ fn tvm() {
|
||||
is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num);
|
||||
}
|
||||
|
||||
/// XIRR of `values` on `dates`, with an optional guess, as a number or an error.
|
||||
fn xirr_of(values: &[f64], dates: &[f64], guess: Option<f64>) -> Value {
|
||||
let mut args = vec![rf(col(values)), rf(col(dates))];
|
||||
args.extend(guess.map(n));
|
||||
ev("XIRR", args)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn xirr_is(values: &[f64], dates: &[f64], guess: Option<f64>, expected: f64) {
|
||||
assert_eq!(xirr_of(values, dates, guess), Value::Number(expected), "XIRR{values:?} {dates:?} {guess:?}");
|
||||
}
|
||||
|
||||
fn irr_of(values: &[f64], guess: Option<f64>) -> Value {
|
||||
let mut args = vec![rf(col(values))];
|
||||
args.extend(guess.map(n));
|
||||
ev("IRR", args)
|
||||
}
|
||||
|
||||
/// Expected values observed in Excel 365 with these synthetic inputs. XIRR matches bit for
|
||||
/// bit: its answer is a bisection midpoint, about 1e-8 from the exact root.
|
||||
#[test]
|
||||
fn xirr_follows_excel_bisection() {
|
||||
let (b, y1, y2) = (43831.0, 44196.0, 44561.0);
|
||||
// Root 10%: the bracket and so the answer depend on the guess, not on the flows.
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], None, 0.099_999_994_039_535_52);
|
||||
xirr_is(&[-100.0, 121.0], &[b, y2], None, 0.099_999_994_039_535_52);
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.0), 0.099_999_995_117_187_5);
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.25), 0.099_999_997_764_825_82);
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], Some(5.0), 0.100_000_002_421_438_7);
|
||||
xirr_is(&[-100.0, 60.0, 60.0], &[b, y1, y2], None, 0.130_662_387_609_481_82);
|
||||
xirr_is(&[-100.0, 150.0], &[b, y1], None, 0.499_999_994_039_535_54);
|
||||
// Fractional dates are truncated.
|
||||
xirr_is(&[-100.0, 60.0, 60.0], &[b, y1 + 0.9, y2 + 0.2], None, 0.130_662_387_609_481_82);
|
||||
// Negative roots: minus the guess, then halfway to -100% each step.
|
||||
xirr_is(&[-100.0, 73.0], &[b, y1], None, -0.269_999_996_572_733);
|
||||
xirr_is(&[-100.0, 13.0], &[b, y1], None, -0.870_000_001_043_081_1);
|
||||
xirr_is(&[-100.0, 1e-29], &[b, 45658.0], None, -0.999_999_359_104_708);
|
||||
// A guess of 100% or more steps through rates below -100% (whole years only).
|
||||
xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(2.0), -1.653_112_880_885_601);
|
||||
xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(-0.3), -0.846_887_112_781_405_5);
|
||||
is_err(xirr_of(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(1.0)), CellError::Num);
|
||||
// One-day spans.
|
||||
xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23);
|
||||
xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34);
|
||||
xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5);
|
||||
// A leading zero cash flow scales the residual to 0: Excel halves the guess to a tiny
|
||||
// number whatever the flows (observed), and a negative guess is #NUM!.
|
||||
let z = [0.0, -100.0, 110.0];
|
||||
let zd = [b, y1, y2];
|
||||
xirr_is(&z, &zd, None, 2.980_232_238_769_531_4e-9);
|
||||
xirr_is(&z, &zd, Some(0.2), 2.980_232_238_769_531_4e-9);
|
||||
xirr_is(&z, &zd, Some(0.0), 4.882_812_5e-9);
|
||||
xirr_is(&z, &zd, Some(5.0), 4.656_612_873_077_392_6e-9);
|
||||
xirr_is(&[0.0, -100.0, 50.0], &zd, None, 2.980_232_238_769_531_4e-9);
|
||||
is_err(xirr_of(&z, &zd, Some(-0.5)), CellError::Num);
|
||||
// Dates before the first are allowed (time runs from the first date); in the second
|
||||
// case the search finds no sign change.
|
||||
xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6);
|
||||
is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b - 365.0, y2], None), CellError::Num);
|
||||
// A negative guess never reaches a positive root; a guess at or below -1 is #NUM!.
|
||||
is_err(xirr_of(&[-100.0, 110.0], &[b, y1], Some(-0.1)), CellError::Num);
|
||||
is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, y1, y2], Some(-1.0)), CellError::Num);
|
||||
// Two roots with the guess outside them; all dates the same.
|
||||
is_err(xirr_of(&[-100.0, 300.0, -210.0], &[b, y1, y2], None), CellError::Num);
|
||||
is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b, b], None), CellError::Num);
|
||||
}
|
||||
|
||||
/// IRR follows Excel's answers to about 1e-12 and its #NUM! cases.
|
||||
#[test]
|
||||
fn irr_follows_excel() {
|
||||
assert_eq!(irr_of(&[-100.0, 110.0], None), Value::Number(0.100_000_000_000_000_09));
|
||||
close_tol(irr_of(&[-0.0001, 0.0, 0.0, 0.0, 100.0], None), 30.622_776_600_497_09, 1e-9);
|
||||
let mut late = vec![-100.0];
|
||||
late.extend([0.0; 19]);
|
||||
late.push(1e-5);
|
||||
is_err(irr_of(&late, None), CellError::Num);
|
||||
// ...but from a guess just above -100% Newton creeps down to the root.
|
||||
let mut late18 = vec![-100.0];
|
||||
late18.extend([0.0; 18]);
|
||||
late18.push(1e-5);
|
||||
close_tol(irr_of(&late18, Some(-0.99)), -0.571_866_760_128_087_4, 1e-9);
|
||||
close_tol(irr_of(&[-100.0, 300.0, -210.0], Some(0.9)), 0.887_298_334_620_741_5, 1e-12);
|
||||
is_err(irr_of(&[-100.0, 60.0, 60.0], Some(-1.0)), CellError::Value);
|
||||
close_tol(irr_of(&[-100.0, 60.0, 60.0], Some(-0.999_999)), 0.130_662_386_291_807_5, 1e-12);
|
||||
// A small Newton step alone is not convergence when cancellation leaves a large scaled residual.
|
||||
close_tol(irr_of(&[-1e-9, 1.0, -1e8], None), 112_701_664.379_258_29, 1e-8);
|
||||
// An exact repeated root at the starting guess (zero slope) is the answer, as in Excel.
|
||||
assert_eq!(irr_of(&[1.0, -2.0, 1.0], Some(0.0)), Value::Number(0.0));
|
||||
assert_eq!(irr_of(&[-1.0, 3.0, -3.0, 1.0], Some(0.0)), Value::Number(0.0));
|
||||
close_tol(irr_of(&[1.0, -2.0, 1.0], None), 1.09e-7, 1e-7);
|
||||
}
|
||||
|
||||
/// RATE with the given arguments, as a number or an error.
|
||||
fn rate_of(args: &[f64]) -> Value {
|
||||
ev("RATE", args.iter().map(|x| n(*x)).collect())
|
||||
@@ -145,6 +237,42 @@ fn pmt_edge_cases_follow_excel() {
|
||||
close_tol(ev("PMT", vec![n(0.05), n(10.0), n(100.0), n(50.0), n(1.0)]), -16.119701185541427, 1e-15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_cash_flows_follow_excel_for_xirr_and_xnpv() {
|
||||
// Each result below was observed in Excel on a synthetic workbook: five rows, the first
|
||||
// four -10000, 2750, 4250, 3250 on 39448, 39508, 39751, 39859; the last row varies.
|
||||
let dates = col(&[39448.0, 39508.0, 39751.0, 39859.0, 39904.0]);
|
||||
let gap = arr([39448.0, 39508.0, 39751.0, 39859.0].iter().map(|x| vec![nv(*x)]).chain([vec![Value::Empty]]).collect());
|
||||
let flows = |last: Value| arr([-10000.0, 2750.0, 4250.0, 3250.0].iter().map(|x| vec![nv(*x)]).chain([vec![last]]).collect());
|
||||
let rate = 0.033791377645041754;
|
||||
// XIRR: a blank value counts as 0 and a blank date is ignored when its value is blank or 0. The answer is a bisection midpoint, within about 1e-8 of the exact rate.
|
||||
close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(dates.clone())]), rate, 1e-7);
|
||||
close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(dates.clone())]), rate, 1e-7);
|
||||
close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(gap.clone())]), rate, 1e-7);
|
||||
close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(gap.clone())]), rate, 1e-7);
|
||||
is_err(ev("XIRR", vec![rf(flows(nv(2750.0))), rf(gap.clone())]), CellError::Num);
|
||||
is_err(ev("XIRR", vec![rf(flows(tv("-"))), rf(dates.clone())]), CellError::Value);
|
||||
// XNPV is strict: a blank value is #NUM! where 0 is a number.
|
||||
close_tol(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(dates.clone())]), -382.66, 1e-2);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates.clone())]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(tv("-"))), rf(dates.clone())]), CellError::Num);
|
||||
// In the first row a blank value or date is #VALUE! for XNPV; XIRR reads a blank date there as day 0.
|
||||
let first_row = |value: Value, date: Value| {
|
||||
let cells = |x: Value, rest: [f64; 4]| arr(std::iter::once(vec![x]).chain(rest.iter().map(|y| vec![nv(*y)])).collect());
|
||||
(rf(cells(value, [2750.0, 4250.0, 3250.0, 500.0])), rf(cells(date, [39508.0, 39751.0, 39859.0, 39904.0])))
|
||||
};
|
||||
let (v0, d0) = first_row(Value::Empty, nv(39448.0));
|
||||
is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value);
|
||||
let (v0, d0) = first_row(nv(0.0), Value::Empty);
|
||||
is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value);
|
||||
let (v0, d0) = first_row(nv(-10000.0), Value::Empty);
|
||||
is_err(ev("XNPV", vec![n(0.09), v0.clone(), d0.clone()]), CellError::Value);
|
||||
close_tol(ev("XIRR", vec![v0, d0]), 0.000_664_654_374_122_619_6, 1e-7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cash_flows() {
|
||||
close_tol(ev("NPV", vec![n(0.1), n(-10000.0), n(3000.0), n(4200.0), n(6800.0)]), 1188.443412, 1e-9);
|
||||
|
||||
@@ -152,72 +152,6 @@ pub(super) fn cumprinc(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
cumulative(a, true)
|
||||
}
|
||||
|
||||
/// Newton iteration with a numeric derivative, keeping the rate above -1.
|
||||
fn newton(f: impl Fn(f64) -> f64, guess: f64) -> Option<f64> {
|
||||
let mut x = guess;
|
||||
for _ in 0..200 {
|
||||
let y = f(x);
|
||||
if !y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let h = 1e-6 * x.abs().max(1e-3);
|
||||
let d = (f(x + h) - f(x - h)) / (2.0 * h);
|
||||
if d == 0.0 || !d.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let mut nx = x - y / d;
|
||||
if nx <= -1.0 {
|
||||
nx = (x - 1.0) / 2.0;
|
||||
if nx <= -1.0 {
|
||||
nx = -0.999_999_999;
|
||||
}
|
||||
}
|
||||
if (nx - x).abs() < 1e-12 * nx.abs().max(1.0) {
|
||||
return Some(nx);
|
||||
}
|
||||
x = nx;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Tries Newton from the guess and a few fallback starting points; then bisection over a
|
||||
/// bracket if one can be found.
|
||||
fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R<f64> {
|
||||
let check = |r: f64| f(r).is_finite() && f(r).abs() < 1e-7 * (1.0 + f(guess).abs().min(1e12));
|
||||
for g in [guess, 0.1, 0.01, 0.5, -0.5, 1.0, 0.001, 5.0, -0.9, 10.0] {
|
||||
if let Some(r) = newton(&f, g)
|
||||
&& r > -1.0
|
||||
&& check(r)
|
||||
{
|
||||
return Ok(r);
|
||||
}
|
||||
}
|
||||
// Scan for a sign change and bisect.
|
||||
let grid: Vec<f64> = [-0.999_999, -0.99, -0.9, -0.5, -0.2, 0.0, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0, 1000.0].to_vec();
|
||||
for w in grid.windows(2) {
|
||||
let (mut lo, mut hi) = match w {
|
||||
[a, b] => (*a, *b),
|
||||
_ => continue,
|
||||
};
|
||||
let (flo, fhi) = (f(lo), f(hi));
|
||||
if !(flo.is_finite() && fhi.is_finite()) || flo * fhi > 0.0 {
|
||||
continue;
|
||||
}
|
||||
let lo_neg = flo < 0.0;
|
||||
for _ in 0..200 {
|
||||
let mid = 0.5 * (lo + hi);
|
||||
let fm = f(mid);
|
||||
if (fm < 0.0) == lo_neg {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return Ok(0.5 * (lo + hi));
|
||||
}
|
||||
Err(CellError::Num)
|
||||
}
|
||||
|
||||
/// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus
|
||||
/// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to
|
||||
/// judge how close to zero the first can get in floating point.
|
||||
@@ -314,8 +248,15 @@ pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
num_val(sum)
|
||||
}
|
||||
|
||||
/// Values and dates for XNPV/XIRR: both must be numeric and of equal length.
|
||||
fn dated_flows(values: &Value, dates: &Value) -> R<(Vec<f64>, Vec<f64>)> {
|
||||
/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. XNPV rejects a
|
||||
/// date before the first; XIRR (`lenient`) takes it, as Excel does.
|
||||
///
|
||||
/// Blank cells follow what Excel returns (observed on synthetic workbooks). With `lenient` (XIRR)
|
||||
/// a blank value counts as 0 and a blank date is ignored when its value is blank or 0; a nonzero
|
||||
/// value without a date is `#NUM!`, except in the first row, where the date is read as day 0.
|
||||
/// XNPV is strict: a blank (or text) value or a blank date is `#NUM!`, except in the first row,
|
||||
/// where it is `#VALUE!`.
|
||||
fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec<f64>, Vec<f64>)> {
|
||||
let va = as_array(values);
|
||||
let da = as_array(dates);
|
||||
if va.data.len() != da.data.len() {
|
||||
@@ -323,21 +264,33 @@ fn dated_flows(values: &Value, dates: &Value) -> R<(Vec<f64>, Vec<f64>)> {
|
||||
}
|
||||
let mut v = Vec::with_capacity(va.data.len());
|
||||
let mut d = Vec::with_capacity(da.data.len());
|
||||
for (x, y) in va.data.iter().zip(da.data.iter()) {
|
||||
match x {
|
||||
Value::Number(n) => v.push(*n),
|
||||
for (i, (x, y)) in va.data.iter().zip(da.data.iter()).enumerate() {
|
||||
// Excel (XNPV): a blank or text value or a blank date is #NUM!, except in the first row,
|
||||
// where it is #VALUE!.
|
||||
let strict_err = if i == 0 { CellError::Value } else { CellError::Num };
|
||||
let value = match x {
|
||||
Value::Number(n) => *n,
|
||||
Value::Empty if lenient => 0.0,
|
||||
Value::Empty => return Err(strict_err),
|
||||
Value::Error(e) => return Err(*e),
|
||||
_ => return Err(CellError::Value),
|
||||
}
|
||||
_ if lenient => return Err(CellError::Value),
|
||||
_ => return Err(strict_err),
|
||||
};
|
||||
match y {
|
||||
Value::Number(n) => d.push(n.trunc()),
|
||||
Value::Error(e) => return Err(*e),
|
||||
Value::Text(_) => d.push(y.to_number()?.trunc()),
|
||||
Value::Empty if !lenient => return Err(strict_err),
|
||||
// XIRR skips a blank date next to a 0 flow and reads one in the first row as day 0.
|
||||
Value::Empty if value == 0.0 => continue,
|
||||
Value::Empty if i == 0 => d.push(0.0),
|
||||
Value::Empty => return Err(CellError::Num),
|
||||
_ => return Err(CellError::Value),
|
||||
}
|
||||
v.push(value);
|
||||
}
|
||||
let d0 = *d.first().ok_or(CellError::Num)?;
|
||||
if d.iter().any(|&x| x < d0 || x < 0.0) {
|
||||
if d.iter().any(|&x| (x < d0 && !lenient) || x < 0.0) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
Ok((v, d))
|
||||
@@ -353,35 +306,219 @@ pub(super) fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
if rate <= -1.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?;
|
||||
let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value, false)?;
|
||||
num_val(xnpv_calc(rate, &v, &d))
|
||||
}
|
||||
|
||||
/// Excel's XIRR solver, reconstructed by observing Excel with synthetic inputs (not from its
|
||||
/// code; its documentation says only "iteration", 100 tries and 0.000001 percent). It looks
|
||||
/// only at the sign of XNPV until the end, so its answer is the root to about 1e-8, not to the
|
||||
/// last digit:
|
||||
///
|
||||
/// - Bracket the root from the guess (0 counts as 1e-5): double the rate while XNPV keeps the
|
||||
/// sign it has at the guess and that sign differs from the first nonzero value (the root is higher).
|
||||
/// Otherwise the root is lower: bisect towards 0 if XNPV changes sign there; halve the rate
|
||||
/// towards 0 if XNPV is larger in size at 0 than at the guess; otherwise try minus the guess
|
||||
/// and then step halfway to -100% each time. A negative guess only moves towards 0 (root
|
||||
/// higher) or towards -100% (root lower).
|
||||
/// - Bisect the bracket, taking the midpoint from the upper end, until half the bracket is
|
||||
/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first nonzero value|; return that
|
||||
/// midpoint. A zero XNPV counts as the upper side.
|
||||
/// - Halving towards 0 that gets within that tolerance of 0 without a sign change goes on with
|
||||
/// the negative side; at most 100 XNPV evaluations in all; a rate of -100% or an XNPV that
|
||||
/// can't be computed (a negative base for fractional years) is #NUM!.
|
||||
struct XirrSolver<'a> {
|
||||
values: &'a [f64],
|
||||
/// First nonzero value: sets the search direction and the residual scale.
|
||||
first: f64,
|
||||
years: Vec<f64>,
|
||||
evals: usize,
|
||||
/// XNPV must be within this of 0 at the answer.
|
||||
residual: f64,
|
||||
}
|
||||
|
||||
impl XirrSolver<'_> {
|
||||
const MAX_EVALS: usize = 100;
|
||||
|
||||
fn tol(rate: f64) -> f64 {
|
||||
1e-8 * (rate.abs() + 0.5)
|
||||
}
|
||||
|
||||
fn same_sign(a: f64, b: f64) -> bool {
|
||||
a * b > 0.0
|
||||
}
|
||||
|
||||
fn f(&mut self, rate: f64) -> R<f64> {
|
||||
self.evals += 1;
|
||||
if self.evals > Self::MAX_EVALS {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let base = 1.0 + rate;
|
||||
if base == 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let mut sum = 0.0;
|
||||
for (x, t) in self.values.iter().zip(&self.years) {
|
||||
sum += x / base.powf(*t);
|
||||
}
|
||||
if sum.is_finite() { Ok(sum) } else { Err(CellError::Num) }
|
||||
}
|
||||
|
||||
fn solve(&mut self, guess: f64) -> R<f64> {
|
||||
let g = if guess == 0.0 { 1e-5 } else { guess };
|
||||
let fg = self.f(g)?;
|
||||
let higher = fg * self.first < 0.0;
|
||||
if g > 0.0 {
|
||||
if higher {
|
||||
return self.double(g, fg);
|
||||
}
|
||||
let f0 = self.f(0.0)?;
|
||||
if !Self::same_sign(f0, fg) {
|
||||
return self.bisect(g, fg, 0.0, f0);
|
||||
}
|
||||
if f0.abs() > fg.abs() {
|
||||
return self.halve(g, fg, g, fg);
|
||||
}
|
||||
return self.negative_side(g, fg);
|
||||
}
|
||||
if higher { self.halve(g, fg, g, fg) } else { self.towards_minus_one(g, fg) }
|
||||
}
|
||||
|
||||
fn double(&mut self, mut x: f64, mut fx: f64) -> R<f64> {
|
||||
loop {
|
||||
let next = 2.0 * x;
|
||||
let fnext = self.f(next)?;
|
||||
if !Self::same_sign(fnext, fx) {
|
||||
return self.bisect(x, fx, next, fnext);
|
||||
}
|
||||
(x, fx) = (next, fnext);
|
||||
}
|
||||
}
|
||||
|
||||
fn halve(&mut self, mut x: f64, mut fx: f64, g: f64, fg: f64) -> R<f64> {
|
||||
loop {
|
||||
let step = -x / 2.0;
|
||||
let next = x + step;
|
||||
let fnext = self.f(next)?;
|
||||
if !Self::same_sign(fnext, fx) {
|
||||
return self.bisect(x, fx, next, fnext);
|
||||
}
|
||||
if step.abs() < Self::tol(next) {
|
||||
if next < 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
return self.negative_side(g, fg);
|
||||
}
|
||||
(x, fx) = (next, fnext);
|
||||
}
|
||||
}
|
||||
|
||||
fn negative_side(&mut self, g: f64, fg: f64) -> R<f64> {
|
||||
let fm = self.f(-g)?;
|
||||
if !Self::same_sign(fm, fg) {
|
||||
return self.bisect(g, fg, -g, fm);
|
||||
}
|
||||
self.towards_minus_one(-g, fm)
|
||||
}
|
||||
|
||||
fn towards_minus_one(&mut self, mut x: f64, mut fx: f64) -> R<f64> {
|
||||
loop {
|
||||
let next = x + (-1.0 - x) / 2.0;
|
||||
let fnext = self.f(next)?;
|
||||
if !Self::same_sign(fnext, fx) {
|
||||
return self.bisect(x, fx, next, fnext);
|
||||
}
|
||||
(x, fx) = (next, fnext);
|
||||
}
|
||||
}
|
||||
|
||||
fn bisect(&mut self, a: f64, fa: f64, b: f64, fb: f64) -> R<f64> {
|
||||
let (mut lo, mut flo, mut hi) = if a < b { (a, fa, b) } else { (b, fb, a) };
|
||||
loop {
|
||||
let mid = hi - (hi - lo) / 2.0;
|
||||
let fm = self.f(mid)?;
|
||||
if (hi - lo) / 2.0 < Self::tol(mid) && fm.abs() < self.residual {
|
||||
return Ok(mid);
|
||||
}
|
||||
if Self::same_sign(fm, flo) {
|
||||
(lo, flo) = (mid, fm);
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?;
|
||||
let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?;
|
||||
let guess = opt_num(a, 2, 0.1)?;
|
||||
if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
|
||||
if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
num_val(solve_rate(|r| xnpv_calc(r, &v, &d), guess)?)
|
||||
if v.first() == Some(&0.0) {
|
||||
// Excel with a 0 (or blank) first flow: the residual scale is 0, so the search just
|
||||
// halves the guess towards 0 until the step is under the tolerance; a negative guess is #NUM!.
|
||||
if guess < 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let mut x = if guess == 0.0 { 1e-5 } else { guess };
|
||||
// Bounded: a huge guess halves to the tolerance within about 1100 steps.
|
||||
for _ in 0..1100 {
|
||||
if x / 2.0 < XirrSolver::tol(x / 2.0) {
|
||||
break;
|
||||
}
|
||||
x /= 2.0;
|
||||
}
|
||||
return num_val(x / 2.0);
|
||||
}
|
||||
let d0 = d.first().copied().unwrap_or(0.0);
|
||||
let first = v.iter().copied().find(|x| *x != 0.0).unwrap_or(0.0);
|
||||
let mut solver = XirrSolver { values: &v, first, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() };
|
||||
num_val(solver.solve(guess)?)
|
||||
}
|
||||
|
||||
/// Excel's IRR solver, approximated from observation (Excel's documentation says 20 tries and
|
||||
/// 0.00001 percent): Newton's method on the discount factor 1/(1+rate), where the cash flows
|
||||
/// are a polynomial, from 1/(1+guess) until a step moves less than 1e-8, for at most 100 steps.
|
||||
/// Excel's answers agree with it to about 1e-12 on ordinary flows (the last digits differ) and
|
||||
/// on which flows have no answer, apart from a few far from any guess.
|
||||
fn irr_solve(v: &[f64], guess: f64) -> R<f64> {
|
||||
let mut x = 1.0 / (1.0 + guess);
|
||||
for _ in 0..100 {
|
||||
let (mut s, mut ds, mut scale) = (0.0, 0.0, 0.0);
|
||||
for c in v.iter().rev() {
|
||||
ds = ds * x + s;
|
||||
s = s * x + c;
|
||||
scale = scale * x.abs() + c.abs();
|
||||
}
|
||||
if ds == 0.0 {
|
||||
// An exact root with a zero slope (a repeated root such as {1,-2,1} at guess 0) is
|
||||
// still the answer: Excel returns 0 there.
|
||||
return if s == 0.0 && x > 0.0 { Ok(1.0 / x - 1.0) } else { Err(CellError::Num) };
|
||||
}
|
||||
let next = x - s / ds;
|
||||
if !next.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
if (next - x).abs() < 1e-8 && scale.is_finite() && s.abs() <= 1e-12 * scale {
|
||||
return if next > 0.0 { Ok(1.0 / next - 1.0) } else { Err(CellError::Num) };
|
||||
}
|
||||
x = next;
|
||||
}
|
||||
Err(CellError::Num)
|
||||
}
|
||||
|
||||
pub(super) fn irr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let v = array_numbers(&a.first().ok_or(CellError::Value)?.value)?;
|
||||
let guess = opt_num(a, 1, 0.1)?;
|
||||
// Excel: a guess at or below -100% is #VALUE! for IRR (#NUM! for XIRR).
|
||||
if guess <= -1.0 {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let f = |r: f64| {
|
||||
let mut s = 0.0;
|
||||
let mut d = 1.0;
|
||||
for x in &v {
|
||||
s += x / d;
|
||||
d *= 1.0 + r;
|
||||
}
|
||||
s
|
||||
};
|
||||
num_val(solve_rate(f, guess)?)
|
||||
num_val(irr_solve(&v, guess)?)
|
||||
}
|
||||
|
||||
pub(super) fn mirr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
|
||||
@@ -22,17 +22,17 @@ fn chars(s: &str) -> Vec<char> {
|
||||
}
|
||||
|
||||
fn check_len(s: String) -> R<Value> {
|
||||
if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT {
|
||||
if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
text_val(s)
|
||||
}
|
||||
|
||||
/// Pushes `piece` onto `out`, failing once the result exceeds the cell limit.
|
||||
fn push_capped(out: &mut String, piece: &str) -> R<()> {
|
||||
fn push_capped(out: &mut String, piece: &str, over: CellError) -> R<()> {
|
||||
// Checked before copying, so one oversized piece is refused without being appended.
|
||||
if out.len().saturating_add(piece.len()) > MAX_TEXT * 4 {
|
||||
return Err(CellError::Value);
|
||||
return Err(over);
|
||||
}
|
||||
out.push_str(piece);
|
||||
Ok(())
|
||||
@@ -47,22 +47,35 @@ fn piece(v: &Value) -> R<std::borrow::Cow<'_, str>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// CONCATENATE cuts at the cell limit like `&`; CONCAT and TEXTJOIN give `#CALC!` past it.
|
||||
fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let mut out = String::new();
|
||||
for x in a {
|
||||
push_capped(&mut out, &piece(&scalar(x))?)?;
|
||||
// Past the budget, later arguments are still converted so their errors propagate.
|
||||
let v = scalar(x);
|
||||
let piece = piece(&v)?;
|
||||
if out.len() <= MAX_TEXT * 4 {
|
||||
out.push_str(&piece);
|
||||
}
|
||||
}
|
||||
check_len(out)
|
||||
text_val(gridcraft_core::cap_text(out))
|
||||
}
|
||||
|
||||
fn check_calc(s: String) -> R<Value> {
|
||||
if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT {
|
||||
return Err(CellError::Calc);
|
||||
}
|
||||
text_val(s)
|
||||
}
|
||||
|
||||
fn concat(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let mut out = String::new();
|
||||
for x in a {
|
||||
for v in as_array(&x.value).iter() {
|
||||
push_capped(&mut out, &piece(v)?)?;
|
||||
push_capped(&mut out, &piece(v)?, CellError::Calc)?;
|
||||
}
|
||||
}
|
||||
check_len(out)
|
||||
check_calc(out)
|
||||
}
|
||||
|
||||
/// The error `v.to_text()` would give, found without building any text.
|
||||
@@ -98,12 +111,12 @@ fn textjoin(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
&& !delims.data.is_empty()
|
||||
&& let Some(d) = delims.data.get((joined - 1) % delims.data.len())
|
||||
{
|
||||
push_capped(&mut out, &piece(d)?)?;
|
||||
push_capped(&mut out, &piece(d)?, CellError::Calc)?;
|
||||
}
|
||||
push_capped(&mut out, &s)?;
|
||||
push_capped(&mut out, &s, CellError::Calc)?;
|
||||
joined += 1;
|
||||
}
|
||||
check_len(out)
|
||||
check_calc(out)
|
||||
}
|
||||
|
||||
fn count_arg(a: &[Arg], i: usize, default: f64) -> R<usize> {
|
||||
@@ -252,7 +265,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
let n = n.trunc();
|
||||
let total = s.chars().count() as f64 * n;
|
||||
let total = s.encode_utf16().count() as f64 * n;
|
||||
if total > MAX_TEXT as f64 {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
@@ -772,7 +785,7 @@ fn arraytotext(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
} else if c > 0 {
|
||||
out.push_str(if strict { "," } else { ", " });
|
||||
}
|
||||
push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict))?;
|
||||
push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict), CellError::Value)?;
|
||||
}
|
||||
}
|
||||
if strict {
|
||||
@@ -1207,20 +1220,37 @@ mod tests {
|
||||
is_text(ev("TEXTJOIN", vec![t("-"), b(false), av(arr(vec![vec![tv("a"), tv(""), tv("b")]]))]), "a--b");
|
||||
is_text(ev("TEXTJOIN", vec![av(row_t(&[",", ";"])), b(true), t("a"), t("b"), t("c")]), "a,b;c");
|
||||
is_err(ev("CONCAT", vec![t("a"), e(CellError::NA)]), CellError::NA);
|
||||
// Past 32,767 characters: CONCAT and TEXTJOIN are #CALC!, CONCATENATE cuts like `&`
|
||||
// (checked in Excel: LEN(...) is #CALC!, #CALC! and 32767).
|
||||
let x = || t(&"x".repeat(20_000));
|
||||
is_err(ev("CONCAT", vec![x(), x()]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(false), x(), x()]), CellError::Calc);
|
||||
assert_eq!(ev("CONCATENATE", vec![x(), x()]), Value::text("x".repeat(32_767)));
|
||||
assert_eq!(ev("CONCAT", vec![x()]), Value::text("x".repeat(20_000)));
|
||||
// An error after the cut still propagates.
|
||||
let big = || t(&"x".repeat(32_767));
|
||||
is_err(ev("CONCATENATE", vec![big(), big(), big(), big(), big(), e(CellError::NA)]), CellError::NA);
|
||||
let emoji = "😀";
|
||||
is_err(ev("CONCAT", vec![t(&emoji.repeat(16_384))]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![t(""), b(false), t(&emoji.repeat(16_384))]), CellError::Calc);
|
||||
assert_eq!(ev("CONCATENATE", vec![t(&emoji.repeat(16_384))]), Value::text(emoji.repeat(16_383)));
|
||||
is_err(ev("REPT", vec![t(emoji), n(16_384.0)]), CellError::Value);
|
||||
assert_eq!(ev("REPT", vec![t(emoji), n(16_383.0)]), Value::text(emoji.repeat(16_383)));
|
||||
// Lifting: CONCATENATE over an array.
|
||||
assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]);
|
||||
}
|
||||
|
||||
/// Security: TEXTJOIN builds its result piece by piece and stops at the text cap, rather
|
||||
/// than first copying every input (100,000 references to one 32,767-character text were
|
||||
/// 3 GB of copies). Errors among the inputs still win, in argument order.
|
||||
/// 3 GB of copies), giving `#CALC!` there as past the cell limit. Errors among the inputs still
|
||||
/// win, in argument order.
|
||||
#[test]
|
||||
fn textjoin_stops_at_the_text_cap() {
|
||||
use gridcraft_core::Array;
|
||||
let long = tv(&"x".repeat(32_767));
|
||||
let many = || av(Array::filled(100_000, 1, long.clone()).into());
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(true), many()]), CellError::Value);
|
||||
is_err(ev("TEXTJOIN", vec![av(Array::filled(1, 100_000, long.clone()).into()), b(false), t("a"), t("b")]), CellError::Value);
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(true), many()]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![av(Array::filled(1, 100_000, long.clone()).into()), b(false), t("a"), t("b")]), CellError::Calc);
|
||||
is_err(ev("TEXTJOIN", vec![t(","), b(true), many(), e(CellError::Div0)]), CellError::Div0);
|
||||
is_err(ev("TEXTJOIN", vec![av(arr(vec![vec![tv(","), Value::Error(CellError::NA)]])), b(true), t("a")]), CellError::NA);
|
||||
// Delimiters cycle and are converted only where used.
|
||||
|
||||
@@ -11,7 +11,7 @@ pub(crate) type R<T> = Result<T, CellError>;
|
||||
|
||||
/// Largest array a function may build.
|
||||
pub(crate) const MAX_CELLS: usize = 10_000_000;
|
||||
/// Longest text a cell can hold.
|
||||
/// Longest text a cell can hold, in UTF-16 code units.
|
||||
pub(crate) const MAX_TEXT: usize = 32_767;
|
||||
|
||||
/// Scalar-position lifting tables.
|
||||
@@ -20,11 +20,11 @@ pub(crate) const S: &[bool] = &[true];
|
||||
pub(crate) const A: &[bool] = &[false];
|
||||
|
||||
/// Turns an implementation result into a cell value: errors become error values, non-finite
|
||||
/// numbers become `#NUM!`, text longer than 32,767 characters becomes `#VALUE!`.
|
||||
/// numbers become `#NUM!`, text longer than 32,767 UTF-16 code units becomes `#VALUE!`.
|
||||
pub(crate) fn finish(r: R<Value>) -> Value {
|
||||
match r {
|
||||
Ok(Value::Number(n)) => Value::number(n),
|
||||
Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.chars().count() > MAX_TEXT => Value::Error(CellError::Value),
|
||||
Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.encode_utf16().count() > MAX_TEXT => Value::Error(CellError::Value),
|
||||
Ok(v) => v,
|
||||
Err(e) => Value::Error(e),
|
||||
}
|
||||
|
||||
@@ -288,7 +288,7 @@ fn base_tool_definitions() -> Vec<Value> {
|
||||
json!({
|
||||
"range": string("Source data range including headers, e.g. \"A1:C6\""),
|
||||
"type": enumeration("Chart type", CHART_TYPES),
|
||||
"subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers"]),
|
||||
"subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers", "stacked100Markers"]),
|
||||
"title": string("Chart title"),
|
||||
"at": string("Top-left anchor cell (default: right of the data)"),
|
||||
}),
|
||||
|
||||
@@ -15,6 +15,7 @@ test-support = []
|
||||
|
||||
[dependencies]
|
||||
gridcraft-core = { workspace = true }
|
||||
sha1 = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
gridcraft-formula = { workspace = true }
|
||||
gridcraft-math = { workspace = true }
|
||||
|
||||
@@ -501,6 +501,8 @@ pub enum ChartKind {
|
||||
Line,
|
||||
LineMarkers,
|
||||
LineStacked,
|
||||
LineStacked100,
|
||||
LineStacked100Markers,
|
||||
Pie,
|
||||
Doughnut,
|
||||
Area,
|
||||
@@ -683,10 +685,17 @@ pub struct Chart {
|
||||
}
|
||||
|
||||
/// Whether a series of kind `b` can be drawn in a chart of kind `a` without making it a combo:
|
||||
/// the same kind, or a line with or without markers, or a scatter with or without lines.
|
||||
/// the same kind, or a line or 100% stacked line with or without markers, or a scatter with or
|
||||
/// without lines.
|
||||
pub fn same_family(a: ChartKind, b: ChartKind) -> bool {
|
||||
use ChartKind::*;
|
||||
a == b || matches!((a, b), (Line | LineMarkers, Line | LineMarkers) | (Scatter | ScatterLines, Scatter | ScatterLines))
|
||||
a == b
|
||||
|| matches!(
|
||||
(a, b),
|
||||
(Line | LineMarkers, Line | LineMarkers)
|
||||
| (LineStacked100 | LineStacked100Markers, LineStacked100 | LineStacked100Markers)
|
||||
| (Scatter | ScatterLines, Scatter | ScatterLines)
|
||||
)
|
||||
}
|
||||
|
||||
/// The kind a combo chart's series `i` with its own kind `own` is drawn as.
|
||||
@@ -730,20 +739,34 @@ fn grouped(k: ChartKind) -> Option<Grouped> {
|
||||
use ChartKind::*;
|
||||
match k {
|
||||
ColumnClustered | ColumnStacked | ColumnStacked100 => Some(Grouped::Column),
|
||||
Line | LineMarkers | LineStacked => Some(Grouped::Line),
|
||||
Line | LineMarkers | LineStacked | LineStacked100 | LineStacked100Markers => Some(Grouped::Line),
|
||||
Area | AreaStacked | AreaStacked100 => Some(Grouped::Area),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Kind `k` drawn in the grouping of `first`, the first series of its type on its axes: columns
|
||||
/// and areas take its kind; a line is stacked when it is, and unstacked (keeping its own
|
||||
/// markers) when it isn't.
|
||||
/// and areas take its kind; a line is stacked when it is, stacked to 100% (keeping its own
|
||||
/// markers) when it is, and unstacked (keeping its own markers) when it isn't.
|
||||
fn regroup(k: ChartKind, first: ChartKind) -> ChartKind {
|
||||
use ChartKind::*;
|
||||
let marked = matches!(k, LineMarkers | LineStacked100Markers);
|
||||
match (grouped(k), first) {
|
||||
(Some(Grouped::Line), ChartKind::LineStacked) => ChartKind::LineStacked,
|
||||
(Some(Grouped::Line), _) if k == ChartKind::LineStacked => ChartKind::Line,
|
||||
(Some(Grouped::Line), _) => k,
|
||||
(Some(Grouped::Line), LineStacked) => LineStacked,
|
||||
(Some(Grouped::Line), LineStacked100 | LineStacked100Markers) => {
|
||||
if marked {
|
||||
LineStacked100Markers
|
||||
} else {
|
||||
LineStacked100
|
||||
}
|
||||
}
|
||||
(Some(Grouped::Line), _) => {
|
||||
if marked {
|
||||
LineMarkers
|
||||
} else {
|
||||
Line
|
||||
}
|
||||
}
|
||||
_ => first,
|
||||
}
|
||||
}
|
||||
@@ -845,6 +868,8 @@ impl Chart {
|
||||
| ChartKind::Line
|
||||
| ChartKind::LineMarkers
|
||||
| ChartKind::LineStacked
|
||||
| ChartKind::LineStacked100
|
||||
| ChartKind::LineStacked100Markers
|
||||
| ChartKind::Area
|
||||
| ChartKind::AreaStacked
|
||||
| ChartKind::AreaStacked100
|
||||
@@ -1401,6 +1426,10 @@ mod series_kind_tests {
|
||||
assert_eq!(drawn(&chart(Line, &[None, Some(LineMarkers), Some(Area)])), vec![Line, LineMarkers, Line]);
|
||||
assert_eq!(drawn(&chart(ScatterLines, &[Some(Scatter), Some(Line)])), vec![Scatter, ScatterLines]);
|
||||
assert_eq!(drawn(&chart(ColumnClustered, &[Some(Line)])), vec![ColumnClustered]);
|
||||
assert_eq!(
|
||||
drawn(&chart(LineStacked100Markers, &[Some(LineStacked100), None, Some(LineMarkers)])),
|
||||
vec![LineStacked100, LineStacked100Markers, LineStacked100Markers]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1415,6 +1444,15 @@ mod series_kind_tests {
|
||||
// An unstacked line keeps its own markers; a stacked one after it is unstacked.
|
||||
let c = chart(Combo, &[Some(Line), Some(LineMarkers), Some(LineStacked)]);
|
||||
assert_eq!(drawn(&c), vec![Line, LineMarkers, Line]);
|
||||
// Lines after a 100% stacked one are stacked to 100%, each keeping its own markers; a
|
||||
// 100% stacked line after a stacked one is stacked, and after an unstacked one unstacked.
|
||||
let c = chart(Combo, &[Some(LineStacked100), Some(LineMarkers), Some(LineStacked), Some(LineStacked100Markers)]);
|
||||
assert_eq!(drawn(&c), vec![LineStacked100, LineStacked100Markers, LineStacked100, LineStacked100Markers]);
|
||||
assert_eq!(c.series_kinds(), drawn(&c));
|
||||
let c = chart(Combo, &[Some(LineStacked), Some(LineStacked100Markers)]);
|
||||
assert_eq!(drawn(&c), vec![LineStacked, LineStacked]);
|
||||
let c = chart(Combo, &[Some(LineMarkers), Some(LineStacked100), Some(LineStacked100Markers)]);
|
||||
assert_eq!(drawn(&c), vec![LineMarkers, Line, LineMarkers]);
|
||||
// Each pair of axes has its own first.
|
||||
let mut c = chart(Combo, &[Some(ColumnClustered), Some(ColumnStacked)]);
|
||||
c.series[1].secondary = true;
|
||||
|
||||
@@ -11,7 +11,10 @@ pub enum Orientation {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PrintSettings {
|
||||
pub orientation: Orientation,
|
||||
/// Paper size name (`Letter`, `A4`, `Legal`…).
|
||||
/// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]). Empty means no paper is
|
||||
/// stated, so the printer's or locale's paper applies: a reader may leave it so for a file
|
||||
/// that states none (none does yet). Print layout falls back to Letter and XLSX writes no
|
||||
/// `paperSize`. New sheets default to Letter.
|
||||
pub paper: String,
|
||||
/// Margins in inches: left, right, top, bottom, header, footer.
|
||||
pub margins: [f32; 6],
|
||||
@@ -258,7 +261,8 @@ pub struct LineInfo {
|
||||
pub outline: u8,
|
||||
pub collapsed: bool,
|
||||
pub style: Option<crate::style::StyleId>,
|
||||
/// The size was set by the user (rows): automatic heights follow the content.
|
||||
/// The size was set by the user. Rows without it follow their content's height; columns
|
||||
/// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…).
|
||||
#[serde(default)]
|
||||
pub custom: bool,
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod cell;
|
||||
mod cellmap;
|
||||
pub mod features;
|
||||
pub mod macros;
|
||||
pub mod paper;
|
||||
pub mod password;
|
||||
pub mod preserved;
|
||||
pub mod python;
|
||||
@@ -31,7 +32,7 @@ pub use style::{
|
||||
};
|
||||
pub use workbook::{
|
||||
CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString,
|
||||
RefHost, ShowObjects, Workbook, WorkbookView,
|
||||
RefHost, ShowObjects, Workbook, WorkbookView, WriteReservation,
|
||||
};
|
||||
|
||||
/// Font used for new workbooks. Only a name: renderers substitute an available open font
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats
|
||||
//! (paper ids or page sizes) and print layout all read this one table.
|
||||
|
||||
/// Paper names and sizes in points, width then height, as the paper is named: Ledger is
|
||||
/// Tabloid turned on its side. Each size has one name, so a size reads back as the name it was
|
||||
/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and
|
||||
/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and
|
||||
/// envelopes are the JIS ones too.
|
||||
pub const PAPERS: [(&str, f32, f32); 24] = [
|
||||
("Letter", 612.0, 792.0),
|
||||
("Legal", 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", 792.0, 1224.0),
|
||||
("Ledger", 1224.0, 792.0),
|
||||
("Executive", 522.0, 756.0),
|
||||
("Statement", 396.0, 612.0),
|
||||
("B4", 728.50, 1031.81),
|
||||
("B5", 515.91, 728.50),
|
||||
("B6", 362.83, 515.91),
|
||||
("B4 (ISO)", 708.66, 1000.63),
|
||||
("B5 (ISO)", 498.90, 708.66),
|
||||
("B6 (ISO)", 354.33, 498.90),
|
||||
("Envelope #10", 297.0, 684.0),
|
||||
("Envelope DL", 311.81, 623.62),
|
||||
("Japanese Postcard", 283.46, 419.53),
|
||||
("Japanese Double Postcard", 419.53, 566.93),
|
||||
("Japanese Envelope #3", 340.16, 666.14),
|
||||
// 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out.
|
||||
("Japanese Envelope #4", 255.12, 581.10),
|
||||
("Japanese Envelope Kaku #2", 680.31, 941.10),
|
||||
("Japanese Envelope Kaku #3", 612.28, 785.20),
|
||||
];
|
||||
|
||||
/// Other spellings of the names above, in [`key`] form.
|
||||
const ALIASES: [(&str, &str); 13] = [
|
||||
// The B5 envelope is ISO B5 itself (176×250 mm): one size, one name.
|
||||
("envelopeb5", "B5 (ISO)"),
|
||||
("usletter", "Letter"),
|
||||
("uslegal", "Legal"),
|
||||
("11x17", "Tabloid"),
|
||||
("b4jis", "B4"),
|
||||
("b5jis", "B5"),
|
||||
("b6jis", "B6"),
|
||||
("postcard", "Japanese Postcard"),
|
||||
("doublepostcard", "Japanese Double Postcard"),
|
||||
("chou#3", "Japanese Envelope #3"),
|
||||
("chou#4", "Japanese Envelope #4"),
|
||||
("kaku#2", "Japanese Envelope Kaku #2"),
|
||||
("kaku#3", "Japanese Envelope Kaku #3"),
|
||||
];
|
||||
|
||||
/// A name as compared: spaces, hyphens, underscores and parentheses don't matter, nor does case
|
||||
/// (`B5 (JIS)`, `b5-jis` and `b5jis` are one name).
|
||||
fn key(name: &str) -> String {
|
||||
name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], "")
|
||||
}
|
||||
|
||||
/// The paper `name` stands for, under its table name.
|
||||
pub fn canonical(name: &str) -> Option<&'static str> {
|
||||
// No paper name is long; a huge one (from a file or a command) is not worth folding.
|
||||
if name.len() > 64 {
|
||||
return None;
|
||||
}
|
||||
let k = key(name);
|
||||
PAPERS.iter().map(|(n, _, _)| *n).find(|n| key(n) == k).or_else(|| ALIASES.iter().find(|(a, _)| *a == k).map(|(_, n)| *n))
|
||||
}
|
||||
|
||||
/// The size of paper `name` in points (width, height).
|
||||
pub fn size_pt(name: &str) -> Option<(f32, f32)> {
|
||||
let n = canonical(name)?;
|
||||
PAPERS.iter().find(|(p, _, _)| *p == n).map(|(_, w, h)| (*w, *h))
|
||||
}
|
||||
|
||||
/// The paper of a page `width` × `height` points, within 2 mm on each side: the nearest one as it
|
||||
/// stands, else the nearest one turned. Some papers are less than 4 mm apart (Letter and Japanese
|
||||
/// Envelope Kaku #3), so the nearest wins, not the first in the table.
|
||||
///
|
||||
/// The name is the paper as the page stands: a 17×11 in page is `Ledger`. A caller that also
|
||||
/// records a landscape orientation should pass the size upright (narrow side first), since
|
||||
/// print layout turns the named paper once more for landscape.
|
||||
pub fn for_size(width: f32, height: f32) -> Option<&'static str> {
|
||||
const TOLERANCE: f32 = 5.67; // 2 mm
|
||||
let nearest = |w: f32, h: f32| {
|
||||
PAPERS
|
||||
.iter()
|
||||
.filter_map(|(n, pw, ph)| {
|
||||
let (dw, dh) = ((pw - w).abs(), (ph - h).abs());
|
||||
(dw < TOLERANCE && dh < TOLERANCE).then_some((dw + dh, *n))
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(_, n)| n)
|
||||
};
|
||||
nearest(width, height).or_else(|| nearest(height, width))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_and_sizes() {
|
||||
assert_eq!(size_pt("b5-jis"), Some((515.91, 728.50)));
|
||||
assert_eq!(size_pt("US Letter"), Some((612.0, 792.0)));
|
||||
assert_eq!(size_pt("nonsense"), None);
|
||||
assert_eq!(for_size(1224.0, 792.0), Some("Ledger"));
|
||||
assert_eq!(for_size(792.0, 1224.0), Some("Tabloid"));
|
||||
assert_eq!(for_size(842.0, 595.0), Some("A4"));
|
||||
assert_eq!(canonical("ledger"), Some("Ledger"));
|
||||
assert_eq!(canonical(""), None);
|
||||
assert_eq!(canonical(&"A4".repeat(1000)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_size_reads_back_as_its_name() {
|
||||
for (name, w, h) in PAPERS {
|
||||
assert_eq!(for_size(w, h), Some(name), "{name}");
|
||||
}
|
||||
assert_eq!(canonical("Envelope B5"), Some("B5 (ISO)"));
|
||||
}
|
||||
|
||||
/// Letter (612×792) and Japanese Envelope Kaku #3 (612.28×785.2) are within 2 mm of some
|
||||
/// of the same sizes: the nearer paper wins, whichever comes first in the table.
|
||||
#[test]
|
||||
fn for_size_picks_the_nearest_paper() {
|
||||
assert_eq!(for_size(612.2, 788.0), Some("Japanese Envelope Kaku #3"));
|
||||
assert_eq!(for_size(612.0, 790.0), Some("Letter"));
|
||||
assert_eq!(for_size(788.0, 612.2), Some("Japanese Envelope Kaku #3"));
|
||||
// A wide page that is a paper as it stands is not read as another paper turned.
|
||||
assert_eq!(for_size(1224.0, 792.0), Some("Ledger"));
|
||||
assert_eq!(for_size(1000.0, 10.0), None);
|
||||
assert_eq!(for_size(f32::NAN, 792.0), None);
|
||||
assert_eq!(for_size(f32::INFINITY, f32::INFINITY), None);
|
||||
}
|
||||
}
|
||||
@@ -160,6 +160,7 @@ impl PasswordHash {
|
||||
return Err("the stored password hash is damaged".into());
|
||||
};
|
||||
let got = match algorithm.to_ascii_uppercase().replace('_', "-").as_str() {
|
||||
"SHA-1" => iterated::<sha1::Sha1>(password, &salt, *spin_count),
|
||||
"SHA-512" => iterated::<sha2::Sha512>(password, &salt, *spin_count),
|
||||
"SHA-384" => iterated::<sha2::Sha384>(password, &salt, *spin_count),
|
||||
"SHA-256" => iterated::<sha2::Sha256>(password, &salt, *spin_count),
|
||||
@@ -236,6 +237,19 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha1_iterated_hash_verifies_the_correct_password() {
|
||||
// Known answer for "s3cret", salt "0123456789abcdef", spin count 10, computed outside this code.
|
||||
let h = PasswordHash::Iterated {
|
||||
algorithm: "SHA-1".into(),
|
||||
hash: "b2+ArdbduWEP3TNb+4NZg6qjkEk=".into(),
|
||||
salt: crate::b64::encode(b"0123456789abcdef"),
|
||||
spin_count: 10,
|
||||
};
|
||||
assert!(h.verify("s3cret").unwrap());
|
||||
assert!(!h.verify("s3cret ").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterated_hash_verifies_and_refuses_what_it_cannot_check() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let h = PasswordHash::new_sha512("s3cret", b"0123456789abcdef");
|
||||
@@ -245,7 +259,7 @@ mod tests {
|
||||
let PasswordHash::Iterated { hash, salt, .. } = h else { return Err("not an iterated hash".into()) };
|
||||
let other =
|
||||
|algorithm: &str, spin_count| PasswordHash::Iterated { algorithm: algorithm.into(), hash: hash.clone(), salt: salt.clone(), spin_count };
|
||||
assert!(other("SHA-1", 10).verify("s3cret").is_err());
|
||||
assert!(!other("SHA-1", 10).verify("s3cret").unwrap());
|
||||
assert!(other("MD5", 10).verify("s3cret").is_err());
|
||||
assert!(other("SHA-512", MAX_SPIN_COUNT + 1).verify("s3cret").is_err());
|
||||
assert!(!other("SHA-256", 2).verify("s3cret")?);
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::sheet::Visibility;
|
||||
use crate::style::Style;
|
||||
|
||||
/// A relationship from an owning part (the package root, the workbook or a sheet, or a kept part)
|
||||
/// to a kept part or to an external target.
|
||||
@@ -32,6 +33,13 @@ pub struct PreservedPart {
|
||||
pub data: Arc<[u8]>,
|
||||
/// The part's own relationships, ids unchanged (the part's bytes refer to them).
|
||||
pub rels: Vec<PreservedRel>,
|
||||
/// Differential formats its XML refers to by `dxfId`, by their id in the source file's styles
|
||||
/// part. GridCraft rewrites the styles part, so the ids are renumbered on save (kept
|
||||
/// PivotTables).
|
||||
pub dxfs: Vec<(u32, Style)>,
|
||||
/// Custom number formats its XML refers to by `numFmtId` (code by id in the source file),
|
||||
/// renumbered on save like [`Self::dxfs`] (kept PivotTables and pivot caches).
|
||||
pub num_fmts: Vec<(u32, String)>,
|
||||
}
|
||||
|
||||
/// A raw XML element of an owning part that refers to kept parts, re-emitted on save with its
|
||||
|
||||
@@ -224,6 +224,9 @@ pub struct Workbook {
|
||||
/// alone has none and is not written there.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub structure_password: Option<crate::PasswordHash>,
|
||||
/// "Password to modify" (XLSX `fileSharing`): the file opens read-only unless it is given.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub write_reservation: Option<WriteReservation>,
|
||||
/// Custom fill lists (Options › Custom Lists) beyond the built-in ones.
|
||||
pub custom_lists: Vec<Vec<String>>,
|
||||
/// Named cell styles (Cell Styles gallery): name → style.
|
||||
@@ -294,6 +297,15 @@ impl Default for Workbook {
|
||||
}
|
||||
}
|
||||
|
||||
/// The write-reservation of a file (XLSX `fileSharing`): who reserved it, whether it asks to open
|
||||
/// read-only, and the hash of its password to modify, never the password.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct WriteReservation {
|
||||
pub user_name: String,
|
||||
pub read_only_recommended: bool,
|
||||
pub password: Option<crate::PasswordHash>,
|
||||
}
|
||||
|
||||
/// The active sheet index of a [`Workbook`].
|
||||
///
|
||||
/// Every other part of a workbook value is immutable once shared (the engine keeps versions as
|
||||
@@ -564,6 +576,7 @@ impl Workbook {
|
||||
props: DocProps::default(),
|
||||
protected_structure: false,
|
||||
structure_password: None,
|
||||
write_reservation: None,
|
||||
custom_lists: vec![],
|
||||
cell_styles: vec![],
|
||||
phonetics: vec![],
|
||||
|
||||
+105
-13
@@ -7,7 +7,9 @@
|
||||
//! built-in encoding ([`symbol_code`]), for Greek letters and mathematical operators.
|
||||
//! - Arabic is shaped and set in embedded Type3 subsets, with exact shaped advances.
|
||||
//! - Vector drawing: rectangles, lines (solid or dashed), polygons, circles (Bézier), clipping.
|
||||
//! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded).
|
||||
//! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded). The
|
||||
//! decoded image bytes one document keeps across all its pages are capped
|
||||
//! ([`MAX_DOC_IMAGE_BYTES`]); images past the cap are left out.
|
||||
//! - Coordinates are points with a **top-left origin** (y grows down); text `y` is the baseline.
|
||||
//!
|
||||
//! Streams are written uncompressed (images use the RunLengthDecode filter).
|
||||
@@ -510,6 +512,11 @@ pub struct Page {
|
||||
content: String,
|
||||
fonts: [bool; FONT_SLOTS],
|
||||
images: Vec<ImageData>,
|
||||
/// Image bytes this page may still keep before the document's image budget is spent. Set by
|
||||
/// [`PdfDoc::add_page`] and [`PdfDoc::page_mut`], which hand out one page at a time.
|
||||
image_room: u64,
|
||||
/// Bytes of image data this page keeps, counted as images are added.
|
||||
image_kept: u64,
|
||||
/// Indexes into `images`, by content hash; a hash match is confirmed with [`ImageData::same`].
|
||||
image_index: HashMap<u64, Vec<usize>>,
|
||||
/// Pixel comparisons made while looking up duplicate pictures (test instrumentation).
|
||||
@@ -532,6 +539,10 @@ pub struct Page {
|
||||
const MAX_PAGE_CONTENT: usize = 64 * 1024 * 1024;
|
||||
/// Largest image (pixels) embedded.
|
||||
const MAX_IMAGE_PIXELS: u64 = 40_000_000;
|
||||
/// Most bytes of image data (RGB plus alpha planes) one document keeps across all its pages.
|
||||
/// Each [`Page::image_rgba`] call keeps its own copy, so a picture repeated on every page of a
|
||||
/// long export would otherwise grow without bound; images past the budget are left out.
|
||||
pub const MAX_DOC_IMAGE_BYTES: u64 = 512 * 1024 * 1024;
|
||||
/// Deepest `q` nesting a PDF consumer must support (the PDF specification's implementation limits).
|
||||
const MAX_SAVE_DEPTH: usize = 28;
|
||||
/// Line join styles, as the `j` operator takes them.
|
||||
@@ -553,6 +564,22 @@ impl Page {
|
||||
fn full(&self) -> bool {
|
||||
self.content.len() > MAX_PAGE_CONTENT
|
||||
}
|
||||
|
||||
/// Bytes of image data this page may still add before the document's image budget
|
||||
/// ([`MAX_DOC_IMAGE_BYTES`]) is spent. An image of `pw`×`ph` pixels needs up to `pw * ph * 4`;
|
||||
/// callers can skip decoding pictures that cannot fit (the room never grows back while a
|
||||
/// document is built).
|
||||
pub fn image_room(&self) -> u64 {
|
||||
self.image_room
|
||||
}
|
||||
|
||||
/// Bytes of image data kept by this page, summed from its images (tests check the running
|
||||
/// [`Page::image_kept`] count against it).
|
||||
#[cfg(test)]
|
||||
fn image_bytes(&self) -> u64 {
|
||||
self.images.iter().fold(0u64, |acc, i| acc.saturating_add(i.rgb.len() as u64).saturating_add(i.alpha.as_ref().map_or(0, |a| a.len() as u64)))
|
||||
}
|
||||
|
||||
fn op(&mut self, s: &str) {
|
||||
if !self.full() {
|
||||
self.content.push_str(s);
|
||||
@@ -914,7 +941,8 @@ impl Page {
|
||||
}
|
||||
|
||||
/// Draws an RGBA image (`pw`×`ph` pixels, row-major, straight alpha) into the box
|
||||
/// `(x, y, w, h)`. Malformed or oversized buffers are ignored.
|
||||
/// `(x, y, w, h)`. Malformed or oversized buffers are ignored, and so are images that do not
|
||||
/// fit in what is left of the document's image budget ([`Page::image_room`]).
|
||||
pub fn image_rgba(&mut self, destination: Rect, rgba: &[u8], pixel_size: [u32; 2]) {
|
||||
let Rect { x, y, width: w, height: h } = destination;
|
||||
let [pw, ph] = pixel_size;
|
||||
@@ -926,6 +954,16 @@ impl Page {
|
||||
if self.saved.len() >= MAX_SAVE_DEPTH {
|
||||
return;
|
||||
}
|
||||
// Room for the worst case (RGB plus an alpha plane) is checked before anything is
|
||||
// allocated, so the document's image bytes stay bounded however many pages it has. Past
|
||||
// the budget, a picture this page already holds can still be drawn again: it is only
|
||||
// built for the lookup when the page holds one of the same size, so the temporary copy
|
||||
// made to compare is bounded by pixel dimensions the page already accepted (up to
|
||||
// `px * 4` bytes) and is dropped when nothing matches.
|
||||
let over_budget = px * 4 > self.image_room;
|
||||
if over_budget && !self.images.iter().any(|o| o.width == pw && o.height == ph) {
|
||||
return;
|
||||
}
|
||||
let px = px as usize;
|
||||
let mut rgb = Vec::with_capacity(px * 3);
|
||||
// The alpha plane is only allocated once a non-opaque pixel shows up.
|
||||
@@ -944,23 +982,33 @@ impl Page {
|
||||
}
|
||||
}
|
||||
let img = ImageData::new(pw, ph, rgb, alpha);
|
||||
// The same picture drawn again on this page shares one XObject.
|
||||
let candidates = self.image_index.entry(img.hash).or_default();
|
||||
// The same picture drawn again on this page shares one XObject. The lookup does not
|
||||
// insert: only an accepted picture gets an index entry, so refused pictures past the
|
||||
// budget don't grow the index.
|
||||
#[cfg(test)]
|
||||
let comparisons = &mut self.image_comparisons;
|
||||
let known = candidates.iter().copied().find(|&i| {
|
||||
#[cfg(test)]
|
||||
{
|
||||
*comparisons += 1;
|
||||
}
|
||||
self.images.get(i).is_some_and(|o| o.same(&img))
|
||||
let images = &self.images;
|
||||
let known = self.image_index.get(&img.hash).and_then(|candidates| {
|
||||
candidates.iter().copied().find(|&i| {
|
||||
#[cfg(test)]
|
||||
{
|
||||
*comparisons += 1;
|
||||
}
|
||||
images.get(i).is_some_and(|o| o.same(&img))
|
||||
})
|
||||
});
|
||||
let idx = match known {
|
||||
Some(i) => i,
|
||||
None if over_budget => return,
|
||||
None => {
|
||||
candidates.push(self.images.len());
|
||||
// Only a picture this page doesn't hold yet spends the document's image budget.
|
||||
let kept = (img.rgb.len() as u64).saturating_add(img.alpha.as_ref().map_or(0, |a| a.len() as u64));
|
||||
self.image_room = self.image_room.saturating_sub(kept);
|
||||
self.image_kept = self.image_kept.saturating_add(kept);
|
||||
let idx = self.images.len();
|
||||
self.image_index.entry(img.hash).or_default().push(idx);
|
||||
self.images.push(img);
|
||||
self.images.len() - 1
|
||||
idx
|
||||
}
|
||||
};
|
||||
let s = format!("q {} 0 0 {} {} {} cm /Im{} Do Q", n(w), n(h), n(x), n(self.y(y + h)), idx + 1);
|
||||
@@ -981,6 +1029,14 @@ pub struct Info {
|
||||
pub struct PdfDoc {
|
||||
pages: Vec<Page>,
|
||||
pub info: Info,
|
||||
/// Image budget lowered by [`PdfDoc::set_image_budget`]; `None` = [`MAX_DOC_IMAGE_BYTES`].
|
||||
image_budget: Option<u64>,
|
||||
/// Image bytes kept by every page except [`PdfDoc::open_page`], kept up to date as pages are
|
||||
/// handed out so the remaining room is found without scanning every page.
|
||||
image_used: u64,
|
||||
/// The page last handed out by [`PdfDoc::add_page`] or [`PdfDoc::page_mut`], whose images
|
||||
/// may have grown since; its bytes are folded into `image_used` when another page is handed out.
|
||||
open_page: Option<usize>,
|
||||
}
|
||||
|
||||
/// PackBits-style run-length encoding (PDF `RunLengthDecode`).
|
||||
@@ -1016,12 +1072,17 @@ impl PdfDoc {
|
||||
pub fn add_page(&mut self, width_pt: f32, height_pt: f32) -> &mut Page {
|
||||
let width = if width_pt.is_finite() { width_pt.clamp(3.0, 14_400.0) } else { 612.0 };
|
||||
let height = if height_pt.is_finite() { height_pt.clamp(3.0, 14_400.0) } else { 792.0 };
|
||||
self.close_open_page();
|
||||
let image_room = self.image_room(0);
|
||||
self.open_page = Some(self.pages.len());
|
||||
self.pages.push(Page {
|
||||
width,
|
||||
height,
|
||||
content: String::new(),
|
||||
fonts: [false; FONT_SLOTS],
|
||||
images: Vec::new(),
|
||||
image_room,
|
||||
image_kept: 0,
|
||||
image_index: HashMap::new(),
|
||||
#[cfg(test)]
|
||||
image_comparisons: 0,
|
||||
@@ -1037,13 +1098,44 @@ impl PdfDoc {
|
||||
&mut self.pages[i]
|
||||
}
|
||||
|
||||
/// Lowers the bytes of image data the whole document keeps (never above
|
||||
/// [`MAX_DOC_IMAGE_BYTES`], nor above a budget set before); images drawn past it are left out.
|
||||
pub fn set_image_budget(&mut self, bytes: u64) {
|
||||
let cap = self.image_budget.unwrap_or(MAX_DOC_IMAGE_BYTES);
|
||||
self.image_budget = Some(bytes.min(cap));
|
||||
}
|
||||
|
||||
/// Image bytes the document may still keep: its budget minus what every closed page holds
|
||||
/// and the `open_kept` bytes of the page being handed out.
|
||||
fn image_room(&self, open_kept: u64) -> u64 {
|
||||
self.image_budget.unwrap_or(MAX_DOC_IMAGE_BYTES).saturating_sub(self.image_used.saturating_add(open_kept))
|
||||
}
|
||||
|
||||
/// Folds the images the open page added since it was handed out into the document's count.
|
||||
fn close_open_page(&mut self) {
|
||||
if let Some(kept) = self.open_page.take().and_then(|i| self.pages.get(i)).map(|p| p.image_kept) {
|
||||
self.image_used = self.image_used.saturating_add(kept);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn page_count(&self) -> usize {
|
||||
self.pages.len()
|
||||
}
|
||||
|
||||
/// The page at `i`, to keep drawing on it.
|
||||
pub fn page_mut(&mut self, i: usize) -> Option<&mut Page> {
|
||||
self.pages.get_mut(i)
|
||||
if i >= self.pages.len() {
|
||||
return None;
|
||||
}
|
||||
self.close_open_page();
|
||||
let kept = self.pages.get(i)?.image_kept;
|
||||
// Page `i` is open again: its bytes leave the closed count until the next hand-out.
|
||||
self.image_used = self.image_used.saturating_sub(kept);
|
||||
let room = self.image_room(kept);
|
||||
self.open_page = Some(i);
|
||||
let page = self.pages.get_mut(i)?;
|
||||
page.image_room = room;
|
||||
Some(page)
|
||||
}
|
||||
|
||||
/// Whether some Arabic text was set in the standard and CID fonts, which have no Arabic glyphs,
|
||||
|
||||
@@ -923,6 +923,81 @@ fn cjk_text_is_not_replaced_by_question_marks() -> Result<(), Box<dyn Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A picture drawn on every page keeps only as many copies as the document-wide image budget
|
||||
/// holds, and the running byte counts stay in step as pages are added and reopened.
|
||||
#[test]
|
||||
fn image_bytes_are_bounded_across_pages() -> Result<(), Box<dyn Error>> {
|
||||
// Each page keeps its own copy of a picture it draws, so a picture repeated on every page of
|
||||
// a long export grew without bound (a 3 KB workbook reached 2 GiB). The document-wide budget
|
||||
// stops adding copies once it is spent.
|
||||
let mut d = PdfDoc::new();
|
||||
assert_eq!(d.add_page(100.0, 100.0).image_room(), MAX_DOC_IMAGE_BYTES);
|
||||
d.set_image_budget(u64::MAX);
|
||||
assert_eq!(d.add_page(100.0, 100.0).image_room(), MAX_DOC_IMAGE_BYTES, "the budget is never raised");
|
||||
let mut d = PdfDoc::new();
|
||||
d.set_image_budget(4);
|
||||
d.set_image_budget(8);
|
||||
assert_eq!(d.add_page(100.0, 100.0).image_room(), 4, "a later, higher budget doesn't raise a lower one");
|
||||
|
||||
let mut d = PdfDoc::new();
|
||||
d.set_image_budget(10_000);
|
||||
// Opaque 32×32: 4096 bytes of room needed, 3072 bytes (RGB, no mask) kept.
|
||||
let px = [200u8, 200, 200, 255].repeat(32 * 32);
|
||||
for _ in 0..50 {
|
||||
let p = d.add_page(100.0, 100.0);
|
||||
p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &px, [32, 32]);
|
||||
}
|
||||
let kept: u64 = d.pages.iter().map(Page::image_bytes).sum();
|
||||
assert_eq!(kept, 2 * 3072);
|
||||
assert_eq!(d.pages.iter().filter(|p| !p.images.is_empty()).count(), 2);
|
||||
assert!(d.pages.iter().skip(2).all(|p| p.images.is_empty() && p.content.is_empty()));
|
||||
// A page reopened later sees what the whole document already holds.
|
||||
let p = d.page_mut(0).ok_or_else(|| io::Error::other("missing page"))?;
|
||||
assert_eq!(p.image_room(), 10_000 - 2 * 3072);
|
||||
// The copy page 0 already holds is drawn again past the budget; a new picture of the same
|
||||
// size is refused; a small one still fits.
|
||||
p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &px, [32, 32]);
|
||||
p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &[100u8, 100, 100, 255].repeat(32 * 32), [32, 32]);
|
||||
p.image_rgba(Rect::new(0.0, 0.0, 10.0, 10.0), &[255; 4 * 4 * 4], [4, 4]);
|
||||
assert_eq!(d.pages[0].images.len(), 2, "the new big picture is refused, the small one still fits");
|
||||
assert_eq!(d.pages[0].content.matches(" Do Q").count(), 3, "the held copy is drawn twice, the small one once");
|
||||
// The running per-page counts match the images each page holds, and a page handed out next
|
||||
// sees what the reopened page added.
|
||||
assert!(d.pages.iter().all(|p| p.image_kept == p.image_bytes()));
|
||||
assert_eq!(d.add_page(100.0, 100.0).image_room(), 10_000 - 2 * 3072 - 4 * 4 * 3);
|
||||
assert!(d.page_mut(10_000).is_none());
|
||||
assert_eq!(d.page_mut(1).map(|p| p.image_room()), Some(10_000 - 2 * 3072 - 4 * 4 * 3));
|
||||
let pdf = d.finish()?;
|
||||
check_xref(&pdf)?;
|
||||
// The identical 32×32 copies on pages 0 and 1 are written once; the 4×4 picture is the other.
|
||||
assert_eq!(String::from_utf8_lossy(&pdf).matches("/Subtype /Image").count(), 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_the_page_holds_is_drawn_again_after_the_budget_is_spent() -> Result<(), Box<dyn Error>> {
|
||||
let mut d = PdfDoc::new();
|
||||
// Room for exactly one translucent 1×1 picture (3 bytes of RGB plus 1 of alpha).
|
||||
d.set_image_budget(4);
|
||||
let p = d.add_page(100.0, 100.0);
|
||||
let pixel = [10u8, 20, 30, 128];
|
||||
p.image_rgba(Rect::new(0.0, 0.0, 10.0, 10.0), &pixel, [1, 1]);
|
||||
assert_eq!(p.image_room(), 0);
|
||||
p.image_rgba(Rect::new(20.0, 0.0, 10.0, 10.0), &pixel, [1, 1]);
|
||||
p.image_rgba(Rect::new(40.0, 0.0, 10.0, 10.0), &[10u8, 20, 30, 64], [1, 1]);
|
||||
assert_eq!(p.images.len(), 1, "a new picture past the budget is refused");
|
||||
assert_eq!(p.content.matches("/Im1 Do Q").count(), 2, "the picture the page holds is drawn both times");
|
||||
// Refused pictures leave no trace in the duplicate index, however many distinct ones come.
|
||||
for v in 0..=255u8 {
|
||||
p.image_rgba(Rect::new(60.0, 0.0, 10.0, 10.0), &[v, 0, 0, 64], [1, 1]);
|
||||
}
|
||||
assert_eq!(p.images.len(), 1);
|
||||
assert_eq!(p.image_index.len(), 1, "a refused picture adds no index entry");
|
||||
assert_eq!(p.image_index.values().map(Vec::len).sum::<usize>(), 1);
|
||||
check_xref(&d.finish()?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arabic_is_shaped_and_preserved_or_falls_back_without_a_font() {
|
||||
let text = "مَرْحَبًا 123 (ABC)";
|
||||
|
||||
@@ -327,6 +327,18 @@ impl SheetApp {
|
||||
self.open_dialog(name, p.clone());
|
||||
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
|
||||
}
|
||||
"ui.selectionMode" => {
|
||||
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
|
||||
match p.get("mode").and_then(Json::as_str) {
|
||||
Some(id) => match crate::grid::SelectionMode::parse(id) {
|
||||
Some(mode) => self.grid.set_selection_mode(mode),
|
||||
None => return Some(Err(format!("unknown selection mode {id:?} (use \"extend\", \"add\" or \"off\")"))),
|
||||
},
|
||||
None if p.get("mode").is_some_and(|v| !v.is_null()) => return Some(Err("`mode` must be \"extend\", \"add\" or \"off\"".into())),
|
||||
None => {}
|
||||
}
|
||||
Ok(json!({"mode": self.grid.selection_mode.id()}))
|
||||
}
|
||||
"ui.pythonMode" => {
|
||||
// `{"on": true}` starts Python mode on the active cell (or switches the edit in
|
||||
// progress to it), `{"on": false}` leaves it; without `on` it switches. A start
|
||||
|
||||
@@ -18,6 +18,8 @@ impl SheetApp {
|
||||
self.message = Some(("Text Box".into(), clean_error(&e)));
|
||||
return;
|
||||
}
|
||||
// Editing a cell ends Extend and Add mode, as in Excel.
|
||||
self.grid.set_selection_mode(crate::grid::SelectionMode::Off);
|
||||
let Some(d) = self.session.active() else { return };
|
||||
let Some(sh) = d.wb.active() else { return };
|
||||
let at = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active);
|
||||
|
||||
@@ -6,6 +6,9 @@ impl SheetApp {
|
||||
Ok(r) => self.after_open(Some(path), &r),
|
||||
// A password-protected workbook: ask for the password; the dialog opens it.
|
||||
Err(e) if e.contains(gridcraft_engine::io::PASSWORD_REQUIRED) => self.open_dialog("openPassword", json!({"path": path})),
|
||||
Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => {
|
||||
self.open_dialog("openPassword", json!({"path": path, "modify": true}))
|
||||
}
|
||||
Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))),
|
||||
}
|
||||
self.after_engine();
|
||||
@@ -95,6 +98,10 @@ impl SheetApp {
|
||||
self.backstage = None;
|
||||
self.open_dialog("openPassword", json!({"name": name, "base64": b64}));
|
||||
}
|
||||
Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => {
|
||||
self.backstage = None;
|
||||
self.open_dialog("openPassword", json!({"name": name, "base64": b64, "modify": true}));
|
||||
}
|
||||
Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))),
|
||||
}
|
||||
self.after_engine();
|
||||
|
||||
@@ -98,6 +98,31 @@ impl Page {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a print preview was built for: document, revision, scope, the selection when it is
|
||||
/// the scope, and fit to page.
|
||||
type PreviewKey = (u64, u64, PrintScope, String, bool);
|
||||
|
||||
/// What File › Print › Settings prints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PrintScope {
|
||||
ActiveSheets,
|
||||
EntireWorkbook,
|
||||
/// The selected cells of the active sheet.
|
||||
Selection,
|
||||
}
|
||||
|
||||
impl PrintScope {
|
||||
const ALL: [PrintScope; 3] = [PrintScope::ActiveSheets, PrintScope::EntireWorkbook, PrintScope::Selection];
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
PrintScope::ActiveSheets => "Print Active Sheets",
|
||||
PrintScope::EntireWorkbook => "Print Entire Workbook",
|
||||
PrintScope::Selection => "Print Selection",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Document properties shown on the Info page: (`file.properties` key, label).
|
||||
const PROPERTIES: [(&str, &str); 6] = [
|
||||
("title", "Title"),
|
||||
@@ -116,14 +141,14 @@ pub struct Backstage {
|
||||
props: [String; 6],
|
||||
/// Focus at the end of the previous frame, before egui clears it on Esc.
|
||||
text_edit_focused: bool,
|
||||
/// Print: the whole workbook rather than the active sheet.
|
||||
pub print_all: bool,
|
||||
/// Print: what to print (the Settings menu's first choice).
|
||||
pub print_scope: PrintScope,
|
||||
/// Print: fit each sheet on one page.
|
||||
pub fit_to_page: bool,
|
||||
/// Print: the previewed page (0-based).
|
||||
preview_page: usize,
|
||||
/// Print: the preview for (document, revision, whole workbook, fit to page).
|
||||
preview: Option<((u64, u64, bool, bool), Json)>,
|
||||
/// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page).
|
||||
preview: Option<(PreviewKey, Json)>,
|
||||
/// Save As: the chosen file type (an extension from [`SAVE_TYPES`]).
|
||||
pub save_format: &'static str,
|
||||
/// Home and Open: when the recent workbooks were last changed.
|
||||
@@ -141,7 +166,7 @@ impl Backstage {
|
||||
page,
|
||||
props: Default::default(),
|
||||
text_edit_focused: false,
|
||||
print_all: false,
|
||||
print_scope: PrintScope::ActiveSheets,
|
||||
fit_to_page: false,
|
||||
preview_page: 0,
|
||||
preview: None,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::{
|
||||
Align2, Backstage, Icon, Json, Outcome, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme, vec2,
|
||||
Align2, Backstage, Icon, Json, Outcome, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme,
|
||||
vec2,
|
||||
};
|
||||
|
||||
/// Builds the print scope and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action.
|
||||
@@ -10,11 +11,19 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
dim(ui, lang.tr("No workbook is open."));
|
||||
return;
|
||||
};
|
||||
let mut params = json!({"sheets": if bs.print_all { "all" } else { "active" }});
|
||||
let mut params = json!({"sheets": if bs.print_scope == PrintScope::EntireWorkbook { "all" } else { "active" }});
|
||||
// The selection is not part of the document revision, so it goes in the preview's key.
|
||||
let mut selection = String::new();
|
||||
if bs.print_scope == PrintScope::Selection
|
||||
&& let Some(d) = app.session.active()
|
||||
{
|
||||
selection = d.selection.a1();
|
||||
params["range"] = json!(selection);
|
||||
}
|
||||
if bs.fit_to_page {
|
||||
params["fitToPage"] = json!(true);
|
||||
}
|
||||
let key = (uid, revision, bs.print_all, bs.fit_to_page);
|
||||
let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page);
|
||||
if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) {
|
||||
let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null);
|
||||
bs.preview = Some((key, preview));
|
||||
@@ -34,14 +43,13 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
out.close = app.services.print_native.is_none();
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
let scope = if bs.print_all { "Print Entire Workbook" } else { "Print Active Sheets" };
|
||||
egui::ComboBox::from_id_salt("backstage_print_scope")
|
||||
.width(230.0)
|
||||
.selected_text(lang.tr(scope))
|
||||
.selected_text(lang.tr(bs.print_scope.label()))
|
||||
.show_ui(ui, |ui| {
|
||||
for (all, label) in [(false, "Print Active Sheets"), (true, "Print Entire Workbook")] {
|
||||
if ui.selectable_label(bs.print_all == all, lang.tr(label)).clicked() {
|
||||
bs.print_all = all;
|
||||
for scope in PrintScope::ALL {
|
||||
if ui.selectable_label(bs.print_scope == scope, lang.tr(scope.label())).clicked() {
|
||||
bs.print_scope = scope;
|
||||
bs.preview_page = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,6 +280,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
("ui.window.close", "Close Window", ""),
|
||||
("ui.window.beginResize", "Resize Window", "{direction: north|south|east|west|northeast|northwest|southeast|southwest}"),
|
||||
("ui.dialog", "Open Dialog", ""),
|
||||
(
|
||||
"ui.selectionMode",
|
||||
"Extend or Add to Selection",
|
||||
"{mode?: \"extend\" (F8) | \"add\" (Shift+F8) | \"off\"} → {mode}; {} reports the mode",
|
||||
),
|
||||
("ui.backstage", "File (Backstage view)", "{page?: home|new|open|info|saveAs|print|export|options|account|close}"),
|
||||
(
|
||||
"ui.printSettings",
|
||||
|
||||
@@ -458,6 +458,22 @@ impl Dialog {
|
||||
// An empty password from the start, so OK on the untouched field says "incorrect"
|
||||
// rather than asking for the password again.
|
||||
let mut values = params.clone();
|
||||
// A workbook with a password to modify asks for that, or a read-only open.
|
||||
if p("modify").as_bool().unwrap_or(false) {
|
||||
values["modifyPassword"] = json!("");
|
||||
values["readOnly"] = json!(false);
|
||||
return Some(Dialog::form(
|
||||
"openPassword",
|
||||
"Password",
|
||||
"file.open",
|
||||
vec![
|
||||
Note(format!("'{file}' is reserved by its author. Enter the password to modify it, or open it read-only.")),
|
||||
Password { key: "modifyPassword", label: "Password:" },
|
||||
Check { key: "readOnly", label: "Read Only" },
|
||||
],
|
||||
values,
|
||||
));
|
||||
}
|
||||
values["password"] = json!("");
|
||||
Dialog::form(
|
||||
"openPassword",
|
||||
@@ -515,7 +531,13 @@ impl Dialog {
|
||||
Choice {
|
||||
key: "operation",
|
||||
label: "Operation",
|
||||
options: vec![("none", "None"), ("add", "Add"), ("subtract", "Subtract"), ("multiply", "Multiply"), ("divide", "Divide")],
|
||||
options: vec![
|
||||
("none", "None"),
|
||||
("add", "Paste Special|Add"),
|
||||
("subtract", "Subtract"),
|
||||
("multiply", "Multiply"),
|
||||
("divide", "Divide"),
|
||||
],
|
||||
},
|
||||
Check { key: "skipBlanks", label: "Skip blanks" },
|
||||
Check { key: "transpose", label: "Transpose (E)" },
|
||||
@@ -657,7 +679,7 @@ impl Dialog {
|
||||
vec![
|
||||
Check { key: "tab", label: "Tab" },
|
||||
Check { key: "semicolon", label: "Semicolon" },
|
||||
Check { key: "comma", label: "Comma" },
|
||||
Check { key: "comma", label: "Text to Columns|Comma" },
|
||||
Check { key: "space", label: "Space" },
|
||||
Text { key: "other", label: "Other:" },
|
||||
Check { key: "treatConsecutive", label: "Treat consecutive delimiters as one" },
|
||||
@@ -1011,6 +1033,7 @@ impl Dialog {
|
||||
dialog
|
||||
}
|
||||
"manageRules" => Dialog::custom("manageRules", "Conditional Formatting Rules Manager", json!({})),
|
||||
"newFormattingRule" => cond_format_rules::new_rule_dialog(app, ¶ms),
|
||||
"commandSearch" => Dialog::custom("commandSearch", "Search Commands", json!({})),
|
||||
"agents" => Dialog::custom("agents", "Agent Control", json!({})),
|
||||
"about" => {
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::show::ok_cancel;
|
||||
use super::{Color32, Dialog, Icon, Json, Sense, SheetApp, Stroke, StrokeKind, icons, json, vec2};
|
||||
|
||||
/// Every chart type the All Charts tab offers: `(type, subtype, label)` for `insert.chart`.
|
||||
const ALL_CHARTS: [(&str, &str, &str); 21] = [
|
||||
const ALL_CHARTS: [(&str, &str, &str); 23] = [
|
||||
("column", "", "Clustered Column"),
|
||||
("column", "stacked", "Stacked Column"),
|
||||
("column", "stacked100", "100% Stacked Column"),
|
||||
@@ -12,6 +12,8 @@ const ALL_CHARTS: [(&str, &str, &str); 21] = [
|
||||
("line", "", "Line"),
|
||||
("line", "markers", "Line with Markers"),
|
||||
("line", "stacked", "Stacked Line"),
|
||||
("line", "stacked100", "100% Stacked Line"),
|
||||
("line", "stacked100Markers", "100% Stacked Line with Markers"),
|
||||
("pie", "", "Pie"),
|
||||
("doughnut", "", "Doughnut"),
|
||||
("area", "", "Area"),
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
use super::{Json, SheetApp, json};
|
||||
//! Conditional formatting dialogs: the rules manager, and the New / Edit Formatting Rule editor
|
||||
//! with its 2- and 3-colour scale stops.
|
||||
|
||||
use super::show::{ok_cancel_enabled, track_pick};
|
||||
use super::{Dialog, Json, RefPick, SheetApp, json};
|
||||
use egui::{Color32, Sense, Stroke, StrokeKind, vec2};
|
||||
use gridcraft_engine::core::{CellRef, RangeRef};
|
||||
use gridcraft_engine::model::{CfRule, CfValueKind, Color as CellColor, Theme};
|
||||
|
||||
/// The list scrolls inside the dialog: a sheet read from a file can carry thousands of rules, and
|
||||
/// a list laid out in full made the window as tall as all of them (issue #3321).
|
||||
const LIST_HEIGHT: f32 = 360.0;
|
||||
|
||||
pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
let lang = app.ui.language;
|
||||
// Read the rules in place: running `home.manageRules` for them each frame copied and
|
||||
// serialised every rule and journaled a step 60 times a second.
|
||||
let count = app.session.active().and_then(|d| d.wb.active()).map_or(0, |sh| sh.cond_formats.len());
|
||||
@@ -13,15 +21,20 @@ pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
return;
|
||||
}
|
||||
let mut action: Option<Json> = None;
|
||||
let mut edit: Option<(usize, Json)> = None;
|
||||
let row_height = ui.spacing().interact_size.y;
|
||||
egui::ScrollArea::both().max_height(LIST_HEIGHT).auto_shrink([false, true]).show_rows(ui, row_height, count, |ui, rows| {
|
||||
let Some(sh) = app.session.active().and_then(|d| d.wb.active()) else { return };
|
||||
for i in rows {
|
||||
let Some(cf) = sh.cond_formats.get(i) else { break };
|
||||
let kind = serde_json::to_value(&cf.rule).ok().and_then(|r| r.as_object().and_then(|o| o.keys().next().cloned())).unwrap_or_default();
|
||||
let rule = serde_json::to_value(&cf.rule).unwrap_or(Json::Null);
|
||||
let kind = rule.as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default();
|
||||
let ranges = cf.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().join(",");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!("{}. {kind} applies to {ranges}", i + 1));
|
||||
if kind.contains("ColorScale") && ui.small_button(lang.tr("Edit")).clicked() {
|
||||
edit = Some((i, rule.clone()));
|
||||
}
|
||||
if ui.small_button("▲").clicked() {
|
||||
action = Some(json!({"moveUp": i}));
|
||||
}
|
||||
@@ -34,7 +47,443 @@ pub(super) fn manage_rules(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some((i, rule)) = edit {
|
||||
app.open_dialog("newFormattingRule", json!({"edit": i, "rule": rule}));
|
||||
}
|
||||
if let Some(params) = action {
|
||||
app.run_or_alert("home.manageRules", params);
|
||||
}
|
||||
}
|
||||
|
||||
/// The New Formatting Rule dialog, or the rule editor Manage Rules opens on an existing colour
|
||||
/// scale (`edit` and `rule` in the params).
|
||||
pub(super) fn new_rule_dialog(app: &mut SheetApp, params: &Json) -> Dialog {
|
||||
let theme = app.session.active().map(|d| d.wb.theme.clone()).unwrap_or_default();
|
||||
// Excel titles the Manage Rules path "Edit Formatting Rule": OK replaces the rule rather than
|
||||
// adding one, and the window should say so.
|
||||
let editing = params.get("edit").is_some();
|
||||
let title = if editing { "Edit Formatting Rule" } else { "New Formatting Rule" };
|
||||
let mut d = Dialog::custom("newFormattingRule", title, new_rule_defaults(params, &theme));
|
||||
d.command = Some(if editing { "home.manageRules" } else { "home.conditionalFormat" });
|
||||
// The sheet and selection the rule was opened on: Excel's "Applies to" stays put
|
||||
// even if the selection moves or another sheet is shown before OK.
|
||||
let (sheet, applies_to) = app
|
||||
.session
|
||||
.active()
|
||||
.map(|doc| {
|
||||
(
|
||||
doc.wb.active().map(|sh| sh.name.clone()).unwrap_or_default(),
|
||||
doc.selection.ranges.iter().map(RangeRef::a1).collect::<Vec<_>>().join(","),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
d.values.insert("sheet".into(), json!(sheet));
|
||||
d.values.insert("applies_to".into(), json!(applies_to));
|
||||
sync_rule_pick(&mut d);
|
||||
d
|
||||
}
|
||||
|
||||
/// The command params OK sends: the rule the editor describes, on the scope it opened with.
|
||||
pub(super) fn rule_params(d: &Dialog) -> Json {
|
||||
let mut out = match d.values.get("ruleType").and_then(Json::as_str).unwrap_or("allCells") {
|
||||
"formula" => {
|
||||
let formula = d.values.get("formula").and_then(Json::as_str).unwrap_or("").to_string();
|
||||
let preset = d.values.get("preset").and_then(Json::as_str).unwrap_or("lightRedFillDarkRedText");
|
||||
json!({"rule": {"type": "expression", "formula": formula, "preset": preset}})
|
||||
}
|
||||
_ => {
|
||||
let stops: Vec<Json> = d.values.get("stops").and_then(Json::as_array).map(|a| a.iter().map(cf_stop_params).collect()).unwrap_or_default();
|
||||
json!({"rule": {"type": "colorScale", "stops": stops}})
|
||||
}
|
||||
};
|
||||
// The rule covers the sheet and range the dialog opened on, not whatever the
|
||||
// selection shows now: a formula rule's pick box holds the same opening scope, and
|
||||
// colour scales have no pick box but need it just as much to edit in place.
|
||||
let sheet = d.values.get("sheet").and_then(Json::as_str).unwrap_or_default();
|
||||
let applies_to = d.values.get("applies_to").and_then(Json::as_str).unwrap_or_default();
|
||||
if !sheet.is_empty() && !applies_to.is_empty() {
|
||||
out["sheet"] = json!(sheet);
|
||||
out["range"] = json!(applies_to);
|
||||
}
|
||||
if let Some(edit) = d.values.get("edit").and_then(Json::as_u64) {
|
||||
out["edit"] = json!(edit);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Draws the rule-type list and the editor for the chosen type, then OK/Cancel. OK stays disabled
|
||||
/// while the rule description is incomplete (a formula stop or rule with no formula, or a rule
|
||||
/// type this PR does not implement yet).
|
||||
pub(super) fn new_formatting_rule(ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
|
||||
let lang = crate::i18n::current(ui.ctx());
|
||||
ui.label(lang.tr("Select a Rule Type"));
|
||||
let mut rule_type = d.values.get("ruleType").and_then(Json::as_str).unwrap_or("allCells").to_string();
|
||||
for (v, label) in RULE_TYPES {
|
||||
ui.selectable_value(&mut rule_type, (*v).to_string(), lang.tr(label));
|
||||
}
|
||||
d.values.insert("ruleType".into(), json!(rule_type));
|
||||
// Only a formula rule's box takes grid references, and it keeps the sheet and "Applies to"
|
||||
// range the dialog opened on.
|
||||
sync_rule_pick(d);
|
||||
ui.separator();
|
||||
ui.label(lang.tr("Edit the Rule Description"));
|
||||
let supported = match rule_type.as_str() {
|
||||
"allCells" => {
|
||||
colour_scale_editor(ui, d, lang);
|
||||
// A formula stop needs a formula: one whose value is missing, not a string, or
|
||||
// blank would create a rule that never applies. Other stops confirm as they are.
|
||||
d.values.get("stops").and_then(Json::as_array).is_none_or(|stops| {
|
||||
stops.iter().all(|s| {
|
||||
s.get("type").and_then(Json::as_str) != Some("formula")
|
||||
|| s.get("value").and_then(Json::as_str).is_some_and(|f| !f.trim().is_empty())
|
||||
})
|
||||
})
|
||||
}
|
||||
"formula" => {
|
||||
ui.label(lang.tr("Format values where this formula is true:"));
|
||||
let mut formula = d.values.get("formula").and_then(Json::as_str).unwrap_or("").to_string();
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut formula).desired_width(360.0));
|
||||
if r.changed() {
|
||||
d.values.insert("formula".into(), json!(formula.clone()));
|
||||
}
|
||||
if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key == "formula") {
|
||||
track_pick(pick, &r, r.changed());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(lang.tr("with"));
|
||||
preset_combo(ui, d, lang);
|
||||
});
|
||||
// A formula rule with no formula never applies; OK waits for one.
|
||||
!formula.trim().is_empty()
|
||||
}
|
||||
_ => {
|
||||
ui.label(lang.tr("This rule type isn't available yet."));
|
||||
false
|
||||
}
|
||||
};
|
||||
ok_cancel_enabled(ui, confirm, open, supported);
|
||||
}
|
||||
|
||||
fn cf_stop_json(kind: CfValueKind, color: &CellColor, theme: &Theme) -> Json {
|
||||
let (ty, value) = match kind {
|
||||
CfValueKind::Min => ("min", Json::Null),
|
||||
CfValueKind::Max => ("max", Json::Null),
|
||||
CfValueKind::Number(n) => ("num", json!(n)),
|
||||
CfValueKind::Percent(n) => ("percent", json!(n)),
|
||||
CfValueKind::Percentile(n) => ("percentile", json!(n)),
|
||||
CfValueKind::Formula(f) => ("formula", json!(f)),
|
||||
};
|
||||
let hex = color.hex(theme).unwrap_or_else(|| "#000000".into());
|
||||
// `source` keeps a theme colour by reference: OK without touching the picker sends it back
|
||||
// unchanged, instead of freezing the theme's current RGB into the rule.
|
||||
json!({"type": ty, "value": value, "color": hex.clone(), "source": color, "sourceHex": hex})
|
||||
}
|
||||
|
||||
/// The stop as the engine takes it, dropping the dialog's bookkeeping. A colour the user did not
|
||||
/// change keeps its original theme reference; a changed one is sent as the picked RGB.
|
||||
fn cf_stop_params(stop: &Json) -> Json {
|
||||
let mut obj = stop.as_object().cloned().unwrap_or_default();
|
||||
let source = obj.remove("source").and_then(|v| serde_json::from_value::<CellColor>(v).ok());
|
||||
let source_hex = obj.remove("sourceHex").and_then(|v| v.as_str().map(str::to_string));
|
||||
if let (Some(source), Some(source_hex)) = (source, source_hex)
|
||||
&& obj.get("color").and_then(Json::as_str).is_some_and(|c| c.eq_ignore_ascii_case(&source_hex))
|
||||
{
|
||||
obj.insert(
|
||||
"color".into(),
|
||||
match source {
|
||||
CellColor::Auto => json!("auto"),
|
||||
CellColor::Rgb(v) => json!(format!("#{v:06X}")),
|
||||
CellColor::Theme(i, tint) => json!({"theme": i, "tint": tint as f64 / 1000.0}),
|
||||
},
|
||||
);
|
||||
}
|
||||
Json::Object(obj)
|
||||
}
|
||||
|
||||
fn default_scale_stops(style: &str) -> Vec<Json> {
|
||||
if style == "2color" {
|
||||
vec![json!({"type": "min", "value": null, "color": "#F8696B"}), json!({"type": "max", "value": null, "color": "#63BE7B"})]
|
||||
} else {
|
||||
vec![
|
||||
json!({"type": "min", "value": null, "color": "#F8696B"}),
|
||||
json!({"type": "percentile", "value": 50, "color": "#FFEB84"}),
|
||||
json!({"type": "max", "value": null, "color": "#63BE7B"}),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn new_rule_defaults(params: &Json, theme: &Theme) -> Json {
|
||||
// Excel's New Formatting Rule opens on the first type. Manage Rules edits a colour scale,
|
||||
// so an edit always stays on that branch.
|
||||
let mut rule_type = params.get("ruleType").and_then(Json::as_str).unwrap_or("allCells").to_string();
|
||||
if params.get("edit").is_some() || !matches!(rule_type.as_str(), "allCells" | "formula") {
|
||||
rule_type = "allCells".into();
|
||||
}
|
||||
let mut style = params.get("style").and_then(Json::as_str).unwrap_or("3color").to_string();
|
||||
if !matches!(style.as_str(), "2color" | "3color") {
|
||||
style = "3color".into();
|
||||
}
|
||||
let existing = params.get("rule").and_then(|rule| serde_json::from_value::<CfRule>(rule.clone()).ok()).and_then(|rule| match rule {
|
||||
CfRule::ColorScale { stops } if (2..=3).contains(&stops.len()) => {
|
||||
Some(stops.into_iter().map(|(kind, color)| cf_stop_json(kind, &color, theme)).collect::<Vec<_>>())
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let stops = match existing {
|
||||
Some(stops) => {
|
||||
style = if stops.len() == 2 { "2color".into() } else { "3color".into() };
|
||||
stops
|
||||
}
|
||||
None => default_scale_stops(&style),
|
||||
};
|
||||
json!({
|
||||
"ruleType": rule_type,
|
||||
"style": style,
|
||||
"stops": stops,
|
||||
"formula": "",
|
||||
"preset": "lightRedFillDarkRedText",
|
||||
"edit": params.get("edit").cloned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_hex_color(s: &str) -> Color32 {
|
||||
let h = s.trim_start_matches('#');
|
||||
u32::from_str_radix(h.get(..6).unwrap_or("000000"), 16)
|
||||
.map(|v| Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))
|
||||
.unwrap_or(Color32::WHITE)
|
||||
}
|
||||
|
||||
fn hex_color(c: Color32) -> String {
|
||||
format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())
|
||||
}
|
||||
|
||||
fn scale_preview(ui: &mut egui::Ui, stops: &[Json]) {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(280.0, 26.0), Sense::hover());
|
||||
let colors: Vec<Color32> = stops.iter().map(|s| parse_hex_color(s.get("color").and_then(Json::as_str).unwrap_or("#FFFFFF"))).collect();
|
||||
if colors.is_empty() {
|
||||
return;
|
||||
}
|
||||
let n = 64;
|
||||
for i in 0..n {
|
||||
let t = i as f32 / (n - 1) as f32;
|
||||
let pos = t * (colors.len() - 1) as f32;
|
||||
let lo = pos.floor() as usize;
|
||||
let hi = (lo + 1).min(colors.len() - 1);
|
||||
let f = pos - lo as f32;
|
||||
let a = colors[lo];
|
||||
let b = colors[hi];
|
||||
let c = Color32::from_rgb(
|
||||
(a.r() as f32 + (b.r() as f32 - a.r() as f32) * f) as u8,
|
||||
(a.g() as f32 + (b.g() as f32 - a.g() as f32) * f) as u8,
|
||||
(a.b() as f32 + (b.b() as f32 - a.b() as f32) * f) as u8,
|
||||
);
|
||||
let x = rect.left() + rect.width() * i as f32 / n as f32;
|
||||
ui.painter().rect_filled(egui::Rect::from_min_size(egui::pos2(x, rect.top()), vec2(rect.width() / n as f32 + 0.5, rect.height())), 0.0, c);
|
||||
}
|
||||
ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::from_gray(190)), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
fn stop_combo(ui: &mut egui::Ui, id: (&'static str, usize), current: &mut String, options: &[(&str, &str)], lang: crate::i18n::Language) {
|
||||
let shown = options.iter().find(|(v, _)| *v == current).map(|(_, l)| lang.tr(l)).unwrap_or(current.as_str());
|
||||
egui::ComboBox::from_id_salt(id).selected_text(shown).width(120.0).show_ui(ui, |ui| {
|
||||
for (v, l) in options {
|
||||
if ui.selectable_label(current == v, lang.tr(l)).clicked() {
|
||||
*current = (*v).to_string();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn colour_scale_editor(ui: &mut egui::Ui, d: &mut Dialog, lang: crate::i18n::Language) {
|
||||
ui.label(lang.tr("Format all cells based on their values"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(lang.tr("Format Style:"));
|
||||
let mut style = d.values.get("style").and_then(Json::as_str).unwrap_or("3color").to_string();
|
||||
egui::ComboBox::from_id_salt("newFormattingRule.style")
|
||||
.selected_text(lang.tr(if style == "2color" { "2-Color Scale" } else { "3-Color Scale" }))
|
||||
.width(150.0)
|
||||
.show_ui(ui, |ui| {
|
||||
for (v, l) in [("2color", "2-Color Scale"), ("3color", "3-Color Scale")] {
|
||||
if ui.selectable_label(style == v, lang.tr(l)).clicked() {
|
||||
style = v.to_string();
|
||||
}
|
||||
}
|
||||
});
|
||||
d.values.insert("style".into(), json!(style));
|
||||
// The midpoint comes back as the default #FFEB84 rather than a copy of the minimum's
|
||||
// colour, so 3 → 2 → 3 restores Excel's scale.
|
||||
let mut stops = d.values.get("stops").and_then(Json::as_array).cloned().unwrap_or_default();
|
||||
if style == "2color" && stops.len() == 3 {
|
||||
stops.remove(1);
|
||||
} else if style == "3color" && stops.len() == 2 {
|
||||
stops.insert(1, json!({"type": "percentile", "value": 50, "color": "#FFEB84"}));
|
||||
}
|
||||
d.values.insert("stops".into(), Json::Array(stops));
|
||||
});
|
||||
let mut stops = d.values.get("stops").and_then(Json::as_array).cloned().unwrap_or_default();
|
||||
let count = stops.len();
|
||||
for i in 0..count {
|
||||
let mut obj = stops.get(i).and_then(Json::as_object).cloned().unwrap_or_default();
|
||||
let mut ty = obj.get("type").and_then(Json::as_str).unwrap_or("num").to_string();
|
||||
let options: &[(&str, &str)] = if i == 0 {
|
||||
&[("min", "Lowest value"), ("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
|
||||
} else if i + 1 == count {
|
||||
&[("max", "Highest value"), ("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
|
||||
} else {
|
||||
&[("num", "Number"), ("percent", "Percent"), ("percentile", "Percentile"), ("formula", "Formula")]
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(lang.tr(if i == 0 {
|
||||
"Minimum"
|
||||
} else if i + 1 == count {
|
||||
"Maximum"
|
||||
} else {
|
||||
"Midpoint"
|
||||
}));
|
||||
stop_combo(ui, ("newFormattingRule.stopType", i), &mut ty, options, lang);
|
||||
match ty.as_str() {
|
||||
"min" | "max" => {
|
||||
ui.label(lang.tr(if ty == "min" { "Lowest value" } else { "Highest value" }));
|
||||
}
|
||||
"formula" => {
|
||||
let mut f = obj.get("value").and_then(Json::as_str).unwrap_or("").to_string();
|
||||
ui.add(egui::TextEdit::singleline(&mut f).desired_width(120.0).hint_text(lang.tr("Formula")));
|
||||
// Store what the field shows as a string even when it was not edited: a
|
||||
// stop switched from Number still holds that number, which is no formula.
|
||||
obj.insert("value".into(), json!(f));
|
||||
}
|
||||
_ => {
|
||||
let mut n = obj.get("value").and_then(Json::as_f64).unwrap_or(0.0);
|
||||
let speed = if ty == "num" { 1.0 } else { 0.1 };
|
||||
if ui.add(egui::DragValue::new(&mut n).speed(speed).range(if ty == "num" { f64::MIN..=f64::MAX } else { 0.0..=100.0 })).changed()
|
||||
{
|
||||
obj.insert("value".into(), json!(n));
|
||||
}
|
||||
// A numeric stop must carry a number: a stop switched from Lowest or
|
||||
// Highest value still holds `null`, which the engine refuses.
|
||||
if obj.get("value").and_then(Json::as_f64).is_none() {
|
||||
obj.insert("value".into(), json!(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = parse_hex_color(obj.get("color").and_then(Json::as_str).unwrap_or("#FFFFFF"));
|
||||
let mut rgb = [c.r(), c.g(), c.b()];
|
||||
if ui.color_edit_button_srgb(&mut rgb).changed() {
|
||||
obj.insert("color".into(), json!(hex_color(Color32::from_rgb(rgb[0], rgb[1], rgb[2]))));
|
||||
}
|
||||
});
|
||||
obj.insert("type".into(), json!(ty));
|
||||
stops[i] = Json::Object(obj);
|
||||
}
|
||||
d.values.insert("stops".into(), Json::Array(stops.clone()));
|
||||
scale_preview(ui, &stops);
|
||||
}
|
||||
|
||||
fn preset_combo(ui: &mut egui::Ui, d: &mut Dialog, lang: crate::i18n::Language) {
|
||||
const PRESETS: &[(&str, &str)] = &[
|
||||
("lightRedFillDarkRedText", "Light Red Fill with Dark Red Text"),
|
||||
("yellowFillDarkYellowText", "Yellow Fill with Dark Yellow Text"),
|
||||
("greenFillDarkGreenText", "Green Fill with Dark Green Text"),
|
||||
("lightRedFill", "Light Red Fill"),
|
||||
("redText", "Red Text"),
|
||||
("redBorder", "Red Border"),
|
||||
];
|
||||
let mut preset = d.values.get("preset").and_then(Json::as_str).unwrap_or("lightRedFillDarkRedText").to_string();
|
||||
let shown = PRESETS.iter().find(|(v, _)| *v == preset).map(|(_, l)| lang.tr(l)).unwrap_or(preset.as_str());
|
||||
egui::ComboBox::from_id_salt("newFormattingRule.preset").selected_text(shown).width(260.0).show_ui(ui, |ui| {
|
||||
for (v, l) in PRESETS {
|
||||
if ui.selectable_label(preset == *v, lang.tr(l)).clicked() {
|
||||
preset = (*v).to_string();
|
||||
}
|
||||
}
|
||||
});
|
||||
d.values.insert("preset".into(), json!(preset));
|
||||
}
|
||||
|
||||
/// Excel's six rule types, in its order.
|
||||
const RULE_TYPES: &[(&str, &str)] = &[
|
||||
("allCells", "Format all cells based on their values"),
|
||||
("cellsThatContain", "Format only cells that contain"),
|
||||
("topBottom", "Format only top or bottom ranked values"),
|
||||
("aboveBelow", "Format only values that are above or below average"),
|
||||
("uniqueDuplicate", "Format only unique or duplicate values"),
|
||||
("formula", "Use a formula to determine which cells to format"),
|
||||
];
|
||||
|
||||
/// Gives a formula rule's box point mode, on the sheet and selection the dialog opened on;
|
||||
/// other rule types take clicks on the grid as selection.
|
||||
fn sync_rule_pick(d: &mut Dialog) {
|
||||
if d.values.get("ruleType").and_then(Json::as_str) != Some("formula") {
|
||||
d.pick = None;
|
||||
return;
|
||||
}
|
||||
if d.pick.is_some() {
|
||||
return;
|
||||
}
|
||||
let sheet = d.values.get("sheet").and_then(Json::as_str).unwrap_or_default().to_string();
|
||||
let applies_to = d.values.get("applies_to").and_then(Json::as_str).unwrap_or_default().to_string();
|
||||
d.pick = Some(RefPick { key: "formula", sheet, caret: 0, point: None, anchor: CellRef::new(0, 0), refocus: false, applies_to });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn formula_rule_picks_references_and_keeps_the_opening_range() {
|
||||
let mut session = gridcraft_engine::Session::default();
|
||||
session.new_workbook();
|
||||
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
|
||||
let mut d = Dialog::open(&mut app, "newFormattingRule", json!({"ruleType": "formula"})).unwrap();
|
||||
assert!(d.picks_references());
|
||||
assert_eq!(d.pick.as_ref().unwrap().sheet, sheet);
|
||||
|
||||
// A grid click writes the reference into the formula box.
|
||||
d.pick_reference(CellRef::new(0, 0), &sheet, false);
|
||||
assert_eq!(d.values["formula"], "=$A$1");
|
||||
|
||||
// Moving the selection before OK must not move the rule.
|
||||
app.session.execute("selection.set", json!({"range": "D2:E6"})).unwrap();
|
||||
let params = super::super::build_params(&d);
|
||||
assert_eq!(params["sheet"], sheet.as_str());
|
||||
assert_eq!(params["range"], "B2:C5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rule_switched_to_formula_picks_on_the_opening_scope() {
|
||||
let mut session = gridcraft_engine::Session::default();
|
||||
session.new_workbook();
|
||||
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
|
||||
// The dialog opens on the default (colour scale) type; choosing the formula type later
|
||||
// turns point mode on, still on the sheet and range it opened with.
|
||||
let mut d = Dialog::open(&mut app, "newFormattingRule", json!({})).unwrap();
|
||||
assert!(!d.picks_references());
|
||||
d.values.insert("ruleType".into(), json!("formula"));
|
||||
sync_rule_pick(&mut d);
|
||||
assert!(d.picks_references());
|
||||
|
||||
app.session.execute("selection.set", json!({"range": "D2:E6"})).unwrap();
|
||||
let params = super::super::build_params(&d);
|
||||
assert_eq!(params["sheet"], sheet.as_str());
|
||||
assert_eq!(params["range"], "B2:C5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_scale_rule_keeps_the_opening_range_without_grid_references() {
|
||||
let mut session = gridcraft_engine::Session::default();
|
||||
session.new_workbook();
|
||||
session.execute("selection.set", json!({"range": "B2:C5"})).unwrap();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap().name.clone();
|
||||
let d = Dialog::open(&mut app, "newFormattingRule", json!({})).unwrap();
|
||||
assert!(!d.picks_references());
|
||||
// No pick box, but the rule still covers the range and sheet the dialog opened on.
|
||||
let params = super::super::build_params(&d);
|
||||
assert_eq!(params["sheet"], sheet.as_str());
|
||||
assert_eq!(params["range"], "B2:C5");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ pub(crate) fn build_params(d: &Dialog) -> Json {
|
||||
v["range"] = json!(pick.applies_to);
|
||||
}
|
||||
}
|
||||
"newFormattingRule" => v = super::cond_format_rules::rule_params(d),
|
||||
"series" => {
|
||||
if let Some(s) = d.values.get("stop").and_then(Json::as_str).and_then(|s| s.parse::<f64>().ok()) {
|
||||
v["stop"] = json!(s);
|
||||
@@ -121,6 +122,27 @@ pub(crate) fn build_params(d: &Dialog) -> Json {
|
||||
v
|
||||
}
|
||||
|
||||
fn command_error(app: &mut SheetApp, d: &mut Dialog, e: String) {
|
||||
if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) {
|
||||
// Data Analysis asks before replacing data in its output range.
|
||||
d.values.insert("askOverwrite".into(), json!(true));
|
||||
} else if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) {
|
||||
// The decryption password opened an encrypted, reserved workbook; ask for the modify password.
|
||||
let mut params = Json::Object(d.values.clone());
|
||||
params["modify"] = json!(true);
|
||||
if let Some(next) = Dialog::open(app, "openPassword", params) {
|
||||
*d = Dialog { back: d.back.take(), ..next };
|
||||
}
|
||||
} else if d.name == "openPassword" {
|
||||
// A wrong password: say so, clear the field and stay open for another try.
|
||||
let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" };
|
||||
d.values.insert(field.into(), json!(""));
|
||||
app.message = Some((d.title.clone(), crate::clean_error(&e)));
|
||||
} else {
|
||||
app.message = Some((d.title.clone(), crate::clean_error(&e)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes and draws the active dialog, dispatches its body by name, consumes picture-inbox results, runs OK/confirm commands, handles Esc/close and restores the back-dialog stack.
|
||||
pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let Some(mut d) = app.dialog.take() else { return };
|
||||
@@ -149,7 +171,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let width = match d.name.as_str() {
|
||||
"formatCells" => 560.0,
|
||||
"about" => 820.0,
|
||||
"insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "journal" | "agents" | "equation" => 520.0,
|
||||
"insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "newFormattingRule" | "journal" | "agents" | "equation" => 520.0,
|
||||
"macros" => 480.0,
|
||||
"recommendedCharts" => 600.0,
|
||||
"analysisToolPak" => 420.0,
|
||||
@@ -195,6 +217,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
"nameManager" => name_manager(app, ui, &mut d, &mut open),
|
||||
"pasteName" => paste_name(app, ui, &mut d, &mut confirm, &mut open),
|
||||
"manageRules" => manage_rules(app, ui),
|
||||
"newFormattingRule" => super::cond_format_rules::new_formatting_rule(ui, &mut d, &mut confirm, &mut open),
|
||||
"recommendedCharts" => recommended_charts(app, ui, &mut d, &mut confirm, &mut open),
|
||||
"selectData" => select_data(app, ui, &mut d, &mut confirm, &mut open),
|
||||
"commandSearch" => command_search(app, ui, &mut d, &mut confirm),
|
||||
@@ -442,16 +465,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
app.after_open(path.as_deref(), &r);
|
||||
}
|
||||
}
|
||||
// Data Analysis asks before replacing data in its output range.
|
||||
Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => {
|
||||
d.values.insert("askOverwrite".into(), json!(true));
|
||||
}
|
||||
// A wrong password: say so, clear the field and stay open for another try.
|
||||
Err(e) if d.name == "openPassword" => {
|
||||
d.values.insert("password".into(), json!(""));
|
||||
app.message = Some((d.title.clone(), crate::clean_error(&e)));
|
||||
}
|
||||
Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))),
|
||||
Err(e) => command_error(app, &mut d, e),
|
||||
}
|
||||
} else if confirm {
|
||||
open = false;
|
||||
@@ -524,6 +538,11 @@ pub(super) fn open_confirmed_link(app: &mut SheetApp, d: &Dialog) -> Result<(),
|
||||
}
|
||||
|
||||
pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool) {
|
||||
ok_cancel_enabled(ui, confirm, open, true);
|
||||
}
|
||||
|
||||
/// Like [`ok_cancel`], but OK (and Enter) do nothing while `enabled` is false.
|
||||
pub(super) fn ok_cancel_enabled(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool, enabled: bool) {
|
||||
ui.add_space(8.0);
|
||||
// A row as tall as the buttons: a right-to-left layout straight in the window takes all the
|
||||
// height it is offered, which stretched every form dialog to the screen's height.
|
||||
@@ -531,14 +550,15 @@ pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool)
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let lang = crate::i18n::current(ui.ctx());
|
||||
let t = crate::theme::Tokens::get(ui.ctx());
|
||||
let ok = ui.add(egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
|
||||
if ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter)) {
|
||||
let ok =
|
||||
ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
|
||||
if enabled && (ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter))) {
|
||||
*confirm = true;
|
||||
}
|
||||
if ui.button(format!(" {} ", lang.tr("Cancel"))).clicked() {
|
||||
*open = false;
|
||||
}
|
||||
})
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -571,7 +591,7 @@ pub(super) fn take_first_focus(d: &mut Dialog, r: &egui::Response) {
|
||||
|
||||
/// Keeps a picking formula box's caret, and gives it the keyboard back after a grid click put a
|
||||
/// reference in it (the click took the focus), its caret after the reference.
|
||||
fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) {
|
||||
pub(super) fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) {
|
||||
if typed {
|
||||
pick.point = None;
|
||||
}
|
||||
|
||||
@@ -345,7 +345,10 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face
|
||||
let mut bound: Vec<String> = Vec::new();
|
||||
for (bold, italic) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let Some(primary) = pick_face(faces, bold, italic) else { continue };
|
||||
let role = role_key(family, bold, italic);
|
||||
let mut chain: Vec<String> = Vec::new();
|
||||
// The face the role's text is actually drawn in: the first one whose file could be read.
|
||||
let mut drawn: Option<&Face> = None;
|
||||
for face in [Some(primary), pick_face(faces, false, false)] {
|
||||
let Some(face) = face else { continue };
|
||||
let key = face_key(face);
|
||||
@@ -359,12 +362,15 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face
|
||||
fonts.font_data.insert(key.clone(), std::sync::Arc::new(fd));
|
||||
}
|
||||
chain.push(key);
|
||||
drawn.get_or_insert(face);
|
||||
}
|
||||
if chain.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(drawn) = drawn else { continue };
|
||||
// Imitate what the drawn face lacks: italic when it is upright; bold when it is the family's
|
||||
// plain face (the family has no bold of its own, or the bold file couldn't be read).
|
||||
let own_bold = pick_face(faces, false, italic).is_none_or(|plain| face_key(plain) != face_key(primary));
|
||||
set_synthetic(&role, SLANT, italic && !drawn.italic);
|
||||
set_synthetic(&role, BOLD, bold && (face_key(drawn) != face_key(primary) || !own_bold));
|
||||
chain.extend(base.iter().cloned());
|
||||
let role = role_key(family, bold, italic);
|
||||
fonts.families.insert(egui::FontFamily::Name(role.clone().into()), chain);
|
||||
bound.push(role);
|
||||
}
|
||||
@@ -389,6 +395,41 @@ pub fn is_bound(role: &str) -> bool {
|
||||
bound().read().unwrap_or_else(std::sync::PoisonError::into_inner).contains(role)
|
||||
}
|
||||
|
||||
/// Roles drawn with a face that lacks their slant or weight (Arial Black has one face only), as
|
||||
/// `{role}|slant` and `{role}|bold`. Excel imitates the missing style (observed in its PDF: a cell in
|
||||
/// Arial Black, bold italic, is slanted by 1/3 and outlined about 1/36 of its size thick).
|
||||
static SYNTHETIC: OnceLock<std::sync::RwLock<HashSet<String>>> = OnceLock::new();
|
||||
const SLANT: &str = "slant";
|
||||
const BOLD: &str = "bold";
|
||||
|
||||
fn synthetic() -> &'static std::sync::RwLock<HashSet<String>> {
|
||||
SYNTHETIC.get_or_init(|| std::sync::RwLock::new(HashSet::new()))
|
||||
}
|
||||
|
||||
fn set_synthetic(role: &str, style: &str, on: bool) {
|
||||
let mut set = synthetic().write().unwrap_or_else(|e| e.into_inner());
|
||||
let key = format!("{role}|{style}");
|
||||
if on {
|
||||
set.insert(key);
|
||||
} else {
|
||||
set.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_synthetic(role: &str, style: &str) -> bool {
|
||||
is_bound(role) && synthetic().read().unwrap_or_else(|e| e.into_inner()).contains(&format!("{role}|{style}"))
|
||||
}
|
||||
|
||||
/// Does italic text in this installed family have to be slanted when drawn (no italic face)?
|
||||
pub fn is_slanted(family: &str, bold: bool) -> bool {
|
||||
is_synthetic(&role_key(family, bold, true), SLANT)
|
||||
}
|
||||
|
||||
/// Does bold text in this installed family have to be thickened when drawn (no face of its own)?
|
||||
pub fn is_emboldened(family: &str, italic: bool) -> bool {
|
||||
is_synthetic(&role_key(family, true, italic), BOLD)
|
||||
}
|
||||
|
||||
/// Serializes tests that mutate the process-wide bound-family registry.
|
||||
#[cfg(test)]
|
||||
pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
@@ -490,6 +531,44 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_a_family_has_no_face_for_are_imitated() {
|
||||
let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-fonts-synthetic-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
// One font file stands in for every face; each face is its own (path, index) by its name.
|
||||
let face = |family: &str, file: &str, weight: f32, italic: bool| {
|
||||
let path = dir.join(file);
|
||||
std::fs::write(&path, epaint_default_fonts::UBUNTU_LIGHT).expect("write");
|
||||
Face { family: family.into(), names: vec![family.into()], path, index: 0, weight, italic }
|
||||
};
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
// Like Arial Black: one face, whatever its weight.
|
||||
let mut bound = bind_faces(&mut fonts, "One Face", &[face("One Face", "one.ttf", 900.0, false)]);
|
||||
let full = [
|
||||
face("Full", "full.ttf", 400.0, false),
|
||||
face("Full", "full-b.ttf", 700.0, false),
|
||||
face("Full", "full-i.ttf", 400.0, true),
|
||||
face("Full", "full-bi.ttf", 700.0, true),
|
||||
];
|
||||
bound.extend(bind_faces(&mut fonts, "Full", &full));
|
||||
// Bold and italic faces whose files can't be read: the regular face draws them, imitated.
|
||||
let gone = |file: &str, weight: f32, italic: bool| Face { path: dir.join(file), ..face("Gone", "gone.ttf", weight, italic) };
|
||||
let broken = [face("Gone", "gone.ttf", 400.0, false), gone("missing-b.ttf", 700.0, false), gone("missing-i.ttf", 400.0, true)];
|
||||
bound.extend(bind_faces(&mut fonts, "Gone", &broken));
|
||||
set_bound(bound);
|
||||
assert!(is_slanted("One Face", false) && is_slanted("One Face", true));
|
||||
assert!(is_emboldened("One Face", false) && is_emboldened("One Face", true));
|
||||
assert!(is_slanted("Gone", false) && is_emboldened("Gone", false), "the regular face stands in, imitated");
|
||||
assert!(!is_slanted("Full", false) && !is_slanted("Full", true), "its own italic faces are drawn as they are");
|
||||
assert!(!is_emboldened("Full", false) && !is_emboldened("Full", true), "its own bold faces are drawn as they are");
|
||||
assert!(!is_slanted("Not Bound", false) && !is_emboldened("Not Bound", false));
|
||||
set_bound([]);
|
||||
assert!(!is_slanted("One Face", false) && !is_emboldened("One Face", false), "nothing is imitated once unbound");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A font that is just a table directory and a `name` table holding `records` as
|
||||
/// `(Windows language id, name id, text)`: all [`file_faces`] reads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -327,6 +327,10 @@ pub struct GridState {
|
||||
pub cells_rect: Option<Rect>,
|
||||
/// Column and row of the clicked header cell, and where to open the menu.
|
||||
pub filter_menu: Option<(u32, u32, Pos2)>,
|
||||
/// Pending popup edits travel with this window and are dropped when its menu or window closes.
|
||||
pub filter_checks: Option<Vec<(String, bool)>>,
|
||||
pub filter_search: String,
|
||||
pub filter_buttons: Vec<egui::Id>,
|
||||
pub context_menu: Option<Pos2>,
|
||||
/// The frame a right-click opened `context_menu` in: that click's own press doesn't close it.
|
||||
pub context_menu_frame: u64,
|
||||
@@ -401,10 +405,71 @@ pub struct GridState {
|
||||
pub wheel_zoom: Option<WheelZoom>,
|
||||
/// A one-finger touch drag in progress: it pans the sheet instead of selecting.
|
||||
pub touch_pan: bool,
|
||||
/// F8 Extend Selection or Shift+F8 Add or Remove Selection mode (see [`SelectionMode`]).
|
||||
pub selection_mode: SelectionMode,
|
||||
/// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next
|
||||
/// arrow moves it again instead of keeping it.
|
||||
pub add_pending: Option<RangeRef>,
|
||||
/// Add mode header drag: the areas kept from before the drag, which the dragged range joins.
|
||||
pub header_drag_base: Vec<String>,
|
||||
/// What the macro step editor shows on the grid (Check, debugging).
|
||||
pub macro_overlay: Option<crate::macro_editor::MacroOverlay>,
|
||||
}
|
||||
|
||||
/// Excel's keyboard selection modes, shown in the status bar. In Extend mode (F8) arrow keys and
|
||||
/// clicks extend from the anchor as if Shift were held. In Add mode (Shift+F8) arrow keys move the
|
||||
/// active cell without dropping the selected areas, Shift+arrows grow a new area from there, and a
|
||||
/// click adds an area (or removes one already selected) as Ctrl+click does. Esc, the same key
|
||||
/// again, or editing a cell turns the mode off.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum SelectionMode {
|
||||
#[default]
|
||||
Off,
|
||||
Extend,
|
||||
Add,
|
||||
}
|
||||
|
||||
impl SelectionMode {
|
||||
/// The id the `ui.selectionMode` command takes and returns.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Off => "off",
|
||||
Self::Extend => "extend",
|
||||
Self::Add => "add",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(id: &str) -> Option<Self> {
|
||||
match id.trim().to_ascii_lowercase().as_str() {
|
||||
"off" | "none" => Some(Self::Off),
|
||||
"extend" => Some(Self::Extend),
|
||||
"add" => Some(Self::Add),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The status bar text (an i18n catalog key), when the mode shows one.
|
||||
pub fn status_text(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Off => None,
|
||||
Self::Extend => Some("Extend Selection"),
|
||||
Self::Add => Some("Add or Remove Selection"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GridState {
|
||||
/// Turns `mode` on, or off when it is already on (F8 / Shift+F8); the other mode ends.
|
||||
pub fn toggle_selection_mode(&mut self, mode: SelectionMode) {
|
||||
self.set_selection_mode(if self.selection_mode == mode { SelectionMode::Off } else { mode });
|
||||
}
|
||||
|
||||
pub fn set_selection_mode(&mut self, mode: SelectionMode) {
|
||||
self.selection_mode = mode;
|
||||
self.add_pending = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ctrl+wheel zoom for one (doc uid, sheet). egui eases a notch in over several frames and
|
||||
/// fine-grained wheels send parts of one, so the turning is counted in notches, and each whole
|
||||
/// notch steps [`WHEEL_ZOOM_LADDER`]. With animations on the zoom then glides to that step.
|
||||
|
||||
@@ -230,6 +230,25 @@ pub(super) fn merged_edges(wb: &Workbook, si: usize, sh: &Sheet, geo: &Geo, area
|
||||
out
|
||||
}
|
||||
|
||||
/// One cell's text as a layout job, wrapped at `wrap` (`f32::INFINITY`: one line). `slant` draws it
|
||||
/// oblique, for an italic cell whose font has no italic face (see [`crate::fonts::is_slanted`]).
|
||||
pub(super) fn cell_job(text: String, font: FontId, color: Color32, wrap: f32, slant: bool) -> egui::text::LayoutJob {
|
||||
let mut job = egui::text::LayoutJob::simple(text, font, color, wrap);
|
||||
for section in &mut job.sections {
|
||||
section.format.italics = slant;
|
||||
}
|
||||
job
|
||||
}
|
||||
|
||||
/// Paints one cell's text; `bold_dx` > 0 paints it again that far right, to thicken a bold cell
|
||||
/// whose font has no bold face (see [`crate::fonts::is_emboldened`]).
|
||||
pub(super) fn paint_cell_galley(p: &Painter, pos: Pos2, galley: std::sync::Arc<egui::Galley>, color: Color32, bold_dx: f32) {
|
||||
if bold_dx > 0.0 {
|
||||
p.galley(pos + egui::vec2(bold_dx, 0.0), galley.clone(), color);
|
||||
}
|
||||
p.galley(pos, galley, color);
|
||||
}
|
||||
|
||||
/// The smaller font that makes `text` fit in `room` points of width (Shrink to fit), or `None`
|
||||
/// when it already fits at its own size.
|
||||
pub(super) fn shrink_font(p: &Painter, text: &str, font: &FontId, room: f32) -> Option<FontId> {
|
||||
|
||||
@@ -4,11 +4,11 @@ use super::editor::validation_arrow;
|
||||
use super::geo::Geo;
|
||||
use super::keyboard::keyboard;
|
||||
use super::menus::set_fill_tag;
|
||||
use super::selection::select_ranges;
|
||||
use super::selection::{add_mode_base, select_ranges};
|
||||
use super::tables::{is_filter_button, table_headings};
|
||||
use super::{
|
||||
CellRef, Color32, CursorIcon, Drag, EditState, MAX_COLS, MAX_ROWS, Painter, Pos2, RangeRef, Rect, Sheet, SheetApp, Stroke, Tokens, Workbook,
|
||||
json, pos2, vec2,
|
||||
CellRef, Color32, CursorIcon, Drag, EditState, MAX_COLS, MAX_ROWS, Painter, Pos2, RangeRef, Rect, SelectionMode, Sheet, SheetApp, Stroke, Tokens,
|
||||
Workbook, json, pos2, vec2,
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ interaction
|
||||
@@ -23,6 +23,7 @@ struct InteractionInput<'a> {
|
||||
press_origin: Option<Pos2>,
|
||||
any_pointer_down: bool,
|
||||
modifiers: egui::Modifiers,
|
||||
selection_modifiers: egui::Modifiers,
|
||||
position: Option<Pos2>,
|
||||
primary_clicked: bool,
|
||||
in_cells: bool,
|
||||
@@ -58,6 +59,12 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
|
||||
let primary_clicked = resp.clicked_by(egui::PointerButton::Primary);
|
||||
let pointer = ctx.input(|i| i.pointer.clone());
|
||||
let mods = ctx.input(|i| i.modifiers);
|
||||
let mut selection_modifiers = mods;
|
||||
match app.grid.selection_mode {
|
||||
SelectionMode::Extend => selection_modifiers.shift = true,
|
||||
SelectionMode::Add => selection_modifiers.command = true,
|
||||
SelectionMode::Off => {}
|
||||
}
|
||||
// Hit-testing works in logical coordinates (see `Geo::rtl`).
|
||||
let pos = pointer.interact_pos().or(pointer.hover_pos()).map(|p| geo.mirror_pos(p));
|
||||
let in_cells = pos.is_some_and(|p| geo.in_cells(p));
|
||||
@@ -91,6 +98,7 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
|
||||
press_origin: pointer.press_origin(),
|
||||
any_pointer_down: pointer.any_down(),
|
||||
modifiers: mods,
|
||||
selection_modifiers,
|
||||
position: pos,
|
||||
primary_clicked,
|
||||
in_cells,
|
||||
@@ -341,7 +349,7 @@ fn handle_header_autofit(app: &mut SheetApp, input: &InteractionInput<'_>) -> bo
|
||||
|
||||
fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
|
||||
let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
|
||||
let mods = input.modifiers;
|
||||
let mods = input.selection_modifiers;
|
||||
let resp = input.response;
|
||||
let in_col_header = input.in_column_header;
|
||||
if in_col_header {
|
||||
@@ -372,6 +380,7 @@ fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>,
|
||||
return;
|
||||
}
|
||||
let range = if mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) };
|
||||
app.grid.header_drag_base = add_mode_base(app);
|
||||
note_selecting_press(app);
|
||||
select_ranges(app, range, mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c));
|
||||
app.grid.drag = Drag::Cols(if mods.shift { sel.anchor.col } else { c });
|
||||
@@ -380,7 +389,7 @@ fn handle_column_header_press(app: &mut SheetApp, input: &InteractionInput<'_>,
|
||||
|
||||
fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p: Pos2) {
|
||||
let (geo, sh, wb, sel) = (input.geo, input.sheet, input.workbook, &input.selection);
|
||||
let mods = input.modifiers;
|
||||
let mods = input.selection_modifiers;
|
||||
let in_row_header = input.in_row_header;
|
||||
if in_row_header {
|
||||
if let Some((r, y)) = row_edge(geo, sh, p.y) {
|
||||
@@ -394,15 +403,24 @@ fn handle_row_header_press(app: &mut SheetApp, input: &InteractionInput<'_>, p:
|
||||
return;
|
||||
}
|
||||
let range = if mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) };
|
||||
app.grid.header_drag_base = add_mode_base(app);
|
||||
note_selecting_press(app);
|
||||
select_ranges(app, range, mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0)));
|
||||
app.grid.drag = Drag::Rows(if mods.shift { sel.anchor.row } else { r });
|
||||
}
|
||||
}
|
||||
|
||||
/// The link of cell `c` on the active sheet as the session holds it now: a click may have just
|
||||
/// committed an edit the frame's workbook snapshot predates (a `HYPERLINK` target cell).
|
||||
fn current_cell_link(app: &SheetApp, c: CellRef) -> Option<gridcraft_engine::model::Hyperlink> {
|
||||
let d = app.session.active()?;
|
||||
gridcraft_engine::links::cell_link(&d.wb, d.wb.active_sheet(), c)
|
||||
}
|
||||
|
||||
fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
let (geo, sh, wb, resp) = (input.geo, input.sheet, input.workbook, input.response);
|
||||
let (pos, mods, sel) = (input.position, input.modifiers, &input.selection);
|
||||
let sel_mods = input.selection_modifiers;
|
||||
let (primary_clicked, in_cells, in_col_header, in_row_header, in_corner) =
|
||||
(input.primary_clicked, input.in_cells, input.in_column_header, input.in_row_header, input.in_corner);
|
||||
let (freeze_cols, freeze_rows) = (input.freeze_columns, input.freeze_rows);
|
||||
@@ -520,15 +538,29 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
return;
|
||||
}
|
||||
app.grid.last_click = Some((c, now));
|
||||
if mods.shift {
|
||||
if sel_mods.shift {
|
||||
note_selecting_press(app);
|
||||
app.grid.header_drag_base = add_mode_base(app);
|
||||
let mut ranges = app.grid.header_drag_base.clone();
|
||||
if let Some(pending) = app.grid.add_pending.take()
|
||||
&& ranges.last().is_some_and(|r| r == &pending.a1())
|
||||
{
|
||||
ranges.pop();
|
||||
}
|
||||
ranges.push(RangeRef::new(sel.anchor, c).a1());
|
||||
let _ = app.run("selection.set", json!({"range": ranges.join(","), "active": sel.active.a1()}));
|
||||
if let Some(d) = app.session.active_mut() {
|
||||
d.selection.anchor = sel.anchor;
|
||||
}
|
||||
} else if mods.shift {
|
||||
note_selecting_press(app);
|
||||
let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()}));
|
||||
if let Some(d) = app.session.active_mut() {
|
||||
d.selection.anchor = sel.anchor;
|
||||
}
|
||||
} else if mods.command {
|
||||
} else if mods.command || sel_mods.command {
|
||||
// Ctrl+click (without Alt) on a hyperlink's text follows it instead of adding the cell to the selection.
|
||||
if let Some(h) = sh.hyperlinks.get(&c).cloned()
|
||||
if let Some(h) = current_cell_link(app, c)
|
||||
&& acts
|
||||
&& !mods.alt
|
||||
&& p.x < geo.cell_rect(sh, c).left() + geo.cell_rect(sh, c).width() * 0.8
|
||||
@@ -545,7 +577,7 @@ fn handle_press(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
let _ = app.run("cell.toggleCheckbox", json!({"cell": c.a1()}));
|
||||
}
|
||||
// A click on a hyperlink's text follows it (like Excel); elsewhere in the cell selects.
|
||||
if let Some(h) = sh.hyperlinks.get(&c).cloned()
|
||||
if let Some(h) = current_cell_link(app, c)
|
||||
&& acts
|
||||
&& !mods.any()
|
||||
{
|
||||
@@ -719,14 +751,16 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
}
|
||||
Drag::Rows(anchor) => {
|
||||
let r = geo.row_at(sh, p.y);
|
||||
let _ =
|
||||
app.session.run("selection.set", json!({"range": RangeRef::rows(anchor.min(r), anchor.max(r)).a1(), "active": sel.active.a1()}));
|
||||
let range = RangeRef::rows(anchor.min(r), anchor.max(r)).a1();
|
||||
let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::<Vec<_>>().join(",");
|
||||
let _ = app.run("selection.set", json!({"range": ranges, "active": sel.active.a1()}));
|
||||
scroll_by(app, vec2(0.0, auto.y));
|
||||
}
|
||||
Drag::Cols(anchor) => {
|
||||
let c = geo.col_at(sh, p.x);
|
||||
let _ =
|
||||
app.session.run("selection.set", json!({"range": RangeRef::cols(anchor.min(c), anchor.max(c)).a1(), "active": sel.active.a1()}));
|
||||
let range = RangeRef::cols(anchor.min(c), anchor.max(c)).a1();
|
||||
let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::<Vec<_>>().join(",");
|
||||
let _ = app.run("selection.set", json!({"range": ranges, "active": sel.active.a1()}));
|
||||
scroll_by(app, vec2(auto.x, 0.0));
|
||||
}
|
||||
drag @ (Drag::PointRows(_) | Drag::PointCols(_)) => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::geo::Geo;
|
||||
use super::interact::object_key;
|
||||
use super::menus::is_checkbox;
|
||||
use super::{CellRef, Drag, Sheet, SheetApp, json};
|
||||
use super::selection::add_mode_move;
|
||||
use super::{CellRef, Drag, SelectionMode, Sheet, SheetApp, json};
|
||||
|
||||
/// Whether something other than the grid owns the keyboard this frame: an editor, a dialog, a
|
||||
/// message, a menu or another focused widget. Kept out of [`keyboard`] to hold its complexity
|
||||
@@ -82,6 +83,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => {
|
||||
use egui::Key;
|
||||
let Some(m) = selection_mode_key(app, sh, key, m) else { continue };
|
||||
let nudged = object_key(app, sh, key, m);
|
||||
if nudged || crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) {
|
||||
shortcut_ran |= !nudged;
|
||||
@@ -89,13 +91,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
let cmd = m.command;
|
||||
let shift = m.shift;
|
||||
let mv = |app: &mut SheetApp, dr: i64, dc: i64| {
|
||||
let from = app.session.active().map(|d| if shift { d.selection.moving_end() } else { d.selection.active });
|
||||
let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd}));
|
||||
app.grid.ensure_visible = true;
|
||||
app.grid.reveal_moving_end = shift;
|
||||
app.grid.reveal_from = from;
|
||||
};
|
||||
let mv = |app: &mut SheetApp, dr: i64, dc: i64| move_selection(app, dr, dc, shift, cmd);
|
||||
match key {
|
||||
Key::ArrowUp => mv(app, -1, 0),
|
||||
Key::ArrowDown => mv(app, 1, 0),
|
||||
@@ -106,6 +102,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
Key::PageUp if !cmd => mv(app, -page, 0),
|
||||
Key::PageDown => app.run_or_alert("sheet.next", json!({})),
|
||||
Key::PageUp => app.run_or_alert("sheet.previous", json!({})),
|
||||
// Add mode: Home and End move the active cell as arrows do, keeping the selected areas.
|
||||
Key::Home if cmd => {
|
||||
let r = sh.freeze.map(|f| f.0).unwrap_or(0);
|
||||
let c = sh.freeze.map(|f| f.1).unwrap_or(0);
|
||||
@@ -149,11 +146,13 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
}
|
||||
Key::Escape if app.selected_object.is_some() => app.selected_object = None,
|
||||
Key::Escape => cancel_pending(app),
|
||||
Key::Escape => cancel_pending_and_selection_mode(app),
|
||||
Key::Space if !cmd && !shift && is_checkbox(sh, app) => app.run_or_alert("cell.toggleCheckbox", json!({})),
|
||||
// F8 Extend Selection, Shift+F8 Add or Remove Selection: each toggles its mode.
|
||||
Key::F8 if m.alt => {
|
||||
app.open_dialog("macros", json!({}));
|
||||
}
|
||||
Key::F8 if !cmd => toggle_selection_mode(app, shift),
|
||||
Key::F9 => app.run_or_alert("formulas.calculateNow", json!({})),
|
||||
Key::F4 if !cmd => {}
|
||||
// Ctrl+Shift+letter (⌘⇧letter) runs the macro with that shortcut, unless GridCraft uses it.
|
||||
@@ -243,6 +242,76 @@ fn request_grid_ime(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response,
|
||||
});
|
||||
}
|
||||
|
||||
/// The F8 selection modes' part of a key press. Extend mode makes the navigation keys extend from
|
||||
/// the anchor as if Shift were held; Add mode moves Shift+Home and Ctrl+Shift+End within the area
|
||||
/// being added, and Home, Ctrl+Home and Ctrl+End move the active cell keeping the areas. The modifiers to handle the key with, or `None` when the key was handled here.
|
||||
/// Kept out of [`keyboard`] to hold its complexity within the workspace limit.
|
||||
fn selection_mode_key(app: &mut SheetApp, sh: &Sheet, key: egui::Key, m: egui::Modifiers) -> Option<egui::Modifiers> {
|
||||
use egui::Key;
|
||||
let navigation =
|
||||
matches!(key, Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight | Key::PageUp | Key::PageDown | Key::Home | Key::End);
|
||||
let m = if navigation && app.grid.selection_mode == SelectionMode::Extend { egui::Modifiers { shift: true, ..m } } else { m };
|
||||
if app.grid.selection_mode == SelectionMode::Add && m.shift && (key == Key::Home || (m.command && key == Key::End)) {
|
||||
let from = app.session.active().map(|d| d.selection.moving_end()).unwrap_or_default();
|
||||
let to = match (key, m.command) {
|
||||
(Key::Home, true) => CellRef::new(0, 0),
|
||||
(Key::Home, false) => CellRef::new(from.row, 0),
|
||||
(Key::End, true) => sh.used_range().map(|u| u.end).unwrap_or_default(),
|
||||
_ => from,
|
||||
};
|
||||
add_mode_move(app, i64::from(to.row) - i64::from(from.row), i64::from(to.col) - i64::from(from.col), true, false);
|
||||
return None;
|
||||
}
|
||||
if add_mode_home_end(app, sh, key, m.command) {
|
||||
return None;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// An arrow or Page key's move: `selection.move` (extending with Shift, jumping with Ctrl), or in
|
||||
/// Add mode a move of the active cell that keeps the selected areas.
|
||||
fn move_selection(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, cmd: bool) {
|
||||
let from = app.session.active().map(|d| if shift { d.selection.moving_end() } else { d.selection.active });
|
||||
if app.grid.selection_mode == SelectionMode::Add {
|
||||
add_mode_move(app, dr, dc, shift, cmd);
|
||||
app.grid.reveal_from = from;
|
||||
return;
|
||||
}
|
||||
let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd}));
|
||||
app.grid.ensure_visible = true;
|
||||
app.grid.reveal_moving_end = shift;
|
||||
app.grid.reveal_from = from;
|
||||
}
|
||||
|
||||
/// Add mode: Home and Ctrl+Home/Ctrl+End move the active cell as the arrows do, keeping the
|
||||
/// selected areas. Whether the key was one of those (and so was handled).
|
||||
fn add_mode_home_end(app: &mut SheetApp, sh: &Sheet, key: egui::Key, cmd: bool) -> bool {
|
||||
if app.grid.selection_mode != SelectionMode::Add || !(cmd || key == egui::Key::Home) {
|
||||
return false;
|
||||
}
|
||||
let a = app.session.active().map(|d| d.selection.active).unwrap_or_default();
|
||||
let to = match key {
|
||||
egui::Key::Home if cmd => CellRef::new(sh.freeze.map(|f| f.0).unwrap_or(0), sh.freeze.map(|f| f.1).unwrap_or(0)),
|
||||
egui::Key::End => sh.used_range().map(|u| u.end).unwrap_or_default(),
|
||||
_ => CellRef::new(a.row, 0),
|
||||
};
|
||||
add_mode_move(app, i64::from(to.row) - i64::from(a.row), i64::from(to.col) - i64::from(a.col), false, false);
|
||||
true
|
||||
}
|
||||
|
||||
/// Esc: what [`cancel_pending`] cancels, and the F8 selection modes end.
|
||||
fn cancel_pending_and_selection_mode(app: &mut SheetApp) {
|
||||
cancel_pending(app);
|
||||
let _ = app.run("ui.selectionMode", json!({"mode": "off"}));
|
||||
}
|
||||
|
||||
/// F8 toggles Extend Selection, Shift+F8 Add or Remove Selection.
|
||||
fn toggle_selection_mode(app: &mut SheetApp, shift: bool) {
|
||||
let target = if shift { SelectionMode::Add } else { SelectionMode::Extend };
|
||||
let mode = if app.grid.selection_mode == target { SelectionMode::Off } else { target };
|
||||
let _ = app.run("ui.selectionMode", json!({"mode": mode.id()}));
|
||||
}
|
||||
|
||||
/// This frame's input events, without those the focused form control took.
|
||||
fn grid_events(app: &mut SheetApp, ctx: &egui::Context, sh: &Sheet) -> Vec<egui::Event> {
|
||||
let events = ctx.input(|i| i.events.clone());
|
||||
|
||||
@@ -31,14 +31,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
|
||||
}
|
||||
}
|
||||
let wb = app.session.active().map(|d| d.wb.clone()).unwrap_or(wb);
|
||||
let values = gridcraft_engine::cmd::data::filter_values(&wb, si, col);
|
||||
let key = egui::Id::unique(("filter_sel", col));
|
||||
let search_key = egui::Id::unique(("filter_search", col));
|
||||
let buttons_key = egui::Id::unique(("filter_buttons", col));
|
||||
// Enter is the menu's OK, as in Excel: taken before the search box (which would only drop its
|
||||
// focus) and the value checkboxes (which would toggle) see it. A focused button keeps it as its click.
|
||||
let buttons: Vec<egui::Id> = ui.ctx().data_mut(|d| d.get_temp(buttons_key)).unwrap_or_default();
|
||||
let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| buttons.contains(&f));
|
||||
let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| app.grid.filter_buttons.contains(&f));
|
||||
let enter = !on_button && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
|
||||
let mut close = false;
|
||||
let area = egui::Area::new(egui::Id::unique("filter_menu")).fixed_pos(at + vec2(-180.0, 10.0)).order(egui::Order::Foreground);
|
||||
@@ -57,9 +52,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
|
||||
}
|
||||
ui.separator();
|
||||
ui.label(egui::RichText::new("Filter").strong());
|
||||
let mut checks: Vec<(String, bool)> = ui.ctx().data_mut(|d| d.get_temp::<Vec<(String, bool)>>(key)).unwrap_or(values.clone());
|
||||
let mut checks = app.grid.filter_checks.clone().unwrap_or_else(|| gridcraft_engine::cmd::data::filter_values(&wb, si, col));
|
||||
// A search narrows the list; Select All and Apply then only cover the matches.
|
||||
let mut search: String = ui.ctx().data_mut(|d| d.get_temp(search_key)).unwrap_or_default();
|
||||
let mut search = app.grid.filter_search.clone();
|
||||
let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text("Search").desired_width(f32::INFINITY));
|
||||
if !was_open {
|
||||
field.request_focus();
|
||||
@@ -81,10 +76,8 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
|
||||
ui.checkbox(on, v.as_str());
|
||||
}
|
||||
});
|
||||
ui.ctx().data_mut(|d| {
|
||||
d.insert_temp(key, checks.clone());
|
||||
d.insert_temp(search_key, search.clone());
|
||||
});
|
||||
app.grid.filter_checks = Some(checks.clone());
|
||||
app.grid.filter_search.clone_from(&search);
|
||||
let checks: Vec<(String, bool)> = checks.iter().map(|(v, on)| (v.clone(), *on && matches(v))).collect();
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
@@ -96,8 +89,12 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
|
||||
// Nothing checked would hide every row, so Enter (unlike a click on Apply) does nothing then.
|
||||
let any = checks.iter().any(|(_, on)| *on);
|
||||
let apply = ui.button("Apply");
|
||||
ui.ctx().data_mut(|d| d.insert_temp(buttons_key, vec![ascending.id, descending.id, clear.id, apply.id]));
|
||||
app.grid.filter_buttons = vec![ascending.id, descending.id, clear.id, apply.id];
|
||||
if apply.clicked() || (enter && any) {
|
||||
let mut checks = gridcraft_engine::cmd::data::filter_selection(&wb, si, col, &checks);
|
||||
for (value, on) in &mut checks {
|
||||
*on &= matches(value);
|
||||
}
|
||||
let blanks = checks.iter().any(|(v, on)| v == "(Blanks)" && *on);
|
||||
let vals: Vec<String> = checks.iter().filter(|(v, on)| *on && v != "(Blanks)").map(|(v, _)| v.clone()).collect();
|
||||
let p = if checks.iter().all(|(_, b)| *b) {
|
||||
@@ -112,11 +109,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
|
||||
});
|
||||
});
|
||||
if close || popup_dismissed(&response.response, was_open) {
|
||||
ui.ctx().data_mut(|d| {
|
||||
d.remove::<Vec<(String, bool)>>(key);
|
||||
d.remove::<String>(search_key);
|
||||
d.remove::<Vec<egui::Id>>(buttons_key);
|
||||
});
|
||||
app.grid.filter_checks = None;
|
||||
app.grid.filter_search.clear();
|
||||
app.grid.filter_buttons.clear();
|
||||
app.grid.filter_menu = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::active_row::paint_active_row;
|
||||
use super::cell_paint::{
|
||||
Look, MergedArea, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border, paint_cf_icon,
|
||||
painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y,
|
||||
Look, MergedArea, cell_job, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border,
|
||||
paint_cell_galley, paint_cf_icon, painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y,
|
||||
};
|
||||
use super::geo::Geo;
|
||||
use super::tables::{filter_button_rect, paint_filter_button};
|
||||
@@ -352,6 +352,11 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
|
||||
let size = st.font.size * 96.0 / 72.0 * z;
|
||||
let fam = theme::cell_family(&st.font.name, st.font.bold, st.font.italic);
|
||||
let font = FontId::new(size, fam);
|
||||
let slant = st.font.italic && crate::fonts::is_slanted(&st.font.name, st.font.bold);
|
||||
let embolden = st.font.bold && crate::fonts::is_emboldened(&st.font.name, st.font.italic);
|
||||
// How far the second impression of imitated bold sits from the first, by the size painted.
|
||||
let ppp = p.ctx().pixels_per_point();
|
||||
let bold_dx = |size: f32| if embolden { (size / 36.0).max(1.0 / ppp) } else { 0.0 };
|
||||
// Digits fit by the cell's own font and size, not the default 11pt (9pt marks in narrow columns).
|
||||
let char_w = p.layout_no_wrap("0".to_string(), font.clone(), Color32::PLACEHOLDER).size().x.max(1.0);
|
||||
let avail_w = rect.right() - text_left;
|
||||
@@ -380,7 +385,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
|
||||
// Rotated text wraps along its own direction (below), not across the column width.
|
||||
if !rotated && (st.align.wrap || st.align.h == HAlign::Justify) {
|
||||
let wrap_w = (rect.width() - 2.0 * pad - indent).max(4.0);
|
||||
let mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, wrap_w);
|
||||
let mut job = cell_job(text.clone(), font.clone(), color, wrap_w, slant);
|
||||
job.direction = direction;
|
||||
job.halign_min_is_start = false;
|
||||
job.halign = match painted_halign(halign, geo.rtl) {
|
||||
@@ -397,7 +402,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
|
||||
let (text_top, text_bottom) = galley_baseline_bounds(&galley);
|
||||
let y = wrapped_cell_text_y(st.align.v, *rect, text_bottom - text_top, z) - text_top;
|
||||
let text_clip = wrapped_text_clip(p, *rect, &galley, y, st.align.v);
|
||||
p.with_clip_rect(text_clip).galley(pos2(x, y), galley, color);
|
||||
paint_cell_galley(&p.with_clip_rect(text_clip), pos2(x, y), galley, color, bold_dx(size));
|
||||
return;
|
||||
}
|
||||
// Wrap Text off: Excel ignores the line breaks and draws the whole string on one line.
|
||||
@@ -412,7 +417,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
|
||||
let shrunk = small.is_some();
|
||||
let font = small.unwrap_or(font);
|
||||
let layout = |text: String| {
|
||||
let mut job = egui::text::LayoutJob::simple(text, font.clone(), color, f32::INFINITY);
|
||||
let mut job = cell_job(text, font.clone(), color, f32::INFINITY, slant);
|
||||
job.direction = direction;
|
||||
job.halign_min_is_start = false;
|
||||
p.layout_job(job)
|
||||
@@ -507,18 +512,16 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
|
||||
let angle = -(st.align.rotation as f32).to_radians();
|
||||
// Upright (±90°) wrapped text wraps to the row height: lines then stack across the column.
|
||||
let galley = if st.align.wrap && st.align.rotation.abs() == 90 {
|
||||
let mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0));
|
||||
let mut job = cell_job(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0), slant);
|
||||
job.direction = direction;
|
||||
p.layout_job(job)
|
||||
} else {
|
||||
galley.clone()
|
||||
};
|
||||
let pos = rotated_text_pos(*rect, galley.size(), angle, halign, st.align.v, pad, indent);
|
||||
let mut shape = egui::epaint::TextShape::new(pos, galley, color);
|
||||
shape.angle = angle;
|
||||
cp.add(shape);
|
||||
paint_rotated_galley(&cp, pos, galley, color, angle, bold_dx(font.size));
|
||||
} else {
|
||||
cp.galley(pos2(x, y), galley.clone(), color);
|
||||
paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx(font.size));
|
||||
}
|
||||
paint_text_decorations(
|
||||
&cp,
|
||||
@@ -526,6 +529,19 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
|
||||
);
|
||||
}
|
||||
|
||||
/// Paints rotated cell text; `bold_dx` > 0 first paints it that far along the text's own
|
||||
/// direction, the second impression of imitated bold.
|
||||
fn paint_rotated_galley(cp: &Painter, pos: Pos2, galley: std::sync::Arc<egui::Galley>, color: Color32, angle: f32, bold_dx: f32) {
|
||||
if bold_dx > 0.0 {
|
||||
let mut thick = egui::epaint::TextShape::new(pos + bold_dx * egui::vec2(angle.cos(), angle.sin()), galley.clone(), color);
|
||||
thick.angle = angle;
|
||||
cp.add(thick);
|
||||
}
|
||||
let mut shape = egui::epaint::TextShape::new(pos, galley, color);
|
||||
shape.angle = angle;
|
||||
cp.add(shape);
|
||||
}
|
||||
|
||||
struct TextDecoration {
|
||||
x: f32,
|
||||
y: f32,
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::geo::Geo;
|
||||
use super::interact::{hidden_col_edge, hidden_row_edge};
|
||||
#[cfg(test)]
|
||||
use super::show::hidden_around;
|
||||
use super::{CellRef, Color32, Painter, RangeRef, Rect, Sheet, SheetApp, Stroke, StrokeKind, Tokens, json, pos2, vec2};
|
||||
use super::{CellRef, Color32, Painter, RangeRef, Rect, SelectionMode, Sheet, SheetApp, Stroke, StrokeKind, Tokens, json, pos2, vec2};
|
||||
|
||||
/// Where the active cell is on screen: the whole merged cell when it is part of one.
|
||||
fn active_rect(geo: &Geo, sh: &Sheet, sel: &gridcraft_engine::Selection) -> Rect {
|
||||
@@ -190,15 +190,67 @@ fn toggled_ranges(mut ranges: Vec<String>, clicked: String, add: bool) -> Vec<St
|
||||
ranges
|
||||
}
|
||||
|
||||
/// An arrow (or Page Up/Down, Ctrl+arrow) in Add mode. Without Shift the active cell moves and the
|
||||
/// selected areas stay, the cell it lands on becoming a provisional last area that the next arrow
|
||||
/// moves again; with Shift that area grows from its anchor and is kept, so the next arrow starts
|
||||
/// another one.
|
||||
pub(super) fn add_mode_move(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, jump: bool) {
|
||||
app.grid.ensure_visible = true;
|
||||
app.grid.reveal_moving_end = shift;
|
||||
if shift {
|
||||
let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": jump}));
|
||||
app.grid.add_pending = None;
|
||||
return;
|
||||
}
|
||||
let Some(mut keep) = app.session.active().map(|d| d.selection.ranges.clone()) else { return };
|
||||
// Only the provisional area this mode made is dropped, and only while it is still the last area.
|
||||
if let Some(p) = app.grid.add_pending.take()
|
||||
&& keep.last() == Some(&p)
|
||||
{
|
||||
keep.pop();
|
||||
}
|
||||
// The engine works out where the cell lands (hidden rows, merged cells, Ctrl+arrow jumps).
|
||||
let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": false, "jump": jump}));
|
||||
let Some((area, active)) = app.session.active().map(|d| (d.selection.current(), d.selection.active)) else { return };
|
||||
// Landing on an area already kept leaves it kept: the next arrow doesn't drop it.
|
||||
let kept = keep.contains(&area);
|
||||
keep.retain(|r| *r != area);
|
||||
keep.push(area);
|
||||
let range = keep.iter().map(|r| r.a1()).collect::<Vec<_>>().join(",");
|
||||
let _ = app.run("selection.set", json!({"range": range, "active": active.a1()}));
|
||||
app.grid.add_pending = (!kept).then_some(area);
|
||||
}
|
||||
|
||||
/// The active sheet's areas in Add mode, as `selection.set` takes them; empty in other modes.
|
||||
pub(super) fn add_mode_base(app: &SheetApp) -> Vec<String> {
|
||||
if app.grid.selection_mode != SelectionMode::Add {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ranges = app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect::<Vec<_>>()).unwrap_or_default();
|
||||
if let Some(pending) = app.grid.add_pending
|
||||
&& ranges.last().is_some_and(|range| range == &pending.a1())
|
||||
{
|
||||
ranges.pop();
|
||||
}
|
||||
ranges
|
||||
}
|
||||
|
||||
pub(super) fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) {
|
||||
let current: Vec<String> =
|
||||
if add { app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() } else { vec![] };
|
||||
// A clicked area is kept: the next Add mode arrow starts a new one.
|
||||
app.grid.add_pending = None;
|
||||
let current: Vec<RangeRef> = if add { app.session.active().map(|d| d.selection.ranges.clone()).unwrap_or_default() } else { vec![] };
|
||||
let clicked = r.a1();
|
||||
let ranges = toggled_ranges(current, clicked.clone(), add);
|
||||
// A click on a cell inside a larger kept area removes that area, as a click on a single-cell area does.
|
||||
let inside =
|
||||
(add && current.len() > 1 && r.start == r.end).then(|| current.iter().position(|x| x.a1() != clicked && x.contains(r.start))).flatten();
|
||||
let ranges: Vec<String> = match inside {
|
||||
Some(i) => current.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, x)| x.a1()).collect(),
|
||||
None => toggled_ranges(current.iter().map(|x| x.a1()).collect(), clicked.clone(), add),
|
||||
};
|
||||
// A removed area takes the active cell with it; `selection.set` then puts it at the start of the last area.
|
||||
let params =
|
||||
if ranges.contains(&clicked) { json!({"range": ranges.join(","), "active": active.a1()}) } else { json!({"range": ranges.join(",")}) };
|
||||
let _ = app.session.run("selection.set", params);
|
||||
let _ = app.run("selection.set", params);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -360,6 +360,7 @@ impl<F: Fn(&mut SheetApp, egui::Vec2) -> Geo> ActiveCellVisibility<'_, F> {
|
||||
}
|
||||
|
||||
fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &Geo, sh: &Sheet, wb: &Workbook) {
|
||||
let window = app.session.active_window();
|
||||
let previous_popups = (app.grid.filter_menu, app.grid.list_picker, app.grid.header_menu, app.grid.fill_menu);
|
||||
// A pan the grid never saw end (it was hidden mid-drag) must not swallow the next press.
|
||||
if app.grid.touch_pan && !resp.dragged() && !resp.drag_stopped() {
|
||||
@@ -374,6 +375,15 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re
|
||||
crate::paper_view::interact(app, ui, resp, geo, sh, wb);
|
||||
interact(app, ui, resp, geo, sh, wb);
|
||||
}
|
||||
// A form button can switch windows and swap GridState; the old popup and geometry belong to the outgoing window.
|
||||
if app.session.active_window() != window {
|
||||
return;
|
||||
}
|
||||
if previous_popups.0 != app.grid.filter_menu && previous_popups.0.is_some() {
|
||||
app.grid.filter_checks = None;
|
||||
app.grid.filter_search.clear();
|
||||
app.grid.filter_buttons.clear();
|
||||
}
|
||||
update_cursor(app, ui, resp, geo, sh);
|
||||
crate::text_box::show(app, ui, geo, sh);
|
||||
if app.editor.as_ref().is_some_and(|e| !e.from_formula_bar) {
|
||||
@@ -771,7 +781,7 @@ pub(crate) fn paint_overlays(input: OverlayInput<'_>) {
|
||||
);
|
||||
}
|
||||
// Hyperlink tooltip.
|
||||
if let Some(h) = hover.and_then(|c| sh.hyperlinks.get(&c))
|
||||
if let Some(h) = hover.and_then(|c| gridcraft_engine::links::cell_link(wb, si, c))
|
||||
&& app.editor.is_none()
|
||||
{
|
||||
let tip = h.tooltip.clone().unwrap_or_else(|| format!("{}\nClick once to follow. Click and hold to select this cell.", h.target));
|
||||
|
||||
@@ -667,6 +667,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_special_add_and_text_to_columns_comma_have_their_own_keys() {
|
||||
// "Add" is also the Solver button and "Comma" also the cell style (Spanish Excel: Sumar
|
||||
// vs Agregar, Coma vs Millares), so the two dialog options are keyed by context. English
|
||||
// shows the plain label, and a catalog that translates the plain label translates the
|
||||
// keyed one too, so the dialog option doesn't fall back to English.
|
||||
for (keyed, plain) in [("Paste Special|Add", "Add"), ("Text to Columns|Comma", "Comma")] {
|
||||
assert_eq!(Language::En.tr(keyed), plain);
|
||||
for language in Language::ALL {
|
||||
let shown = language.tr(keyed);
|
||||
assert!(!shown.contains('|'), "{} shows a context prefix for {keyed}: {shown}", language.code());
|
||||
if language.tr(plain) != plain {
|
||||
assert_ne!(shown, plain, "{} translates {plain:?} but not {keyed:?}", language.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translations_never_show_the_context_prefix() {
|
||||
// `tr` returns a found translation as it is, so a catalog that keeps `context|` in its
|
||||
|
||||
@@ -337,6 +337,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Uloží sešit pod jiným názvem nebo do jiné složky.",
|
||||
"Print Active Sheets" => "Vytisknout aktivní listy",
|
||||
"Print Entire Workbook" => "Vytisknout celý sešit",
|
||||
"Print Selection" => "Vytisknout výběr",
|
||||
"Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku",
|
||||
"Page Setup…" => "Vzhled stránky…",
|
||||
"Page {page} of {pages}" => "Stránka {page} z {pages}",
|
||||
@@ -435,6 +436,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Výběr odkazu",
|
||||
"Calculate" => "Přepočítat",
|
||||
"Select destination and press Enter or choose Paste" => "Vyberte cíl a stiskněte Enter nebo zvolte Vložit",
|
||||
"Extend Selection" => "Rozšířit výběr",
|
||||
"Add or Remove Selection" => "Přidat nebo odebrat výběr",
|
||||
"General" => "Obecný",
|
||||
"Number" => "Číslo",
|
||||
"Currency" => "Měna",
|
||||
@@ -580,6 +583,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Previous sheet" => "Předchozí list",
|
||||
"Zoom In" => "Přiblížit",
|
||||
"Zoom Out" => "Oddálit",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nové pravidlo formátování",
|
||||
"Edit Formatting Rule" => "Upravit pravidlo formátování",
|
||||
"Format all cells based on their values" => "Formátovat všechny buňky podle jejich hodnot",
|
||||
"Format Style:" => "Styl formátu:",
|
||||
"2-Color Scale" => "Dvoubarevná škála",
|
||||
"3-Color Scale" => "Tříbarevná škála",
|
||||
"Lowest value" => "Nejnižší hodnota",
|
||||
"Highest value" => "Nejvyšší hodnota",
|
||||
"Percent" => "Procento",
|
||||
"Percentile" => "Percentil",
|
||||
"Formula" => "Vzorec",
|
||||
"Midpoint" => "Střední bod",
|
||||
"More Rules…" => "Další pravidla…",
|
||||
"Select a Rule Type" => "Vybrat typ pravidla",
|
||||
"Edit the Rule Description" => "Upravit popis pravidla",
|
||||
"Format only cells that contain" => "Formátovat pouze buňky, které obsahují",
|
||||
"Format only top or bottom ranked values" => "Formátovat pouze hodnoty s nejvyšším nebo nejnižším pořadím",
|
||||
"Format only values that are above or below average" => "Formátovat pouze hodnoty nad nebo pod průměrem",
|
||||
"Format only unique or duplicate values" => "Formátovat pouze jedinečné nebo duplicitní hodnoty",
|
||||
"Use a formula to determine which cells to format" => "Pomocí vzorce určit, které buňky se mají formátovat",
|
||||
"Format values where this formula is true:" => "Formátovat hodnoty, pro které platí tento vzorec:",
|
||||
"with" => "s",
|
||||
"This rule type isn't available yet." => "Tento typ pravidla zatím není dostupný.",
|
||||
// widgets.rs (alphabetical keys).
|
||||
"Dismiss" => "Zavřít",
|
||||
"Rename" => "Přejmenovat",
|
||||
@@ -746,6 +773,13 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Vyplnit měsíce",
|
||||
"Fill Years" => "Vyplnit roky",
|
||||
"Auto Fill Options" => "Možnosti automatického vyplnění",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Světle červená výplň s tmavě červeným textem",
|
||||
"Yellow Fill with Dark Yellow Text" => "Žlutá výplň s tmavě žlutým textem",
|
||||
"Green Fill with Dark Green Text" => "Zelená výplň s tmavě zeleným textem",
|
||||
"Light Red Fill" => "Světle červená výplň",
|
||||
"Red Text" => "Červený text",
|
||||
"Red Border" => "Červený rámeček",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -356,6 +356,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
}
|
||||
"Print Active Sheets" => "Aktive Blätter drucken",
|
||||
"Print Entire Workbook" => "Gesamte Arbeitsmappe drucken",
|
||||
"Print Selection" => "Auswahl drucken",
|
||||
"Fit Sheet on One Page" => "Blatt auf einer Seite darstellen",
|
||||
"Page Setup…" => "Seite einrichten…",
|
||||
"Page {page} of {pages}" => "Seite {page} von {pages}",
|
||||
@@ -452,6 +453,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Zeigen",
|
||||
"Calculate" => "Berechnen",
|
||||
"Select destination and press Enter or choose Paste" => "Ziel auswählen und die Eingabetaste drücken oder „Einfügen“ wählen",
|
||||
"Extend Selection" => "Markierung erweitern",
|
||||
"Add or Remove Selection" => "Markierung hinzufügen oder entfernen",
|
||||
"General" => "Standard",
|
||||
"Number" => "Zahl",
|
||||
"Currency" => "Währung",
|
||||
@@ -671,6 +674,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Reihe…",
|
||||
"Down" => "Nach unten",
|
||||
"Up" => "Nach oben",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Neue Formatierungsregel",
|
||||
"Edit Formatting Rule" => "Formatierungsregel bearbeiten",
|
||||
"Select a Rule Type" => "Regeltyp auswählen",
|
||||
"Edit the Rule Description" => "Regelbeschreibung bearbeiten",
|
||||
"Format all cells based on their values" => "Alle Zellen basierend auf ihren Werten formatieren",
|
||||
"Format only cells that contain" => "Nur Zellen formatieren, die enthalten",
|
||||
"Format only top or bottom ranked values" => "Nur Werte formatieren, die oben oder unten eingestuft sind",
|
||||
"Format only values that are above or below average" => "Nur Werte formatieren, die über oder unter dem Durchschnitt liegen",
|
||||
"Format only unique or duplicate values" => "Nur eindeutige oder doppelte Werte formatieren",
|
||||
"Use a formula to determine which cells to format" => "Formel zur Ermittlung der zu formatierenden Zellen verwenden",
|
||||
"This rule type isn't available yet." => "Dieser Regeltyp ist noch nicht verfügbar.",
|
||||
"Format Style:" => "Formatvorlage:",
|
||||
"2-Color Scale" => "2-Farben-Skala",
|
||||
"3-Color Scale" => "3-Farben-Skala",
|
||||
"Midpoint" => "Mittelpunkt",
|
||||
"Lowest value" => "Niedrigster Wert",
|
||||
"Highest value" => "Höchster Wert",
|
||||
"Percent" => "Prozent",
|
||||
"Percentile" => "Perzentil",
|
||||
"Formula" => "Formel",
|
||||
"Format values where this formula is true:" => "Werte formatieren, für die diese Formel wahr ist:",
|
||||
"with" => "mit",
|
||||
"More Rules…" => "Weitere Regeln…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Helle rote Füllung mit dunkelrotem Text",
|
||||
"Yellow Fill with Dark Yellow Text" => "Gelbe Füllung mit dunkelgelbem Text",
|
||||
"Green Fill with Dark Green Text" => "Grüne Füllung mit dunkelgrünem Text",
|
||||
"Light Red Fill" => "Helle rote Füllung",
|
||||
"Red Text" => "Roter Text",
|
||||
"Red Border" => "Roter Rahmen",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -315,6 +315,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Αποθηκεύστε το βιβλίο εργασίας με άλλο όνομα ή σε άλλον φάκελο.",
|
||||
"Print Active Sheets" => "Εκτύπωση ενεργών φύλλων",
|
||||
"Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας",
|
||||
"Print Selection" => "Εκτύπωση επιλογής",
|
||||
"Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα",
|
||||
"Page Setup…" => "Διαμόρφωση σελίδας…",
|
||||
"Page {page} of {pages}" => "Σελίδα {page} από {pages}",
|
||||
@@ -671,6 +672,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Τιμές και μορφές αριθμών",
|
||||
"Operation" => "Πράξη",
|
||||
"Add" => "Πρόσθεση",
|
||||
"Paste Special|Add" => "Πρόσθεση",
|
||||
"Subtract" => "Αφαίρεση",
|
||||
"Multiply" => "Πολλαπλασιασμός",
|
||||
"Divide" => "Διαίρεση",
|
||||
@@ -708,6 +710,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Στηλοθέτης",
|
||||
"Semicolon" => "Ερωτηματικό (;)",
|
||||
"Comma" => "Κόμμα",
|
||||
"Text to Columns|Comma" => "Κόμμα",
|
||||
"Space" => "Διάστημα",
|
||||
"Other:" => "Άλλο:",
|
||||
"Treat consecutive delimiters as one" => "Αντιμετώπιση διαδοχικών διαχωριστικών ως ενός",
|
||||
@@ -921,6 +924,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Line" => "Γραμμή",
|
||||
"Line with Markers" => "Γραμμή με δείκτες",
|
||||
"Stacked Line" => "Σωρευμένες γραμμές",
|
||||
"100% Stacked Line" => "Σωρευμένες γραμμές 100%",
|
||||
"100% Stacked Line with Markers" => "Σωρευμένες γραμμές 100% με δείκτες",
|
||||
"Pie" => "Πίτα",
|
||||
"Doughnut" => "Δακτύλιος",
|
||||
"Area" => "Περιοχή",
|
||||
@@ -1153,6 +1158,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Συμπλήρωση μηνών",
|
||||
"Fill Years" => "Συμπλήρωση ετών",
|
||||
"Auto Fill Options" => "Επιλογές αυτόματης συμπλήρωσης",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Νέος κανόνας μορφοποίησης",
|
||||
"Edit Formatting Rule" => "Επεξεργασία κανόνα μορφοποίησης",
|
||||
"Select a Rule Type" => "Επιλογή τύπου κανόνα",
|
||||
"Edit the Rule Description" => "Επεξεργασία περιγραφής κανόνα",
|
||||
"Format all cells based on their values" => "Μορφοποίηση όλων των κελιών με βάση τις τιμές τους",
|
||||
"Format only cells that contain" => "Μορφοποίηση μόνο κελιών που περιέχουν",
|
||||
"Format only top or bottom ranked values" => "Μορφοποίηση μόνο τιμών με την υψηλότερη ή χαμηλότερη κατάταξη",
|
||||
"Format only values that are above or below average" => "Μορφοποίηση μόνο τιμών πάνω ή κάτω από τον μέσο όρο",
|
||||
"Format only unique or duplicate values" => "Μορφοποίηση μόνο μοναδικών ή διπλότυπων τιμών",
|
||||
"Use a formula to determine which cells to format" => "Χρήση τύπου για τον καθορισμό των κελιών που θα μορφοποιηθούν",
|
||||
"This rule type isn't available yet." => "Αυτός ο τύπος κανόνα δεν είναι ακόμη διαθέσιμος.",
|
||||
"Format Style:" => "Στυλ μορφής:",
|
||||
"2-Color Scale" => "Κλίμακα 2 χρωμάτων",
|
||||
"3-Color Scale" => "Κλίμακα 3 χρωμάτων",
|
||||
"Midpoint" => "Μέσο σημείο",
|
||||
"Lowest value" => "Χαμηλότερη τιμή",
|
||||
"Highest value" => "Υψηλότερη τιμή",
|
||||
"Percent" => "Ποσοστό",
|
||||
"Percentile" => "Εκατοστημόριο",
|
||||
"Formula" => "Τύπος",
|
||||
"More Rules…" => "Περισσότεροι κανόνες…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -343,6 +343,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Guarda el libro con otro nombre o en otra carpeta.",
|
||||
"Print Active Sheets" => "Imprimir hojas activas",
|
||||
"Print Entire Workbook" => "Imprimir todo el libro",
|
||||
"Print Selection" => "Imprimir selección",
|
||||
"Fit Sheet on One Page" => "Ajustar hoja en una página",
|
||||
"Page Setup…" => "Configurar página…",
|
||||
"Page {page} of {pages}" => "Página {page} de {pages}",
|
||||
@@ -439,6 +440,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Señalar",
|
||||
"Calculate" => "Calcular",
|
||||
"Select destination and press Enter or choose Paste" => "Seleccione el destino y presione Entrar o elija Pegar",
|
||||
"Extend Selection" => "Extender selección",
|
||||
"Add or Remove Selection" => "Agregar o quitar selección",
|
||||
"General" => "General",
|
||||
"Number" => "Número",
|
||||
"Currency" => "Moneda",
|
||||
@@ -677,6 +680,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Serie…",
|
||||
"Down" => "Hacia abajo",
|
||||
"Up" => "Hacia arriba",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nueva regla de formato",
|
||||
"Edit Formatting Rule" => "Editar regla de formato",
|
||||
"Select a Rule Type" => "Seleccionar un tipo de regla",
|
||||
"Edit the Rule Description" => "Editar la descripción de la regla",
|
||||
"Format all cells based on their values" => "Dar formato a todas las celdas según sus valores",
|
||||
"Format only cells that contain" => "Dar formato solo a las celdas que contengan",
|
||||
"Format only top or bottom ranked values" => "Dar formato solo a los valores con clasificación superior o inferior",
|
||||
"Format only values that are above or below average" => "Dar formato solo a los valores que estén por encima o por debajo del promedio",
|
||||
"Format only unique or duplicate values" => "Dar formato solo a los valores únicos o duplicados",
|
||||
"Use a formula to determine which cells to format" => "Usar una fórmula para determinar qué celdas se van a aplicar formato",
|
||||
"This rule type isn't available yet." => "Este tipo de regla aún no está disponible.",
|
||||
"Format Style:" => "Estilo de formato:",
|
||||
"2-Color Scale" => "Escala de 2 colores",
|
||||
"3-Color Scale" => "Escala de 3 colores",
|
||||
"Midpoint" => "Punto medio",
|
||||
"Lowest value" => "Valor mínimo",
|
||||
"Highest value" => "Valor máximo",
|
||||
"Percent" => "Porcentaje",
|
||||
"Percentile" => "Percentil",
|
||||
"Formula" => "Fórmula",
|
||||
"Format values where this formula is true:" => "Dar formato a los valores donde esta fórmula sea verdadera:",
|
||||
"with" => "con",
|
||||
"More Rules…" => "Más reglas…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Relleno rojo claro con texto rojo oscuro",
|
||||
"Yellow Fill with Dark Yellow Text" => "Relleno amarillo con texto amarillo oscuro",
|
||||
"Green Fill with Dark Green Text" => "Relleno verde con texto verde oscuro",
|
||||
"Light Red Fill" => "Relleno rojo claro",
|
||||
"Red Text" => "Texto rojo",
|
||||
"Red Border" => "Borde rojo",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -314,6 +314,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Point",
|
||||
"Calculate" => "Calculer",
|
||||
"Select destination and press Enter or choose Paste" => "Sélectionnez la destination et appuyez sur Entrée ou choisissez Coller",
|
||||
"Extend Selection" => "Étendre la sélection",
|
||||
"Add or Remove Selection" => "Ajouter ou supprimer la sélection",
|
||||
"General" => "Standard",
|
||||
"Number" => "Nombre",
|
||||
"Currency" => "Monétaire",
|
||||
@@ -430,6 +432,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Enregistrer le classeur sous un autre nom ou dans un autre dossier.",
|
||||
"Print Active Sheets" => "Imprimer les feuilles actives",
|
||||
"Print Entire Workbook" => "Imprimer tout le classeur",
|
||||
"Print Selection" => "Imprimer la sélection",
|
||||
"Fit Sheet on One Page" => "Ajuster la feuille sur une page",
|
||||
"Page Setup…" => "Mise en page…",
|
||||
"Page {page} of {pages}" => "Page {page} sur {pages}",
|
||||
@@ -639,6 +642,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "Série…",
|
||||
"Down" => "Vers le bas",
|
||||
"Up" => "Vers le haut",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nouvelle règle de mise en forme",
|
||||
"Edit Formatting Rule" => "Modifier la règle de mise en forme",
|
||||
"Select a Rule Type" => "Sélectionner un type de règle",
|
||||
"Edit the Rule Description" => "Modifier la description de la règle",
|
||||
"Format all cells based on their values" => "Mettre en forme toutes les cellules en fonction de leurs valeurs",
|
||||
"Format only cells that contain" => "Mettre en forme uniquement les cellules qui contiennent",
|
||||
"Format only top or bottom ranked values" => "Mettre en forme uniquement les valeurs classées en haut ou en bas",
|
||||
"Format only values that are above or below average" => "Mettre en forme uniquement les valeurs supérieures ou inférieures à la moyenne",
|
||||
"Format only unique or duplicate values" => "Mettre en forme uniquement les valeurs uniques ou en double",
|
||||
"Use a formula to determine which cells to format" => "Utiliser une formule pour déterminer pour quelles cellules le format sera appliqué",
|
||||
"This rule type isn't available yet." => "Ce type de règle n'est pas encore disponible.",
|
||||
"Format Style:" => "Style de mise en forme :",
|
||||
"2-Color Scale" => "Échelle à 2 couleurs",
|
||||
"3-Color Scale" => "Échelle à 3 couleurs",
|
||||
"Midpoint" => "Point milieu",
|
||||
"Lowest value" => "Valeur la plus basse",
|
||||
"Highest value" => "Valeur la plus haute",
|
||||
"Percent" => "Pourcentage",
|
||||
"Percentile" => "Centile",
|
||||
"Formula" => "Formule",
|
||||
"Format values where this formula is true:" => "Mettre en forme les valeurs pour lesquelles cette formule est vraie :",
|
||||
"with" => "avec",
|
||||
"More Rules…" => "Autres règles…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Remplissage rouge clair avec texte rouge foncé",
|
||||
"Yellow Fill with Dark Yellow Text" => "Remplissage jaune avec texte jaune foncé",
|
||||
"Green Fill with Dark Green Text" => "Remplissage vert avec texte vert foncé",
|
||||
"Light Red Fill" => "Remplissage rouge clair",
|
||||
"Red Text" => "Texte rouge",
|
||||
"Red Border" => "Bordure rouge",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -417,6 +417,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Salva la cartella di lavoro con un altro nome o in un'altra cartella.",
|
||||
"Print Active Sheets" => "Stampa fogli attivi",
|
||||
"Print Entire Workbook" => "Stampa intera cartella di lavoro",
|
||||
"Print Selection" => "Stampa selezione",
|
||||
"Fit Sheet on One Page" => "Adatta foglio a una pagina",
|
||||
"Page Setup…" => "Imposta pagina…",
|
||||
"Page {page} of {pages}" => "Pagina {page} di {pages}",
|
||||
@@ -552,6 +553,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Valori e formati numero",
|
||||
"Operation" => "Operazione",
|
||||
"Add" => "Aggiungi",
|
||||
"Paste Special|Add" => "Aggiungi",
|
||||
"Subtract" => "Sottrai",
|
||||
"Multiply" => "Moltiplica",
|
||||
"Divide" => "Dividi",
|
||||
@@ -591,6 +593,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tabulazione",
|
||||
"Semicolon" => "Punto e virgola",
|
||||
"Comma" => "Virgola",
|
||||
"Text to Columns|Comma" => "Virgola",
|
||||
"Space" => "Spazio",
|
||||
"Other:" => "Altro:",
|
||||
"Treat consecutive delimiters as one" => "Considera delimitatori consecutivi come uno solo",
|
||||
@@ -810,6 +813,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Line" => "Linee",
|
||||
"Line with Markers" => "Linee con indicatori",
|
||||
"Stacked Line" => "Linee in pila",
|
||||
"100% Stacked Line" => "Linee in pila 100%",
|
||||
"100% Stacked Line with Markers" => "Linee in pila 100% con indicatori",
|
||||
"Pie" => "Torta",
|
||||
"Doughnut" => "Anello",
|
||||
"Area" => "Area",
|
||||
@@ -1157,6 +1162,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Riempi mesi",
|
||||
"Fill Years" => "Riempi anni",
|
||||
"Auto Fill Options" => "Opzioni di riempimento automatico",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nuova regola di formattazione",
|
||||
"Edit Formatting Rule" => "Modifica regola di formattazione",
|
||||
"Select a Rule Type" => "Seleziona un tipo di regola",
|
||||
"Edit the Rule Description" => "Modifica la descrizione della regola",
|
||||
"Format all cells based on their values" => "Formatta tutte le celle in base ai loro valori",
|
||||
"Format only cells that contain" => "Formatta solo le celle che contengono",
|
||||
"Format only top or bottom ranked values" => "Formatta solo i valori con classificazione superiore o inferiore",
|
||||
"Format only values that are above or below average" => "Formatta solo i valori superiori o inferiori alla media",
|
||||
"Format only unique or duplicate values" => "Formatta solo valori univoci o duplicati",
|
||||
"Use a formula to determine which cells to format" => "Usa una formula per determinare quali celle formattare",
|
||||
"This rule type isn't available yet." => "Questo tipo di regola non è ancora disponibile.",
|
||||
"Format Style:" => "Stile formato:",
|
||||
"2-Color Scale" => "Scala a 2 colori",
|
||||
"3-Color Scale" => "Scala a 3 colori",
|
||||
"Midpoint" => "Punto medio",
|
||||
"Lowest value" => "Valore minimo",
|
||||
"Highest value" => "Valore massimo",
|
||||
"Percent" => "Percentuale",
|
||||
"Percentile" => "Percentile",
|
||||
"Formula" => "Formula",
|
||||
"More Rules…" => "Altre regole…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -305,6 +305,8 @@ pub(super) const CORE: &[(&str, &str)] = &[
|
||||
("Point", "ポイント"),
|
||||
("Calculate", "計算"),
|
||||
("Select destination and press Enter or choose Paste", "貼り付け先を選び、Enter キーを押すか [貼り付け] を選びます"),
|
||||
("Extend Selection", "選択範囲の拡張"),
|
||||
("Add or Remove Selection", "選択範囲の追加または削除"),
|
||||
("General", "標準"),
|
||||
("Number", "数値"),
|
||||
("Currency", "通貨"),
|
||||
@@ -418,6 +420,7 @@ pub(super) const CORE: &[(&str, &str)] = &[
|
||||
("Save the workbook under another name or in another folder.", "ブックを別の名前または別のフォルダーに保存します。"),
|
||||
("Print Active Sheets", "作業中のシートを印刷"),
|
||||
("Print Entire Workbook", "ブック全体を印刷"),
|
||||
("Print Selection", "選択した部分を印刷"),
|
||||
("Fit Sheet on One Page", "シートを 1 ページに印刷"),
|
||||
("Page Setup…", "ページ設定…"),
|
||||
("Page {page} of {pages}", "{page} / {pages} ページ"),
|
||||
@@ -567,6 +570,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Values and number formats", "値と数値の書式"),
|
||||
("Operation", "演算"),
|
||||
("Add", "加算"),
|
||||
("Paste Special|Add", "加算"),
|
||||
("Subtract", "減算"),
|
||||
("Multiply", "乗算"),
|
||||
("Divide", "除算"),
|
||||
@@ -606,6 +610,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Tab", "タブ"),
|
||||
("Semicolon", "セミコロン"),
|
||||
("Comma", "コンマ"),
|
||||
("Text to Columns|Comma", "コンマ"),
|
||||
("Space", "スペース"),
|
||||
("Other:", "その他:"),
|
||||
("Treat consecutive delimiters as one", "連続した区切り文字は 1 文字として扱う"),
|
||||
@@ -829,6 +834,8 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Line", "折れ線"),
|
||||
("Line with Markers", "マーカー付き折れ線"),
|
||||
("Stacked Line", "積み上げ折れ線"),
|
||||
("100% Stacked Line", "100% 積み上げ折れ線"),
|
||||
("100% Stacked Line with Markers", "マーカー付き 100% 積み上げ折れ線"),
|
||||
("Pie", "円"),
|
||||
("Doughnut", "ドーナツ"),
|
||||
("Area", "面"),
|
||||
@@ -1143,6 +1150,26 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("\\@char has non-numeric argument {argument}", "\\@char の引数 {argument} が数値ではありません"),
|
||||
("\\@char with invalid code point {code}", "\\@char のコード ポイント {code} が無効です"),
|
||||
("Invalid environment name character: {character}", "環境名に無効な文字があります: {character}"),
|
||||
("New Formatting Rule", "新しい書式ルール"),
|
||||
("Edit Formatting Rule", "書式ルールの編集"),
|
||||
("Select a Rule Type", "ルールの種類を選択"),
|
||||
("Edit the Rule Description", "ルールの説明を編集"),
|
||||
("Format all cells based on their values", "値に基づいてすべてのセルを書式設定"),
|
||||
("Format only cells that contain", "含むセルのみを書式設定"),
|
||||
("Format only top or bottom ranked values", "上位または下位に入る値のみを書式設定"),
|
||||
("Format only values that are above or below average", "平均より上または下の値のみを書式設定"),
|
||||
("Format only unique or duplicate values", "重複する値または一意の値のみを書式設定"),
|
||||
("Use a formula to determine which cells to format", "数式を使用して、書式設定するセルを決定"),
|
||||
("This rule type isn't available yet.", "このルールの種類はまだ使用できません。"),
|
||||
("Format Style:", "書式スタイル:"),
|
||||
("2-Color Scale", "2 色スケール"),
|
||||
("3-Color Scale", "3 色スケール"),
|
||||
("Midpoint", "中間"),
|
||||
("Lowest value", "最小値"),
|
||||
("Highest value", "最大値"),
|
||||
("Percentile", "パーセンタイル"),
|
||||
("Formula", "数式"),
|
||||
("More Rules…", "その他のルール…"),
|
||||
];
|
||||
|
||||
/// Labels of the ribbon menus, pop-ups and palettes that the reference catalog does not cover (the
|
||||
|
||||
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "가리키기",
|
||||
"Calculate" => "계산",
|
||||
"Select destination and press Enter or choose Paste" => "대상을 선택하고 Enter 키를 누르거나 [붙여넣기]를 선택하세요",
|
||||
"Extend Selection" => "선택 영역 확장",
|
||||
"Add or Remove Selection" => "선택 영역 추가 또는 제거",
|
||||
"General" => "일반",
|
||||
"Number" => "숫자",
|
||||
"Currency" => "통화",
|
||||
@@ -430,6 +432,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "통합 문서를 다른 이름 또는 다른 폴더에 저장합니다.",
|
||||
"Print Active Sheets" => "활성 시트 인쇄",
|
||||
"Print Entire Workbook" => "전체 통합 문서 인쇄",
|
||||
"Print Selection" => "선택 영역 인쇄",
|
||||
"Fit Sheet on One Page" => "한 페이지에 시트 맞추기",
|
||||
"Page Setup…" => "페이지 설정…",
|
||||
"Page {page} of {pages}" => "{page}/{pages} 페이지",
|
||||
@@ -637,6 +640,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Series…" => "연속 데이터…",
|
||||
"Down" => "아래쪽",
|
||||
"Up" => "위쪽",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "새 서식 규칙",
|
||||
"Edit Formatting Rule" => "서식 규칙 편집",
|
||||
"Select a Rule Type" => "규칙 유형 선택",
|
||||
"Edit the Rule Description" => "규칙 설명 편집",
|
||||
"Format all cells based on their values" => "해당 값에 따라 모든 셀의 서식 지정",
|
||||
"Format only cells that contain" => "다음을 포함하는 셀만 서식 지정",
|
||||
"Format only top or bottom ranked values" => "순위가 위 또는 아래인 값만 서식 지정",
|
||||
"Format only values that are above or below average" => "평균보다 높거나 낮은 값만 서식 지정",
|
||||
"Format only unique or duplicate values" => "고유하거나 중복되는 값만 서식 지정",
|
||||
"Use a formula to determine which cells to format" => "수식을 사용하여 서식을 지정할 셀 결정",
|
||||
"This rule type isn't available yet." => "이 규칙 유형은 아직 사용할 수 없습니다.",
|
||||
"Format Style:" => "서식 스타일:",
|
||||
"2-Color Scale" => "2색조 눈금",
|
||||
"3-Color Scale" => "3색조 눈금",
|
||||
"Midpoint" => "중간점",
|
||||
"Lowest value" => "최저값",
|
||||
"Highest value" => "최고값",
|
||||
"Percent" => "백분율",
|
||||
"Percentile" => "백분위수",
|
||||
"Formula" => "수식",
|
||||
"Format values where this formula is true:" => "다음 수식을 만족하는 값에 서식 지정:",
|
||||
"with" => "서식:",
|
||||
"More Rules…" => "기타 규칙…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "연한 빨강 채우기 및 진한 빨강 텍스트",
|
||||
"Yellow Fill with Dark Yellow Text" => "노랑 채우기 및 진한 노랑 텍스트",
|
||||
"Green Fill with Dark Green Text" => "연한 초록 채우기 및 진한 초록 텍스트",
|
||||
"Light Red Fill" => "연한 빨강 채우기",
|
||||
"Red Text" => "빨강 텍스트",
|
||||
"Red Border" => "빨강 테두리",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -305,6 +305,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Aanwijzen",
|
||||
"Calculate" => "Berekenen",
|
||||
"Select destination and press Enter or choose Paste" => "Selecteer de bestemming en druk op Enter of kies Plakken",
|
||||
"Extend Selection" => "Selectie uitbreiden",
|
||||
"Add or Remove Selection" => "Selectie toevoegen of verwijderen",
|
||||
"General" => "Algemeen",
|
||||
"Number" => "Getal",
|
||||
"Currency" => "Valuta",
|
||||
@@ -417,6 +419,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "De werkmap onder een andere naam of in een andere map opslaan.",
|
||||
"Print Active Sheets" => "Actieve bladen afdrukken",
|
||||
"Print Entire Workbook" => "Hele werkmap afdrukken",
|
||||
"Print Selection" => "Selectie afdrukken",
|
||||
"Fit Sheet on One Page" => "Blad op één pagina passen",
|
||||
"Page Setup…" => "Pagina-instelling…",
|
||||
"Page {page} of {pages}" => "Pagina {page} van {pages}",
|
||||
@@ -709,6 +712,37 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Maanden vullen",
|
||||
"Fill Years" => "Jaren vullen",
|
||||
"Auto Fill Options" => "Opties voor automatisch vullen",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nieuwe opmaakregel",
|
||||
"Edit Formatting Rule" => "Opmaakregel bewerken",
|
||||
"Select a Rule Type" => "Een regeltype selecteren",
|
||||
"Edit the Rule Description" => "De beschrijving van de regel bewerken",
|
||||
"Format all cells based on their values" => "Alle cellen opmaken op basis van hun waarden",
|
||||
"Format only cells that contain" => "Alleen cellen opmaken die bevatten",
|
||||
"Format only top or bottom ranked values" => "Alleen waarden met een hoge of lage rangorde opmaken",
|
||||
"Format only values that are above or below average" => "Alleen waarden boven of onder het gemiddelde opmaken",
|
||||
"Format only unique or duplicate values" => "Alleen unieke of dubbele waarden opmaken",
|
||||
"Use a formula to determine which cells to format" => "Een formule gebruiken om te bepalen welke cellen worden opgemaakt",
|
||||
"This rule type isn't available yet." => "Dit regeltype is nog niet beschikbaar.",
|
||||
"Format Style:" => "Opmaakstijl:",
|
||||
"2-Color Scale" => "Schaal met 2 kleuren",
|
||||
"3-Color Scale" => "Schaal met 3 kleuren",
|
||||
"Midpoint" => "Middelpunt",
|
||||
"Lowest value" => "Laagste waarde",
|
||||
"Highest value" => "Hoogste waarde",
|
||||
"Percent" => "Percentage",
|
||||
"Percentile" => "Percentiel",
|
||||
"Formula" => "Formule",
|
||||
"Format values where this formula is true:" => "Waarden opmaken waarop deze formule waar is:",
|
||||
"with" => "met",
|
||||
"More Rules…" => "Meer regels…",
|
||||
// Conditional formatting: the formatting presets the rule editor offers.
|
||||
"Light Red Fill with Dark Red Text" => "Lichte rode opvulling met donkerrode tekst",
|
||||
"Yellow Fill with Dark Yellow Text" => "Gele opvulling met donkergele tekst",
|
||||
"Green Fill with Dark Green Text" => "Groene opvulling met donkergroene tekst",
|
||||
"Light Red Fill" => "Lichte rode opvulling",
|
||||
"Red Text" => "Rode tekst",
|
||||
"Red Border" => "Rode rand",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -409,6 +409,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Zapisz skoroszyt pod inną nazwą lub w innym folderze.",
|
||||
"Print Active Sheets" => "Drukuj aktywne arkusze",
|
||||
"Print Entire Workbook" => "Drukuj cały skoroszyt",
|
||||
"Print Selection" => "Drukuj zaznaczenie",
|
||||
"Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony",
|
||||
"Page Setup…" => "Ustawienia strony…",
|
||||
"Page {page} of {pages}" => "Strona {page} z {pages}",
|
||||
@@ -543,6 +544,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Wartości i formaty liczb",
|
||||
"Operation" => "Operacja",
|
||||
"Add" => "Dodaj",
|
||||
"Paste Special|Add" => "Dodaj",
|
||||
"Subtract" => "Odejmij",
|
||||
"Multiply" => "Pomnóż",
|
||||
"Divide" => "Podziel",
|
||||
@@ -582,6 +584,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tabulator",
|
||||
"Semicolon" => "Średnik",
|
||||
"Comma" => "Przecinek",
|
||||
"Text to Columns|Comma" => "Przecinek",
|
||||
"Space" => "Spacja",
|
||||
"Other:" => "Inny:",
|
||||
"Treat consecutive delimiters as one" => "Traktuj kolejne ograniczniki jako jeden",
|
||||
@@ -798,6 +801,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Line" => "Liniowy",
|
||||
"Line with Markers" => "Liniowy ze znacznikami",
|
||||
"Stacked Line" => "Liniowy skumulowany",
|
||||
"100% Stacked Line" => "Liniowy 100% skumulowany",
|
||||
"100% Stacked Line with Markers" => "Liniowy 100% skumulowany ze znacznikami",
|
||||
"Pie" => "Kołowy",
|
||||
"Doughnut" => "Pierścieniowy",
|
||||
"Area" => "Warstwowy",
|
||||
@@ -1145,6 +1150,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Wypełnij miesiącami",
|
||||
"Fill Years" => "Wypełnij latami",
|
||||
"Auto Fill Options" => "Opcje autowypełniania",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nowa reguła formatowania",
|
||||
"Edit Formatting Rule" => "Edytuj regułę formatowania",
|
||||
"Select a Rule Type" => "Wybierz typ reguły",
|
||||
"Edit the Rule Description" => "Edytuj opis reguły",
|
||||
"Format all cells based on their values" => "Formatuj wszystkie komórki na podstawie ich wartości",
|
||||
"Format only cells that contain" => "Formatuj tylko komórki zawierające",
|
||||
"Format only top or bottom ranked values" => "Formatuj tylko wartości o najwyższej lub najniższej pozycji",
|
||||
"Format only values that are above or below average" => "Formatuj tylko wartości powyżej lub poniżej średniej",
|
||||
"Format only unique or duplicate values" => "Formatuj tylko wartości unikatowe lub zduplikowane",
|
||||
"Use a formula to determine which cells to format" => "Użyj formuły do określenia, które komórki mają być formatowane",
|
||||
"This rule type isn't available yet." => "Ten typ reguły nie jest jeszcze dostępny.",
|
||||
"Format Style:" => "Styl formatu:",
|
||||
"2-Color Scale" => "Skala dwukolorowa",
|
||||
"3-Color Scale" => "Skala trójkolorowa",
|
||||
"Midpoint" => "Punkt środkowy",
|
||||
"Lowest value" => "Najniższa wartość",
|
||||
"Highest value" => "Najwyższa wartość",
|
||||
"Percent" => "Procent",
|
||||
"Percentile" => "Percentyl",
|
||||
"Formula" => "Formuła",
|
||||
"More Rules…" => "Więcej reguł…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -299,6 +299,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Point" => "Apontar",
|
||||
"Calculate" => "Calcular",
|
||||
"Select destination and press Enter or choose Paste" => "Selecione o destino e pressione Enter ou escolha Colar",
|
||||
"Extend Selection" => "Estender Seleção",
|
||||
"Add or Remove Selection" => "Adicionar ou Remover Seleção",
|
||||
"General" => "Geral",
|
||||
"Number" => "Número",
|
||||
"Currency" => "Moeda",
|
||||
@@ -424,6 +426,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Save the workbook under another name or in another folder." => "Salve a pasta de trabalho com outro nome ou em outra pasta.",
|
||||
"Print Active Sheets" => "Imprimir planilhas ativas",
|
||||
"Print Entire Workbook" => "Imprimir toda a pasta de trabalho",
|
||||
"Print Selection" => "Imprimir seleção",
|
||||
"Fit Sheet on One Page" => "Ajustar planilha em uma página",
|
||||
"Page Setup…" => "Configurar página…",
|
||||
"Page {page} of {pages}" => "Página {page} de {pages}",
|
||||
@@ -577,6 +580,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Values and number formats" => "Valores e formatos de número",
|
||||
"Operation" => "Operação",
|
||||
"Add" => "Adicionar",
|
||||
"Paste Special|Add" => "Adicionar",
|
||||
"Subtract" => "Subtrair",
|
||||
"Multiply" => "Multiplicar",
|
||||
"Divide" => "Dividir",
|
||||
@@ -616,6 +620,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Tab" => "Tabulação",
|
||||
"Semicolon" => "Ponto e vírgula",
|
||||
"Comma" => "Vírgula",
|
||||
"Text to Columns|Comma" => "Vírgula",
|
||||
"Space" => "Espaço",
|
||||
"Other:" => "Outros:",
|
||||
"Treat consecutive delimiters as one" => "Considerar delimitadores consecutivos como um só",
|
||||
@@ -835,6 +840,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Line" => "Linhas",
|
||||
"Line with Markers" => "Linhas com Marcadores",
|
||||
"Stacked Line" => "Linhas Empilhadas",
|
||||
"100% Stacked Line" => "Linhas 100% Empilhadas",
|
||||
"100% Stacked Line with Markers" => "Linhas 100% Empilhadas com Marcadores",
|
||||
"Pie" => "Pizza",
|
||||
"Doughnut" => "Rosca",
|
||||
"Area" => "Área",
|
||||
@@ -1161,6 +1168,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Fill Months" => "Preencher Meses",
|
||||
"Fill Years" => "Preencher Anos",
|
||||
"Auto Fill Options" => "Opções de Autopreenchimento",
|
||||
// Conditional formatting: colour scales.
|
||||
"New Formatting Rule" => "Nova Regra de Formatação",
|
||||
"Edit Formatting Rule" => "Editar Regra de Formatação",
|
||||
"Select a Rule Type" => "Selecionar um Tipo de Regra",
|
||||
"Edit the Rule Description" => "Editar a Descrição da Regra",
|
||||
"Format all cells based on their values" => "Formatar todas as células com base em seus valores",
|
||||
"Format only cells that contain" => "Formatar apenas células que contenham",
|
||||
"Format only top or bottom ranked values" => "Formatar apenas valores classificados acima ou abaixo",
|
||||
"Format only values that are above or below average" => "Formatar apenas valores acima ou abaixo da média",
|
||||
"Format only unique or duplicate values" => "Formatar apenas valores exclusivos ou duplicados",
|
||||
"Use a formula to determine which cells to format" => "Usar uma fórmula para determinar quais células devem ser formatadas",
|
||||
"This rule type isn't available yet." => "Este tipo de regra ainda não está disponível.",
|
||||
"Format Style:" => "Estilo de Formatação:",
|
||||
"2-Color Scale" => "Escala de 2 Cores",
|
||||
"3-Color Scale" => "Escala de 3 Cores",
|
||||
"Midpoint" => "Ponto Médio",
|
||||
"Lowest value" => "Valor mais baixo",
|
||||
"Highest value" => "Valor mais alto",
|
||||
"Percent" => "Porcentagem",
|
||||
"Percentile" => "Percentil",
|
||||
"Formula" => "Fórmula",
|
||||
"More Rules…" => "Mais Regras…",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user