mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-19 04:19:52 -06:00
Compare commits
111
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ec4034b26 | ||
|
|
72f11bbacb | ||
|
|
5cbe45d16e | ||
|
|
5514a3a099 | ||
|
|
42acfafcd3 | ||
|
|
83ab01678a | ||
|
|
00e8f4fae0 | ||
|
|
f8af138f28 | ||
|
|
aef4ceb10d | ||
|
|
8f8078c134 | ||
|
|
c9d2883b86 | ||
|
|
a3119f57c2 | ||
|
|
272ae54101 | ||
|
|
bf48def687 | ||
|
|
dbf674ef48 | ||
|
|
644861c132 | ||
|
|
c8450fd1e5 | ||
|
|
a492d8031a | ||
|
|
5b1d89f867 | ||
|
|
1f0d416f74 | ||
|
|
82c97858df | ||
|
|
20c5742f79 | ||
|
|
21def4fa1a | ||
|
|
61ee368369 | ||
|
|
d1a5c9671f | ||
|
|
12dd9aea9b | ||
|
|
6980b00dac | ||
|
|
f36eaf3fbe | ||
|
|
12e1b5379b | ||
|
|
bea2191b35 | ||
|
|
620174e069 | ||
|
|
4c388df949 | ||
|
|
807cf23b02 | ||
|
|
24f58a2ee4 | ||
|
|
319a3e4c2e | ||
|
|
d60709a173 | ||
|
|
cf5e91ed5e | ||
|
|
10506a1f1d | ||
|
|
47b67127d5 | ||
|
|
98bb5d6958 | ||
|
|
8a04139ef2 | ||
|
|
e03780704e | ||
|
|
5e692e0aba | ||
|
|
027d5d1f43 | ||
|
|
2c2699d87b | ||
|
|
87d2264d92 | ||
|
|
f6a75ef153 | ||
|
|
4656391c70 | ||
|
|
cb58bed1cb | ||
|
|
71ba34f061 | ||
|
|
a6cb00b6a7 | ||
|
|
c8e42061fa | ||
|
|
191c3b3ff7 | ||
|
|
c47bdffcd6 | ||
|
|
d04914bca6 | ||
|
|
b00e592054 | ||
|
|
3296878d87 | ||
|
|
56a02dcc8c | ||
|
|
e4e2c5292a | ||
|
|
113e312809 | ||
|
|
88310f3f4d | ||
|
|
d95c11b370 | ||
|
|
430f53df72 | ||
|
|
f3546f25d9 | ||
|
|
527b884429 | ||
|
|
6c2ba27110 | ||
|
|
0925c25666 | ||
|
|
e54cfba348 | ||
|
|
50e01f7646 | ||
|
|
cb4ac4d554 | ||
|
|
0c737637e5 | ||
|
|
09fcfb63a7 | ||
|
|
4bc91dbc6a | ||
|
|
2f0a986bad | ||
|
|
65257b780c | ||
|
|
c0bc784197 | ||
|
|
433ef8c85d | ||
|
|
f1ffb82737 | ||
|
|
9d71a809e4 | ||
|
|
d183fdcb5a | ||
|
|
c3bd68f061 | ||
|
|
8ceee8ef5a | ||
|
|
ba0009a1c3 | ||
|
|
0ee8c0d15f | ||
|
|
c2457bdb8c | ||
|
|
cbe10f0501 | ||
|
|
6535174664 | ||
|
|
74f09bc672 | ||
|
|
bc0cd89225 | ||
|
|
524ce912e5 | ||
|
|
ebc986fcc9 | ||
|
|
66c82e0fd2 | ||
|
|
c0db2ca597 | ||
|
|
77cfbda1bc | ||
|
|
f8c4dac15b | ||
|
|
9f3c04e9ca | ||
|
|
d0033570df | ||
|
|
3d19fa43f6 | ||
|
|
42d3e9adbb | ||
|
|
dd598ba705 | ||
|
|
b0c3d8eb3b | ||
|
|
f410a770c1 | ||
|
|
44526f0d2b | ||
|
|
ffe73b3bd7 | ||
|
|
9cbbaaeaed | ||
|
|
bf9b3cb9b1 | ||
|
|
6ff543ce76 | ||
|
|
4dd4ff9a93 | ||
|
|
9331dbb474 | ||
|
|
a6d70bcafb | ||
|
|
28a645ca13 |
Generated
+86
-21
@@ -922,12 +922,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
|
||||
[[package]]
|
||||
name = "craft-csv"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -935,9 +935,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -981,15 +981,53 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-math"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ods"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
|
||||
dependencies = [
|
||||
"craft-odf",
|
||||
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
"craft-cfb",
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"sha1 0.11.0",
|
||||
@@ -1001,10 +1039,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-opc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-zip",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1012,7 +1050,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bc358686389892a3827e64fc26bedc278ef1e299#bc358686389892a3827e64fc26bedc278ef1e299"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd"
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
@@ -1031,7 +1069,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
|
||||
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
@@ -1067,7 +1110,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1114,7 +1157,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -1133,10 +1176,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xls"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"md-5",
|
||||
"miniz_oxide 0.9.1",
|
||||
"sha1 0.10.7",
|
||||
@@ -1146,19 +1189,29 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xlsx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-drawingml",
|
||||
"craft-opc",
|
||||
"craft-sheet",
|
||||
"craft-xml",
|
||||
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1167,7 +1220,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2405,11 +2468,13 @@ version = "0.19.1"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-csv",
|
||||
"craft-math",
|
||||
"craft-ods",
|
||||
"craft-offcrypto",
|
||||
"craft-opc",
|
||||
"craft-xls",
|
||||
"craft-xlsx",
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
"gridcraft-functions",
|
||||
|
||||
+12
-10
@@ -30,25 +30,27 @@ gridcraft-math = { path = "crates/math" }
|
||||
# ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one
|
||||
# craft-libs revision.
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "=0.1.0", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
|
||||
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bc358686389892a3827e64fc26bedc278ef1e299", version = "0.1.0", default-features = false }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
|
||||
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
|
||||
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
|
||||
# turn them into workbooks.
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
|
||||
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
|
||||
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
|
||||
# SpreadsheetML string encoding/decoding; workbook model mapping stays in gridcraft-xlsx.
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -88,7 +90,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
epaint_default_fonts = "0.37"
|
||||
# One native window per workbook: the window list, Window menu titles and the immediate-viewport
|
||||
# driver. Same craft-libs revision as craft-update above.
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", default-features = false, features = ["egui"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
+8
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**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-15 · **Change:** minor (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 (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) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
|
||||
@@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-11-16 | A selected chart outlines its data as Excel does (series names red, category labels purple, values one blue block), and dragging a corner of the values outline changes the cells the chart plots: series keep their formatting, a wider block adds series, aligned names and labels follow, one undo step, Esc cancels; `chart.setValuesRange` does the same for scripts, the CLI and MCP (#4389, #4390) |
|
||||
| 2026-11-06 | A sheet keeps its own scroll position when sheets are inserted, deleted or moved before it: a new PivotTable or inserted sheet opens at the top instead of where its neighbour was scrolled; a closed window's positions are let go (#3485) |
|
||||
| 2026-11-02 | Form controls: Insert › Controls places buttons, sliders (scroll bars) and spin buttons on the sheet. A slider or spin button holds a whole number from 0 to 30000 in a linked cell (a drag or a held arrow is one undo step, and editing the cell moves the control); a button runs a macro or one command through the macro policy, asking first in a workbook opened from a file; Assign Action and Format Control edit them, and XLSX files read and write them (control properties, `<controls>` and VML), alongside the form controls GridCraft keeps unchanged |
|
||||
| 2026-11-02 | Dialogs take ranges by selection on the grid: reference boxes (RefEdit) with a collapse button that shrinks the dialog while the person selects, in Goal Seek, Solver (including the Model Range of Load/Save) and Data Analysis; while collapsed, the arrow keys move the selection and Shift+arrow extends it, and F4 cycles a reference's anchors |
|
||||
@@ -177,14 +178,17 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-19 | Long flat operator chains (`=A1+A2+…`) up to Excel's 8,192-character limit (4,096 operands): entering, filling, inserting rows, undo, Evaluate Formula and XLSX save no longer overflow the stack; chains past 64 operands are saved as plain formulas, not dynamic arrays; Spanish formula entry accepts chains past 256 operands (#916) |
|
||||
| 2026-10-19 | Linux: "Use system setting" for the theme keeps following the desktop when the XDG Desktop Portal stops answering: each read gives up after 2 s and the next poll reconnects, where one unanswered call stalled the watcher for the rest of the session |
|
||||
| 2026-10-16 | Memory: undo steps share a sheet's picture bytes and the workbook's VBA project instead of copying them: 50 edits on a sheet with a 20 MB picture keep 22 MB instead of 992 MB |
|
||||
| 2026-10-16 | Custom Sort dialog: header-named column dropdowns, smart Order labels, add/delete/copy/move levels, resizable window, selection follows the headers checkbox and returns on close; a selected block (such as a table's totals row) is sorted as selected |
|
||||
| 2026-10-16 | Memory: floating pictures are decoded at about the size they are drawn, with limits, into a cache bounded by bytes and dropped with their workbook, instead of at full size into one that never let go; two open workbooks no longer show each other's picture. 12 large pictures scrolled through keep 40 MB of textures instead of 258 MB, and none once the workbook closes |
|
||||
| 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 | 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-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 | `.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 |
|
||||
@@ -201,6 +205,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-13 | XLSX export writes a picture used on several sheets once, as one `xl/media` part every drawing points to (it wrote a copy per drawing: a 16-sheet workbook with one 112 KB logo grew from 0.4 to 1.9 MB) (#985) |
|
||||
| 2026-10-13 | XLSX: `[Content_Types].xml`, `_rels/.rels`, the workbook rels and `xl/workbook.xml` are the first zip entries (document properties last), so libmagic and PHP `finfo` detect the file type even with large properties (#1090) |
|
||||
| 2026-10-13 | Conditional formatting: a rule gathers range statistics only when it reads them (top/bottom, above average, duplicates, scales, bars, icons) and borrows them instead of copying them per cell, so the per-frame lookup of an expression or cell-value rule no longer visits its whole range (#1098, part 1) |
|
||||
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
|
||||
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
|
||||
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
|
||||
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
|
||||
@@ -274,6 +279,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-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 |
|
||||
@@ -318,6 +324,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 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 |
|
||||
| 2026-10-14 | trivial | Progress log: RATE follows Excel's iteration |
|
||||
| 2026-10-13 | trivial | Progress log: More Colors… and Recent Colors in the colour menus (#928) |
|
||||
| 2026-10-13 | minor | Multi-level category axes (read, drawn, written); progress log row |
|
||||
| 2026-10-13 | trivial | Progress log: shared pictures written once on XLSX export (#985) |
|
||||
|
||||
@@ -12,10 +12,10 @@
|
||||
//! - `gridcraft:open` (from the host): `{ name, bytes }`. It opens like a workbook picked with
|
||||
//! File › Open or dropped on the window; a file over [`MAX_OPEN_BYTES`] is refused before it is
|
||||
//! copied.
|
||||
//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes }` for every file GridCraft would
|
||||
//! otherwise download: Save and Save As (an .xlsx workbook) and Export as PDF. The host stores
|
||||
//! it and reports failures itself. GridCraft doesn't tell the host which saves make a file the
|
||||
//! document, so `saveAs` is always `false`.
|
||||
//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes, export }` for every file GridCraft
|
||||
//! would otherwise download. With `export: false`, the host stores the XLSX workbook; with
|
||||
//! `export: true`, it stores a separate file (such as a PDF) without replacing the workbook.
|
||||
//! `saveAs` remains `false`; it does not distinguish Save from Save As here.
|
||||
//! - `gridcraft:dirty` whenever unsaved changes appear or go away, `gridcraft:failed` when the
|
||||
//! app couldn't start.
|
||||
//!
|
||||
@@ -27,16 +27,16 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_web_host::web::{FileData, Host, Message};
|
||||
use craft_web_host::{Mode, Outgoing, file_name, message_type};
|
||||
use gridcraft_ui_egui::{Inbox, Services, SheetApp};
|
||||
use wasm_bindgen::JsValue;
|
||||
|
||||
use crate::host_save::{SaveMessage, sync_saved};
|
||||
use crate::hostmode::open_name;
|
||||
|
||||
/// The app id in the host messages (`gridcraft:ready`).
|
||||
const APP: &str = "gridcraft";
|
||||
|
||||
/// Saved files that count as a workbook: the document is then clean under the name it was saved as.
|
||||
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
|
||||
|
||||
/// The largest workbook taken from the host page, refused before it is copied.
|
||||
const MAX_OPEN_BYTES: u64 = 512 << 20;
|
||||
|
||||
@@ -46,6 +46,7 @@ const MAX_AUTHOR_CHARS: usize = 200;
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
host: Rc<Host>,
|
||||
save_target: Rc<SaveTarget>,
|
||||
/// Names of the files handed to the host since the last frame.
|
||||
saved: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
@@ -55,7 +56,19 @@ impl Bridge {
|
||||
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
|
||||
/// with downloads), or a parent on another origin.
|
||||
pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
|
||||
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), saved: Rc::default() })
|
||||
let host = Host::connect(APP, canvas)?;
|
||||
let save_target = match host.mode() {
|
||||
Mode::Parent => {
|
||||
// Host::connect already admitted only a same-origin parent. Keep that origin
|
||||
// as the postMessage target so later navigation can't receive workbook bytes.
|
||||
let window = web_sys::window()?;
|
||||
let parent = window.parent().ok().flatten()?;
|
||||
let origin = window.location().origin().ok()?;
|
||||
SaveTarget::Parent { parent, origin }
|
||||
}
|
||||
Mode::Page => SaveTarget::Page(canvas.clone()),
|
||||
};
|
||||
Some(Self { host: Rc::new(host), save_target: Rc::new(save_target), saved: Rc::default() })
|
||||
}
|
||||
|
||||
/// Send saved and exported files to the host instead of downloading them, and hear files
|
||||
@@ -91,20 +104,13 @@ impl Bridge {
|
||||
/// crate does not repeat a state it already reported).
|
||||
pub fn sync(&self, app: &mut SheetApp) {
|
||||
let saved = std::mem::take(&mut *self.saved.borrow_mut());
|
||||
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
|
||||
&& let Some(doc) = app.session.active_mut()
|
||||
{
|
||||
doc.saved = doc.wb.clone();
|
||||
if doc.path.is_none() {
|
||||
doc.title = name.clone();
|
||||
}
|
||||
}
|
||||
sync_saved(&saved, app);
|
||||
self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty()));
|
||||
}
|
||||
|
||||
fn post_save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = file_name(path);
|
||||
self.host.post_save(&name, bytes, None, false)?;
|
||||
let name = file_name(Some(path), "document");
|
||||
self.save_target.post(SaveMessage::new(&name, bytes)).map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))?;
|
||||
self.saved.borrow_mut().push(name);
|
||||
Ok(())
|
||||
}
|
||||
@@ -118,6 +124,38 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// A save-only adapter: the pinned host crate's `post_save` cannot add app-specific fields.
|
||||
/// All other messages and transport detection still go through `Host`.
|
||||
enum SaveTarget {
|
||||
Parent { parent: web_sys::Window, origin: String },
|
||||
Page(web_sys::HtmlCanvasElement),
|
||||
}
|
||||
|
||||
impl SaveTarget {
|
||||
fn post(&self, save: SaveMessage<'_>) -> Result<(), JsValue> {
|
||||
let buffer = js_sys::Uint8Array::from(save.bytes).buffer();
|
||||
let kind = message_type(APP, Outgoing::Save.kind());
|
||||
let payload = js_sys::Object::new();
|
||||
let set = |key, value: JsValue| js_sys::Reflect::set(&payload, &JsValue::from_str(key), &value);
|
||||
set("name", save.name.into())?;
|
||||
set("bytes", buffer.clone().into())?;
|
||||
set("saveAs", JsValue::FALSE)?;
|
||||
set("export", JsValue::from_bool(save.export))?;
|
||||
match self {
|
||||
Self::Parent { parent, origin } => {
|
||||
set("type", kind.as_str().into())?;
|
||||
parent.post_message_with_transfer(&payload, origin, &js_sys::Array::of1(&buffer))
|
||||
}
|
||||
Self::Page(canvas) => {
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_detail(&payload.into());
|
||||
let event = web_sys::CustomEvent::new_with_event_init_dict(&kind, &init)?;
|
||||
canvas.dispatch_event(&event).map(|_| ())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an open message carries, pushed onto the inbox for the next frame, like a dropped
|
||||
/// file. A host's file is untrusted input: an oversized one is refused before it is copied into
|
||||
/// the app's memory (the data's own length, not the host's claim).
|
||||
@@ -133,11 +171,3 @@ fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData)
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((open_name(name), array.to_vec()));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
fn is_workbook(name: &str) -> bool {
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
|
||||
}
|
||||
|
||||
fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Host save payloads and workbook receipts, shared with native regression tests.
|
||||
|
||||
use gridcraft_ui_egui::SheetApp;
|
||||
|
||||
/// Only these outputs replace the editable workbook in the host.
|
||||
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
|
||||
|
||||
pub struct SaveMessage<'a> {
|
||||
pub name: &'a str,
|
||||
pub bytes: &'a [u8],
|
||||
pub export: bool,
|
||||
}
|
||||
|
||||
impl<'a> SaveMessage<'a> {
|
||||
pub fn new(name: &'a str, bytes: &'a [u8]) -> Self {
|
||||
// All other outputs are exports, not necessarily PDFs.
|
||||
Self { name, bytes, export: !is_workbook(name) }
|
||||
}
|
||||
}
|
||||
|
||||
fn is_workbook(name: &str) -> bool {
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
|
||||
}
|
||||
|
||||
/// Preserve the bridge's existing rule: only a workbook receipt marks the document saved.
|
||||
pub fn sync_saved(saved: &[String], app: &mut SheetApp) {
|
||||
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
|
||||
&& let Some(doc) = app.session.active_mut()
|
||||
{
|
||||
doc.saved = doc.wb.clone();
|
||||
if doc.path.is_none() {
|
||||
doc.title = name.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn save_payload_marks_exports_and_preserves_name_and_bytes() {
|
||||
let bytes = [0, 1, 127, 128, 255];
|
||||
for (name, export) in [("finance.xlsx", false), ("finance.XLSX", false), ("finance.pdf", true), ("finance.PDF", true)] {
|
||||
let message = SaveMessage::new(name, &bytes);
|
||||
assert_eq!(message.export, export, "{name}");
|
||||
assert_eq!(message.name, name);
|
||||
assert_eq!(message.bytes, bytes.as_slice());
|
||||
assert_eq!(message.bytes.as_ptr(), bytes.as_ptr(), "the payload borrows the original bytes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_outputs_are_exports_not_workbook_saves() {
|
||||
for name in ["finance.csv", "finance.bin", "finance", "finance.xlsx.pdf", "finance.xlsx.bak"] {
|
||||
assert!(SaveMessage::new(name, &[]).export, "{name}");
|
||||
}
|
||||
assert!(!SaveMessage::new("finance.pdf.xlsx", &[]).export);
|
||||
}
|
||||
|
||||
fn edited_app() -> Result<SheetApp, String> {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("cell.set", json!({"cell": "A1", "input": "42"})).map_err(|e| e.to_string())?;
|
||||
Ok(SheetApp::new(session, Default::default()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_receipts_leave_the_workbook_dirty_and_its_title_unchanged() -> Result<(), String> {
|
||||
for name in ["finance.pdf", "finance.PDF"] {
|
||||
let mut app = edited_app()?;
|
||||
let doc = app.session.active().ok_or("no active document")?;
|
||||
assert!(doc.is_dirty());
|
||||
let title = doc.title.clone();
|
||||
let saved = doc.saved.clone();
|
||||
sync_saved(&[name.to_string()], &mut app);
|
||||
let doc = app.session.active().ok_or("no active document")?;
|
||||
assert!(doc.is_dirty(), "{name}");
|
||||
assert!(Arc::ptr_eq(&saved, &doc.saved), "an export must not replace the saved snapshot");
|
||||
assert_eq!(doc.title, title);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workbook_receipts_mark_saved_and_later_exports_do_not_replace_them() -> Result<(), String> {
|
||||
for name in ["finance.xlsx", "finance.XLSX"] {
|
||||
let mut app = edited_app()?;
|
||||
assert!(app.session.active().ok_or("no active document")?.is_dirty());
|
||||
sync_saved(&[name.to_string(), "finance.pdf".to_string()], &mut app);
|
||||
let doc = app.session.active().ok_or("no active document")?;
|
||||
assert!(!doc.is_dirty());
|
||||
assert!(Arc::ptr_eq(&doc.saved, &doc.wb));
|
||||
assert_eq!(doc.title, name);
|
||||
app.session.execute("cell.set", json!({"cell": "A1", "input": "43"})).map_err(|e| e.to_string())?;
|
||||
sync_saved(&["finance.PDF".to_string()], &mut app);
|
||||
assert!(app.session.active().ok_or("no active document")?.is_dirty(), "a subsequent export leaves new edits unsaved");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod host_save;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod hostmode;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod prefs;
|
||||
|
||||
@@ -25,9 +25,6 @@ chrono = { workspace = true }
|
||||
# Icon + VERSIONINFO for gridcraft.exe; build.rs only uses it when the target is Windows.
|
||||
winresource = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Retain X11 fallback; draw Wayland client-side controls without bundled title fonts.
|
||||
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
|
||||
|
||||
+11
-20
@@ -17,6 +17,7 @@ mod graphics;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod opener;
|
||||
mod print;
|
||||
|
||||
use std::cell::RefCell;
|
||||
@@ -218,16 +219,16 @@ fn open_with_system(target: &str) {
|
||||
log::warn!("refused to open {target:?}: only http, https and mailto links are opened");
|
||||
return;
|
||||
};
|
||||
let target = target.as_str();
|
||||
let cmd = if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else if cfg!(windows) {
|
||||
"explorer"
|
||||
} else {
|
||||
"xdg-open"
|
||||
// By absolute path where the platform has one (#2176): a bare `explorer` would be looked up
|
||||
// in the application's directory first.
|
||||
let env = |key: &str| std::env::var(key).ok();
|
||||
let (system_root, windir) = (env("SystemRoot"), env("windir"));
|
||||
let Some((program, arg)) = opener::opener_command(opener::Os::current(), &target, system_root.as_deref(), windir.as_deref()) else {
|
||||
log::warn!("refused to open {target:?}: it could be read as an option");
|
||||
return;
|
||||
};
|
||||
if let Err(e) = std::process::Command::new(cmd).arg(target).spawn() {
|
||||
log::warn!("{cmd} {target}: {e}");
|
||||
if let Err(e) = std::process::Command::new(&program).arg(&arg).spawn() {
|
||||
log::warn!("{} {arg}: {e}", program.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,21 +359,11 @@ fn main() -> eframe::Result<()> {
|
||||
}
|
||||
let window_builder = viewport.clone();
|
||||
let options = eframe::NativeOptions { viewport, ..Default::default() };
|
||||
#[cfg(unix)]
|
||||
#[cfg(target_os = "macos")]
|
||||
let mut options = options;
|
||||
// Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (see graphics.rs).
|
||||
#[cfg(target_os = "macos")]
|
||||
graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64")));
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; GRIDCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()) && std::env::var_os("GRIDCRAFT_WAYLAND").is_none() {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
b.with_x11();
|
||||
}));
|
||||
}
|
||||
// Before eframe creates the wgpu instance: Windows starts on DirectX 12, or OpenGL when
|
||||
// DirectX 12 has no GPU driver, and never touches Vulkan unless asked (see graphics.rs).
|
||||
#[cfg(target_os = "windows")]
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! How a link is handed to the operating system's opener (#2176).
|
||||
//!
|
||||
//! The opener is spawned by absolute path where the platform has a fixed one: a bare program name
|
||||
//! on Windows is searched for in the application's own directory (and the current directory)
|
||||
//! before System32 and the Windows directory, so an `explorer.exe` planted next to a portable
|
||||
//! GridCraft would run with the user's session. The target never becomes an option of the opener,
|
||||
//! and on Windows the characters Explorer's own command-line parser treats specially are
|
||||
//! percent-encoded. Pure functions, so the tests run on every OS.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Whose opener to use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Os {
|
||||
Mac,
|
||||
Windows,
|
||||
/// Linux, the BSDs and other freedesktop systems: `xdg-open`.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Os {
|
||||
pub fn current() -> Os {
|
||||
if cfg!(target_os = "macos") {
|
||||
Os::Mac
|
||||
} else if cfg!(windows) {
|
||||
Os::Windows
|
||||
} else {
|
||||
Os::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Used when neither `SystemRoot` nor `windir` holds a usable path.
|
||||
const DEFAULT_WINDOWS_DIR: &str = "C:\\Windows";
|
||||
|
||||
/// The Windows directory: `SystemRoot`, else `windir`, else `C:\Windows`. A value is used only
|
||||
/// when it is a local drive path (`X:\…`) without `..` segments; relative or network values
|
||||
/// would bring back the search this exists to avoid.
|
||||
pub fn windows_dir(system_root: Option<&str>, windir: Option<&str>) -> String {
|
||||
[system_root, windir]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(str::trim)
|
||||
.find(|d| is_local_drive_path(d))
|
||||
.map_or(DEFAULT_WINDOWS_DIR, |d| d.trim_end_matches(['\\', '/']))
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// `X:\…` or `X:/…` (not the drive-relative `X:` or `X:dir`), with no `..` segment and no quote.
|
||||
fn is_local_drive_path(d: &str) -> bool {
|
||||
let mut chars = d.chars();
|
||||
let drive = chars.next().is_some_and(|c| c.is_ascii_alphabetic()) && chars.next() == Some(':');
|
||||
let rest = chars.as_str();
|
||||
let rooted = rest.starts_with(['\\', '/']);
|
||||
drive && rooted && !d.contains('"') && !rest.split(['\\', '/']).any(|seg| seg == "..")
|
||||
}
|
||||
|
||||
/// Percent-encodes the characters Explorer's command-line parser (comma-separated switches such
|
||||
/// as `/select,`), the C runtime's quoting rules and `cmd` treat specially: space, `"`, `,` and
|
||||
/// `^`. Space, `"` and `^` may not appear unencoded in a URL, so encoding them leaves the address
|
||||
/// unchanged. A comma may, and RFC 3986 does not treat `%2C` as equivalent to it (a `mailto:`
|
||||
/// recipient list is comma-separated); it is encoded anyway because Explorer's parser separates
|
||||
/// switches at commas, and a handler that percent-decodes the address sees the comma again.
|
||||
pub fn escape_for_explorer(target: &str) -> String {
|
||||
let mut out = String::with_capacity(target.len());
|
||||
for c in target.chars() {
|
||||
match c {
|
||||
' ' => out.push_str("%20"),
|
||||
'"' => out.push_str("%22"),
|
||||
',' => out.push_str("%2C"),
|
||||
'^' => out.push_str("%5E"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The program and its single argument that open `target` (already accepted by
|
||||
/// `links::classify`) on `os`. `None` when the target could be read as an option: it starts with
|
||||
/// `-` or `/`, or is empty. `xdg-open` takes no `--`, so refusing is the only safe answer.
|
||||
pub fn opener_command(os: Os, target: &str, system_root: Option<&str>, windir: Option<&str>) -> Option<(PathBuf, String)> {
|
||||
if target.is_empty() || target.starts_with(['-', '/']) {
|
||||
return None;
|
||||
}
|
||||
Some(match os {
|
||||
Os::Mac => (PathBuf::from("/usr/bin/open"), target.to_string()),
|
||||
Os::Windows => {
|
||||
let exe = format!("{}\\explorer.exe", windows_dir(system_root, windir));
|
||||
(PathBuf::from(exe), escape_for_explorer(target))
|
||||
}
|
||||
// Found on PATH: its location differs between distributions and the BSDs.
|
||||
Os::Other => (PathBuf::from("xdg-open"), target.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn windows_opener_is_explorer_in_the_windows_directory() {
|
||||
let (exe, arg) = opener_command(Os::Windows, "https://a.example/x", Some("C:\\Windows"), None).unwrap_or_default();
|
||||
assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe"));
|
||||
assert_eq!(arg, "https://a.example/x");
|
||||
// Never a bare name, whatever the environment says.
|
||||
for (root, windir) in [(None, None), (Some(""), Some("")), (Some("Windows"), None), (Some(".\\"), Some("explorer"))] {
|
||||
let (exe, _) = opener_command(Os::Windows, "https://a.example", root, windir).unwrap_or_default();
|
||||
assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe"), "{root:?} {windir:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_dir_prefers_system_root_then_windir_then_default() {
|
||||
assert_eq!(windows_dir(Some("D:\\WINNT\\"), Some("E:\\Win")), "D:\\WINNT");
|
||||
assert_eq!(windows_dir(None, Some("E:\\Win")), "E:\\Win");
|
||||
assert_eq!(windows_dir(Some("relative\\dir"), Some("e:/win/")), "e:/win");
|
||||
assert_eq!(windows_dir(None, None), "C:\\Windows");
|
||||
assert_eq!(windows_dir(Some("D:\\"), None), "D:");
|
||||
for bad in ["\\\\host\\share", "//host/share", "C:", "C:Windows", "C:\\Windows\\..\\Users\\x", "C:\\\"x", "", " ", "1:\\x"] {
|
||||
assert_eq!(windows_dir(Some(bad), None), "C:\\Windows", "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explorer_switch_characters_are_percent_encoded() {
|
||||
let (_, arg) = opener_command(Os::Windows, "https://x/,/select,C:\\Windows\\a b\"^", None, None).unwrap_or_default();
|
||||
assert_eq!(arg, "https://x/%2C/select%2CC:\\Windows\\a%20b%22%5E");
|
||||
assert!(!arg.contains([' ', '"', ',', '^']));
|
||||
assert_eq!(escape_for_explorer("mailto:a@b.example?subject=Hi there"), "mailto:a@b.example?subject=Hi%20there");
|
||||
// Other platforms get the address as it is.
|
||||
let (_, arg) = opener_command(Os::Other, "https://x/a,b", None, None).unwrap_or_default();
|
||||
assert_eq!(arg, "https://x/a,b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_and_freedesktop_openers() {
|
||||
let (exe, arg) = opener_command(Os::Mac, "https://a.example", None, None).unwrap_or_default();
|
||||
assert_eq!((exe, arg.as_str()), (PathBuf::from("/usr/bin/open"), "https://a.example"));
|
||||
let (exe, _) = opener_command(Os::Other, "mailto:a@b.example", None, None).unwrap_or_default();
|
||||
assert_eq!(exe, PathBuf::from("xdg-open"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_never_becomes_an_option() {
|
||||
for os in [Os::Mac, Os::Windows, Os::Other] {
|
||||
for bad in ["-a", "--help", "-e calc", "/select,C:\\x", "/root,C:\\", ""] {
|
||||
assert_eq!(opener_command(os, bad, None, None), None, "{os:?} {bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,11 @@ sync_github_name = false
|
||||
[people.edurbs]
|
||||
sync_github_name = true
|
||||
|
||||
[people.Cheejyg]
|
||||
real_name = "Glenn Chee"
|
||||
display_name = "Cheejyg"
|
||||
sync_github_name = false
|
||||
|
||||
[people.arcanii]
|
||||
real_name = "Bryan Mark"
|
||||
display_name = "Arcanii"
|
||||
|
||||
+73
-25
@@ -59,26 +59,29 @@ pub struct Calc {
|
||||
|
||||
/// Who gets the cells when two arrays want the same ones. Excel (measured by a reviewer on
|
||||
/// PR #2483) lets the spill that already exists keep its cells, whichever anchor comes first;
|
||||
/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here:
|
||||
/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here, for
|
||||
/// each cell both want:
|
||||
///
|
||||
/// 1. an anchor that held a spill before this calculation outranks one that did not;
|
||||
/// 2. otherwise the anchor first in reading order (row, then column) wins.
|
||||
/// 1. the anchor whose spill held that cell before this calculation keeps it, so an array that
|
||||
/// grows into another's area is `#SPILL!` even when it held a spill of its own;
|
||||
/// 2. otherwise an anchor that held a spill before this calculation outranks one that did not;
|
||||
/// 3. otherwise the anchor first in reading order (row, then column) wins.
|
||||
///
|
||||
/// Rule 2 alone decides when nothing is remembered, so the result never depends on hash order
|
||||
/// Rule 3 alone decides when nothing is remembered, so the result never depends on hash order
|
||||
/// or evaluation order. A full recalculation remembers the layout the sheet held before it
|
||||
/// started (rule 1), so it agrees with the incremental one; a workbook that is calculated for
|
||||
/// the first time has no such layout (rule 2 only).
|
||||
///
|
||||
/// Known limits: (a) the xlsx reader does not restore spill layouts, so a workbook opened from a
|
||||
/// file is laid out by rule 2 alone, although Excel keeps the layout the file records; (b) when
|
||||
/// both anchors held a spill and one grows into the other, rule 2 decides, where Excel keeps
|
||||
/// the cells the other already owns.
|
||||
/// started, so it agrees with the incremental one; a workbook that is calculated for the first
|
||||
/// time has no such layout (rule 3 only). The xlsx reader restores the area each dynamic array
|
||||
/// was saved spilling over, so a workbook opened from a file keeps the layout it was saved with.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Standing {
|
||||
/// `true`: `keys` are the anchors that held a spill (full recalculation, which lays every
|
||||
/// spill out afresh). `false`: `keys` are the formulas that held none (incremental).
|
||||
held: bool,
|
||||
keys: HashSet<Key>,
|
||||
/// The area each anchor that held a spill filled before this calculation, for the anchors the
|
||||
/// calculation lays out again (full: all of them; incremental: the formulas it recalculates).
|
||||
/// Any other anchor still fills the area the sheet shows.
|
||||
areas: HashMap<Key, RangeRef>,
|
||||
}
|
||||
|
||||
impl Standing {
|
||||
@@ -86,7 +89,7 @@ impl Standing {
|
||||
self.keys.contains(&k) == self.held
|
||||
}
|
||||
|
||||
/// Whether `a` takes cells from `b` when both want them.
|
||||
/// Whether `a` takes cells from `b` when both want them and neither held them (rules 2, 3).
|
||||
fn outranks(&self, a: Key, b: Key) -> bool {
|
||||
match (self.had_spill(a), self.had_spill(b)) {
|
||||
(true, false) => true,
|
||||
@@ -94,6 +97,22 @@ impl Standing {
|
||||
_ => (a.1.row, a.1.col) < (b.1.row, b.1.col),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `k`'s spill held `cell` before this calculation; `now` is the area the sheet
|
||||
/// shows for `k`.
|
||||
fn held_cell(&self, k: Key, now: Option<RangeRef>, cell: CellRef) -> bool {
|
||||
self.had_spill(k) && self.areas.get(&k).copied().or(now).is_some_and(|r| r.contains(cell))
|
||||
}
|
||||
|
||||
/// Whether `a` takes `cell` from `b` when both want it (rule 1, then [`Self::outranks`]). Each
|
||||
/// anchor comes with the area the sheet shows for it.
|
||||
fn outranks_at(&self, (a, a_now): (Key, Option<RangeRef>), (b, b_now): (Key, Option<RangeRef>), cell: CellRef) -> bool {
|
||||
match (self.held_cell(a, a_now, cell), self.held_cell(b, b_now, cell)) {
|
||||
(true, false) => true,
|
||||
(false, true) => false,
|
||||
_ => self.outranks(a, b),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of cells by row, each row's columns in their own set: a window of rows and columns is
|
||||
@@ -313,12 +332,18 @@ impl Calc {
|
||||
self.rebuild(wb);
|
||||
// The layout the sheets hold now decides who keeps cells two arrays both want.
|
||||
// (A Python cell that holds a spill counts too, as it does in the incremental pass.)
|
||||
let mut held = HashSet::default();
|
||||
let mut areas: HashMap<Key, RangeRef> = HashMap::default();
|
||||
for i in 0..wb.sheets.len() {
|
||||
if let Some(sh) = wb.sheet(i) {
|
||||
held.extend(sh.spill_ranges.keys().filter(|a| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some())).map(|a| (i, *a)));
|
||||
areas.extend(
|
||||
sh.spill_ranges
|
||||
.iter()
|
||||
.filter(|(a, _)| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some()))
|
||||
.map(|(a, r)| ((i, *a), *r)),
|
||||
);
|
||||
}
|
||||
}
|
||||
let held = areas.keys().copied().collect();
|
||||
// Spills are laid out again from the formulas where they are now (a structural edit moves
|
||||
// or deletes the formulas, not the values they spilled).
|
||||
for i in 0..wb.sheets.len() {
|
||||
@@ -330,7 +355,7 @@ impl Calc {
|
||||
}
|
||||
}
|
||||
let all: Vec<Key> = self.graph.nodes.keys().copied().collect();
|
||||
self.standing = Standing { held: true, keys: held };
|
||||
self.standing = Standing { held: true, keys: held, areas };
|
||||
self.run(wb, all, true);
|
||||
self.standing = Standing::default();
|
||||
}
|
||||
@@ -542,8 +567,15 @@ impl Calc {
|
||||
if !full {
|
||||
// What each formula held before this calculation touched it.
|
||||
for &k in &dirty {
|
||||
if seen.insert(k) && wb.sheet(k.0).is_some_and(|s| !s.spill_ranges.contains_key(&k.1)) {
|
||||
self.standing.keys.insert(k);
|
||||
if seen.insert(k) {
|
||||
match wb.sheet(k.0).and_then(|s| s.spill_ranges.get(&k.1)) {
|
||||
Some(r) => {
|
||||
self.standing.areas.insert(k, *r);
|
||||
}
|
||||
None => {
|
||||
self.standing.keys.insert(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -664,7 +696,7 @@ impl Calc {
|
||||
let end = CellRef::new(key.1.row.saturating_add(array.rows as u32 - 1), key.1.col.saturating_add(array.cols as u32 - 1));
|
||||
let range = RangeRef::new(key.1, end);
|
||||
// Two arrays that want the same cells (see [`Standing`]): a spill already laid out
|
||||
// that this anchor outranks is taken over, and recalculated.
|
||||
// that this anchor outranks on every cell they share is taken over, and recalculated.
|
||||
let standing = &self.standing;
|
||||
// A spill can only be in the way where it has cells besides its anchor, and an
|
||||
// anchor itself blocks the array. When no spilled cell lies in the range, the owners
|
||||
@@ -675,13 +707,18 @@ impl Calc {
|
||||
sheet
|
||||
.spill_ranges
|
||||
.iter()
|
||||
.filter(|(o, r)| **o != key.1 && r.intersects(&range) && standing.outranks(*key, (key.0, **o)))
|
||||
.filter(|(o, r)| {
|
||||
**o != key.1
|
||||
&& r.intersection(&range).is_some_and(|shared| {
|
||||
shared.iter().all(|cell| standing.outranks_at((*key, old), ((key.0, **o), Some(**r)), cell))
|
||||
})
|
||||
})
|
||||
.map(|(o, r)| (*o, *r))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let blocked = spill_is_blocked(sheet, *key, range, end, standing);
|
||||
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
|
||||
if !blocked {
|
||||
for (o, r) in outranked {
|
||||
for c in r.iter() {
|
||||
@@ -739,11 +776,22 @@ thread_local! {
|
||||
pub(crate) static OWNER_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether the array at `anchor` can't be laid out over `range`. A spill already laid out that
|
||||
/// `anchor` outranks does not block it: it is taken over when written back.
|
||||
fn spill_is_blocked(sheet: &gridcraft_model::Sheet, anchor: Key, range: RangeRef, end: CellRef, standing: &Standing) -> bool {
|
||||
let outranked =
|
||||
|cell: CellRef| sheet.spill_ranges.iter().any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks(anchor, (anchor.0, *o)));
|
||||
/// Whether the array at `anchor` (with the area the sheet showed for it) can't be laid out over
|
||||
/// `range`. A spill already laid out that `anchor` outranks does not block it: it is taken over
|
||||
/// when written back.
|
||||
fn spill_is_blocked(
|
||||
sheet: &gridcraft_model::Sheet,
|
||||
(anchor, now): (Key, Option<RangeRef>),
|
||||
range: RangeRef,
|
||||
end: CellRef,
|
||||
standing: &Standing,
|
||||
) -> bool {
|
||||
let outranked = |cell: CellRef| {
|
||||
sheet
|
||||
.spill_ranges
|
||||
.iter()
|
||||
.any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks_at((anchor, now), ((anchor.0, *o), Some(*r)), cell))
|
||||
};
|
||||
end.row >= gridcraft_core::MAX_ROWS
|
||||
|| end.col >= gridcraft_core::MAX_COLS
|
||||
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
|
||||
|
||||
@@ -163,9 +163,9 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
|
||||
}
|
||||
|
||||
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
|
||||
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it
|
||||
/// (see `Standing`; unless that formula is recalculated in this pass, and so may spill elsewhere
|
||||
/// now). A spill it outranks gives way to it when written back.
|
||||
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
|
||||
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
|
||||
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
|
||||
fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
|
||||
let Some(sh) = host.wb.sheet(sheet) else { return false };
|
||||
let end =
|
||||
@@ -182,7 +182,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
|
||||
&& r.contains(c)
|
||||
&& !host.exprs.contains_key(&(sheet, *o))
|
||||
&& !host.python.contains_key(&(sheet, *o))
|
||||
&& standing.outranks((sheet, *o), (sheet, anchor))
|
||||
&& standing.outranks_at(((sheet, *o), Some(*r)), ((sheet, anchor), own.copied()), c)
|
||||
})
|
||||
};
|
||||
end.row >= gridcraft_core::MAX_ROWS
|
||||
|
||||
@@ -368,6 +368,24 @@ fn iterative_calculation_of_text_and_errors() {
|
||||
assert_eq!(t.get("B1"), Value::Error(CellError::Div0));
|
||||
}
|
||||
|
||||
/// `&`, CONCAT and TEXTJOIN turn a number into at most 15 significant digits, decimal unless that
|
||||
/// would need 16 integer digits or more than 21 characters below 1.
|
||||
#[test]
|
||||
fn text_joins_convert_numbers_to_15_significant_digits() {
|
||||
let mut t = T::new();
|
||||
for (formula, text) in [
|
||||
("=(1E15-0.5)&\"\"", "1E+15"),
|
||||
("=(999999999999999)&\"\"", "999999999999999"),
|
||||
("=1234567890123456&\"\"", "1.23456789012346E+15"),
|
||||
("=(9.99999999999999E-9)&\"\"", "9.99999999999999E-09"),
|
||||
("=CONCAT(1/3*1E-5)", "3.33333333333333E-06"),
|
||||
("=TEXTJOIN(\",\",TRUE,1/3*1E-4,0.1+0.2)", "0.0000333333333333333,0.3"),
|
||||
] {
|
||||
t.set("A1", formula);
|
||||
assert_eq!(t.get("A1"), Value::from(text), "{formula}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circular_references_without_iterative_calculation() {
|
||||
let mut t = T::new();
|
||||
@@ -706,6 +724,53 @@ fn spill_into_the_old_area_of_a_blocked_neighbour() {
|
||||
assert_eq!([t.num("C8"), t.num("D8"), t.num("C9"), t.num("D9")], [1.0, 2.0, 3.0, 4.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_recalc_keeps_a_spill_from_an_array_that_grew_into_it() {
|
||||
// Both arrays spill; in manual calculation F13 then grows over F14:G14, which C14's array
|
||||
// fills. A full recalculation gives what an automatic one would: C14 keeps its cells and F13
|
||||
// is #SPILL!, although F13 comes first in reading order.
|
||||
let mut t = T::new();
|
||||
t.set("J1", "1");
|
||||
t.set("C14", "=SEQUENCE(1,7)");
|
||||
t.set("F13", "=SEQUENCE(J1,2)");
|
||||
assert_eq!([t.num("F13"), t.num("G13")], [1.0, 2.0]);
|
||||
t.wb.calc.mode = gridcraft_model::CalcMode::Manual;
|
||||
t.set("J1", "5");
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
assert_eq!(t.get("F13"), Value::Error(CellError::Spill));
|
||||
assert_eq!([t.num("C14"), t.num("F14"), t.num("G14"), t.num("I14")], [1.0, 4.0, 5.0, 7.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_recalc_lays_out_arrays_as_an_automatic_one_when_one_shrinks_for_another() {
|
||||
// C1 grows into C3, which A3's array fills, and A3 grows into E3, which E1's array leaves.
|
||||
// Automatic recalculation lays them out in reading order with each former area still filled:
|
||||
// C1 is #SPILL! and A3 takes A3:E3. A full recalculation after the same edit in manual
|
||||
// calculation gives the same sheet.
|
||||
let build = |manual: bool| {
|
||||
let mut t = T::new();
|
||||
t.set("J1", "2");
|
||||
t.set("C1", "=SEQUENCE(J1)");
|
||||
t.set("A3", "=SEQUENCE(1,J1+1)");
|
||||
t.set("E1", "=SEQUENCE(5-J1)");
|
||||
assert_eq!([t.num("C2"), t.num("C3"), t.num("E3")], [2.0, 3.0, 3.0]);
|
||||
if manual {
|
||||
t.wb.calc.mode = gridcraft_model::CalcMode::Manual;
|
||||
}
|
||||
t.set("J1", "4");
|
||||
if manual {
|
||||
t.calc.recalc_all(&mut t.wb);
|
||||
}
|
||||
t
|
||||
};
|
||||
let (automatic, full) = (build(false), build(true));
|
||||
assert_eq!(automatic.get("C1"), Value::Error(CellError::Spill));
|
||||
assert_eq!([automatic.num("A3"), automatic.num("C3"), automatic.num("E3")], [1.0, 3.0, 5.0]);
|
||||
for cell in ["A1", "C1", "C2", "C3", "C4", "E1", "E2", "A3", "B3", "C3", "D3", "E3"] {
|
||||
assert_eq!(full.get(cell), automatic.get(cell), "{cell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formulas_reading_an_array_that_loses_a_spill_conflict_read_spill_errors() {
|
||||
// Two arrays of one recalculation want the same empty cell: the one laid out second is
|
||||
|
||||
@@ -444,14 +444,27 @@ pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
|
||||
}
|
||||
}
|
||||
|
||||
/// Number → text the way Excel converts in `&` and `TEXT(x,"General")`-free contexts: up to 15
|
||||
/// significant digits, scientific for very large or very small magnitudes.
|
||||
/// Number → text the way Excel converts in `&`, CONCAT and TEXTJOIN: at most 15 significant
|
||||
/// digits, rounded first; scientific from 1E+15, below 1E-9, and wherever the decimal would be
|
||||
/// longer than 21 characters, not counting the sign (`0.` plus 19 decimals). Excel-verified only
|
||||
/// for positive 15-digit mantissas: `0.0000692361330972509` stays decimal and
|
||||
/// `1.28233995888454E-06` does not, as Excel caches them. The limit for shorter mantissas from
|
||||
/// 1E-6 to 1E-9 (e.g. `0.0000099999999999999` decimal) and for negatives (sign excluded) are
|
||||
/// inferred.
|
||||
pub fn number_to_text(n: f64) -> String {
|
||||
if n == 0.0 || !n.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
// Round to 15 significant digits first, then pick decimal or scientific from the rounded
|
||||
// magnitude, so 999999999999999.5 reads `1E+15`, never a 16-digit integer.
|
||||
let a = n.abs();
|
||||
if !(1e-9..1e15).contains(&a) && a.round() != a || a >= 1e15 {
|
||||
let sci = format!("{:.14e}", n);
|
||||
let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
|
||||
let mag: i32 = exp.parse().unwrap_or(0);
|
||||
let sig = mant.bytes().filter(u8::is_ascii_digit).count() - mant.bytes().rev().take_while(|&b| b == b'0').count();
|
||||
// Characters after `0.` for |n| < 1: the leading zeros, then the significant digits.
|
||||
let decimals_below_one = -mag - 1 + sig as i32;
|
||||
if !(-9..15).contains(&mag) || decimals_below_one > 19 {
|
||||
return sci_text(n, 15);
|
||||
}
|
||||
// A value just below 1e15 can round up to 1e15 at 15 significant digits. Only that narrow
|
||||
@@ -460,7 +473,6 @@ pub fn number_to_text(n: f64) -> String {
|
||||
return sci_text(n, 15);
|
||||
}
|
||||
// 15 significant digits, trailing zeros trimmed.
|
||||
let mag = a.log10().floor() as i32;
|
||||
let decimals = (14 - mag).clamp(0, 30) as usize;
|
||||
let s = format!("{:.*}", decimals, n);
|
||||
trim_decimal(&s)
|
||||
@@ -499,9 +511,44 @@ mod tests {
|
||||
assert_eq!(number_to_text(1234567890123456.0), "1.23456789012346E+15");
|
||||
assert_eq!(number_to_text(0.0001), "0.0001");
|
||||
assert_eq!(number_to_text(1e-10), "1E-10");
|
||||
assert_eq!(number_to_text(1e15 - 0.5), "1E+15");
|
||||
assert_eq!(number_to_text(1e15 - 0.1), "1E+15");
|
||||
assert_eq!(number_to_text(-(1e15 - 0.5)), "-1E+15");
|
||||
assert_eq!(number_to_text(999999999999999.0), "999999999999999");
|
||||
assert_eq!(number_to_text(9.999999999999999e-10), "0.000000001");
|
||||
assert_eq!(number_to_text(-9.999999999999999e-10), "-0.000000001");
|
||||
assert_eq!(number_to_text(1.0 / 3.0), "0.333333333333333");
|
||||
}
|
||||
|
||||
/// Excel switches to scientific when the 15-digit decimal would be longer than 21 characters
|
||||
/// (`0.` plus 19 decimals). Excel-verified: IMTAN, IMSECH, IMCSCH and IMEXP results cached by
|
||||
/// Excel for Mac in the `formulas` project's test.xlsx (ENGINEERING!S53, R47, S37, V37, V39).
|
||||
#[test]
|
||||
fn number_text_small_magnitudes() {
|
||||
assert_eq!(number_to_text(6.92361330972509e-5), "0.0000692361330972509");
|
||||
assert_eq!(number_to_text(2.41377759972715e-4), "0.000241377759972715");
|
||||
assert_eq!(number_to_text(1.28233995888454e-6), "1.28233995888454E-06");
|
||||
assert_eq!(number_to_text(-4.48088972789593e-6), "-4.48088972789593E-06");
|
||||
assert_eq!(number_to_text(5.98317105631764e-7), "5.98317105631764E-07");
|
||||
assert_eq!(number_to_text(-2.99158552811404e-7), "-2.99158552811404E-07");
|
||||
// Just below powers of ten: the 21-character limit, and the rounded magnitude.
|
||||
assert_eq!(number_to_text(9.99999999999999e-5), "0.0000999999999999999");
|
||||
assert_eq!(number_to_text(9.99999999999999e-6), "9.99999999999999E-06");
|
||||
assert_eq!(number_to_text(9.9999999999999e-6), "0.0000099999999999999");
|
||||
assert_eq!(number_to_text(9.99999999999999e-9), "9.99999999999999E-09");
|
||||
assert_eq!(number_to_text(-9.99999999999999e-9), "-9.99999999999999E-09");
|
||||
assert_eq!(number_to_text(9.99999999999999e-10), "9.99999999999999E-10");
|
||||
assert_eq!(number_to_text(9.999999999999999e-6), "0.00001");
|
||||
assert_eq!(number_to_text(0.00001), "0.00001");
|
||||
assert_eq!(number_to_text(0.000001), "0.000001");
|
||||
assert_eq!(number_to_text(1.5e-9), "0.0000000015");
|
||||
// Large side: 15 significant digits, scientific from 1E+15.
|
||||
assert_eq!(number_to_text(99999999999999.9), "99999999999999.9");
|
||||
assert_eq!(number_to_text(999999999999999.4), "999999999999999");
|
||||
assert_eq!(number_to_text(9999999999999998.0), "1E+16");
|
||||
assert_eq!(number_to_text(9.99999999999999e15), "9.99999999999999E+15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_text_rounds_up_to_scientific_boundary() {
|
||||
assert_eq!(number_to_text(999999999999999.9), "1E+15");
|
||||
|
||||
+48
-2
@@ -4,7 +4,9 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value, compare};
|
||||
use gridcraft_model::{CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Underline, Workbook, default_icon_thresholds};
|
||||
use gridcraft_model::{
|
||||
CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Table, Underline, Workbook, default_icon_thresholds,
|
||||
};
|
||||
|
||||
/// The conditional look of one cell.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -20,10 +22,12 @@ pub struct CfLook {
|
||||
pub hide_value: bool,
|
||||
}
|
||||
|
||||
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates).
|
||||
/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates), and each
|
||||
/// table's visible edges. The grid and print keep one per paint.
|
||||
#[derive(Default)]
|
||||
pub struct CfCache {
|
||||
stats: HashMap<usize, RuleStats>,
|
||||
table_edges: HashMap<RangeRef, crate::tables::ShownEdges>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
@@ -275,6 +279,11 @@ impl CfCache {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// [`crate::tables::shown_edges`] of `t`, found once per cache.
|
||||
pub fn table_edges(&mut self, sh: &Sheet, t: &Table) -> crate::tables::ShownEdges {
|
||||
*self.table_edges.entry(t.range).or_insert_with(|| crate::tables::shown_edges(sh, t))
|
||||
}
|
||||
|
||||
/// Conditional look of `c`, or `None` when no rule applies.
|
||||
pub fn look(&mut self, wb: &Workbook, sheet: usize, c: CellRef) -> Option<CfLook> {
|
||||
let sh = wb.sheet(sheet)?;
|
||||
@@ -728,6 +737,43 @@ mod tests {
|
||||
assert_eq!([look("A1"), look("A2")], [true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_compare_with_cells_on_other_sheets() {
|
||||
let mut s = crate::Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "E1", "values": [["Suspended"], ["OK"], ["Terminated"], [7], [3]]})).unwrap();
|
||||
let rule = |r: serde_json::Value| json!({"range": "E1:E5", "rule": r});
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$8", "preset": "redText"})),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$9", "preset": "redText"})),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute(
|
||||
"home.conditionalFormat",
|
||||
rule(json!({"type": "expression", "formula": "=AND(ISNUMBER(E1),E1>'Vehicle Range'!$B$1)", "preset": "yellowFill"})),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "Vehicle Range"})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "'Vehicle Range'!A8", "values": [["Suspended"], ["Terminated"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "'Vehicle Range'!B1", "values": [[5]]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let report = d.wb.sheets.iter().position(|sh| sh.name != "Vehicle Range").unwrap();
|
||||
let mut cache = CfCache::new();
|
||||
let mut look = |a: &str| cache.look(&d.wb, report, CellRef::parse(a).unwrap()).and_then(|l| l.style).unwrap_or_default();
|
||||
let looks = ["E1", "E2", "E3", "E4", "E5"].map(&mut look);
|
||||
// The cells equal to 'Vehicle Range'!A8 or A9 get the red text.
|
||||
let red_text = looks[0].font.color;
|
||||
assert_ne!(red_text, Color::Auto);
|
||||
let red = |st: &Style| st.font.color == red_text;
|
||||
let filled = |st: &Style| st.fill.pattern == PatternType::Solid;
|
||||
assert_eq!(looks.each_ref().map(red), [true, false, true, false, false]);
|
||||
assert_eq!(looks.each_ref().map(filled), [false, false, false, true, false]);
|
||||
}
|
||||
#[test]
|
||||
fn text_rules_skip_error_values() {
|
||||
let mut s = crate::Session::new();
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Where a chart's data sits on a sheet, as the blocks a selected chart outlines: series names in
|
||||
//! red, category labels in purple and values in blue (#4390). Dragging a corner of the values
|
||||
//! block points the chart at other cells, and the names and categories follow it (#4389).
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, col_to_letters};
|
||||
use gridcraft_formula::{Expr, RefKind, SheetSel, parse, quote_sheet};
|
||||
use gridcraft_model::{Chart, Series, Workbook};
|
||||
|
||||
/// Most series a chart takes from a dragged block (Excel's limit per chart).
|
||||
pub const MAX_SERIES: u32 = 255;
|
||||
/// Most cells a dragged values block may span, as for `chart.selectData`.
|
||||
pub const MAX_CELLS: u64 = 1_000_000;
|
||||
|
||||
/// A chart's data as blocks of cells on one sheet.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ChartData {
|
||||
/// The sheet the data is on.
|
||||
pub sheet: usize,
|
||||
/// Every series' values: one column per series (one row with `by_rows`), in series order.
|
||||
pub values: RangeRef,
|
||||
/// Series run across rows rather than down columns.
|
||||
pub by_rows: bool,
|
||||
/// The category labels every series shares, when they line up beside `values`.
|
||||
pub categories: Option<RangeRef>,
|
||||
/// One name cell per series, in the line beside `values`, when every series has one there.
|
||||
pub names: Option<RangeRef>,
|
||||
}
|
||||
|
||||
impl ChartData {
|
||||
/// The blocks after the values move to `to`: category labels keep their column (row) and
|
||||
/// span the new points, and names keep their row (column) and span the new series.
|
||||
pub fn moved(&self, to: RangeRef) -> ChartData {
|
||||
let (categories, names) = if self.by_rows {
|
||||
(
|
||||
self.categories.map(|c| RangeRef::new(CellRef::new(c.start.row, to.start.col), CellRef::new(c.start.row, to.end.col))),
|
||||
self.names.map(|n| RangeRef::new(CellRef::new(to.start.row, n.start.col), CellRef::new(to.end.row, n.start.col))),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
self.categories.map(|c| RangeRef::new(CellRef::new(to.start.row, c.start.col), CellRef::new(to.end.row, c.start.col))),
|
||||
self.names.map(|n| RangeRef::new(CellRef::new(n.start.row, to.start.col), CellRef::new(n.start.row, to.end.col))),
|
||||
)
|
||||
};
|
||||
ChartData { values: to, categories, names, ..*self }
|
||||
}
|
||||
|
||||
/// The cells of series `i` within `values` (`None` past the last series).
|
||||
fn line(&self, values: RangeRef, i: u32) -> Option<RangeRef> {
|
||||
if self.by_rows {
|
||||
let row = values.start.row.checked_add(i).filter(|r| *r <= values.end.row)?;
|
||||
Some(RangeRef::new(CellRef::new(row, values.start.col), CellRef::new(row, values.end.col)))
|
||||
} else {
|
||||
let col = values.start.col.checked_add(i).filter(|c| *c <= values.end.col)?;
|
||||
Some(RangeRef::new(CellRef::new(values.start.row, col), CellRef::new(values.end.row, col)))
|
||||
}
|
||||
}
|
||||
|
||||
/// How many series `values` holds.
|
||||
fn count(&self, values: RangeRef) -> u32 {
|
||||
if self.by_rows { values.height() } else { values.width() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The sheet and cells a series reference names. `home` is the chart's own sheet, for an
|
||||
/// unqualified reference. Literals, names, 3-D spans, other workbooks and whole rows or columns
|
||||
/// are not blocks.
|
||||
fn block(wb: &Workbook, home: usize, text: &str) -> Option<(usize, RangeRef)> {
|
||||
let Ok(Expr::Ref(r)) = parse(text.trim().trim_start_matches('=')) else { return None };
|
||||
let sheet = match &r.sheet {
|
||||
SheetSel::Current => home,
|
||||
SheetSel::Named(n) => wb.sheet_index(n)?,
|
||||
SheetSel::Span(..) => return None,
|
||||
};
|
||||
matches!(r.kind, RefKind::Cell(_) | RefKind::Range(..)).then(|| (sheet, r.range()))
|
||||
}
|
||||
|
||||
/// `chart`'s data on `home`'s workbook as blocks, when its series form one: every series' values
|
||||
/// on one sheet, in adjacent columns (or rows) of the same extent, in series order. `None` for
|
||||
/// any other layout, and for a PivotChart, whose series follow its PivotTable.
|
||||
pub fn chart_data(wb: &Workbook, home: usize, chart: &Chart) -> Option<ChartData> {
|
||||
if chart.pivot.is_some() {
|
||||
return None;
|
||||
}
|
||||
let first = chart.series.first()?;
|
||||
let (sheet, r0) = block(wb, home, &first.values)?;
|
||||
let by_rows = match (r0.width(), r0.height()) {
|
||||
(1, 1) => chart.by_rows,
|
||||
(1, _) => false,
|
||||
(_, 1) => true,
|
||||
_ => return None,
|
||||
};
|
||||
let n = u32::try_from(chart.series.len()).ok()?;
|
||||
let last = n.checked_sub(1)?;
|
||||
let values = if by_rows {
|
||||
RangeRef::new(r0.start, CellRef::new(r0.end.row.checked_add(last)?, r0.end.col))
|
||||
} else {
|
||||
RangeRef::new(r0.start, CellRef::new(r0.end.row, r0.end.col.checked_add(last)?))
|
||||
};
|
||||
let mut data = ChartData { sheet, values, by_rows, categories: None, names: None };
|
||||
for (i, se) in (0..n).zip(&chart.series) {
|
||||
if block(wb, home, &se.values) != Some((sheet, data.line(values, i)?)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// Category labels shared by every series, in one line beside the points. Compared as blocks,
|
||||
// not text: `=Sheet1!$A$2:$A$4` and `Sheet1!$A$2:$A$4` are the same labels.
|
||||
let cats = |se: &Series| se.categories.as_deref().and_then(|t| block(wb, home, t));
|
||||
if let Some((s, c)) = cats(first)
|
||||
&& s == sheet
|
||||
&& chart.series.iter().all(|se| cats(se) == Some((s, c)))
|
||||
{
|
||||
let lines_up = if by_rows {
|
||||
c.height() == 1
|
||||
&& (c.start.col, c.end.col) == (values.start.col, values.end.col)
|
||||
&& !(values.start.row..=values.end.row).contains(&c.start.row)
|
||||
} else {
|
||||
c.width() == 1
|
||||
&& (c.start.row, c.end.row) == (values.start.row, values.end.row)
|
||||
&& !(values.start.col..=values.end.col).contains(&c.start.col)
|
||||
};
|
||||
data.categories = lines_up.then_some(c);
|
||||
}
|
||||
// A name cell for every series, all in one line beside the values.
|
||||
let names: Option<Vec<CellRef>> = chart
|
||||
.series
|
||||
.iter()
|
||||
.map(|se| se.name.as_deref().and_then(|t| block(wb, home, t)).filter(|(s, r)| *s == sheet && r.is_single()).map(|(_, r)| r.start))
|
||||
.collect();
|
||||
if let Some(cells) = names
|
||||
&& let (Some(a), Some(b)) = (cells.first(), cells.last())
|
||||
{
|
||||
let lines_up = (0..n).zip(&cells).all(|(i, c)| {
|
||||
if by_rows {
|
||||
c.col == a.col && Some(c.row) == values.start.row.checked_add(i) && !(values.start.col..=values.end.col).contains(&c.col)
|
||||
} else {
|
||||
c.row == a.row && Some(c.col) == values.start.col.checked_add(i) && !(values.start.row..=values.end.row).contains(&c.row)
|
||||
}
|
||||
});
|
||||
data.names = lines_up.then(|| RangeRef::new(*a, *b));
|
||||
}
|
||||
Some(data)
|
||||
}
|
||||
|
||||
/// Why [`with_values`] refused.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ValuesError {
|
||||
/// The chart's series are not one block of cells ([`chart_data`] is `None`).
|
||||
NotABlock,
|
||||
/// The block is over [`MAX_CELLS`] cells or [`MAX_SERIES`] series.
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// `chart` with its values moved to `to` on the data's own sheet, as dragging a corner of the
|
||||
/// values outline does. Series `i` takes the `i`-th column (row) of `to` and keeps everything
|
||||
/// else it had (colour, kind, axis, trendlines); a wider block adds series and a narrower one
|
||||
/// drops the last ones. Category labels and names that line up follow the block; ones that don't
|
||||
/// stay as they are. A data range kept for Switch Row/Column becomes the moved blocks.
|
||||
pub fn with_values(wb: &Workbook, home: usize, chart: &Chart, to: RangeRef) -> Result<Chart, ValuesError> {
|
||||
let data = chart_data(wb, home, chart).ok_or(ValuesError::NotABlock)?;
|
||||
if to.count() > MAX_CELLS || data.count(to) > MAX_SERIES {
|
||||
return Err(ValuesError::TooLarge);
|
||||
}
|
||||
let sheet = wb.sheet(data.sheet).ok_or(ValuesError::NotABlock)?;
|
||||
let q = quote_sheet(&sheet.name);
|
||||
let row = |r: u32| u64::from(r) + 1;
|
||||
let range = |r: RangeRef| format!("{q}!${}${}:${}${}", col_to_letters(r.start.col), row(r.start.row), col_to_letters(r.end.col), row(r.end.row));
|
||||
let cell = |c: CellRef| format!("{q}!${}${}", col_to_letters(c.col), row(c.row));
|
||||
let moved = data.moved(to);
|
||||
let shared_cats = chart.series.first().and_then(|se| se.categories.clone());
|
||||
let mut out = chart.clone();
|
||||
// Keep the orientation the series were read in: a block of one cell per series is read by
|
||||
// `by_rows`, so a stale flag would make the moved series unreadable as a block.
|
||||
out.by_rows = data.by_rows;
|
||||
out.series = (0..data.count(to))
|
||||
.filter_map(|i| {
|
||||
let line = moved.line(to, i)?;
|
||||
let old = chart.series.get(i as usize);
|
||||
let mut se = old.cloned().unwrap_or_else(|| Series { categories: shared_cats.clone(), ..Series::default() });
|
||||
se.values = range(line);
|
||||
if let Some(c) = moved.categories {
|
||||
se.categories = Some(range(c));
|
||||
}
|
||||
if let Some(n) = moved.names {
|
||||
se.name =
|
||||
Some(cell(if data.by_rows { CellRef::new(line.start.row, n.start.col) } else { CellRef::new(n.start.row, line.start.col) }));
|
||||
}
|
||||
// Bubble sizes in a line of their own beside the old points span the new ones.
|
||||
if let (Some(old_line), Some(text)) = (data.line(data.values, i), se.bubble_sizes.clone())
|
||||
&& let Some((s, b)) = block(wb, home, &text)
|
||||
&& s == data.sheet
|
||||
{
|
||||
let follows = if data.by_rows {
|
||||
b.height() == 1 && (b.start.col, b.end.col) == (old_line.start.col, old_line.end.col)
|
||||
} else {
|
||||
b.width() == 1 && (b.start.row, b.end.row) == (old_line.start.row, old_line.end.row)
|
||||
};
|
||||
if follows {
|
||||
se.bubble_sizes = Some(range(if data.by_rows {
|
||||
RangeRef::new(CellRef::new(b.start.row, to.start.col), CellRef::new(b.start.row, to.end.col))
|
||||
} else {
|
||||
RangeRef::new(CellRef::new(to.start.row, b.start.col), CellRef::new(to.end.row, b.start.col))
|
||||
}));
|
||||
}
|
||||
}
|
||||
Some(se)
|
||||
})
|
||||
.collect();
|
||||
if out.source.is_some() {
|
||||
let all = [moved.categories, moved.names].into_iter().flatten().fold(to, |a, r| a.union(&r));
|
||||
out.source = Some(format!("{q}!{}", all.a1()));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -27,6 +27,7 @@ pub use filter::filter_values;
|
||||
pub(crate) use filter::{apply_filter, grow_autofilter};
|
||||
use filter::{clear_filter, filter_by, reapply, toggle_filter};
|
||||
use grouping::{detail, group, outline_settings, show_levels, subtotal};
|
||||
pub use sort::sort_context;
|
||||
use sort::{quick_sort, sort};
|
||||
#[cfg(test)]
|
||||
use tools::split_delimited;
|
||||
@@ -212,7 +213,7 @@ fn data_target(s: &Session, p: &Json, cmd: &str) -> Result<(usize, RangeRef)> {
|
||||
/// Excel's header guess: the first row is text over a column of numbers, or is bold.
|
||||
fn guess_header(wb: &Workbook, sh: &Sheet, r: RangeRef) -> bool {
|
||||
if let Some(t) = sh.table_at(r.start) {
|
||||
return t.header_row;
|
||||
return t.header_row && r.start.row == t.range.start.row;
|
||||
}
|
||||
if r.height() < 2 {
|
||||
return false;
|
||||
|
||||
@@ -28,6 +28,21 @@ fn sort_target(s: &Session, p: &Json) -> Result<(usize, RangeRef)> {
|
||||
Ok((sheet, data_range(s, p)?))
|
||||
}
|
||||
|
||||
/// The worksheet (index), range and header guess the Custom Sort dialog works on: the sheet named by
|
||||
/// `sheet` or a `Sheet!` prefix on `range`, else the active one.
|
||||
pub fn sort_context(s: &Session, p: &Json) -> Result<(usize, RangeRef, bool)> {
|
||||
let (sheet, explicit) = sort_target(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
let sel = d.selection.current();
|
||||
// An explicit block wins over the table range, so a selected totals row can be sorted.
|
||||
let r = match sh.used_range() {
|
||||
Some(used) if p.get("range").is_none() && !sel.is_single() => sel.intersection(&used).unwrap_or(sel),
|
||||
_ => explicit,
|
||||
};
|
||||
Ok((sheet, r, bool_param(p, "header").unwrap_or_else(|| guess_header(&d.wb, sh, r))))
|
||||
}
|
||||
|
||||
pub(super) fn quick_sort(s: &mut Session, p: &Json, asc: bool) -> Result<Json> {
|
||||
let (sheet, r) = sort_target(s, p)?;
|
||||
let col = col_param(p.get("column"), r.start.col).unwrap_or(s.doc()?.selection.active.col).clamp(r.start.col, r.end.col);
|
||||
@@ -68,7 +83,9 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
});
|
||||
}
|
||||
if keys.is_empty() {
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header})));
|
||||
let (sheet, r, header) = sort_context(s, p)?;
|
||||
let name = s.doc()?.wb.sheet(sheet).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?;
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("sort".into(), json!({"range": r.a1(), "header": header, "sheet": name})));
|
||||
return ok();
|
||||
}
|
||||
if keys.len() > 64 {
|
||||
|
||||
@@ -35,7 +35,7 @@ use go_to::go_to_special;
|
||||
#[cfg(test)]
|
||||
use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts};
|
||||
use paste_special::paste_special;
|
||||
pub(crate) use paste_special::{rewrite_all_formulas, rewrite_cell_links, rewrite_python_refs};
|
||||
pub(crate) use paste_special::{rewrite_all_formulas_many, rewrite_cell_links, rewrite_python_refs};
|
||||
use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
@@ -566,10 +566,15 @@ fn paste_validations(
|
||||
|
||||
/// Applies a reference adjustment to every cell formula and defined name in the workbook.
|
||||
pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> {
|
||||
rewrite_all_formulas_many(wb, target, std::slice::from_ref(e))
|
||||
}
|
||||
|
||||
/// [`rewrite_all_formulas`] for several edits applied in order, visiting each formula once.
|
||||
pub(crate) fn rewrite_all_formulas_many(wb: &mut gridcraft_model::Workbook, target: &str, edits: &[gridcraft_formula::adjust::Edit]) -> Result<()> {
|
||||
use gridcraft_formula::adjust::Edit;
|
||||
// Rows and columns inserted or deleted on the target sheet move its legacy array ranges too
|
||||
// (a cut moves its arrays itself).
|
||||
let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
|
||||
let moves_arrays = |e: &Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. });
|
||||
for si in 0..wb.sheets.len() {
|
||||
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
let keys: Vec<(CellRef, std::sync::Arc<Formula>)> =
|
||||
@@ -577,16 +582,29 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
|
||||
if keys.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let on_target = moves_arrays && host.eq_ignore_ascii_case(target);
|
||||
let on_target = host.eq_ignore_ascii_case(target);
|
||||
let Some(sheet) = wb.sheet_mut(si) else { continue };
|
||||
for (c, f) in keys {
|
||||
// Borrows the tree and copies and prints only the formulas the edit changes. A formula
|
||||
// the edit leaves alone keeps its stored text, even if that text is not canonical.
|
||||
let Some(new) = f.with_expr(|x| gridcraft_formula::adjust::adjust_if_changed(x, &host, target, e)) else { continue };
|
||||
let array = match f.array {
|
||||
Some(a) if on_target => crate::cmd::sheet::map_range(a, e),
|
||||
a => a,
|
||||
// Borrows the tree and copies and prints only the formulas the edits change. A formula
|
||||
// the edits leave alone keeps its stored text, even if that text is not canonical.
|
||||
let Some(new) = f.with_expr(|x| {
|
||||
let mut cur: Option<gridcraft_formula::Expr> = None;
|
||||
for e in edits {
|
||||
if let Some(n) = gridcraft_formula::adjust::adjust_if_changed(cur.as_ref().unwrap_or(x), &host, target, e) {
|
||||
cur = Some(n);
|
||||
}
|
||||
}
|
||||
cur
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let mut array = f.array;
|
||||
for e in edits {
|
||||
array = match array {
|
||||
Some(a) if on_target && moves_arrays(e) => crate::cmd::sheet::map_range(a, e),
|
||||
a => a,
|
||||
};
|
||||
}
|
||||
let nf = match new {
|
||||
Some(new) => Formula { array, dynamic: f.dynamic, ..Formula::from_expr(new) },
|
||||
None if array != f.array => Formula { array, ..(*f).clone() },
|
||||
@@ -600,12 +618,12 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &
|
||||
for n in wb.names.iter_mut() {
|
||||
if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) {
|
||||
// Names are workbook-level: unqualified refs don't occur; qualified ones adjust.
|
||||
let new = gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e);
|
||||
let new = edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e));
|
||||
n.formula = gridcraft_formula::print(&new);
|
||||
}
|
||||
}
|
||||
rewrite_cell_links(wb, |host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e));
|
||||
rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e))
|
||||
rewrite_cell_links(wb, |host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)));
|
||||
rewrite_python_refs(wb, &|host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e)))
|
||||
}
|
||||
|
||||
/// Runs `f` over every reference a floating object holds (a chart's series values, categories,
|
||||
|
||||
@@ -22,7 +22,7 @@ mod window;
|
||||
|
||||
pub(crate) use cells::is_checkbox_cell;
|
||||
use cells::{background, checkbox, draw_border, new_cell_style, recently_used, theme_colors, theme_fonts, toggle_checkbox, use_in_formula};
|
||||
use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data};
|
||||
use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data, set_values_range};
|
||||
use data::{from_csv, from_table_range, queries, table_resize};
|
||||
use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline};
|
||||
pub(crate) use scripts::has_scripts;
|
||||
@@ -61,6 +61,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
select_data
|
||||
),
|
||||
// Dragging a corner of a selected chart's values outline on the sheet (#4389).
|
||||
cmd!(
|
||||
"chart.setValuesRange",
|
||||
"Resize Chart Data",
|
||||
[],
|
||||
None,
|
||||
"{chart?, range: \"B2:C9\" (the block every series' values come from, one column or row per series, on the data's sheet; names and category labels that line up follow it, series keep their formatting)}",
|
||||
has_doc,
|
||||
set_values_range
|
||||
),
|
||||
cmd!("chart.changeType", "Change Chart Type…", ["Chart Design", "Type"], None, "{chart?, type, subtype?}", has_doc, |s, p| s
|
||||
.execute("chart.set", p.clone())),
|
||||
cmd!(
|
||||
|
||||
@@ -233,6 +233,38 @@ pub(super) fn select_data(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Points the chart's series at another block of cells on their sheet, keeping each series'
|
||||
/// formatting, as dragging a corner of the selected chart's values outline does (#4389).
|
||||
pub(super) fn set_values_range(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
use crate::chart_data::{ValuesError, chart_data, with_values};
|
||||
let text = str_param(p, "range").ok_or_else(|| bad("chart.setValuesRange", "missing `range`"))?;
|
||||
let (si, ci) = find_chart(s, p)?;
|
||||
let d = s.doc()?;
|
||||
let chart = d.wb.sheet(si).and_then(|sh| sh.charts.get(ci)).ok_or_else(|| bad("chart", "no such chart"))?;
|
||||
let Some(data) = chart_data(&d.wb, si, chart) else {
|
||||
return Err(bad("chart.setValuesRange", "the chart's series are not one block of cells"));
|
||||
};
|
||||
let (sheet_name, body) = split_sheet(text.trim().trim_start_matches('='));
|
||||
if let Some(n) = sheet_name
|
||||
&& d.wb.sheet_index(&n) != Some(data.sheet)
|
||||
{
|
||||
return Err(bad("chart.setValuesRange", "the range must be on the sheet the chart's data is on"));
|
||||
}
|
||||
let to = RangeRef::parse(body).ok_or_else(|| bad("chart.setValuesRange", "not a range"))?;
|
||||
let new = with_values(&d.wb, si, chart, to).map_err(|e| match e {
|
||||
ValuesError::NotABlock => bad("chart.setValuesRange", "the chart's series are not one block of cells"),
|
||||
ValuesError::TooLarge => bad("chart.setValuesRange", "range too large for a chart"),
|
||||
})?;
|
||||
let values = format!("{}!{}", gridcraft_formula::quote_sheet(d.wb.sheet(data.sheet).map_or("", |sh| sh.name.as_str())), to.a1());
|
||||
with_chart(s, p, move |c| {
|
||||
c.series = new.series;
|
||||
c.source = new.source;
|
||||
c.by_rows = new.by_rows;
|
||||
Ok(())
|
||||
})
|
||||
.map(|r| json!({"chart": r["chart"], "values": values}))
|
||||
}
|
||||
|
||||
pub(super) fn move_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, ci) = find_chart(s, p)?;
|
||||
let target = match p.get("sheet").and_then(Json::as_str) {
|
||||
|
||||
@@ -177,7 +177,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str
|
||||
let mut pics = PicCache::default();
|
||||
for lay in layouts {
|
||||
let Some(sh) = wb.sheet(lay.sheet) else { continue };
|
||||
let mut cf = if sh.cond_formats.is_empty() { None } else { Some(crate::cf::CfCache::new()) };
|
||||
let mut cf = crate::cf::CfCache::new();
|
||||
let k = lay.k();
|
||||
let (aw, ah) = lay.avail();
|
||||
for (pi, (ri, ci)) in lay.pages.iter().enumerate() {
|
||||
|
||||
@@ -25,12 +25,12 @@ pub(super) struct Look {
|
||||
pub(super) cf: Option<crate::cf::CfLook>,
|
||||
}
|
||||
|
||||
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut Option<crate::cf::CfCache>) -> Look {
|
||||
fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut crate::cf::CfCache) -> Look {
|
||||
let mut style = match sh.table_at(c) {
|
||||
Some(t) => crate::tables::table_cell_style(wb, si, t, c),
|
||||
Some(t) => crate::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c),
|
||||
None => wb.styles.get(sh.style_id(c)).clone(),
|
||||
};
|
||||
let cfl = cf.as_mut().and_then(|cache| cache.look(wb, si, c));
|
||||
let cfl = cf.look(wb, si, c);
|
||||
if let Some(st) = cfl.as_ref().and_then(|l| l.style.as_ref()) {
|
||||
if st.align.reading_order.is_some() {
|
||||
style.align.reading_order = st.align.reading_order;
|
||||
@@ -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 Option<crate::cf::CfCache>) {
|
||||
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) {
|
||||
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 {
|
||||
|
||||
@@ -242,15 +242,20 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert:
|
||||
/// Rewrites every formula reference (chart series included), sparkline source and PivotTable
|
||||
/// source for a structural edit on `target`.
|
||||
pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
|
||||
cx.edits.push((target.to_string(), e.clone()));
|
||||
rewrite_many(cx, target, std::slice::from_ref(e))
|
||||
}
|
||||
|
||||
/// [`rewrite`] for several edits applied in order, parsing each reference once.
|
||||
fn rewrite_many(cx: &mut Ctx, target: &str, edits: &[Edit]) -> Result<()> {
|
||||
cx.edits.extend(edits.iter().map(|e| (target.to_string(), e.clone())));
|
||||
let wb = &mut cx.wb;
|
||||
super::edit::rewrite_all_formulas(wb, target, e)?;
|
||||
super::edit::rewrite_all_formulas_many(wb, target, edits)?;
|
||||
for si in 0..wb.sheets.len() {
|
||||
let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
let Some(sh) = wb.sheet_mut(si) else { continue };
|
||||
let fix = |text: &str| -> String {
|
||||
match gridcraft_formula::parse(text) {
|
||||
Ok(expr) => gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e)),
|
||||
Ok(expr) => gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))),
|
||||
Err(_) => text.to_string(),
|
||||
}
|
||||
};
|
||||
@@ -263,7 +268,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> {
|
||||
let body = pt.source.trim().trim_start_matches('=');
|
||||
if let Ok(expr) = gridcraft_formula::parse(body) {
|
||||
let before = gridcraft_formula::print(&expr);
|
||||
let after = gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e));
|
||||
let after = gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e)));
|
||||
if after != before {
|
||||
pt.source = after;
|
||||
}
|
||||
@@ -378,23 +383,21 @@ fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result<Json> {
|
||||
let out = edit(s, |cx| {
|
||||
let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default();
|
||||
cx.protection_checked = true;
|
||||
// Last area first, so the earlier ones keep their positions.
|
||||
for (at, count) in areas {
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let block = match axis {
|
||||
Axis::Rows => RangeRef::rows(at, (at + count - 1).min(MAX_ROWS - 1)),
|
||||
Axis::Cols => RangeRef::cols(at, (at + count - 1).min(MAX_COLS - 1)),
|
||||
};
|
||||
sh.take_cells(block);
|
||||
match axis {
|
||||
Axis::Rows => sh.cells.shift_rows(at + count, -(count as i64)),
|
||||
Axis::Cols => sh.cells.shift_cols(at + count, -(count as i64)),
|
||||
}
|
||||
{
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// Cells move once, past every deleted area above or left of them.
|
||||
let ascending: Vec<(u32, u32)> = areas.iter().rev().copied().collect();
|
||||
match axis {
|
||||
Axis::Rows => sh.cells.delete_rows(&ascending),
|
||||
Axis::Cols => sh.cells.delete_cols(&ascending),
|
||||
}
|
||||
// Last area first, so the earlier ones keep their positions.
|
||||
for &(at, count) in &areas {
|
||||
shift_sheet_features(sh, axis, at, count, false);
|
||||
}
|
||||
rewrite(cx, &name, &Edit::Delete { axis, at, count })?;
|
||||
}
|
||||
let edits: Vec<Edit> = areas.iter().map(|&(at, count)| Edit::Delete { axis, at, count }).collect();
|
||||
rewrite_many(cx, &name, &edits)?;
|
||||
cx.structural = true;
|
||||
Ok(Json::Null)
|
||||
})?;
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::Mutex;
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value};
|
||||
use gridcraft_model::{Sheet, Workbook};
|
||||
use gridcraft_numfmt::{Formatted, NumberFormat, format_value};
|
||||
use gridcraft_numfmt::{Formatted, NumberFormat, format_value, format_value_full};
|
||||
|
||||
/// Parsed number formats are cached by code.
|
||||
pub(crate) fn parsed(code: &str) -> NumberFormat {
|
||||
@@ -116,7 +116,8 @@ pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool {
|
||||
wb.styles.get(sheet.style_id(at)).protection.hidden
|
||||
}
|
||||
|
||||
/// The text a cell shows (full precision General; the grid narrows General to fit the column).
|
||||
/// The text a cell shows (General up to the 11-character cell width; the grid narrows General
|
||||
/// further to fit the column).
|
||||
pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
if sheet.show_formulas
|
||||
&& let Some(f) = sheet.cell(c).and_then(|x| x.formula.as_ref())
|
||||
@@ -124,20 +125,35 @@ pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
{
|
||||
return format!("={}", f.text);
|
||||
}
|
||||
value_text(wb, sheet, c)
|
||||
shown_text(wb, sheet, c)
|
||||
}
|
||||
|
||||
/// A cell's value with its number format applied, independent of column width: no `#####`
|
||||
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result.
|
||||
/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result. A number
|
||||
/// shown as General (also through a coloured or sectioned General, or a Text format) is written
|
||||
/// as [`format_value_full`] writes it, never with an exponent: `&`'s 15 significant digits below
|
||||
/// 1E+15 (`124412140710`, not `1.24412E+11`), the shortest round-trip digits from 1E+15 (every
|
||||
/// integer below 1e16 exactly). Excel writes the cell display.
|
||||
pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
let style = wb.styles.get(sheet.style_id(c));
|
||||
with_fill_space(format_value_full(&sheet.value(c), &parsed(style.num_fmt.as_str()), wb.date_system))
|
||||
}
|
||||
|
||||
/// A cell's value through its number format, General at the 11-character cell width.
|
||||
fn shown_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String {
|
||||
let style = wb.styles.get(sheet.style_id(c));
|
||||
value_text_as(wb, &sheet.value(c), style.num_fmt.as_str())
|
||||
}
|
||||
|
||||
/// [`value_text`] for a value and a format code given apart from a cell (print takes the code
|
||||
/// from the cell's effective look, which a conditional format can override).
|
||||
/// A value through a format code given apart from a cell, as a cell shows it (General at the
|
||||
/// 11-character cell width). Print takes the code from the cell's effective look, which a
|
||||
/// conditional format can override.
|
||||
pub fn value_text_as(wb: &Workbook, v: &Value, code: &str) -> String {
|
||||
let f = format(v, code, wb);
|
||||
with_fill_space(format(v, code, wb))
|
||||
}
|
||||
|
||||
/// The formatted text with a single space where a `*x` repeat fill would expand.
|
||||
fn with_fill_space(f: Formatted) -> String {
|
||||
match f.fill {
|
||||
Some((_, pos)) => {
|
||||
let mut t = f.text;
|
||||
|
||||
+48
-15
@@ -558,20 +558,13 @@ pub fn source_path(path: &str) -> Option<std::path::PathBuf> {
|
||||
/// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all
|
||||
/// characters in each cell" (Microsoft Support, *Excel formatting and features that are not
|
||||
/// transferred to other file formats*): number formats applied, never column-width `#####`.
|
||||
/// One intentional difference: a number shown as General is not narrowed to the cell width and
|
||||
/// never gets an exponent (`gridcraft_numfmt::format_value_full`). Below 1E+15 it is written as
|
||||
/// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as
|
||||
/// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers
|
||||
/// that `&` writes in scientific notation as their 15 digits in full.
|
||||
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
|
||||
gridcraft_xlsx::write_csv(sh, delimiter, |c| {
|
||||
// General's grid-width formatting rounds large identifiers to scientific notation.
|
||||
// Delimited files have no column width, so preserve the whole numeric value instead.
|
||||
if wb.styles.get(sh.style_id(c)).num_fmt.as_str().eq_ignore_ascii_case("General")
|
||||
&& let gridcraft_core::Value::Number(number) = sh.value(c)
|
||||
&& number.is_finite()
|
||||
{
|
||||
number.to_string()
|
||||
} else {
|
||||
crate::display::value_text(wb, sh, c)
|
||||
}
|
||||
})
|
||||
.map_err(|e| EngineError::Other(e.to_string()))
|
||||
gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and
|
||||
@@ -1062,6 +1055,12 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
// A brand-new file gets the restrictive default: no group/other write, whatever the umask.
|
||||
#[cfg(unix)]
|
||||
if prior.is_none() {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o644);
|
||||
}
|
||||
let mut f = opts.open(&tmp).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
@@ -1085,16 +1084,50 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
if let Some(p) = &prior {
|
||||
let _ = f.set_permissions(p.clone());
|
||||
}
|
||||
f.write_all(bytes).and_then(|()| f.flush()).map_err(|e| {
|
||||
// `sync_all` before the rename: without it a power loss right after the rename can leave
|
||||
// the new name pointing at an empty or truncated file while the old workbook is gone.
|
||||
// A file system that cannot flush at all (some network mounts; on Apple targets std asks
|
||||
// for F_FULLFSYNC, which they refuse) keeps the old behaviour: skip the flush, still rename.
|
||||
let synced = |f: &std::fs::File| f.sync_all().or_else(|e| if full_sync_unsupported(&e) { Ok(()) } else { Err(e) });
|
||||
f.write_all(bytes).and_then(|()| f.flush()).and_then(|()| synced(&f)).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
})?;
|
||||
drop(f);
|
||||
std::fs::rename(&tmp, path).map_err(|e| {
|
||||
// A write or rename that fails (full disk, the workbook locked by another app) leaves
|
||||
// no temporary file beside the user's workbook.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
EngineError::Other(format!("{path}: {e}"))
|
||||
})
|
||||
})?;
|
||||
// Make the rename itself durable. Best effort: the workbook is already in place, so a
|
||||
// directory that can't be opened or synced (some file systems) is not a failed save.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let dir = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new("."));
|
||||
if let Ok(d) = std::fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// True when a flush failed only because the file system cannot do it: on Unix ENOTTY (25, what
|
||||
/// `fcntl(F_FULLFSYNC)` returns on such volumes; on Windows 25 is ERROR_SEEK, a real failure), on
|
||||
/// Apple targets ENOTSUP (45, which std leaves uncategorized there), or an unsupported-operation
|
||||
/// error (EOPNOTSUPP/ENOSYS, and ENOTSUP where it equals EOPNOTSUPP). Any other error is a real
|
||||
/// failure.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn full_sync_unsupported(e: &std::io::Error) -> bool {
|
||||
flush_unsupported_on(e, cfg!(unix), cfg!(target_vendor = "apple"))
|
||||
}
|
||||
|
||||
/// [`full_sync_unsupported`] for a given platform, so each platform's raw codes can be tested
|
||||
/// on any host.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn flush_unsupported_on(e: &std::io::Error, unix: bool, apple: bool) -> bool {
|
||||
let raw = e.raw_os_error();
|
||||
(unix && raw == Some(25)) || (apple && raw == Some(45)) || e.kind() == std::io::ErrorKind::Unsupported
|
||||
}
|
||||
|
||||
/// The mode a saved file gets from the file it replaces (`old`): all of it when its group was
|
||||
|
||||
@@ -78,6 +78,34 @@ fn restored_mode_drops_the_group_and_special_bits_when_the_group_is_lost() {
|
||||
assert_eq!(super::restored_mode(0o104_755, false), 0o705, "setuid is dropped");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn fresh_save_drops_group_and_other_write_under_a_permissive_umask() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if std::env::var_os("GRIDCRAFT_UMASK_CHILD").is_none() {
|
||||
// Re-run this test in a child shell whose umask is 0002.
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let status = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("umask 0002 && exec \"$0\" --exact io::tests::fresh_save_drops_group_and_other_write_under_a_permissive_umask")
|
||||
.arg(exe)
|
||||
.env("GRIDCRAFT_UMASK_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-umask-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let fresh = dir.join("new.xlsx");
|
||||
write_file(fresh.to_str().unwrap(), b"v").unwrap();
|
||||
let mode = std::fs::metadata(&fresh).unwrap().permissions().mode() & 0o777;
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(mode & 0o022 == 0, "mode {mode:o}");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn open_refuses_directories_and_unknowable_lengths() {
|
||||
@@ -344,6 +372,65 @@ fn failed_save_leaves_no_temporary_file() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A save replaces an existing workbook with exactly the new bytes, and a save into a folder
|
||||
/// that doesn't exist fails without creating anything. The flush to disk before the rename is
|
||||
/// not covered: a power loss can't be simulated in a unit test.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn save_writes_exact_bytes_and_fails_cleanly_without_a_folder() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-write-exact-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dest = dir.join("Book.xlsx");
|
||||
std::fs::write(&dest, b"old workbook that is longer than the new one").unwrap();
|
||||
let bytes: Vec<u8> = (0..=255u8).cycle().take(100_000).collect();
|
||||
write_file(dest.to_str().unwrap(), &bytes).unwrap();
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), bytes);
|
||||
assert!(!dir.join("Book.xlsx.sctmp").exists());
|
||||
let missing = dir.join("no-such-folder").join("Book.xlsx");
|
||||
assert!(write_file(missing.to_str().unwrap(), b"x").is_err());
|
||||
assert!(!dir.join("no-such-folder").exists());
|
||||
assert_eq!(std::fs::read(&dest).unwrap(), bytes, "the existing workbook is untouched");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Only "this file system cannot flush" errors are tolerated when syncing a saved file.
|
||||
/// The fallback on a real network mount is not tested.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn full_sync_tolerates_only_unsupported_errors() {
|
||||
use std::io::{Error, ErrorKind};
|
||||
assert_eq!(full_sync_unsupported(&Error::from_raw_os_error(25)), cfg!(unix));
|
||||
assert!(full_sync_unsupported(&Error::from(ErrorKind::Unsupported)));
|
||||
assert!(!full_sync_unsupported(&Error::from(ErrorKind::PermissionDenied)));
|
||||
assert!(!full_sync_unsupported(&Error::from(ErrorKind::StorageFull)));
|
||||
assert!(!full_sync_unsupported(&Error::from_raw_os_error(28)), "ENOSPC on Linux");
|
||||
assert!(!full_sync_unsupported(&Error::from_raw_os_error(5)), "EIO");
|
||||
}
|
||||
|
||||
/// Apple's ENOTSUP is 45 (EOPNOTSUPP is 102), and std maps only the latter to
|
||||
/// `ErrorKind::Unsupported`: F_FULLFSYNC refused with ENOTSUP must still save. Elsewhere 45 is
|
||||
/// another error (EL2NSYNC on Linux) and stays a failed save.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn full_sync_tolerates_apple_enotsup() {
|
||||
use std::io::Error;
|
||||
let enotsup = Error::from_raw_os_error(45);
|
||||
assert!(flush_unsupported_on(&enotsup, true, true), "ENOTSUP on Apple");
|
||||
assert!(!flush_unsupported_on(&enotsup, true, false), "45 on other Unix");
|
||||
assert!(!flush_unsupported_on(&enotsup, false, false), "45 on Windows");
|
||||
assert!(flush_unsupported_on(&Error::from_raw_os_error(25), true, true), "ENOTTY on Apple");
|
||||
assert!(!flush_unsupported_on(&Error::from_raw_os_error(5), true, true), "EIO on Apple");
|
||||
assert!(!flush_unsupported_on(&Error::from_raw_os_error(28), true, true), "ENOSPC on Apple");
|
||||
}
|
||||
|
||||
/// The real helper on an Apple host: a raw ENOTSUP from F_FULLFSYNC is tolerated.
|
||||
#[cfg(target_vendor = "apple")]
|
||||
#[test]
|
||||
fn full_sync_tolerates_raw_enotsup_on_apple() {
|
||||
assert!(full_sync_unsupported(&std::io::Error::from_raw_os_error(45)));
|
||||
}
|
||||
|
||||
/// While a script runs (#2178), file reads and writes are refused whatever command or
|
||||
/// parameter asked for them; nesting and dropping the sandbox restore access.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -527,9 +614,80 @@ fn delimited_exports_preserve_general_precision_and_explicit_number_formats() {
|
||||
sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() });
|
||||
sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() });
|
||||
sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() });
|
||||
// Every integer below 1e16 that f64 holds (also 2^53 and the even integers above it) keeps
|
||||
// every digit; larger numbers keep the shortest digits that read back as the same value,
|
||||
// and a number `&` would write with an exponent is written out in full, so reopening the
|
||||
// file can't give it a scientific format that then rounds it on the next save.
|
||||
let cells = [
|
||||
(1234567890123456.0, "1234567890123456"),
|
||||
(-9007199254740991.0, "-9007199254740991"),
|
||||
(9007199254740992.0, "9007199254740992"),
|
||||
(9007199254740994.0, "9007199254740994"),
|
||||
(9123456789012346.0, "9123456789012346"),
|
||||
(-9999999999999998.0, "-9999999999999998"),
|
||||
(12345678901234567.0, "12345678901234568"),
|
||||
(1e20, "100000000000000000000"),
|
||||
(1e15 - 0.5, "999999999999999.5"),
|
||||
(1.0 / 3.0 * 1e-6, "0.000000333333333333333"),
|
||||
(1.23456789012346e-10, "0.000000000123456789012346"),
|
||||
];
|
||||
for (col, (n, _)) in cells.iter().enumerate() {
|
||||
sheet.set_cell(CellRef::new(0, col as u32 + 3), Cell { value: Value::Number(*n), ..Default::default() });
|
||||
}
|
||||
for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] {
|
||||
let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap();
|
||||
assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n"));
|
||||
let tail: Vec<&str> = cells.iter().map(|(_, text)| *text).collect();
|
||||
assert_eq!(output, format!("124412140710{s}1.23456789012345{s}1.24E+11{s}{}\r\n", tail.join(separator), s = separator));
|
||||
// Reopening the file and saving it again changes nothing.
|
||||
let (reopened, _) = open_bytes(path, output.as_bytes()).unwrap();
|
||||
assert_eq!(String::from_utf8(save_bytes(&reopened, path).unwrap()).unwrap(), output);
|
||||
}
|
||||
}
|
||||
|
||||
/// A number shown as General is written as `&` converts it (15 significant digits), whatever
|
||||
/// colour, sections or literals the format adds, and in a Text cell. Excel writes the cell
|
||||
/// display (`1.24412E+11`, `0.333333333`); GridCraft keeps the digits so part codes survive
|
||||
/// (integers below 1e16 keep all their digits, and nothing gets an exponent; see the test above).
|
||||
#[test]
|
||||
fn delimited_exports_write_general_numbers_as_text_converts_them() {
|
||||
use gridcraft_core::Value;
|
||||
use gridcraft_model::{Cell, NumFmt, StyleId};
|
||||
let mut wb = Workbook::new();
|
||||
let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code));
|
||||
let (blue, signed, red, text, unit) =
|
||||
(styled("[Blue]General"), styled("General;-General"), styled("General;[Red]-General"), styled("@"), styled("General\" mm\""));
|
||||
let code = 124412140710.0;
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let cells = [
|
||||
(Value::Number(1.0 / 3.0), StyleId::DEFAULT),
|
||||
(Value::Number(0.1 + 0.2), StyleId::DEFAULT),
|
||||
(Value::Number(1e20), StyleId::DEFAULT),
|
||||
(Value::Number(code), blue),
|
||||
(Value::Number(9007199254740994.0), blue),
|
||||
(Value::Number(-1.0 / 3.0), blue),
|
||||
(Value::Number(-code), signed),
|
||||
(Value::Number(-code), red),
|
||||
(Value::Number(code), text),
|
||||
(Value::Number(code), unit),
|
||||
];
|
||||
for (col, (value, style)) in cells.into_iter().enumerate() {
|
||||
sh.set_cell(CellRef::new(0, col as u32), Cell { value, formula: None, py: None, style });
|
||||
}
|
||||
for (path, sep) in [("out.csv", ","), ("out.txt", "\t")] {
|
||||
let output = String::from_utf8(save_bytes(&wb, path).unwrap()).unwrap();
|
||||
let expected = [
|
||||
"0.333333333333333",
|
||||
"0.3",
|
||||
"100000000000000000000",
|
||||
"124412140710",
|
||||
"9007199254740994",
|
||||
"-0.333333333333333",
|
||||
"-124412140710",
|
||||
"-124412140710",
|
||||
"124412140710",
|
||||
"124412140710 mm",
|
||||
];
|
||||
assert_eq!(output, format!("{}\r\n", expected.join(sep)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
pub mod catalog;
|
||||
pub mod cf;
|
||||
pub mod chart_data;
|
||||
mod chart_svg;
|
||||
mod clip_html;
|
||||
pub mod cmd;
|
||||
|
||||
+252
-86
@@ -2,7 +2,7 @@
|
||||
//! `TableStyleLight1…21 / Medium1…28 / Dark1…11` names so files round-trip).
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef};
|
||||
use gridcraft_model::{BorderLine, BorderStyle, Cell, Color, Fill, Formula, PatternType, Style, Table, Workbook};
|
||||
use gridcraft_model::{BorderLine, BorderStyle, Borders, Cell, Color, Fill, Formula, PatternType, Sheet, Style, Table, Workbook};
|
||||
|
||||
/// (family, number) from a style name, e.g. `TableStyleMedium2` → ("Medium", 2).
|
||||
pub fn parse_style_name(name: &str) -> (&'static str, u32) {
|
||||
@@ -22,113 +22,279 @@ fn accent_for(n: u32) -> Option<u8> {
|
||||
if k == 0 { None } else { Some(3 + k as u8) }
|
||||
}
|
||||
|
||||
/// Header/band/body colours for a table style.
|
||||
/// Fills, text colours and thin lines of a table style, per part of the table (the recipes in
|
||||
/// plan/excel/table-style-spec.json). Band 1 is the first data row; unbanded rows use band 2.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct TableLook {
|
||||
pub header_fill: Option<Color>,
|
||||
pub header_font: Color,
|
||||
pub header_bold: bool,
|
||||
pub band_fill: Option<Color>,
|
||||
pub body_fill: Option<Color>,
|
||||
pub line: Option<Color>,
|
||||
pub total_top: Option<Color>,
|
||||
pub band1: Option<Color>,
|
||||
pub band2: Option<Color>,
|
||||
pub body_font: Color,
|
||||
pub top: Option<Color>,
|
||||
pub header_bottom: Option<Color>,
|
||||
pub inner_h: Option<Color>,
|
||||
pub inner_v: Option<Color>,
|
||||
pub sides: Option<Color>,
|
||||
pub bottom: Option<Color>,
|
||||
/// The totals row's double top rule (the gallery doesn't show totals).
|
||||
pub total_top: Color,
|
||||
}
|
||||
|
||||
pub fn look(style: &str) -> TableLook {
|
||||
let (fam, n) = parse_style_name(style);
|
||||
let acc = accent_for(n);
|
||||
let base = |tint: i16| match acc {
|
||||
Some(a) => Color::Theme(a, tint),
|
||||
None => Color::Theme(1, if tint == 0 { 0 } else { tint.clamp(-1000, 1000) }),
|
||||
// An accent tint, or the neutral column's colour.
|
||||
let a = |tint: i16, neutral: Color| acc.map_or(neutral, |a| Color::Theme(a, tint));
|
||||
let (black, white) = (Color::Theme(1, 0), Color::Theme(0, 0));
|
||||
let (grey, mid_grey) = (Color::Theme(0, -150), Color::Theme(0, -350));
|
||||
let main = a(0, black);
|
||||
let plain = TableLook {
|
||||
header_fill: None,
|
||||
header_font: black,
|
||||
band1: None,
|
||||
band2: None,
|
||||
body_font: black,
|
||||
top: None,
|
||||
header_bottom: None,
|
||||
inner_h: None,
|
||||
inner_v: None,
|
||||
sides: None,
|
||||
bottom: None,
|
||||
total_top: main,
|
||||
};
|
||||
let neutral_light = |tint: i16| match acc {
|
||||
Some(a) => Color::Theme(a, tint),
|
||||
None => Color::Theme(0, -((1000 - tint).clamp(0, 1000) / 6)),
|
||||
};
|
||||
match fam {
|
||||
"Light" => {
|
||||
let group = (n - 1) / 7; // 0: lines only, 1: banded header line, 2: grid
|
||||
match (fam, n.saturating_sub(1) / 7) {
|
||||
("Light", 0) => {
|
||||
let text = a(-250, black);
|
||||
let line = Some(main);
|
||||
TableLook { header_font: text, body_font: text, band1: Some(a(800, grey)), top: line, header_bottom: line, bottom: line, ..plain }
|
||||
}
|
||||
("Light", 1) => {
|
||||
let line = Some(main);
|
||||
TableLook { header_fill: line, header_font: white, top: line, inner_h: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Light", _) => {
|
||||
let line = Some(main);
|
||||
TableLook { band1: Some(a(800, grey)), top: line, header_bottom: line, inner_v: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Medium", 0) => {
|
||||
let line = Some(a(400, black));
|
||||
TableLook { header_fill: Some(main), header_font: white, band1: Some(a(800, grey)), top: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Medium", 1) => TableLook {
|
||||
header_fill: Some(main),
|
||||
header_font: white,
|
||||
band1: Some(a(600, mid_grey)),
|
||||
band2: Some(a(800, grey)),
|
||||
header_bottom: Some(white),
|
||||
inner_v: Some(white),
|
||||
..plain
|
||||
},
|
||||
("Medium", 2) => {
|
||||
// Accent header over neutral grey bands and black rules; the neutral style adds a grid.
|
||||
let line = Some(black);
|
||||
let grid = if acc.is_none() { line } else { None };
|
||||
let header_fill = Some(main);
|
||||
TableLook {
|
||||
header_fill: None,
|
||||
header_font: if group == 0 { base(-250) } else { Color::Auto },
|
||||
header_bold: true,
|
||||
band_fill: Some(neutral_light(800)),
|
||||
body_fill: None,
|
||||
line: Some(base(0)),
|
||||
total_top: Some(base(0)),
|
||||
header_fill,
|
||||
header_font: white,
|
||||
band1: Some(grey),
|
||||
top: line,
|
||||
header_bottom: line,
|
||||
inner_v: grid,
|
||||
sides: grid,
|
||||
bottom: line,
|
||||
total_top: black,
|
||||
..plain
|
||||
}
|
||||
}
|
||||
"Dark" => TableLook {
|
||||
header_fill: Some(Color::Theme(1, 0)),
|
||||
header_font: Color::Theme(0, 0),
|
||||
header_bold: true,
|
||||
band_fill: Some(base(-250)),
|
||||
body_fill: Some(base(0)),
|
||||
line: None,
|
||||
total_top: Some(Color::Theme(0, 0)),
|
||||
},
|
||||
_ => TableLook {
|
||||
header_fill: Some(base(0)),
|
||||
header_font: Color::Theme(0, 0),
|
||||
header_bold: true,
|
||||
band_fill: Some(neutral_light(800)),
|
||||
body_fill: None,
|
||||
line: if (n - 1) / 7 == 0 { None } else { Some(base(400)) },
|
||||
total_top: Some(base(0)),
|
||||
("Medium", _) => {
|
||||
let line = Some(a(400, black));
|
||||
let pale = Some(a(800, grey));
|
||||
TableLook { header_fill: pale, band1: Some(a(600, mid_grey)), band2: pale, top: line, inner_v: line, sides: line, bottom: line, ..plain }
|
||||
}
|
||||
("Dark", 0) => TableLook {
|
||||
header_fill: Some(black),
|
||||
header_font: white,
|
||||
band1: Some(a(-250, Color::Theme(1, 250))),
|
||||
band2: Some(a(0, Color::Theme(1, 450))),
|
||||
body_font: white,
|
||||
header_bottom: Some(white),
|
||||
total_top: white,
|
||||
..plain
|
||||
},
|
||||
_ if n == 8 => TableLook { header_fill: Some(black), header_font: white, band1: Some(mid_grey), band2: Some(grey), ..plain },
|
||||
_ => {
|
||||
// Dark 9-11 pair accents 1+2, 3+4 and 5+6: the header takes the even one.
|
||||
let k = n.clamp(9, 11) as u8 - 8;
|
||||
let (head, body) = (Color::Theme(3 + 2 * k, 0), 2 + 2 * k);
|
||||
let band1 = Some(Color::Theme(body, 600));
|
||||
TableLook { header_fill: Some(head), header_font: white, band1, band2: Some(Color::Theme(body, 800)), total_top: head, ..plain }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style a table gives a cell (merged over the cell's own style: explicit fills/fonts win).
|
||||
/// Which parts of a table are on (the Table Style Options checkboxes).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TableParts {
|
||||
pub header_row: bool,
|
||||
pub totals_row: bool,
|
||||
pub banded_rows: bool,
|
||||
pub banded_cols: bool,
|
||||
pub first_col: bool,
|
||||
pub last_col: bool,
|
||||
}
|
||||
|
||||
impl TableParts {
|
||||
pub fn of(t: &Table) -> TableParts {
|
||||
TableParts {
|
||||
header_row: t.header_row,
|
||||
totals_row: t.totals_row,
|
||||
banded_rows: t.banded_rows,
|
||||
banded_cols: t.banded_cols,
|
||||
first_col: t.first_col,
|
||||
last_col: t.last_col,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a table style paints on one cell of a `rows` x `cols` table (`row`, `col` from its
|
||||
/// top-left). Each line has one owner: a horizontal line is a cell's bottom (top only on the
|
||||
/// first row and the totals row), a vertical one a cell's right (left only on the first column).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct CellLook {
|
||||
pub fill: Option<Color>,
|
||||
pub font: Color,
|
||||
pub bold: bool,
|
||||
pub borders: Borders,
|
||||
}
|
||||
|
||||
pub fn cell_look(lk: &TableLook, p: TableParts, row: u32, col: u32, rows: u32, cols: u32) -> CellLook {
|
||||
let last_row = rows.saturating_sub(1);
|
||||
let last_col = cols.saturating_sub(1);
|
||||
let is_header = p.header_row && row == 0;
|
||||
let is_total = p.totals_row && row == last_row && !is_header;
|
||||
let thin = |c: Option<Color>| c.map(|color| BorderLine { style: BorderStyle::Thin, color }).unwrap_or_default();
|
||||
let mut b = Borders::default();
|
||||
if row == 0 {
|
||||
b.top = thin(lk.top);
|
||||
}
|
||||
b.bottom = thin(if row == last_row {
|
||||
lk.bottom
|
||||
} else if is_header {
|
||||
lk.header_bottom
|
||||
} else if p.totals_row && row.saturating_add(1) == last_row {
|
||||
None // the totals row draws its own top rule
|
||||
} else {
|
||||
lk.inner_h
|
||||
});
|
||||
if col == 0 {
|
||||
b.left = thin(lk.sides);
|
||||
}
|
||||
b.right = thin(if col == last_col { lk.sides } else { lk.inner_v });
|
||||
let mut out = CellLook { borders: b, font: lk.body_font, ..Default::default() };
|
||||
if is_header {
|
||||
out.fill = lk.header_fill;
|
||||
out.font = lk.header_font;
|
||||
out.bold = true;
|
||||
} else if is_total {
|
||||
out.fill = lk.band2;
|
||||
out.bold = true;
|
||||
out.borders.top = BorderLine { style: BorderStyle::Double, color: lk.total_top };
|
||||
} else {
|
||||
let data_row = row.saturating_sub(p.header_row as u32);
|
||||
let band1 = (p.banded_rows && data_row.is_multiple_of(2)) || (p.banded_cols && col.is_multiple_of(2));
|
||||
out.fill = if band1 { lk.band1 } else { lk.band2 };
|
||||
}
|
||||
if (p.first_col && col == 0) || (p.last_col && col == last_col) {
|
||||
out.bold = true;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The style a table gives a cell (merged over the cell's own style: explicit fills, fonts and
|
||||
/// borders win).
|
||||
pub fn table_cell_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> Style {
|
||||
let own = wb.sheet(sheet).map(|sh| wb.styles.get(sh.style_id(c)).clone()).unwrap_or_default();
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let rows = end.row.saturating_sub(start.row).saturating_add(1);
|
||||
let cols = end.col.saturating_sub(start.col).saturating_add(1);
|
||||
let lk = cell_look(&look(&t.style), TableParts::of(t), c.row.saturating_sub(start.row), c.col.saturating_sub(start.col), rows, cols);
|
||||
let mut s = own.clone();
|
||||
let lk = look(&t.style);
|
||||
let is_header = t.header_row && c.row == t.range.start.row;
|
||||
let is_total = t.totals_row && c.row == t.range.end.row;
|
||||
let data_row = c.row.saturating_sub(t.range.start.row + t.header_row as u32);
|
||||
let data_col = c.col - t.range.start.col;
|
||||
let explicit_fill = own.fill.pattern != PatternType::None;
|
||||
if is_header {
|
||||
if let Some(f) = lk.header_fill
|
||||
&& !explicit_fill
|
||||
{
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
if own.font.color == Color::Auto {
|
||||
s.font.color = lk.header_font;
|
||||
}
|
||||
s.font.bold = s.font.bold || lk.header_bold;
|
||||
if let Some(l) = lk.line {
|
||||
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
|
||||
}
|
||||
} else if is_total {
|
||||
s.font.bold = true;
|
||||
if let Some(l) = lk.total_top {
|
||||
s.borders.top = BorderLine { style: BorderStyle::Double, color: l };
|
||||
}
|
||||
} else {
|
||||
let band = (t.banded_rows && data_row.is_multiple_of(2)) || (t.banded_cols && data_col.is_multiple_of(2));
|
||||
if !explicit_fill {
|
||||
if band {
|
||||
if let Some(f) = lk.band_fill {
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
} else if let Some(f) = lk.body_fill {
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
}
|
||||
if let Some(l) = lk.line
|
||||
&& t.style.contains("Light")
|
||||
&& c.row == t.range.end.row
|
||||
{
|
||||
s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l };
|
||||
if let Some(f) = lk.fill
|
||||
&& own.fill.pattern == PatternType::None
|
||||
{
|
||||
s.fill = Fill::solid(f);
|
||||
}
|
||||
if own.font.color == Color::Auto {
|
||||
s.font.color = lk.font;
|
||||
}
|
||||
s.font.bold = s.font.bold || lk.bold;
|
||||
for (side, line) in [
|
||||
(&mut s.borders.top, lk.borders.top),
|
||||
(&mut s.borders.bottom, lk.borders.bottom),
|
||||
(&mut s.borders.left, lk.borders.left),
|
||||
(&mut s.borders.right, lk.borders.right),
|
||||
] {
|
||||
if side.is_none() {
|
||||
*side = line;
|
||||
}
|
||||
}
|
||||
if (t.first_col && c.col == t.range.start.col) || (t.last_col && c.col == t.range.end.col) {
|
||||
s.font.bold = true;
|
||||
s
|
||||
}
|
||||
|
||||
/// A table's first and last visible row and column (hidden or filtered lines skipped).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ShownEdges {
|
||||
pub top: u32,
|
||||
pub bottom: u32,
|
||||
pub left: u32,
|
||||
pub right: u32,
|
||||
}
|
||||
|
||||
/// Finds [`ShownEdges`]. It scans the hidden lines at each edge, so the grid and print call it
|
||||
/// once per table per paint (through [`crate::cf::CfCache::table_edges`]), not once per cell.
|
||||
pub fn shown_edges(sh: &Sheet, t: &Table) -> ShownEdges {
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let row_shown = |r: &u32| sh.row_height(*r) > 0.0;
|
||||
let col_shown = |k: &u32| sh.col_width(*k) > 0.0;
|
||||
// With every row (or column) hidden, each cell takes both edges' lines; nothing is drawn.
|
||||
ShownEdges {
|
||||
top: (start.row..=end.row).find(row_shown).unwrap_or(end.row),
|
||||
bottom: (start.row..=end.row).rev().find(row_shown).unwrap_or(start.row),
|
||||
left: (start.col..=end.col).find(col_shown).unwrap_or(end.col),
|
||||
right: (start.col..=end.col).rev().find(col_shown).unwrap_or(start.col),
|
||||
}
|
||||
if t.style.starts_with("TableStyleDark") && !is_header && own.font.color == Color::Auto {
|
||||
s.font.color = Color::Theme(0, 0);
|
||||
}
|
||||
|
||||
/// The style the grid and print draw for a table cell. Like [`table_cell_style`], but the
|
||||
/// table's outer frame follows hidden rows and columns: the last visible row takes the table's
|
||||
/// bottom line, the last visible column its right side, and the first visible row and column its
|
||||
/// top line and left side. (Each frame line is owned by the edge cell, which is never drawn while
|
||||
/// it is hidden or filtered out.) Convert to Range uses [`table_cell_style`], the table as it is.
|
||||
pub fn table_cell_shown_style(wb: &Workbook, sheet: usize, t: &Table, e: ShownEdges, c: CellRef) -> Style {
|
||||
let mut s = table_cell_style(wb, sheet, t, c);
|
||||
let Some(sh) = wb.sheet(sheet) else { return s };
|
||||
let (start, end) = (t.range.start, t.range.end);
|
||||
let below = c.row < end.row && c.row >= e.bottom;
|
||||
let above = c.row > start.row && c.row <= e.top;
|
||||
let right = c.col < end.col && c.col >= e.right;
|
||||
let left = c.col > start.col && c.col <= e.left;
|
||||
if !(below || above || right || left) {
|
||||
return s;
|
||||
}
|
||||
let own = wb.styles.get(sh.style_id(c)).borders;
|
||||
if below && own.bottom.is_none() {
|
||||
s.borders.bottom = table_cell_style(wb, sheet, t, CellRef::new(end.row, c.col)).borders.bottom;
|
||||
}
|
||||
if above && own.top.is_none() {
|
||||
s.borders.top = table_cell_style(wb, sheet, t, CellRef::new(start.row, c.col)).borders.top;
|
||||
}
|
||||
if right && own.right.is_none() {
|
||||
s.borders.right = table_cell_style(wb, sheet, t, CellRef::new(c.row, end.col)).borders.right;
|
||||
}
|
||||
if left && own.left.is_none() {
|
||||
s.borders.left = table_cell_style(wb, sheet, t, CellRef::new(c.row, start.col)).borders.left;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
@@ -869,6 +869,65 @@ fn deleting_a_multi_area_row_selection_removes_every_area_and_undoes_once() {
|
||||
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "C1")), (Value::Number(2.0), Value::Number(4.0), Value::Empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::disallowed_methods)] // native-only test: timing the two deletes
|
||||
fn deleting_many_separate_rows_takes_about_as_long_as_one_block() {
|
||||
// #2287: every 10th row of a 12,000-row sheet, as 1,200 single-row areas.
|
||||
let (rows, step) = (12_000u32, 10u32);
|
||||
let values: Vec<serde_json::Value> = (0..rows).map(|r| json!([r, r + 100_000, r + 200_000])).collect();
|
||||
let deleted = |r: u32| r >= 1 && (r - 1).is_multiple_of(step);
|
||||
let list = (0..rows).filter(|&r| deleted(r)).map(|r| format!("{0}:{0}", r + 1)).collect::<Vec<_>>().join(",");
|
||||
let build = || {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E1", "input": format!("=SUM(A1:A{rows})")})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "E3", "input": "=B25"})).unwrap();
|
||||
s
|
||||
};
|
||||
let mut block = build();
|
||||
let t = std::time::Instant::now();
|
||||
block.execute("home.deleteRows", json!({"rows": format!("2:{}", rows / step + 1)})).unwrap();
|
||||
let block_time = t.elapsed();
|
||||
|
||||
let mut s = build();
|
||||
let t = std::time::Instant::now();
|
||||
s.execute("home.deleteRows", json!({"rows": list})).unwrap();
|
||||
let separate_time = t.elapsed();
|
||||
|
||||
let kept: Vec<u32> = (0..rows).filter(|&r| !deleted(r)).collect();
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
assert_eq!(sh.used_range().unwrap().end.row as usize, kept.len() - 1);
|
||||
for (i, r) in kept.iter().enumerate() {
|
||||
assert_eq!(sh.value(CellRef::new(i as u32, 0)), Value::Number(*r as f64));
|
||||
assert_eq!(sh.value(CellRef::new(i as u32, 2)), Value::Number((*r + 200_000) as f64));
|
||||
}
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "E1"})).unwrap()["formula"], format!("=SUM(A1:A{})", kept.len()));
|
||||
// B25 loses rows 2, 12 and 22 above it; the formula itself moves from E3 to E2.
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "E2"})).unwrap()["formula"], "=B22");
|
||||
assert!(
|
||||
separate_time < block_time * 20 + std::time::Duration::from_millis(500),
|
||||
"separate rows took {separate_time:?}, one block took {block_time:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_many_separate_columns_matches_per_area_result() {
|
||||
let mut s = s();
|
||||
let values: Vec<serde_json::Value> = (0..50).map(|r| json!((0..40).map(|c| r * 100 + c).collect::<Vec<_>>())).collect();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A60", "input": "=SUM(A1:AN1)+H2"})).unwrap();
|
||||
// Columns B, E, H (refs) and F:G.
|
||||
s.execute("home.deleteColumns", json!({"cols": "B:B,E:E,H:H,F:G"})).unwrap();
|
||||
let kept: Vec<u32> = (0..40).filter(|c| ![1, 4, 5, 6, 7].contains(c)).collect();
|
||||
for r in 0..50u32 {
|
||||
for (i, c) in kept.iter().enumerate() {
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::new(r, i as u32)), Value::Number((r * 100 + c) as f64));
|
||||
}
|
||||
}
|
||||
assert_eq!(s.execute("cell.get", json!({"cell": "A60"})).unwrap()["formula"], "=SUM(A1:AI1)+#REF!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_columns_reorders_without_overwriting_and_undoes_once() {
|
||||
let mut s = s();
|
||||
@@ -3078,9 +3137,10 @@ fn overlapping_spills_keep_the_one_that_exists_whichever_anchor_is_first() {
|
||||
#[test]
|
||||
fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() {
|
||||
use gridcraft_core::CellError::Spill;
|
||||
// Both arrays already spill; F8 (first in reading order) grows down over E10's spill, takes
|
||||
// its cells, shrinks back and lets it spill again, then the steps are undone, redone, edited
|
||||
// inside the contested area and cleared. Every state must match a full recalc.
|
||||
// Both arrays already spill; F8 (first in reading order) grows down over E10's spill, is
|
||||
// #SPILL! because E10 holds those cells (as in Excel), shrinks back and spills again, then the
|
||||
// steps are undone, redone, edited inside the contested area and cleared. Every state must
|
||||
// match a full recalc.
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "H1", "input": "1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F8", "input": "=SEQUENCE(H1)"})).unwrap();
|
||||
@@ -3102,18 +3162,18 @@ fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() {
|
||||
s.execute(id, params.clone()).unwrap();
|
||||
assert_matches_full_recalc(&s);
|
||||
if i == 0 {
|
||||
// Both held a spill: reading order gives F8 the cells.
|
||||
assert_eq!(v(&s, "F12"), Value::Number(5.0));
|
||||
assert_eq!(v(&s, "E10"), Value::Error(Spill));
|
||||
// Both held a spill: E10 holds F10, so it keeps it and F8 is blocked.
|
||||
assert_eq!(v(&s, "F8"), Value::Error(Spill));
|
||||
assert_eq!(v(&s, "F10"), Value::Number(20.0));
|
||||
}
|
||||
if i == 2 {
|
||||
assert_eq!(v(&s, "E10"), Value::Number(10.0));
|
||||
assert_eq!(v(&s, "F10"), Value::Number(20.0));
|
||||
}
|
||||
if i == 3 {
|
||||
// Undone back to the grown F8.
|
||||
assert_eq!(v(&s, "F12"), Value::Number(5.0));
|
||||
assert_eq!(v(&s, "E10"), Value::Error(Spill));
|
||||
// Undone back to the grown F8, blocked again.
|
||||
assert_eq!(v(&s, "F8"), Value::Error(Spill));
|
||||
assert_eq!(v(&s, "F10"), Value::Number(20.0));
|
||||
}
|
||||
if i == 8 {
|
||||
assert_eq!((v(&s, "F8"), v(&s, "E10"), v(&s, "F9")), (Value::Empty, Value::Empty, Value::Empty));
|
||||
@@ -3355,6 +3415,21 @@ fn a_spill_that_goes_away_unblocks_another() {
|
||||
assert_eq!((v(&s, "E10"), v(&s, "G10")), (Value::Number(1.0), Value::Number(3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_contested_spill_area_stays_with_its_array_after_reopening() {
|
||||
// F13's array wants F14:G14, which C14's array already fills, so F13 is #SPILL!. The file
|
||||
// can only cache #VALUE! for it; reopening (which recalculates) used to hand the area to F13
|
||||
// for coming first in reading order.
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "C14", "input": "=SEQUENCE(1,7)"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "F13", "input": "=SEQUENCE(5,2)"})).unwrap();
|
||||
assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill));
|
||||
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
|
||||
s.execute("file.open", json!({"name": "contested.xlsx", "base64": saved["base64"]})).unwrap();
|
||||
assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill));
|
||||
assert_eq!((v(&s, "C14"), v(&s, "G14"), v(&s, "I14")), (Value::Number(1.0), Value::Number(5.0), Value::Number(7.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_reading_another_arrays_spill_is_updated() {
|
||||
// G5 is evaluated before D11 in the same pass, so it first reads D11's old spill.
|
||||
@@ -3379,6 +3454,19 @@ fn indirect_reads_a_spill_laid_out_in_the_same_pass() {
|
||||
assert_eq!(v(&s, "E5"), Value::Number(9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_rows_lays_out_spills_where_the_formulas_moved() {
|
||||
// D1's array grows with the inserted rows to D1:D10 and C10's array moves down to C12:E14:
|
||||
// the area C10:E12 it filled before the insertion blocks neither of them.
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "D1", "input": "=SEQUENCE(ROWS(A2:A9))"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C8", "input": "=1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "C10", "input": "=SEQUENCE(3,3)"})).unwrap();
|
||||
s.execute("home.insertRows", json!({"rows": "3:4"})).unwrap();
|
||||
assert_eq!((v(&s, "D1"), v(&s, "D10")), (Value::Number(1.0), Value::Number(10.0)));
|
||||
assert_eq!((v(&s, "C12"), v(&s, "D12"), v(&s, "E14")), (Value::Number(1.0), Value::Number(2.0), Value::Number(9.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_survives_empty_params() {
|
||||
let mut s = Session::new();
|
||||
@@ -6624,6 +6712,7 @@ fn a_script_cannot_switch_windows() {
|
||||
assert_eq!(v(&s, "A1"), Value::number(2.0));
|
||||
}
|
||||
|
||||
mod chart_data;
|
||||
mod controls;
|
||||
mod equation;
|
||||
mod json_golden;
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
//! A chart's data as blocks on the sheet, and `chart.setValuesRange`, which dragging a corner of a
|
||||
//! selected chart's values outline runs (#4389, #4390).
|
||||
|
||||
use gridcraft_core::RangeRef;
|
||||
use gridcraft_model::{Chart, Color};
|
||||
use serde_json::json;
|
||||
|
||||
use super::s;
|
||||
use crate::Session;
|
||||
use crate::chart_data::{ChartData, chart_data};
|
||||
|
||||
fn r(a: &str) -> RangeRef {
|
||||
RangeRef::parse(a).unwrap()
|
||||
}
|
||||
|
||||
fn chart(s: &Session) -> Chart {
|
||||
s.doc().unwrap().wb.active().unwrap().charts[0].clone()
|
||||
}
|
||||
|
||||
fn data(s: &Session) -> Option<ChartData> {
|
||||
chart_data(&s.doc().unwrap().wb, 0, &chart(s))
|
||||
}
|
||||
|
||||
/// Points each plotted series has, as the chart resolves them.
|
||||
fn points(s: &Session) -> Vec<usize> {
|
||||
gridcraft_chart::resolve(&s.doc().unwrap().wb, 0, &chart(s)).series.iter().map(|se| se.values.len()).collect()
|
||||
}
|
||||
|
||||
/// 10..80 down A1:A8, charted from A1:A5 only.
|
||||
fn single_column() -> Session {
|
||||
let mut s = s();
|
||||
let values: Vec<_> = (1..=8).map(|i| json!([i * 10])).collect();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A1:A5"})).unwrap();
|
||||
s.execute("insert.chart", json!({"type": "column"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Region names across row 1, quarters down column A, charted from A1:C4.
|
||||
fn table() -> Session {
|
||||
let mut s = s();
|
||||
s.execute(
|
||||
"range.setValues",
|
||||
json!({"range": "A1", "values": [
|
||||
["", "North", "South", "East"],
|
||||
["Q1", 10, 15, 12],
|
||||
["Q2", 20, 25, 22],
|
||||
["Q3", 30, 35, 32],
|
||||
["Q4", 40, 45, 42],
|
||||
["Q5", 50, 55, 52],
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("selection.set", json!({"range": "A1:C4"})).unwrap();
|
||||
s.execute("insert.chart", json!({"type": "column"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_column_chart_is_one_values_block() {
|
||||
let s = single_column();
|
||||
assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("A1:A5"), by_rows: false, categories: None, names: None }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_chart_has_names_categories_and_values_blocks() {
|
||||
let s = table();
|
||||
assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:C4"), by_rows: false, categories: Some(r("A2:A4")), names: Some(r("B1:C1")) }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_values_down_plots_the_new_rows_and_undo_puts_them_back() {
|
||||
let mut s = single_column();
|
||||
assert_eq!(points(&s), [5]);
|
||||
let out = s.execute("chart.setValuesRange", json!({"range": "A1:A8"})).unwrap();
|
||||
assert_eq!(out["values"], "Sheet1!A1:A8");
|
||||
assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$8");
|
||||
assert_eq!(points(&s), [8]);
|
||||
assert_eq!(data(&s).unwrap().values, r("A1:A8"));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(points(&s), [5]);
|
||||
assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wider_block_adds_series_and_existing_series_keep_their_formatting() {
|
||||
let mut s = table();
|
||||
s.execute("chart.formatSelection", json!({"series": 1, "color": "#C00000"})).unwrap();
|
||||
let south = chart(&s).series[1].color;
|
||||
assert!(south.is_some());
|
||||
s.execute("chart.setValuesRange", json!({"range": "B2:D6"})).unwrap();
|
||||
let c = chart(&s);
|
||||
assert_eq!(c.series.len(), 3);
|
||||
assert_eq!(c.series[1].color, south, "South keeps its colour");
|
||||
assert_eq!(c.series[2].color, None::<Color>, "the new series takes the automatic colour");
|
||||
let names: Vec<_> = c.series.iter().map(|se| se.name.clone().unwrap()).collect();
|
||||
assert_eq!(names, ["Sheet1!$B$1", "Sheet1!$C$1", "Sheet1!$D$1"], "names follow along the header row");
|
||||
assert!(c.series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "labels span the new points");
|
||||
assert_eq!(c.series[2].values, "Sheet1!$D$2:$D$6");
|
||||
assert_eq!(c.source.as_deref(), Some("Sheet1!A1:D6"), "Switch Row/Column sees the moved blocks");
|
||||
assert_eq!(points(&s), [5, 5, 5]);
|
||||
assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:D6"), by_rows: false, categories: Some(r("A2:A6")), names: Some(r("B1:D1")) }));
|
||||
// A narrower block drops the last series.
|
||||
s.execute("chart.setValuesRange", json!({"range": "B2:B3"})).unwrap();
|
||||
let c = chart(&s);
|
||||
assert_eq!(c.series.len(), 1);
|
||||
assert_eq!(c.series[0].categories.as_deref(), Some("Sheet1!$A$2:$A$3"));
|
||||
s.execute("chart.switchRowColumn", json!({})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn series_in_rows_grow_across_the_columns() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A1:E2"})).unwrap();
|
||||
s.execute("insert.chart", json!({"type": "line"})).unwrap();
|
||||
assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:E2"), true)));
|
||||
s.execute("chart.setValuesRange", json!({"range": "A1:G2"})).unwrap();
|
||||
assert_eq!(points(&s), [7, 7]);
|
||||
assert_eq!(chart(&s).series[1].values, "Sheet1!$A$2:$G$2");
|
||||
}
|
||||
|
||||
/// Changes the first chart on the first sheet in place, as a file can leave it.
|
||||
fn edit_chart(s: &mut Session, f: impl FnOnce(&mut Chart)) {
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
f(&mut wb.sheet_mut(0).unwrap().charts[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn category_labels_written_with_and_without_equals_are_one_block() {
|
||||
let mut s = table();
|
||||
edit_chart(&mut s, |c| c.series[1].categories = Some("=Sheet1!$A$2:$A$4".into()));
|
||||
assert_eq!(data(&s).unwrap().categories, Some(r("A2:A4")));
|
||||
s.execute("chart.setValuesRange", json!({"range": "B2:C6"})).unwrap();
|
||||
assert!(chart(&s).series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "both series' labels follow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn series_read_in_rows_stay_resizable_after_shrinking_to_one_cell_each() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "A1:E2"})).unwrap();
|
||||
s.execute("insert.chart", json!({"type": "line"})).unwrap();
|
||||
// A file can carry series in rows without saying so; the layout is read from the series.
|
||||
edit_chart(&mut s, |c| c.by_rows = false);
|
||||
assert_eq!(data(&s).map(|d| d.by_rows), Some(true));
|
||||
s.execute("chart.setValuesRange", json!({"range": "A1:A2"})).unwrap();
|
||||
assert!(chart(&s).by_rows);
|
||||
assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:A2"), true)), "still one block, still in rows");
|
||||
s.execute("chart.setValuesRange", json!({"range": "A1:C2"})).unwrap();
|
||||
assert_eq!(points(&s), [3, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_values_range_refuses_what_it_cannot_do() {
|
||||
let mut s = table();
|
||||
let before = chart(&s);
|
||||
for (params, why) in [
|
||||
(json!({}), "missing `range`"),
|
||||
(json!({"range": "not a range"}), "not a range"),
|
||||
(json!({"range": "A1:Z100000"}), "too large"),
|
||||
(json!({"range": "A1:JA2"}), "too large"),
|
||||
(json!({"range": "Sheet2!B2:C4"}), ""),
|
||||
(json!({"chart": 999, "range": "B2:C4"}), "chart"),
|
||||
] {
|
||||
let err = s.execute("chart.setValuesRange", params.clone()).unwrap_err();
|
||||
assert!(err.to_string().contains(why), "{params}: {err}");
|
||||
assert_eq!(chart(&s), before, "{params} left the chart as it was");
|
||||
}
|
||||
// Series with a gap between them are not one block.
|
||||
s.execute("selection.set", json!({"range": "A1:D4"})).unwrap();
|
||||
s.execute("chart.selectData", json!({"range": "A1:D4"})).unwrap();
|
||||
s.execute("chart.selectData", json!({"removeSeries": [1]})).unwrap();
|
||||
assert_eq!(data(&s), None);
|
||||
let err = s.execute("chart.setValuesRange", json!({"range": "B2:C4"})).unwrap_err();
|
||||
assert!(err.to_string().contains("not one block"), "{err}");
|
||||
}
|
||||
@@ -35,7 +35,7 @@ use std::sync::Arc;
|
||||
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, col_to_letters};
|
||||
use gridcraft_engine::calc::Calc;
|
||||
use gridcraft_engine::model::{CalcMode, Formula, Sheet, SheetViewMode, Workbook};
|
||||
use gridcraft_engine::{EngineError, Session, command_specs, find_command, io};
|
||||
use gridcraft_engine::{EngineError, HistoryEntry, Session, command_specs, find_command, io};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
const SAMPLES: [&str; 3] = ["sales", "budget", "grades"];
|
||||
@@ -219,8 +219,24 @@ fn shrink(sample: &str, steps: &[Step], kind: &str) -> Vec<Step> {
|
||||
|
||||
struct Harness {
|
||||
s: Session,
|
||||
/// The workbook at the start of the current episode (what undoing everything gives back).
|
||||
base: Arc<Workbook>,
|
||||
/// What undoing everything gives back: the workbook at the start of the current episode or,
|
||||
/// once the undo history has dropped its oldest steps (it is bounded by count and by the
|
||||
/// memory its snapshots hold), the state before the oldest step it kept.
|
||||
floor: Arc<Workbook>,
|
||||
/// The workbook of the oldest undo step when the history was last looked at, to notice the
|
||||
/// history dropping it.
|
||||
oldest: Option<Arc<Workbook>>,
|
||||
}
|
||||
|
||||
/// Where redoing the `n` steps just undone ends. The first of them went onto the redo history
|
||||
/// with the final workbook `end`. The redo history is bounded like undo and drops its oldest
|
||||
/// entries first, so when that entry is gone every older one is too, and redo stops after fewer
|
||||
/// than `n` steps at the oldest entry it kept.
|
||||
fn redo_target(end: &Arc<Workbook>, redo: &[HistoryEntry], n: usize) -> Arc<Workbook> {
|
||||
if n == 0 || redo.iter().rev().take(n).any(|e| Arc::ptr_eq(&e.wb, end)) {
|
||||
return end.clone();
|
||||
}
|
||||
redo.first().map_or_else(|| end.clone(), |e| e.wb.clone())
|
||||
}
|
||||
|
||||
fn fail(step: usize, kind: &'static str, what: impl Into<String>) -> Failure {
|
||||
@@ -243,8 +259,8 @@ impl Harness {
|
||||
fn new(sample: &str) -> Harness {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": sample})).expect("sample opens");
|
||||
let base = s.doc().expect("document").wb.clone();
|
||||
Harness { s, base }
|
||||
let floor = s.doc().expect("document").wb.clone();
|
||||
Harness { s, floor, oldest: None }
|
||||
}
|
||||
|
||||
fn wb(&self) -> Arc<Workbook> {
|
||||
@@ -262,6 +278,7 @@ impl Harness {
|
||||
return Err(fail(i, "documents", format!("`{id}` changed the number of open documents; exclude it in EXCLUDED")));
|
||||
}
|
||||
let after = self.wb();
|
||||
self.track_history();
|
||||
let spec = find_command(id).expect("generated ids are registered");
|
||||
if !spec.undoable
|
||||
&& !matches!(id, "edit.undo" | "edit.redo")
|
||||
@@ -293,6 +310,7 @@ impl Harness {
|
||||
/// and reload; the next episode starts from here with an empty history.
|
||||
fn end_episode(&mut self, i: usize) -> Result<(), Failure> {
|
||||
let end = self.wb();
|
||||
self.track_history();
|
||||
let mut n = 0;
|
||||
while !self.s.doc().expect("document").undo.is_empty() {
|
||||
if let Err(EngineError::Internal(_, msg)) = self.s.execute("edit.undo", json!({})) {
|
||||
@@ -304,7 +322,7 @@ impl Harness {
|
||||
}
|
||||
}
|
||||
let undone = self.wb();
|
||||
if let Some(diff) = workbook_diff(&self.base, &undone) {
|
||||
if let Some(diff) = workbook_diff(&self.floor, &undone) {
|
||||
return Err(fail(i, "undo", format!("undoing all {n} steps doesn't give back the starting workbook: {diff}")));
|
||||
}
|
||||
if watch_list(&end) != watch_list(&undone) {
|
||||
@@ -312,23 +330,39 @@ impl Harness {
|
||||
}
|
||||
self.check_state(i)?;
|
||||
// Only the steps undone here: an `edit.undo {steps}` in the sequence may have left more.
|
||||
let target = redo_target(&end, &self.s.doc().expect("document").redo, n);
|
||||
for _ in 0..n {
|
||||
if let Err(EngineError::Internal(_, msg)) = self.s.execute("edit.redo", json!({})) {
|
||||
return Err(fail(i, "panic", format!("`edit.redo` panicked while redoing everything: {msg}")));
|
||||
}
|
||||
}
|
||||
if let Some(diff) = workbook_diff(&end, &self.wb()) {
|
||||
return Err(fail(i, "redo", format!("redoing all {n} steps doesn't give back the final workbook: {diff}")));
|
||||
if let Some(diff) = workbook_diff(&target, &self.wb()) {
|
||||
let what = if Arc::ptr_eq(&target, &end) { "the final workbook" } else { "the newest step the redo history kept" };
|
||||
return Err(fail(i, "redo", format!("redoing all {n} steps doesn't give back {what}: {diff}")));
|
||||
}
|
||||
self.check_state(i)?;
|
||||
guarded(i, "xlsx roundtrip", || roundtrip_diff(&end))?;
|
||||
let d = self.s.active_mut().expect("document");
|
||||
d.undo.clear();
|
||||
d.redo.clear();
|
||||
self.base = d.wb.clone();
|
||||
self.floor = d.wb.clone();
|
||||
self.oldest = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Notices the undo history dropping its oldest step: its oldest entry changed without the
|
||||
/// history emptying in between. From then on undoing everything stops at the new oldest entry,
|
||||
/// including after an `edit.undo` in the sequence has already used up what is left.
|
||||
fn track_history(&mut self) {
|
||||
let oldest = self.s.doc().expect("document").undo.first().map(|e| e.wb.clone());
|
||||
if let (Some(was), Some(now)) = (&self.oldest, &oldest)
|
||||
&& !Arc::ptr_eq(was, now)
|
||||
{
|
||||
self.floor = now.clone();
|
||||
}
|
||||
self.oldest = oldest;
|
||||
}
|
||||
|
||||
fn finish(&mut self, steps: usize) -> Result<(), Failure> {
|
||||
self.end_episode(steps)
|
||||
}
|
||||
@@ -1135,3 +1169,42 @@ fn view_mode_switch_is_not_an_undo_difference() {
|
||||
assert!(failure.is_none(), "`{id}`: {failure:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Review of #2332: once the undo history has dropped its oldest steps, an `edit.undo` in the
|
||||
/// sequence can use up everything it kept before the episode ends. Undoing everything then has
|
||||
/// nothing left to do, and the workbook is the state before the oldest step kept, not the
|
||||
/// episode's start.
|
||||
#[test]
|
||||
fn a_trimmed_history_undone_in_the_sequence_stops_at_its_oldest_step() {
|
||||
let mut h = Harness::new("sales");
|
||||
// Past the engine's 100-step undo limit, so it drops the oldest 5 steps.
|
||||
for i in 0..105 {
|
||||
h.s.execute("cell.set", json!({"cell": format!("Z{}", i + 1), "input": i.to_string()})).expect("cell.set");
|
||||
h.track_history();
|
||||
}
|
||||
assert_eq!(h.s.doc().expect("document").undo.len(), 100, "the history dropped its oldest steps");
|
||||
if let Err(f) = h.step(0, "edit.undo", &json!({"steps": 100})) {
|
||||
panic!("{f:?}");
|
||||
}
|
||||
assert!(h.s.doc().expect("document").undo.is_empty());
|
||||
if let Err(f) = h.end_episode(0) {
|
||||
panic!("{f:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Review of #2332: the redo history is bounded too, so undoing `n` steps may leave fewer than
|
||||
/// `n` to redo, and redo then stops at the oldest entry it kept rather than at the final workbook.
|
||||
#[test]
|
||||
fn redo_stops_at_the_oldest_step_its_history_kept() {
|
||||
let h = Harness::new("sales");
|
||||
let selection = h.s.doc().expect("document").selection.clone();
|
||||
let entry = |wb: &Arc<Workbook>| HistoryEntry { label: String::new(), wb: wb.clone(), selection: selection.clone(), retained_bytes: 0 };
|
||||
let end = Arc::new((*h.wb()).clone());
|
||||
let kept = Arc::new((*h.wb()).clone());
|
||||
// Both steps kept: the first one undone went onto the redo history with the final workbook.
|
||||
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&end), entry(&kept)], 2), &end));
|
||||
// Its entry dropped: redo stops at the oldest entry left.
|
||||
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&kept)], 2), &kept));
|
||||
// Nothing undone, so nothing to redo, whatever an earlier `edit.undo` left there.
|
||||
assert!(Arc::ptr_eq(&redo_target(&end, &[entry(&kept)], 0), &end));
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ mod sparse_clear_invalidation;
|
||||
mod stored_list_shape;
|
||||
mod structural_edit_rewrite;
|
||||
mod table_resize_overlap;
|
||||
mod table_style_looks;
|
||||
mod table_total_row_last_row;
|
||||
mod trace_error;
|
||||
mod workbook_author;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Table styles look like the Format as Table gallery: every row of the gallery (Light 1-7, 8-14,
|
||||
//! 15-21, Medium 1-7, …) has its own fills and lines, as recorded in plan/excel/table-style-spec.json.
|
||||
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::model::*;
|
||||
use gridcraft_engine::tables::{ShownEdges, shown_edges, table_cell_shown_style, table_cell_style};
|
||||
use serde_json::json;
|
||||
|
||||
const ROWS: u32 = 6; // header + 5 data rows
|
||||
const COLS: u32 = 5;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": [["a", "b", "c", "d", "e"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range": "A1:E6", "header": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The look of every cell of a 6x5 table (header on, banded rows) in `style`, row by row.
|
||||
fn grid_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let mut t = wb.sheet(0).unwrap().tables[0].clone();
|
||||
t.style = format!("TableStyle{style}");
|
||||
edit(&mut t);
|
||||
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_style(wb, 0, &t, CellRef::new(r, c))).collect()).collect()
|
||||
}
|
||||
|
||||
fn grid(style: &str) -> Vec<Vec<Style>> {
|
||||
grid_with(&session(), style, |_| {})
|
||||
}
|
||||
|
||||
fn thin(color: Color) -> BorderLine {
|
||||
BorderLine { style: BorderStyle::Thin, color }
|
||||
}
|
||||
|
||||
const NONE: BorderLine = BorderLine { style: BorderStyle::None, color: Color::Auto };
|
||||
const BLACK: Color = Color::Theme(1, 0);
|
||||
const WHITE: Color = Color::Theme(0, 0);
|
||||
|
||||
#[test]
|
||||
fn each_row_of_the_gallery_has_its_own_look() {
|
||||
// Same accent (or neutral) across the gallery's rows, so only the row-group differs.
|
||||
for set in [
|
||||
&["Light1", "Light8", "Light15", "Medium1", "Medium8", "Medium15", "Medium22", "Dark1", "Dark8"][..],
|
||||
&["Light2", "Light9", "Light16", "Medium2", "Medium9", "Medium16", "Medium23", "Dark2", "Dark9"][..],
|
||||
] {
|
||||
let looks: Vec<_> = set.iter().map(|s| grid(s)).collect();
|
||||
for (i, a) in looks.iter().enumerate() {
|
||||
for (j, b) in looks.iter().enumerate().skip(i + 1) {
|
||||
assert_ne!(a, b, "{} and {} look the same", set[i], set[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_bands_are_visibly_grey() {
|
||||
let theme = Theme::default();
|
||||
let fill = |style: &str, row: usize| grid(style)[row][0].fill.fg.resolve(&theme).unwrap();
|
||||
// lt1 -150 (about #D9D9D9) and lt1 -350 (about #A6A6A6).
|
||||
for ch in fill("Light1", 1) {
|
||||
assert!((210..=225).contains(&ch), "Light1 band {:?}", fill("Light1", 1));
|
||||
}
|
||||
for ch in fill("Medium8", 1) {
|
||||
assert!((160..=172).contains(&ch), "Medium8 band1 {:?}", fill("Medium8", 1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light15_has_a_vertical_grid_and_no_row_lines() {
|
||||
let g = grid("Light15");
|
||||
assert_eq!(g[0][0].borders.top, thin(BLACK));
|
||||
assert_eq!(g[0][2].borders.bottom, thin(BLACK), "header bottom");
|
||||
assert_eq!(g[2][1].borders.right, thin(BLACK), "inner vertical");
|
||||
assert_eq!(g[0][1].borders.right, thin(BLACK), "inner vertical in the header");
|
||||
assert_eq!(g[2][0].borders.left, thin(BLACK), "left side");
|
||||
assert_eq!(g[2][4].borders.right, thin(BLACK), "right side");
|
||||
assert_eq!(g[5][2].borders.bottom, thin(BLACK), "bottom");
|
||||
assert_eq!(g[2][1].borders.bottom, NONE, "no inner horizontal");
|
||||
assert_eq!(g[2][1].borders.top, NONE, "no inner horizontal");
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(0, -150));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium2_has_a_pale_accent_frame_and_no_row_lines() {
|
||||
let g = grid("Medium2");
|
||||
let line = thin(Color::Theme(4, 400));
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(4, 0));
|
||||
assert_eq!(g[0][0].font.color, WHITE);
|
||||
assert_eq!(g[0][2].borders.top, line);
|
||||
assert_eq!(g[0][0].borders.left, line, "the sides run down the header too");
|
||||
assert_eq!(g[3][0].borders.left, line);
|
||||
assert_eq!(g[3][4].borders.right, line);
|
||||
assert_eq!(g[5][2].borders.bottom, line);
|
||||
assert_eq!(g[0][2].borders.bottom, NONE, "no header bottom");
|
||||
assert_eq!(g[2][2].borders.bottom, NONE, "no inner horizontal");
|
||||
assert_eq!(g[2][2].borders.right, NONE, "no inner vertical");
|
||||
assert_eq!(g[1][2].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][2].fill.pattern, PatternType::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium9_has_white_verticals_and_header_bottom() {
|
||||
let g = grid("Medium9");
|
||||
assert_eq!(g[0][1].borders.bottom, thin(WHITE));
|
||||
assert_eq!(g[0][1].borders.right, thin(WHITE));
|
||||
assert_eq!(g[3][1].borders.right, thin(WHITE));
|
||||
assert_eq!(g[3][1].borders.bottom, NONE);
|
||||
assert_eq!(g[3][0].borders.left, NONE, "no frame");
|
||||
assert_eq!(g[5][4].borders.bottom, NONE, "no frame");
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark2_bands_in_shaded_and_full_accent_under_a_black_header() {
|
||||
let g = grid("Dark2");
|
||||
assert_eq!(g[0][0].fill.fg, BLACK);
|
||||
assert_eq!(g[0][0].borders.bottom, thin(WHITE));
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, -250));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 0));
|
||||
assert_eq!(g[2][0].font.color, WHITE);
|
||||
assert_eq!(g[2][0].borders, Borders::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark9_pairs_two_accents() {
|
||||
let g = grid("Dark9");
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(5, 0));
|
||||
assert_eq!(g[0][0].font.color, WHITE);
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][0].font.color, BLACK);
|
||||
let g = grid("Dark11");
|
||||
assert_eq!(g[0][0].fill.fg, Color::Theme(9, 0));
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(8, 600));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_options_change_the_look() {
|
||||
let s = session();
|
||||
// Banded rows off: every data row looks like the second band.
|
||||
let g = grid_with(&s, "Medium9", |t| t.banded_rows = false);
|
||||
assert_eq!(g[1][0].fill.fg, Color::Theme(4, 800));
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800));
|
||||
// Banded columns alternate by column.
|
||||
let g = grid_with(&s, "Medium9", |t| {
|
||||
t.banded_rows = false;
|
||||
t.banded_cols = true;
|
||||
});
|
||||
assert_eq!(g[2][0].fill.fg, Color::Theme(4, 600));
|
||||
assert_eq!(g[2][1].fill.fg, Color::Theme(4, 800));
|
||||
// Header off: the top line moves to the first data row, and nothing is drawn as a header.
|
||||
let g = grid_with(&s, "Light15", |t| t.header_row = false);
|
||||
assert_eq!(g[0][2].borders.top, thin(BLACK));
|
||||
assert_eq!(g[0][2].borders.bottom, NONE);
|
||||
assert!(!g[0][2].font.bold);
|
||||
// Totals row: bold, double top rule, no banding.
|
||||
let g = grid_with(&s, "Medium2", |t| t.totals_row = true);
|
||||
assert!(g[5][1].font.bold);
|
||||
assert_eq!(g[5][1].borders.top, BorderLine { style: BorderStyle::Double, color: Color::Theme(4, 0) });
|
||||
assert_eq!(g[5][1].borders.bottom, thin(Color::Theme(4, 400)));
|
||||
// First and last column bold.
|
||||
let g = grid_with(&s, "Medium2", |t| {
|
||||
t.first_col = true;
|
||||
t.last_col = true;
|
||||
});
|
||||
assert!(g[2][0].font.bold && g[2][4].font.bold && !g[2][2].font.bold);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_formatting_wins() {
|
||||
let mut s = session();
|
||||
s.execute("home.fillColor", json!({"range": "B3", "color": "#FF0000"})).unwrap();
|
||||
s.execute("home.fontColor", json!({"range": "B3", "color": "#00FF00"})).unwrap();
|
||||
s.execute("home.borders", json!({"range": "B3", "preset": "bottom"})).unwrap();
|
||||
let g = grid_with(&s, "Dark2", |_| {});
|
||||
assert_eq!(g[2][1].fill, Fill::solid(Color::Rgb(0xFF0000)));
|
||||
assert_eq!(g[2][1].font.color, Color::Rgb(0x00FF00));
|
||||
assert_eq!(g[2][1].borders.bottom.style, BorderStyle::Thin);
|
||||
assert_eq!(g[2][1].borders.bottom.color, Color::Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_style_name_is_safe() {
|
||||
for name in ["Light0", "Light99", "Medium0", "Medium4000000000", "Dark0", "Dark12", "Dark99", "Bogus"] {
|
||||
let _ = grid(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the grid and print draw: like `grid_with`, but through the hidden-row/column aware
|
||||
/// `table_cell_shown_style`.
|
||||
fn shown_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec<Vec<Style>> {
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
let mut t = wb.sheet(0).unwrap().tables[0].clone();
|
||||
t.style = format!("TableStyle{style}");
|
||||
edit(&mut t);
|
||||
let e = shown_edges(wb.sheet(0).unwrap(), &t);
|
||||
(0..ROWS).map(|r| (0..COLS).map(|c| table_cell_shown_style(wb, 0, &t, e, CellRef::new(r, c))).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_follows_the_last_visible_row_and_column() {
|
||||
let frame = thin(Color::Theme(4, 400));
|
||||
// Nothing hidden: the shown look is the table look.
|
||||
let s = session();
|
||||
assert_eq!(shown_with(&s, "Medium2", |_| {}), grid_with(&s, "Medium2", |_| {}));
|
||||
// Last data row (and the one before it) and last column hidden: the frame moves in.
|
||||
let mut s = session();
|
||||
s.execute("home.hideRows", json!({"rows": "5:6"})).unwrap();
|
||||
s.execute("home.hideColumns", json!({"cols": "E:E"})).unwrap();
|
||||
let t = &s.doc().unwrap().wb.sheet(0).unwrap().tables[0];
|
||||
assert_eq!(shown_edges(s.doc().unwrap().wb.sheet(0).unwrap(), t), ShownEdges { top: 0, bottom: 3, left: 0, right: 3 });
|
||||
let g = shown_with(&s, "Medium2", |_| {});
|
||||
for (c, cell) in g[3].iter().take(4).enumerate() {
|
||||
assert_eq!(cell.borders.bottom, frame, "bottom frame on row 4, col {c}");
|
||||
}
|
||||
for (r, row) in g.iter().take(4).enumerate() {
|
||||
assert_eq!(row[3].borders.right, frame, "right frame on col D, row {r}");
|
||||
}
|
||||
// Rows above the last visible one keep their inner look (Medium 2 has no row lines).
|
||||
assert_eq!(g[2][1].borders.bottom, NONE);
|
||||
// Convert to Range and friends still see the table as it is.
|
||||
assert_eq!(grid_with(&s, "Medium2", |_| {})[3][1].borders.bottom, NONE);
|
||||
// Header off and the first data row filtered out: the top line moves down.
|
||||
let mut s = session();
|
||||
s.execute("home.hideRows", json!({"rows": "1:1"})).unwrap();
|
||||
s.execute("home.hideColumns", json!({"cols": "A:A"})).unwrap();
|
||||
let g = shown_with(&s, "Light15", |t| t.header_row = false);
|
||||
assert_eq!(g[1][2].borders.top, thin(BLACK));
|
||||
assert_eq!(g[2][1].borders.left, thin(BLACK));
|
||||
// Explicit borders still win.
|
||||
let mut s = session();
|
||||
s.execute("home.borders", json!({"range": "B5", "preset": "none"})).unwrap();
|
||||
s.execute("home.fillColor", json!({"range": "B5", "color": "#FF0000"})).unwrap();
|
||||
s.execute("home.borders", json!({"range": "C5", "preset": "bottom"})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows": "6:6"})).unwrap();
|
||||
let g = shown_with(&s, "Medium2", |_| {});
|
||||
assert_eq!(g[4][1].borders.bottom, frame);
|
||||
assert_eq!(g[4][2].borders.bottom.color, Color::Auto);
|
||||
}
|
||||
@@ -617,6 +617,11 @@ mod tests {
|
||||
cx(ev("IMCSC", vec![t("4+3i")]), -0.075_489_832_915_863_7, 0.064_877_471_370_635_5);
|
||||
is_text(ev("IMSECH", vec![t("0")]), "1");
|
||||
is_err(ev("IMCSCH", vec![t("0")]), CellError::Num);
|
||||
// Excel-cached results (Excel for Mac, `formulas` project test.xlsx, ENGINEERING sheet): a
|
||||
// part needing more than 21 characters as a decimal is written in scientific notation.
|
||||
is_text(ev("IMCSCH", vec![t("13+5j")]), "1.28233995888454E-06+4.33496947416312E-06j");
|
||||
is_text(ev("IMEXP", vec![t("-13+25j")]), "2.24044486393732E-06-2.99158552811404E-07j");
|
||||
is_text(ev("IMSECH", vec![t("7+25j")]), "0.00180771853884451+0.000241377759972715j");
|
||||
// sech z · cosh z = 1
|
||||
let Value::Text(c) = ev("IMCOSH", vec![t("4+3i")]) else { panic!() };
|
||||
let Value::Text(sc) = ev("IMSECH", vec![t("4+3i")]) else { panic!() };
|
||||
|
||||
@@ -33,6 +33,82 @@ 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);
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn rate_is(args: &[f64], expected: f64) {
|
||||
close_tol(rate_of(args), expected, 1e-15);
|
||||
}
|
||||
|
||||
/// Expected values observed in Excel 365 with these synthetic inputs.
|
||||
#[test]
|
||||
fn rate_follows_excel_iteration() {
|
||||
// No payments and a zero future value: the answer is -100%, which the iteration
|
||||
// approaches without reaching. Excel returns the last iterate, bit for bit.
|
||||
rate_is(&[5.0, 0.0, -100.0, 0.0], -0.999_999_409_145_182_5);
|
||||
rate_is(&[3.0, 0.0, -50.0, 0.0], -0.999_999_744_782_979_9);
|
||||
rate_is(&[10.0, 0.0, -1.0, 0.0], -0.999_998_741_101_371_3);
|
||||
rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, 0.5], -0.999_999_408_783_809_4);
|
||||
rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, -0.99], -0.999_999_411_730_630_3);
|
||||
// Second starting point goes the other way when the equation is positive at the guess.
|
||||
rate_is(&[5.0, 0.0, 100.0, 0.0], -0.999_999_409_810_240_3);
|
||||
rate_is(&[5.0, 0.0, -100.0, 1e-29], -0.999_999_260_333_075_4);
|
||||
rate_is(&[5.0, 0.0, -100.0, 1e4], 1.511_886_431_510_563_3);
|
||||
rate_is(&[4.0, 0.0, -1.0, 100.0], 2.162_277_660_168_009);
|
||||
// Within 1e-7 by step but not by value: Excel keeps going.
|
||||
rate_is(&[5.0, 0.0, -1e25, 0.0], -0.999_999_628_525_605_1);
|
||||
// 200 steps without converging: the last iterate when it is within 1e-4, else #NUM!.
|
||||
rate_is(&[20.0, 0.0, -1.0, 0.0], -0.999_112_071_912_539_3);
|
||||
rate_is(&[36.0, 0.0, -1.0, 0.0, 0.0, -0.994], -0.999_875_315_309_626_9);
|
||||
is_err(rate_of(&[12.0, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[25.0, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[20.0, 0.0, -1e60, 0.0]), CellError::Num);
|
||||
// Large rates the iteration can't reach are #NUM! in Excel.
|
||||
is_err(rate_of(&[4.0, 0.0, -0.0001, 100.0]), CellError::Num);
|
||||
is_err(rate_of(&[5.0, 0.0, -100.0, 1e5]), CellError::Num);
|
||||
is_err(rate_of(&[10.0, -300.0, 1000.0]), CellError::Num);
|
||||
// ...but are found from a closer guess.
|
||||
rate_is(&[4.0, 0.0, -0.1, 100.0, 0.0, 4.0], 4.623_413_251_903_489);
|
||||
close_tol(rate_of(&[10.0, -300.0, 1000.0, 0.0, 0.0, 0.3]), 0.273_198_424_105_560_4, 1e-12);
|
||||
// Converging on a rate at or below -100% (or within 1e-7 of it) is #NUM!.
|
||||
is_err(rate_of(&[1.0, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[10.0, -1000.0, 1000.0]), CellError::Num);
|
||||
is_err(rate_of(&[1.0, 0.0, -100.0, 1e-5]), CellError::Num);
|
||||
rate_is(&[1.0, 0.0, -100.0, 2e-5], -0.999_999_8);
|
||||
is_err(rate_of(&[5.0, 0.0, -1e30, 0.0]), CellError::Num);
|
||||
is_err(rate_of(&[0.5, 0.0, -1.0, 0.0]), CellError::Num);
|
||||
// A value that never gets near zero is #NUM!, however small the step.
|
||||
is_err(rate_of(&[4.0, 0.0, 100.0, 100.0]), CellError::Num);
|
||||
is_err(rate_of(&[4.0, 0.0, -1e-12, 1e-6]), CellError::Num);
|
||||
rate_is(&[4.0, 0.0, -1e-14, 1e-8], 0.099_000_000_283_235_72);
|
||||
// Subnormal steps are flushed to zero.
|
||||
rate_is(&[3.0, 0.0, -1e-305, 0.0], 0.101);
|
||||
is_err(rate_of(&[4.0, 0.0, 0.0, 100.0]), CellError::Num);
|
||||
// Guess at or below -1 is #VALUE!; type is 0 or anything else (1).
|
||||
is_err(rate_of(&[10.0, -100.0, 1000.0, 0.0, 0.0, -1.0]), CellError::Value);
|
||||
is_err(rate_of(&[0.0, -100.0, 1000.0]), CellError::Num);
|
||||
// Excel does not step the second point back to -1: a fractional nper with a guess near -1 is #NUM!
|
||||
// even though a root exists at -0.99, and the same case from a guess of -0.99 finds it.
|
||||
is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.9995]), CellError::Num);
|
||||
is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.5]), CellError::Num);
|
||||
close_tol(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.99]), -0.99, 1e-7);
|
||||
assert_eq!(rate_of(&[10.0, -100.0, 1000.0, 0.0, 2.0]), rate_of(&[10.0, -100.0, 1000.0, 0.0, 1.0]));
|
||||
// Ordinary loans, and large amounts that can't get within 1e-7 of zero.
|
||||
close_tol(rate_of(&[360.0, -1000.0, 150000.0]), 0.005_850_253_376_759_637, 1e-11);
|
||||
close_tol(rate_of(&[360.0, -1000.0, 150000.0, 0.0, 1.0]), 0.005_898_953_457_098_463, 1e-11);
|
||||
close_tol(rate_of(&[1000.0, -1e6, 1e8]), 0.009_999_522_655_994_865, 1e-12);
|
||||
close_tol(rate_of(&[360.0, -1e9, 1.5e11]), 0.005_850_253_376_759_668, 1e-12);
|
||||
close_tol(rate_of(&[10.0, -50.0, 1000.0]), -0.109_560_293_684_682_5, 1e-14);
|
||||
// Roots at 0% come out as rounding noise in both, so only the absolute size matters.
|
||||
match rate_of(&[10.0, -100.0, 1000.0]) {
|
||||
Value::Number(x) => assert!(x.abs() < 1e-8, "{x}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// PMT within about 4 ULPs of Excel's (Value2 of synthetic probes; libm differs by an ULP across
|
||||
/// platforms). The old `(1 + rate)^nper` form was 25 to 91 ULPs off on these, enough to flip a loan schedule's final `IF(p - SUM(r) > 0, ...)`.
|
||||
#[test]
|
||||
|
||||
@@ -218,21 +218,85 @@ fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R<f64> {
|
||||
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.
|
||||
fn rate_equation(r: f64, np: f64, pmt: f64, pv: f64, fv: f64, typ: f64) -> (f64, f64) {
|
||||
if r == 0.0 {
|
||||
return (pv + pmt * np + fv, pv.abs() + (pmt * np).abs() + fv.abs());
|
||||
}
|
||||
let p = (1.0 + r).powf(np);
|
||||
let (a, b) = (pv * p, pmt * (1.0 / r + typ) * (p - 1.0));
|
||||
(a + b + fv, a.abs() + b.abs() + fv.abs())
|
||||
}
|
||||
|
||||
/// Excel works with subnormal numbers flushed to zero: a secant step that underflows doesn't
|
||||
/// move. Observed with RATE(3,0,-1E-305,0), which is 0.101 (the second starting point).
|
||||
fn flush_subnormal(x: f64) -> f64 {
|
||||
if x.abs() < f64::MIN_POSITIVE { 0.0 } else { x }
|
||||
}
|
||||
|
||||
/// Excel's RATE solver, reconstructed by observing Excel with synthetic inputs (not from its
|
||||
/// code; its documentation says only "iteration", 20 steps and 0.0000001):
|
||||
///
|
||||
/// - A secant iteration starting at the guess and at the guess moved 0.001 toward a larger
|
||||
/// value of the equation, for at most 200 steps.
|
||||
/// - It stops at the first iterate that moved less than 1e-7 and where the equation is within
|
||||
/// 1e-7 of zero (or as close as its terms allow, for very large amounts). Excel returns that
|
||||
/// iterate, not the exact root, so a slowly converging case such as no payments and a zero
|
||||
/// future value (exact answer -100%) gives a rate just above -1.
|
||||
/// - The result must be above -1 by more than the tolerance; otherwise it is #NUM!.
|
||||
/// - After 200 steps without that, Excel still returns the last iterate if it is within a
|
||||
/// looser 1e-4 (step, equation value and distance above -1); otherwise #NUM!. So a root the
|
||||
/// iteration can't reach (a very large rate) is #NUM! even though it exists.
|
||||
fn rate_solve(f: impl Fn(f64) -> (f64, f64), guess: f64) -> R<f64> {
|
||||
const STEPS: usize = 200;
|
||||
const TOL: f64 = 1e-7;
|
||||
const LOOSE: f64 = 1e-4;
|
||||
let eval = |x: f64| {
|
||||
let (y, size) = f(x);
|
||||
if y.is_finite() { Ok((y, size)) } else { Err(CellError::Num) }
|
||||
};
|
||||
let near_zero = |y: f64, size: f64| y.abs() < TOL || y.abs() <= 1e-12 * size;
|
||||
let (mut x0, (mut f0, _)) = (guess, eval(guess)?);
|
||||
let mut x1 = if f0 < 0.0 { guess + 0.001 } else { guess - 0.001 };
|
||||
let (mut f1, mut size1) = eval(x1)?;
|
||||
for _ in 0..STEPS {
|
||||
let den = flush_subnormal(f1 - f0);
|
||||
if den == 0.0 {
|
||||
// The secant is flat: done if the iteration had already settled.
|
||||
if (x1 - x0).abs() < TOL && near_zero(f1, size1) && x1 - TOL > -1.0 {
|
||||
return Ok(x1);
|
||||
}
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let x2 = x1 - flush_subnormal(f1 * (x1 - x0)) / den;
|
||||
if !x2.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (f2, size2) = eval(x2)?;
|
||||
if (x2 - x1).abs() < TOL && near_zero(f2, size2) {
|
||||
return if x2 - TOL > -1.0 { Ok(x2) } else { Err(CellError::Num) };
|
||||
}
|
||||
(x0, f0, x1, f1, size1) = (x1, f1, x2, f2, size2);
|
||||
}
|
||||
if (x1 - x0).abs() < LOOSE && f1.abs() < LOOSE && x1 - LOOSE > -1.0 {
|
||||
return Ok(x1);
|
||||
}
|
||||
Err(CellError::Num)
|
||||
}
|
||||
|
||||
pub(super) fn rate(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let (np, pmt, pv) = (num(a, 0)?, num(a, 1)?, num(a, 2)?);
|
||||
let (fv, typ, guess) = (opt_num(a, 3, 0.0)?, type_arg(a, 4)?, opt_num(a, 5, 0.1)?);
|
||||
if np <= 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let f = |r: f64| {
|
||||
if r.abs() < 1e-12 {
|
||||
pv + pmt * np + fv
|
||||
} else {
|
||||
let p = (1.0 + r).powf(np);
|
||||
pv * p + pmt * (1.0 + r * typ) * (p - 1.0) / r + fv
|
||||
}
|
||||
};
|
||||
num_val(solve_rate(f, guess)?)
|
||||
// Excel: a guess at or below -100% is #VALUE!, not #NUM!.
|
||||
if guess <= -1.0 {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
num_val(rate_solve(|r| rate_equation(r, np, pmt, pv, fv, typ), guess)?)
|
||||
}
|
||||
|
||||
pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
|
||||
@@ -290,6 +290,44 @@ impl CellStore {
|
||||
let moved = self.take_rows(0..=u32::MAX, from..=u32::MAX);
|
||||
self.put_rows(moved.into_iter().map(|(row, cols)| (row, shift_keys(cols, delta))));
|
||||
}
|
||||
/// Deletes the rows in `spans` (`(first, count)`, ascending and disjoint) and closes the gaps
|
||||
/// in one pass: each later cell moves up once by the number of deleted rows above it.
|
||||
pub fn delete_rows(&mut self, spans: &[(u32, u32)]) {
|
||||
self.delete_lines(spans, true);
|
||||
}
|
||||
/// Column form of [`CellStore::delete_rows`].
|
||||
pub fn delete_cols(&mut self, spans: &[(u32, u32)]) {
|
||||
self.delete_lines(spans, false);
|
||||
}
|
||||
fn delete_lines(&mut self, spans: &[(u32, u32)], rows: bool) {
|
||||
let Some(&(first, _)) = spans.first() else { return };
|
||||
// Lines deleted before the end of each span, for mapping a kept line to its new place.
|
||||
let mut before = Vec::with_capacity(spans.len());
|
||||
let mut total = 0u32;
|
||||
for &(_, count) in spans {
|
||||
total = total.saturating_add(count);
|
||||
before.push(total);
|
||||
}
|
||||
let map = |v: u32| -> Option<u32> {
|
||||
let i = spans.partition_point(|&(at, _)| at <= v);
|
||||
let Some(i) = i.checked_sub(1) else { return Some(v) };
|
||||
let (at, count) = spans.get(i).copied().unwrap_or_default();
|
||||
if v - at < count { None } else { Some(v - before.get(i).copied().unwrap_or_default()) }
|
||||
};
|
||||
let keys: Vec<CellRef> = if rows {
|
||||
let r = RangeRef::new(CellRef::new(first, 0), CellRef::new(gridcraft_core::MAX_ROWS - 1, gridcraft_core::MAX_COLS - 1));
|
||||
self.iter_range(r).map(|(c, _)| c).collect()
|
||||
} else {
|
||||
self.iter().filter(|(c, _)| c.col >= first).map(|(c, _)| c).collect()
|
||||
};
|
||||
let moved: Vec<(CellRef, Cell)> = keys.into_iter().filter_map(|c| self.remove(c).map(|cell| (c, cell))).collect();
|
||||
for (c, cell) in moved {
|
||||
let to = if rows { map(c.row).map(|r| CellRef::new(r, c.col)) } else { map(c.col).map(|x| CellRef::new(c.row, x)) };
|
||||
if let Some(to) = to {
|
||||
self.set(to, cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Shifts cells within rows `r0..=r1` and columns `>= from` horizontally (Insert/Delete Cells
|
||||
/// with shift right/left).
|
||||
pub fn shift_cols_in_rows(&mut self, r0: u32, r1: u32, from: u32, delta: i64) {
|
||||
|
||||
+40
-12
@@ -293,23 +293,22 @@ impl NumberFormat {
|
||||
}
|
||||
|
||||
/// Formats a number. The flag is true when the value cannot be shown (date out of range).
|
||||
fn format_number(&self, n: f64, sys: DateSystem) -> (Formatted, bool) {
|
||||
let general = |n: f64| Formatted {
|
||||
text: format_general_fit(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()),
|
||||
color: None,
|
||||
fill: None,
|
||||
numeric: true,
|
||||
};
|
||||
/// With `full`, General is not narrowed to the cell width but written by [`general_full`].
|
||||
fn format_number(&self, n: f64, sys: DateSystem, full: bool) -> (Formatted, bool) {
|
||||
let general_text = |n: f64, width: usize| if full { Some(general_full(n)) } else { format_general_fit(n, width) };
|
||||
let general =
|
||||
|n: f64| Formatted { text: general_text(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()), color: None, fill: None, numeric: true };
|
||||
if self.is_general() {
|
||||
return (general(n), false);
|
||||
}
|
||||
let Some((sec, drop_sign)) = self.select(n) else { return (general(n), false) };
|
||||
let minus = n < 0.0 && !drop_sign;
|
||||
let out: Option<Out> = match sec.kind {
|
||||
SecKind::Text => Some(render::render_text(sec, &format_general_fit(n, GENERAL_WIDTH).unwrap_or_default())),
|
||||
SecKind::Text => Some(render::render_text(sec, &general_text(n, GENERAL_WIDTH).unwrap_or_default())),
|
||||
SecKind::General => {
|
||||
let width = if minus { GENERAL_WIDTH - 1 } else { GENERAL_WIDTH };
|
||||
Some(render::render_general(sec, n.abs(), width))
|
||||
let text = general_text(n.abs(), width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11)));
|
||||
Some(render::render_general(sec, &text))
|
||||
}
|
||||
SecKind::Date => {
|
||||
if minus {
|
||||
@@ -405,16 +404,45 @@ impl NumberFormat {
|
||||
|
||||
/// Formats a cell value for display.
|
||||
pub fn format_value(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted {
|
||||
format_value_with(v, fmt, sys, false)
|
||||
}
|
||||
|
||||
/// Formats a cell value as Save As CSV/Text writes it: like [`format_value`], except that a number
|
||||
/// shown as General (a General or Text section, with or without colour and literals) is not
|
||||
/// narrowed to the cell width but written by `general_full`: `124412140710`, not `1.24412E+11`.
|
||||
/// Excel writes the cell display here; GridCraft keeps the digits.
|
||||
pub fn format_value_full(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted {
|
||||
format_value_with(v, fmt, sys, true)
|
||||
}
|
||||
|
||||
/// General for Save As CSV/Text: the text `&` gives (15 significant digits), but never with an
|
||||
/// exponent, because reopening the file would give the cell a scientific format that rounds it
|
||||
/// on the next save. Where `&` writes an exponent, a number of 1 or more is written as the
|
||||
/// shortest digits that read back as the same value (every integer f64 holds below 1e16 exactly,
|
||||
/// so 16-digit card numbers survive), and a smaller one as its 15 significant digits in full.
|
||||
fn general_full(n: f64) -> String {
|
||||
let text = gridcraft_core::number_to_text(n);
|
||||
if !text.contains('E') {
|
||||
text
|
||||
} else if n.abs() >= 1.0 {
|
||||
format!("{n}")
|
||||
} else {
|
||||
let mag: i32 = format!("{n:.14e}").split_once('e').and_then(|(_, e)| e.parse().ok()).unwrap_or(0);
|
||||
gridcraft_core::value::trim_decimal(&format!("{:.*}", (14 - mag).max(0) as usize, n))
|
||||
}
|
||||
}
|
||||
|
||||
fn format_value_with(v: &Value, fmt: &NumberFormat, sys: DateSystem, full: bool) -> Formatted {
|
||||
match v {
|
||||
Value::Empty => Formatted::default(),
|
||||
Value::Number(n) if !n.is_finite() => Formatted { text: CellError::Num.as_str().into(), ..Formatted::default() },
|
||||
Value::Number(n) => fmt.format_number(*n, sys).0,
|
||||
Value::Number(n) => fmt.format_number(*n, sys, full).0,
|
||||
Value::Text(t) => fmt.format_text(t),
|
||||
Value::Bool(b) => Formatted { text: if *b { "TRUE" } else { "FALSE" }.into(), ..Formatted::default() },
|
||||
Value::Error(e) => Formatted { text: e.as_str().into(), ..Formatted::default() },
|
||||
Value::Array(a) => match a.data.first() {
|
||||
Some(Value::Array(_)) | None => Formatted::default(),
|
||||
Some(first) => format_value(first, fmt, sys),
|
||||
Some(first) => format_value_with(first, fmt, sys, full),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -525,7 +553,7 @@ pub fn text_function(v: &Value, code: &str, sys: DateSystem) -> Result<String, C
|
||||
if !n.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (f, overflow) = fmt.format_number(n, sys);
|
||||
let (f, overflow) = fmt.format_number(n, sys, false);
|
||||
if overflow { Err(CellError::Value) } else { Ok(f.text) }
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use gridcraft_core::DateSystem;
|
||||
use gridcraft_core::date::{datetime_from_serial, max_serial};
|
||||
|
||||
use crate::calendar::Calendar;
|
||||
use crate::decimal::{decimal_digits, fixed, fixed_from_digits, format_general_fit};
|
||||
use crate::decimal::{decimal_digits, fixed, fixed_from_digits};
|
||||
use crate::parse::{DatePart, Section, Tok};
|
||||
|
||||
/// Text being built plus the first repeat-fill position.
|
||||
@@ -81,12 +81,13 @@ pub(crate) fn render_text_within(sec: &Section, text: &str, max_units: usize) ->
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Renders a number through a General section (literals around the General keyword).
|
||||
pub(crate) fn render_general(sec: &Section, v: f64, width: usize) -> Out {
|
||||
/// Renders a number through a General section: `general` (the number already written as General)
|
||||
/// with the section's literals around it.
|
||||
pub(crate) fn render_general(sec: &Section, general: &str) -> Out {
|
||||
let mut out = Out::default();
|
||||
for t in &sec.toks {
|
||||
match t {
|
||||
Tok::General => out.push(&format_general_fit(v, width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11)))),
|
||||
Tok::General => out.push(general),
|
||||
Tok::Fill(c) => out.fill(*c),
|
||||
other => out.push_tok(other),
|
||||
}
|
||||
|
||||
@@ -668,7 +668,7 @@ fn text_uncached(v: &Value, code: &str, sys: DateSystem) -> Result<String, CellE
|
||||
if !n.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (f, overflow) = fmt.format_number(n, sys);
|
||||
let (f, overflow) = fmt.format_number(n, sys, false);
|
||||
if overflow { Err(CellError::Value) } else { Ok(f.text) }
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,9 @@ impl SheetApp {
|
||||
if matches!(id, "file.save" | "file.saveAs" | "file.saveBytes") {
|
||||
self.store_view_state();
|
||||
}
|
||||
if let Some(refused) = dialogs::refuse_sheet_change(self, id) {
|
||||
return Err(refused);
|
||||
}
|
||||
if matches!(
|
||||
id,
|
||||
"sheet.activate"
|
||||
|
||||
@@ -298,9 +298,12 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
|
||||
return painted;
|
||||
}
|
||||
// Source outlines stay in cell space beneath every floating object.
|
||||
if let Some(ch) = sh.charts.iter().find(|ch| app.selected_chart() == Some(ch.id))
|
||||
if let Some((_, data)) = selected_chart_data(app, geo, wb, si, sh, p.clip_rect()) {
|
||||
paint_chart_data(p, geo, sh, &data);
|
||||
} else if let Some(ch) = sh.charts.iter().find(|ch| app.selected_chart() == Some(ch.id))
|
||||
&& anchor_rect(geo, sh, &ch.anchor).intersects(p.clip_rect())
|
||||
{
|
||||
// Series that are not one block of cells: each series' values on this sheet.
|
||||
for s in &ch.series {
|
||||
if let Ok(gridcraft_engine::formula::Expr::Ref(rf)) = gridcraft_engine::formula::parse(&s.values)
|
||||
&& rf.sheet_name().is_none_or(|n| n.eq_ignore_ascii_case(&sh.name))
|
||||
@@ -550,6 +553,88 @@ fn selection_frame(p: &Painter, r: Rect) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from a corner of a selected chart's values outline a press still grabs it.
|
||||
const DATA_HANDLE_REACH: f32 = 6.0;
|
||||
/// The corners of a values outline, which drag it (#4389).
|
||||
const DATA_HANDLES: [crate::objects::Handle; 4] =
|
||||
[crate::objects::Handle::TopLeft, crate::objects::Handle::TopRight, crate::objects::Handle::BottomLeft, crate::objects::Handle::BottomRight];
|
||||
|
||||
/// The selected chart and its data as blocks on sheet `si` (`sh`), while the chart lies on screen
|
||||
/// within `clip`: the blocks a drag of its values outline previews, else where they are. `None`
|
||||
/// when no chart is selected, its data is on another sheet or its series are not one block.
|
||||
pub(crate) fn selected_chart_data(
|
||||
app: &SheetApp,
|
||||
geo: &Geo,
|
||||
wb: &Workbook,
|
||||
si: usize,
|
||||
sh: &Sheet,
|
||||
clip: Rect,
|
||||
) -> Option<(u32, gridcraft_engine::chart_data::ChartData)> {
|
||||
if objects_hidden(wb) {
|
||||
return None;
|
||||
}
|
||||
let id = app.selected_chart()?;
|
||||
let ch = sh.charts.iter().find(|ch| ch.id == id)?;
|
||||
let dragged = match app.grid.drag {
|
||||
crate::grid::Drag::ChartData { chart, to, .. } if chart == id => Some(to),
|
||||
_ => None,
|
||||
};
|
||||
// A drag that scrolls the chart away keeps its preview: the block is still being dragged.
|
||||
if dragged.is_none() && !anchor_rect(geo, sh, &ch.anchor).intersects(clip) {
|
||||
return None;
|
||||
}
|
||||
let data = gridcraft_engine::chart_data::chart_data(wb, si, ch).filter(|d| d.sheet == si)?;
|
||||
Some((id, dragged.flatten().map_or(data, |to| data.moved(to))))
|
||||
}
|
||||
|
||||
/// Where the handle on corner `h` of the values outline `rr` is painted.
|
||||
fn data_handle_rect(h: crate::objects::Handle, rr: Rect) -> Rect {
|
||||
Rect::from_center_size(h.pos(rr), vec2(7.0, 7.0))
|
||||
}
|
||||
|
||||
/// Outlines a chart's data as Excel does: series names in red, category labels in purple and
|
||||
/// values in blue (#4390), with a handle on each corner of the values (#4389). Each pane clips
|
||||
/// its own part, so frozen panes show the block once.
|
||||
fn paint_chart_data(p: &Painter, geo: &Geo, sh: &Sheet, data: &gridcraft_engine::chart_data::ChartData) {
|
||||
let t = Tokens::get(p.ctx());
|
||||
let blocks = [(data.names, 1, false), (data.categories, 2, false), (Some(data.values), 0, true)];
|
||||
for (range, color, handles) in blocks.into_iter().filter_map(|(r, c, h)| r.map(|r| (r, t.ref_color(c, true), h))) {
|
||||
let rr = geo.range_rect(sh, range);
|
||||
for pane in geo.range_panes(range) {
|
||||
let pp = p.with_clip_rect(pane.intersect(p.clip_rect()));
|
||||
pp.rect_stroke(rr, 0.0, Stroke::new(1.5, color), StrokeKind::Inside);
|
||||
if handles {
|
||||
for h in DATA_HANDLES {
|
||||
pp.rect_filled(data_handle_rect(h, rr), 0.0, Color32::WHITE);
|
||||
pp.rect_filled(data_handle_rect(h, rr).shrink(1.0), 0.0, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The corner of the selected chart's values outline under `p`, with the chart and its values
|
||||
/// block. Like [`hit`], only over the cell area and while objects show; the caller asks
|
||||
/// [`hit`] first, since objects paint over the outline.
|
||||
pub fn chart_data_handle(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(u32, gridcraft_engine::core::RangeRef, crate::objects::Handle)> {
|
||||
if !geo.cells.contains(p) {
|
||||
return None;
|
||||
}
|
||||
let wb = &app.session.active()?.wb;
|
||||
let (id, data) = selected_chart_data(app, geo, wb, wb.active_sheet(), sh, geo.cells)?;
|
||||
let rr = geo.range_rect(sh, data.values);
|
||||
// Only a corner some pane paints: with frozen panes, a corner scrolled under the frozen band
|
||||
// is hidden, and the frozen cells it lies under keep the press.
|
||||
let panes = geo.range_panes(data.values);
|
||||
DATA_HANDLES
|
||||
.into_iter()
|
||||
.filter(|h| panes.iter().any(|pane| pane.intersects(data_handle_rect(*h, rr))))
|
||||
.map(|h| (h, h.pos(rr).distance(p)))
|
||||
.filter(|(_, d)| *d <= DATA_HANDLE_REACH)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(h, _)| (id, data.values, h))
|
||||
}
|
||||
|
||||
/// Where object `o` sits on the sheet (logical coordinates), when it exists on `sh`.
|
||||
pub fn object_rect(geo: &Geo, sh: &Sheet, o: ObjRef) -> Option<Rect> {
|
||||
sh.object_anchor(o).map(|a| anchor_rect(geo, sh, &a))
|
||||
|
||||
@@ -26,6 +26,7 @@ mod names;
|
||||
mod paste;
|
||||
mod ref_edit;
|
||||
mod show;
|
||||
mod sort_dialog;
|
||||
mod spelling;
|
||||
mod zoom;
|
||||
|
||||
@@ -38,6 +39,7 @@ use names::pasteable_names;
|
||||
pub(crate) use ref_edit::SHEET_DELETED;
|
||||
pub(crate) use show::build_params;
|
||||
pub use show::show;
|
||||
pub(crate) use sort_dialog::{grid_sense, refuse_sheet_change};
|
||||
use zoom::zoom_preset;
|
||||
|
||||
/// A form field. `Ref` is a range reference that can also be picked by selecting on the grid
|
||||
@@ -64,6 +66,8 @@ pub struct Dialog {
|
||||
pub tab: String,
|
||||
pub search: String,
|
||||
pub list_index: usize,
|
||||
/// Custom Sort's own state: the selection to restore and the column choices.
|
||||
sort: sort_dialog::State,
|
||||
pub result: Option<Json>,
|
||||
/// "Show password" is ticked: password fields show their text.
|
||||
pub show_password: bool,
|
||||
@@ -233,6 +237,7 @@ impl Dialog {
|
||||
tab: String::new(),
|
||||
search: String::new(),
|
||||
list_index: 0,
|
||||
sort: Default::default(),
|
||||
result: None,
|
||||
show_password: false,
|
||||
focus_first_field: true,
|
||||
@@ -258,6 +263,7 @@ impl Dialog {
|
||||
tab: String::new(),
|
||||
search: String::new(),
|
||||
list_index: 0,
|
||||
sort: Default::default(),
|
||||
result: None,
|
||||
show_password: false,
|
||||
focus_first_field: false,
|
||||
@@ -989,11 +995,7 @@ impl Dialog {
|
||||
}],
|
||||
json!({"kind": "blanks"}),
|
||||
),
|
||||
"sort" => {
|
||||
// Seed "Sort by" from the column the user is actually in (#1906).
|
||||
let col = app.session.active().map(|d| gridcraft_engine::core::col_to_letters(d.selection.active.col)).unwrap_or_else(|| "A".into());
|
||||
Dialog::custom("sort", "Sort", json!({"header": true, "levels": [{"column": col, "order": "asc"}]}))
|
||||
}
|
||||
"sort" => sort_dialog::open(app, ¶ms)?,
|
||||
"nameManager" => Dialog::custom("nameManager", "Name Manager", json!({})),
|
||||
"pasteName" => {
|
||||
// F3 opens it only when the workbook has names to paste, as in Excel.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#[cfg(test)]
|
||||
use super::show::build_params;
|
||||
use super::show::{form_fields, ok_cancel};
|
||||
use super::{Dialog, Field, Icon, Json, SheetApp, json, vec2};
|
||||
use super::{Dialog, Field, Json, SheetApp, json, vec2};
|
||||
|
||||
/// Initial values of the Data Validation form: the rule stored on the active cell, so OK without
|
||||
/// edits keeps it; a plain list rule when the cell has none.
|
||||
@@ -180,109 +180,8 @@ pub(super) fn advanced_filter_form(app: &SheetApp, ui: &mut egui::Ui, d: &mut Di
|
||||
ui.allocate_ui(vec2(ui.available_width(), ui.spacing().interact_size.y + 8.0), |ui| ok_cancel(ui, confirm, open));
|
||||
}
|
||||
|
||||
/// Draws the sort-level editor: header toggle, column/by/order controls, add/remove level, and `data.sort` on confirmation.
|
||||
pub(super) fn sort(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) {
|
||||
let lang = app.ui.language;
|
||||
let mut header = d.values.get("header").and_then(Json::as_bool).unwrap_or(true);
|
||||
ui.checkbox(&mut header, "My list has headers");
|
||||
d.values.insert("header".into(), json!(header));
|
||||
let mut levels: Vec<Json> = d.values.get("levels").and_then(Json::as_array).cloned().unwrap_or_default();
|
||||
// Columns of the region around the active cell, labelled with their header (or first value).
|
||||
let columns: Vec<(String, String)> = app
|
||||
.session
|
||||
.active()
|
||||
.and_then(|d| {
|
||||
let sh = d.wb.active()?;
|
||||
let region = gridcraft_engine::selection::current_region(sh, d.selection.active);
|
||||
Some(
|
||||
(region.start.col..=region.end.col)
|
||||
.map(|c| {
|
||||
let letter = gridcraft_engine::core::col_to_letters(c);
|
||||
// The region starts at the header row when one is present, so the
|
||||
// label always comes from start.row: header text with headers on,
|
||||
// first data value with them off.
|
||||
let label_row = region.start.row;
|
||||
let text = gridcraft_engine::display::cell_text(&d.wb, sh, gridcraft_engine::core::CellRef::new(label_row, c));
|
||||
let text: String = text.chars().take(24).collect();
|
||||
(letter.clone(), if text.is_empty() { letter } else { format!("{letter}: {text}") })
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut remove = None;
|
||||
for (i, lv) in levels.iter_mut().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(lang.tr(if i == 0 { "Sort by" } else { "Then by" }));
|
||||
let mut col = lv["column"].as_str().unwrap_or("A").to_string();
|
||||
if columns.is_empty() {
|
||||
ui.add(egui::TextEdit::singleline(&mut col).desired_width(50.0)).labelled_by(label.id);
|
||||
} else {
|
||||
// The closed box shows the same "B: Revenue" label as the list, not the bare letter (#3446).
|
||||
let shown =
|
||||
columns.iter().find(|(letter, _)| letter.eq_ignore_ascii_case(&col)).map_or_else(|| col.clone(), |(_, label)| label.clone());
|
||||
craft_ui::ComboBox::from_id_salt(("sort_col", i))
|
||||
.selected_text(shown)
|
||||
.show_ui(ui, |ui| {
|
||||
for (letter, label) in &columns {
|
||||
ui.selectable_value(&mut col, letter.clone(), label.as_str());
|
||||
}
|
||||
})
|
||||
.response
|
||||
.labelled_by(label.id);
|
||||
}
|
||||
lv["column"] = json!(col.to_ascii_uppercase());
|
||||
let mut by = lv["by"].as_str().unwrap_or("values").to_string();
|
||||
craft_ui::ComboBox::from_id_salt(("by", i))
|
||||
.selected_text(match by.as_str() {
|
||||
"cellColor" => "Cell Color",
|
||||
"fontColor" => "Font Color",
|
||||
_ => "Cell Values",
|
||||
})
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut by, "values".into(), "Cell Values");
|
||||
ui.selectable_value(&mut by, "cellColor".into(), "Cell Color");
|
||||
ui.selectable_value(&mut by, "fontColor".into(), "Font Color");
|
||||
})
|
||||
.response
|
||||
.accessible_name(lang.tr("Sort On"));
|
||||
lv["by"] = json!(by);
|
||||
let mut desc = lv["order"].as_str() == Some("desc");
|
||||
ui.radio_value(&mut desc, false, "A to Z");
|
||||
ui.radio_value(&mut desc, true, "Z to A");
|
||||
lv["order"] = json!(if desc { "desc" } else { "asc" });
|
||||
if crate::widgets::icon_button(ui, Icon::Close, crate::theme::Tokens::get(ui.ctx()).text_dim, "Remove level", vec2(18.0, 18.0)).clicked()
|
||||
{
|
||||
remove = Some(i);
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(i) = remove
|
||||
&& levels.len() > 1
|
||||
{
|
||||
levels.remove(i);
|
||||
}
|
||||
if ui.button("+ Add Level").clicked() {
|
||||
let used: Vec<String> = levels.iter().filter_map(|l| l.get("column").and_then(Json::as_str).map(str::to_string)).collect();
|
||||
let next = columns
|
||||
.iter()
|
||||
.map(|(l, _)| l)
|
||||
.find(|l| !used.contains(l))
|
||||
.cloned()
|
||||
.or_else(|| columns.last().map(|(l, _)| l.clone()))
|
||||
.unwrap_or_else(|| "B".into());
|
||||
levels.push(json!({"column": next, "order": "asc"}));
|
||||
}
|
||||
d.values.insert("levels".into(), Json::Array(levels.clone()));
|
||||
let mut open = true;
|
||||
ok_cancel(ui, confirm, &mut open);
|
||||
if *confirm {
|
||||
app.run_or_alert("data.sort", json!({"header": header, "keys": levels}));
|
||||
}
|
||||
if !open {
|
||||
*confirm = true;
|
||||
}
|
||||
}
|
||||
// Custom Sort lives in its own module; `show` reaches it from here.
|
||||
pub(super) use super::sort_dialog::sort;
|
||||
|
||||
#[cfg(test)]
|
||||
mod data_validation_tests {
|
||||
|
||||
@@ -1,8 +1,23 @@
|
||||
use egui::Modifiers;
|
||||
|
||||
use super::show::ok_cancel;
|
||||
use super::{Dialog, Json, Key, SheetApp, json};
|
||||
|
||||
/// Draws the Find/Replace form with case, whole-cell and workbook options, requests field focus once, and runs find/replace with the current parameters.
|
||||
pub(super) fn find(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
// The dialog stays open over the sheet, so Undo and Redo reach the workbook (a Replace All
|
||||
// is undone without closing it first); inside a text box they edit the typed text instead.
|
||||
// A modal message blocks workbook shortcuts; otherwise use the grid's own shortcut table.
|
||||
if app.message.is_none() && !ui.ctx().text_edit_focused() {
|
||||
let pressed = ui.input_mut(|i| {
|
||||
[(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z), (Modifiers::COMMAND, Key::Z), (Modifiers::COMMAND, Key::Y)]
|
||||
.into_iter()
|
||||
.find(|&(m, key)| i.consume_key(m, key))
|
||||
});
|
||||
if let Some((m, key)) = pressed {
|
||||
crate::ribbon::shortcut(app, key, m);
|
||||
}
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
for tab in ["Find", "Replace"] {
|
||||
if ui.selectable_label(d.tab == tab, tab).clicked() {
|
||||
|
||||
@@ -326,6 +326,8 @@ fn active_sheet_name(app: &SheetApp) -> String {
|
||||
/// dialog about to run its command must not, since references without a sheet name would be
|
||||
/// read against the sheet still shown.
|
||||
pub(super) fn end_pick(app: &mut SheetApp, d: &mut Dialog) -> Result<(), String> {
|
||||
// Custom Sort puts back the selection it changed whenever it lets go of the grid.
|
||||
super::sort_dialog::restore_selection(app, d);
|
||||
d.refs.target = None;
|
||||
d.refs.collapsed = None;
|
||||
let Some(home) = d.refs.home.as_mut() else { return Ok(()) };
|
||||
|
||||
@@ -174,6 +174,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
"advancedFilter" => window.default_height(0.0),
|
||||
_ => window,
|
||||
};
|
||||
let window = super::sort_dialog::window(window, &d.name, ctx, app.ui.language);
|
||||
let (window, collapsed) = place_window(app, ctx, &mut d, window, window_id);
|
||||
let shown = window.show(ctx, |ui| {
|
||||
if let Some(key) = &collapsed {
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
//! Custom Sort (Data › Sort): sort levels with column, sort-on and order pickers.
|
||||
//!
|
||||
//! The dialog restores the grid selection it changed when it lets go of the grid (see
|
||||
//! [`restore_selection`], called from `ref_edit::end_pick`) and keeps the worksheet it opened on.
|
||||
|
||||
use gridcraft_engine::Selection;
|
||||
use gridcraft_engine::core::{CellRef, RangeRef, Value, col_to_letters};
|
||||
|
||||
use super::show::ok_cancel;
|
||||
use super::{Dialog, Json, Sense, SheetApp, json, vec2};
|
||||
use crate::i18n::Language;
|
||||
use crate::icons::Icon;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// Commands that change which worksheet is shown or which worksheets exist: refused while Sort is
|
||||
/// open, so Sort always acts on the worksheet it opened on.
|
||||
const SHEET_COMMANDS: [&str; 8] =
|
||||
["sheet.activate", "sheet.next", "sheet.previous", "sheet.move", "sheet.hide", "sheet.unhide", "home.insertSheet", "home.deleteSheet"];
|
||||
|
||||
/// What the dialog keeps besides its field values.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(super) struct State {
|
||||
/// The exact selection to restore when Sort closes, including ranges and the shift anchor.
|
||||
restore: Option<Selection>,
|
||||
/// The workbook and worksheet Sort opened on, by identity: the only one it may sort. A sheet's
|
||||
/// position changes when sheets are inserted, deleted, moved or undone, its [`SheetUid`] does not.
|
||||
home: Option<(u64, u64)>,
|
||||
choices: Option<ChoicesCache>,
|
||||
}
|
||||
|
||||
/// The column choices for one sheet revision, range, header setting and language.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ChoicesCache {
|
||||
language: Language,
|
||||
doc_uid: Option<u64>,
|
||||
sheet_index: Option<usize>,
|
||||
revision: Option<u64>,
|
||||
range: Option<String>,
|
||||
header: bool,
|
||||
choices: Vec<Choice>,
|
||||
}
|
||||
|
||||
/// A column of the sorted range: its letters, its label and whether its values are numbers.
|
||||
type Choice = (String, String, bool);
|
||||
|
||||
/// Opens Custom Sort on the range, worksheet and header guess of `data.sort`, seeding "Sort by" from the
|
||||
/// active column (#1906). A request that can't be resolved is reported and opens nothing.
|
||||
pub(super) fn open(app: &mut SheetApp, params: &Json) -> Option<Dialog> {
|
||||
let (sheet, range, header) = match gridcraft_engine::cmd::data::sort_context(&app.session, params) {
|
||||
Ok(context) => context,
|
||||
Err(e) => {
|
||||
app.message = Some(("Sort".into(), crate::clean_error(&e.to_string())));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// Sort works on the worksheet shown, so a request for another one shows it first.
|
||||
if app.session.active().is_some_and(|doc| doc.wb.active_sheet() != sheet)
|
||||
&& let Err(e) = app.run("sheet.activate", json!({"sheet": sheet}))
|
||||
{
|
||||
app.message = Some(("Sort".into(), crate::clean_error(&e)));
|
||||
return None;
|
||||
}
|
||||
// An open filter menu would take the Enter that confirms Sort (and apply its filter).
|
||||
app.grid.filter_menu = None;
|
||||
let restore = app.session.active().map(|doc| doc.selection.clone());
|
||||
let home = sheet_key(app);
|
||||
let active_col = app.session.active().map(|doc| doc.selection.active.col);
|
||||
let first = col_to_letters(active_col.filter(|c| (range.start.col..=range.end.col).contains(c)).unwrap_or(range.start.col));
|
||||
if header && range.height() > 1 {
|
||||
let _ = app.run("selection.set", json!({"range": body_of(range).a1()}));
|
||||
}
|
||||
let mut d = Dialog::custom("sort", "Sort", json!({"header": header, "range": range.a1(), "levels": [{"column": first, "order": "asc"}]}));
|
||||
d.sort.restore = restore;
|
||||
d.sort.home = home;
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// `r` without its header row.
|
||||
fn body_of(r: RangeRef) -> RangeRef {
|
||||
RangeRef::new(CellRef::new(r.start.row.saturating_add(1), r.start.col), r.end)
|
||||
}
|
||||
|
||||
/// The active workbook and worksheet by identity (document uid, [`SheetUid`]).
|
||||
///
|
||||
/// [`SheetUid`]: gridcraft_engine::model::SheetUid
|
||||
fn sheet_key(app: &SheetApp) -> Option<(u64, u64)> {
|
||||
let doc = app.session.active()?;
|
||||
Some((doc.uid, doc.wb.active()?.uid.get()))
|
||||
}
|
||||
|
||||
/// Puts back the selection from before Sort opened (once) on the worksheet it opened on: the
|
||||
/// selection shown while that sheet is active, else the one the sheet keeps for when it is shown
|
||||
/// again. Nothing is restored once that sheet is gone. Runs whenever a dialog lets go of the grid.
|
||||
pub(super) fn restore_selection(app: &mut SheetApp, d: &mut Dialog) {
|
||||
let Some((doc_uid, sheet_uid)) = d.sort.home.filter(|_| d.name == "sort") else { return };
|
||||
let Some(doc) = app.session.active_mut().filter(|doc| doc.uid == doc_uid) else { return };
|
||||
let Some(index) = doc.wb.sheets.iter().position(|s| s.uid.get() == sheet_uid) else { return };
|
||||
let Some(selection) = d.sort.restore.take() else { return };
|
||||
if index == doc.wb.active_sheet() {
|
||||
doc.selection = selection;
|
||||
} else {
|
||||
if doc.sheet_selections.len() < doc.wb.sheets.len() {
|
||||
doc.sheet_selections.resize(doc.wb.sheets.len(), Selection::default());
|
||||
}
|
||||
if let Some(slot) = doc.sheet_selections.get_mut(index) {
|
||||
*slot = selection;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason `id` is refused while Sort is open, if it is.
|
||||
pub(crate) fn refuse_sheet_change(app: &SheetApp, id: &str) -> Option<String> {
|
||||
(app.dialog.as_ref().is_some_and(|d| d.name == "sort") && SHEET_COMMANDS.contains(&id))
|
||||
.then(|| "Close the Sort dialog before switching or changing worksheets.".into())
|
||||
}
|
||||
|
||||
/// The grid ignores the mouse while Sort is open, so the selection cannot change under the dialog.
|
||||
pub(crate) fn grid_sense(app: &SheetApp) -> Sense {
|
||||
if app.dialog.as_ref().is_some_and(|d| d.name == "sort") { Sense::hover() } else { Sense::click_and_drag() }
|
||||
}
|
||||
|
||||
/// Sort moves and resizes. Its minimum width fits the whole toolbar row (the level buttons and the
|
||||
/// headers checkbox) in the interface language, so a longer translation widens the window instead
|
||||
/// of overlapping or wrapping the row.
|
||||
pub(super) fn window<'a>(window: egui::Window<'a>, name: &str, ctx: &egui::Context, lang: Language) -> egui::Window<'a> {
|
||||
if name != "sort" {
|
||||
return window;
|
||||
}
|
||||
let width = toolbar_width(ctx, lang).max(480.0);
|
||||
window.resizable(true).min_width(width).min_height(260.0).default_width(width.max(500.0)).default_height(320.0)
|
||||
}
|
||||
|
||||
/// The width of the toolbar row of [`sort`] with its labels on one line, plus the window frame.
|
||||
fn toolbar_width(ctx: &egui::Context, lang: Language) -> f32 {
|
||||
let style = ctx.global_style();
|
||||
let painter = ctx.layer_painter(egui::LayerId::background());
|
||||
let text = |font: egui::FontId, key: &str| painter.layout_no_wrap(lang.tr(key).to_string(), font, egui::Color32::PLACEHOLDER).size().x;
|
||||
let button_font = crate::theme::ui_font(12.5);
|
||||
// Mirrors `small_button_accent`: a 24px icon cell and the label plus 6px.
|
||||
let buttons: f32 = ["Add Level", "Delete Level", "Copy Level"].iter().map(|key| 24.0 + text(button_font.clone(), key) + 6.0).sum();
|
||||
let arrows = 2.0 * 24.0;
|
||||
let spacing = &style.spacing;
|
||||
let checkbox = spacing.icon_width + spacing.icon_spacing + text(egui::TextStyle::Body.resolve(&style), "My list has headers");
|
||||
// Five buttons and the checkbox, with the gaps between them, and the window's inner margin.
|
||||
(buttons + arrows + checkbox + 6.0 * spacing.item_spacing.x + 2.0 * style.spacing.window_margin.left as f32 + 16.0).ceil()
|
||||
}
|
||||
|
||||
/// The label of a column that has no header text: `Column A`, in the interface language.
|
||||
fn column_label(lang: Language, letters: &str) -> String {
|
||||
lang.tr("Column {letters}").replace("{letters}", letters)
|
||||
}
|
||||
|
||||
/// The columns of `range` with their labels: header text, or `Column A`, `Column B`… without headers.
|
||||
fn column_choices(app: &SheetApp, range: Option<RangeRef>, header: bool) -> Vec<Choice> {
|
||||
let Some(r) = range else { return Vec::new() };
|
||||
let lang = app.ui.language;
|
||||
let sh = app.session.active().and_then(|doc| doc.wb.active());
|
||||
let body_start = r.start.row.saturating_add(u32::from(header));
|
||||
let cols = r.end.col.saturating_sub(r.start.col).saturating_add(1).max(1) as usize;
|
||||
// Total sampled cells are bounded across all columns, not per column.
|
||||
let rows_per_col = (200_000 / cols).max(1);
|
||||
(r.start.col..=r.end.col)
|
||||
.map(|c| {
|
||||
let letters = col_to_letters(c);
|
||||
let text = match (header, sh) {
|
||||
(true, Some(sh)) => sh.value(CellRef::new(r.start.row, c)).display().trim().to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let label = if text.is_empty() { column_label(lang, &letters) } else { text };
|
||||
let numeric =
|
||||
sh.is_some_and(|sh| values_are_numeric((body_start..=r.end.row).take(rows_per_col).map(|row| sh.value(CellRef::new(row, c)))));
|
||||
(letters, label, numeric)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The column choices, recomputed only when the sheet, range, header setting or language changed.
|
||||
fn cached_choices(app: &SheetApp, d: &mut Dialog, range: Option<RangeRef>, header: bool) -> Vec<Choice> {
|
||||
let language = app.ui.language;
|
||||
let (doc_uid, sheet_index, revision) =
|
||||
app.session.active().map(|doc| (Some(doc.uid), Some(doc.wb.active_sheet()), Some(doc.revision))).unwrap_or_default();
|
||||
let range_key = range.map(|r| r.a1());
|
||||
if let Some(cache) = &d.sort.choices
|
||||
&& cache.language == language
|
||||
&& cache.doc_uid == doc_uid
|
||||
&& cache.sheet_index == sheet_index
|
||||
&& cache.revision == revision
|
||||
&& cache.range == range_key
|
||||
&& cache.header == header
|
||||
{
|
||||
return cache.choices.clone();
|
||||
}
|
||||
let choices = column_choices(app, range, header);
|
||||
d.sort.choices = Some(ChoicesCache { language, doc_uid, sheet_index, revision, range: range_key, header, choices: choices.clone() });
|
||||
choices
|
||||
}
|
||||
|
||||
/// The column a new level starts on: the first column no level uses, and once every column is used
|
||||
/// the selected level's column (as Copy Level would give), so more levels can always be added.
|
||||
fn next_level_column(choices: &[Choice], levels: &[Json], selected: usize) -> Option<String> {
|
||||
let used: Vec<&str> = levels.iter().filter_map(|l| l["column"].as_str()).collect();
|
||||
choices
|
||||
.iter()
|
||||
.map(|(l, _, _)| l.as_str())
|
||||
.find(|l| !used.contains(l))
|
||||
.or_else(|| levels.get(selected).and_then(|l| l["column"].as_str()))
|
||||
.or_else(|| choices.first().map(|(l, _, _)| l.as_str()))
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
/// Draws the sort-level editor: header toggle, level actions, the level rows and OK/Cancel; OK runs `data.sort`.
|
||||
pub(super) fn sort(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool) {
|
||||
let mut header = d.values.get("header").and_then(Json::as_bool).unwrap_or(true);
|
||||
let was_header = header;
|
||||
let range = d.values.get("range").and_then(Json::as_str).and_then(RangeRef::parse);
|
||||
let lang = app.ui.language;
|
||||
let choices = cached_choices(app, d, range, header);
|
||||
let mut levels: Vec<Json> = d.values.get("levels").and_then(Json::as_array).cloned().unwrap_or_default();
|
||||
let mut selected = d.list_index.min(levels.len().saturating_sub(1));
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
// Levels are not limited by the columns, allow the same column twice (up to 64 levels).
|
||||
let next_column = next_level_column(&choices, &levels, selected);
|
||||
if text_icon_button(ui, Icon::Plus, t.accent, "Add Level", levels.len() < 64 && next_column.is_some()).clicked()
|
||||
&& let Some(next) = next_column
|
||||
{
|
||||
levels.push(json!({"column": next, "order": "asc"}));
|
||||
selected = levels.len() - 1;
|
||||
}
|
||||
if text_icon_button(ui, Icon::Close, t.danger, "Delete Level", !levels.is_empty()).clicked() && selected < levels.len() {
|
||||
levels.remove(selected);
|
||||
selected = selected.saturating_sub(1);
|
||||
}
|
||||
if text_icon_button(ui, Icon::Copy, t.text, "Copy Level", !levels.is_empty() && levels.len() < 64).clicked()
|
||||
&& let Some(lv) = levels.get(selected).cloned()
|
||||
{
|
||||
levels.insert(selected + 1, lv);
|
||||
selected += 1;
|
||||
}
|
||||
if icon_button(ui, Icon::ChevronUp, t.text, "Move Up", selected > 0).clicked() {
|
||||
levels.swap(selected, selected - 1);
|
||||
selected -= 1;
|
||||
}
|
||||
if icon_button(ui, Icon::Chevron, t.text, "Move Down", selected + 1 < levels.len()).clicked() {
|
||||
levels.swap(selected, selected + 1);
|
||||
selected += 1;
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.checkbox(&mut header, lang.tr("My list has headers"));
|
||||
});
|
||||
});
|
||||
d.values.insert("header".into(), json!(header));
|
||||
if header != was_header
|
||||
&& let Some(r) = range
|
||||
{
|
||||
let shown = if header && r.height() > 1 { body_of(r) } else { r };
|
||||
let _ = app.run("selection.set", json!({"range": shown.a1()}));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let table_height = (ui.available_height() - 48.0).max(60.0);
|
||||
egui::ScrollArea::vertical().max_height(table_height).min_scrolled_height(table_height).auto_shrink([false, false]).show(ui, |ui| {
|
||||
levels_table(ui, &mut levels, &mut selected, &choices, lang);
|
||||
});
|
||||
d.list_index = selected;
|
||||
d.values.insert("levels".into(), Json::Array(levels.clone()));
|
||||
let mut open = true;
|
||||
ok_cancel(ui, confirm, &mut open);
|
||||
if *confirm && !levels.is_empty() {
|
||||
let mut p = json!({"header": header, "keys": levels});
|
||||
if let Some(r) = d.values.get("range").and_then(Json::as_str) {
|
||||
p["range"] = json!(r);
|
||||
}
|
||||
// The range has no sheet name, so it must not be read against another worksheet.
|
||||
let failure = if sheet_key(app) != d.sort.home {
|
||||
Some("Return to the original worksheet to sort, or cancel.".to_string())
|
||||
} else {
|
||||
app.run("data.sort", p).err().map(|e| crate::clean_error(&e))
|
||||
};
|
||||
if let Some(message) = failure {
|
||||
app.message = Some((d.title.clone(), message));
|
||||
*confirm = false;
|
||||
}
|
||||
}
|
||||
if !open {
|
||||
*confirm = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// The selectable level rows: "Sort by"/"Then by" with the column, sort-on and order pickers.
|
||||
fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, choices: &[Choice], lang: Language) {
|
||||
let gap = ui.spacing().item_spacing.x;
|
||||
// The row label column grows with the translated words, so a longer one is never wrapped or cut.
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let label_w = ["Sort by", "Then by"]
|
||||
.iter()
|
||||
.map(|key| ui.painter().layout_no_wrap(lang.tr(key).to_string(), font.clone(), egui::Color32::PLACEHOLDER).size().x.ceil() + 4.0)
|
||||
.fold(64.0, f32::max);
|
||||
let row_h = 26.0;
|
||||
let rest = (ui.available_width() - 16.0 - label_w - 3.0 * gap).max(300.0);
|
||||
let w = rest / 3.0;
|
||||
let cell = |ui: &mut egui::Ui, w: f32, h: f32, add: &mut dyn FnMut(&mut egui::Ui)| {
|
||||
ui.allocate_ui_with_layout(vec2(w, h), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.set_min_size(vec2(w, h));
|
||||
add(ui);
|
||||
});
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
cell(ui, label_w + gap + w, 18.0, &mut |ui| {
|
||||
ui.strong(lang.tr("Sort|Column"));
|
||||
});
|
||||
cell(ui, w, 18.0, &mut |ui| {
|
||||
ui.strong(lang.tr("Sort On"));
|
||||
});
|
||||
cell(ui, w, 18.0, &mut |ui| {
|
||||
ui.strong(lang.tr("Order"));
|
||||
});
|
||||
});
|
||||
let accent = Tokens::get(ui.ctx()).accent;
|
||||
for (i, lv) in levels.iter_mut().enumerate() {
|
||||
let row_rect = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), row_h));
|
||||
let row = ui.interact(row_rect, ui.scope_id().with(("sortRow", i)), Sense::click());
|
||||
if i == *selected {
|
||||
ui.painter().rect_filled(row_rect, 3.0, accent.gamma_multiply(0.18));
|
||||
} else if row.hovered() {
|
||||
ui.painter().rect_filled(row_rect, 3.0, accent.gamma_multiply(0.07));
|
||||
}
|
||||
if row.clicked() {
|
||||
*selected = i;
|
||||
}
|
||||
ui.allocate_ui_with_layout(row_rect.size(), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
cell(ui, label_w, row_h, &mut |ui| {
|
||||
ui.add(egui::Label::new(lang.tr(if i == 0 { "Sort by" } else { "Then by" })).selectable(false));
|
||||
});
|
||||
let mut col = lv["column"].as_str().unwrap_or("A").to_string();
|
||||
// The closed box names the column as its open list does (#3446), whatever the case of the stored letter.
|
||||
let shown = choices
|
||||
.iter()
|
||||
.find(|(l, _, _)| l.eq_ignore_ascii_case(&col))
|
||||
.map_or_else(|| column_label(lang, &col.to_ascii_uppercase()), |(_, t, _)| t.clone());
|
||||
let r = craft_ui::ComboBox::from_id_salt(("col", i)).selected_text(shown).width(w).show_ui(ui, |ui| {
|
||||
for (letters, label, _) in choices {
|
||||
ui.selectable_value(&mut col, letters.clone(), label);
|
||||
}
|
||||
});
|
||||
r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Sort|Column")));
|
||||
if r.response.clicked() {
|
||||
*selected = i;
|
||||
}
|
||||
lv["column"] = json!(col.to_ascii_uppercase());
|
||||
let mut by = lv["by"].as_str().unwrap_or("values").to_string();
|
||||
let by_label = lang.tr(match by.as_str() {
|
||||
"cellColor" => "Cell Color",
|
||||
"fontColor" => "Font Color",
|
||||
_ => "Cell Values",
|
||||
});
|
||||
let r = craft_ui::ComboBox::from_id_salt(("by", i)).selected_text(by_label).width(w).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut by, "values".into(), lang.tr("Cell Values"));
|
||||
ui.selectable_value(&mut by, "cellColor".into(), lang.tr("Cell Color"));
|
||||
ui.selectable_value(&mut by, "fontColor".into(), lang.tr("Font Color"));
|
||||
});
|
||||
r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Sort On")));
|
||||
if r.response.clicked() {
|
||||
*selected = i;
|
||||
}
|
||||
lv["by"] = json!(by);
|
||||
let numeric = choices.iter().find(|(l, _, _)| lv["column"].as_str() == Some(l.as_str())).is_some_and(|(_, _, n)| *n);
|
||||
let (asc_label, desc_label) = if numeric { ("Smallest to Largest", "Largest to Smallest") } else { ("A to Z", "Z to A") };
|
||||
let (asc_label, desc_label) = (lang.tr(asc_label), lang.tr(desc_label));
|
||||
let mut desc = lv["order"].as_str() == Some("desc");
|
||||
let order_label = if desc { desc_label } else { asc_label };
|
||||
let r = craft_ui::ComboBox::from_id_salt(("order", i)).selected_text(order_label).width(w).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut desc, false, asc_label);
|
||||
ui.selectable_value(&mut desc, true, desc_label);
|
||||
});
|
||||
r.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, lang.tr("Order")));
|
||||
if r.response.clicked() {
|
||||
*selected = i;
|
||||
}
|
||||
lv["order"] = json!(if desc { "desc" } else { "asc" });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A bordered icon-only button with a tooltip, greyed out when disabled.
|
||||
fn icon_button(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, tip: &str, enabled: bool) -> egui::Response {
|
||||
let color = if enabled { color } else { Tokens::get(ui.ctx()).text_disabled };
|
||||
let response = ui.add_enabled_ui(enabled, |ui| crate::widgets::icon_button(ui, icon, color, tip, vec2(24.0, 24.0))).inner;
|
||||
button_border(ui, response.rect);
|
||||
response
|
||||
}
|
||||
|
||||
/// A bordered button with a coloured icon and a text label, greyed out when disabled.
|
||||
fn text_icon_button(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, label: &str, enabled: bool) -> egui::Response {
|
||||
let response = ui.add_enabled_ui(enabled, |ui| crate::widgets::small_button_accent(ui, icon, Some(color), label, label, false)).inner;
|
||||
button_border(ui, response.rect);
|
||||
response
|
||||
}
|
||||
|
||||
/// Draws the visible border around a button's `rect`.
|
||||
fn button_border(ui: &egui::Ui, rect: egui::Rect) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.painter().rect_stroke(rect, 4.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// Whether the values are numbers (blanks aside), which picks "Smallest to Largest" over "A to Z".
|
||||
fn values_are_numeric(values: impl IntoIterator<Item = Value>) -> bool {
|
||||
let mut has_number = false;
|
||||
for value in values {
|
||||
match value {
|
||||
Value::Empty => {}
|
||||
Value::Number(_) => has_number = true,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
has_number
|
||||
}
|
||||
@@ -160,6 +160,11 @@ mod tests {
|
||||
assert_eq!(sig("IF", En, Language::Es), "IF(prueba_lógica, [valor_si_verdadero], [valor_si_falso])");
|
||||
assert_eq!(sig("SUM", En, Language::Es), "SUM(número1, [número2], ...)");
|
||||
assert_eq!(description("IF", En, Language::Es).as_deref(), Some("Devuelve un valor según una condición."));
|
||||
// Portuguese help, including brackets that open and close on different arguments.
|
||||
assert_eq!(sig("IF", En, Language::PtBr), "IF(teste_lógico, [valor_se_verdadeiro], [valor_se_falso])");
|
||||
assert_eq!(description("IF", En, Language::PtBr).as_deref(), Some("Retorna um valor quando uma condição é TRUE e outro quando é FALSE."));
|
||||
assert_eq!(sig("SWITCH", En, Language::PtBr), "SWITCH(expressão, valor1, resultado1, [padrão_ou_valor2, resultado2], ...)");
|
||||
assert_eq!(sig("LAMBDA", En, Language::PtBr), "LAMBDA([parâmetro1, ...], cálculo)");
|
||||
// Spanish names and separators, from a localized name.
|
||||
assert_eq!(sig("suma", Es, Language::Es), "SUMA(número1; [número2]; ...)");
|
||||
assert_eq!(description("SUMA", Es, Language::Es).as_deref(), Some("Suma los números."));
|
||||
|
||||
@@ -151,6 +151,14 @@ pub enum Drag {
|
||||
/// step of an earlier drag.
|
||||
stepped: bool,
|
||||
},
|
||||
/// Dragging a corner of the selected chart's values outline (#4389): `to` is the previewed
|
||||
/// block, which the release gives the chart.
|
||||
ChartData {
|
||||
chart: u32,
|
||||
orig: RangeRef,
|
||||
corner: crate::objects::Handle,
|
||||
to: Option<RangeRef>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The fill a left-drag of the handle just made, which the Auto Fill Options button can redo
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(super) fn center_across_end(start: u32, limit: u32, continues: impl Fn(u32)
|
||||
pub(super) fn look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut CfCache) -> (Look, Option<CfLook>) {
|
||||
let mut style = wb.styles.get(sh.style_id(c)).clone();
|
||||
if let Some(t) = sh.table_at(c) {
|
||||
style = gridcraft_engine::tables::table_cell_style(wb, si, t, c);
|
||||
style = gridcraft_engine::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c);
|
||||
}
|
||||
let cfl = cf.look(wb, si, c);
|
||||
if let Some(l) = &cfl
|
||||
|
||||
@@ -57,7 +57,7 @@ fn drag_cursor(drag: &Drag, rtl: bool) -> Option<CursorIcon> {
|
||||
Drag::ResizeCol { .. } => Some(CursorIcon::ResizeColumn),
|
||||
Drag::ResizeRow { .. } => Some(CursorIcon::ResizeRow),
|
||||
Drag::Freeze { cols, .. } => Some(if *cols { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeVertical }),
|
||||
Drag::Object { handle: Some(h), .. } => Some(h.cursor(rtl)),
|
||||
Drag::Object { handle: Some(h), .. } | Drag::ChartData { corner: h, .. } => Some(h.cursor(rtl)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +87,9 @@ fn hover_cursor(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, poin
|
||||
let mods = ctx.input(|i| i.modifiers);
|
||||
let works = hit.is_some_and(|(o, _)| o.kind == ObjKind::Control && app.selected_object != Some(o) && !mods.command && !mods.ctrl);
|
||||
let on_object = hit.is_some();
|
||||
if let Some(h) = object_handle {
|
||||
// A corner of the selected chart's values outline resizes the chart's data, where no object covers it.
|
||||
let data_handle = if idle && !on_object { crate::chartview::chart_data_handle(app, geo, sh, p).map(|(.., h)| h) } else { None };
|
||||
if let Some(h) = object_handle.or(data_handle) {
|
||||
ctx.set_cursor_icon(h.cursor(geo.rtl));
|
||||
} else if works {
|
||||
ctx.set_cursor_icon(CursorIcon::PointingHand);
|
||||
|
||||
@@ -157,6 +157,20 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A corner of the selected chart's values outline drags the block the chart plots
|
||||
// (#4389); a click on it keeps the chart selected.
|
||||
if let Some(p) = at
|
||||
&& app.editor.is_none()
|
||||
&& let Some((chart, orig, corner)) = crate::chartview::chart_data_handle(app, geo, sh, p)
|
||||
{
|
||||
if primary_drag {
|
||||
app.grid.drag = Drag::ChartData { chart, orig, corner, to: None };
|
||||
if let Some(now) = pos {
|
||||
drag_chart_data(app, geo, sh, now);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
app.selected_object = None;
|
||||
}
|
||||
// A right-click on a chart, picture, shape, slicer or form control opens the object's menu, not
|
||||
@@ -630,22 +644,30 @@ fn handle_context_menu_and_keyboard(app: &mut SheetApp, input: &InteractionInput
|
||||
keyboard(app, &ctx, resp, geo, sh);
|
||||
}
|
||||
|
||||
/// Whether Esc was pressed this frame, with any modifiers; every Esc press is then spent, so the
|
||||
/// grid's own Esc doesn't also drop a pending copy or Format Painter.
|
||||
fn spend_escape(ctx: &egui::Context) -> bool {
|
||||
ctx.input_mut(|i| {
|
||||
let pressed = i.key_pressed(egui::Key::Escape);
|
||||
if pressed {
|
||||
i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }));
|
||||
}
|
||||
pressed
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
let (geo, sh, wb, sel, pos) = (input.geo, input.sheet, input.workbook, &input.selection, input.position);
|
||||
let resp = input.response;
|
||||
// Esc during a header-boundary drag cancels it: undo the preview, ignore the release. egui
|
||||
// aborts the drag on Esc, so `resp.dragged()` is already false in this frame. The key is
|
||||
// spent on the drag, so the grid's Esc doesn't also drop a pending copy or Format Painter.
|
||||
if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. })
|
||||
&& input.context.input_mut(|i| {
|
||||
let pressed = i.key_pressed(egui::Key::Escape);
|
||||
if pressed {
|
||||
// With any modifiers, as before: the drag is cancelled and every Esc press spent.
|
||||
i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }));
|
||||
}
|
||||
pressed
|
||||
})
|
||||
{
|
||||
// Esc during a drag of a chart's values outline drops it: the chart keeps its data, whatever
|
||||
// modifiers are held (egui ends the drag on any Esc, so the release must not apply it).
|
||||
if matches!(app.grid.drag, Drag::ChartData { .. }) && spend_escape(&input.context) {
|
||||
app.grid.drag = Drag::None;
|
||||
}
|
||||
if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. }) && spend_escape(&input.context) {
|
||||
// Undo back to where the drag began, but never past it into an earlier edit.
|
||||
let steps = resize_steps(app);
|
||||
if steps > 0 {
|
||||
@@ -742,6 +764,10 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
scroll_by(app, auto);
|
||||
}
|
||||
Drag::Object { .. } => drag_object(app, geo, sh, p),
|
||||
Drag::ChartData { .. } => {
|
||||
drag_chart_data(app, geo, sh, p);
|
||||
scroll_by(app, auto);
|
||||
}
|
||||
Drag::None => {}
|
||||
}
|
||||
}
|
||||
@@ -822,6 +848,23 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
coalesce_resize_undo(app);
|
||||
}
|
||||
}
|
||||
// The release may be the first frame to report the pointer's last position, so the
|
||||
// block is taken from there. (Esc already dropped a cancelled drag, and so did a
|
||||
// change to the chart's data; one in the release's own frame is caught here.)
|
||||
Drag::ChartData { chart, orig, corner, to } => {
|
||||
let to = if resp.drag_stopped()
|
||||
&& let Some(p) = pos
|
||||
{
|
||||
Some(chart_data_target(geo, sh, orig, corner, p))
|
||||
} else {
|
||||
to
|
||||
};
|
||||
if let Some(to) = to.filter(|to| *to != orig)
|
||||
&& chart_still_plots(app, chart, orig)
|
||||
{
|
||||
app.run_or_alert("chart.setValuesRange", json!({"chart": chart, "range": to.a1()}));
|
||||
}
|
||||
}
|
||||
Drag::MoveCols { source, before: Some(before) } => {
|
||||
if let Err(e) = app.run("sheet.moveColumns", json!({"cols": source.a1(), "before": before})) {
|
||||
app.message = Some(("GridCraft".into(), crate::clean_error(&e)));
|
||||
@@ -1201,6 +1244,69 @@ fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Previews the selected chart's values block with the grabbed corner dragged to `p` (logical
|
||||
/// coordinates); the opposite corner stays. The release gives the chart the block
|
||||
/// (`chart.setValuesRange`).
|
||||
fn drag_chart_data(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
|
||||
let Drag::ChartData { chart, orig, corner, .. } = app.grid.drag else { return };
|
||||
// The chart's data changed under the drag: drop it, as Esc does, rather than preview a
|
||||
// block the release would put over that change.
|
||||
if !chart_still_plots(app, chart, orig) {
|
||||
app.grid.drag = Drag::None;
|
||||
return;
|
||||
}
|
||||
app.grid.drag = Drag::ChartData { chart, orig, corner, to: Some(chart_data_target(geo, sh, orig, corner, p)) };
|
||||
}
|
||||
|
||||
/// Whether chart `chart` on the active sheet still plots the values block `orig` its drag
|
||||
/// started from. A command run between frames (the control channel, a macro) may have changed
|
||||
/// or removed it, and the dragged block would then overwrite that change. Read from the session,
|
||||
/// not the frame's workbook, which predates such a command.
|
||||
fn chart_still_plots(app: &SheetApp, chart: u32, orig: RangeRef) -> bool {
|
||||
let Some(wb) = app.session.active().map(|d| &d.wb) else { return false };
|
||||
let si = wb.active_sheet();
|
||||
wb.sheet(si)
|
||||
.and_then(|sh| sh.charts.iter().find(|ch| ch.id == chart))
|
||||
.and_then(|ch| gridcraft_engine::chart_data::chart_data(wb, si, ch))
|
||||
.is_some_and(|data| data.sheet == si && data.values == orig)
|
||||
}
|
||||
|
||||
/// The values block `orig` with its `corner` dragged to `p`. Each edge the corner moves snaps
|
||||
/// to the gridline nearest the pointer, so every row and column changes over at its own middle
|
||||
/// whatever its height or width, and a release where the press was (on the corner's own
|
||||
/// gridlines) changes nothing. The block may flip past its fixed edges, as a selection does; a
|
||||
/// moving edge dropped on its fixed edge keeps one row or column.
|
||||
fn chart_data_target(geo: &Geo, sh: &Sheet, orig: RangeRef, corner: crate::objects::Handle, p: Pos2) -> RangeRef {
|
||||
let (sx, sy) = corner.sides();
|
||||
let (x, y) = (p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0), p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0));
|
||||
// Gridline `k` is the top (left) edge of row (column) `k`; the last one closes the sheet.
|
||||
let row = geo.row_at(sh, y);
|
||||
let row_line = nearest_line(geo.y(sh, row), sh.row_height(row) * geo.z, row, y, MAX_ROWS);
|
||||
let col = geo.col_at(sh, x);
|
||||
let col_line = nearest_line(geo.x(sh, col), sh.col_width(col) * geo.z, col, x, MAX_COLS);
|
||||
let (r0, r1) = between_lines(if sy < 0 { orig.end.row.saturating_add(1) } else { orig.start.row }, row_line, sy);
|
||||
let (c0, c1) = between_lines(if sx < 0 { orig.end.col.saturating_add(1) } else { orig.start.col }, col_line, sx);
|
||||
RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1))
|
||||
}
|
||||
|
||||
/// The gridline nearest `v` for line `index`, which starts at `start` and is `size` long: its
|
||||
/// own start, or the next line's past its middle (never past `last`).
|
||||
fn nearest_line(start: f32, size: f32, index: u32, v: f32, last: u32) -> u32 {
|
||||
if v - start < size / 2.0 { index } else { index.saturating_add(1).min(last) }
|
||||
}
|
||||
|
||||
/// The rows (columns) from gridline `fixed` to gridline `moving`. A moving edge on the fixed one
|
||||
/// keeps one line on its own side: after it for a bottom or right edge (`dir` > 0), before it
|
||||
/// for a top or left edge.
|
||||
fn between_lines(fixed: u32, moving: u32, dir: i8) -> (u32, u32) {
|
||||
let moving = match (moving == fixed, dir > 0) {
|
||||
(false, _) => moving,
|
||||
(true, true) => fixed.saturating_add(1),
|
||||
(true, false) => fixed.saturating_sub(1),
|
||||
};
|
||||
(fixed.min(moving), fixed.max(moving).saturating_sub(1))
|
||||
}
|
||||
|
||||
/// A click on a hyperlink. References select; web and e-mail addresses ask first (the dialog's
|
||||
/// OK calls `Session::open_confirmed_link`, since `link.open` refuses them for programmatic
|
||||
/// callers, #2181); every other kind is refused with a message. The decision is the engine's
|
||||
@@ -1253,6 +1359,28 @@ pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, exte
|
||||
mod resize_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_chart_data_edge_snaps_to_the_nearest_gridline_of_any_size() {
|
||||
// Row 5 starts at 100 and is 20 tall: before its middle the line is its own, past it the next.
|
||||
assert_eq!(nearest_line(100.0, 20.0, 5, 109.0, MAX_ROWS), 5);
|
||||
assert_eq!(nearest_line(100.0, 20.0, 5, 111.0, MAX_ROWS), 6);
|
||||
// A 100-tall row changes over at 50 into it, not at the grabbed row's middle.
|
||||
assert_eq!(nearest_line(100.0, 100.0, 5, 149.0, MAX_ROWS), 5);
|
||||
assert_eq!(nearest_line(100.0, 100.0, 5, 151.0, MAX_ROWS), 6);
|
||||
assert_eq!(nearest_line(0.0, 20.0, MAX_ROWS - 1, 19.0, MAX_ROWS), MAX_ROWS);
|
||||
// A1:A5 (lines 0 and 5) by its bottom edge: on line 5 it stays, on 8 it grows, on 2 it shrinks.
|
||||
assert_eq!(between_lines(0, 5, 1), (0, 4));
|
||||
assert_eq!(between_lines(0, 8, 1), (0, 7));
|
||||
assert_eq!(between_lines(0, 2, 1), (0, 1));
|
||||
// Dropped on its fixed edge it keeps one row; past it the block flips.
|
||||
assert_eq!(between_lines(4, 4, 1), (4, 4));
|
||||
assert_eq!(between_lines(4, 2, 1), (2, 3));
|
||||
// By its top edge (fixed line 5, below A5).
|
||||
assert_eq!(between_lines(5, 0, -1), (0, 4));
|
||||
assert_eq!(between_lines(5, 5, -1), (4, 4));
|
||||
assert_eq!(between_lines(5, 7, -1), (5, 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_targets_follow_the_selection_only_when_the_dragged_line_is_in_it() {
|
||||
let sel = [RangeRef::cols(0, 0), RangeRef::cols(2, 3)];
|
||||
|
||||
@@ -2,8 +2,10 @@ use super::geo::Geo;
|
||||
use super::menus::is_checkbox;
|
||||
use super::{CellRef, Drag, Sheet, SheetApp, json};
|
||||
|
||||
/// Grid keyboard handling when no text field has focus.
|
||||
pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) {
|
||||
/// 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
|
||||
/// within the workspace limit.
|
||||
fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response) -> bool {
|
||||
// Focus left on an editor that no longer exists goes back to the grid.
|
||||
let stale = [egui::Id::unique("gridcraft.cell_editor"), egui::Id::unique("gridcraft.formula_bar"), crate::text_box::editor_id()];
|
||||
let editing = app.editor.is_some() || app.text_box_editor.is_some();
|
||||
@@ -14,7 +16,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
// An open filter menu owns the keyboard even when a click inside it left focus on nothing (#1516).
|
||||
// So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an
|
||||
// arrow key would move the selection the menu fills from), and a macro's question.
|
||||
if editing
|
||||
editing
|
||||
|| app.dialog.is_some()
|
||||
|| other_focus
|
||||
|| app.message.is_some()
|
||||
@@ -22,7 +24,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
|| app.grid.fill_menu.is_some()
|
||||
|| matches!(app.grid.drag, Drag::Fill { menu: true, .. })
|
||||
|| app.macros.question.is_some()
|
||||
{
|
||||
}
|
||||
|
||||
/// Grid keyboard handling when no text field has focus.
|
||||
pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) {
|
||||
if keyboard_elsewhere(app, ctx, resp) {
|
||||
return;
|
||||
}
|
||||
if ctx.memory(|m| m.focused()).is_none() {
|
||||
@@ -32,6 +38,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
ctx.memory_mut(|m| {
|
||||
m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true })
|
||||
});
|
||||
request_grid_ime(app, ctx, resp, geo, sh);
|
||||
let events = grid_events(app, ctx, sh);
|
||||
// A shortcut key that also types a character (Shift+Space sends Text(" ")) must not start an edit.
|
||||
let shortcut_pressed = events.iter().any(|e| {
|
||||
@@ -43,6 +50,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
// a shortcut ran, that text must not start an edit over what it just did.
|
||||
let mut shortcut_ran = false;
|
||||
for ev in events {
|
||||
// IME events are handled outside the match to keep this loop's complexity down. Any
|
||||
// non-commit IME event (preedit, delete-surrounding) falls through to `_ => {}` below.
|
||||
if handle_ime_commit(app, &ev, shortcut_pressed, shortcut_ran) {
|
||||
return;
|
||||
}
|
||||
match ev {
|
||||
egui::Event::Copy => {
|
||||
app.copy_to_clipboard(ctx, "edit.copy");
|
||||
@@ -58,11 +70,13 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
// insert text at, so a middle click on a cell is deliberately not a paste.
|
||||
egui::Event::MiddleClickPaste { .. } => {}
|
||||
egui::Event::Text(_) if shortcut_pressed || shortcut_ran => {}
|
||||
// A space on a checkbox cell toggles it (the `Key::Space` arm below). The same key
|
||||
// press also arrives as text, and typing text starts editing the cell -- so the cell
|
||||
// toggled *and* opened an editor holding a space, which Enter then committed over the
|
||||
// checkbox (#1951).
|
||||
egui::Event::Text(text) if text == " " && is_checkbox(sh, app) => {}
|
||||
egui::Event::Text(text) if text.chars().all(|c| !c.is_control()) && !text.is_empty() => {
|
||||
app.begin_edit(Some(text), false);
|
||||
if let Some(ed) = app.editor.as_mut() {
|
||||
ed.caret = ed.text.chars().count();
|
||||
}
|
||||
seed_editor(app, text);
|
||||
return;
|
||||
}
|
||||
egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => {
|
||||
@@ -146,7 +160,9 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
// Ctrl+Shift+letter (⌘⇧letter) runs the macro with that shortcut, unless GridCraft uses it.
|
||||
_ if cmd && shift && !m.alt && crate::macro_ui::run_shortcut(app, key) => {}
|
||||
_ if cmd && !crate::keymap::altgr_text(ctx, m, ctx.os() == egui::os::OperatingSystem::Mac) => {
|
||||
crate::ribbon::shortcut(app, key, m)
|
||||
// The same key the English table reads: Ctrl+Shift+, typing `;` is Ctrl+;.
|
||||
let (key, shift) = crate::keymap::us_key(key, physical_key, shift).unwrap_or((key, shift));
|
||||
crate::ribbon::shortcut(app, key, egui::Modifiers { shift, ..m });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -156,6 +172,78 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the in-cell editor with typed or committed text and put the caret after it.
|
||||
fn seed_editor(app: &mut SheetApp, text: String) {
|
||||
app.begin_edit(Some(text), false);
|
||||
if let Some(ed) = app.editor.as_mut() {
|
||||
ed.caret = ed.text.chars().count();
|
||||
}
|
||||
}
|
||||
|
||||
/// Seed the editor from a finished composition, if `ev` is one.
|
||||
///
|
||||
/// Only `ImeEvent::Commit` is finished text; a preedit is the input method's in-progress
|
||||
/// spelling and must not seed the editor. `Event::Ime` and `Event::Text` are mutually
|
||||
/// exclusive for one keystroke, so accepting a commit cannot double-insert a character.
|
||||
/// Returns whether the caller should stop handling this frame's events.
|
||||
fn handle_ime_commit(app: &mut SheetApp, ev: &egui::Event, shortcut_pressed: bool, shortcut_ran: bool) -> bool {
|
||||
let egui::Event::Ime(egui::ImeEvent::Commit(text)) = ev else { return false };
|
||||
if shortcut_pressed || shortcut_ran || text.is_empty() {
|
||||
return false;
|
||||
}
|
||||
seed_editor(app, text.clone());
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask the OS to route keystrokes through the input method while the grid owns keyboard input.
|
||||
///
|
||||
/// egui enables IME only for a widget that publishes `PlatformOutput::ime` in that frame. The
|
||||
/// in-cell `TextEdit` opens *after* the grid has consumed the first keystroke, so without this
|
||||
/// the first key of a CJK composition is delivered as raw `Event::Text` and lands in the cell
|
||||
/// (Wubi `xta` writes `x` and the input method only ever sees `ta`). The request must be
|
||||
/// published on every focused frame, not in response to a key: winit applies it at the end of
|
||||
/// the frame, so a key arriving while IME is still off cannot be recovered.
|
||||
///
|
||||
/// `PlatformOutput` is rebuilt every frame, so returning early (an editor, a dialog or another
|
||||
/// widget taking focus) simply leaves `ime` as `None` and the input method turns off.
|
||||
fn request_grid_ime(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) {
|
||||
if !ctx.memory(|m| m.owns_ime_events(resp.id)) {
|
||||
return;
|
||||
}
|
||||
let Some(d) = app.session.active() else { return };
|
||||
let active = d.selection.active;
|
||||
let merged = sh.merge_at(active);
|
||||
// `begin_edit` refuses a locked cell on a protected sheet. Publishing an IME request for
|
||||
// one would let the user compose text that is then discarded, so skip it up front, using
|
||||
// the same merged-cell anchor and protection check as `SheetApp::begin_edit`.
|
||||
let anchor = merged.map(|m| m.start).unwrap_or(active);
|
||||
if app.session.locked_cell_message(d.wb.active_sheet(), anchor).is_some() {
|
||||
return;
|
||||
}
|
||||
// `cell_rect`/`range_rect` are logical coordinates, but `IMEOutput` needs screen ones.
|
||||
// On a right-to-left sheet the grid is mirrored, so publishing the logical rect puts the
|
||||
// candidate window on the opposite side. After mirroring, `rect.min` is the screen-side
|
||||
// start of the cell in both layouts, which is where the caret belongs.
|
||||
let rect = match merged {
|
||||
Some(m) => geo.mirror_rect(geo.range_rect(sh, m)),
|
||||
None => geo.mirror_rect(geo.cell_rect(sh, active)),
|
||||
};
|
||||
let cursor_rect = egui::Rect::from_min_size(rect.min, egui::vec2(1.0, rect.height()));
|
||||
// egui 0.37 identifies an IME context by (owner, generation). The generation must change
|
||||
// when this owner gains focus and stay stable for ordinary text and selection updates.
|
||||
let gained_focus = resp.gained_focus();
|
||||
let generation = ctx.data_mut(|data| {
|
||||
let g: &mut u64 = data.get_temp_mut_or_default(egui::Id::unique("gridcraft.grid_ime_generation"));
|
||||
if gained_focus || *g == 0 {
|
||||
*g = g.wrapping_add(1);
|
||||
}
|
||||
*g
|
||||
});
|
||||
ctx.output_mut(|o| {
|
||||
o.ime = Some(egui::output::IMEOutput::new(resp.id, generation, egui::IMEPurpose::Normal, rect, cursor_rect));
|
||||
});
|
||||
}
|
||||
|
||||
/// 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());
|
||||
|
||||
@@ -53,7 +53,7 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
} else {
|
||||
Rect::from_min_max(available.min, pos2(available.right() - bar, available.bottom()))
|
||||
};
|
||||
let resp = ui.allocate_rect(rect, Sense::click_and_drag());
|
||||
let resp = ui.allocate_rect(rect, crate::dialogs::grid_sense(app));
|
||||
app.grid.rect = Some(rect);
|
||||
let Some(d) = app.session.active() else { return };
|
||||
let wb: Arc<Workbook> = d.wb.clone();
|
||||
|
||||
@@ -21,6 +21,7 @@ mod ko;
|
||||
mod nl;
|
||||
mod pl;
|
||||
mod pt;
|
||||
mod pt_functions;
|
||||
mod ro;
|
||||
mod ru;
|
||||
mod sr;
|
||||
@@ -252,6 +253,7 @@ impl Language {
|
||||
fn function_help(self) -> Option<(HelpTable, HelpTable)> {
|
||||
match self {
|
||||
Self::Es => Some((es_functions::DESCRIPTIONS, es_functions::ARGUMENTS)),
|
||||
Self::PtBr => Some((pt_functions::DESCRIPTIONS, pt_functions::ARGUMENTS)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -493,6 +495,45 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Custom Sort dialog's own strings have a row in every catalog (no silent English
|
||||
/// fallback), keep the `{letters}` placeholder, and read as plain English in English.
|
||||
#[test]
|
||||
fn custom_sort_strings_are_translated_in_every_catalog() {
|
||||
let keys = [
|
||||
"Sort by",
|
||||
"Then by",
|
||||
"My list has headers",
|
||||
"Cell Values",
|
||||
"Cell Color",
|
||||
"Font Color",
|
||||
"A to Z",
|
||||
"Z to A",
|
||||
"Add Level",
|
||||
"Delete Level",
|
||||
"Copy Level",
|
||||
"Move Up",
|
||||
"Move Down",
|
||||
"Order",
|
||||
"Sort On",
|
||||
"Sort|Column",
|
||||
"Column {letters}",
|
||||
"Smallest to Largest",
|
||||
"Largest to Smallest",
|
||||
"Close the Sort dialog before switching or changing worksheets.",
|
||||
"Return to the original worksheet to sort, or cancel.",
|
||||
];
|
||||
for key in keys {
|
||||
let english = key.rsplit_once('|').map_or(key, |(_, label)| label);
|
||||
assert_eq!(Language::En.tr(key), english);
|
||||
for language in Language::ALL.into_iter().filter(|l| *l != Language::En) {
|
||||
let code = language.code();
|
||||
let shown = language.translated(key).unwrap_or_else(|| panic!("{code}: no row for {key:?}"));
|
||||
assert!(!shown.trim().is_empty() && !shown.contains('|'), "{code}: bad translation of {key:?}: {shown:?}");
|
||||
assert_eq!(shown.contains("{letters}"), key.contains("{letters}"), "{code}: placeholder of {key:?}: {shown:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_puts_each_value_in_once() {
|
||||
// A value holding a placeholder (a macro named `{steps}`) is shown as it is.
|
||||
|
||||
@@ -600,6 +600,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Zobrazit",
|
||||
"Collapse dialog" => "Sbalit dialogové okno",
|
||||
"Expand dialog" => "Rozbalit dialogové okno",
|
||||
"My list has headers" => "Data obsahují záhlaví",
|
||||
"Sort by" => "Seřadit podle",
|
||||
"Then by" => "Potom podle",
|
||||
"Cell Values" => "Hodnoty buněk",
|
||||
"Cell Color" => "Barva buňky",
|
||||
"A to Z" => "Od A do Z",
|
||||
"Z to A" => "Od Z do A",
|
||||
"Add Level" => "Přidat úroveň",
|
||||
"Delete Level" => "Odstranit úroveň",
|
||||
"Copy Level" => "Kopírovat úroveň",
|
||||
"Move Up" => "Posunout nahoru",
|
||||
"Move Down" => "Posunout dolů",
|
||||
"Order" => "Pořadí",
|
||||
"Sort On" => "Seřadit podle",
|
||||
"Sort|Column" => "Sloupec",
|
||||
"Column {letters}" => "Sloupec {letters}",
|
||||
"Smallest to Largest" => "Od nejmenšího po největší",
|
||||
"Largest to Smallest" => "Od největšího po nejmenší",
|
||||
"Close the Sort dialog before switching or changing worksheets." => "Před přepnutím nebo změnou listů zavřete dialogové okno Seřadit.",
|
||||
"Return to the original worksheet to sort, or cancel." => "Chcete-li řadit, vraťte se na původní list, nebo akci zrušte.",
|
||||
"Numerical Count" => "Počet čísel",
|
||||
"Minimum" => "Minimum",
|
||||
"Maximum" => "Maximum",
|
||||
|
||||
@@ -520,6 +520,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Anzeigen",
|
||||
"Collapse dialog" => "Dialogfeld reduzieren",
|
||||
"Expand dialog" => "Dialogfeld erweitern",
|
||||
"My list has headers" => "Daten haben Überschriften",
|
||||
"Sort by" => "Sortieren nach",
|
||||
"Then by" => "Anschließend nach",
|
||||
"Cell Values" => "Zellenwerte",
|
||||
"Cell Color" => "Zellenfarbe",
|
||||
"A to Z" => "A bis Z",
|
||||
"Z to A" => "Z bis A",
|
||||
"Add Level" => "Ebene hinzufügen",
|
||||
"Delete Level" => "Ebene löschen",
|
||||
"Copy Level" => "Ebene kopieren",
|
||||
"Move Up" => "Nach oben",
|
||||
"Move Down" => "Nach unten",
|
||||
"Order" => "Reihenfolge",
|
||||
"Sort On" => "Sortieren nach",
|
||||
"Sort|Column" => "Spalte",
|
||||
"Column {letters}" => "Spalte {letters}",
|
||||
"Smallest to Largest" => "Vom Kleinsten zum Größten",
|
||||
"Largest to Smallest" => "Vom Größten zum Kleinsten",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Schließen Sie das Dialogfeld „Sortieren“, bevor Sie das Blatt wechseln oder Blätter ändern."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Kehren Sie zum ursprünglichen Blatt zurück, um zu sortieren, oder brechen Sie ab.",
|
||||
"Numerical Count" => "Numerische Zählung",
|
||||
"Minimum" => "Minimum",
|
||||
"Maximum" => "Maximum",
|
||||
|
||||
@@ -884,7 +884,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Cell Color" => "Χρώμα κελιού",
|
||||
"A to Z" => "Α έως Ω",
|
||||
"Z to A" => "Ω έως Α",
|
||||
"+ Add Level" => "+ Προσθήκη επιπέδου",
|
||||
"Add Level" => "Προσθήκη επιπέδου",
|
||||
"Delete Level" => "Διαγραφή επιπέδου",
|
||||
"Copy Level" => "Αντιγραφή επιπέδου",
|
||||
"Move Up" => "Μετακίνηση πάνω",
|
||||
"Move Down" => "Μετακίνηση κάτω",
|
||||
"Order" => "Σειρά",
|
||||
"Sort On" => "Ταξινόμηση ως προς",
|
||||
"Sort|Column" => "Στήλη",
|
||||
"Column {letters}" => "Στήλη {letters}",
|
||||
"Smallest to Largest" => "Από το μικρότερο στο μεγαλύτερο",
|
||||
"Largest to Smallest" => "Από το μεγαλύτερο στο μικρότερο",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Κλείστε το παράθυρο διαλόγου Ταξινόμηση πριν αλλάξετε ή τροποποιήσετε φύλλα εργασίας."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Επιστρέψτε στο αρχικό φύλλο εργασίας για να ταξινομήσετε ή ακυρώστε.",
|
||||
"New…" => "Νέο…",
|
||||
"Edit…" => "Επεξεργασία…",
|
||||
"Name" => "Όνομα",
|
||||
|
||||
@@ -526,6 +526,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Mostrar",
|
||||
"Collapse dialog" => "Contraer diálogo",
|
||||
"Expand dialog" => "Expandir diálogo",
|
||||
"My list has headers" => "Mis datos tienen encabezados",
|
||||
"Sort by" => "Ordenar por",
|
||||
"Then by" => "Luego por",
|
||||
"Cell Values" => "Valores de celda",
|
||||
"Cell Color" => "Color de celda",
|
||||
"A to Z" => "De A a Z",
|
||||
"Z to A" => "De Z a A",
|
||||
"Add Level" => "Agregar nivel",
|
||||
"Delete Level" => "Eliminar nivel",
|
||||
"Copy Level" => "Copiar nivel",
|
||||
"Move Up" => "Subir",
|
||||
"Move Down" => "Bajar",
|
||||
"Order" => "Orden",
|
||||
"Sort On" => "Ordenar según",
|
||||
"Sort|Column" => "Columna",
|
||||
"Column {letters}" => "Columna {letters}",
|
||||
"Smallest to Largest" => "De menor a mayor",
|
||||
"Largest to Smallest" => "De mayor a menor",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Cierre el cuadro de diálogo Ordenar antes de cambiar de hoja o modificar las hojas."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Vuelva a la hoja original para ordenar o cancele.",
|
||||
"Numerical Count" => "Recuento numérico",
|
||||
"Minimum" => "Mínimo",
|
||||
"Maximum" => "Máximo",
|
||||
|
||||
@@ -486,6 +486,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Afficher",
|
||||
"Collapse dialog" => "Réduire la boîte de dialogue",
|
||||
"Expand dialog" => "Développer la boîte de dialogue",
|
||||
"My list has headers" => "Mes données ont des en-têtes",
|
||||
"Sort by" => "Trier par",
|
||||
"Then by" => "Puis par",
|
||||
"Cell Values" => "Valeurs de cellule",
|
||||
"Cell Color" => "Couleur de cellule",
|
||||
"A to Z" => "De A à Z",
|
||||
"Z to A" => "De Z à A",
|
||||
"Add Level" => "Ajouter un niveau",
|
||||
"Delete Level" => "Supprimer le niveau",
|
||||
"Copy Level" => "Copier le niveau",
|
||||
"Move Up" => "Monter",
|
||||
"Move Down" => "Descendre",
|
||||
"Order" => "Ordre",
|
||||
"Sort On" => "Trier sur",
|
||||
"Sort|Column" => "Colonne",
|
||||
"Column {letters}" => "Colonne {letters}",
|
||||
"Smallest to Largest" => "Du plus petit au plus grand",
|
||||
"Largest to Smallest" => "Du plus grand au plus petit",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Fermez la boîte de dialogue Trier avant de changer de feuille ou de modifier les feuilles."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Revenez à la feuille d’origine pour trier, ou annulez.",
|
||||
"Numerical Count" => "Nombre de valeurs numériques",
|
||||
"Minimum" => "Minimum",
|
||||
"Maximum" => "Maximum",
|
||||
|
||||
@@ -770,7 +770,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Cell Color" => "Colore cella",
|
||||
"A to Z" => "Dalla A alla Z",
|
||||
"Z to A" => "Dalla Z alla A",
|
||||
"+ Add Level" => "+ Aggiungi livello",
|
||||
"Add Level" => "Aggiungi livello",
|
||||
"Delete Level" => "Elimina livello",
|
||||
"Copy Level" => "Copia livello",
|
||||
"Move Up" => "Sposta su",
|
||||
"Move Down" => "Sposta giù",
|
||||
"Order" => "Ordine",
|
||||
"Sort On" => "Ordina in base a",
|
||||
"Sort|Column" => "Colonna",
|
||||
"Column {letters}" => "Colonna {letters}",
|
||||
"Smallest to Largest" => "Dal più piccolo al più grande",
|
||||
"Largest to Smallest" => "Dal più grande al più piccolo",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Chiudi la finestra di dialogo Ordina prima di cambiare o modificare i fogli di lavoro."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Torna al foglio di lavoro originale per ordinare oppure annulla.",
|
||||
"New…" => "Nuovo…",
|
||||
"Edit…" => "Modifica…",
|
||||
"Name" => "Nome",
|
||||
|
||||
@@ -786,7 +786,22 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
|
||||
("Cell Color", "セルの色"),
|
||||
("A to Z", "昇順"),
|
||||
("Z to A", "降順"),
|
||||
("+ Add Level", "+ レベルの追加"),
|
||||
("Add Level", "レベルの追加"),
|
||||
("Delete Level", "レベルの削除"),
|
||||
("Copy Level", "レベルのコピー"),
|
||||
("Move Up", "上へ移動"),
|
||||
("Move Down", "下へ移動"),
|
||||
("Order", "順序"),
|
||||
("Sort On", "並べ替えのキー"),
|
||||
("Sort|Column", "列"),
|
||||
("Column {letters}", "列 {letters}"),
|
||||
("Smallest to Largest", "小さい順"),
|
||||
("Largest to Smallest", "大きい順"),
|
||||
(
|
||||
"Close the Sort dialog before switching or changing worksheets.",
|
||||
"シートを切り替えたり変更したりする前に、並べ替えダイアログを閉じてください。",
|
||||
),
|
||||
("Return to the original worksheet to sort, or cancel.", "並べ替えるには元のシートに戻るか、キャンセルしてください。"),
|
||||
("New…", "新規作成…"),
|
||||
("Edit…", "編集…"),
|
||||
("Name", "名前"),
|
||||
|
||||
@@ -490,6 +490,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "표시",
|
||||
"Collapse dialog" => "대화 상자 축소",
|
||||
"Expand dialog" => "대화 상자 확장",
|
||||
"My list has headers" => "내 데이터에 머리글 표시",
|
||||
"Sort by" => "정렬 기준",
|
||||
"Then by" => "다음 기준",
|
||||
"Cell Values" => "셀 값",
|
||||
"Cell Color" => "셀 색",
|
||||
"A to Z" => "A에서 Z",
|
||||
"Z to A" => "Z에서 A",
|
||||
"Add Level" => "기준 추가",
|
||||
"Delete Level" => "기준 삭제",
|
||||
"Copy Level" => "기준 복사",
|
||||
"Move Up" => "위로 이동",
|
||||
"Move Down" => "아래로 이동",
|
||||
"Order" => "정렬",
|
||||
"Sort On" => "정렬 기준",
|
||||
"Sort|Column" => "열",
|
||||
"Column {letters}" => "{letters} 열",
|
||||
"Smallest to Largest" => "가장 작은 값에서 가장 큰 값으로",
|
||||
"Largest to Smallest" => "가장 큰 값에서 가장 작은 값으로",
|
||||
"Close the Sort dialog before switching or changing worksheets." => "시트를 전환하거나 변경하기 전에 정렬 대화 상자를 닫으세요.",
|
||||
"Return to the original worksheet to sort, or cancel." => "정렬하려면 원래 시트로 돌아가거나 취소하세요.",
|
||||
"Numerical Count" => "숫자 셀 수",
|
||||
"Minimum" => "최소값",
|
||||
"Maximum" => "최대값",
|
||||
|
||||
@@ -561,6 +561,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Weergeven",
|
||||
"Collapse dialog" => "Dialoogvenster samenvouwen",
|
||||
"Expand dialog" => "Dialoogvenster uitvouwen",
|
||||
"My list has headers" => "Mijn gegevens bevatten kopteksten",
|
||||
"Sort by" => "Sorteren op",
|
||||
"Then by" => "Vervolgens op",
|
||||
"Cell Values" => "Celwaarden",
|
||||
"Cell Color" => "Celkleur",
|
||||
"A to Z" => "A tot Z",
|
||||
"Z to A" => "Z tot A",
|
||||
"Add Level" => "Niveau toevoegen",
|
||||
"Delete Level" => "Niveau verwijderen",
|
||||
"Copy Level" => "Niveau kopiëren",
|
||||
"Move Up" => "Omhoog",
|
||||
"Move Down" => "Omlaag",
|
||||
"Order" => "Volgorde",
|
||||
"Sort On" => "Sorteren op",
|
||||
"Sort|Column" => "Kolom",
|
||||
"Column {letters}" => "Kolom {letters}",
|
||||
"Smallest to Largest" => "Van klein naar groot",
|
||||
"Largest to Smallest" => "Van groot naar klein",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Sluit het dialoogvenster Sorteren voordat u van blad wisselt of bladen wijzigt."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Ga terug naar het oorspronkelijke blad om te sorteren, of annuleer.",
|
||||
"Numerical Count" => "Numerieke telling",
|
||||
"Minimum" => "Minimum",
|
||||
"Maximum" => "Maximum",
|
||||
|
||||
@@ -761,7 +761,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Cell Color" => "Kolor komórki",
|
||||
"A to Z" => "Od A do Z",
|
||||
"Z to A" => "Od Z do A",
|
||||
"+ Add Level" => "+ Dodaj poziom",
|
||||
"Add Level" => "Dodaj poziom",
|
||||
"Delete Level" => "Usuń poziom",
|
||||
"Copy Level" => "Kopiuj poziom",
|
||||
"Move Up" => "Przesuń w górę",
|
||||
"Move Down" => "Przesuń w dół",
|
||||
"Order" => "Kolejność",
|
||||
"Sort On" => "Sortuj na podstawie",
|
||||
"Sort|Column" => "Kolumna",
|
||||
"Column {letters}" => "Kolumna {letters}",
|
||||
"Smallest to Largest" => "Od najmniejszych do największych",
|
||||
"Largest to Smallest" => "Od największych do najmniejszych",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Zamknij okno dialogowe Sortowanie przed przełączeniem lub zmianą arkuszy."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Wróć do oryginalnego arkusza, aby posortować, lub anuluj.",
|
||||
"New…" => "Nowy…",
|
||||
"Edit…" => "Edytuj…",
|
||||
"Name" => "Nazwa",
|
||||
|
||||
@@ -795,7 +795,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Cell Color" => "Cor da Célula",
|
||||
"A to Z" => "De A a Z",
|
||||
"Z to A" => "De Z a A",
|
||||
"+ Add Level" => "+ Adicionar Nível",
|
||||
"Add Level" => "Adicionar Nível",
|
||||
"Delete Level" => "Excluir Nível",
|
||||
"Copy Level" => "Copiar Nível",
|
||||
"Move Up" => "Mover para Cima",
|
||||
"Move Down" => "Mover para Baixo",
|
||||
"Order" => "Ordem",
|
||||
"Sort On" => "Classificar em",
|
||||
"Sort|Column" => "Coluna",
|
||||
"Column {letters}" => "Coluna {letters}",
|
||||
"Smallest to Largest" => "Do Menor para o Maior",
|
||||
"Largest to Smallest" => "Do Maior para o Menor",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Feche a caixa de diálogo Classificar antes de alternar ou alterar planilhas."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Volte para a planilha original para classificar ou cancele.",
|
||||
"New…" => "Novo…",
|
||||
"Edit…" => "Editar…",
|
||||
"Name" => "Nome",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -767,7 +767,21 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Cell Color" => "Culoare celulă",
|
||||
"A to Z" => "De la A la Z",
|
||||
"Z to A" => "De la Z la A",
|
||||
"+ Add Level" => "+ Adăugare nivel",
|
||||
"Add Level" => "Adăugare nivel",
|
||||
"Delete Level" => "Ștergere nivel",
|
||||
"Copy Level" => "Copiere nivel",
|
||||
"Move Up" => "Mutare în sus",
|
||||
"Move Down" => "Mutare în jos",
|
||||
"Order" => "Ordine",
|
||||
"Sort On" => "Sortare pe baza",
|
||||
"Sort|Column" => "Coloană",
|
||||
"Column {letters}" => "Coloană {letters}",
|
||||
"Smallest to Largest" => "De la cel mai mic la cel mai mare",
|
||||
"Largest to Smallest" => "De la cel mai mare la cel mai mic",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Închideți caseta de dialog Sortare înainte de a comuta sau a modifica foile de lucru."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Reveniți la foaia de lucru inițială pentru a sorta sau anulați.",
|
||||
"New…" => "Nou…",
|
||||
"Edit…" => "Editare…",
|
||||
"Name" => "Nume",
|
||||
|
||||
@@ -494,6 +494,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Показать",
|
||||
"Collapse dialog" => "Свернуть диалоговое окно",
|
||||
"Expand dialog" => "Развернуть диалоговое окно",
|
||||
"My list has headers" => "Мои данные содержат заголовки",
|
||||
"Sort by" => "Сортировать по",
|
||||
"Then by" => "Затем по",
|
||||
"Cell Values" => "Значения ячеек",
|
||||
"Cell Color" => "Цвет ячейки",
|
||||
"A to Z" => "От А до Я",
|
||||
"Z to A" => "От Я до А",
|
||||
"Add Level" => "Добавить уровень",
|
||||
"Delete Level" => "Удалить уровень",
|
||||
"Copy Level" => "Копировать уровень",
|
||||
"Move Up" => "Вверх",
|
||||
"Move Down" => "Вниз",
|
||||
"Order" => "Порядок",
|
||||
"Sort On" => "Сортировка",
|
||||
"Sort|Column" => "Столбец",
|
||||
"Column {letters}" => "Столбец {letters}",
|
||||
"Smallest to Largest" => "От наименьшего к наибольшему",
|
||||
"Largest to Smallest" => "От наибольшего к наименьшему",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Закройте диалоговое окно «Сортировка», прежде чем переключать или изменять листы."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Вернитесь на исходный лист, чтобы выполнить сортировку, или отмените действие.",
|
||||
"Numerical Count" => "Количество чисел",
|
||||
"Minimum" => "Минимум",
|
||||
"Maximum" => "Максимум",
|
||||
|
||||
@@ -481,6 +481,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Prikaži",
|
||||
"Collapse dialog" => "Skupi dijalog",
|
||||
"Expand dialog" => "Proširi dijalog",
|
||||
"My list has headers" => "Moji podaci imaju zaglavlja",
|
||||
"Sort by" => "Sortiraj po",
|
||||
"Then by" => "Zatim po",
|
||||
"Cell Values" => "Vrednosti ćelija",
|
||||
"Cell Color" => "Boja ćelije",
|
||||
"A to Z" => "Od A do Z",
|
||||
"Z to A" => "Od Z do A",
|
||||
"Add Level" => "Dodaj nivo",
|
||||
"Delete Level" => "Izbriši nivo",
|
||||
"Copy Level" => "Kopiraj nivo",
|
||||
"Move Up" => "Pomeri nagore",
|
||||
"Move Down" => "Pomeri nadole",
|
||||
"Order" => "Redosled",
|
||||
"Sort On" => "Sortiraj po",
|
||||
"Sort|Column" => "Kolona",
|
||||
"Column {letters}" => "Kolona {letters}",
|
||||
"Smallest to Largest" => "Od najmanjeg do najvećeg",
|
||||
"Largest to Smallest" => "Od najvećeg do najmanjeg",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Zatvorite dijalog Sortiranje pre nego što promenite ili izmenite radne listove."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Vratite se na prvobitni radni list da biste sortirali, ili otkažite.",
|
||||
"Numerical Count" => "Broj numeričkih vrednosti",
|
||||
"Minimum" => "Minimum",
|
||||
"Maximum" => "Maksimum",
|
||||
|
||||
@@ -451,6 +451,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Göster",
|
||||
"Collapse dialog" => "İletişim kutusunu daralt",
|
||||
"Expand dialog" => "İletişim kutusunu genişlet",
|
||||
"My list has headers" => "Verilerimde üst bilgi var",
|
||||
"Sort by" => "Sıralama ölçütü",
|
||||
"Then by" => "Sonra",
|
||||
"Cell Values" => "Hücre Değerleri",
|
||||
"Cell Color" => "Hücre Rengi",
|
||||
"A to Z" => "A'dan Z'ye",
|
||||
"Z to A" => "Z'den A'ya",
|
||||
"Add Level" => "Düzey Ekle",
|
||||
"Delete Level" => "Düzeyi Sil",
|
||||
"Copy Level" => "Düzeyi Kopyala",
|
||||
"Move Up" => "Yukarı Taşı",
|
||||
"Move Down" => "Aşağı Taşı",
|
||||
"Order" => "Sıra",
|
||||
"Sort On" => "Sıralama Ölçütü",
|
||||
"Sort|Column" => "Sütun",
|
||||
"Column {letters}" => "Sütun {letters}",
|
||||
"Smallest to Largest" => "En Küçükten En Büyüğe",
|
||||
"Largest to Smallest" => "En Büyükten En Küçüğe",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Çalışma sayfaları arasında geçiş yapmadan veya sayfaları değiştirmeden önce Sırala iletişim kutusunu kapatın."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Sıralamak için özgün çalışma sayfasına dönün veya iptal edin.",
|
||||
"Numerical Count" => "Sayısal Sayım",
|
||||
"Minimum" => "En Küçük",
|
||||
"Maximum" => "En Büyük",
|
||||
|
||||
@@ -757,14 +757,28 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"{count} cell(s) found" => "{count} cell(s) found",
|
||||
"Reference:" => "Reference:",
|
||||
"Special…" => "Special…",
|
||||
"My list has headers" => "My list has headers",
|
||||
"Sort by" => "Sort by",
|
||||
"Then by" => "Then by",
|
||||
"Cell Values" => "Cell Values",
|
||||
"Cell Color" => "Cell Color",
|
||||
"A to Z" => "A to Z",
|
||||
"Z to A" => "Z to A",
|
||||
"+ Add Level" => "+ Add Level",
|
||||
"My list has headers" => "Мої дані містять заголовки",
|
||||
"Sort by" => "Сортувати за",
|
||||
"Then by" => "Потім за",
|
||||
"Cell Values" => "Значення клітинок",
|
||||
"Cell Color" => "Колір клітинки",
|
||||
"A to Z" => "Від А до Я",
|
||||
"Z to A" => "Від Я до А",
|
||||
"Add Level" => "Додати рівень",
|
||||
"Delete Level" => "Видалити рівень",
|
||||
"Copy Level" => "Копіювати рівень",
|
||||
"Move Up" => "Вгору",
|
||||
"Move Down" => "Вниз",
|
||||
"Order" => "Порядок",
|
||||
"Sort On" => "Сортування",
|
||||
"Sort|Column" => "Стовпець",
|
||||
"Column {letters}" => "Стовпець {letters}",
|
||||
"Smallest to Largest" => "Від найменшого до найбільшого",
|
||||
"Largest to Smallest" => "Від найбільшого до найменшого",
|
||||
"Close the Sort dialog before switching or changing worksheets." => {
|
||||
"Закрийте діалогове вікно «Сортування», перш ніж перемикати або змінювати аркуші."
|
||||
}
|
||||
"Return to the original worksheet to sort, or cancel." => "Поверніться на вихідний аркуш, щоб виконати сортування, або скасуйте дію.",
|
||||
"New…" => "New…",
|
||||
"Edit…" => "Edit…",
|
||||
"Name" => "Name",
|
||||
|
||||
@@ -451,6 +451,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "Hiện",
|
||||
"Collapse dialog" => "Thu gọn hộp thoại",
|
||||
"Expand dialog" => "Mở rộng hộp thoại",
|
||||
"My list has headers" => "Dữ liệu của tôi có tiêu đề",
|
||||
"Sort by" => "Sắp xếp theo",
|
||||
"Then by" => "Sau đó theo",
|
||||
"Cell Values" => "Giá trị ô",
|
||||
"Cell Color" => "Màu ô",
|
||||
"A to Z" => "A đến Z",
|
||||
"Z to A" => "Z đến A",
|
||||
"Add Level" => "Thêm cấp",
|
||||
"Delete Level" => "Xóa cấp",
|
||||
"Copy Level" => "Sao chép cấp",
|
||||
"Move Up" => "Di chuyển lên",
|
||||
"Move Down" => "Di chuyển xuống",
|
||||
"Order" => "Thứ tự",
|
||||
"Sort On" => "Sắp xếp theo",
|
||||
"Sort|Column" => "Cột",
|
||||
"Column {letters}" => "Cột {letters}",
|
||||
"Smallest to Largest" => "Nhỏ nhất đến lớn nhất",
|
||||
"Largest to Smallest" => "Lớn nhất đến nhỏ nhất",
|
||||
"Close the Sort dialog before switching or changing worksheets." => "Hãy đóng hộp thoại Sắp xếp trước khi chuyển hoặc thay đổi trang tính.",
|
||||
"Return to the original worksheet to sort, or cancel." => "Hãy quay lại trang tính ban đầu để sắp xếp, hoặc hủy.",
|
||||
"Numerical Count" => "Số đếm số",
|
||||
"Minimum" => "Tối thiểu",
|
||||
"Maximum" => "Tối đa",
|
||||
|
||||
@@ -482,6 +482,26 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
|
||||
"Show" => "显示",
|
||||
"Collapse dialog" => "折叠对话框",
|
||||
"Expand dialog" => "展开对话框",
|
||||
"My list has headers" => "数据包含标题",
|
||||
"Sort by" => "主要关键字",
|
||||
"Then by" => "次要关键字",
|
||||
"Cell Values" => "单元格值",
|
||||
"Cell Color" => "单元格颜色",
|
||||
"A to Z" => "A 到 Z",
|
||||
"Z to A" => "Z 到 A",
|
||||
"Add Level" => "添加条件",
|
||||
"Delete Level" => "删除条件",
|
||||
"Copy Level" => "复制条件",
|
||||
"Move Up" => "上移",
|
||||
"Move Down" => "下移",
|
||||
"Order" => "次序",
|
||||
"Sort On" => "排序依据",
|
||||
"Sort|Column" => "列",
|
||||
"Column {letters}" => "列 {letters}",
|
||||
"Smallest to Largest" => "从小到大",
|
||||
"Largest to Smallest" => "从大到小",
|
||||
"Close the Sort dialog before switching or changing worksheets." => "切换或更改工作表之前,请先关闭“排序”对话框。",
|
||||
"Return to the original worksheet to sort, or cancel." => "请返回原工作表后再排序,或取消。",
|
||||
"Numerical Count" => "数值计数",
|
||||
"Minimum" => "最小值",
|
||||
"Maximum" => "最大值",
|
||||
|
||||
@@ -55,14 +55,54 @@ fn borders(preset: &str) -> Shortcut {
|
||||
Shortcut::Run("home.borders", json!({"preset": preset}))
|
||||
}
|
||||
|
||||
/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US
|
||||
/// layout (as Excel matches Ctrl+Shift+4 rather than the `$` character); `mac` selects the Excel
|
||||
/// for Mac variants where they differ. Navigation keys go by the logical key: with Num Lock off
|
||||
/// the numpad's arrows and Page Down report the digit keys (Num6, Num3) as their physical keys.
|
||||
pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Option<Shortcut> {
|
||||
/// Navigation keys go by the logical key: with Num Lock off the numpad's arrows and Page Down
|
||||
/// report the digit keys (Num6, Num3) as their physical keys.
|
||||
fn is_navigation(key: Key) -> bool {
|
||||
use Key::*;
|
||||
let navigation = matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete);
|
||||
let key = if navigation { key } else { physical.unwrap_or(key) };
|
||||
matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete)
|
||||
}
|
||||
|
||||
/// The US key and Shift state a symbol or digit key press stands for in the English shortcuts.
|
||||
/// Digits go by position (Ctrl+Shift+4 is the currency format wherever `$` is). Punctuation keys
|
||||
/// go by the character the layout types, as Excel does: Shift+, types `;` on a Croatian or German
|
||||
/// keyboard, so Ctrl+Shift+, is Ctrl+; (today's date) there, and a lone `+` is the US Shift+=.
|
||||
/// A character egui has no key for (`č`, `ö`, `<`) arrives as the key's position, which stands
|
||||
/// in. `None` for every other key (letters, navigation, function keys).
|
||||
pub fn us_key(key: Key, physical: Option<Key>, shift: bool) -> Option<(Key, bool)> {
|
||||
use Key::*;
|
||||
if is_navigation(key) {
|
||||
return None;
|
||||
}
|
||||
let at = physical?;
|
||||
let symbol =
|
||||
|k: Key| matches!(k, Backtick | Minus | Equals | OpenBracket | CloseBracket | Backslash | Semicolon | Quote | Comma | Period | Slash);
|
||||
match at {
|
||||
Num0 | Num1 | Num2 | Num3 | Num4 | Num5 | Num6 | Num7 | Num8 | Num9 => Some((at, shift)),
|
||||
_ if symbol(at) => Some(match key {
|
||||
// Characters a US keyboard types with Shift.
|
||||
Colon => (Semicolon, true),
|
||||
Plus => (Equals, true),
|
||||
Questionmark => (Slash, true),
|
||||
Pipe => (Backslash, true),
|
||||
OpenCurlyBracket => (OpenBracket, true),
|
||||
CloseCurlyBracket => (CloseBracket, true),
|
||||
// An unshifted US character, typed here with or without Shift.
|
||||
_ if key != at && symbol(key) => (key, false),
|
||||
_ => (key, shift),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US
|
||||
/// layout: digits and letters go by it, punctuation by the character typed ([`us_key`]). `mac`
|
||||
/// selects the Excel for Mac variants where they differ. Navigation keys go by the logical key.
|
||||
pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Option<Shortcut> {
|
||||
let (key, shift) = match us_key(key, physical, m.shift) {
|
||||
Some(us) => us,
|
||||
None if is_navigation(key) => (key, m.shift),
|
||||
None => (physical.unwrap_or(key), m.shift),
|
||||
};
|
||||
let ctx = LookupContext {
|
||||
key,
|
||||
modifiers: m,
|
||||
@@ -71,7 +111,7 @@ pub fn lookup(key: Key, physical: Option<Key>, m: Modifiers, mac: bool) -> Optio
|
||||
alt: m.alt && !m.ctrl && !m.command,
|
||||
ctrl_alt: m.alt && (m.ctrl || m.command),
|
||||
plain: !m.ctrl && !m.command && !m.alt,
|
||||
shift: m.shift,
|
||||
shift,
|
||||
mac,
|
||||
};
|
||||
lookup_number_formats(ctx)
|
||||
|
||||
@@ -27,36 +27,55 @@ pub(super) fn table_gallery(app: &mut SheetApp, ui: &mut Ui, cmd: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A style's gallery thumbnail: a 5x5 table (header row, banded rows) painted cell by cell from
|
||||
/// the same look the grid uses.
|
||||
pub(super) fn paint_table_swatch(ui: &Ui, r: Rect, wb: &gridcraft_engine::model::Workbook, style: &str) {
|
||||
let lk = gridcraft_engine::tables::look(style);
|
||||
let res = |c: Option<gridcraft_engine::model::Color>| c.and_then(|c| c.resolve(&wb.theme)).map(theme::color32);
|
||||
use egui::emath::GuiRounding;
|
||||
use gridcraft_engine::tables::{TableParts, cell_look, look};
|
||||
let lk = look(style);
|
||||
let parts = TableParts { header_row: true, totals_row: false, banded_rows: true, banded_cols: false, first_col: false, last_col: false };
|
||||
let res = |c: gridcraft_engine::model::Color| c.resolve(&wb.theme).map(theme::color32);
|
||||
let p = ui.painter();
|
||||
let t = Tokens::get(ui.ctx());
|
||||
p.rect_filled(r, 0.0, t.grid_bg);
|
||||
let rows = 5;
|
||||
let rh = r.height() / rows as f32;
|
||||
for i in 0..rows {
|
||||
let rr = Rect::from_min_size(pos2(r.left(), r.top() + i as f32 * rh), vec2(r.width(), rh));
|
||||
let fill = if i == 0 {
|
||||
res(lk.header_fill)
|
||||
} else if i % 2 == 1 {
|
||||
res(lk.band_fill)
|
||||
} else {
|
||||
res(lk.body_fill)
|
||||
};
|
||||
if let Some(f) = fill {
|
||||
p.rect_filled(rr, 0.0, f);
|
||||
}
|
||||
if let Some(l) = res(lk.line) {
|
||||
p.line_segment([rr.left_bottom(), rr.right_bottom()], Stroke::new(1.0, l));
|
||||
}
|
||||
for k in 0..3 {
|
||||
let x = rr.left() + 4.0 + k as f32 * (r.width() - 8.0) / 3.0;
|
||||
let col = if i == 0 { res(Some(lk.header_font)).unwrap_or(t.cell_text) } else { t.sheet_control_border };
|
||||
p.line_segment([pos2(x, rr.center().y), pos2(x + 10.0, rr.center().y)], Stroke::new(1.0, col));
|
||||
let line = |l: gridcraft_engine::model::BorderLine| if l.is_none() { None } else { Some(res(l.color).unwrap_or(t.cell_text)) };
|
||||
let n = 5u32;
|
||||
let (cw, rh) = (r.width() / n as f32, r.height() / n as f32);
|
||||
// Cell edges on whole pixels keep the lines crisp and the rows evenly spaced.
|
||||
let ppp = ui.pixels_per_point();
|
||||
let at = |start: f32, size: f32, k: u32| (start + size * k as f32).round_to_pixels(ppp);
|
||||
for row in 0..n {
|
||||
for col in 0..n {
|
||||
let (x0, x1) = (at(r.left(), cw, col), at(r.left(), cw, col + 1));
|
||||
let cr = Rect::from_min_max(pos2(x0, at(r.top(), rh, row)), pos2(x1, at(r.top(), rh, row + 1)));
|
||||
let cl = cell_look(&lk, parts, row, col, n, n);
|
||||
if let Some(f) = cl.fill.and_then(res) {
|
||||
p.rect_filled(cr, 0.0, f);
|
||||
}
|
||||
let b = cl.borders;
|
||||
// Excel centres the dash in the space inside the cell's own lines, across about half of it.
|
||||
let inset = |l: gridcraft_engine::model::BorderLine| if l.is_none() { 0.0 } else { 1.0 };
|
||||
let inner = Rect::from_min_max(
|
||||
pos2(cr.left() + inset(b.left), cr.top() + inset(b.top)),
|
||||
pos2(cr.right() - inset(b.right), cr.bottom() - inset(b.bottom)),
|
||||
);
|
||||
// When the gap can't split evenly, Excel puts the spare pixel below the dash.
|
||||
let top = ((inner.center().y - 0.5) * ppp).floor() / ppp;
|
||||
let (mid, half) = (inner.center().x, cw * 0.26);
|
||||
let dash = Rect::from_min_max(pos2((mid - half).round_to_pixels(ppp), top), pos2((mid + half).round_to_pixels(ppp), top + 1.0));
|
||||
p.rect_filled(dash, 0.0, res(cl.font).unwrap_or(t.cell_text));
|
||||
for (side, edge) in [
|
||||
(b.top, Rect::from_min_max(cr.left_top(), pos2(cr.right(), cr.top() + 1.0))),
|
||||
(b.bottom, Rect::from_min_max(pos2(cr.left(), cr.bottom() - 1.0), cr.right_bottom())),
|
||||
(b.left, Rect::from_min_max(cr.left_top(), pos2(cr.left() + 1.0, cr.bottom()))),
|
||||
(b.right, Rect::from_min_max(pos2(cr.right() - 1.0, cr.top()), cr.right_bottom())),
|
||||
] {
|
||||
if let Some(c) = line(side) {
|
||||
p.rect_filled(edge, 0.0, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
pub(super) fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) {
|
||||
|
||||
@@ -70,7 +70,8 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) {
|
||||
None
|
||||
}
|
||||
},
|
||||
Key::Semicolon => {
|
||||
// Ctrl+Shift+; (the time) is in `keymap::lookup`; Cmd+Shift+; on a Mac does nothing.
|
||||
Key::Semicolon if !shift => {
|
||||
// Insert today's date.
|
||||
let text = app
|
||||
.session
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Space on a checkbox cell toggles it and nothing else (#1951).
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton};
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use gridcraft_engine::core::Value;
|
||||
use gridcraft_ui_egui::{SheetApp, grid::Geo};
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
fn harness(session: Session) -> Harness {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
/// A space, as a keyboard reports it: the key press, the text it produces, then the release.
|
||||
fn space(h: &mut Harness) {
|
||||
let k = |pressed| Event::Key { key: Key::Space, physical_key: Some(Key::Space), pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
h.input_mut().events.push(k(true));
|
||||
h.input_mut().events.push(Event::Text(" ".into()));
|
||||
h.input_mut().events.push(k(false));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn press(h: &mut Harness, key: Key) {
|
||||
let k = |pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
h.input_mut().events.push(k(true));
|
||||
h.input_mut().events.push(k(false));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn value(h: &Harness, a1: &str) -> Option<Value> {
|
||||
let d = h.state().session.active().unwrap();
|
||||
d.wb.active().unwrap().cell(CellRef::parse(a1).unwrap()).map(|c| c.value.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_toggles_a_checkbox_cell_without_editing_it() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "B2", "input": "FALSE"})).unwrap();
|
||||
s.execute("insert.checkbox", json!({"range": "B2"})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
let mut h = harness(s);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(false)));
|
||||
|
||||
// The key press toggles the box; the text it also produces must not start editing, or Enter
|
||||
// commits that space over the checkbox and leaves the cell blank.
|
||||
space(&mut h);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)));
|
||||
assert!(h.state().editor.is_none(), "no editor opened");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "Enter moved on and left the checkbox");
|
||||
|
||||
// And again, back to unchecked. Reached without clicking the box, since a click on the box
|
||||
// toggles it in its own right (below): an ordinary cell, then across to it.
|
||||
click_cell(&mut h, "D2");
|
||||
press(&mut h, Key::ArrowLeft);
|
||||
press(&mut h, Key::ArrowLeft);
|
||||
assert_eq!(active(&h), "B2", "the arrows walked back to the checkbox");
|
||||
space(&mut h);
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(false)));
|
||||
assert!(h.state().editor.is_none());
|
||||
|
||||
// A click on the box toggles it too, which is what the pointer path does with a checkbox
|
||||
// cell and the reason the walk above avoids it.
|
||||
click_cell(&mut h, "B2");
|
||||
assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "the click toggled the box");
|
||||
assert!(h.state().editor.is_none(), "no editor opened");
|
||||
|
||||
// A space still types on an ordinary cell.
|
||||
click_cell(&mut h, "C3");
|
||||
space(&mut h);
|
||||
assert!(h.state().editor.is_some(), "an ordinary cell starts editing");
|
||||
press(&mut h, Key::Escape);
|
||||
}
|
||||
|
||||
/// Click a cell, as a person selects one: the grid's own geometry gives where it is, so the
|
||||
/// click goes through hit-testing and whatever the grid does with focus, rather than the
|
||||
/// selection being set behind the app's back once it is running (#1960 review).
|
||||
fn click_cell(h: &mut Harness, cell: &str) {
|
||||
let pos = {
|
||||
let app = h.state();
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap();
|
||||
let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll);
|
||||
geo.cell_rect(sheet, CellRef::parse(cell).unwrap()).center()
|
||||
};
|
||||
h.input_mut().events.extend([
|
||||
Event::PointerMoved(pos),
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
h.run_steps(2);
|
||||
// The click has to have landed: a selection that did not move would leave each assertion
|
||||
// after it testing the cell before it instead.
|
||||
assert_eq!(active(h), cell, "the click selected {cell}");
|
||||
}
|
||||
|
||||
/// The active cell, in A1 form.
|
||||
fn active(h: &Harness) -> String {
|
||||
h.state().session.active().unwrap().selection.active.to_string()
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! #4389 and #4390: a selected chart outlines its data in the sheet (series names red, category
|
||||
//! labels purple, values blue), and dragging a corner of the values outline changes what the
|
||||
//! chart plots, through real pointer input.
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Shape, vec2};
|
||||
use gridcraft_engine::core::RangeRef;
|
||||
use gridcraft_ui_egui::theme::Tokens;
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, gridcraft_ui_egui::SheetApp>;
|
||||
|
||||
/// 10..50 down A1:A5 and 5s below them, charted from A1:A5, which stays the cell selection as
|
||||
/// after Insert › Chart, so the fill handle sits on the outline's bottom-right corner.
|
||||
fn fixture() -> (Harness, u32) {
|
||||
let mut session = crate::support::blank_session();
|
||||
let values: Vec<_> = [10, 20, 30, 40, 50, 5, 5, 5].iter().map(|v| json!([v])).collect();
|
||||
session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
|
||||
session.execute("selection.set", json!({"range": "A1:A5"})).unwrap();
|
||||
let chart = session.execute("insert.chart", json!({"type": "column", "at": "D3", "width": 300, "height": 200})).unwrap();
|
||||
let id = chart["chart"].as_u64().unwrap() as u32;
|
||||
let mut h = crate::support::stepped_harness(session);
|
||||
h.state_mut().select_object_id(Some(id));
|
||||
h.run_steps(2);
|
||||
(h, id)
|
||||
}
|
||||
|
||||
fn values(h: &Harness) -> String {
|
||||
h.state().session.doc().unwrap().wb.active().unwrap().charts[0].series[0].values.clone()
|
||||
}
|
||||
|
||||
/// On-screen rect of `range`.
|
||||
fn rect(h: &Harness, range: &str) -> egui::Rect {
|
||||
let app = h.state();
|
||||
let sh = app.session.doc().unwrap().wb.active().unwrap();
|
||||
app.grid.geo.as_ref().unwrap().range_rect(sh, RangeRef::parse(range).unwrap())
|
||||
}
|
||||
|
||||
fn hover(h: &mut Harness, at: Pos2) {
|
||||
h.input_mut().events.push(Event::PointerMoved(at));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn button(h: &mut Harness, at: Pos2, pressed: bool) {
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// Presses at `from` and moves to `to` in small steps, leaving the button down.
|
||||
fn press_and_move(h: &mut Harness, from: Pos2, to: Pos2) {
|
||||
hover(h, from);
|
||||
button(h, from, true);
|
||||
press_and_move_on(h, from, to);
|
||||
}
|
||||
|
||||
/// With the button already down, moves from `from` to `to` in small steps.
|
||||
fn press_and_move_on(h: &mut Harness, from: Pos2, to: Pos2) {
|
||||
for i in 1..=8 {
|
||||
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (i as f32 / 8.0)));
|
||||
h.run_steps(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_values_corner_extends_the_chart_data() {
|
||||
let (mut h, id) = fixture();
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
|
||||
let corner = rect(&h, "A1:A5").right_bottom();
|
||||
hover(&mut h, corner);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeNwSe, "the corner shows a resize cursor, not the fill cross");
|
||||
// Three rows down from the corner, as the hand moves it.
|
||||
let target = rect(&h, "A8").right_bottom();
|
||||
press_and_move(&mut h, corner, target);
|
||||
// The outline previews the new block while the button is held; the chart is unchanged.
|
||||
let blue = Tokens::get(&h.ctx).ref_color(0, true);
|
||||
let preview = rect(&h, "A1:A8");
|
||||
let previewed = h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == preview && r.stroke.color == blue));
|
||||
assert!(previewed, "the outline follows the pointer");
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
|
||||
button(&mut h, target, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$8", "the chart plots the dragged block");
|
||||
assert_eq!(h.state().selected_chart(), Some(id), "the chart stays selected");
|
||||
let a6 = h.state().session.doc().unwrap().wb.active().unwrap().value(gridcraft_engine::core::CellRef::parse("A6").unwrap());
|
||||
assert_eq!(a6, gridcraft_engine::core::Value::number(5.0), "the press did not drag the fill handle");
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "one undo step puts the block back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_top_corner_down_shrinks_the_chart_data() {
|
||||
let (mut h, _) = fixture();
|
||||
let corner = rect(&h, "A1:A5").left_top() + vec2(1.0, 1.0);
|
||||
let target = rect(&h, "A3").left_top() + vec2(1.0, 1.0);
|
||||
press_and_move(&mut h, corner, target);
|
||||
button(&mut h, target, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$3:$A$5");
|
||||
}
|
||||
|
||||
/// #4391 review: a corner lies on the boundary of the next row and column, so reading the pointer
|
||||
/// as is put a press on the bottom-right corner of A1:A5 in B6.
|
||||
#[test]
|
||||
fn a_drag_back_to_the_grabbed_corner_or_along_its_edge_keeps_the_other_axis() {
|
||||
// Away and back to the very point pressed: nothing changes.
|
||||
let (mut h, _) = fixture();
|
||||
let corner = rect(&h, "A1:A5").right_bottom();
|
||||
press_and_move(&mut h, corner, corner + vec2(40.0, 30.0));
|
||||
press_and_move_on(&mut h, corner + vec2(40.0, 30.0), corner);
|
||||
button(&mut h, corner, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "a release where the press was leaves the data alone");
|
||||
// Straight down the right edge of column A: rows only, no column B.
|
||||
let (mut h, _) = fixture();
|
||||
let corner = rect(&h, "A1:A5").right_bottom();
|
||||
let target = rect(&h, "A6").right_bottom();
|
||||
press_and_move(&mut h, corner, target);
|
||||
button(&mut h, target, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$6");
|
||||
}
|
||||
|
||||
/// #4391 review: the drag read the pointer from the middle of the grabbed row, so with a tall
|
||||
/// row 5 the pointer could reach the bottom of a short row 6 and the block stayed at A1:A5.
|
||||
#[test]
|
||||
fn a_drag_past_rows_of_unequal_height_follows_the_rows_under_the_pointer() {
|
||||
let (mut h, _) = fixture();
|
||||
h.state_mut().run("home.rowHeight", json!({"rows": "5:5", "height": 120})).unwrap();
|
||||
h.run_steps(2);
|
||||
let corner = rect(&h, "A1:A5").right_bottom();
|
||||
let row6 = rect(&h, "A6");
|
||||
assert!(rect(&h, "A5").height() > 3.0 * row6.height(), "row 5 is much taller than row 6");
|
||||
// Short of the middle of row 6 the edge stays on row 5's bottom gridline.
|
||||
let short = corner + vec2(0.0, row6.height() * 0.4);
|
||||
press_and_move(&mut h, corner, short);
|
||||
assert!(values_outline_at(&h, "A1:A5"));
|
||||
// At the bottom of row 6 the block takes row 6, in the preview and on release.
|
||||
let target = row6.right_bottom();
|
||||
press_and_move_on(&mut h, short, target);
|
||||
assert!(values_outline_at(&h, "A1:A6"), "the preview takes row 6");
|
||||
button(&mut h, target, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$6");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_cancels_a_values_drag() {
|
||||
let (mut h, _) = fixture();
|
||||
let corner = rect(&h, "A1:A5").right_bottom();
|
||||
let target = rect(&h, "A8").right_bottom();
|
||||
press_and_move(&mut h, corner, target);
|
||||
h.key_press(Key::Escape);
|
||||
h.run_steps(2);
|
||||
button(&mut h, target, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
|
||||
}
|
||||
|
||||
/// Whether the last frame stroked `range` in the values blue.
|
||||
fn values_outline_at(h: &Harness, range: &str) -> bool {
|
||||
let blue = Tokens::get(&h.ctx).ref_color(0, true);
|
||||
let want = rect(h, range);
|
||||
h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == blue))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_in_the_same_frame_as_the_last_move_takes_the_release_position() {
|
||||
let (mut h, _) = fixture();
|
||||
let (corner, a6, end) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A6").right_bottom(), rect(&h, "A8").right_bottom());
|
||||
press_and_move(&mut h, corner, a6);
|
||||
// The pointer reaches A8 and the button goes up within one frame.
|
||||
h.input_mut().events.push(Event::PointerMoved(end));
|
||||
h.input_mut().events.push(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$8");
|
||||
}
|
||||
|
||||
/// A command that changes the chart's data while the button is held (the control channel runs
|
||||
/// between frames) makes the drag stale: releasing must not put the dragged block over it,
|
||||
/// whether the pointer moves on first or is released straight away.
|
||||
#[test]
|
||||
fn a_chart_data_change_during_the_drag_is_not_overwritten_by_the_release() {
|
||||
for move_on in [true, false] {
|
||||
let (mut h, id) = fixture();
|
||||
let (corner, a7, a8) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A7").right_bottom(), rect(&h, "A8").right_bottom());
|
||||
press_and_move(&mut h, corner, a7);
|
||||
h.state_mut().session.execute("chart.setValuesRange", json!({"chart": id, "range": "A2:A4"})).unwrap();
|
||||
if move_on {
|
||||
press_and_move_on(&mut h, a7, a8);
|
||||
}
|
||||
button(&mut h, if move_on { a8 } else { a7 }, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$2:$A$4", "the newer data stays (pointer moved on: {move_on})");
|
||||
assert!(!values_outline_at(&h, "A1:A8") && !values_outline_at(&h, "A1:A7"), "no stale preview is left (pointer moved on: {move_on})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_with_ctrl_held_still_cancels_a_values_drag() {
|
||||
let (mut h, _) = fixture();
|
||||
let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom());
|
||||
press_and_move(&mut h, corner, target);
|
||||
h.input_mut().events.push(Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::CTRL });
|
||||
h.run_steps(2);
|
||||
button(&mut h, target, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_stays_while_the_drag_scrolls_the_chart_away() {
|
||||
let (mut h, _) = fixture();
|
||||
// Column A stays in a frozen pane while the chart in D:H scrolls off to the left.
|
||||
h.state_mut().run("view.freezePanes", json!({"cell": "B1"})).unwrap();
|
||||
h.run_steps(2);
|
||||
let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom());
|
||||
press_and_move(&mut h, corner, target);
|
||||
assert!(values_outline_at(&h, "A1:A8"));
|
||||
h.state_mut().view_mut().unwrap().scroll.x = 3000.0;
|
||||
h.run_steps(2);
|
||||
assert!(values_outline_at(&h, "A1:A8"), "the dragged block is still previewed");
|
||||
button(&mut h, target, false);
|
||||
assert_eq!(values(&h), "Sheet1!$A$1:$A$8");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corner_hidden_under_frozen_rows_cannot_be_grabbed() {
|
||||
let mut session = crate::support::blank_session();
|
||||
let values: Vec<_> = (1..=12).map(|v| json!([v])).collect();
|
||||
session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap();
|
||||
session.execute("selection.set", json!({"range": "A5:A8"})).unwrap();
|
||||
let chart = session.execute("insert.chart", json!({"type": "column", "at": "D2", "width": 300, "height": 200})).unwrap();
|
||||
session.execute("view.freezePanes", json!({"cell": "A4"})).unwrap();
|
||||
let mut h = crate::support::stepped_harness(session);
|
||||
h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32));
|
||||
// Scroll two rows, so the top of row 5 lies under the frozen rows 1-3.
|
||||
let two_rows = {
|
||||
let sh = h.state().session.doc().unwrap().wb.active().unwrap().clone();
|
||||
(sh.row_top(5) - sh.row_top(3)) as f32
|
||||
};
|
||||
h.state_mut().view_mut().unwrap().scroll.y = two_rows;
|
||||
h.run_steps(2);
|
||||
let app = h.state();
|
||||
let sh = app.session.doc().unwrap().wb.active().unwrap();
|
||||
let geo = app.grid.geo.as_ref().unwrap();
|
||||
let block = geo.range_rect(sh, RangeRef::parse("A5:A8").unwrap());
|
||||
let hidden = block.left_top();
|
||||
let frozen_bottom = geo.y(sh, 2) + sh.row_height(2) as f32 * geo.z;
|
||||
assert!(geo.cells.contains(hidden) && hidden.y + 4.0 < frozen_bottom, "the top corner lies over the frozen rows: {hidden:?} {frozen_bottom}");
|
||||
assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, hidden).is_none(), "a hidden corner is not a handle");
|
||||
assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, block.right_bottom()).is_some(), "a visible corner still is");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_chart_outlines_names_categories_and_values_in_their_colours() {
|
||||
let mut session = crate::support::blank_session();
|
||||
session
|
||||
.execute("range.setValues", json!({"range": "A1", "values": [["", "North", "South"], ["Q1", 10, 15], ["Q2", 20, 25], ["Q3", 30, 35]]}))
|
||||
.unwrap();
|
||||
session.execute("selection.set", json!({"range": "A1:C4"})).unwrap();
|
||||
let chart = session.execute("insert.chart", json!({"type": "column", "at": "F2", "width": 300, "height": 200})).unwrap();
|
||||
let mut h = crate::support::stepped_harness(session);
|
||||
h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32));
|
||||
h.run_steps(2);
|
||||
let t = Tokens::get(&h.ctx);
|
||||
let stroked = |h: &Harness, range: &str, color: egui::Color32| {
|
||||
let want = rect(h, range);
|
||||
h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == color && r.stroke.width == 1.5))
|
||||
};
|
||||
assert!(stroked(&h, "B1:C1", t.ref_color(1, true)), "series names in red");
|
||||
assert!(stroked(&h, "A2:A4", t.ref_color(2, true)), "category labels in purple");
|
||||
assert!(stroked(&h, "B2:C4", t.ref_color(0, true)), "the values as one blue block");
|
||||
assert!(!stroked(&h, "B2:B4", t.ref_color(0, true)), "not one outline per series");
|
||||
}
|
||||
@@ -166,6 +166,56 @@ fn save_actions_include_the_cell_draft_and_close_keeps_the_unsaved_prompt() {
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0));
|
||||
}
|
||||
|
||||
/// Where the title bar's icon button for `name` is. Its icon has no text, so it is found by
|
||||
/// hovering along the title bar until its tooltip ("Save (⌘S)") shows.
|
||||
fn title_bar_button(h: &mut egui_kittest::Harness<'static, SheetApp>, name: &str) -> egui::Pos2 {
|
||||
let autosave = h.get_by_label("AutoSave").rect();
|
||||
let tip = format!("{name} (");
|
||||
let mut x = autosave.right();
|
||||
while x < autosave.right() + 300.0 {
|
||||
let at = egui::pos2(x, autosave.center().y);
|
||||
h.hover_at(at);
|
||||
h.run_steps(3);
|
||||
// The button's accessible label carries its tooltip, so the node found may be the button
|
||||
// itself rather than a tooltip at the pointer: aim at the node.
|
||||
if let Some(node) = h.query_by_label_contains(&tip) {
|
||||
return node.rect().center();
|
||||
}
|
||||
x += 6.0;
|
||||
}
|
||||
panic!("no title bar button shows a {tip:?} tooltip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_title_bar_save_button_saves_the_cell_being_typed() {
|
||||
// Regression test for #223: the title bar's Save button saved the file without the cell the
|
||||
// user was still typing in.
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-title-bar-save-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Book.xlsx").to_string_lossy().into_owned();
|
||||
let mut h = harness(Services::default());
|
||||
h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap();
|
||||
h.run_steps(2);
|
||||
h.input_mut().events.push(egui::Event::Text("123".into()));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_some());
|
||||
let save = title_bar_button(&mut h, "Save");
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(egui::Event::PointerButton {
|
||||
pos: save,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_none(), "Save commits the cell draft");
|
||||
let (wb, _) = gridcraft_engine::io::open_bytes("Book.xlsx", &std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0), "the saved file has the typed value");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Options opens, named Backstage pages are reachable and accessible, an invalid page errors, and both close and Back leave Backstage.
|
||||
fn file_options_opens_the_options_page_and_pages_are_reachable_by_command() {
|
||||
|
||||
@@ -287,7 +287,12 @@ fn table_filter_autofit_works_through_command_and_header_double_click() {
|
||||
let rect = geo.cell_rect(sheet, cell);
|
||||
let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell);
|
||||
let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell));
|
||||
let text_width = gridcraft_engine::cmd::format::approx_text_width("Quarterly Revenue", style.font.size, style.font.bold) * geo.z;
|
||||
// Measured as AutoFit measured it, with the app's fonts (they differ from machine to
|
||||
// machine). The app installs them before AutoFit runs; AutoFit without them, on the
|
||||
// engine's estimate, is `autofit_filter_buttons` in the engine's tests.
|
||||
let measure = app.session.text_width.as_ref().expect("the app measures text with its fonts");
|
||||
let measured = measure("Quarterly Revenue", &style.font, true);
|
||||
let text_width = measured * geo.z;
|
||||
assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}");
|
||||
assert_eq!(app.session.active().unwrap().undo.len(), 1);
|
||||
h.state_mut().session.execute("edit.undo", json!({})).unwrap();
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! IME composition at the grid level.
|
||||
//!
|
||||
//! With a CJK input method, the first keystroke of a composition must reach the input method,
|
||||
//! not be written straight into the cell as raw text. The grid publishes `PlatformOutput::ime`
|
||||
//! on every frame it owns keyboard input, so the OS delivers `ImeEvent`s; a `Commit` opens the
|
||||
//! in-cell editor with the finished text. Plain ASCII keeps using `Event::Text` (no regression).
|
||||
|
||||
use egui::{Event, ImeEvent};
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use gridcraft_ui_egui::SheetApp;
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
/// A warmed harness over `session`, with the grid holding keyboard input on the active cell.
|
||||
///
|
||||
/// The suite pins a font set with no Han face, so the harness draws tofu for the CJK commit
|
||||
/// text: these tests check input routing, not glyph coverage.
|
||||
fn fixture_with(session: Session) -> Harness {
|
||||
let builder = crate::common::builder().allow_missing_glyphs().with_size(egui::vec2(1200.0, 800.0));
|
||||
crate::common::harness_with(builder, crate::common::app(session), 4)
|
||||
}
|
||||
|
||||
/// A warmed harness over a blank workbook, with the grid holding keyboard input on `A1`.
|
||||
fn fixture() -> Harness {
|
||||
fixture_with(crate::support::blank_session())
|
||||
}
|
||||
|
||||
/// A protected sheet with `active` selected, optionally unlocking one cell first.
|
||||
fn protected_session(active: &str, unlock: Option<&str>) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
if let Some(cell) = unlock {
|
||||
s.execute("home.formatCells", json!({"range": cell, "style": {"protection": {"locked": false}}})).unwrap();
|
||||
}
|
||||
s.execute("review.protectSheet", json!({})).unwrap();
|
||||
s.execute("selection.set", json!({"cell": active})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The text the in-cell editor currently holds, or `None` when no editor is open.
|
||||
fn editor_text(h: &Harness) -> Option<String> {
|
||||
h.state().editor.as_ref().map(|ed| ed.text.clone())
|
||||
}
|
||||
|
||||
/// The grid must request IME on every frame it owns keyboard input: winit applies
|
||||
/// `set_ime_allowed` at the end of the frame, so requesting it in response to the first key is
|
||||
/// already too late. The commit tests below only exercise the event handler and would still
|
||||
/// pass with `request_grid_ime` removed, so this asserts the actual fix.
|
||||
#[test]
|
||||
fn grid_publishes_ime_request_before_the_first_keystroke() {
|
||||
let mut h = fixture();
|
||||
h.run_steps(1);
|
||||
let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME");
|
||||
assert!(matches!(ime.purpose, egui::IMEPurpose::Normal), "cell text is ordinary input");
|
||||
assert!(ime.rect.width() > 0.0 && ime.rect.height() > 0.0, "the IME rect must cover the active cell");
|
||||
assert_eq!(ime.cursor_rect.min, ime.rect.min, "the caret sits at the cell's start");
|
||||
assert!(ime.context_generation > 0, "egui 0.37 needs a non-zero IME context generation");
|
||||
}
|
||||
|
||||
/// When a dialog takes the keyboard, `PlatformOutput` must stop advertising a grid IME owner.
|
||||
/// The output is rebuilt each frame, so an early return is what turns IME off.
|
||||
#[test]
|
||||
fn grid_withholds_ime_request_when_it_does_not_own_keyboard_input() {
|
||||
let mut h = fixture();
|
||||
h.state_mut().message = Some(("GridCraft".into(), "busy".into()));
|
||||
h.run_steps(1);
|
||||
assert!(h.output().platform_output.ime.is_none(), "a message dialog must take IME ownership away from the grid");
|
||||
}
|
||||
|
||||
/// A locked cell on a protected sheet cannot be edited, so inviting a composition there would
|
||||
/// only produce text that `SheetApp::begin_edit` discards.
|
||||
#[test]
|
||||
fn locked_cell_on_a_protected_sheet_does_not_request_ime() {
|
||||
let mut h = fixture_with(protected_session("A1", None));
|
||||
h.run_steps(1);
|
||||
assert!(h.output().platform_output.ime.is_none(), "a composition on a locked cell is always refused");
|
||||
}
|
||||
|
||||
/// The protection guard must not disable IME for cells that are still editable.
|
||||
#[test]
|
||||
fn unlocked_cell_on_a_protected_sheet_still_requests_ime() {
|
||||
let mut h = fixture_with(protected_session("C2", Some("C2")));
|
||||
h.run_steps(1);
|
||||
assert!(h.output().platform_output.ime.is_some(), "unlocked cells stay editable on a protected sheet");
|
||||
}
|
||||
|
||||
/// `IMEOutput::rect` is in screen coordinates, while `Geo::cell_rect` is in logical ones; on a
|
||||
/// right-to-left sheet the two differ, and the candidate window must follow the drawn cell.
|
||||
#[test]
|
||||
fn right_to_left_sheet_publishes_mirrored_ime_rects() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("view.rightToLeft", json!({"on": true})).unwrap();
|
||||
s.execute("selection.set", json!({"cell": "B2"})).unwrap();
|
||||
let mut h = fixture_with(s);
|
||||
h.run_steps(1);
|
||||
|
||||
let geo = h.state().grid.geo.clone().expect("the grid has been drawn");
|
||||
let sheet = h.state().session.active().unwrap().wb.active().unwrap();
|
||||
let logical = geo.cell_rect(sheet, CellRef::parse("B2").unwrap());
|
||||
let expected = geo.mirror_rect(logical);
|
||||
assert!(geo.rtl, "the fixture must be right-to-left");
|
||||
assert!((expected.min.x - logical.min.x).abs() > 1.0, "the fixture must distinguish mirrored from logical x");
|
||||
|
||||
let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME");
|
||||
assert!((ime.rect.min.x - expected.min.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected);
|
||||
assert!((ime.rect.max.x - expected.max.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected);
|
||||
assert!((ime.cursor_rect.min.x - ime.rect.min.x).abs() < 0.01, "the caret must sit at the mirrored cell's start");
|
||||
}
|
||||
|
||||
/// A committed composition opens the editor with its text and leaves the caret after it.
|
||||
#[test]
|
||||
fn ime_commit_opens_editor_with_committed_text() {
|
||||
let mut h = fixture();
|
||||
h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into())));
|
||||
h.run_steps(2);
|
||||
let ed = h.state().editor.as_ref().expect("an IME commit must open the in-cell editor");
|
||||
assert_eq!(ed.text, "张", "the committed text should seed the editor");
|
||||
assert_eq!(ed.caret, ed.text.chars().count(), "the caret should sit after the committed text");
|
||||
}
|
||||
|
||||
/// A preedit is not text yet: it must not open the editor on its own, only the commit does.
|
||||
#[test]
|
||||
fn ime_preedit_does_not_seed_editor() {
|
||||
let mut h = fixture();
|
||||
h.input_mut().events.push(Event::Ime(ImeEvent::Preedit { text: "zh".into(), active_range_chars: Some(0..2) }));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_none(), "a preedit must not seed the editor on its own");
|
||||
h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into())));
|
||||
h.run_steps(2);
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("张"), "the commit after a preedit opens the editor");
|
||||
}
|
||||
|
||||
/// Plain ASCII never composes, so `Event::Text` still seeds the editor exactly as before.
|
||||
#[test]
|
||||
fn ascii_text_still_seeds_editor_no_regression() {
|
||||
let mut h = fixture();
|
||||
h.input_mut().events.push(Event::Text("abc".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("abc"), "ASCII typing must still seed the editor");
|
||||
}
|
||||
@@ -19,6 +19,30 @@ fn blank() -> Session {
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_formulas_ribbon_keeps_watch_window_inside_the_ribbon() {
|
||||
// Regression test for #360 (#342): Watch Window was a fourth small button in a column of
|
||||
// three, so it hung below the ribbon and was cut off.
|
||||
fn texts(shape: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts(s, out)),
|
||||
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut h = harness(blank());
|
||||
h.state_mut().ui.ribbon_tab = "Formulas".into();
|
||||
h.run_steps(3);
|
||||
// Ribbon button labels are painted text: find them among the frame's shapes.
|
||||
let mut painted = Vec::new();
|
||||
h.output().shapes.iter().for_each(|c| texts(&c.shape, &mut painted));
|
||||
let bottom_of = |word: &str| painted.iter().filter(|(s, _)| s.contains(word)).map(|(_, r)| r.bottom()).fold(f32::NEG_INFINITY, f32::max);
|
||||
// "Calculation Options" is a big button whose second line sits at the foot of the ribbon.
|
||||
let (watch, foot) = (bottom_of("Window"), bottom_of("Options"));
|
||||
assert!(watch.is_finite() && foot.is_finite(), "the Formulas ribbon paints Watch Window and Calculation Options");
|
||||
assert!(watch <= foot + 0.5, "Watch Window's label ends at y={watch}, below the ribbon's last label row (y={foot})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_scrollbar_pages_and_drags_without_changing_selection() {
|
||||
let mut h = harness(blank());
|
||||
@@ -312,6 +336,77 @@ fn arrows_escape_and_undo() {
|
||||
assert_eq!(value(&h, "B2"), Value::Empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_redo_reach_the_sheet_while_find_and_replace_is_open() {
|
||||
let mut h = harness(blank());
|
||||
for t in ["x1", "x2"] {
|
||||
text(&mut h, t);
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
}
|
||||
h.state_mut().open_dialog("find", json!({"replace": true}));
|
||||
h.run_steps(3);
|
||||
if let Some(d) = h.state_mut().dialog.as_mut() {
|
||||
d.values.insert("what".into(), json!("x"));
|
||||
d.values.insert("with".into(), json!("y"));
|
||||
}
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Replace All").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")));
|
||||
// Keyboard focus on a button must not reserve Undo/Redo for text editing.
|
||||
h.get_by_label("Replace All").focus();
|
||||
h.run_steps(2);
|
||||
assert!(h.ctx.egui_wants_keyboard_input());
|
||||
assert!(!h.ctx.text_edit_focused());
|
||||
key(&mut h, Key::Z, Modifiers::COMMAND);
|
||||
assert!(h.state().dialog.is_some(), "the dialog stays open");
|
||||
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("x1"), Value::from("x2")), "one Undo takes back the whole Replace All");
|
||||
key(&mut h, Key::Y, Modifiers::COMMAND);
|
||||
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")));
|
||||
// The Mac Redo shortcut works too, as it does on the sheet.
|
||||
key(&mut h, Key::Z, Modifiers::COMMAND);
|
||||
assert_eq!(value(&h, "A1"), Value::from("x1"));
|
||||
key(&mut h, Key::Z, Modifiers::COMMAND | Modifiers::SHIFT);
|
||||
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")));
|
||||
assert!(h.state().dialog.is_some(), "the dialog is still open");
|
||||
h.get_by_label("Find what:").focus();
|
||||
h.run_steps(2);
|
||||
assert!(h.ctx.text_edit_focused());
|
||||
let before = h.state().dialog.as_ref().unwrap().values.get("what").cloned();
|
||||
h.input_mut().events.push(Event::Text("extra".into()));
|
||||
h.run_steps(2);
|
||||
assert_ne!(h.state().dialog.as_ref().unwrap().values.get("what"), before.as_ref());
|
||||
key(&mut h, Key::Z, Modifiers::COMMAND);
|
||||
assert_eq!(h.state().dialog.as_ref().unwrap().values.get("what"), before.as_ref(), "Undo restores the Find field");
|
||||
assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")), "text-field Undo leaves the sheet alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_message_blocks_workbook_undo_and_redo() {
|
||||
let mut session = blank();
|
||||
session.execute("cell.set", json!({"cell": "A1", "input": "first"})).unwrap();
|
||||
session.execute("cell.set", json!({"cell": "A1", "input": "second"})).unwrap();
|
||||
session.execute("edit.undo", json!({})).unwrap();
|
||||
let mut h = harness(session);
|
||||
h.state_mut().open_dialog("find", json!({"replace": true}));
|
||||
h.run_steps(3);
|
||||
// An empty search raises the real modal error over Find and Replace.
|
||||
h.get_by_label("Replace All").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().message.is_some());
|
||||
assert!(!h.ctx.text_edit_focused());
|
||||
for (key_code, modifiers) in [(Key::Z, Modifiers::COMMAND), (Key::Y, Modifiers::COMMAND), (Key::Z, Modifiers::COMMAND | Modifiers::SHIFT)] {
|
||||
key(&mut h, key_code, modifiers);
|
||||
assert_eq!(value(&h, "A1"), Value::from("first"), "the message blocks workbook shortcuts");
|
||||
assert!(h.state().message.is_some());
|
||||
}
|
||||
h.state_mut().message = None;
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Replace All").focus();
|
||||
h.run_steps(2);
|
||||
key(&mut h, Key::Y, Modifiers::COMMAND);
|
||||
assert_eq!(value(&h, "A1"), Value::from("second"), "Redo works again after dismissing the message");
|
||||
}
|
||||
#[test]
|
||||
fn shift_arrows_in_point_mode_extend_from_the_pointed_cell() {
|
||||
let mut s = blank();
|
||||
|
||||
@@ -212,6 +212,144 @@ fn alt_down_only_opens_enabled_table_filter_buttons() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A key press as a non-US layout reports it: `typed` is the character the layout types (egui's
|
||||
/// logical key), `at` the key's position named after a US keyboard.
|
||||
fn key_on_layout(h: &mut Harness, typed: Key, at: Key, m: Modifiers) {
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m });
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn editor_text(h: &Harness) -> Option<String> {
|
||||
h.state().editor.as_ref().map(|e| e.text.clone())
|
||||
}
|
||||
|
||||
fn today(h: &Harness) -> String {
|
||||
let d = h.state().session.active().unwrap();
|
||||
let now = gridcraft_engine::core::date::serial_in_system(d.wb.date_system, gridcraft_engine::calc::now_serial());
|
||||
gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(now.floor()), "m/d/yyyy", &d.wb).text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_shortcuts_follow_the_character_the_layout_types() {
|
||||
// Croatian and German keyboards type `;` with Shift+, and `:` with Shift+. (US positions).
|
||||
// `+` is unshifted, on the US `=` key (Croatian) or `]` key (German); `'` is the US `-` key
|
||||
// (Croatian) or Shift+# on the US `\` key (German); Shift+0 types `=` on both.
|
||||
for (layout, plus_at, quote_at, quote_shift) in [("hr", Key::Equals, Key::Minus, false), ("de", Key::CloseBracket, Key::Backslash, true)] {
|
||||
let mut h = harness(book("C2"));
|
||||
let size = style(&h, "C2").font.size;
|
||||
// Ctrl+; (Ctrl+Shift+,): today's date, not Decrease Font Size.
|
||||
key_on_layout(&mut h, Key::Semicolon, Key::Comma, CTRL_SHIFT);
|
||||
assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;");
|
||||
assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+; changed the font size");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
// Ctrl+: (Ctrl+Shift+.): the time, not Increase Font Size.
|
||||
key_on_layout(&mut h, Key::Colon, Key::Period, CTRL_SHIFT);
|
||||
let time = editor_text(&h).unwrap_or_default();
|
||||
assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}");
|
||||
assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+: changed the font size");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
// Ctrl+': the formula of the cell above.
|
||||
key_on_layout(&mut h, Key::Quote, quote_at, if quote_shift { CTRL_SHIFT } else { CTRL });
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("=A1*2"), "{layout}: Ctrl+'");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
// Ctrl++: Insert, as Ctrl+Shift+= on a US keyboard.
|
||||
key_on_layout(&mut h, Key::Plus, plus_at, CTRL);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells"), "{layout}: Ctrl++");
|
||||
h.state_mut().dialog = None;
|
||||
// Digits go by position: Ctrl+Shift+0 unhides columns although it types `=`.
|
||||
h.state_mut().session.run("selection.set", json!({"range": "B:B"})).unwrap();
|
||||
h.state_mut().session.run("home.hideColumns", json!({})).unwrap();
|
||||
h.state_mut().session.run("selection.set", json!({"range": "A1:C1"})).unwrap();
|
||||
key_on_layout(&mut h, Key::Equals, Key::Num0, CTRL_SHIFT);
|
||||
assert!(h.state().dialog.is_none(), "{layout}: Ctrl+Shift+0 opened {:?}", h.state().dialog.as_ref().map(|d| d.name()));
|
||||
let d = h.state().session.active().unwrap();
|
||||
assert!(!d.wb.active().unwrap().is_col_hidden(1), "{layout}: Ctrl+Shift+0 didn't unhide column B");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_and_time_shortcuts_on_azerty_and_czech_keyboards() {
|
||||
// French AZERTY types `;` and `:` unshifted on the US `,` and `.` keys; Czech QWERTZ types `;`
|
||||
// unshifted on the US backtick key and `:` with Shift+. (US positions).
|
||||
for (layout, semi_at, semi_m, colon_m) in [("fr", Key::Comma, CTRL, CTRL), ("cs", Key::Backtick, CTRL, CTRL_SHIFT)] {
|
||||
let mut h = harness(book("C2"));
|
||||
let size = style(&h, "C2").font.size;
|
||||
key_on_layout(&mut h, Key::Semicolon, semi_at, semi_m);
|
||||
assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
key_on_layout(&mut h, Key::Colon, Key::Period, colon_m);
|
||||
let time = editor_text(&h).unwrap_or_default();
|
||||
assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}");
|
||||
assert_eq!(style(&h, "C2").font.size, size, "{layout}: the font size changed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_keys_type_their_character_in_a_cell_being_edited() {
|
||||
// While a cell is edited the grid reads no shortcuts, so `;` and `:` (Shift+, and Shift+. on
|
||||
// Croatian and German keyboards) are typed, and nothing changes the font size.
|
||||
let mut h = harness(book("C2"));
|
||||
let size = style(&h, "C2").font.size;
|
||||
h.input_mut().events.push(Event::Text("x".into()));
|
||||
h.run_steps(2);
|
||||
for (typed, at, text) in [(Key::Semicolon, Key::Comma, ";"), (Key::Colon, Key::Period, ":")] {
|
||||
let m = Modifiers::SHIFT;
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m });
|
||||
h.input_mut().events.push(Event::Text(text.into()));
|
||||
h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m });
|
||||
h.run_steps(2);
|
||||
}
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("x;:"));
|
||||
assert_eq!(style(&h, "C2").font.size, size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn us_symbol_shortcuts_keep_their_keys() {
|
||||
let mut h = harness(book("C2"));
|
||||
// Ctrl+;: the date. Ctrl+Shift+; arrives as `:` on Windows and as `;` with Shift elsewhere.
|
||||
key(&mut h, Key::Semicolon, CTRL);
|
||||
assert_eq!(editor_text(&h), Some(today(&h)));
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
for typed in [Key::Colon, Key::Semicolon] {
|
||||
key_on_layout(&mut h, typed, Key::Semicolon, CTRL_SHIFT);
|
||||
assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Ctrl+Shift+; as {typed:?}");
|
||||
key(&mut h, Key::Escape, Modifiers::NONE);
|
||||
}
|
||||
// Ctrl+Shift+, and Ctrl+Shift+. (`<` and `>` have no egui key) change the font size.
|
||||
let size = style(&h, "C2").font.size;
|
||||
key(&mut h, Key::Period, CTRL_SHIFT);
|
||||
assert!(style(&h, "C2").font.size > size);
|
||||
key(&mut h, Key::Comma, CTRL_SHIFT);
|
||||
assert_eq!(style(&h, "C2").font.size, size);
|
||||
// Ctrl+Shift+= arrives as `+`: Insert.
|
||||
key_on_layout(&mut h, Key::Plus, Key::Equals, CTRL_SHIFT);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells"));
|
||||
let run = |id: &'static str| Some(Shortcut::Run(id, json!({})));
|
||||
// The lookup itself: `;` typed with Shift is Ctrl+; (handled with the Ctrl letters), not the
|
||||
// key's position (Decrease Font Size).
|
||||
assert_eq!(lookup(Key::Semicolon, Some(Key::Comma), CTRL_SHIFT, false), None);
|
||||
assert_eq!(lookup(Key::Colon, Some(Key::Period), CTRL_SHIFT, false), Some(Shortcut::Time));
|
||||
assert_eq!(lookup(Key::Comma, Some(Key::Comma), CTRL_SHIFT, false), run("home.decreaseFontSize"));
|
||||
// A character egui has no key for (`č` on the US `;` key) leaves the position.
|
||||
assert_eq!(lookup(Key::Semicolon, Some(Key::Semicolon), CTRL_SHIFT, false), Some(Shortcut::Time));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_shift_semicolon_on_a_mac_does_not_insert_the_date() {
|
||||
// The Mac table has Cmd+; (the time) and Control+; (the date), and nothing for Cmd+Shift+;. It
|
||||
// arrives as `:` on the US `;` key, or on the US `.` key of a Croatian or German keyboard.
|
||||
let mut h = harness(book("C2"));
|
||||
h.ctx.set_os(egui::os::OperatingSystem::Mac);
|
||||
let cmd_shift = Modifiers { shift: true, mac_cmd: true, command: true, ..Modifiers::NONE };
|
||||
for at in [Key::Semicolon, Key::Period] {
|
||||
key_on_layout(&mut h, Key::Colon, at, cmd_shift);
|
||||
assert_eq!(editor_text(&h), None, "Cmd+Shift+; at {at:?}");
|
||||
}
|
||||
key(&mut h, Key::Semicolon, Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE });
|
||||
assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Cmd+; is still the time");
|
||||
}
|
||||
|
||||
/// #1443: Ctrl+Q (also with Shift or Alt, which is what AltGr+Q reports on Windows) must not
|
||||
/// close the window and lose unsaved input; macOS keeps Cmd+Q as the app's Quit.
|
||||
#[test]
|
||||
|
||||
@@ -16,6 +16,7 @@ mod cell_editor_caret;
|
||||
mod cell_pictures;
|
||||
mod cf_rule_pick;
|
||||
mod cf_rules_manager;
|
||||
mod chart_data_drag;
|
||||
mod chart_data_table;
|
||||
mod chart_resize;
|
||||
mod chart_source_layering;
|
||||
@@ -59,6 +60,7 @@ mod header_column_drag;
|
||||
mod host_chrome;
|
||||
mod hyperlink_ctrl_click;
|
||||
mod hyperlink_dialog;
|
||||
mod ime_composition;
|
||||
mod in_cell_editor_size;
|
||||
mod in_cell_editor_wrap;
|
||||
mod ink_render;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use egui::{Color32, RawInput, Rect, Shape, pos2, vec2};
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_ui_egui::theme;
|
||||
use gridcraft_ui_egui::{SheetApp, theme};
|
||||
use serde_json::json;
|
||||
|
||||
/// Builds a pivot report at D3 and returns the painted shapes after six frames in the caller's light or dark mode.
|
||||
@@ -57,3 +57,47 @@ fn pivot_field_button_surfaces_follow_the_active_theme() {
|
||||
assert_eq!(field_button_fill(&shapes, "Region ▾"), expected, "dark mode: {dark}");
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten(shape: Shape, out: &mut Vec<Shape>) {
|
||||
match shape {
|
||||
Shape::Vec(shapes) => shapes.into_iter().for_each(|s| flatten(s, out)),
|
||||
s => out.push(s),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_field_list_scrollbar_sits_at_the_pane_edge() {
|
||||
// Regression test for #1485: with enough source fields to scroll, the field list's scrollbar
|
||||
// sat just right of the longest (short) field name instead of at the pane's right edge.
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
let names: Vec<String> = (1..=14).map(|i| format!("F{i}")).collect();
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("range.setValues", json!({"range": "A1", "values": [names.clone(), (1..=14).collect::<Vec<i32>>()]})).unwrap();
|
||||
session.execute("insert.pivotTable", json!({"source": "Sheet1!A1:N2", "destination": "Sheet1!A5", "rows": ["F1"], "values": ["F2"]})).unwrap();
|
||||
session.execute("selection.set", json!({"cell": "A5"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
let first = h.get_by_label("F1").rect();
|
||||
// A floating scrollbar is drawn while the pointer is over its area.
|
||||
h.get_by_label("F1").hover();
|
||||
h.run_steps(3);
|
||||
let mut shapes = Vec::new();
|
||||
h.output().shapes.iter().for_each(|c| flatten(c.shape.clone(), &mut shapes));
|
||||
let bar = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 12.0 && r.rect.height() >= 20.0 && r.rect.left() > first.left() => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.max_by(|a, b| a.right().total_cmp(&b.right()))
|
||||
.expect("the field list draws a scrollbar");
|
||||
assert!(bar.right() > 1200.0 - 20.0, "the scrollbar {bar:?} sits at the pane's right edge, not beside the field names ({first:?})");
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
/// A harness around the app with `session` loaded.
|
||||
fn harness(session: Session) -> Harness {
|
||||
crate::support::harness(session, 4)
|
||||
}
|
||||
@@ -22,10 +23,12 @@ fn sales() -> Session {
|
||||
s
|
||||
}
|
||||
|
||||
/// The column of the first sort level in the open dialog.
|
||||
fn col(h: &Harness) -> String {
|
||||
h.state().dialog.as_ref().unwrap().values["levels"][0]["column"].as_str().unwrap_or("<missing>").to_string()
|
||||
}
|
||||
|
||||
/// Sort by starts on the column the cursor is in.
|
||||
#[test]
|
||||
fn sort_dialog_seeds_the_active_column() {
|
||||
let mut h = harness(sales());
|
||||
@@ -34,8 +37,8 @@ fn sort_dialog_seeds_the_active_column() {
|
||||
assert_eq!(col(&h), "B", "Sort by starts on the column the cursor is in, not A");
|
||||
}
|
||||
|
||||
/// #3446: the closed "Sort by" box shows the column's name next to its letter,
|
||||
/// as the open list does ("B: Revenue", not just "B").
|
||||
/// #3446: the closed "Sort by" box shows the column's name, as the open list does
|
||||
/// ("Revenue", not just the letter "B").
|
||||
#[test]
|
||||
fn closed_column_box_shows_the_column_name() {
|
||||
use egui::accesskit::Role;
|
||||
@@ -43,17 +46,18 @@ fn closed_column_box_shows_the_column_name() {
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
let shown: Vec<String> = h.get_all_by_role(Role::ComboBox).filter_map(|n| n.value()).collect();
|
||||
assert!(shown.iter().any(|v| v == "B: Revenue"), "the Sort by box shows the column name: {shown:?}");
|
||||
assert!(shown.iter().any(|v| v == "Revenue"), "the Sort by box shows the column name: {shown:?}");
|
||||
}
|
||||
|
||||
/// Add Level picks a column no other level uses.
|
||||
#[test]
|
||||
fn add_level_picks_a_column_no_level_uses_yet() {
|
||||
let mut h = harness(sales());
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
// Level 1 seeded B; clicking "+ Add Level" must not default level 2 to B too (#1906 review).
|
||||
// Level 1 seeded B; clicking "Add Level" must not default level 2 to B too (#1906 review).
|
||||
h.run_steps(6);
|
||||
h.get_by_label("+ Add Level").click();
|
||||
h.get_by_label("Add Level").click();
|
||||
h.run_steps(6);
|
||||
let cols: Vec<String> = h.state().dialog.as_ref().unwrap().values["levels"]
|
||||
.as_array()
|
||||
@@ -63,6 +67,102 @@ fn add_level_picks_a_column_no_level_uses_yet() {
|
||||
assert_ne!(cols[0], cols[1], "the second level defaults to a different column: {cols:?}");
|
||||
}
|
||||
|
||||
/// Add Level is not limited by the number of columns (Excel allows many levels): with every
|
||||
/// column in use it adds a level on the selected level's column, and never one outside the range.
|
||||
#[test]
|
||||
fn add_level_keeps_adding_levels_when_every_column_is_used() {
|
||||
let mut s = sales();
|
||||
s.execute("selection.set", json!({"range": "A1:A4", "active": "A2"})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
for _ in 0..2 {
|
||||
h.get_by_label("Add Level").click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
let levels = h.state().dialog.as_ref().unwrap().values["levels"].as_array().unwrap();
|
||||
assert_eq!(levels.len(), 3, "Add Level stays available with one column");
|
||||
assert!(levels.iter().all(|l| l["column"] == "A"), "no level uses a column outside A: {levels:?}");
|
||||
}
|
||||
|
||||
/// In the interface languages whose scripts the bundled fonts cover (CJK and Vietnamese need the
|
||||
/// optional font repo), the toolbar (level buttons and the headers checkbox) stays on one row without
|
||||
/// overlapping: the window widens for a longer translation.
|
||||
#[test]
|
||||
fn toolbar_fits_without_overlap_in_every_language() {
|
||||
use gridcraft_ui_egui::i18n::Language;
|
||||
for language in Language::ALL.into_iter().filter(|l| !matches!(l, Language::Ja | Language::Ko | Language::Zh | Language::Vi)) {
|
||||
let mut app = crate::common::app(sales());
|
||||
app.ui.language = language;
|
||||
let mut h = crate::support::app_harness(app, 4);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(6);
|
||||
let rects: Vec<egui::Rect> = ["Add Level", "Delete Level", "Copy Level", "Move Up", "Move Down", "My list has headers"]
|
||||
.iter()
|
||||
.map(|key| h.get_by_label(language.tr(key)).rect())
|
||||
.collect();
|
||||
let code = language.code();
|
||||
for (i, a) in rects.iter().enumerate() {
|
||||
for b in &rects[i + 1..] {
|
||||
assert!(!a.intersects(*b), "{code}: toolbar items overlap: {a:?} {b:?}");
|
||||
}
|
||||
assert!((a.center().y - rects[0].center().y).abs() < 12.0, "{code}: the toolbar wrapped: {rects:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape restores every selected area and the active cell.
|
||||
#[test]
|
||||
fn sort_dialog_restores_all_selected_areas_and_the_active_cell() {
|
||||
let mut s = sales();
|
||||
s.execute("selection.set", json!({"range": "A1:A4,B1:B4", "active": "B2"})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
h.input_mut().events.push(egui::Event::Key {
|
||||
key: Key::Escape,
|
||||
physical_key: Some(Key::Escape),
|
||||
pressed: true,
|
||||
repeat: false,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(2);
|
||||
let selection = &h.state().session.active().unwrap().selection;
|
||||
assert_eq!(selection.a1(), "A1:A4,B1:B4");
|
||||
assert_eq!(selection.active.a1(), "B2");
|
||||
}
|
||||
|
||||
/// Cancel after toggling headers restores the original selection.
|
||||
#[test]
|
||||
fn sort_dialog_restores_initial_selection_after_header_toggle() {
|
||||
let mut h = harness(sales());
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("My list has headers").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" Cancel ").click();
|
||||
h.run_steps(2);
|
||||
let selection = &h.state().session.active().unwrap().selection;
|
||||
assert_eq!(selection.a1(), "B2");
|
||||
assert_eq!(selection.active.a1(), "B2");
|
||||
}
|
||||
|
||||
/// OK after toggling headers restores the original selection.
|
||||
#[test]
|
||||
fn sort_dialog_restores_initial_selection_after_confirming_with_header_toggle() {
|
||||
let mut h = harness(sales());
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
h.get_by_label("My list has headers").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(2);
|
||||
let selection = &h.state().session.active().unwrap().selection;
|
||||
assert_eq!(selection.a1(), "B2");
|
||||
assert_eq!(selection.active.a1(), "B2");
|
||||
}
|
||||
|
||||
/// OK sorts the rows by the seeded column.
|
||||
#[test]
|
||||
fn sorting_by_the_seeded_column_orders_the_rows() {
|
||||
let mut h = harness(sales());
|
||||
@@ -82,3 +182,171 @@ fn sorting_by_the_seeded_column_orders_the_rows() {
|
||||
let nums: Vec<i64> = (1..4).map(|r| sh.value(gridcraft_engine::core::CellRef::new(r, 1))).filter_map(|v| v.as_f64().map(|n| n as i64)).collect();
|
||||
assert_eq!(nums, vec![10, 20, 30], "sort ran on the seeded column B");
|
||||
}
|
||||
|
||||
/// A request whose range cannot be read opens nothing, so OK cannot sort the selection instead.
|
||||
#[test]
|
||||
fn sort_dialog_rejects_an_invalid_range_instead_of_sorting_the_selection() {
|
||||
let mut h = harness(sales());
|
||||
h.state_mut().open_dialog("sort", json!({"range": "not a range"}));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().dialog.is_none(), "no dialog opens for a range that cannot be read");
|
||||
assert!(h.state().message.is_some(), "the rejection is explained");
|
||||
assert!(!h.state().session.journal.iter().any(|(id, _)| id == "data.sort"), "nothing was sorted");
|
||||
}
|
||||
|
||||
/// A range on another worksheet is sorted there, not on the worksheet that happened to be active.
|
||||
#[test]
|
||||
fn sort_dialog_keeps_the_worksheet_the_range_names() {
|
||||
let mut s = sales();
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "Other!A1", "values": [["Item", "Qty"], ["z", 3], ["x", 1], ["y", 2]]})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().run("data.sort", json!({"range": "Other!A1:B4"})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name.as_str()), Some("sort"));
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().name, "Other", "the dialog shows the worksheet it sorts");
|
||||
assert_eq!(col(&h), "A");
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(2);
|
||||
let doc = h.state().session.active().unwrap();
|
||||
let qty =
|
||||
|sheet: &str, row| doc.wb.sheet(doc.wb.sheet_index(sheet).unwrap()).unwrap().value(gridcraft_engine::core::CellRef::new(row, 1)).as_f64();
|
||||
assert_eq!((1..4).map(|r| qty("Other", r)).collect::<Vec<_>>(), [Some(1.0), Some(2.0), Some(3.0)]);
|
||||
assert_eq!((1..4).map(|r| qty("Sheet1", r)).collect::<Vec<_>>(), [Some(30.0), Some(10.0), Some(20.0)], "the other worksheet is untouched");
|
||||
}
|
||||
|
||||
/// An open filter menu closes when Sort opens, so it cannot take the Enter that confirms Sort.
|
||||
#[test]
|
||||
fn sort_dialog_closes_an_open_filter_menu() {
|
||||
let mut h = harness(sales());
|
||||
h.state_mut().grid.filter_menu = Some((1, 0, egui::pos2(100.0, 100.0)));
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().grid.filter_menu.is_none());
|
||||
h.input_mut().events.push(egui::Event::Key {
|
||||
key: Key::Enter,
|
||||
physical_key: Some(Key::Enter),
|
||||
pressed: true,
|
||||
repeat: false,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(2);
|
||||
assert!(h.state().session.journal.iter().any(|(id, _)| id == "data.sort"), "Enter confirmed Sort");
|
||||
assert!(!h.state().session.journal.iter().any(|(id, _)| id == "data.filterBy"), "and applied no filter");
|
||||
}
|
||||
|
||||
/// Worksheet-changing commands are refused while Sort is open.
|
||||
#[test]
|
||||
fn sheet_tabs_cannot_switch_while_sort_is_open() {
|
||||
let mut s = sales();
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
for id in ["sheet.activate", "sheet.next", "sheet.previous", "sheet.move", "sheet.hide", "sheet.unhide", "home.insertSheet", "home.deleteSheet"] {
|
||||
assert!(h.state_mut().run(id, json!({"sheet": 1})).is_err(), "{id} is refused while Sort is open");
|
||||
}
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 0);
|
||||
assert!(h.state().dialog.is_some());
|
||||
}
|
||||
|
||||
/// OK on another worksheet than the one Sort opened on refuses to sort and keeps the dialog open.
|
||||
#[test]
|
||||
fn sort_refuses_to_run_on_another_worksheet_and_stays_open() {
|
||||
let mut s = sales();
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
h.state_mut().session.execute("sheet.activate", json!({"sheet": 1})).unwrap();
|
||||
h.run_steps(2);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(2);
|
||||
let state = h.state();
|
||||
assert_eq!(state.dialog.as_ref().map(|d| d.name.as_str()), Some("sort"), "the dialog stays open with its levels");
|
||||
assert!(state.message.is_some(), "the refusal is explained");
|
||||
h.state_mut().session.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
let doc = h.state().session.active().unwrap();
|
||||
let first = doc.wb.active().unwrap().value(gridcraft_engine::core::CellRef::new(1, 1)).as_f64();
|
||||
assert_eq!(first, Some(30.0), "the original worksheet was not sorted");
|
||||
}
|
||||
|
||||
/// The dialog follows its worksheet by identity: moving the tab keeps Sort working on it.
|
||||
#[test]
|
||||
fn sort_still_runs_after_its_worksheet_moves_to_another_position() {
|
||||
let mut s = sales();
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
h.state_mut().session.execute("sheet.move", json!({"sheet": 0, "to": 1})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 1);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().dialog.is_none(), "the sort ran and the dialog closed");
|
||||
let sh = h.state().session.active().unwrap().wb.active().unwrap();
|
||||
let revenue: Vec<_> = (1..4).map(|r| sh.value(gridcraft_engine::core::CellRef::new(r, 1)).as_f64()).collect();
|
||||
assert_eq!(revenue, [Some(10.0), Some(20.0), Some(30.0)], "the moved worksheet was sorted");
|
||||
}
|
||||
|
||||
/// A different worksheet that takes the opening worksheet's position is not the opening worksheet.
|
||||
#[test]
|
||||
fn sort_refuses_a_different_worksheet_at_the_same_position() {
|
||||
let mut s = sales();
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
h.state_mut().session.execute("home.deleteSheet", json!({"sheet": 0})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 0);
|
||||
h.get_by_label(" OK ").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name.as_str()), Some("sort"));
|
||||
assert!(h.state().message.is_some(), "the refusal is explained");
|
||||
assert!(!h.state().session.journal.iter().any(|(id, _)| id == "data.sort"), "nothing was sorted");
|
||||
}
|
||||
|
||||
/// Cancelling while another worksheet is active still restores the opening worksheet's selection.
|
||||
#[test]
|
||||
fn sort_cancel_restores_the_selection_of_the_opening_worksheet() {
|
||||
let mut s = sales();
|
||||
s.execute("home.insertSheet", json!({"name": "Other"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
let mut h = harness(s);
|
||||
h.state_mut().open_dialog("sort", json!({}));
|
||||
h.run_steps(2);
|
||||
h.state_mut().session.execute("sheet.activate", json!({"sheet": 1})).unwrap();
|
||||
h.run_steps(2);
|
||||
let other = h.state().session.active().unwrap().selection.a1();
|
||||
let done = gridcraft_ui_egui::control::handle(h.state_mut(), &egui::Context::default(), "ui.dialog.cancel", &json!({}));
|
||||
assert!(matches!(done, gridcraft_ui_egui::control::Outcome::Done(_)));
|
||||
assert_eq!(h.state().session.active().unwrap().selection.a1(), other, "the active worksheet's selection is left alone");
|
||||
h.state_mut().session.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
assert_eq!(h.state().session.active().unwrap().selection.a1(), "B2", "the opening worksheet got its selection back");
|
||||
}
|
||||
|
||||
/// Control cancel and dialog replacement restore the selection.
|
||||
#[test]
|
||||
fn sort_selection_is_restored_when_control_cancels_or_replaces_the_dialog() {
|
||||
let mut cancelled = harness(sales());
|
||||
cancelled.state_mut().open_dialog("sort", json!({}));
|
||||
let done = gridcraft_ui_egui::control::handle(cancelled.state_mut(), &egui::Context::default(), "ui.dialog.cancel", &json!({}));
|
||||
assert!(matches!(done, gridcraft_ui_egui::control::Outcome::Done(_)));
|
||||
assert!(cancelled.state().dialog.is_none());
|
||||
assert_eq!(cancelled.state().session.active().unwrap().selection.a1(), "B2");
|
||||
|
||||
let mut replaced = harness(sales());
|
||||
replaced.state_mut().open_dialog("sort", json!({}));
|
||||
replaced.state_mut().open_dialog("zoom", json!({}));
|
||||
assert_eq!(replaced.state().dialog.as_ref().unwrap().name, "zoom");
|
||||
assert_eq!(replaced.state().session.active().unwrap().selection.a1(), "B2");
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ gridcraft-math = { workspace = true }
|
||||
gridcraft-model = { workspace = true }
|
||||
craft-cfb = { workspace = true }
|
||||
craft-csv = { workspace = true }
|
||||
craft-math = { workspace = true }
|
||||
craft-ods = { workspace = true }
|
||||
craft-offcrypto = { workspace = true }
|
||||
craft-opc = { workspace = true }
|
||||
craft-xls = { workspace = true }
|
||||
|
||||
@@ -271,7 +271,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
}
|
||||
let fill = sp.child("solidFill").and_then(dml_color).unwrap_or_default();
|
||||
let line = ln.and_then(|l| l.child("solidFill")).and_then(dml_color).unwrap_or_default();
|
||||
let text = obj.child("txBody").map(body_text).unwrap_or_default();
|
||||
let text = tb.map(|tb| if has_math { math_body_text(tb) } else { body_text(tb) }).unwrap_or_default();
|
||||
let mut format = read_text_format(obj.child("txBody"));
|
||||
format.no_line = ln.is_some_and(|l| l.child("noFill").is_some());
|
||||
Some(Shape { id: 0, kind, anchor, fill, line, text, format, math: Default::default() })
|
||||
@@ -411,6 +411,55 @@ fn body_text(tb: &El) -> String {
|
||||
tb.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::<String>()).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
/// A rejected Office Math box still needs its visible run text. Do not reinterpret
|
||||
/// that text as LaTeX. Keep traversal and output bounded independently of conversion.
|
||||
fn math_body_text(tb: &El) -> String {
|
||||
const MAX_BYTES: usize = 1 << 20;
|
||||
fn append(text: &str, out: &mut String) {
|
||||
let mut end = text.len().min(MAX_BYTES.saturating_sub(out.len()));
|
||||
while !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
out.push_str(&text[..end]);
|
||||
}
|
||||
fn visit(e: &El, depth: usize, left: &mut usize, out: &mut String) {
|
||||
if depth > 64 || *left == 0 || out.len() >= MAX_BYTES {
|
||||
return;
|
||||
}
|
||||
*left -= 1;
|
||||
if e.name.ends_with("Pr") {
|
||||
return;
|
||||
}
|
||||
if e.name == "t" {
|
||||
append(&e.text, out);
|
||||
} else if e.name == "AlternateContent" {
|
||||
// Choice and fallback describe the same content, not two text runs.
|
||||
if let Some(c) = e.child("Fallback").or_else(|| e.child("Choice")) {
|
||||
visit(c, depth + 1, left, out);
|
||||
}
|
||||
} else {
|
||||
for child in &e.children {
|
||||
visit(child, depth + 1, left, out);
|
||||
if *left == 0 || out.len() >= MAX_BYTES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
let mut left = 100_000;
|
||||
for (i, p) in tb.kids("p").enumerate() {
|
||||
if left == 0 || out.len() >= MAX_BYTES {
|
||||
break;
|
||||
}
|
||||
if i > 0 {
|
||||
append("\n", &mut out);
|
||||
}
|
||||
visit(p, 0, &mut left, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a body without Office Math still holds the text the writer wrote for `src`: the same
|
||||
/// paragraphs, read back through the same parser. The marker joins run text across paragraphs,
|
||||
/// so a paragraph split that changes no character passes it; the text does not.
|
||||
@@ -691,3 +740,23 @@ pub fn image_content_type(ext: &str) -> &'static str {
|
||||
_ => "image/png",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod math_fallback_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fallback_uses_one_alternative_and_ignores_properties() {
|
||||
let tb = crate::xml::parse(br#"<txBody><p><rPr><t>hidden</t></rPr><r><t>before </t></r><AlternateContent><Choice><r><t>choice</t></r></Choice><Fallback><r><t>fallback</t></r></Fallback></AlternateContent><r><t> after</t></r></p><p><r><t>next</t></r></p></txBody>"#).unwrap();
|
||||
assert_eq!(math_body_text(&tb), "before fallback after\nnext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_output_cap_keeps_utf8_intact() {
|
||||
let xml = format!("<txBody><p><r><t>a{}</t></r></p></txBody>", "λ".repeat(1 << 19));
|
||||
let tb = crate::xml::parse(xml.as_bytes()).unwrap();
|
||||
let text = math_body_text(&tb);
|
||||
assert_eq!(text.len(), (1 << 20) - 1);
|
||||
assert!(text.starts_with('a') && text.ends_with('λ'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,6 +335,18 @@ mod tests {
|
||||
assert!(checked > gridcraft_functions::all().len() * 10, "only {checked} formulas parsed");
|
||||
}
|
||||
|
||||
/// NETWORKDAYS.INTL and WORKDAY.INTL are in the file format's own function list: saved without
|
||||
/// `_xlfn.` (LibreOffice gives #NAME? for the prefixed spelling), and the prefixed spelling of a
|
||||
/// file written by an older version still reads (#3517, #2775).
|
||||
#[test]
|
||||
fn intl_day_functions_are_saved_without_the_prefix() {
|
||||
let f = Formula::new("NETWORKDAYS.INTL(DATE(2026,1,5),DATE(2026,1,9),1)+WORKDAY.INTL(DATE(2026,1,5),3,1)");
|
||||
assert_eq!(to_file(&f), "NETWORKDAYS.INTL(DATE(2026,1,5),DATE(2026,1,9),1)+WORKDAY.INTL(DATE(2026,1,5),3,1)");
|
||||
assert_eq!(text_to_file("=WORKDAY.INTL(A1,3,1)"), "WORKDAY.INTL(A1,3,1)");
|
||||
assert_eq!(from_file("_xlfn.NETWORKDAYS.INTL(A1,B1,1)+_xlfn.WORKDAY.INTL(A1,3,1)"), "NETWORKDAYS.INTL(A1,B1,1)+WORKDAY.INTL(A1,3,1)");
|
||||
assert_eq!(from_file("NETWORKDAYS.INTL(A1,B1,1)"), "NETWORKDAYS.INTL(A1,B1,1)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spill_references() {
|
||||
assert_eq!(to_file(&Formula::new("SUM(Sheet1!$D$1#)+B2#")), "SUM(_xlfn.ANCHORARRAY(Sheet1!$D$1))+_xlfn.ANCHORARRAY(B2)");
|
||||
|
||||
+96
-613
@@ -1,32 +1,17 @@
|
||||
//! Data-only OpenDocument Spreadsheet import. Formula caches become constants; styles and
|
||||
//! other ODF features are deliberately not translated. All fixtures are authored in Rust.
|
||||
//! Format reference: ODF 1.3, part 3, sections 6.1 and 9.1:
|
||||
//! <https://docs.oasis-open.org/office/OpenDocument/v1.3/os/part3-schema/OpenDocument-v1.3-os-part3-schema.html>.
|
||||
//! Data-only OpenDocument Spreadsheet import backed by `craft-ods`.
|
||||
//! Formula caches become constants; styles and other ODF features are deliberately not translated.
|
||||
|
||||
use std::io::{Cursor, Read};
|
||||
use std::sync::Arc;
|
||||
|
||||
use gridcraft_core::date::{days_in_month, serial_from_ymd};
|
||||
use gridcraft_core::{CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRef, Value};
|
||||
use gridcraft_core::{CellError, CellRef, RangeRef, Value};
|
||||
use gridcraft_model::{Cell, NumFmt, Sheet, StyleId, Workbook};
|
||||
use quick_xml::NsReader;
|
||||
use quick_xml::XmlVersion;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::name::ResolveResult;
|
||||
|
||||
use crate::package::{MAX_ENTRIES, Package};
|
||||
use crate::package::MAX_ENTRIES;
|
||||
use crate::read::SheetNames;
|
||||
use crate::{IoError, ReadReport};
|
||||
|
||||
const MIME: &[u8] = b"application/vnd.oasis.opendocument.spreadsheet";
|
||||
const OFFICE: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:office:1.0";
|
||||
const TABLE: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:table:1.0";
|
||||
const TEXT: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:text:1.0";
|
||||
const CALC_EXT: &[u8] = b"urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0";
|
||||
const MANIFEST: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0";
|
||||
const MAX_CELLS: u64 = 1_000_000;
|
||||
const MAX_MERGES: u64 = 100_000;
|
||||
const MAX_CELL_TEXT: usize = 1024 * 1024;
|
||||
const MAX_TEXT: u64 = 64 * 1024 * 1024;
|
||||
const MAX_SHEETS: usize = 1024;
|
||||
|
||||
/// Reads only the small, exact mimetype entry, including when the ZIP uses compression.
|
||||
@@ -48,622 +33,120 @@ pub(crate) fn has_mimetype(bytes: &[u8]) -> bool {
|
||||
/// imported as constants, so editing their inputs does not recalculate the original formula.
|
||||
/// Always inspect the returned warnings. Saving to ODS is not supported.
|
||||
pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
let mut package = Package::open(bytes)?;
|
||||
// The exact mimetype, as `sniff` requires: craft-ods alone accepts some near misses.
|
||||
if !has_mimetype(bytes) {
|
||||
return Err(IoError::Format("missing or invalid ODS mimetype".into()));
|
||||
}
|
||||
if let Some(manifest) = package.read("META-INF/manifest.xml")? {
|
||||
check_manifest(&manifest)?;
|
||||
}
|
||||
let content = package.read("content.xml")?.ok_or_else(|| IoError::Format("ODS content.xml is missing".into()))?;
|
||||
let mut import = Import::new();
|
||||
import.parse(&content)?;
|
||||
if import.wb.sheets.is_empty() {
|
||||
let book = craft_ods::read(bytes, &craft_ods::Options::default()).map_err(map_error)?;
|
||||
if book.sheets.is_empty() {
|
||||
return Err(IoError::Format("ODS contains no worksheets".into()));
|
||||
}
|
||||
Ok((import.wb, import.report))
|
||||
}
|
||||
if book.sheets.len() > MAX_SHEETS {
|
||||
return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into()));
|
||||
}
|
||||
|
||||
fn is_ns(ns: ResolveResult<'_>, expected: &[u8]) -> bool {
|
||||
matches!(ns, ResolveResult::Bound(n) if n.as_ref() == expected)
|
||||
}
|
||||
// `Workbook::new` starts with an empty Sheet1; the ODS tables are the only sheets.
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheets.clear();
|
||||
let mut names = SheetNames::default();
|
||||
let mut report = ReadReport::default();
|
||||
report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported.");
|
||||
|
||||
fn attr(reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>, ns: &[u8], name: &[u8]) -> Result<Option<String>, IoError> {
|
||||
let mut found = None;
|
||||
for a in e.attributes() {
|
||||
let a = a.map_err(|e| IoError::Xml(e.to_string()))?;
|
||||
let (resolved, local) = reader.resolver_mut().resolve_attribute(a.key);
|
||||
if is_ns(resolved, ns) && local.as_ref() == name {
|
||||
let value = a.normalized_value(XmlVersion::Explicit1_0).map_err(|e| IoError::Xml(e.to_string()))?;
|
||||
if value.len() > MAX_CELL_TEXT {
|
||||
return Err(IoError::TooLarge("ODS attribute exceeds 1 MiB".into()));
|
||||
}
|
||||
found = Some(value.into_owned());
|
||||
let mut warned_rename = false;
|
||||
let mut warned_unavailable = false;
|
||||
|
||||
for src_sheet in book.sheets {
|
||||
let mut name = names.unique(src_sheet.name.trim_matches('\''), wb.sheets.len());
|
||||
if wb.check_sheet_name(&name, None).is_err() {
|
||||
name = wb.next_sheet_name();
|
||||
names.insert(&name);
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn positive(value: Option<String>, default: u32, limit: u32) -> Result<u32, IoError> {
|
||||
let n = match value {
|
||||
Some(s) => s.parse::<u32>().map_err(|_| IoError::Format("invalid ODS repeat or span count".into()))?,
|
||||
None => default,
|
||||
};
|
||||
if n == 0 || n > limit {
|
||||
return Err(IoError::TooLarge("ODS repeat or span exceeds worksheet bounds".into()));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn xml_error(e: impl std::fmt::Display) -> IoError {
|
||||
IoError::Xml(format!("ODS: {e}"))
|
||||
}
|
||||
|
||||
fn check_manifest(bytes: &[u8]) -> Result<(), IoError> {
|
||||
let mut reader = NsReader::from_reader(bytes);
|
||||
let mut depth = 0usize;
|
||||
let mut root_seen = false;
|
||||
loop {
|
||||
let event = reader.read_event().map_err(xml_error)?;
|
||||
match &event {
|
||||
Event::Start(e) | Event::Empty(e) => {
|
||||
let (ns, name) = reader.resolver_mut().resolve_element(e.name());
|
||||
if is_ns(ns.clone(), MANIFEST) && name.as_ref() == b"encryption-data" {
|
||||
return Err(IoError::Format("encrypted ODS files are not supported".into()));
|
||||
}
|
||||
if depth == 0 {
|
||||
if root_seen || !is_ns(ns, MANIFEST) || name.as_ref() != b"manifest" {
|
||||
return Err(xml_error("expected one manifest:manifest root"));
|
||||
}
|
||||
root_seen = true;
|
||||
}
|
||||
if matches!(event, Event::Start(_)) {
|
||||
depth += 1;
|
||||
if depth > crate::xml::MAX_DEPTH {
|
||||
return Err(xml_error("manifest nested too deeply"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::End(_) => depth = depth.checked_sub(1).ok_or_else(|| xml_error("unexpected manifest closing element"))?,
|
||||
Event::DocType(_) => return Err(xml_error("DOCTYPE is not supported")),
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
let mut sheet = Sheet::new(name);
|
||||
if !warned_rename && sheet.name != src_sheet.name {
|
||||
warned_rename = true;
|
||||
report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names.");
|
||||
}
|
||||
}
|
||||
if !root_seen || depth != 0 {
|
||||
return Err(xml_error("incomplete manifest"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Tag {
|
||||
Document,
|
||||
Body,
|
||||
Spreadsheet,
|
||||
Table,
|
||||
Rows,
|
||||
Row,
|
||||
Cell,
|
||||
Covered,
|
||||
Paragraph,
|
||||
Inline,
|
||||
Space,
|
||||
Tab,
|
||||
Break,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn tag(reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>) -> Tag {
|
||||
let (ns, name) = reader.resolver_mut().resolve_element(e.name());
|
||||
let local = name.as_ref();
|
||||
if is_ns(ns.clone(), OFFICE) {
|
||||
return match local {
|
||||
b"document-content" => Tag::Document,
|
||||
b"body" => Tag::Body,
|
||||
b"spreadsheet" => Tag::Spreadsheet,
|
||||
_ => Tag::Other,
|
||||
};
|
||||
}
|
||||
if is_ns(ns.clone(), TABLE) {
|
||||
return match local {
|
||||
b"table" => Tag::Table,
|
||||
b"table-row-group" | b"table-header-rows" | b"table-rows" => Tag::Rows,
|
||||
b"table-row" => Tag::Row,
|
||||
b"table-cell" => Tag::Cell,
|
||||
b"covered-table-cell" => Tag::Covered,
|
||||
_ => Tag::Other,
|
||||
};
|
||||
}
|
||||
if is_ns(ns, TEXT) {
|
||||
return match local {
|
||||
b"p" | b"h" => Tag::Paragraph,
|
||||
b"span" | b"a" | b"meta" | b"meta-field" | b"ruby" | b"ruby-base" => Tag::Inline,
|
||||
b"s" => Tag::Space,
|
||||
b"tab" => Tag::Tab,
|
||||
b"line-break" => Tag::Break,
|
||||
_ => Tag::Other,
|
||||
};
|
||||
}
|
||||
Tag::Other
|
||||
}
|
||||
|
||||
struct SheetDraft {
|
||||
sheet: Sheet,
|
||||
depth: usize,
|
||||
row: u32,
|
||||
}
|
||||
struct RowDraft {
|
||||
depth: usize,
|
||||
repeat: u32,
|
||||
col: u32,
|
||||
cells: Vec<RepeatedCell>,
|
||||
}
|
||||
struct RepeatedCell {
|
||||
col: u32,
|
||||
repeat: u32,
|
||||
width: u32,
|
||||
height: u32,
|
||||
cell: Cell,
|
||||
}
|
||||
struct CellDraft {
|
||||
depth: usize,
|
||||
repeat: u32,
|
||||
width: u32,
|
||||
height: u32,
|
||||
covered: bool,
|
||||
kind: Option<String>,
|
||||
raw: Option<String>,
|
||||
formula: bool,
|
||||
text: String,
|
||||
paragraph: Option<usize>,
|
||||
paragraphs: usize,
|
||||
paragraph_started: bool,
|
||||
pending_space: bool,
|
||||
}
|
||||
struct Import {
|
||||
wb: Workbook,
|
||||
report: ReadReport,
|
||||
stack: Vec<Tag>,
|
||||
sheet: Option<SheetDraft>,
|
||||
row: Option<RowDraft>,
|
||||
cell: Option<CellDraft>,
|
||||
cells: u64,
|
||||
merges: u64,
|
||||
text: u64,
|
||||
formats: Vec<(&'static str, StyleId)>,
|
||||
spreadsheet_seen: bool,
|
||||
}
|
||||
|
||||
impl Import {
|
||||
fn new() -> Self {
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheets.clear();
|
||||
let mut report = ReadReport::default();
|
||||
report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported.");
|
||||
Self { wb, report, stack: vec![], sheet: None, row: None, cell: None, cells: 0, merges: 0, text: 0, formats: vec![], spreadsheet_seen: false }
|
||||
}
|
||||
|
||||
fn parse(&mut self, bytes: &[u8]) -> Result<(), IoError> {
|
||||
let mut reader = NsReader::from_reader(bytes);
|
||||
let mut root_seen = false;
|
||||
loop {
|
||||
match reader.read_event().map_err(xml_error)? {
|
||||
Event::Start(e) => {
|
||||
if self.stack.len() >= crate::xml::MAX_DEPTH {
|
||||
return Err(xml_error("XML nested too deeply"));
|
||||
}
|
||||
if self.stack.is_empty() {
|
||||
if root_seen || tag(&mut reader, &e) != Tag::Document {
|
||||
return Err(xml_error("expected one office:document-content root"));
|
||||
}
|
||||
root_seen = true;
|
||||
}
|
||||
self.start(&mut reader, &e)?;
|
||||
for (coord, src_cell) in src_sheet.cells {
|
||||
// A typed value that cannot be read (an unparsable number or date, an error cache,
|
||||
// a formula without a result) keeps what the cell showed, else its raw value.
|
||||
let Some(value) = src_cell.value().map(map_value) else {
|
||||
if !warned_unavailable {
|
||||
warned_unavailable = true;
|
||||
report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result].");
|
||||
}
|
||||
Event::Empty(e) => {
|
||||
if self.stack.is_empty() {
|
||||
return Err(xml_error("expected office:document-content with a spreadsheet"));
|
||||
}
|
||||
self.start(&mut reader, &e)?;
|
||||
self.end()?;
|
||||
}
|
||||
Event::End(_) => self.end()?,
|
||||
Event::Text(t) => {
|
||||
let text = t.xml_content(XmlVersion::Explicit1_0).map_err(xml_error)?;
|
||||
if self.stack.is_empty() && !text.trim().is_empty() {
|
||||
return Err(xml_error("text outside the document"));
|
||||
}
|
||||
self.append(&text)?;
|
||||
}
|
||||
Event::CData(t) => self.append(&t.decode().map_err(xml_error)?)?,
|
||||
Event::GeneralRef(r) => {
|
||||
let ch = match r.resolve_char_ref().map_err(xml_error)? {
|
||||
Some(c) => c,
|
||||
None => match &*r {
|
||||
b"amp" => '&',
|
||||
b"lt" => '<',
|
||||
b"gt" => '>',
|
||||
b"apos" => '\'',
|
||||
b"quot" => '"',
|
||||
_ => return Err(xml_error("unsupported XML entity")),
|
||||
},
|
||||
};
|
||||
self.append(ch.encode_utf8(&mut [0; 4]))?;
|
||||
}
|
||||
Event::DocType(_) => return Err(xml_error("DOCTYPE is not supported")),
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !root_seen || !self.stack.is_empty() || !self.spreadsheet_seen {
|
||||
return Err(xml_error("incomplete ODS document"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start(&mut self, reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>) -> Result<(), IoError> {
|
||||
let t = tag(reader, e);
|
||||
let depth = self.stack.len();
|
||||
match t {
|
||||
Tag::Spreadsheet if self.stack == [Tag::Document, Tag::Body] => {
|
||||
if self.spreadsheet_seen {
|
||||
return Err(xml_error("multiple spreadsheets in one document"));
|
||||
}
|
||||
self.spreadsheet_seen = true;
|
||||
}
|
||||
Tag::Table if self.stack == [Tag::Document, Tag::Body, Tag::Spreadsheet] => {
|
||||
if self.wb.sheets.len() >= MAX_SHEETS {
|
||||
return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into()));
|
||||
}
|
||||
let original = attr(reader, e, TABLE, b"name")?.unwrap_or_default();
|
||||
let mut name = crate::read::SheetNames::of(&self.wb).unique(original.trim_matches('\''), self.wb.sheets.len());
|
||||
if self.wb.check_sheet_name(&name, None).is_err() {
|
||||
name = self.wb.next_sheet_name();
|
||||
}
|
||||
if name != original {
|
||||
self.report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names.");
|
||||
}
|
||||
self.sheet = Some(SheetDraft { sheet: Sheet::new(name), depth, row: 0 });
|
||||
}
|
||||
Tag::Row if self.sheet.as_ref().is_some_and(|s| self.stack.get(s.depth + 1..).is_some_and(|p| p.iter().all(|t| *t == Tag::Rows))) => {
|
||||
self.row =
|
||||
Some(RowDraft { depth, repeat: positive(attr(reader, e, TABLE, b"number-rows-repeated")?, 1, u32::MAX)?, col: 0, cells: vec![] });
|
||||
}
|
||||
Tag::Cell | Tag::Covered if self.row.as_ref().is_some_and(|r| depth == r.depth + 1) => {
|
||||
let kind = if attr(reader, e, CALC_EXT, b"value-type")?.as_deref() == Some("error") {
|
||||
Some("error".into())
|
||||
let text = if !src_cell.text.is_empty() {
|
||||
src_cell.text.as_str()
|
||||
} else if let Some(raw) = src_cell.raw.as_deref() {
|
||||
raw
|
||||
} else if src_cell.formula.is_some() {
|
||||
"[Unavailable ODS formula result]"
|
||||
} else {
|
||||
attr(reader, e, OFFICE, b"value-type")?
|
||||
"[Unsupported ODS value]"
|
||||
};
|
||||
let key: &[u8] = match kind.as_deref() {
|
||||
Some("boolean") => b"boolean-value",
|
||||
Some("date") => b"date-value",
|
||||
Some("time") => b"time-value",
|
||||
Some("string") => b"string-value",
|
||||
_ => b"value",
|
||||
};
|
||||
self.cell = Some(CellDraft {
|
||||
depth,
|
||||
repeat: positive(attr(reader, e, TABLE, b"number-columns-repeated")?, 1, u32::MAX)?,
|
||||
width: positive(attr(reader, e, TABLE, b"number-columns-spanned")?, 1, MAX_COLS)?,
|
||||
height: positive(attr(reader, e, TABLE, b"number-rows-spanned")?, 1, MAX_ROWS)?,
|
||||
covered: t == Tag::Covered,
|
||||
kind,
|
||||
raw: attr(reader, e, OFFICE, key)?,
|
||||
formula: attr(reader, e, TABLE, b"formula")?.is_some(),
|
||||
text: String::new(),
|
||||
paragraph: None,
|
||||
paragraphs: 0,
|
||||
paragraph_started: false,
|
||||
pending_space: false,
|
||||
});
|
||||
}
|
||||
Tag::Paragraph if self.cell.as_ref().is_some_and(|c| depth == c.depth + 1) => {
|
||||
if let Some(cell) = self.cell.as_mut() {
|
||||
if cell.paragraphs > 0 {
|
||||
push_text(&mut cell.text, "\n")?;
|
||||
}
|
||||
cell.paragraph = Some(depth);
|
||||
cell.paragraphs += 1;
|
||||
cell.paragraph_started = false;
|
||||
cell.pending_space = false;
|
||||
}
|
||||
}
|
||||
Tag::Space | Tag::Tab | Tag::Break if self.captures_text() => {
|
||||
let count = if t == Tag::Space {
|
||||
let n = attr(reader, e, TEXT, b"c")?.map(|s| s.parse::<u32>()).transpose().map_err(xml_error)?.unwrap_or(1);
|
||||
if n as usize > MAX_CELL_TEXT {
|
||||
return Err(IoError::TooLarge("ODS repeated spaces exceed 1 MiB".into()));
|
||||
}
|
||||
n
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let value = match t {
|
||||
Tag::Space => " ",
|
||||
Tag::Tab => "\t",
|
||||
_ => "\n",
|
||||
};
|
||||
if let Some(cell) = self.cell.as_mut() {
|
||||
if cell.pending_space {
|
||||
push_text(&mut cell.text, " ")?;
|
||||
cell.pending_space = false;
|
||||
}
|
||||
cell.paragraph_started = true;
|
||||
if cell.text.len().saturating_add(count as usize) > MAX_CELL_TEXT {
|
||||
return Err(IoError::TooLarge("ODS cell text exceeds 1 MiB".into()));
|
||||
}
|
||||
for _ in 0..count {
|
||||
cell.text.push_str(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.stack.push(t);
|
||||
Ok(())
|
||||
}
|
||||
sheet.set_cell(CellRef::new(coord.row, coord.col), Cell::styled(Value::Text(Arc::from(text)), StyleId::DEFAULT));
|
||||
continue;
|
||||
};
|
||||
|
||||
fn captures_text(&self) -> bool {
|
||||
self.cell
|
||||
.as_ref()
|
||||
.and_then(|c| c.paragraph)
|
||||
.is_some_and(|depth| self.stack.get(depth..).is_some_and(|p| p.iter().all(|t| matches!(t, Tag::Paragraph | Tag::Inline))))
|
||||
}
|
||||
|
||||
fn append(&mut self, text: &str) -> Result<(), IoError> {
|
||||
if self.captures_text()
|
||||
&& let Some(cell) = self.cell.as_mut()
|
||||
{
|
||||
// ODF 1.3 section 6.1.2: collapse XML whitespace across inline runs,
|
||||
// but expand explicit text:s/tab/line-break elements separately.
|
||||
for ch in text.chars() {
|
||||
if matches!(ch, ' ' | '\t' | '\n' | '\r') {
|
||||
cell.pending_space = cell.paragraph_started;
|
||||
} else {
|
||||
if cell.pending_space {
|
||||
push_text(&mut cell.text, " ")?;
|
||||
cell.pending_space = false;
|
||||
}
|
||||
push_text(&mut cell.text, ch.encode_utf8(&mut [0; 4]))?;
|
||||
cell.paragraph_started = true;
|
||||
let format = match src_cell.value_type {
|
||||
Some(craft_ods::ValueType::Date) => {
|
||||
let with_time = src_cell.raw.as_deref().and_then(craft_ods::date_serial).is_some_and(|(_, time)| time);
|
||||
Some(if with_time { "yyyy-mm-dd hh:mm:ss.000" } else { "yyyy-mm-dd" })
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(&mut self) -> Result<(), IoError> {
|
||||
self.stack.pop().ok_or_else(|| xml_error("unexpected closing element"))?;
|
||||
let depth = self.stack.len();
|
||||
if let Some(cell) = self.cell.as_mut()
|
||||
&& cell.paragraph == Some(depth)
|
||||
{
|
||||
cell.paragraph = None;
|
||||
}
|
||||
if self.cell.as_ref().is_some_and(|c| c.depth == depth) {
|
||||
self.finish_cell()?;
|
||||
}
|
||||
if self.row.as_ref().is_some_and(|r| r.depth == depth) {
|
||||
self.finish_row()?;
|
||||
}
|
||||
if self.sheet.as_ref().is_some_and(|s| s.depth == depth)
|
||||
&& let Some(sheet) = self.sheet.take()
|
||||
{
|
||||
self.wb.sheets.push(Arc::new(sheet.sheet));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_cell(&mut self) -> Result<(), IoError> {
|
||||
let Some(draft) = self.cell.take() else { return Ok(()) };
|
||||
let cell = self.convert(&draft);
|
||||
let (width, height) = if draft.covered { (1, 1) } else { (draft.width, draft.height) };
|
||||
let Some(row) = self.row.as_mut() else { return Ok(()) };
|
||||
let kept = !cell.is_blank() || width > 1 || height > 1;
|
||||
// Writers pad rows with blank repeats up to their own (possibly wider) sheet edge;
|
||||
// blank cells past ours carry no data, so clip them instead of rejecting the file.
|
||||
let end = match row.col.checked_add(draft.repeat).filter(|n| *n <= MAX_COLS) {
|
||||
Some(end) => end,
|
||||
None if !kept => MAX_COLS,
|
||||
None => return Err(IoError::TooLarge("ODS row exceeds worksheet width".into())),
|
||||
};
|
||||
if kept {
|
||||
// Charge the text a row keeps before the row is done, so a row of many long cells is
|
||||
// refused as it grows; finish_row charges the row's repeats beyond the first.
|
||||
if let Value::Text(t) = &cell.value {
|
||||
self.text = self.text.saturating_add(u64::from(draft.repeat).saturating_mul(t.len() as u64));
|
||||
if self.text > MAX_TEXT {
|
||||
return Err(IoError::TooLarge("ODS expands beyond the import limit (64 MiB of text)".into()));
|
||||
}
|
||||
}
|
||||
row.cells.push(RepeatedCell { col: row.col, repeat: draft.repeat, width, height, cell });
|
||||
}
|
||||
row.col = end;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert(&mut self, draft: &CellDraft) -> Cell {
|
||||
let raw = draft.raw.as_deref();
|
||||
let mut format = None;
|
||||
let value = match draft.kind.as_deref() {
|
||||
Some("float" | "percentage" | "currency") => raw.and_then(|s| s.parse::<f64>().ok()).filter(|n| n.is_finite()).map(|n| {
|
||||
if draft.kind.as_deref() == Some("percentage") {
|
||||
format = Some("0.00%");
|
||||
}
|
||||
Value::Number(n)
|
||||
}),
|
||||
Some("boolean") => match raw {
|
||||
Some("true" | "1") => Some(Value::Bool(true)),
|
||||
Some("false" | "0") => Some(Value::Bool(false)),
|
||||
Some(craft_ods::ValueType::Time) => Some("[h]:mm:ss.000"),
|
||||
Some(craft_ods::ValueType::Percentage) => Some("0.00%"),
|
||||
Some(craft_ods::ValueType::Currency) => Some("#,##0.00"),
|
||||
_ => None,
|
||||
},
|
||||
Some("string") if raw.is_some() || draft.paragraphs > 0 || !draft.formula => Some(Value::Text(Arc::from(raw.unwrap_or(&draft.text)))),
|
||||
Some("void") if !draft.formula => Some(Value::Empty),
|
||||
Some("date") => raw.and_then(parse_date).map(|(n, f)| {
|
||||
format = Some(f);
|
||||
Value::Number(n)
|
||||
}),
|
||||
Some("time") => raw.and_then(parse_duration).map(|n| {
|
||||
format = Some("[h]:mm:ss.000");
|
||||
Value::Number(n)
|
||||
}),
|
||||
None if !draft.formula => Some(if draft.text.is_empty() { Value::Empty } else { Value::Text(Arc::from(draft.text.as_str())) }),
|
||||
_ => None,
|
||||
};
|
||||
let value = value.unwrap_or_else(|| {
|
||||
self.report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result].");
|
||||
let text = if !draft.text.is_empty() { draft.text.as_str() } else if let Some(raw) = raw { raw } else if draft.formula { "[Unavailable ODS formula result]" } else { "[Unsupported ODS value]" };
|
||||
Value::Text(Arc::from(text))
|
||||
});
|
||||
let style = match format {
|
||||
Some(code) => match self.formats.iter().find(|(f, _)| *f == code) {
|
||||
Some((_, id)) => *id,
|
||||
None => {
|
||||
let id = self.wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code));
|
||||
self.formats.push((code, id));
|
||||
id
|
||||
}
|
||||
},
|
||||
None => StyleId::DEFAULT,
|
||||
};
|
||||
Cell { style, ..Cell::value(value) }
|
||||
};
|
||||
let style_id = format.map_or(StyleId::DEFAULT, |code| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code)));
|
||||
|
||||
let target_coord = CellRef::new(coord.row, coord.col);
|
||||
sheet.set_cell(target_coord, Cell::styled(value, style_id));
|
||||
}
|
||||
|
||||
for m in src_sheet.merges {
|
||||
let range = RangeRef::new(CellRef::new(m.first.row, m.first.col), CellRef::new(m.last.row, m.last.col));
|
||||
sheet.merges.push(range);
|
||||
}
|
||||
wb.sheets.push(Arc::new(sheet));
|
||||
}
|
||||
|
||||
fn finish_row(&mut self) -> Result<(), IoError> {
|
||||
let Some(row) = self.row.take() else { return Ok(()) };
|
||||
let Some(sheet) = self.sheet.as_mut() else { return Ok(()) };
|
||||
// Blank trailing row repeats past the sheet edge (e.g. from larger-sheet writers) are clipped.
|
||||
let end = match sheet.row.checked_add(row.repeat).filter(|n| *n <= MAX_ROWS) {
|
||||
Some(end) => end,
|
||||
None if row.cells.is_empty() => MAX_ROWS,
|
||||
None => return Err(IoError::TooLarge("ODS exceeds worksheet height".into())),
|
||||
};
|
||||
for entry in row.cells {
|
||||
let count = u64::from(entry.repeat) * u64::from(row.repeat);
|
||||
if !entry.cell.is_blank() {
|
||||
self.cells = self.cells.saturating_add(count);
|
||||
if let Value::Text(t) = &entry.cell.value {
|
||||
let repeats = count.saturating_sub(u64::from(entry.repeat));
|
||||
self.text = self.text.saturating_add(repeats.saturating_mul(t.len() as u64));
|
||||
}
|
||||
}
|
||||
let merged = entry.width > 1 || entry.height > 1;
|
||||
if merged {
|
||||
self.merges = self.merges.saturating_add(count);
|
||||
}
|
||||
if self.cells > MAX_CELLS || self.merges > MAX_MERGES || self.text > MAX_TEXT {
|
||||
return Err(IoError::TooLarge("ODS expands beyond the import limit (1 million cells, 100000 merges or 64 MiB of text)".into()));
|
||||
}
|
||||
let last_col = entry.col.checked_add(entry.repeat - 1).and_then(|c| c.checked_add(entry.width - 1));
|
||||
let last_row = end.checked_add(entry.height - 1);
|
||||
if last_col.is_none_or(|c| c >= MAX_COLS) || last_row.is_none_or(|r| r > MAX_ROWS) {
|
||||
return Err(IoError::TooLarge("ODS merged cell exceeds worksheet bounds".into()));
|
||||
}
|
||||
if merged && ((entry.repeat > 1 && entry.width > 1) || (row.repeat > 1 && entry.height > 1)) {
|
||||
return Err(IoError::Format("repeated ODS cells have overlapping merges".into()));
|
||||
}
|
||||
for r in sheet.row..end {
|
||||
for c in entry.col..entry.col + entry.repeat {
|
||||
let pos = CellRef::new(r, c);
|
||||
if !entry.cell.is_blank() {
|
||||
sheet.sheet.cells.set(pos, entry.cell.clone());
|
||||
}
|
||||
if merged {
|
||||
sheet.sheet.merges.push(RangeRef::new(pos, CellRef::new(r + entry.height - 1, c + entry.width - 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sheet.row = end;
|
||||
Ok(())
|
||||
Ok((wb, report))
|
||||
}
|
||||
|
||||
fn map_error(e: craft_ods::Error) -> IoError {
|
||||
match e {
|
||||
craft_ods::Error::Encrypted => IoError::Format("encrypted ODS files are not supported".into()),
|
||||
craft_ods::Error::Xml(msg) => IoError::Xml(format!("ODS: {msg}")),
|
||||
craft_ods::Error::TooLarge(msg) => IoError::TooLarge(msg),
|
||||
craft_ods::Error::Invalid(msg) => IoError::Format(msg),
|
||||
other => IoError::Format(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn push_text(out: &mut String, text: &str) -> Result<(), IoError> {
|
||||
if out.len().saturating_add(text.len()) > MAX_CELL_TEXT {
|
||||
return Err(IoError::TooLarge("ODS cell text exceeds 1 MiB".into()));
|
||||
fn map_value(v: craft_ods::Value) -> Value {
|
||||
match v {
|
||||
craft_ods::Value::Empty => Value::Empty,
|
||||
craft_ods::Value::Number(n) => Value::Number(n),
|
||||
craft_ods::Value::Text(s) => Value::Text(s),
|
||||
craft_ods::Value::Bool(b) => Value::Bool(b),
|
||||
craft_ods::Value::Error(e) => Value::Error(map_cell_error(e)),
|
||||
}
|
||||
out.push_str(text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Support unzoned ISO calendar dates and times. A timezone, invalid date or out-of-range
|
||||
/// calendar year remains text; never silently discard an offset or roll an invalid date.
|
||||
fn parse_date(s: &str) -> Option<(f64, &'static str)> {
|
||||
let (date, time) = s.split_once('T').map_or((s, None), |(d, t)| (d, Some(t)));
|
||||
if date.len() != 10 || date.get(4..5)? != "-" || date.get(7..8)? != "-" {
|
||||
return None;
|
||||
fn map_cell_error(e: craft_ods::CellError) -> CellError {
|
||||
match e {
|
||||
craft_ods::CellError::Null => CellError::Null,
|
||||
craft_ods::CellError::Div0 => CellError::Div0,
|
||||
craft_ods::CellError::Value => CellError::Value,
|
||||
craft_ods::CellError::Ref => CellError::Ref,
|
||||
craft_ods::CellError::Name => CellError::Name,
|
||||
craft_ods::CellError::Num => CellError::Num,
|
||||
craft_ods::CellError::NA => CellError::NA,
|
||||
craft_ods::CellError::GettingData => CellError::GettingData,
|
||||
craft_ods::CellError::Spill => CellError::Spill,
|
||||
craft_ods::CellError::Calc => CellError::Calc,
|
||||
craft_ods::CellError::Blocked => CellError::Blocked,
|
||||
_ => CellError::Value,
|
||||
}
|
||||
let year: i32 = digits(date.get(..4)?)?.parse().ok()?;
|
||||
let month: u32 = digits(date.get(5..7)?)?.parse().ok()?;
|
||||
let day: u32 = digits(date.get(8..10)?)?.parse().ok()?;
|
||||
if !(1900..=9999).contains(&year) || !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) {
|
||||
return None;
|
||||
}
|
||||
let day = serial_from_ymd(DateSystem::D1900, year.into(), month.into(), day.into())?;
|
||||
let Some(time) = time else { return Some((day, "yyyy-mm-dd")) };
|
||||
let mut parts = time.split(':');
|
||||
let h = parts.next()?;
|
||||
let m = parts.next()?;
|
||||
let sec = parts.next()?;
|
||||
if parts.next().is_some() || h.len() != 2 || m.len() != 2 || sec.split('.').next()?.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
let h: u32 = digits(h)?.parse().ok()?;
|
||||
let m: u32 = digits(m)?.parse().ok()?;
|
||||
let sec = decimal(sec)?;
|
||||
if h >= 24 || m >= 60 || sec >= 60.0 {
|
||||
return None;
|
||||
}
|
||||
Some((day + (h as f64 * 3600.0 + m as f64 * 60.0 + sec) / 86400.0, "yyyy-mm-dd hh:mm:ss.000"))
|
||||
}
|
||||
|
||||
fn digits(s: &str) -> Option<&str> {
|
||||
(!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then_some(s)
|
||||
}
|
||||
fn decimal(s: &str) -> Option<f64> {
|
||||
match s.split_once('.') {
|
||||
Some((a, b)) => {
|
||||
digits(a)?;
|
||||
digits(b)?;
|
||||
}
|
||||
None => {
|
||||
digits(s)?;
|
||||
}
|
||||
}
|
||||
s.parse::<f64>().ok().filter(|n| n.is_finite())
|
||||
}
|
||||
|
||||
/// A bounded ISO day/time duration. Calendar years/months cannot be represented as days.
|
||||
fn parse_duration(s: &str) -> Option<f64> {
|
||||
let (negative, s) = s.strip_prefix('-').map_or((false, s), |s| (true, s));
|
||||
let mut rest = s.strip_prefix('P')?;
|
||||
let mut total = 0.0;
|
||||
let mut any = false;
|
||||
if let Some((days, tail)) = rest.split_once('D') {
|
||||
total += digits(days)?.parse::<f64>().ok()? * 86400.0;
|
||||
rest = tail;
|
||||
any = true;
|
||||
}
|
||||
if let Some(mut time) = rest.strip_prefix('T') {
|
||||
let mut time_any = false;
|
||||
for (unit, factor) in [('H', 3600.0), ('M', 60.0), ('S', 1.0)] {
|
||||
if let Some((n, tail)) = time.split_once(unit) {
|
||||
let value = if unit == 'S' { decimal(n)? } else { digits(n)?.parse::<f64>().ok()? };
|
||||
total += value * factor;
|
||||
time = tail;
|
||||
time_any = true;
|
||||
}
|
||||
}
|
||||
if !time.is_empty() || !time_any {
|
||||
return None;
|
||||
}
|
||||
any = true;
|
||||
} else if !rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let days = total / 86400.0;
|
||||
(any && days.is_finite() && days <= 2_958_465.0).then_some(if negative { -days } else { days })
|
||||
}
|
||||
|
||||
+159
-511
@@ -4,38 +4,131 @@
|
||||
|
||||
use crate::xml::El;
|
||||
|
||||
/// Deepest OMML nesting converted.
|
||||
/// Deepest OMML nesting marked.
|
||||
const MAX_DEPTH: usize = 64;
|
||||
/// Longest LaTeX the conversion produces before it gives up. `gridcraft_math::check` refuses a
|
||||
/// longer source anyway, so converting the rest of a wide or long equation would only spend time
|
||||
/// and memory on a hostile file.
|
||||
const MAX_OUT_BYTES: usize = gridcraft_math::MAX_SOURCE_BYTES;
|
||||
|
||||
/// The LaTeX for an `m:oMath` (or `m:oMathPara`) element, if every part is in the subset and the
|
||||
/// result lays out.
|
||||
pub fn to_latex(e: &El) -> Option<String> {
|
||||
let out = convert(e)?;
|
||||
if e.name != "oMathPara" && e.name != "oMath" {
|
||||
return None;
|
||||
}
|
||||
validate_conversion(e, 0, false, &mut (1 << 20))?;
|
||||
let mut xml = String::new();
|
||||
write_el(e, &mut xml);
|
||||
let math = craft_math::omml::read_str(&xml)?;
|
||||
let out = craft_math::math_latex::to_latex(&math.nodes);
|
||||
let out = out.trim().to_string();
|
||||
(!out.is_empty() && gridcraft_math::check(&out).is_ok()).then_some(out)
|
||||
}
|
||||
|
||||
/// The conversion itself, before the final check: `None` for a construct outside the subset, an
|
||||
/// equation nested past [`MAX_DEPTH`] or one whose LaTeX exceeds [`MAX_OUT_BYTES`].
|
||||
fn convert(e: &El) -> Option<String> {
|
||||
let mut out = String::new();
|
||||
match e.name.as_str() {
|
||||
"oMathPara" => {
|
||||
let maths: Vec<&El> = e.kids("oMath").collect();
|
||||
for (i, m) in maths.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(" \\\\ ");
|
||||
}
|
||||
seq(m, &mut out, 0)?;
|
||||
}
|
||||
// The shared reader is tolerant; this importer must fall back instead of losing
|
||||
// equation content. Bound escaped XML before serializing or descending further.
|
||||
fn validate_conversion(e: &El, depth: usize, property: bool, remaining: &mut usize) -> Option<()> {
|
||||
if depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let charge = e.name.len().checked_mul(2)?.checked_add(16)?.checked_add(e.text.len().checked_mul(6)?)?;
|
||||
*remaining = remaining.checked_sub(charge)?;
|
||||
for (key, value) in &e.attrs {
|
||||
*remaining = remaining.checked_sub(key.len().checked_add(value.len().checked_mul(6)?)?.checked_add(8)?)?;
|
||||
}
|
||||
let property = property || e.name.ends_with("Pr");
|
||||
if !property
|
||||
&& !matches!(
|
||||
e.name.as_str(),
|
||||
"oMath"
|
||||
| "oMathPara"
|
||||
| "r"
|
||||
| "t"
|
||||
| "f"
|
||||
| "num"
|
||||
| "den"
|
||||
| "rad"
|
||||
| "deg"
|
||||
| "e"
|
||||
| "sSup"
|
||||
| "sSub"
|
||||
| "sSubSup"
|
||||
| "sPre"
|
||||
| "sub"
|
||||
| "sup"
|
||||
| "nary"
|
||||
| "d"
|
||||
| "m"
|
||||
| "mr"
|
||||
| "eqArr"
|
||||
| "acc"
|
||||
| "bar"
|
||||
| "groupChr"
|
||||
| "limLow"
|
||||
| "limUpp"
|
||||
| "lim"
|
||||
| "func"
|
||||
| "fName"
|
||||
| "borderBox"
|
||||
| "phant"
|
||||
| "box"
|
||||
)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// These limits truncate in the shared reader rather than refusing the matrix.
|
||||
if (e.name == "m" && e.kids("mr").count() > 1000) || (e.name == "mr" && e.kids("e").count() > 64) {
|
||||
return None;
|
||||
}
|
||||
// The pinned emitter treats a literal caret as syntax. Preserve original text
|
||||
// rather than inventing a superscript; structural scripts remain supported.
|
||||
if e.name == "t" && e.text.contains('^') {
|
||||
return None;
|
||||
}
|
||||
for child in &e.children {
|
||||
validate_conversion(child, depth + 1, property, remaining)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn write_el(e: &El, out: &mut String) {
|
||||
out.push_str("<m:");
|
||||
out.push_str(&e.name);
|
||||
for (k, v) in &e.attrs {
|
||||
out.push(' ');
|
||||
if k == "val" {
|
||||
out.push_str("m:val");
|
||||
} else {
|
||||
out.push_str(k);
|
||||
}
|
||||
"oMath" => seq(e, &mut out, 0)?,
|
||||
_ => return None,
|
||||
out.push_str("=\"");
|
||||
push_xml_escaped(v, out);
|
||||
out.push('"');
|
||||
}
|
||||
if e.children.is_empty() && e.text.is_empty() {
|
||||
out.push_str("/>");
|
||||
return;
|
||||
}
|
||||
out.push('>');
|
||||
if !e.text.is_empty() {
|
||||
push_xml_escaped(&e.text, out);
|
||||
}
|
||||
for c in &e.children {
|
||||
write_el(c, out);
|
||||
}
|
||||
out.push_str("</m:");
|
||||
out.push_str(&e.name);
|
||||
out.push('>');
|
||||
}
|
||||
|
||||
fn push_xml_escaped(s: &str, out: &mut String) {
|
||||
for ch in s.chars() {
|
||||
match ch {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(ch),
|
||||
}
|
||||
}
|
||||
Some(out.trim().to_string())
|
||||
}
|
||||
|
||||
/// The first `m:oMath`/`m:oMathPara` under `e` (an `a14:m` element or a paragraph), searched to a
|
||||
@@ -178,35 +271,8 @@ fn mark_bytes(h: &mut u64, bytes: &[u8]) {
|
||||
}
|
||||
|
||||
/// Children in order, skipping property elements.
|
||||
fn seq(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
if depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
for c in &e.children {
|
||||
node(c, out, depth + 1)?;
|
||||
if out.len() > MAX_OUT_BYTES {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `{…}` around a child's contents (empty group when the child is missing).
|
||||
fn group(e: Option<&El>, out: &mut String, depth: usize) -> Option<()> {
|
||||
out.push('{');
|
||||
if let Some(e) = e {
|
||||
seq(e, out, depth)?;
|
||||
}
|
||||
out.push('}');
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The property elements and the properties in them that this converter reads, so the ones
|
||||
/// that decide what an equation says beyond its structure and text. [`body_marker`] hashes
|
||||
/// exactly these, and [`val`] and [`on`] read only these, so the two cannot drift: a property
|
||||
/// read here without a row in this table reads as absent, which the conversion tests show.
|
||||
const PROPERTIES: &[(&str, &[&str])] = &[
|
||||
("rPr", &["nor", "sty", "scr"]),
|
||||
("rPr", &["nor", "sty", "scr", "lit"]),
|
||||
("fPr", &["type"]),
|
||||
("radPr", &["degHide"]),
|
||||
("naryPr", &["chr", "limLoc", "subHide", "supHide"]),
|
||||
@@ -221,446 +287,6 @@ fn read_properties(pr: &str) -> &'static [&'static str] {
|
||||
PROPERTIES.iter().find(|(name, _)| *name == pr).map_or(&[], |(_, names)| names)
|
||||
}
|
||||
|
||||
/// The `val` of property `name` in the property element `props`, when the converter reads it.
|
||||
fn val<'a>(props: Option<&'a El>, name: &str) -> Option<&'a str> {
|
||||
props.filter(|p| read_properties(&p.name).contains(&name)).and_then(|p| p.child(name)).and_then(|c| c.attr("val"))
|
||||
}
|
||||
|
||||
/// Whether the switch `name` in the property element `props` is on, when the converter reads it.
|
||||
fn on(props: Option<&El>, name: &str) -> bool {
|
||||
props
|
||||
.filter(|p| read_properties(&p.name).contains(&name))
|
||||
.and_then(|p| p.child(name))
|
||||
.is_some_and(|c| c.attr("val").is_none_or(|v| v == "1" || v == "on" || v == "true"))
|
||||
}
|
||||
|
||||
/// LaTeX for one character of a math run.
|
||||
fn char_latex(c: char) -> Option<&'static str> {
|
||||
Some(match c {
|
||||
'α' => "\\alpha ",
|
||||
'β' => "\\beta ",
|
||||
'γ' => "\\gamma ",
|
||||
'δ' => "\\delta ",
|
||||
'ε' => "\\varepsilon ",
|
||||
'ϵ' => "\\epsilon ",
|
||||
'ζ' => "\\zeta ",
|
||||
'η' => "\\eta ",
|
||||
'θ' => "\\theta ",
|
||||
'ϑ' => "\\vartheta ",
|
||||
'ι' => "\\iota ",
|
||||
'κ' => "\\kappa ",
|
||||
'λ' => "\\lambda ",
|
||||
'μ' => "\\mu ",
|
||||
'ν' => "\\nu ",
|
||||
'ξ' => "\\xi ",
|
||||
'π' => "\\pi ",
|
||||
'ρ' => "\\rho ",
|
||||
'σ' => "\\sigma ",
|
||||
'τ' => "\\tau ",
|
||||
'υ' => "\\upsilon ",
|
||||
'φ' => "\\varphi ",
|
||||
'ϕ' => "\\phi ",
|
||||
'χ' => "\\chi ",
|
||||
'ψ' => "\\psi ",
|
||||
'ω' => "\\omega ",
|
||||
'Γ' => "\\Gamma ",
|
||||
'Δ' => "\\Delta ",
|
||||
'Θ' => "\\Theta ",
|
||||
'Λ' => "\\Lambda ",
|
||||
'Ξ' => "\\Xi ",
|
||||
'Π' => "\\Pi ",
|
||||
'Σ' => "\\Sigma ",
|
||||
'Υ' => "\\Upsilon ",
|
||||
'Φ' => "\\Phi ",
|
||||
'Ψ' => "\\Psi ",
|
||||
'Ω' => "\\Omega ",
|
||||
'±' => "\\pm ",
|
||||
'∓' => "\\mp ",
|
||||
'×' => "\\times ",
|
||||
'÷' => "\\div ",
|
||||
'⋅' | '·' => "\\cdot ",
|
||||
'−' => "-",
|
||||
'≤' => "\\le ",
|
||||
'≥' => "\\ge ",
|
||||
'≠' => "\\ne ",
|
||||
'≈' => "\\approx ",
|
||||
'≡' => "\\equiv ",
|
||||
'∼' => "\\sim ",
|
||||
'∝' => "\\propto ",
|
||||
'∞' => "\\infty ",
|
||||
'∂' => "\\partial ",
|
||||
'∇' => "\\nabla ",
|
||||
'∀' => "\\forall ",
|
||||
'∃' => "\\exists ",
|
||||
'∈' => "\\in ",
|
||||
'∉' => "\\notin ",
|
||||
'⊂' => "\\subset ",
|
||||
'⊆' => "\\subseteq ",
|
||||
'⊃' => "\\supset ",
|
||||
'∪' => "\\cup ",
|
||||
'∩' => "\\cap ",
|
||||
'∅' => "\\emptyset ",
|
||||
'→' => "\\to ",
|
||||
'←' => "\\leftarrow ",
|
||||
'⇒' => "\\Rightarrow ",
|
||||
'⇔' => "\\Leftrightarrow ",
|
||||
'…' => "\\ldots ",
|
||||
'⋯' => "\\cdots ",
|
||||
'∘' => "\\circ ",
|
||||
'{' => "\\{",
|
||||
'}' => "\\}",
|
||||
'%' => "\\%",
|
||||
'#' => "\\#",
|
||||
'&' => "\\&",
|
||||
'$' => "\\$",
|
||||
'_' => "\\_",
|
||||
'\\' => "\\backslash ",
|
||||
'~' => "\\sim ",
|
||||
'^' => "\\hat{}",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn run_text(r: &El) -> String {
|
||||
r.kids("t").map(|t| t.text.as_str()).collect()
|
||||
}
|
||||
|
||||
/// Appends `s` escaped for `\text{…}`; `None` once the LaTeX exceeds [`MAX_OUT_BYTES`], checked
|
||||
/// after every character so that a long run never expands in full.
|
||||
fn escape_text(s: &str, out: &mut String) -> Option<()> {
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'{' | '}' | '%' | '#' | '&' | '$' | '_' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'\\' => out.push_str("\\textbackslash "),
|
||||
'^' | '~' => out.push(' '),
|
||||
c => out.push(c),
|
||||
}
|
||||
if out.len() > MAX_OUT_BYTES {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Known operator names written upright in a run (`sin`, `log`, `lim`).
|
||||
const FUNCTIONS: &[&str] = &[
|
||||
"sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh", "log", "ln", "lg", "exp", "lim", "max", "min",
|
||||
"sup", "inf", "det", "gcd", "deg", "dim", "ker", "arg", "Pr", "liminf", "limsup",
|
||||
];
|
||||
|
||||
fn run(r: &El, out: &mut String) -> Option<()> {
|
||||
let text = run_text(r);
|
||||
if text.is_empty() {
|
||||
return Some(());
|
||||
}
|
||||
let rpr = r.child("rPr");
|
||||
if on(rpr, "nor") {
|
||||
out.push_str("\\text{");
|
||||
escape_text(&text, out)?;
|
||||
out.push('}');
|
||||
return Some(());
|
||||
}
|
||||
let plain = val(rpr, "sty") == Some("p");
|
||||
if plain && FUNCTIONS.contains(&text.trim()) {
|
||||
out.push('\\');
|
||||
out.push_str(text.trim());
|
||||
out.push(' ');
|
||||
return Some(());
|
||||
}
|
||||
let wrap = match (val(rpr, "scr"), val(rpr, "sty")) {
|
||||
(Some("double-struck"), _) => Some("\\mathbb{"),
|
||||
(Some("script"), _) => Some("\\mathcal{"),
|
||||
(Some("fraktur"), _) => Some("\\mathfrak{"),
|
||||
(Some("sans-serif"), _) => Some("\\mathsf{"),
|
||||
(Some("monospace"), _) => Some("\\mathtt{"),
|
||||
(_, Some("b")) => Some("\\mathbf{"),
|
||||
(_, Some("bi")) => Some("\\boldsymbol{"),
|
||||
(_, Some("p")) if text.chars().any(|c| c.is_alphabetic()) => Some("\\mathrm{"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(w) = wrap {
|
||||
out.push_str(w);
|
||||
}
|
||||
for c in text.chars() {
|
||||
match char_latex(c) {
|
||||
Some(l) => out.push_str(l),
|
||||
None => out.push(c),
|
||||
}
|
||||
// Checked per character, not from the run's byte length: a character may map to a
|
||||
// longer macro or a shorter sign, so only the LaTeX produced counts.
|
||||
if out.len() > MAX_OUT_BYTES {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if wrap.is_some() {
|
||||
out.push('}');
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// A delimiter character as a `\left`/`\right` argument.
|
||||
fn delim(c: Option<&str>, default: &str) -> String {
|
||||
let c = c.unwrap_or(default);
|
||||
match c {
|
||||
"" => ".".into(),
|
||||
"{" => "\\{".into(),
|
||||
"}" => "\\}".into(),
|
||||
"⟨" | "〈" => "\\langle".into(),
|
||||
"⟩" | "〉" => "\\rangle".into(),
|
||||
"⌊" => "\\lfloor".into(),
|
||||
"⌋" => "\\rfloor".into(),
|
||||
"⌈" => "\\lceil".into(),
|
||||
"⌉" => "\\rceil".into(),
|
||||
"‖" => "\\|".into(),
|
||||
"∣" => "|".into(),
|
||||
other => other.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn nary_op(chr: &str) -> Option<&'static str> {
|
||||
Some(match chr {
|
||||
"∑" => "\\sum",
|
||||
"∏" => "\\prod",
|
||||
"∐" => "\\coprod",
|
||||
"∫" => "\\int",
|
||||
"∬" => "\\iint",
|
||||
"∭" => "\\iiint",
|
||||
"∮" => "\\oint",
|
||||
"⋃" => "\\bigcup",
|
||||
"⋂" => "\\bigcap",
|
||||
"⋁" => "\\bigvee",
|
||||
"⋀" => "\\bigwedge",
|
||||
"⨁" => "\\bigoplus",
|
||||
"⨂" => "\\bigotimes",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn accent(chr: &str) -> Option<&'static str> {
|
||||
Some(match chr {
|
||||
"\u{0302}" | "^" => "\\hat",
|
||||
"\u{030C}" => "\\check",
|
||||
"\u{0303}" | "~" => "\\tilde",
|
||||
"\u{0301}" => "\\acute",
|
||||
"\u{0300}" => "\\grave",
|
||||
"\u{0307}" => "\\dot",
|
||||
"\u{0308}" => "\\ddot",
|
||||
"\u{0306}" => "\\breve",
|
||||
"\u{0305}" | "\u{0304}" | "¯" => "\\bar",
|
||||
"\u{20D7}" | "→" => "\\vec",
|
||||
"\u{20D6}" => "\\overleftarrow",
|
||||
"\u{030A}" => "\\mathring",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn node(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
if depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
match e.name.as_str() {
|
||||
// Properties and run-level DrawingML are not content.
|
||||
n if n.ends_with("Pr") => {}
|
||||
"r" => run(e, out)?,
|
||||
"f" => fraction(e, out, depth)?,
|
||||
"rad" => radical(e, out, depth)?,
|
||||
"sSup" | "sSub" | "sSubSup" => scripts(e, out, depth)?,
|
||||
"nary" => nary(e, out, depth)?,
|
||||
"d" => delimiters(e, out, depth)?,
|
||||
"m" => matrix(e, out, depth)?,
|
||||
"eqArr" => equation_array(e, out, depth)?,
|
||||
"acc" => {
|
||||
out.push_str(accent(val(e.child("accPr"), "chr").unwrap_or("\u{0302}"))?);
|
||||
group(e.child("e"), out, depth)?;
|
||||
}
|
||||
"bar" => {
|
||||
out.push_str(if val(e.child("barPr"), "pos") == Some("top") { "\\overline" } else { "\\underline" });
|
||||
group(e.child("e"), out, depth)?;
|
||||
}
|
||||
"groupChr" => group_char(e, out, depth)?,
|
||||
"limLow" | "limUpp" => limit(e, out, depth)?,
|
||||
"func" => {
|
||||
seq(e.child("fName")?, out, depth)?;
|
||||
out.push(' ');
|
||||
group(e.child("e"), out, depth)?;
|
||||
}
|
||||
"borderBox" => {
|
||||
out.push_str("\\boxed");
|
||||
group(e.child("e"), out, depth)?;
|
||||
}
|
||||
"phant" => {
|
||||
out.push_str("\\phantom");
|
||||
group(e.child("e"), out, depth)?;
|
||||
}
|
||||
"box" => group(e.child("e"), out, depth)?,
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `m:f`: a fraction, or a binomial-style stack without a bar.
|
||||
fn fraction(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
if val(e.child("fPr"), "type") == Some("noBar") {
|
||||
out.push_str("\\genfrac{}{}{0pt}{}");
|
||||
} else {
|
||||
out.push_str("\\frac");
|
||||
}
|
||||
group(e.child("num"), out, depth)?;
|
||||
group(e.child("den"), out, depth)
|
||||
}
|
||||
|
||||
/// `m:rad`: a square root, or a root with a degree.
|
||||
fn radical(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
let hide = on(e.child("radPr"), "degHide");
|
||||
match e.child("deg").filter(|d| !hide && !d.children.is_empty()) {
|
||||
Some(d) => {
|
||||
out.push_str("\\sqrt[");
|
||||
seq(d, out, depth)?;
|
||||
out.push(']');
|
||||
}
|
||||
None => out.push_str("\\sqrt"),
|
||||
}
|
||||
group(e.child("e"), out, depth)
|
||||
}
|
||||
|
||||
/// `m:sSup`, `m:sSub`, `m:sSubSup`: a base with scripts.
|
||||
fn scripts(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
group(e.child("e"), out, depth)?;
|
||||
if let Some(sub) = e.child("sub") {
|
||||
out.push('_');
|
||||
group(Some(sub), out, depth)?;
|
||||
}
|
||||
if let Some(sup) = e.child("sup") {
|
||||
out.push('^');
|
||||
group(Some(sup), out, depth)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `m:nary`: a large operator with its limits and operand.
|
||||
fn nary(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
let p = e.child("naryPr");
|
||||
let op = nary_op(val(p, "chr").unwrap_or("∫"))?;
|
||||
out.push_str(op);
|
||||
if val(p, "limLoc") == Some("undOvr") && op.contains("int") {
|
||||
out.push_str("\\limits");
|
||||
}
|
||||
if !on(p, "subHide") {
|
||||
out.push('_');
|
||||
group(e.child("sub"), out, depth)?;
|
||||
}
|
||||
if !on(p, "supHide") {
|
||||
out.push('^');
|
||||
group(e.child("sup"), out, depth)?;
|
||||
}
|
||||
out.push(' ');
|
||||
group(e.child("e"), out, depth)
|
||||
}
|
||||
|
||||
/// `m:d`: delimiters around one or more parts, with a separator between them.
|
||||
fn delimiters(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
let p = e.child("dPr");
|
||||
out.push_str("\\left");
|
||||
out.push_str(&delim(val(p, "begChr"), "("));
|
||||
out.push(' ');
|
||||
let sep = delim(val(p, "sepChr"), "|");
|
||||
for (i, part) in e.kids("e").enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(" \\middle");
|
||||
out.push_str(&sep);
|
||||
out.push(' ');
|
||||
}
|
||||
seq(part, out, depth)?;
|
||||
}
|
||||
out.push_str(" \\right");
|
||||
out.push_str(&delim(val(p, "endChr"), ")"));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `m:m`: a matrix, row by row.
|
||||
fn matrix(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
out.push_str("\\begin{matrix}");
|
||||
for (i, row) in e.kids("mr").enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(" \\\\ ");
|
||||
}
|
||||
for (k, cell) in row.kids("e").enumerate() {
|
||||
if k > 0 {
|
||||
out.push_str(" & ");
|
||||
}
|
||||
seq(cell, out, depth)?;
|
||||
}
|
||||
}
|
||||
out.push_str("\\end{matrix}");
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `m:eqArr`: equations stacked one per row.
|
||||
fn equation_array(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
out.push_str("\\begin{gathered}");
|
||||
for (i, row) in e.kids("e").enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(" \\\\ ");
|
||||
}
|
||||
seq(row, out, depth)?;
|
||||
}
|
||||
out.push_str("\\end{gathered}");
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Effective brace orientation, including the character default and its precedence over position.
|
||||
fn group_char_is_over(e: &El) -> bool {
|
||||
let p = e.child("groupChrPr");
|
||||
match val(p, "chr").unwrap_or("\u{23DF}") {
|
||||
"\u{23DE}" => true,
|
||||
"\u{23DF}" => false,
|
||||
_ => val(p, "pos") == Some("top"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `m:groupChr`: a brace over or under its content.
|
||||
fn group_char(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
out.push_str(if group_char_is_over(e) { "\\overbrace" } else { "\\underbrace" });
|
||||
group(e.child("e"), out, depth)
|
||||
}
|
||||
|
||||
/// `m:limLow`, `m:limUpp`: a limit under or over its base.
|
||||
fn limit(e: &El, out: &mut String, depth: usize) -> Option<()> {
|
||||
let low = e.name == "limLow";
|
||||
let base = e.child("e");
|
||||
// A function name with a limit (lim, max) takes it as a subscript with \limits.
|
||||
let base_is_fn = base.is_some_and(|b| {
|
||||
let t: String = b.kids("r").map(run_text).collect();
|
||||
b.children.iter().all(|c| c.name == "r") && FUNCTIONS.contains(&t.trim())
|
||||
});
|
||||
// A brace alone under the limit is a labelled brace, as `gridcraft_math::to_omml` writes
|
||||
// `\underbrace{x}_{n}` and `\overbrace{x}^{n}`: the label is the brace's own script, below
|
||||
// for an underbrace and above for an overbrace. An opposite-side limit keeps its placement.
|
||||
let brace = base
|
||||
.and_then(|b| {
|
||||
let mut content = b.children.iter().filter(|c| !c.name.ends_with("Pr"));
|
||||
content.next().filter(|c| c.name == "groupChr" && content.next().is_none())
|
||||
})
|
||||
.filter(|brace| low != group_char_is_over(brace));
|
||||
if base_is_fn {
|
||||
seq(base?, out, depth)?;
|
||||
out.push_str(if low { "\\limits_" } else { "\\limits^" });
|
||||
group(e.child("lim"), out, depth)?;
|
||||
} else if let Some(brace) = brace {
|
||||
group_char(brace, out, depth + 1)?;
|
||||
out.push(if low { '_' } else { '^' });
|
||||
group(e.child("lim"), out, depth)?;
|
||||
} else {
|
||||
out.push_str(if low { "\\underset" } else { "\\overset" });
|
||||
group(e.child("lim"), out, depth)?;
|
||||
group(base, out, depth)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -673,6 +299,29 @@ mod tests {
|
||||
to_latex(&el(xml))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversion_does_not_accept_a_partial_equation() {
|
||||
assert_eq!(latex("<m:r><m:t>x</m:t></m:r><m:unknown/>"), None);
|
||||
assert_eq!(
|
||||
latex(
|
||||
"<m:r><m:t>x</m:t></m:r><mc:AlternateContent xmlns:mc=\"mc\"><mc:Fallback><m:r><m:t>y</m:t></m:r></mc:Fallback></mc:AlternateContent>"
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(latex("<m:r><m:t>x^2</m:t></m:r>"), None);
|
||||
assert_eq!(latex("<m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e><m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>").as_deref(), Some("{x}^{2}"));
|
||||
let cells = "<m:e><m:r><m:t>x</m:t></m:r></m:e>".repeat(65);
|
||||
assert_eq!(latex(&format!("<m:m><m:mr>{cells}</m:mr></m:m>")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_run_property_invalidates_the_saved_source_marker() {
|
||||
let plain = el("<m:r><m:t>x</m:t></m:r>");
|
||||
let literal = el("<m:r><m:rPr><m:lit/></m:rPr><m:t>x</m:t></m:r>");
|
||||
assert_ne!(body_marker(&plain), body_marker(&literal));
|
||||
assert_eq!(body_marker(&plain), body_marker(&plain.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_subset_reads_back() {
|
||||
assert_eq!(latex("<m:r><m:t>x+1</m:t></m:r>").as_deref(), Some("x+1"));
|
||||
@@ -685,13 +334,13 @@ mod tests {
|
||||
let sum = latex(
|
||||
"<m:nary><m:naryPr><m:chr m:val=\"∑\"/><m:limLoc m:val=\"undOvr\"/></m:naryPr><m:sub><m:r><m:t>i=1</m:t></m:r></m:sub><m:sup><m:r><m:t>n</m:t></m:r></m:sup><m:e><m:r><m:t>i</m:t></m:r></m:e></m:nary>",
|
||||
);
|
||||
assert_eq!(sum.as_deref(), Some("\\sum_{i=1}^{n} {i}"));
|
||||
assert_eq!(sum.as_deref(), Some("\\sum\\limits_{i=1}^{n} {i}"));
|
||||
// An integral without a character, with hidden limits.
|
||||
assert_eq!(latex("<m:nary><m:naryPr><m:subHide m:val=\"1\"/><m:supHide m:val=\"1\"/></m:naryPr><m:sub/><m:sup/><m:e><m:r><m:t>f</m:t></m:r></m:e></m:nary>").as_deref(), Some("\\int {f}"));
|
||||
let m = latex(
|
||||
"<m:d><m:dPr><m:begChr m:val=\"[\"/><m:endChr m:val=\"]\"/></m:dPr><m:e><m:m><m:mr><m:e><m:r><m:t>1</m:t></m:r></m:e><m:e><m:r><m:t>0</m:t></m:r></m:e></m:mr><m:mr><m:e><m:r><m:t>0</m:t></m:r></m:e><m:e><m:r><m:t>1</m:t></m:r></m:e></m:mr></m:m></m:e></m:d>",
|
||||
);
|
||||
assert_eq!(m.as_deref(), Some("\\left[ \\begin{matrix}1 & 0 \\\\ 0 & 1\\end{matrix} \\right]"));
|
||||
assert_eq!(m.as_deref(), Some("\\left[\\begin{matrix}1&0\\\\0&1\\end{matrix}\\right]"));
|
||||
assert_eq!(latex("<m:r><m:rPr><m:sty m:val=\"p\"/></m:rPr><m:t>sin</m:t></m:r><m:r><m:t>x</m:t></m:r>").as_deref(), Some("\\sin x"));
|
||||
assert_eq!(latex("<m:r><m:rPr><m:scr m:val=\"double-struck\"/></m:rPr><m:t>R</m:t></m:r>").as_deref(), Some("\\mathbb{R}"));
|
||||
assert_eq!(latex("<m:r><m:rPr><m:nor/></m:rPr><m:t>if {x}</m:t></m:r>").as_deref(), Some("\\text{if \\{x\\}}"));
|
||||
@@ -703,9 +352,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn what_is_outside_the_subset_is_none() {
|
||||
assert_eq!(latex("<m:sPre><m:sub/><m:sup/><m:e/></m:sPre>"), None);
|
||||
assert_eq!(latex("<m:sPre><m:sub/><m:sup/><m:e/></m:sPre>").as_deref(), Some("{}_{}^{}{}"));
|
||||
assert_eq!(latex(""), None, "an empty equation is not maths");
|
||||
assert_eq!(latex("<m:nary><m:naryPr><m:chr m:val=\"☃\"/></m:naryPr><m:e/></m:nary>"), None);
|
||||
assert_eq!(latex("<m:nary><m:naryPr><m:chr m:val=\"☃\"/></m:naryPr><m:e/></m:nary>").as_deref(), Some("☃ {}"));
|
||||
// Deep nesting stops instead of recursing without bound.
|
||||
let deep = format!("{}<m:r><m:t>x</m:t></m:r>{}", "<m:box><m:e>".repeat(100), "</m:e></m:box>".repeat(100));
|
||||
assert_eq!(latex(&deep), None);
|
||||
@@ -719,22 +368,21 @@ mod tests {
|
||||
// refusing it, so the caller falls back to the writer's text in bounded time.
|
||||
let wide = el(&"<m:r><m:t>x</m:t></m:r>".repeat(100_000));
|
||||
let start = std::time::Instant::now();
|
||||
assert_eq!(convert(&wide), None);
|
||||
assert_eq!(to_latex(&wide), None);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
// One run whose text alone is past the cap is refused before it is escaped (each
|
||||
// backslash would otherwise grow to `\textbackslash `).
|
||||
let long = el(&format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{}</m:t></m:r>", "\\".repeat(MAX_OUT_BYTES + 1)));
|
||||
assert_eq!(convert(&long), None);
|
||||
let long = el(&format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{}</m:t></m:r>", "\\".repeat(gridcraft_math::MAX_SOURCE_BYTES + 1)));
|
||||
assert_eq!(to_latex(&long), None);
|
||||
// Groups count the braces they add even when no run adds text.
|
||||
let groups = el(&"<m:box><m:e/></m:box>".repeat(MAX_OUT_BYTES / 2 + 1));
|
||||
assert_eq!(convert(&groups), None);
|
||||
let groups = el(&"<m:box><m:e/></m:box>".repeat(gridcraft_math::MAX_SOURCE_BYTES / 2 + 1));
|
||||
assert_eq!(to_latex(&groups), None);
|
||||
// At the cap the equation still reads back, and the cap counts the LaTeX produced, not
|
||||
// the run's bytes: a minus sign (three bytes of UTF-8) becomes a one-byte `-`.
|
||||
let at_cap = el(&"<m:r><m:t>x</m:t></m:r>".repeat(MAX_OUT_BYTES));
|
||||
assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(MAX_OUT_BYTES));
|
||||
let minus = el(&format!("<m:r><m:t>{}</m:t></m:r>", "\u{2212}".repeat(MAX_OUT_BYTES)));
|
||||
assert_eq!(to_latex(&minus), Some("-".repeat(MAX_OUT_BYTES)));
|
||||
let at_cap = el(&"<m:r><m:t>x</m:t></m:r>".repeat(gridcraft_math::MAX_SOURCE_BYTES));
|
||||
assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(gridcraft_math::MAX_SOURCE_BYTES));
|
||||
let minus = el(&format!("<m:r><m:t>{}</m:t></m:r>", "\u{2212}".repeat(gridcraft_math::MAX_SOURCE_BYTES)));
|
||||
assert_eq!(to_latex(&minus), Some("-".repeat(gridcraft_math::MAX_SOURCE_BYTES)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -764,17 +412,17 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_limit_on_the_opposite_side_of_a_brace_keeps_its_placement() {
|
||||
for (properties, brace, opposite, same, script) in [
|
||||
(r#"<m:chr m:val="⏟"/><m:pos m:val="top"/>"#, "underbrace", "limUpp", "limLow", '_'),
|
||||
(r#"<m:chr m:val="⏞"/><m:pos m:val="bot"/>"#, "overbrace", "limLow", "limUpp", '^'),
|
||||
(r#"<m:pos m:val="top"/>"#, "underbrace", "limUpp", "limLow", '_'),
|
||||
(r#"<m:chr m:val="?"/><m:pos m:val="top"/>"#, "overbrace", "limLow", "limUpp", '^'),
|
||||
for (properties, brace, opposite, same) in [
|
||||
(r#"<m:chr m:val="⏟"/><m:pos m:val="top"/>"#, "overbrace", "limUpp", "limLow"),
|
||||
(r#"<m:chr m:val="⏞"/><m:pos m:val="bot"/>"#, "underbrace", "limLow", "limUpp"),
|
||||
(r#"<m:pos m:val="top"/>"#, "overbrace", "limUpp", "limLow"),
|
||||
(r#"<m:chr m:val="?"/><m:pos m:val="top"/>"#, "overbrace", "limLow", "limUpp"),
|
||||
] {
|
||||
let base = format!("<m:groupChr><m:groupChrPr>{properties}</m:groupChrPr><m:e><m:r><m:t>x</m:t></m:r></m:e></m:groupChr>");
|
||||
let limit = |kind: &str| format!("<m:{kind}><m:e>{base}</m:e><m:lim><m:r><m:t>n</m:t></m:r></m:lim></m:{kind}>");
|
||||
let placement = if opposite == "limLow" { "underset" } else { "overset" };
|
||||
assert_eq!(latex(&limit(opposite)), Some(format!("\\{placement}{{n}}{{\\{brace}{{x}}}}")), "{properties}");
|
||||
assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{script}{{n}}")), "{properties}");
|
||||
let script = |kind: &str| if kind == "limUpp" { '^' } else { '_' };
|
||||
assert_eq!(latex(&limit(opposite)), Some(format!("\\{brace}{{x}}{}{{n}}", script(opposite))), "{properties}");
|
||||
assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{}{{n}}", script(same))), "{properties}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
CellRef, Ctx, DateSystem, El, HashMap, IoError, MAX_FIELDS, PivotCalcField, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotLayout,
|
||||
PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, quote_sheet, same,
|
||||
PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, quote_sheet,
|
||||
};
|
||||
|
||||
// ================================================================ reading
|
||||
@@ -118,8 +118,9 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
|
||||
};
|
||||
let sys = cx.date_system;
|
||||
let mut fields = Vec::new();
|
||||
let mut truncated = false;
|
||||
if let Some(cf) = x.child("cacheFields") {
|
||||
for f in cf.kids("cacheField").take(MAX_FIELDS) {
|
||||
for f in capped(cf.kids("cacheField"), &mut truncated) {
|
||||
let items = f.child("sharedItems").map(|si| si.children.iter().map(|e| item_label_el(e, sys)).collect()).unwrap_or_default();
|
||||
let group = f.child("fieldGroup").map(|g| {
|
||||
let base = g.attr_u32("base").map(|b| b as usize);
|
||||
@@ -142,6 +143,9 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option<CacheIn>
|
||||
});
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
cx.warn(format!("{part}: cache fields past {MAX_FIELDS} were dropped; its PivotTables may be incomplete"));
|
||||
}
|
||||
if fields.is_empty() {
|
||||
cx.warn("a PivotTable's cache has no fields; kept as plain cells");
|
||||
return None;
|
||||
@@ -231,14 +235,25 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
cx.warn(format!("PivotTable \"{}\" has no valid location; kept as plain cells", pt.name));
|
||||
return None;
|
||||
};
|
||||
let pfs: Vec<&El> = x.child("pivotFields").map(|p| p.kids("pivotField").collect()).unwrap_or_default();
|
||||
// Field lists are capped, and a field is used once (Excel puts a field on one axis, once):
|
||||
// each use walks the field's items.
|
||||
// A list cut at the cap is reported, so an incomplete PivotTable can be told apart.
|
||||
let mut truncated = false;
|
||||
let pfs: Vec<&El> = x.child("pivotFields").map(|p| capped(p.kids("pivotField"), &mut truncated)).unwrap_or_default();
|
||||
let pf = |i: usize| pfs.get(i).copied();
|
||||
let idx_list = |name: &str, attr: &str| -> Vec<i64> {
|
||||
x.child(name).map(|e| e.children.iter().filter_map(|f| f.attr_i64(attr)).collect()).unwrap_or_default()
|
||||
let mut used_fields = std::collections::HashSet::new();
|
||||
let mut idx_list = |name: &str, attr: &str| -> Vec<i64> {
|
||||
x.child(name)
|
||||
.map(|e| capped(e.children.iter().filter_map(|f| f.attr_i64(attr)).filter(|&i| i < 0 || used_fields.insert(i)), &mut truncated))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let row_x = idx_list("rowFields", "x");
|
||||
let col_x = idx_list("colFields", "x");
|
||||
let pages: Vec<&El> = x.child("pageFields").map(|p| p.kids("pageField").collect()).unwrap_or_default();
|
||||
let mut page_fields = std::collections::HashSet::new();
|
||||
let pages: Vec<&El> = x
|
||||
.child("pageFields")
|
||||
.map(|p| capped(p.kids("pageField").filter(|f| f.attr_i64("fld").is_none_or(|i| page_fields.insert(i))), &mut truncated))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Layout from the first axis field (pivotField defaults: compact and outline on).
|
||||
let first_axis = row_x.iter().chain(col_x.iter()).find(|i| **i >= 0).and_then(|i| pf(*i as usize));
|
||||
@@ -268,8 +283,11 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
|
||||
let mut filters: Vec<PivotFilter> = Vec::new();
|
||||
|
||||
// Lower-cased names of the fields already filtered on an axis, the first of which wins (as
|
||||
// `same` compares them): scanning the filters for each field would be quadratic.
|
||||
let mut axis_filtered: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
// (fields, position of Σ Values (`-2`) among them)
|
||||
let axis = |cx: &mut Ctx<'_>, list: &[i64], filters: &mut Vec<PivotFilter>| -> (Vec<PivotField>, Option<usize>) {
|
||||
let mut axis = |cx: &mut Ctx<'_>, list: &[i64], filters: &mut Vec<PivotFilter>| -> (Vec<PivotField>, Option<usize>) {
|
||||
let mut v = Vec::new();
|
||||
let mut values_at = None;
|
||||
for &i in list {
|
||||
@@ -282,7 +300,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
}
|
||||
let i = i as usize;
|
||||
let Some((name, group)) = field_ref(cx, cache, i) else { continue };
|
||||
let labels = cache.fields.get(i).map(|f| f.labels().to_vec()).unwrap_or_default();
|
||||
let labels: &[String] = cache.fields.get(i).map(|f| f.labels()).unwrap_or(&[]);
|
||||
let mut f = PivotField { source_col: name.clone(), date_group: group, sort: PivotSort::None, collapsed_items: vec![] };
|
||||
if let Some(e) = pf(i) {
|
||||
f.sort = match e.attr("sortType") {
|
||||
@@ -293,11 +311,9 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
let items = items_of(e);
|
||||
let lab = |it: &El| it.attr_u32("x").and_then(|k| labels.get(k as usize)).cloned();
|
||||
f.collapsed_items = items.iter().filter(|it| !it.flag("sd", true)).filter_map(|it| lab(it)).collect();
|
||||
if items.iter().any(|it| it.flag("h", false)) {
|
||||
if items.iter().any(|it| it.flag("h", false)) && axis_filtered.insert(name.to_lowercase()) {
|
||||
let shown: Vec<String> = items.iter().filter(|it| !it.flag("h", false)).filter_map(|it| lab(it)).collect();
|
||||
if !filters.iter().any(|ff| same(&ff.source_col, &name)) {
|
||||
filters.push(PivotFilter { source_col: name.clone(), selected: Some(shown) });
|
||||
}
|
||||
filters.push(PivotFilter { source_col: name.clone(), selected: Some(shown) });
|
||||
}
|
||||
}
|
||||
v.push(f);
|
||||
@@ -308,7 +324,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
for p in &pages {
|
||||
let Some(i) = p.attr_i64("fld").filter(|i| *i >= 0).map(|i| i as usize) else { continue };
|
||||
let Some((name, _)) = field_ref(cx, cache, i) else { continue };
|
||||
let labels = cache.fields.get(i).map(|f| f.labels().to_vec()).unwrap_or_default();
|
||||
let labels: &[String] = cache.fields.get(i).map(|f| f.labels()).unwrap_or(&[]);
|
||||
let selected = if let Some(k) = p.attr_u32("item") {
|
||||
labels.get(k as usize).map(|l| vec![l.clone()])
|
||||
} else {
|
||||
@@ -341,7 +357,8 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
|
||||
// Values.
|
||||
if let Some(df) = x.child("dataFields") {
|
||||
for d in df.kids("dataField") {
|
||||
truncated |= df.kids("dataField").nth(MAX_FIELDS).is_some();
|
||||
for d in df.kids("dataField").take(MAX_FIELDS) {
|
||||
let Some(i) = d.attr_u32("fld").map(|i| i as usize) else { continue };
|
||||
let Some(f) = cache.fields.get(i) else { continue };
|
||||
let func = match d.attr("subtotal") {
|
||||
@@ -382,11 +399,13 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
}
|
||||
}
|
||||
|
||||
// Calculated fields of the cache (each PivotTable on it can use them).
|
||||
// Calculated fields of the cache (each PivotTable on it can use them); the first of a
|
||||
// lower-cased name wins, looked up in a set rather than by scanning the fields kept so far.
|
||||
let mut calc_names: std::collections::HashSet<String> = pt.calculated_fields.iter().map(|c| c.name.to_lowercase()).collect();
|
||||
for f in &cache.fields {
|
||||
if let Some(formula) = &f.formula
|
||||
&& !f.name.trim().is_empty()
|
||||
&& !pt.calculated_fields.iter().any(|c| same(&c.name, &f.name))
|
||||
&& calc_names.insert(f.name.to_lowercase())
|
||||
{
|
||||
let formula = formula.trim();
|
||||
let formula = if formula.starts_with('=') { formula.to_string() } else { format!("={formula}") };
|
||||
@@ -394,8 +413,21 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option<Pivo
|
||||
}
|
||||
}
|
||||
|
||||
if truncated {
|
||||
cx.warn(format!("PivotTable \"{}\": field lists past {MAX_FIELDS} entries were dropped; the table is incomplete", pt.name));
|
||||
}
|
||||
pt.anchor = loc.start;
|
||||
let above = if pages.is_empty() { 0 } else { pages.len() as u32 + 1 };
|
||||
pt.last_range = Some(RangeRef::new(CellRef::new(loc.start.row.saturating_sub(above), loc.start.col), loc.end));
|
||||
Some(pt)
|
||||
}
|
||||
|
||||
/// The first [`MAX_FIELDS`] items; sets `truncated` when there were more.
|
||||
fn capped<T>(items: impl Iterator<Item = T>, truncated: &mut bool) -> Vec<T> {
|
||||
let mut v: Vec<T> = items.take(MAX_FIELDS.saturating_add(1)).collect();
|
||||
if v.len() > MAX_FIELDS {
|
||||
v.truncate(MAX_FIELDS);
|
||||
*truncated = true;
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
+69
-44
@@ -46,6 +46,57 @@ pub struct Ctx<'a> {
|
||||
pub known_function: Option<&'a dyn Fn(&str) -> bool>,
|
||||
/// The code of the workbook's Python cells, from its Python part.
|
||||
pub python: crate::python_part::ScriptsIn,
|
||||
/// Cell elements read so far, across every sheet (capped by `sheet_read::MAX_CELLS`).
|
||||
pub cells: u64,
|
||||
}
|
||||
|
||||
/// The most worksheets read from one workbook (as the XLS reader allows).
|
||||
const MAX_SHEETS: usize = 4096;
|
||||
/// The most shared strings read from one workbook (as the XLS reader allows): each is an
|
||||
/// `Arc<str>` of its own, so a hundred million tiny `<si/>` would ask for gigabytes.
|
||||
const MAX_STRINGS: usize = 4_000_000;
|
||||
|
||||
/// Sheet names taken while reading, compared as `Workbook::sheet_index` compares them (ASCII case
|
||||
/// folded), with the next `(n)` suffix to try for each base, so renaming duplicates stays linear.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SheetNames {
|
||||
taken: HashSet<String>,
|
||||
next_suffix: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl SheetNames {
|
||||
/// Records `name` as taken.
|
||||
pub(crate) fn insert(&mut self, name: &str) {
|
||||
self.taken.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
|
||||
/// A valid name for the `i`-th sheet based on `name`, not yet taken; it is recorded as taken.
|
||||
pub(crate) fn unique(&mut self, name: &str, i: usize) -> String {
|
||||
let mut base: String = name.chars().filter(|c| !matches!(c, ':' | '\\' | '/' | '?' | '*' | '[' | ']')).take(31).collect();
|
||||
if base.trim().is_empty() {
|
||||
base = format!("Sheet{}", i + 1);
|
||||
}
|
||||
if self.taken.insert(base.to_ascii_lowercase()) {
|
||||
return base;
|
||||
}
|
||||
let key: String = base.chars().take(25).collect::<String>().to_ascii_lowercase();
|
||||
let mut n = self.next_suffix.get(&key).copied().unwrap_or(2);
|
||||
loop {
|
||||
// 25 characters of the base, fewer once the suffix grows past ` (999)`, so the name
|
||||
// stays within 31 characters however many duplicates there are.
|
||||
let suffix = format!(" ({n})");
|
||||
let short: String = base.chars().take(31usize.saturating_sub(suffix.len()).min(25)).collect();
|
||||
let candidate = format!("{short}{suffix}");
|
||||
n = n.saturating_add(1);
|
||||
if self.taken.insert(candidate.to_ascii_lowercase()) {
|
||||
self.next_suffix.insert(key, n);
|
||||
return candidate;
|
||||
}
|
||||
if n == usize::MAX {
|
||||
return base;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
@@ -120,6 +171,9 @@ fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError>
|
||||
let mut phonetics = Vec::new();
|
||||
let mut dropped = 0usize;
|
||||
let res = xml::parse_streaming(&b, &["si"], &mut |si| {
|
||||
if sst.len() >= MAX_STRINGS {
|
||||
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_STRINGS} shared strings")));
|
||||
}
|
||||
let text = xml::rich_text(&si);
|
||||
let raw = si.kids("rPh").count();
|
||||
let (runs, props) = xml::phonetic_data(&si, &text);
|
||||
@@ -130,8 +184,10 @@ fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError>
|
||||
sst.push(Arc::from(text));
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = res {
|
||||
cx.warn(format!("shared strings are damaged ({e}); kept {} strings", sst.len()));
|
||||
match res {
|
||||
Ok(_) => {}
|
||||
Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)),
|
||||
Err(e) => cx.warn(format!("shared strings are damaged ({e}); kept {} strings", sst.len())),
|
||||
}
|
||||
if dropped > 0 {
|
||||
cx.warn(format!("shared strings: {dropped} phonetic runs were dropped (bad sb/eb or no reading)"));
|
||||
@@ -267,6 +323,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
|
||||
shared_formula_bytes: 0,
|
||||
known_function,
|
||||
python: Default::default(),
|
||||
cells: 0,
|
||||
};
|
||||
let root_rels = cx.pkg.rels("")?;
|
||||
let wb_part = find_rel(&root_rels, "officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "xl/workbook.xml".into());
|
||||
@@ -318,11 +375,19 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
|
||||
// Legacy formula cells per model sheet, rewritten once names and tables are known.
|
||||
let mut legacy_formulas: Vec<(usize, Vec<gridcraft_core::CellRef>)> = vec![];
|
||||
let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels);
|
||||
let sheet_els: Vec<El> = wb_xml.child("sheets").map(|s| s.kids("sheet").cloned().collect()).unwrap_or_default();
|
||||
let sheet_els: Vec<&El> = wb_xml.child("sheets").map(|s| s.kids("sheet").collect()).unwrap_or_default();
|
||||
if sheet_els.len() > MAX_SHEETS {
|
||||
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_SHEETS} sheets")));
|
||||
}
|
||||
let mut rel_by_id: HashMap<&str, &Rel> = HashMap::with_capacity(wb_rels.len());
|
||||
for r in &wb_rels {
|
||||
// The first of duplicate ids wins, as a linear search would find it.
|
||||
rel_by_id.entry(r.id.as_str()).or_insert(r);
|
||||
}
|
||||
let mut names = SheetNames::default();
|
||||
for (i, se) in sheet_els.iter().enumerate() {
|
||||
let name = se.attr("name").unwrap_or("").to_string();
|
||||
let rel = se.attr("id").and_then(|id| wb_rels.iter().find(|r| r.id == id)).cloned();
|
||||
let rel = se.attr("id").and_then(|id| rel_by_id.get(id).copied()).cloned();
|
||||
let Some(rel) = rel else {
|
||||
cx.warn(format!("sheet \"{name}\" has no part; skipped"));
|
||||
file_to_model.push(None);
|
||||
@@ -476,46 +541,6 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W
|
||||
Ok((wb, cx.report))
|
||||
}
|
||||
|
||||
/// The sheet names an import has assigned so far, for repairing repeated ones.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SheetNames {
|
||||
/// Assigned names, ASCII-lowercased.
|
||||
taken: HashSet<String>,
|
||||
/// For each lowercased stem, the next suffix to try: a file full of repeated names would
|
||||
/// otherwise retry every occupied suffix for every sheet.
|
||||
next: HashMap<String, u64>,
|
||||
}
|
||||
|
||||
impl SheetNames {
|
||||
pub(crate) fn of(wb: &Workbook) -> Self {
|
||||
SheetNames { taken: wb.sheets.iter().map(|s| s.name.to_ascii_lowercase()).collect(), next: HashMap::new() }
|
||||
}
|
||||
|
||||
/// A valid name for the i-th sheet, unique among the names assigned so far, which it joins.
|
||||
pub(crate) fn unique(&mut self, name: &str, i: usize) -> String {
|
||||
let mut base: String = name.chars().filter(|c| !matches!(c, ':' | '\\' | '/' | '?' | '*' | '[' | ']')).take(31).collect();
|
||||
if base.trim().is_empty() {
|
||||
base = format!("Sheet{}", i + 1);
|
||||
}
|
||||
let name = if self.taken.contains(&base.to_ascii_lowercase()) {
|
||||
let stem: String = base.chars().take(25).collect();
|
||||
let next = self.next.entry(stem.to_ascii_lowercase()).or_insert(2);
|
||||
let found = (*next..).find(|n| !self.taken.contains(&format!("{stem} ({n})").to_ascii_lowercase()));
|
||||
match found {
|
||||
Some(n) => {
|
||||
*next = n + 1;
|
||||
format!("{stem} ({n})")
|
||||
}
|
||||
None => base,
|
||||
}
|
||||
} else {
|
||||
base
|
||||
};
|
||||
self.taken.insert(name.to_ascii_lowercase());
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
/// Strips a sheet qualifier (`'My Sheet'!$A$1` → `$A$1`).
|
||||
fn strip_sheet(s: &str) -> &str {
|
||||
match s.rfind('!') {
|
||||
|
||||
@@ -8,7 +8,7 @@ use gridcraft_core::{CellError, CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRe
|
||||
use gridcraft_formula::Expr;
|
||||
use gridcraft_model::{
|
||||
AutoFilter, Cell, CfOperator, CfRule, CfValueKind, Comment, CondFormat, EditRange, ErrorStyle, FilterCriterion, Formula, Hyperlink, LineInfo,
|
||||
NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Table, TableColumn, TotalsFn,
|
||||
NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Style, Table, TableColumn, TotalsFn,
|
||||
Validation, ValidationKind, XmlColumnPr,
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@ mod rules;
|
||||
|
||||
pub use parts::{read_autofilter, read_table};
|
||||
use parts::{read_comments, read_hyperlinks, read_note_shapes, read_threaded};
|
||||
use rules::{read_cf, read_validation};
|
||||
use rules::{read_cf, read_validation, read_x14_cf};
|
||||
|
||||
struct Shared {
|
||||
anchor: CellRef,
|
||||
@@ -134,6 +134,9 @@ fn settle_python_spills_past_budget(st: &RowState, sheet: &mut Sheet) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most cell elements read from one workbook, across its sheets: the reader's own cap.
|
||||
/// (`calc::eval::MAX_CELLS` has the same value but limits one array result, not a workbook.)
|
||||
pub(crate) const MAX_CELLS: u64 = 16_000_000;
|
||||
/// Target and tooltip bytes kept for hyperlinks of one sheet, over all cells: the same URL is
|
||||
/// copied for every cell of its range, so length × cells must stay bounded whatever the file.
|
||||
const MAX_HYPERLINK_BYTES: u64 = 8 * 1024 * 1024;
|
||||
@@ -191,12 +194,10 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
let rels = cx.pkg.rels(part)?;
|
||||
let mut sheet = Sheet::new(name);
|
||||
let mut st = RowState::default();
|
||||
let res = xml::parse_streaming(&bytes, &["row"], &mut |row| {
|
||||
read_row(cx, &mut sheet, &mut st, &row);
|
||||
Ok(())
|
||||
});
|
||||
let res = xml::parse_streaming(&bytes, &["row"], &mut |row| read_row(cx, &mut sheet, &mut st, &row));
|
||||
let root = match res {
|
||||
Ok(r) => r,
|
||||
Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)),
|
||||
Err(e) => {
|
||||
cx.warn(format!("sheet \"{name}\" is damaged ({e}); kept {} rows", st.rows));
|
||||
El::default()
|
||||
@@ -208,6 +209,12 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
settle_python_spills_past_budget(&st, &mut sheet);
|
||||
drop(bytes);
|
||||
|
||||
// Relationships by id: hyperlinks, drawings and tables each look one up.
|
||||
let mut rel_by_id: HashMap<&str, &Rel> = HashMap::with_capacity(rels.len());
|
||||
for r in &rels {
|
||||
// The first of duplicate ids wins, as a linear search would find it.
|
||||
rel_by_id.entry(r.id.as_str()).or_insert(r);
|
||||
}
|
||||
let mut fit_to_page = false;
|
||||
let mut link_budget = LinkBudget::default();
|
||||
let mut cf_kept_cells = 0u64;
|
||||
@@ -245,7 +252,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
}
|
||||
}
|
||||
}
|
||||
"hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet, &mut link_budget),
|
||||
"hyperlinks" => read_hyperlinks(cx, name, e, &rel_by_id, &mut sheet, &mut link_budget),
|
||||
"autoFilter" => sheet.autofilter = read_autofilter(cx, e),
|
||||
"printOptions" => {
|
||||
sheet.print.gridlines = e.flag("gridLines", false);
|
||||
@@ -319,14 +326,14 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
});
|
||||
}
|
||||
"drawing" => {
|
||||
if let Some(rel) = e.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)) {
|
||||
if let Some(rel) = e.attr("id").and_then(|id| rel_by_id.get(id).copied()) {
|
||||
let target = rel.target.clone();
|
||||
crate::drawing::read_drawing(cx, &target, &mut sheet)?;
|
||||
}
|
||||
}
|
||||
"tableParts" => {
|
||||
for tp in e.kids("tablePart") {
|
||||
if let Some(rel) = tp.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)) {
|
||||
if let Some(rel) = tp.attr("id").and_then(|id| rel_by_id.get(id).copied()) {
|
||||
let target = rel.target.clone();
|
||||
if let Some(x) = cx.optional_xml(&target)?
|
||||
&& let Some(mut t) = read_table(cx, &x)
|
||||
@@ -337,7 +344,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr
|
||||
}
|
||||
}
|
||||
}
|
||||
"extLst" => read_ext(cx, e, &mut sheet),
|
||||
"extLst" => read_ext(cx, e, &mut sheet, &mut cf_kept_cells),
|
||||
"protectedRanges" => read_protected_ranges(e, &mut sheet),
|
||||
_ => {}
|
||||
}
|
||||
@@ -496,19 +503,30 @@ fn read_cols(cx: &Ctx<'_>, e: &El, sheet: &mut Sheet, remaining: &mut u64) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) {
|
||||
/// Charges `n` cell elements against the workbook's [`MAX_CELLS`].
|
||||
fn charge_cells(cx: &mut Ctx<'_>, n: u64) -> Result<(), IoError> {
|
||||
cx.cells = cx.cells.saturating_add(n);
|
||||
if cx.cells > MAX_CELLS {
|
||||
return Err(IoError::TooLarge(format!("the workbook has more than {MAX_CELLS} cells")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One `<row>`. Every `<c>` in it counts against [`MAX_CELLS`], also in a row that is dropped
|
||||
/// for a bad row number: one worksheet part read for many sheets can't parse cells uncounted.
|
||||
fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) -> Result<(), IoError> {
|
||||
st.rows += 1;
|
||||
let r = match row.attr_u32("r") {
|
||||
Some(r) if r >= 1 => r - 1,
|
||||
Some(_) => {
|
||||
st.dropped += 1;
|
||||
return;
|
||||
return charge_cells(cx, row.kids("c").count() as u64);
|
||||
}
|
||||
None => st.next_row,
|
||||
};
|
||||
if r >= MAX_ROWS {
|
||||
st.dropped += 1;
|
||||
return;
|
||||
return charge_cells(cx, row.kids("c").count() as u64);
|
||||
}
|
||||
st.next_row = r + 1;
|
||||
let mut info = LineInfo::default();
|
||||
@@ -532,6 +550,7 @@ fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) {
|
||||
}
|
||||
let mut next_col = 0u32;
|
||||
for c in row.kids("c") {
|
||||
charge_cells(cx, 1)?;
|
||||
let pos = match c.attr("r") {
|
||||
Some(a) => match CellRef::parse(a.trim()) {
|
||||
Some(p) => p,
|
||||
@@ -549,6 +568,7 @@ fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) {
|
||||
next_col = pos.col + 1;
|
||||
read_cell(cx, sheet, st, c, pos);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos: CellRef) {
|
||||
@@ -657,6 +677,14 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos
|
||||
Some(_) => Value::Empty,
|
||||
None => value,
|
||||
};
|
||||
// A dynamic array keeps the area it was saved spilling over (`ref`): when two arrays want the
|
||||
// same cells, recalculating gives them to this one again, as before saving.
|
||||
if dynamic
|
||||
&& formula.as_ref().is_some_and(|f| f.array.is_none())
|
||||
&& let Some(r) = st.dynamic.last().filter(|r| r.start == pos)
|
||||
{
|
||||
sheet.spill_ranges.insert(pos, *r);
|
||||
}
|
||||
sheet.cells.set(pos, Cell { value, formula: formula.map(Arc::new), style, py });
|
||||
}
|
||||
|
||||
@@ -822,7 +850,7 @@ pub fn parse_sqref(s: Option<&str>) -> Vec<RangeRef> {
|
||||
}
|
||||
|
||||
/// Worksheet extensions: x14 data validations and sparklines.
|
||||
fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
|
||||
fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, cf_kept_cells: &mut u64) {
|
||||
for ext in e.kids("ext") {
|
||||
for c in &ext.children {
|
||||
match c.name.as_str() {
|
||||
@@ -850,23 +878,7 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
|
||||
}
|
||||
}
|
||||
}
|
||||
"conditionalFormattings" => {
|
||||
let mut skipped = false;
|
||||
for r in c.kids("conditionalFormatting").flat_map(|f| f.kids("cfRule")) {
|
||||
let idx = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id)).map(|(_, n)| *n);
|
||||
match (idx.and_then(|n| sheet.cond_formats.get_mut(n)), r.child("dataBar")) {
|
||||
(Some(CondFormat { rule: CfRule::DataBar { gradient, .. }, .. }), Some(db)) => {
|
||||
*gradient = db.flag("gradient", true);
|
||||
// Only the fill style is modelled; borders, lengths, axis or negative colours are lost.
|
||||
skipped |= db.attrs.iter().any(|(k, _)| k != "gradient") || db.children.iter().any(|k| k.name != "cfvo");
|
||||
}
|
||||
_ => skipped = true,
|
||||
}
|
||||
}
|
||||
if skipped {
|
||||
cx.warn("some Excel 2010 conditional format extensions were skipped");
|
||||
}
|
||||
}
|
||||
"conditionalFormattings" => read_x14_cf(cx, c, sheet, cf_kept_cells),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -921,6 +933,57 @@ mod tests {
|
||||
assert_eq!(parse_iso_datetime("2024-13-01", DateSystem::D1900), None);
|
||||
}
|
||||
|
||||
fn ctx(pkg: crate::package::Package<'_>) -> Ctx<'_> {
|
||||
Ctx {
|
||||
pkg,
|
||||
report: Default::default(),
|
||||
sst: vec![],
|
||||
phonetics: vec![],
|
||||
xf_map: vec![],
|
||||
dxfs: vec![],
|
||||
palette: vec![],
|
||||
date_system: DateSystem::D1900,
|
||||
styles: Default::default(),
|
||||
persons: Default::default(),
|
||||
next_id: 1,
|
||||
num_fmts: Default::default(),
|
||||
cell_pictures: vec![],
|
||||
cf_ext_ids: vec![],
|
||||
known_function: None,
|
||||
python: Default::default(),
|
||||
cells: 0,
|
||||
shared_formula_bytes: 0,
|
||||
legacy_formulas: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// #2159: the workbook-wide cell cap refuses the open once passed, across sheets.
|
||||
#[test]
|
||||
fn cells_past_the_workbook_cap_are_refused() {
|
||||
let bytes = crate::tests::minimal(r#"<sheetData><row r="1"><c r="A1"><v>1</v></c><c r="B1"><v>2</v></c></row></sheetData>"#, &[], "", "");
|
||||
let pkg = crate::package::Package::open(&bytes).unwrap();
|
||||
let mut cx = ctx(pkg);
|
||||
cx.cells = MAX_CELLS - 2;
|
||||
let (sheet, _) = read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data").unwrap();
|
||||
assert_eq!(sheet.cells.len(), 2);
|
||||
assert!(matches!(read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data"), Err(IoError::TooLarge(_))));
|
||||
}
|
||||
|
||||
/// #2159: the cells of a row dropped for its row number still count against the cap, so a
|
||||
/// part read for many sheets can't parse cells uncounted.
|
||||
#[test]
|
||||
fn cells_of_dropped_rows_count_against_the_cap() {
|
||||
let rows = r#"<sheetData><row r="0"><c><v>1</v></c><c><v>2</v></c></row><row r="2000000"><c><v>3</v></c></row></sheetData>"#;
|
||||
let bytes = crate::tests::minimal(rows, &[], "", "");
|
||||
let pkg = crate::package::Package::open(&bytes).unwrap();
|
||||
let mut cx = ctx(pkg);
|
||||
let (sheet, _) = read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data").unwrap();
|
||||
assert!(sheet.cells.is_empty(), "both rows are dropped");
|
||||
assert_eq!(cx.cells, 3);
|
||||
cx.cells = MAX_CELLS - 2;
|
||||
assert!(matches!(read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data"), Err(IoError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqref_keeps_more_than_ten_thousand_ranges() {
|
||||
let sq = (1..=12_000).map(|r| format!("A{r}")).collect::<Vec<_>>().join(" ");
|
||||
|
||||
@@ -4,12 +4,12 @@ use super::{
|
||||
from_file, truncate_chars, xml,
|
||||
};
|
||||
|
||||
/// `budget` counts the cells and bytes this sheet's hyperlinks have copied so far, across
|
||||
/// `<hyperlinks>` blocks.
|
||||
pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet, budget: &mut LinkBudget) {
|
||||
/// `rels` maps relationship ids to relationships (the first of duplicate ids). `budget` counts the
|
||||
/// cells and bytes this sheet's hyperlinks have copied so far, across `<hyperlinks>` blocks.
|
||||
pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &HashMap<&str, &Rel>, sheet: &mut Sheet, budget: &mut LinkBudget) {
|
||||
for h in e.kids("hyperlink") {
|
||||
let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue };
|
||||
let rel_target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.as_str()).unwrap_or("");
|
||||
let rel_target = h.attr("id").and_then(|id| rels.get(id)).map(|r| r.target.as_str()).unwrap_or("");
|
||||
let location = h.attr("location").filter(|l| !l.is_empty());
|
||||
// Each covered cell gets its own copy of the link: refuse oversized targets before copying.
|
||||
if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::{
|
||||
CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Validation, ValidationKind, from_file,
|
||||
CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Style, Validation, ValidationKind, from_file,
|
||||
parse_sqref, read_color,
|
||||
};
|
||||
|
||||
@@ -57,79 +57,164 @@ pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: &
|
||||
for r in e.kids("cfRule") {
|
||||
let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default());
|
||||
let formulas: Vec<String> = r.kids("formula").map(|f| from_file(f.text.trim())).collect();
|
||||
let f0 = formulas.first().cloned().unwrap_or_default();
|
||||
let text = r.attr("text").unwrap_or("").to_string();
|
||||
// The x14 id that links a data bar to its Excel 2010 extension (solid fill lives there).
|
||||
let ext_id =
|
||||
r.child("extLst").and_then(|l| l.kids("ext").find_map(|x| x.child("id"))).map(|i| i.text.trim().to_string()).filter(|i| !i.is_empty());
|
||||
let rule = match r.attr("type").unwrap_or("") {
|
||||
"cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.get(1).cloned(), style },
|
||||
"expression" => CfRule::Expression { formula: f0, style },
|
||||
"containsText" => CfRule::ContainsText { text, style },
|
||||
"notContainsText" => CfRule::NotContainsText { text, style },
|
||||
"beginsWith" => CfRule::BeginsWith { text, style },
|
||||
"endsWith" => CfRule::EndsWith { text, style },
|
||||
"containsBlanks" => CfRule::Blanks { style },
|
||||
"notContainsBlanks" => CfRule::NoBlanks { style },
|
||||
"containsErrors" => CfRule::Errors { style },
|
||||
"notContainsErrors" => CfRule::NoErrors { style },
|
||||
"duplicateValues" => CfRule::Duplicate { style },
|
||||
"uniqueValues" => CfRule::Unique { style },
|
||||
"top10" => {
|
||||
CfRule::Top10 { bottom: r.flag("bottom", false), percent: r.flag("percent", false), rank: r.attr_u32("rank").unwrap_or(10), style }
|
||||
}
|
||||
"aboveAverage" => CfRule::AboveAverage {
|
||||
below: !r.flag("aboveAverage", true),
|
||||
equal: r.flag("equalAverage", false),
|
||||
std_dev: r.attr_u32("stdDev").unwrap_or(0).min(3) as u8,
|
||||
style,
|
||||
},
|
||||
"timePeriod" => CfRule::TimePeriod { period: r.attr("timePeriod").unwrap_or("today").to_string(), style },
|
||||
"colorScale" => {
|
||||
let Some(cs) = r.child("colorScale") else { continue };
|
||||
let colors = cs.kids("color").map(|c| read_color(c, &cx.palette));
|
||||
CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() }
|
||||
}
|
||||
"dataBar" => {
|
||||
let Some(db) = r.child("dataBar") else { continue };
|
||||
let v = cfvos(db);
|
||||
CfRule::DataBar {
|
||||
min: v.first().cloned().unwrap_or(CfValueKind::Min),
|
||||
max: v.get(1).cloned().unwrap_or(CfValueKind::Max),
|
||||
color: db.child("color").map(|c| read_color(c, &cx.palette)).unwrap_or_default(),
|
||||
gradient: true,
|
||||
show_value: db.flag("showValue", true),
|
||||
let ty = r.attr("type").unwrap_or("");
|
||||
match cf_rule(cx, r, ty, formulas, style) {
|
||||
Some(rule) => {
|
||||
if !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells) {
|
||||
break;
|
||||
}
|
||||
if let Some(id) = ext_id {
|
||||
cx.cf_ext_ids.push((id, sheet.cond_formats.len() - 1));
|
||||
}
|
||||
}
|
||||
"iconSet" => {
|
||||
let Some(is) = r.child("iconSet") else { continue };
|
||||
CfRule::IconSet {
|
||||
set: is.attr("iconSet").unwrap_or("3TrafficLights1").to_string(),
|
||||
thresholds: cfvos(is),
|
||||
reverse: is.flag("reverse", false),
|
||||
show_value: is.flag("showValue", true),
|
||||
}
|
||||
None if matches!(ty, "colorScale" | "dataBar" | "iconSet") => {}
|
||||
None => cx.warn(format!("conditional format type \"{ty}\" is not supported")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_cf(cx: &mut Ctx<'_>, sheet: &mut Sheet, ranges: &[RangeRef], block_cells: u64, r: &El, rule: CfRule, kept_cells: &mut u64) -> bool {
|
||||
let total = kept_cells.saturating_add(block_cells);
|
||||
if total > MAX_COND_CELLS {
|
||||
cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped"));
|
||||
return false;
|
||||
}
|
||||
*kept_cells = total;
|
||||
sheet.cond_formats.push(CondFormat {
|
||||
ranges: ranges.to_vec(),
|
||||
rule,
|
||||
priority: r.attr_u32("priority").unwrap_or(0),
|
||||
stop_if_true: r.flag("stopIfTrue", false),
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// The rule of a `cfRule` (main namespace or x14) of type `ty`, given its formulas and
|
||||
/// differential style; `None` for an unknown type or a scale, bar or icon set without its body.
|
||||
fn cf_rule(cx: &Ctx<'_>, r: &El, ty: &str, formulas: Vec<String>, style: Box<Style>) -> Option<CfRule> {
|
||||
let mut formulas = formulas.into_iter();
|
||||
let f0 = formulas.next().unwrap_or_default();
|
||||
let text = r.attr("text").unwrap_or("").to_string();
|
||||
Some(match ty {
|
||||
"cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.next(), style },
|
||||
"expression" => CfRule::Expression { formula: f0, style },
|
||||
"containsText" => CfRule::ContainsText { text, style },
|
||||
"notContainsText" => CfRule::NotContainsText { text, style },
|
||||
"beginsWith" => CfRule::BeginsWith { text, style },
|
||||
"endsWith" => CfRule::EndsWith { text, style },
|
||||
"containsBlanks" => CfRule::Blanks { style },
|
||||
"notContainsBlanks" => CfRule::NoBlanks { style },
|
||||
"containsErrors" => CfRule::Errors { style },
|
||||
"notContainsErrors" => CfRule::NoErrors { style },
|
||||
"duplicateValues" => CfRule::Duplicate { style },
|
||||
"uniqueValues" => CfRule::Unique { style },
|
||||
"top10" => {
|
||||
CfRule::Top10 { bottom: r.flag("bottom", false), percent: r.flag("percent", false), rank: r.attr_u32("rank").unwrap_or(10), style }
|
||||
}
|
||||
"aboveAverage" => CfRule::AboveAverage {
|
||||
below: !r.flag("aboveAverage", true),
|
||||
equal: r.flag("equalAverage", false),
|
||||
std_dev: r.attr_u32("stdDev").unwrap_or(0).min(3) as u8,
|
||||
style,
|
||||
},
|
||||
"timePeriod" => CfRule::TimePeriod { period: r.attr("timePeriod").unwrap_or("today").to_string(), style },
|
||||
"colorScale" => {
|
||||
let cs = r.child("colorScale")?;
|
||||
let colors = cs.kids("color").map(|c| read_color(c, &cx.palette));
|
||||
CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() }
|
||||
}
|
||||
"dataBar" => {
|
||||
let db = r.child("dataBar")?;
|
||||
let v = cfvos(db);
|
||||
CfRule::DataBar {
|
||||
min: v.first().cloned().unwrap_or(CfValueKind::Min),
|
||||
max: v.get(1).cloned().unwrap_or(CfValueKind::Max),
|
||||
color: db.child("color").map(|c| read_color(c, &cx.palette)).unwrap_or_default(),
|
||||
gradient: true,
|
||||
show_value: db.flag("showValue", true),
|
||||
}
|
||||
other => {
|
||||
cx.warn(format!("conditional format type \"{other}\" is not supported"));
|
||||
}
|
||||
"iconSet" => {
|
||||
let is = r.child("iconSet")?;
|
||||
CfRule::IconSet {
|
||||
set: is.attr("iconSet").unwrap_or("3TrafficLights1").to_string(),
|
||||
thresholds: cfvos(is),
|
||||
reverse: is.flag("reverse", false),
|
||||
show_value: is.flag("showValue", true),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `x14:conditionalFormattings` (MS-XLSX 2.4.6): rules kept out of the main section, such as
|
||||
/// those whose formulas refer to other sheets in the one LibreOffice-saved file seen. They carry
|
||||
/// `xm:f` formulas, an inline `x14:dxf` and priorities shared with the main-section rules.
|
||||
/// Read: cellIs, expression, (not)containsBlanks, (not)containsErrors, duplicate/unique values,
|
||||
/// top10, aboveAverage and timePeriod. The x14 extension a main-section data bar links to by
|
||||
/// `x14:id` adds no rule, only that bar's solid fill (its other settings are skipped with a
|
||||
/// warning). Skipped with a warning (and so lost on save): other data bars, icon sets, colour
|
||||
/// scales and the text rules containsText, notContainsText, beginsWith and endsWith.
|
||||
pub(super) fn read_x14_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: &mut u64) {
|
||||
for cf in e.kids("conditionalFormatting") {
|
||||
let ranges = parse_sqref(cf.child("sqref").map(|s| s.text.as_str()));
|
||||
let block_cells = ranges.iter().map(RangeRef::count).fold(0u64, u64::saturating_add);
|
||||
for r in cf.kids("cfRule") {
|
||||
let ty = r.attr("type").unwrap_or("");
|
||||
let linked = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id.trim())).map(|(_, n)| *n);
|
||||
if let Some(n) = linked {
|
||||
match (sheet.cond_formats.get_mut(n), r.child("dataBar")) {
|
||||
(Some(CondFormat { rule: CfRule::DataBar { gradient, .. }, .. }), Some(db)) => {
|
||||
*gradient = db.flag("gradient", true);
|
||||
// Only the fill style is modelled, with negatives in the bar's colour and no axis;
|
||||
// borders, lengths, other axis positions or negative colours are lost.
|
||||
let modelled = |k: &str, v: &str| {
|
||||
k == "gradient"
|
||||
|| (k == "axisPosition" && v == "none")
|
||||
|| (k == "negativeBarColorSameAsPositive" && matches!(v, "1" | "true"))
|
||||
};
|
||||
if db.attrs.iter().any(|(k, v)| !modelled(k, v)) || db.children.iter().any(|k| k.name != "cfvo") {
|
||||
cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was partly skipped (only its solid fill is kept)"));
|
||||
}
|
||||
}
|
||||
_ => cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let total = kept_cells.saturating_add(block_cells);
|
||||
if total > MAX_COND_CELLS {
|
||||
cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped"));
|
||||
break;
|
||||
if ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Only rule kinds whose formulas are kept and written back here; the others' x14
|
||||
// forms add settings (bar fills and axes, custom icons) the model doesn't hold.
|
||||
let supported = matches!(
|
||||
ty,
|
||||
"cellIs"
|
||||
| "expression"
|
||||
| "containsBlanks"
|
||||
| "notContainsBlanks"
|
||||
| "containsErrors"
|
||||
| "notContainsErrors"
|
||||
| "duplicateValues"
|
||||
| "uniqueValues"
|
||||
| "top10"
|
||||
| "aboveAverage"
|
||||
| "timePeriod"
|
||||
);
|
||||
if !supported {
|
||||
cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was skipped"));
|
||||
continue;
|
||||
}
|
||||
let style = Box::new(r.child("dxf").map(|x| crate::styles::read_x14_dxf(x, &cx.palette, &cx.num_fmts)).unwrap_or_default());
|
||||
let formulas: Vec<String> = r.kids("f").map(|f| from_file(f.text.trim())).collect();
|
||||
if let Some(rule) = cf_rule(cx, r, ty, formulas, style)
|
||||
&& !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
*kept_cells = total;
|
||||
if let Some(id) = ext_id {
|
||||
cx.cf_ext_ids.push((id, sheet.cond_formats.len()));
|
||||
}
|
||||
sheet.cond_formats.push(CondFormat {
|
||||
ranges: ranges.clone(),
|
||||
rule,
|
||||
priority: r.attr_u32("priority").unwrap_or(0),
|
||||
stop_if_true: r.flag("stopIfTrue", false),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user