mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-29 17:56:18 +01:00
fix(filter): preserve checklist identities, formatted-blank values, and migrated visibility on open
This commit is contained in:
commit
0329de4388
112 files changed
+6981
-1885
No files matched your search
Generated
+122
-25
@@ -922,12 +922,17 @@ 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=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-cfb"
|
||||
version = "0.1.0"
|
||||
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 +940,20 @@ 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=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-drawingml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"kurbo",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -982,14 +998,52 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-offcrypto"
|
||||
name = "craft-math"
|
||||
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 = [
|
||||
"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-cfb",
|
||||
"craft-xml",
|
||||
"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=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64 0.23.1",
|
||||
"craft-cfb 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)",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"sha1 0.11.0",
|
||||
@@ -1001,10 +1055,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",
|
||||
]
|
||||
@@ -1031,7 +1085,17 @@ 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=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
|
||||
|
||||
[[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 +1131,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 +1178,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 +1197,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=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-sheet",
|
||||
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
|
||||
"craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
|
||||
"md-5",
|
||||
"miniz_oxide 0.9.1",
|
||||
"sha1 0.10.7",
|
||||
@@ -1146,19 +1210,39 @@ 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-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"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=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e"
|
||||
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 +1251,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",
|
||||
@@ -2403,13 +2497,16 @@ dependencies = [
|
||||
name = "gridcraft-xlsx"
|
||||
version = "0.19.1"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)",
|
||||
"craft-csv",
|
||||
"craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)",
|
||||
"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
-9
@@ -30,25 +30,28 @@ 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 = "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 = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -88,7 +91,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"
|
||||
|
||||
+7
-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 |
|
||||
@@ -181,11 +182,13 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 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 |
|
||||
@@ -202,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) |
|
||||
@@ -275,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 |
|
||||
@@ -319,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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+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)
|
||||
}
|
||||
@@ -23,7 +23,7 @@ mod sort;
|
||||
mod tools;
|
||||
mod validation;
|
||||
|
||||
pub use filter::{FilterChoice, filter_choices, filter_values};
|
||||
pub use filter::{FilterChoice, filter_by_cell_params, filter_choices, filter_choices_params, filter_values};
|
||||
pub(crate) use filter::{apply_filter, grow_autofilter, migrate_loaded_autofilters};
|
||||
use filter::{clear_filter, filter_by, reapply, toggle_filter};
|
||||
use grouping::{detail, group, outline_settings, show_levels, subtotal};
|
||||
|
||||
@@ -88,12 +88,17 @@ pub(super) fn filter_by(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
None
|
||||
} else if let Some(vals) = p.get("values").and_then(Json::as_array) {
|
||||
let mut values: Vec<String> = vals.iter().map(crate::cmd::edit::json_to_input).collect();
|
||||
// Callers such as "Filter by Selected Cell's Value" pass `values` without `blanks`;
|
||||
let identities: Vec<String> = p
|
||||
.get("identities")
|
||||
.and_then(Json::as_array)
|
||||
.map(|arr| arr.iter().filter_map(Json::as_str).map(str::to_string).collect())
|
||||
.unwrap_or_default();
|
||||
// Callers such as programmatic `data.filterBy` pass `values` without `blanks`;
|
||||
// since whitespace-only text belongs to the dropdown's `(Blanks)` group, include blanks
|
||||
// automatically unless the caller explicitly passed `blanks`.
|
||||
let blanks = bool_param(p, "blanks").unwrap_or_else(|| values.iter().any(|v| v.trim().is_empty()));
|
||||
values.retain(|v| !v.trim().is_empty());
|
||||
Some(FilterCriterion::Values { values, blanks })
|
||||
Some(FilterCriterion::Values { values, blanks, identities })
|
||||
} else if let Some(c) = p.get("custom") {
|
||||
let a =
|
||||
(c.get("op").and_then(Json::as_str).unwrap_or("=").to_string(), c.get("value").map(crate::cmd::edit::json_to_input).unwrap_or_default());
|
||||
@@ -170,32 +175,114 @@ fn filter_value_eq(a: &str, b: &str) -> bool {
|
||||
a.trim().eq_ignore_ascii_case(b.trim())
|
||||
}
|
||||
|
||||
/// Whether a `Values` criterion includes blank and whitespace-only cells, including legacy saved criteria.
|
||||
fn values_include_blanks(values: &[String], blanks: bool) -> bool {
|
||||
blanks || values.iter().any(|x| x.trim().is_empty())
|
||||
}
|
||||
|
||||
/// Checks whether a non-blank cell matches any selected value criterion via displayed or underlying text.
|
||||
fn row_matches_values(values: &[String], text: &str, v: &Value) -> bool {
|
||||
values.iter().any(|x| filter_value_eq(x, text) || filter_value_eq(x, &v.display()))
|
||||
}
|
||||
|
||||
/// Migrates legacy saved value criteria that listed whitespace-only strings into `blanks: true` on load.
|
||||
pub(crate) fn migrate_loaded_autofilters(wb: &mut Workbook) {
|
||||
for si in 0..wb.sheets.len() {
|
||||
let needs_migration = wb.sheet(si).and_then(|sh| sh.autofilter.as_ref()).is_some_and(|af| {
|
||||
af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Values { values, .. } if values.iter().any(|v| v.trim().is_empty())))
|
||||
});
|
||||
if !needs_migration {
|
||||
continue;
|
||||
/// Displayed cell text under an explicit `show_formulas` mode (matching `display::cell_text`).
|
||||
fn cell_text_for_mode(wb: &Workbook, sh: &Sheet, c: CellRef, show_formulas: bool) -> String {
|
||||
if show_formulas
|
||||
&& let Some(f) = sh.cell(c).and_then(|x| x.formula.as_ref())
|
||||
&& !crate::display::formula_hidden(wb, sh, c)
|
||||
{
|
||||
return format!("={}", f.text);
|
||||
}
|
||||
crate::display::value_text_as(wb, &sh.value(c), wb.styles.get(sh.style_id(c)).num_fmt.as_str())
|
||||
}
|
||||
|
||||
/// Canonical checklist identity for a non-blank cell under `show_formulas`.
|
||||
///
|
||||
/// Ordinary text whitespace variants (`"Card"` and `" Card "`) share one identity, whereas rows
|
||||
/// whose displayed text and underlying value differ (such as `=" Card "` vs `" =\" Card \" "`
|
||||
/// under Show Formulas, or numbers whose custom format displays spaces) stay distinct.
|
||||
fn choice_identity(v: &Value, t: &str, show_formulas: bool) -> String {
|
||||
let kind = match v {
|
||||
Value::Number(_) => "n",
|
||||
Value::Text(_) => "t",
|
||||
Value::Bool(_) => "b",
|
||||
_ => "e",
|
||||
};
|
||||
let disp_key = if t.trim().is_empty() { String::new() } else { t.trim().to_ascii_lowercase() };
|
||||
let val_key = v.display().trim().to_ascii_lowercase();
|
||||
format!("{}\x1f{kind}\x1f{disp_key}\x1f{val_key}", u8::from(show_formulas))
|
||||
}
|
||||
|
||||
/// Checks whether a non-blank cell matches any selected checklist `choice_identity`.
|
||||
fn row_matches_identities(wb: &Workbook, sh: &Sheet, c: CellRef, v: &Value, current_text: &str, identities: &[String]) -> bool {
|
||||
let cur_id = choice_identity(v, current_text, sh.show_formulas);
|
||||
let mut alt_id: Option<String> = None;
|
||||
identities.iter().any(|id| {
|
||||
let id_sf = id.starts_with("1\x1f");
|
||||
if id_sf == sh.show_formulas {
|
||||
id == &cur_id
|
||||
} else {
|
||||
let alt = alt_id.get_or_insert_with(|| {
|
||||
let alt_text = cell_text_for_mode(wb, sh, c, id_sf);
|
||||
choice_identity(v, &alt_text, id_sf)
|
||||
});
|
||||
id == alt
|
||||
}
|
||||
if let Some(sh) = wb.sheet_mut(si)
|
||||
&& let Some(af) = sh.autofilter.as_mut()
|
||||
{
|
||||
for (_, crit) in &mut af.criteria {
|
||||
if let FilterCriterion::Values { values, blanks } = crit
|
||||
&& values.iter().any(|v| v.trim().is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks whether a non-blank cell matches a `Values` criterion: exact checklist identities when
|
||||
/// submitted by UI checklist/cell actions, or string matching for direct `data.filterBy` callers.
|
||||
fn row_matches_criterion(wb: &Workbook, sh: &Sheet, c: CellRef, v: &Value, text: &str, values: &[String], identities: &[String]) -> bool {
|
||||
if !identities.is_empty() { row_matches_identities(wb, sh, c, v, text, identities) } else { row_matches_values(values, text, v) }
|
||||
}
|
||||
|
||||
/// Header-and-data range covered by a table's own AutoFilter (excluding any totals row).
|
||||
fn table_filter_range(t: &gridcraft_model::Table) -> Option<RangeRef> {
|
||||
if !t.header_row {
|
||||
return None;
|
||||
}
|
||||
let end_row = t.range.end.row.checked_sub(u32::from(t.totals_row))?;
|
||||
(end_row >= t.range.start.row).then(|| RangeRef::new(t.range.start, CellRef::new(end_row, t.range.end.col)))
|
||||
}
|
||||
|
||||
/// Migrates legacy saved value criteria that listed whitespace-only strings into `blanks: true`
|
||||
/// on load, and reapplies every migrated filter so row visibility agrees before first render.
|
||||
pub(crate) fn migrate_loaded_autofilters(wb: &mut Workbook) {
|
||||
let migrate_list = |criteria: &mut [(u32, FilterCriterion)]| -> bool {
|
||||
let mut changed = false;
|
||||
for (_, crit) in criteria {
|
||||
if let FilterCriterion::Values { values, blanks, .. } = crit
|
||||
&& values.iter().any(|v| v.trim().is_empty())
|
||||
{
|
||||
*blanks = true;
|
||||
values.retain(|v| !v.trim().is_empty());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
};
|
||||
for si in 0..wb.sheets.len() {
|
||||
let mut sheet_af_changed = false;
|
||||
let mut migrated_tables: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> = Vec::new();
|
||||
if let Some(sh) = wb.sheet_mut(si) {
|
||||
if let Some(af) = sh.autofilter.as_mut() {
|
||||
sheet_af_changed = migrate_list(&mut af.criteria);
|
||||
}
|
||||
for t in &mut sh.tables {
|
||||
if migrate_list(&mut t.filter)
|
||||
&& let Some(range) = table_filter_range(t)
|
||||
{
|
||||
*blanks = true;
|
||||
values.retain(|v| !v.trim().is_empty());
|
||||
migrated_tables.push((range, t.filter.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if sheet_af_changed {
|
||||
apply_filter(wb, si);
|
||||
}
|
||||
for (range, criteria) in migrated_tables {
|
||||
apply_criteria_range(wb, si, range, &criteria);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,14 +318,26 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) {
|
||||
|
||||
/// Hides rows of the autofilter range that fail any criterion.
|
||||
pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
let Some(af) = wb.sheet(sheet).and_then(|sh| sh.autofilter.clone()) else { return };
|
||||
apply_criteria_range(wb, sheet, af.range, &af.criteria);
|
||||
}
|
||||
|
||||
/// Evaluates `criteria` over `af_range` on `sheet` and updates row visibility.
|
||||
fn apply_criteria_range(wb: &mut Workbook, sheet: usize, af_range: RangeRef, criteria: &[(u32, FilterCriterion)]) {
|
||||
let Some(sh) = wb.sheet(sheet) else { return };
|
||||
let Some(af) = sh.autofilter.clone() else { return };
|
||||
// An imported range can name rows past the grid; none of those exist to hide.
|
||||
let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col));
|
||||
let r = RangeRef::new(af_range.start, CellRef::new(af_range.end.row.min(gridcraft_core::MAX_ROWS - 1), af_range.end.col));
|
||||
let mut hide = Vec::new();
|
||||
// Precompute per-criterion top10 threshold and average once, not per row.
|
||||
// Precompute per-criterion blank inclusion, top10 threshold, and average once before scanning rows.
|
||||
let criterion_blanks: Vec<bool> = criteria
|
||||
.iter()
|
||||
.map(|(_, c)| match c {
|
||||
FilterCriterion::Values { values, blanks, .. } => values_include_blanks(values, *blanks),
|
||||
_ => false,
|
||||
})
|
||||
.collect();
|
||||
let mut col_stats: std::collections::HashMap<usize, (Option<f64>, f64)> = std::collections::HashMap::new();
|
||||
for (i, (off, c)) in af.criteria.iter().enumerate() {
|
||||
for (i, (off, c)) in criteria.iter().enumerate() {
|
||||
if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) {
|
||||
let col = r.start.col + off;
|
||||
let mut nums: Vec<f64> = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect();
|
||||
@@ -257,16 +356,16 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
}
|
||||
for row in r.start.row + 1..=r.end.row {
|
||||
let mut visible = true;
|
||||
for (i, (off, crit)) in af.criteria.iter().enumerate() {
|
||||
for (i, (off, crit)) in criteria.iter().enumerate() {
|
||||
let c = CellRef::new(row, r.start.col + off);
|
||||
let v = sh.value(c);
|
||||
let text = crate::display::cell_text(wb, sh, c);
|
||||
let ok = match crit {
|
||||
FilterCriterion::Values { values, blanks } => {
|
||||
FilterCriterion::Values { values, identities, .. } => {
|
||||
if filter_dropdown_blank(&v) {
|
||||
*blanks || values.iter().any(|x| x.trim().is_empty())
|
||||
criterion_blanks[i]
|
||||
} else {
|
||||
row_matches_values(values, &text, &v)
|
||||
row_matches_criterion(wb, sh, c, &v, &text, values, identities)
|
||||
}
|
||||
}
|
||||
FilterCriterion::Custom { a, b, and } => {
|
||||
@@ -345,14 +444,40 @@ pub(super) fn reapply(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
/// One entry in a column's AutoFilter value checklist: its distinct display `label`, the raw
|
||||
/// criterion `value` (`None` for the `(Blanks)` toggle), and whether it is `checked`.
|
||||
/// criterion `value` (`None` for the `(Blanks)` toggle), its canonical checklist `identity`, and
|
||||
/// whether it is `checked`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FilterChoice {
|
||||
pub label: String,
|
||||
pub value: Option<String>,
|
||||
pub identity: Option<String>,
|
||||
pub checked: bool,
|
||||
}
|
||||
|
||||
/// Builds the `data.filterBy` parameters from the AutoFilter dropdown's `(choice, checked)` state.
|
||||
pub fn filter_choices_params(col: &str, active_checks: &[(&FilterChoice, bool)]) -> Json {
|
||||
if active_checks.iter().all(|(_, on)| *on) {
|
||||
return json!({"column": col, "clear": true});
|
||||
}
|
||||
let blanks = active_checks.iter().any(|(c, on)| *on && c.value.is_none());
|
||||
let vals: Vec<String> = active_checks.iter().filter(|(_, on)| *on).filter_map(|(c, _)| c.value.clone()).collect();
|
||||
let ids: Vec<String> = active_checks.iter().filter(|(_, on)| *on).filter_map(|(c, _)| c.identity.clone()).collect();
|
||||
json!({"column": col, "values": vals, "identities": ids, "blanks": blanks})
|
||||
}
|
||||
|
||||
/// Builds the `data.filterBy` parameters for filtering `col` by the selected cell `c` ("Filter by Selected Cell's Value").
|
||||
pub fn filter_by_cell_params(wb: &Workbook, sh: &Sheet, c: CellRef, col: &str) -> Json {
|
||||
let v = sh.value(c);
|
||||
if filter_dropdown_blank(&v) {
|
||||
return json!({"column": col, "values": [], "blanks": true});
|
||||
}
|
||||
let t = crate::display::cell_text(wb, sh, c);
|
||||
let has_visible_formula = sh.show_formulas && sh.cell(c).and_then(|x| x.formula.as_ref()).is_some() && !crate::display::formula_hidden(wb, sh, c);
|
||||
let raw = if has_visible_formula || t.trim().is_empty() { v.display().trim().to_string() } else { t.trim().to_string() };
|
||||
let id = choice_identity(&v, &t, sh.show_formulas);
|
||||
json!({"column": col, "values": [raw], "identities": [id], "blanks": false})
|
||||
}
|
||||
|
||||
/// Escapes literal text whose trimmed form is `(Blanks)` or `'...(Blanks)...'` by wrapping one
|
||||
/// outer pair of single quotes, keeping `(Blanks)`, `'(Blanks)'`, and `''(Blanks)''` distinct.
|
||||
fn escape_reserved_blanks_label(trimmed: &str) -> String {
|
||||
@@ -363,49 +488,108 @@ fn escape_reserved_blanks_label(trimmed: &str) -> String {
|
||||
if inner.eq_ignore_ascii_case("(Blanks)") { format!("'{trimmed}'") } else { trimmed.to_string() }
|
||||
}
|
||||
|
||||
/// Distinct checklist entries of a filter column, keeping display labels separate from filter values.
|
||||
/// Distinct checklist entries of a filter column, keeping display labels separate from filter identities.
|
||||
pub fn filter_choices(wb: &Workbook, sheet: usize, col: u32) -> Vec<FilterChoice> {
|
||||
let Some(sh) = wb.sheet(sheet) else { return vec![] };
|
||||
let Some(af) = &sh.autofilter else { return vec![] };
|
||||
let off = col.saturating_sub(af.range.start.col);
|
||||
let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c);
|
||||
let mut seen: std::collections::BTreeMap<_, FilterChoice> = std::collections::BTreeMap::new();
|
||||
let selected_blanks = match selected {
|
||||
Some(FilterCriterion::Values { values, blanks, .. }) => values_include_blanks(values, *blanks),
|
||||
_ => false,
|
||||
};
|
||||
type ChoiceBucket = ((u8, i64, String), FilterChoice, (String, &'static str));
|
||||
let mut seen: std::collections::BTreeMap<Option<String>, ChoiceBucket> = std::collections::BTreeMap::new();
|
||||
for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) {
|
||||
let c = CellRef::new(row, col);
|
||||
let v = sh.value(c);
|
||||
let blank = filter_dropdown_blank(&v);
|
||||
let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) };
|
||||
let on = match selected {
|
||||
Some(FilterCriterion::Values { values, blanks }) => {
|
||||
Some(FilterCriterion::Values { values, identities, .. }) => {
|
||||
if blank {
|
||||
*blanks || values.iter().any(|x| x.trim().is_empty())
|
||||
selected_blanks
|
||||
} else {
|
||||
row_matches_values(values, &t, &v)
|
||||
row_matches_criterion(wb, sh, c, &v, &t, values, identities)
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
// Group equivalent text values without merging rows that have different underlying filter identities.
|
||||
let is_text = !blank && matches!(v, Value::Text(_));
|
||||
let (sort, canonical, label, raw_value) = if is_text {
|
||||
let trimmed = t.trim();
|
||||
let normalized = trimmed.to_ascii_lowercase();
|
||||
let val_normalized = v.display().trim().to_ascii_lowercase();
|
||||
let label = if trimmed.is_empty() { t.clone() } else { escape_reserved_blanks_label(trimmed) };
|
||||
let raw = if trimmed.is_empty() { t } else { trimmed.to_string() };
|
||||
((1, 0, normalized.clone()), (normalized, val_normalized), label, Some(raw))
|
||||
} else if blank {
|
||||
(sort_key(&Value::Empty), (t.clone(), String::new()), t, None)
|
||||
} else {
|
||||
(sort_key(&v), (t.clone(), v.display().trim().to_ascii_lowercase()), t.clone(), Some(t))
|
||||
if blank {
|
||||
seen.entry(None).and_modify(|(_, entry, _)| entry.checked |= on).or_insert((
|
||||
sort_key(&Value::Empty),
|
||||
FilterChoice { label: t, value: None, identity: None, checked: on },
|
||||
(String::new(), ""),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let id = choice_identity(&v, &t, sh.show_formulas);
|
||||
let val_trimmed = v.display().trim().to_string();
|
||||
let has_visible_formula =
|
||||
sh.show_formulas && sh.cell(c).and_then(|x| x.formula.as_ref()).is_some() && !crate::display::formula_hidden(wb, sh, c);
|
||||
let trimmed = t.trim();
|
||||
let disp_empty = trimmed.is_empty();
|
||||
let base_label = if disp_empty { escape_reserved_blanks_label(&val_trimmed) } else { escape_reserved_blanks_label(trimmed) };
|
||||
let raw_value = Some(if has_visible_formula || disp_empty { val_trimmed.clone() } else { trimmed.to_string() });
|
||||
let sort = if matches!(v, Value::Text(_)) { (1, 0, base_label.to_ascii_lowercase()) } else { sort_key(&v) };
|
||||
let kind_label = match v {
|
||||
Value::Number(_) => "number",
|
||||
Value::Text(_) => "text",
|
||||
Value::Bool(_) => "boolean",
|
||||
_ => "error",
|
||||
};
|
||||
seen.entry((sort, canonical)).and_modify(|entry| entry.checked |= on).or_insert(FilterChoice { label, value: raw_value, checked: on });
|
||||
let qualifier = if has_visible_formula {
|
||||
format!("result: {val_trimmed}")
|
||||
} else if disp_empty {
|
||||
"formatted blank".to_string()
|
||||
} else if !val_trimmed.eq_ignore_ascii_case(base_label.trim()) {
|
||||
format!("value: {val_trimmed}")
|
||||
} else {
|
||||
kind_label.to_string()
|
||||
};
|
||||
seen.entry(Some(id.clone())).and_modify(|(_, entry, _)| entry.checked |= on).or_insert((
|
||||
sort,
|
||||
FilterChoice { label: base_label, value: raw_value, identity: Some(id), checked: on },
|
||||
(qualifier, kind_label),
|
||||
));
|
||||
}
|
||||
let mut values: Vec<_> = seen.into_iter().collect();
|
||||
values.sort_by(|((a, (ta, va)), _), ((b, (tb, vb)), _)| {
|
||||
a.0.cmp(&b.0).then(a.1.cmp(&b.1)).then_with(|| gridcraft_core::compare_text(&a.2, &b.2)).then_with(|| ta.cmp(tb)).then_with(|| va.cmp(vb))
|
||||
values.sort_by(|(id_a, (sort_a, choice_a, _)), (id_b, (sort_b, choice_b, _))| {
|
||||
sort_a
|
||||
.0
|
||||
.cmp(&sort_b.0)
|
||||
.then(sort_a.1.cmp(&sort_b.1))
|
||||
.then_with(|| gridcraft_core::compare_text(&sort_a.2, &sort_b.2))
|
||||
.then_with(|| gridcraft_core::compare_text(&choice_a.label, &choice_b.label))
|
||||
.then_with(|| id_a.cmp(id_b))
|
||||
});
|
||||
values.into_iter().map(|(_, entry)| entry).collect()
|
||||
let mut label_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
for (_, (_, choice, _)) in &values {
|
||||
*label_counts.entry(choice.label.clone()).or_insert(0) += 1;
|
||||
}
|
||||
let mut qualified: Vec<(FilterChoice, &'static str)> = values
|
||||
.into_iter()
|
||||
.map(|(_, (_, mut choice, (qualifier, kind_label)))| {
|
||||
if label_counts.get(&choice.label).copied().unwrap_or(0) > 1 && !qualifier.is_empty() {
|
||||
choice.label = format!("{} ({qualifier})", choice.label);
|
||||
}
|
||||
(choice, kind_label)
|
||||
})
|
||||
.collect();
|
||||
let mut qualified_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
for (choice, _) in &qualified {
|
||||
*qualified_counts.entry(choice.label.clone()).or_insert(0) += 1;
|
||||
}
|
||||
for (choice, kind_label) in &mut qualified {
|
||||
if qualified_counts.get(&choice.label).copied().unwrap_or(0) > 1 && !kind_label.is_empty() {
|
||||
if let Some(stem) = choice.label.strip_suffix(')') {
|
||||
choice.label = format!("{stem}, {kind_label})");
|
||||
} else {
|
||||
choice.label = format!("{} ({kind_label})", choice.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
qualified.into_iter().map(|(choice, _)| choice).collect()
|
||||
}
|
||||
|
||||
/// Distinct display values of a filter column (for the dropdown list).
|
||||
|
||||
@@ -96,6 +96,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
line: Color::from_hex(&color).unwrap_or(Color::rgb(0x1F, 0x5F, 0xC9)),
|
||||
text,
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
};
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(si)?.shapes.push(shape);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -95,6 +95,7 @@ fn insert_equation(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
text: latex.to_string(),
|
||||
format: Default::default(),
|
||||
math: Default::default(),
|
||||
rotation: 0.0,
|
||||
};
|
||||
shape.math.refresh(latex);
|
||||
let sheet = d.wb.active_sheet();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -164,7 +164,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Object",
|
||||
[],
|
||||
None,
|
||||
"{kind: chart|image|shape|slicer|equation|control, id, at?: \"C3\", dx?, dy?, width?, height? (each at most 10,000 points, or the object's current size when a file made it larger)}",
|
||||
"{kind: chart|image|shape|slicer|equation|control, id, at?: \"C3\", dx?, dy?, width?, height? (each at most 10,000 points, or the object's current size when a file made it larger), rotation?: degrees clockwise (shapes, not ink)}",
|
||||
has_doc,
|
||||
move_object
|
||||
),
|
||||
|
||||
@@ -358,6 +358,7 @@ pub(super) fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
line: Color::Auto,
|
||||
text: name,
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet();
|
||||
|
||||
@@ -163,6 +163,7 @@ pub(super) fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
line,
|
||||
text: str_param(p, "text").unwrap_or("").into(),
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet();
|
||||
@@ -237,6 +238,16 @@ pub(super) fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
pub(super) fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (sheet, o) = object_param(s, p, "object.move")?;
|
||||
let at = cell_param(s, p, "at")?;
|
||||
let rotation = f64_param(p, "rotation").filter(|v| v.is_finite());
|
||||
if rotation.is_some() {
|
||||
let ink = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.shapes.iter().any(|x| x.id == o.id && x.kind == ShapeKind::Ink));
|
||||
if o.kind != ObjKind::Shape || ink {
|
||||
return Err(bad("object.move", "only shapes other than ink rotate"));
|
||||
}
|
||||
if s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.is_protected()) {
|
||||
return Err(EngineError::Other(PROTECTED.into()));
|
||||
}
|
||||
}
|
||||
edit(s, |cx| {
|
||||
let Some(a) = cx.sheet_mut(sheet)?.object_anchor_mut(o) else { return Err(bad("object.move", "no such object")) };
|
||||
if let Some(at) = at {
|
||||
@@ -254,6 +265,11 @@ pub(super) fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let Some(v) = f64_param(p, "height") {
|
||||
a.height = v.clamp(0.0, size_cap(a.height)) as f32;
|
||||
}
|
||||
if let Some(r) = rotation
|
||||
&& let Some(shape) = cx.sheet_mut(sheet)?.shapes.iter_mut().find(|x| x.id == o.id)
|
||||
{
|
||||
shape.rotation = r.rem_euclid(360.0) as f32;
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::draw::{Block, PdfMeasure, Xf, draw_prims, rgb_of};
|
||||
use super::text::wrap_lines;
|
||||
use super::{Anchor, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
|
||||
use super::{Anchor, Baseline, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
|
||||
|
||||
/// Cell pictures fit the current cell (or merged-cell) rectangle without changing aspect ratio.
|
||||
pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32, f32), k: f32) {
|
||||
@@ -175,29 +175,42 @@ fn draw_sparklines(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Bloc
|
||||
fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Block, (x, y, w, h): (f32, f32, f32, f32)) {
|
||||
let fill = rgb_of(shp.fill, wb);
|
||||
let line = rgb_of(shp.line, wb).filter(|_| !shp.format.no_line).map(|c| (c, (0.75 * b.k).max(0.25)));
|
||||
let angle = if shp.rotation.is_finite() { shp.rotation.to_radians() } else { 0.0 };
|
||||
let (sn, cs) = angle.sin_cos();
|
||||
let (cx, cy) = (x + w / 2.0, y + h / 2.0);
|
||||
let turn = |[px, py]: [f32; 2]| {
|
||||
let (dx, dy) = (px - cx, py - cy);
|
||||
[cx + dx * cs - dy * sn, cy + dx * sn + dy * cs]
|
||||
};
|
||||
match shp.kind {
|
||||
ShapeKind::Ellipse => {
|
||||
let pts: Vec<[f32; 2]> = (0..72)
|
||||
.map(|i| {
|
||||
let a = i as f32 / 72.0 * std::f32::consts::TAU;
|
||||
[x + w / 2.0 + w / 2.0 * a.cos(), y + h / 2.0 + h / 2.0 * a.sin()]
|
||||
turn([x + w / 2.0 + w / 2.0 * a.cos(), y + h / 2.0 + h / 2.0 * a.sin()])
|
||||
})
|
||||
.collect();
|
||||
pg.polygon(&pts, fill, line);
|
||||
}
|
||||
ShapeKind::Triangle => pg.polygon(&[[x + w / 2.0, y], [x + w, y + h], [x, y + h]], fill, line),
|
||||
ShapeKind::Triangle => {
|
||||
let pts = [[x + w / 2.0, y], [x + w, y + h], [x, y + h]].map(turn);
|
||||
pg.polygon(&pts, fill, line);
|
||||
}
|
||||
ShapeKind::Line | ShapeKind::Arrow => {
|
||||
let c = line.map(|l| l.0).or(fill).unwrap_or([0, 0, 0]);
|
||||
pg.stroke_line(x, y, x + w, y + h, (1.0 * b.k).max(0.3), c);
|
||||
let [x0, y0] = turn([x, y]);
|
||||
let [x1, y1] = turn([x + w, y + h]);
|
||||
pg.stroke_line(x0, y0, x1, y1, (1.0 * b.k).max(0.3), c);
|
||||
if shp.kind == ShapeKind::Arrow {
|
||||
let ang = h.atan2(w);
|
||||
let al = 8.0 * b.k;
|
||||
let p = |da: f32| [x + w - al * (ang + da).cos(), y + h - al * (ang + da).sin()];
|
||||
pg.polygon(&[[x + w, y + h], p(0.4), p(-0.4)], Some(c), None);
|
||||
let p = |da: f32| turn([x + w - al * (ang + da).cos(), y + h - al * (ang + da).sin()]);
|
||||
pg.polygon(&[turn([x + w, y + h]), p(0.4), p(-0.4)], Some(c), None);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
pg.polygon(&[[x, y], [x + w, y], [x + w, y + h], [x, y + h]], fill, line);
|
||||
let pts = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map(turn);
|
||||
pg.polygon(&pts, fill, line);
|
||||
}
|
||||
}
|
||||
if shp.text.is_empty() {
|
||||
@@ -228,7 +241,8 @@ fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Bl
|
||||
// WordArt's drop shadow: the line again, offset, in the shadow colour (under the text).
|
||||
if let Some(sc) = fm.text_shadow.and_then(|c| rgb_of(c, wb)) {
|
||||
let off = (size * 0.06).max(0.5);
|
||||
pg.text_with_direction(Point::new(lx + off, yy + off), size, font, sc, &l.text, l.direction);
|
||||
let [sx, sy] = turn([lx + off, yy + off]);
|
||||
pg.text_rotated_with_direction(Baseline { origin: Point::new(sx, sy), angle }, size, font, sc, &l.text, l.direction);
|
||||
}
|
||||
// WordArt's text outline, as on screen: the line in the outline colour, offset in eight
|
||||
// directions by half the outline width, under the filled text.
|
||||
@@ -237,10 +251,12 @@ fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Bl
|
||||
{
|
||||
let d = (ow * b.scale / 2.0).clamp(0.25, 20.0);
|
||||
for (dx, dy) in [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)] {
|
||||
pg.text_with_direction(Point::new(lx + dx * d, yy + dy * d), size, font, oc, &l.text, l.direction);
|
||||
let [ox, oy] = turn([lx + dx * d, yy + dy * d]);
|
||||
pg.text_rotated_with_direction(Baseline { origin: Point::new(ox, oy), angle }, size, font, oc, &l.text, l.direction);
|
||||
}
|
||||
}
|
||||
pg.text_with_direction(Point::new(lx, yy), size, font, color, &l.text, l.direction);
|
||||
let [tx, ty] = turn([lx, yy]);
|
||||
pg.text_rotated_with_direction(Baseline { origin: Point::new(tx, ty), angle }, size, font, color, &l.text, l.direction);
|
||||
yy += size * 1.2;
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,34 @@ fn pdf_export_keeps_safe_links_on_their_printed_pages() {
|
||||
assert!(!cropped.contains("/Dest ["));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_export_rotates_a_shape_outline_and_its_text() {
|
||||
let make_page = |rotation| {
|
||||
let mut s = s();
|
||||
let id = s
|
||||
.execute(
|
||||
"insert.shape",
|
||||
json!({"kind": "rectangle", "at": "A1", "width": 120, "height": 60, "text": "TURNED", "fill": "#FF0000", "line": "#0000FF"}),
|
||||
)
|
||||
.unwrap()["shape"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
if rotation != 0 {
|
||||
s.execute("object.move", json!({"kind": "shape", "id": id, "at": "A1", "rotation": rotation})).unwrap();
|
||||
}
|
||||
pdf_pages(&mut s).remove(0)
|
||||
};
|
||||
let upright = make_page(0);
|
||||
let turned = make_page(90);
|
||||
let red_path = |page: &str| {
|
||||
let start = page.find("1 0 0 rg").expect("red rectangle fill");
|
||||
let tail = &page[start..];
|
||||
let end = tail.find(" B").expect("filled and stroked rectangle path") + 2;
|
||||
tail[..end].to_string()
|
||||
};
|
||||
assert_ne!(red_path(&upright), red_path(&turned), "the rectangle's printed outline is rotated");
|
||||
assert!(turned.contains("0 -1 1 0") && turned.contains("(TURNED) Tj"), "shape text uses the rotation matrix: {turned}");
|
||||
}
|
||||
#[test]
|
||||
fn arabic_with_characters_its_font_lacks_still_exports() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -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)
|
||||
})?;
|
||||
|
||||
@@ -92,7 +92,7 @@ fn reapply_slicer(wb: &mut Workbook, sheet: usize, id: u32) {
|
||||
let off = abs_col.saturating_sub(af.range.start.col);
|
||||
af.criteria.retain(|(o, _)| *o != off);
|
||||
if let Some(values) = selected {
|
||||
af.criteria.push((off, FilterCriterion::Values { values, blanks: false }));
|
||||
af.criteria.push((off, FilterCriterion::Values { values, blanks: false, identities: Vec::new() }));
|
||||
}
|
||||
}
|
||||
super::data::apply_filter(wb, sheet);
|
||||
|
||||
@@ -194,6 +194,7 @@ fn insert_word_art(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
text: text.clone(),
|
||||
format: ShapeFormat { no_line: true, align: Some(ShapeTextAlign::Center), anchor: Some(ShapeTextAnchor::Middle), ..Default::default() },
|
||||
math: Default::default(),
|
||||
rotation: 0.0,
|
||||
};
|
||||
apply("insert.wordArt", &mut shape, Some(style), p)?;
|
||||
// Default box: the longest line at the font size (about 0.62 em per character) plus padding.
|
||||
|
||||
@@ -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;
|
||||
|
||||
+13
-14
@@ -140,11 +140,11 @@ fn decrypt_message(name: &str, e: gridcraft_xlsx::DecryptError) -> String {
|
||||
/// [`adopt_python`]) within the limits of [`enforce_python_limits`].
|
||||
fn open_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook, Vec<String>)> {
|
||||
let (mut wb, mut warnings) = read_plain(name, bytes, csv_as_text)?;
|
||||
crate::cmd::data::migrate_loaded_autofilters(&mut wb);
|
||||
warnings.extend(crate::macros::load(&mut wb));
|
||||
crate::cmd::controls::load_action_names(&mut wb);
|
||||
warnings.extend(adopt_python(&mut wb));
|
||||
warnings.extend(enforce_python_limits(&mut wb));
|
||||
crate::cmd::data::migrate_loaded_autofilters(&mut wb);
|
||||
Ok((wb, warnings))
|
||||
}
|
||||
|
||||
@@ -559,20 +559,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
|
||||
@@ -1063,6 +1056,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}"))
|
||||
|
||||
@@ -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() {
|
||||
@@ -586,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
|
||||
}
|
||||
|
||||
+148
-9
@@ -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();
|
||||
@@ -5702,6 +5790,56 @@ fn filtered_copy_with_many_runs_moves_notes_and_merges_with_their_rows() {
|
||||
assert_eq!(sh.merges.iter().filter(|m| m.start.col >= 7).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_move_refuses_to_rotate_ink() {
|
||||
let mut s = s();
|
||||
let id = s.execute("draw.stroke", json!({"points": [[0, 0], [30, 20], [60, 5]]})).unwrap()["shape"].clone();
|
||||
assert!(s.execute("object.move", json!({"kind": "shape", "id": id, "rotation": 45})).is_err());
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_move_rotates_shapes_only() {
|
||||
let mut s = s();
|
||||
let id = s.execute("insert.shape", json!({"kind": "rectangle"})).unwrap()["shape"].clone();
|
||||
s.execute("object.move", json!({"kind": "shape", "id": id, "rotation": -30})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 330.0);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 0.0);
|
||||
s.execute("selection.set", json!({"range": "A1"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
let chart = s.execute("insert.chart", json!({"type": "column"})).unwrap()["chart"].clone();
|
||||
assert!(s.execute("object.move", json!({"kind": "chart", "id": chart, "rotation": 45})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_move_rotation_respects_sheet_protection() {
|
||||
let mut s = s();
|
||||
let id = s.execute("insert.shape", json!({"kind": "rectangle", "at": "A1"})).unwrap()["shape"].clone();
|
||||
let id_num = id.as_u64().unwrap() as u32;
|
||||
let shape_state = |session: &Session| {
|
||||
let doc = session.doc().unwrap();
|
||||
let shape = doc.wb.active().unwrap().shapes.iter().find(|shape| shape.id == id_num).unwrap();
|
||||
(shape.anchor, shape.rotation)
|
||||
};
|
||||
|
||||
// Rotation remains available on an unprotected sheet.
|
||||
s.execute("object.move", json!({"kind": "shape", "id": id_num, "at": "B2", "rotation": 45})).unwrap();
|
||||
let (anchor, rotation) = shape_state(&s);
|
||||
assert_eq!(rotation, 45.0);
|
||||
assert_eq!(anchor.cell, CellRef::parse("B2").unwrap());
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
|
||||
s.execute("review.protectSheet", json!({})).unwrap();
|
||||
let before = shape_state(&s);
|
||||
let undo_len = s.doc().unwrap().undo.len();
|
||||
|
||||
let result = s.execute("object.move", json!({"kind": "shape", "id": id_num, "at": "C3", "rotation": 90}));
|
||||
assert!(result.is_err(), "rotation should be rejected on a protected sheet");
|
||||
assert_eq!(shape_state(&s), before, "a rejected rotation leaves the shape unchanged");
|
||||
assert_eq!(s.doc().unwrap().undo.len(), undo_len);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_quote_prefixed_text_keeps_it_text() {
|
||||
let mut s = s();
|
||||
@@ -6624,6 +6762,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}");
|
||||
}
|
||||
@@ -277,10 +277,10 @@ fn filter_by_selected_whitespace_cell_keeps_blanks_visible_2943() {
|
||||
assert!(!sh.is_row_hidden(5));
|
||||
}
|
||||
|
||||
/// Legacy saved criteria with whitespace-only `<filter val=" "/>` and `blanks: false` migrate on load and keep rows visible on reapply (#2943).
|
||||
/// Legacy saved criteria with whitespace-only `<filter val=" "/>` and `blanks: false` migrate on load and update row visibility immediately (#2943).
|
||||
#[test]
|
||||
fn restored_whitespace_only_criterion_keeps_rows_visible_on_reapply_2943() {
|
||||
use gridcraft_engine::cmd::data::{FilterChoice, filter_choices};
|
||||
use gridcraft_engine::cmd::data::{filter_choices, filter_choices_params};
|
||||
use gridcraft_model::{AutoFilter, FilterCriterion};
|
||||
|
||||
let mut s = Session::new();
|
||||
@@ -292,6 +292,7 @@ fn restored_whitespace_only_criterion_keeps_rows_visible_on_reapply_2943() {
|
||||
"parse": false,
|
||||
"values": [
|
||||
["Name"],
|
||||
[null],
|
||||
[" "],
|
||||
["Card"]
|
||||
]
|
||||
@@ -299,48 +300,177 @@ fn restored_whitespace_only_criterion_keeps_rows_visible_on_reapply_2943() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Simulate a legacy saved workbook whose filter stored `values: [" "]` with `blanks: false`.
|
||||
// Simulate a legacy saved workbook whose filter stored `values: [" "]` with `blanks: false`,
|
||||
// and where the genuinely empty row (row 1 = A2) was hidden by the pre-fix blank branch.
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.autofilter = Some(AutoFilter {
|
||||
range: gridcraft_core::RangeRef::parse("A1:A4").unwrap(),
|
||||
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
|
||||
});
|
||||
sh.rows.entry(1).or_default().hidden = true;
|
||||
sh.rows.entry(3).or_default().hidden = true;
|
||||
}
|
||||
|
||||
// 1. XLSX save + reopen migrates `<filter val=" "/>` AND reapplies immediately on open so
|
||||
// the genuinely empty row A2 is visible before any user `data.reapply` command.
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
|
||||
let (reopened, _) = gridcraft_engine::io::open_bytes("legacy_filter.xlsx", &bytes).unwrap();
|
||||
{
|
||||
let sh = reopened.sheet(0).unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "genuinely empty row must be visible immediately on open");
|
||||
assert!(!sh.is_row_hidden(2), "whitespace-only row must be visible immediately on open");
|
||||
assert!(sh.is_row_hidden(3), "non-matching row must remain hidden on open");
|
||||
}
|
||||
s.active_mut().unwrap().wb = std::sync::Arc::new(reopened);
|
||||
|
||||
// 2. Direct in-memory legacy criterion (`blanks: false`, `values: [" "]`) also keeps blank rows visible on reapply.
|
||||
{
|
||||
let wb = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().wb);
|
||||
wb.sheet_mut(0).unwrap().autofilter = Some(AutoFilter {
|
||||
range: gridcraft_core::RangeRef::parse("A1:A3").unwrap(),
|
||||
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false })],
|
||||
range: gridcraft_core::RangeRef::parse("A1:A4").unwrap(),
|
||||
criteria: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
|
||||
});
|
||||
}
|
||||
// 1. Direct in-memory legacy criterion (`blanks: false`, `values: [" "]`) keeps rows visible on reapply.
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "in-memory legacy whitespace-only row must stay visible after reapply");
|
||||
assert!(sh.is_row_hidden(2), "non-matching row must be hidden after reapply");
|
||||
assert!(!sh.is_row_hidden(1), "in-memory legacy empty row must stay visible after reapply");
|
||||
assert!(!sh.is_row_hidden(2), "in-memory legacy whitespace-only row must stay visible after reapply");
|
||||
assert!(sh.is_row_hidden(3), "non-matching row must be hidden after reapply");
|
||||
|
||||
// 2. XLSX save + reopen migrates `<filter val=" "/>` and keeps rows visible on reapply.
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap();
|
||||
let (reopened, _) = gridcraft_engine::io::open_bytes("legacy_filter.xlsx", &bytes).unwrap();
|
||||
s.active_mut().unwrap().wb = std::sync::Arc::new(reopened);
|
||||
|
||||
s.execute("data.reapply", json!({})).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "restored whitespace-only row must stay visible after reapply");
|
||||
assert!(sh.is_row_hidden(2), "non-matching row must be hidden after reapply");
|
||||
|
||||
// Also verify Show Formulas mode and literal `(Blanks)` vs `'(Blanks)'` dropdown separation.
|
||||
// 3. Verify Show Formulas mode: distinct qualified labels, preserved checklist identity on Apply,
|
||||
// single label for ordinary whitespace variants, and literal `(Blanks)` vs `'(Blanks)'` separation.
|
||||
let mut s2 = Session::new();
|
||||
s2.new_workbook();
|
||||
s2.execute("cell.set", json!({"cell": "A1", "input": "Name"})).unwrap();
|
||||
s2.execute("cell.set", json!({"cell": "A2", "input": "=\" Card \""})).unwrap();
|
||||
s2.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [[" =\" Card \" "], ["(Blanks)"], ["'(Blanks)'"], [" "]]}))
|
||||
.unwrap();
|
||||
s2.execute(
|
||||
"range.setValues",
|
||||
json!({
|
||||
"range": "A3",
|
||||
"parse": false,
|
||||
"values": [[" =\" Card \" "], ["Card"], [" Card "], ["(Blanks)"], ["'(Blanks)'"], [" "]]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
s2.execute("formulas.showFormulas", json!({"on": true})).unwrap();
|
||||
s2.execute("data.filterBy", json!({"column": "A", "values": ["Card"], "blanks": false})).unwrap();
|
||||
|
||||
// With no active criterion, ordinary whitespace variants `"Card"` and `" Card "` merge into one `"Card"` label,
|
||||
// while formula `=" Card "` and literal `" =\" Card \" "` have distinct qualified labels.
|
||||
s2.execute("data.filter", json!({"range": "A1:A8"})).unwrap();
|
||||
let initial_choices = filter_choices(&s2.doc().unwrap().wb, 0, 0);
|
||||
assert_eq!(initial_choices.iter().filter(|c| c.label == "Card").count(), 1, "{initial_choices:?}");
|
||||
let formula_like_labels: Vec<_> = initial_choices.iter().filter(|c| c.label.starts_with("=\" Card \"")).map(|c| c.label.as_str()).collect();
|
||||
assert_eq!(formula_like_labels.len(), 2, "{initial_choices:?}");
|
||||
assert_ne!(formula_like_labels[0], formula_like_labels[1], "colliding identities must have distinct labels: {initial_choices:?}");
|
||||
|
||||
// Filtering by `"Card"` checks `"Card"` and formula `=" Card "`, leaving literal `" =\" Card \" "` unchecked.
|
||||
s2.execute("data.filterBy", json!({"column": "A", "values": ["Card"], "blanks": false})).unwrap();
|
||||
let choices = filter_choices(&s2.doc().unwrap().wb, 0, 0);
|
||||
// Formula `=" Card "` and literal ` =" Card " ` stay separate under Show Formulas; only the formula row is checked.
|
||||
let formula_like: Vec<_> = choices.iter().filter(|c| c.label.contains("=\" Card \"")).collect();
|
||||
assert_eq!(formula_like.len(), 2, "formula and literal text must keep distinct filter identities: {choices:?}");
|
||||
assert_eq!(formula_like.iter().filter(|c| c.checked).count(), 1, "only the matching formula row is checked: {choices:?}");
|
||||
let formula_entry = choices.iter().find(|c| c.label == "=\" Card \" (result: Card)").expect("formula choice");
|
||||
let literal_entry = choices.iter().find(|c| c.label == "=\" Card \" (text)").expect("literal choice");
|
||||
assert!(formula_entry.checked, "{choices:?}");
|
||||
assert!(!literal_entry.checked, "{choices:?}");
|
||||
|
||||
// Clicking Apply without changing the checks keeps the literal `" =\" Card \" "` row hidden.
|
||||
let unchanged_checks: Vec<_> = choices.iter().map(|c| (c, c.checked)).collect();
|
||||
s2.execute("data.filterBy", filter_choices_params("A", &unchanged_checks)).unwrap();
|
||||
let sh2 = s2.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh2.is_row_hidden(1), "formula row A2 stays visible");
|
||||
assert!(sh2.is_row_hidden(2), "literal row A3 stays hidden");
|
||||
assert!(!sh2.is_row_hidden(3), "Card row A4 stays visible");
|
||||
assert!(!sh2.is_row_hidden(4), "whitespace Card row A5 stays visible");
|
||||
|
||||
// Selecting ONLY the formula checkbox leaves the literal row hidden (and vice versa).
|
||||
let only_formula: Vec<_> = choices.iter().map(|c| (c, c.label == "=\" Card \" (result: Card)")).collect();
|
||||
s2.execute("data.filterBy", filter_choices_params("A", &only_formula)).unwrap();
|
||||
let sh2 = s2.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh2.is_row_hidden(1), "formula row A2 visible");
|
||||
assert!(sh2.is_row_hidden(2), "literal row A3 hidden");
|
||||
assert!(sh2.is_row_hidden(3), "Card row A4 hidden");
|
||||
|
||||
let only_literal: Vec<_> = choices.iter().map(|c| (c, c.label == "=\" Card \" (text)")).collect();
|
||||
s2.execute("data.filterBy", filter_choices_params("A", &only_literal)).unwrap();
|
||||
let sh2 = s2.doc().unwrap().wb.active().unwrap();
|
||||
assert!(sh2.is_row_hidden(1), "formula row A2 hidden");
|
||||
assert!(!sh2.is_row_hidden(2), "literal row A3 visible");
|
||||
assert!(sh2.is_row_hidden(3), "Card row A4 hidden");
|
||||
|
||||
// Literal `(Blanks)`, literal `'(Blanks)'`, and the actual `(Blanks)` toggle all have distinct labels and values.
|
||||
assert!(choices.contains(&FilterChoice { label: "(Blanks)".into(), value: None, checked: false }), "{choices:?}");
|
||||
assert!(choices.contains(&FilterChoice { label: "'(Blanks)'".into(), value: Some("(Blanks)".into()), checked: false }), "{choices:?}");
|
||||
assert!(choices.contains(&FilterChoice { label: "''(Blanks)''".into(), value: Some("'(Blanks)'".into()), checked: false }), "{choices:?}");
|
||||
assert!(choices.iter().any(|c| c.label == "(Blanks)" && c.value.is_none() && c.identity.is_none()), "{choices:?}");
|
||||
assert!(choices.iter().any(|c| c.label == "'(Blanks)'" && c.value.as_deref() == Some("(Blanks)")), "{choices:?}");
|
||||
assert!(choices.iter().any(|c| c.label == "''(Blanks)''" && c.value.as_deref() == Some("'(Blanks)'")), "{choices:?}");
|
||||
}
|
||||
|
||||
/// Nonblank cells formatted to display only spaces stay selectable in both dropdown and selected-cell actions (#2943).
|
||||
#[test]
|
||||
fn nonblank_space_formatted_cells_stay_selectable_2943() {
|
||||
use gridcraft_core::CellRef;
|
||||
use gridcraft_engine::cmd::data::{filter_by_cell_params, filter_choices, filter_choices_params};
|
||||
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
|
||||
s.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [[null], [" "], ["Card"]]})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "A1:A5"})).unwrap();
|
||||
|
||||
// 1. Dropdown checklist: selecting only the space-formatted `42` entry keeps row A2 visible and hides blanks.
|
||||
let choices = filter_choices(&s.doc().unwrap().wb, 0, 0);
|
||||
let num_choice = choices.iter().find(|c| c.value.as_deref() == Some("42")).expect("numeric 42 choice");
|
||||
assert_eq!(num_choice.label, "42");
|
||||
let only_42: Vec<_> = choices.iter().map(|c| (c, c.value.as_deref() == Some("42"))).collect();
|
||||
s.execute("data.filterBy", filter_choices_params("A", &only_42)).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "space-formatted 42 row A2 must stay visible");
|
||||
assert!(sh.is_row_hidden(2), "empty row A3 must be hidden");
|
||||
assert!(sh.is_row_hidden(3), "whitespace text row A4 must be hidden");
|
||||
assert!(sh.is_row_hidden(4), "Card row A5 must be hidden");
|
||||
|
||||
// 2. Selected-cell action (`filter_by_cell_params`): on A2 (`42` formatted as `" "`) selects `42`, not blanks;
|
||||
// on A4 (`" "` text) selects blanks, not `42`.
|
||||
s.execute("data.clearFilter", json!({})).unwrap();
|
||||
let params_a2 = {
|
||||
let d = s.doc().unwrap();
|
||||
filter_by_cell_params(&d.wb, d.wb.active().unwrap(), CellRef::parse("A2").unwrap(), "A")
|
||||
};
|
||||
s.execute("data.filterBy", params_a2).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1), "A2 selected-cell filter keeps 42 visible");
|
||||
assert!(sh.is_row_hidden(2), "A2 selected-cell filter hides empty row");
|
||||
assert!(sh.is_row_hidden(3), "A2 selected-cell filter hides whitespace text row");
|
||||
|
||||
let params_a4 = {
|
||||
let d = s.doc().unwrap();
|
||||
filter_by_cell_params(&d.wb, d.wb.active().unwrap(), CellRef::parse("A4").unwrap(), "A")
|
||||
};
|
||||
s.execute("data.filterBy", params_a4).unwrap();
|
||||
let sh = s.doc().unwrap().wb.active().unwrap();
|
||||
assert!(sh.is_row_hidden(1), "A4 selected-cell filter hides 42");
|
||||
assert!(!sh.is_row_hidden(2), "A4 selected-cell filter keeps empty row visible");
|
||||
assert!(!sh.is_row_hidden(3), "A4 selected-cell filter keeps whitespace text row visible");
|
||||
|
||||
// 3. Formatted-blank number `42` vs formatted-blank text `"42"` (`;;;`) keep distinct qualified labels,
|
||||
// and a >11-digit General number (`1234567890123`) keeps its checklist identity across Show Formulas toggles.
|
||||
let mut s3 = Session::new();
|
||||
s3.new_workbook();
|
||||
s3.execute("cell.set", json!({"cell": "A1", "input": "Val"})).unwrap();
|
||||
s3.execute("cell.set", json!({"cell": "A2", "input": "42"})).unwrap();
|
||||
s3.execute("home.numberFormat", json!({"range": "A2", "format": "\" \""})).unwrap();
|
||||
s3.execute("range.setValues", json!({"range": "A3", "parse": false, "values": [["42"]]})).unwrap();
|
||||
s3.execute("home.numberFormat", json!({"range": "A3", "format": ";;;"})).unwrap();
|
||||
s3.execute("cell.set", json!({"cell": "A4", "input": "1234567890123"})).unwrap();
|
||||
s3.execute("data.filter", json!({"range": "A1:A4"})).unwrap();
|
||||
|
||||
let c3 = filter_choices(&s3.doc().unwrap().wb, 0, 0);
|
||||
assert!(c3.iter().any(|c| c.label == "42 (formatted blank, number)"), "{c3:?}");
|
||||
assert!(c3.iter().any(|c| c.label == "42 (formatted blank, text)"), "{c3:?}");
|
||||
|
||||
let only_big: Vec<_> = c3.iter().map(|c| (c, c.value.as_deref() == Some("1.23457E+12"))).collect();
|
||||
s3.execute("data.filterBy", filter_choices_params("A", &only_big)).unwrap();
|
||||
s3.execute("formulas.showFormulas", json!({"on": true})).unwrap();
|
||||
s3.execute("data.reapply", json!({})).unwrap();
|
||||
assert!(!s3.doc().unwrap().wb.active().unwrap().is_row_hidden(3), "1234567890123 stays visible across Show Formulas toggle");
|
||||
}
|
||||
@@ -33,6 +33,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> {
|
||||
|
||||
@@ -690,6 +690,9 @@ pub struct Shape {
|
||||
/// Outline visibility and text formatting (DrawingML `a:ln`, `a:bodyPr`, `a:pPr`, `a:rPr`).
|
||||
#[serde(default)]
|
||||
pub format: ShapeFormat,
|
||||
/// Degrees clockwise about the anchor rect's centre, in `[0, 360)`.
|
||||
#[serde(default)]
|
||||
pub rotation: f32,
|
||||
/// An equation's layout, rebuilt from `text` and never saved.
|
||||
#[serde(skip)]
|
||||
pub math: EquationCache,
|
||||
@@ -1067,6 +1070,10 @@ pub enum FilterCriterion {
|
||||
Values {
|
||||
values: Vec<String>,
|
||||
blanks: bool,
|
||||
/// Exact checklist identities from dropdown or selected-cell UI actions so rows whose
|
||||
/// formatted display text collides (for example under Show Formulas) stay distinct.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
identities: Vec<String>,
|
||||
},
|
||||
/// Custom: one or two comparisons (`op` like `>=`, `=*abc*`), joined by and/or.
|
||||
Custom {
|
||||
|
||||
@@ -946,6 +946,7 @@ mod tests {
|
||||
fill: Color::default(),
|
||||
line: Color::default(),
|
||||
text: String::new(),
|
||||
rotation: 0.0,
|
||||
format: ShapeFormat::default(),
|
||||
math: EquationCache::default(),
|
||||
}),
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
|
||||
|
||||
+182
-12
@@ -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))
|
||||
@@ -385,6 +388,9 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
|
||||
if label && !sp.text.is_empty() && !app.editing_text_box(sp.id) {
|
||||
paint_shape_text(p, wb, sp, r, geo.z);
|
||||
}
|
||||
if sp.rotation != 0.0 {
|
||||
turn_painted(p, start, r.center(), sp.rotation);
|
||||
}
|
||||
done(start, r);
|
||||
}
|
||||
for im in &sh.images {
|
||||
@@ -428,11 +434,13 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
|
||||
}
|
||||
// The selected object's frame and handles go over every object, and move with it on a
|
||||
// right-to-left sheet.
|
||||
if let Some(r) = app.selected_object.and_then(|o| object_rect(geo, sh, o))
|
||||
if let Some(o) = app.selected_object
|
||||
&& let Some(r) = object_rect(geo, sh, o)
|
||||
&& r.intersects(p.clip_rect())
|
||||
{
|
||||
let start = p.add(egui::Shape::Noop);
|
||||
selection_frame(p, r);
|
||||
let (deg, rotates, resizes) = frame_of(sh, o);
|
||||
crate::frame::paint(p, r, deg, rotates, resizes);
|
||||
done(start, r);
|
||||
}
|
||||
painted
|
||||
@@ -540,16 +548,97 @@ pub fn slicer_click(geo: &Geo, sh: &Sheet, wb: &Workbook, si: usize, p: Pos2) ->
|
||||
None
|
||||
}
|
||||
|
||||
fn selection_frame(p: &Painter, r: Rect) {
|
||||
let t = Tokens::get(p.ctx());
|
||||
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.sheet_control_border), StrokeKind::Outside);
|
||||
for h in crate::objects::Handle::ALL {
|
||||
let c = h.pos(r);
|
||||
p.circle_filled(c, 4.0, t.sheet_control_bg);
|
||||
p.circle_stroke(c, 4.0, Stroke::new(1.0, t.sheet_control_border));
|
||||
/// The selected object's turn in degrees, and whether its frame shows a rotation handle and
|
||||
/// resize handles (an ink stroke shows neither).
|
||||
pub fn frame_of(sh: &Sheet, o: ObjRef) -> (f32, bool, bool) {
|
||||
match sh.shapes.iter().find(|s| o.kind == ObjKind::Shape && s.id == o.id) {
|
||||
Some(s) => (s.rotation, s.kind != ShapeKind::Ink, s.kind != ShapeKind::Ink),
|
||||
None => (0.0, false, true),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))
|
||||
@@ -565,7 +654,22 @@ pub fn selected_handle(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option
|
||||
}
|
||||
let o = app.selected_object?;
|
||||
let r = object_rect(geo, sh, o)?;
|
||||
crate::objects::handle_at(r, p).map(|h| (o, r, h))
|
||||
let (deg, _, resizes) = frame_of(sh, o);
|
||||
if !resizes {
|
||||
return None;
|
||||
}
|
||||
crate::objects::handle_at(r, crate::frame::turn(p, r.center(), -deg)).map(|h| (o, r, h))
|
||||
}
|
||||
|
||||
/// The selected object and its rect when `p` is on its rotation handle.
|
||||
pub fn selected_rotate(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(ObjRef, Rect)> {
|
||||
if !geo.cells.contains(p) || app.session.active().is_some_and(|d| objects_hidden(&d.wb)) {
|
||||
return None;
|
||||
}
|
||||
let o = app.selected_object?;
|
||||
let r = object_rect(geo, sh, o)?;
|
||||
let (deg, rotates, _) = frame_of(sh, o);
|
||||
(rotates && matches!(crate::frame::grab_at(r, deg, true, p), Some(crate::frame::Grab::Rotate))).then_some((o, r))
|
||||
}
|
||||
|
||||
/// The topmost object under `p` and its rect: form controls paint on top, so they are hit first,
|
||||
@@ -601,7 +705,7 @@ pub fn hit(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(ObjRef, Re
|
||||
}
|
||||
for s in sh.shapes.iter().rev() {
|
||||
let r = anchor_rect(geo, sh, &s.anchor);
|
||||
if r.expand(3.0).contains(p) {
|
||||
if r.expand(3.0).contains(crate::frame::turn(p, r.center(), -s.rotation)) {
|
||||
let kind = if s.kind == ShapeKind::Equation { ObjKind::Equation } else { ObjKind::Shape };
|
||||
return Some((ObjRef::new(kind, s.id), r));
|
||||
}
|
||||
@@ -615,6 +719,72 @@ pub(crate) fn ink_color(line: Color32, width_pt: f32) -> Color32 {
|
||||
if width_pt > 8.0 { line.gamma_multiply(0.45) } else { line }
|
||||
}
|
||||
|
||||
/// Turn everything painted on `p`'s layer since `start` by `deg` clockwise about `c`.
|
||||
fn turn_painted(p: &Painter, start: egui::layers::ShapeIdx, c: Pos2, deg: f32) {
|
||||
let end = p.add(egui::Shape::Noop).0;
|
||||
let clip = p.clip_rect();
|
||||
p.ctx().graphics_mut(|g| {
|
||||
let list = g.entry(p.layer_id());
|
||||
for i in start.0..end {
|
||||
list.mutate_shape(egui::layers::ShapeIdx(i), |cs| {
|
||||
// A turned shape reaches past its own box: clip it to the sheet only.
|
||||
cs.clip_rect = clip;
|
||||
turn_shape(&mut cs.shape, c, deg);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn turn_shape(shape: &mut egui::Shape, c: Pos2, deg: f32) {
|
||||
use egui::Shape;
|
||||
let t = |q: &mut Pos2| *q = crate::frame::turn(*q, c, deg);
|
||||
match shape {
|
||||
Shape::Noop | Shape::Callback(_) | Shape::Band(_) => {}
|
||||
Shape::Vec(v) => v.iter_mut().for_each(|s| turn_shape(s, c, deg)),
|
||||
Shape::Circle(k) => t(&mut k.center),
|
||||
Shape::Ellipse(e) => {
|
||||
let pts = (0..64)
|
||||
.map(|i| {
|
||||
let a = i as f32 / 64.0 * std::f32::consts::TAU;
|
||||
crate::frame::turn(e.center + vec2(e.radius.x * a.cos(), e.radius.y * a.sin()), c, deg)
|
||||
})
|
||||
.collect();
|
||||
*shape = Shape::Path(PathShape::convex_polygon(pts, e.fill, e.stroke));
|
||||
}
|
||||
Shape::LineSegment { points, .. } => points.iter_mut().for_each(t),
|
||||
Shape::Path(path) => path.points.iter_mut().for_each(t),
|
||||
Shape::Rect(r) => {
|
||||
let pts = rounded_rect_points(r.rect, f32::from(r.corner_radius.nw)).into_iter().map(|q| crate::frame::turn(q, c, deg)).collect();
|
||||
*shape = Shape::Path(PathShape::convex_polygon(pts, r.fill, r.stroke));
|
||||
}
|
||||
Shape::Text(text) => {
|
||||
t(&mut text.pos);
|
||||
text.angle += deg.to_radians();
|
||||
}
|
||||
Shape::Mesh(m) => std::sync::Arc::make_mut(m).vertices.iter_mut().for_each(|v| t(&mut v.pos)),
|
||||
Shape::QuadraticBezier(b) => b.points.iter_mut().for_each(t),
|
||||
Shape::CubicBezier(b) => b.points.iter_mut().for_each(t),
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline of `r` with corners rounded by `radius`, clockwise from the top left.
|
||||
fn rounded_rect_points(r: Rect, radius: f32) -> Vec<Pos2> {
|
||||
let rad = radius.min(r.width() / 2.0).min(r.height() / 2.0).max(0.0);
|
||||
if rad < 0.5 {
|
||||
return vec![r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()];
|
||||
}
|
||||
let corners = [
|
||||
(pos2(r.left() + rad, r.top() + rad), 180.0_f32),
|
||||
(pos2(r.right() - rad, r.top() + rad), 270.0),
|
||||
(pos2(r.right() - rad, r.bottom() - rad), 0.0),
|
||||
(pos2(r.left() + rad, r.bottom() - rad), 90.0),
|
||||
];
|
||||
corners
|
||||
.into_iter()
|
||||
.flat_map(|(o, from)| (0..=8).map(move |i| (from + i as f32 * 90.0 / 8.0).to_radians()).map(move |a| o + vec2(a.cos(), a.sin()) * rad))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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."));
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! The selection frame around a floating object (chart, picture, shape, slicer): its eight
|
||||
//! handles, the rotation handle above a shape, which one a press grabs, and the rect a handle
|
||||
//! drag gives. A turned frame is the rect turned about its centre, `deg` clockwise.
|
||||
|
||||
use egui::{CursorIcon, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2};
|
||||
|
||||
/// Handle radius and the radius a press grabs a handle within (screen points).
|
||||
pub const HANDLE_R: f32 = 4.0;
|
||||
const GRAB_R: f32 = 10.0;
|
||||
/// Frames smaller than this (screen points) show only corner handles on that axis.
|
||||
const EDGE_HANDLES_FROM: f32 = 40.0;
|
||||
/// How far the rotation handle sits above the frame's top edge (screen points), and the step
|
||||
/// Shift snaps the angle to (degrees).
|
||||
const ROTATE_GAP: f32 = 22.0;
|
||||
pub const SNAP_DEG: f32 = 15.0;
|
||||
|
||||
/// Screen point `p` turned `deg` degrees clockwise about `c`.
|
||||
pub fn turn(p: Pos2, c: Pos2, deg: f32) -> Pos2 {
|
||||
let (s, k) = deg.to_radians().sin_cos();
|
||||
let (u, v) = (p.x - c.x, p.y - c.y);
|
||||
pos2(c.x + u * k - v * s, c.y + u * s + v * k)
|
||||
}
|
||||
|
||||
/// One of the eight handles: `x` / `y` are -1 (left/top), 0 (middle) or 1 (right/bottom).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Handle {
|
||||
pub x: i8,
|
||||
pub y: i8,
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
pub const ALL: [Handle; 8] = [
|
||||
Handle { x: -1, y: -1 },
|
||||
Handle { x: 0, y: -1 },
|
||||
Handle { x: 1, y: -1 },
|
||||
Handle { x: 1, y: 0 },
|
||||
Handle { x: 1, y: 1 },
|
||||
Handle { x: 0, y: 1 },
|
||||
Handle { x: -1, y: 1 },
|
||||
Handle { x: -1, y: 0 },
|
||||
];
|
||||
pub fn is_corner(self) -> bool {
|
||||
self.x != 0 && self.y != 0
|
||||
}
|
||||
/// The resize cursor, picked for the handle's direction on a frame turned `deg`.
|
||||
pub fn cursor(self, deg: f32) -> CursorIcon {
|
||||
let a = f32::from(self.y).atan2(f32::from(self.x)).to_degrees() + deg;
|
||||
// Eight compass sectors of 45°; opposite sectors share a cursor.
|
||||
match ((a / 45.0).round() as i32).rem_euclid(4) {
|
||||
0 => CursorIcon::ResizeHorizontal,
|
||||
1 => CursorIcon::ResizeNwSe,
|
||||
2 => CursorIcon::ResizeVertical,
|
||||
_ => CursorIcon::ResizeNeSw,
|
||||
}
|
||||
}
|
||||
pub fn at(self, f: Rect) -> Pos2 {
|
||||
let k = |v: i8| (f32::from(v) + 1.0) / 2.0;
|
||||
pos2(f.min.x + f.width() * k(self.x), f.min.y + f.height() * k(self.y))
|
||||
}
|
||||
pub fn at_turned(self, f: Rect, deg: f32) -> Pos2 {
|
||||
turn(self.at(f), f.center(), deg)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a press on a selected object grabbed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Grab {
|
||||
Move,
|
||||
Resize(Handle),
|
||||
Rotate,
|
||||
}
|
||||
|
||||
impl Grab {
|
||||
pub fn cursor(self, deg: f32) -> CursorIcon {
|
||||
match self {
|
||||
Grab::Move => CursorIcon::Move,
|
||||
Grab::Resize(h) => h.cursor(deg),
|
||||
Grab::Rotate => CursorIcon::Crosshair,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The handles a frame shows: corners always, edge middles when there's room.
|
||||
pub fn handles(f: Rect) -> impl Iterator<Item = Handle> {
|
||||
let (wide, tall) = (f.width() >= EDGE_HANDLES_FROM, f.height() >= EDGE_HANDLES_FROM);
|
||||
Handle::ALL.into_iter().filter(move |h| (h.x != 0 || wide) && (h.y != 0 || tall))
|
||||
}
|
||||
|
||||
/// Where the rotation handle of frame `f` turned `deg` is: above the middle of its top edge.
|
||||
pub fn rotate_handle(f: Rect, deg: f32) -> Pos2 {
|
||||
turn(pos2(f.center().x, f.min.y - ROTATE_GAP), f.center(), deg)
|
||||
}
|
||||
|
||||
/// The handle of frame `f` turned `deg` under screen point `p`; `rotate` offers the rotation
|
||||
/// handle too.
|
||||
pub fn grab_at(f: Rect, deg: f32, rotate: bool, p: Pos2) -> Option<Grab> {
|
||||
if rotate && rotate_handle(f, deg).distance(p) <= GRAB_R {
|
||||
return Some(Grab::Rotate);
|
||||
}
|
||||
let d = |h: &Handle| h.at_turned(f, deg).distance(p);
|
||||
handles(f).filter(|h| d(h) <= GRAB_R).min_by(|a, b| d(a).total_cmp(&d(b))).map(Grab::Resize)
|
||||
}
|
||||
|
||||
/// The angle (degrees clockwise, `[0, 360)`) that points frame `f`'s rotation handle at `p`,
|
||||
/// by whole degrees or, with `snap`, by [`SNAP_DEG`].
|
||||
pub fn angle_to(f: Rect, p: Pos2, snap: bool) -> f32 {
|
||||
let d = p - f.center();
|
||||
// The handle is straight up (-90°) when unturned.
|
||||
let deg = d.y.atan2(d.x).to_degrees() + 90.0;
|
||||
let step = if snap { SNAP_DEG } else { 1.0 };
|
||||
((deg / step).round() * step).rem_euclid(360.0)
|
||||
}
|
||||
|
||||
/// Draw frame `f` turned `deg`: outline, handles and, with `rotate`, the rotation handle.
|
||||
pub fn paint(p: &Painter, f: Rect, deg: f32, rotate: bool, resize: bool) {
|
||||
let line = Stroke::new(1.0, egui::Color32::from_gray(120));
|
||||
if deg == 0.0 {
|
||||
p.rect_stroke(f, 0.0, line, StrokeKind::Outside);
|
||||
} else {
|
||||
let c = f.center();
|
||||
let pts = [f.left_top(), f.right_top(), f.right_bottom(), f.left_bottom(), f.left_top()].map(|q| turn(q, c, deg));
|
||||
p.add(egui::Shape::line(pts.to_vec(), line));
|
||||
}
|
||||
let knob = |c: Pos2| {
|
||||
p.circle_filled(c, HANDLE_R, egui::Color32::WHITE);
|
||||
p.circle_stroke(c, HANDLE_R, Stroke::new(1.0, egui::Color32::from_gray(100)));
|
||||
};
|
||||
if rotate {
|
||||
let r = rotate_handle(f, deg);
|
||||
p.line_segment([turn(f.center_top(), f.center(), deg), r], line);
|
||||
knob(r);
|
||||
// A circling arrow: three quarters of a ring.
|
||||
let ring: Vec<Pos2> = (0..=12).map(|i| r + vec2((i as f32 * 0.4).cos(), (i as f32 * 0.4).sin()) * (HANDLE_R * 0.55)).collect();
|
||||
p.add(egui::Shape::line(ring, Stroke::new(1.0, egui::Color32::from_gray(80))));
|
||||
}
|
||||
if resize {
|
||||
for h in handles(f) {
|
||||
knob(h.at_turned(f, deg));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`resized`] for a frame turned `deg`: the drag is taken along the frame's own axes, and the
|
||||
/// handle opposite the grabbed one stays where it is.
|
||||
pub fn resized_turned(r: Rect, deg: f32, h: Handle, d: egui::Vec2, min: f32, keep_aspect: bool) -> Rect {
|
||||
resized_turned_by_min(r, deg, h, d, egui::Vec2::splat(min), keep_aspect)
|
||||
}
|
||||
|
||||
/// Axis-aware version for objects with a zero-height or zero-width minimum.
|
||||
pub(crate) fn resized_turned_by_min(r: Rect, deg: f32, h: Handle, d: egui::Vec2, min: egui::Vec2, keep_aspect: bool) -> Rect {
|
||||
if deg == 0.0 {
|
||||
return resized_by_min(r, h, d, min, keep_aspect);
|
||||
}
|
||||
let local = turn(pos2(d.x, d.y), Pos2::ZERO, -deg).to_vec2();
|
||||
let n = resized_by_min(r, h, local, min, keep_aspect);
|
||||
let opp = Handle { x: -h.x, y: -h.y };
|
||||
n.translate(opp.at_turned(r, deg) - opp.at_turned(n, deg))
|
||||
}
|
||||
|
||||
/// `r` with handle `h` dragged by `d`; the opposite edges stay put. Never smaller than `min`;
|
||||
/// `keep_aspect` keeps the proportions when a corner is dragged.
|
||||
pub fn resized(r: Rect, h: Handle, d: egui::Vec2, min: f32, keep_aspect: bool) -> Rect {
|
||||
resized_by_min(r, h, d, egui::Vec2::splat(min), keep_aspect)
|
||||
}
|
||||
|
||||
fn resized_by_min(r: Rect, h: Handle, d: egui::Vec2, min: egui::Vec2, keep_aspect: bool) -> Rect {
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (r.min.x, r.min.y, r.max.x, r.max.y);
|
||||
match h.x {
|
||||
-1 => x0 = (x0 + d.x).min(x1 - min.x),
|
||||
1 => x1 = (x1 + d.x).max(x0 + min.x),
|
||||
_ => {}
|
||||
}
|
||||
match h.y {
|
||||
-1 => y0 = (y0 + d.y).min(y1 - min.y),
|
||||
1 => y1 = (y1 + d.y).max(y0 + min.y),
|
||||
_ => {}
|
||||
}
|
||||
if keep_aspect && h.is_corner() && r.width() > 0.0 && r.height() > 0.0 {
|
||||
// Follow whichever side changed more.
|
||||
let (kx, ky) = ((x1 - x0) / r.width(), (y1 - y0) / r.height());
|
||||
let k = if (kx - 1.0).abs() >= (ky - 1.0).abs() { kx } else { ky };
|
||||
let k = k.max(min.x / r.width()).max(min.y / r.height());
|
||||
let (w, hh) = (r.width() * k, r.height() * k);
|
||||
if h.x < 0 {
|
||||
x0 = x1 - w;
|
||||
} else {
|
||||
x1 = x0 + w;
|
||||
}
|
||||
if h.y < 0 {
|
||||
y0 = y1 - hh;
|
||||
} else {
|
||||
y1 = y0 + hh;
|
||||
}
|
||||
}
|
||||
Rect::from_min_max(pos2(x0, y0), pos2(x1, y1))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::vec2;
|
||||
|
||||
fn r() -> Rect {
|
||||
Rect::from_min_size(pos2(100.0, 100.0), vec2(200.0, 100.0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_left_handle_moves_only_the_left_edge() {
|
||||
let n = resized(r(), Handle { x: -1, y: 0 }, vec2(-30.0, 50.0), 20.0, false);
|
||||
assert_eq!(n, Rect::from_min_max(pos2(70.0, 100.0), pos2(300.0, 200.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_top_left_corner_never_crosses_the_opposite_edges() {
|
||||
let n = resized(r(), Handle { x: -1, y: -1 }, vec2(500.0, 500.0), 20.0, false);
|
||||
assert_eq!(n, Rect::from_min_max(pos2(280.0, 180.0), pos2(300.0, 200.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_keeps_the_proportions() {
|
||||
let n = resized(r(), Handle { x: 1, y: 1 }, vec2(200.0, 0.0), 20.0, true);
|
||||
assert_eq!(n.size(), vec2(400.0, 200.0));
|
||||
assert_eq!(n.min, r().min);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_frames_drop_the_edge_handles() {
|
||||
let small = Rect::from_min_size(pos2(0.0, 0.0), vec2(30.0, 100.0));
|
||||
assert!(handles(small).all(|h| h.x != 0));
|
||||
assert_eq!(handles(r()).count(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursors_follow_the_turned_handle() {
|
||||
let right = Handle { x: 1, y: 0 };
|
||||
assert_eq!(right.cursor(0.0), CursorIcon::ResizeHorizontal);
|
||||
assert_eq!(right.cursor(90.0), CursorIcon::ResizeVertical);
|
||||
assert_eq!(right.cursor(45.0), CursorIcon::ResizeNwSe);
|
||||
assert_eq!(Handle { x: 1, y: -1 }.cursor(0.0), CursorIcon::ResizeNeSw);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rotation_handle_points_at_the_pointer() {
|
||||
let c = r().center();
|
||||
assert_eq!(angle_to(r(), c + vec2(0.0, -50.0), false), 0.0);
|
||||
assert_eq!(angle_to(r(), c + vec2(50.0, 0.0), false), 90.0);
|
||||
assert_eq!(angle_to(r(), c + vec2(-50.0, 0.0), false), 270.0);
|
||||
assert_eq!(angle_to(r(), c + vec2(50.0, -40.0), true), 45.0);
|
||||
assert_eq!(grab_at(r(), 0.0, true, rotate_handle(r(), 0.0)), Some(Grab::Rotate));
|
||||
assert_eq!(grab_at(r(), 0.0, false, rotate_handle(r(), 0.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turned_resize_keeps_the_opposite_handle_in_place() {
|
||||
let h = Handle { x: 1, y: 0 };
|
||||
let n = resized_turned(r(), 90.0, h, vec2(0.0, 40.0), 20.0, false);
|
||||
// Turned 90°, the right handle points down: a downward drag widens the frame.
|
||||
assert!((n.width() - 240.0).abs() < 0.01, "{n:?}");
|
||||
let opp = Handle { x: -1, y: 0 };
|
||||
assert!((opp.at_turned(n, 90.0) - opp.at_turned(r(), 90.0)).length() < 0.01);
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,20 @@ pub enum Drag {
|
||||
/// step of an earlier drag.
|
||||
stepped: bool,
|
||||
},
|
||||
/// Turning a shape about the centre of `rect` (its screen rect as the drag began).
|
||||
Rotate {
|
||||
obj: gridcraft_engine::model::ObjRef,
|
||||
rect: Rect,
|
||||
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,8 @@ 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::Rotate { .. } => Some(CursorIcon::Crosshair),
|
||||
Drag::Object { handle: Some(h), .. } | Drag::ChartData { corner: h, .. } => Some(h.cursor(rtl)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,13 +82,21 @@ fn hover_cursor(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, poin
|
||||
let on_cur_border = on_border(cur_rect, p) && border_panes.iter().any(|r| r.contains(p));
|
||||
// The selected object's handles resize it; any object's body moves it.
|
||||
let idle = app.grid.drag == Drag::None && app.editor.is_none();
|
||||
let object_handle = if idle { crate::chartview::selected_handle(app, geo, sh, p).map(|(.., h)| h) } else { None };
|
||||
let object_handle = if idle { crate::chartview::selected_handle(app, geo, sh, p) } else { None };
|
||||
let hit = if idle { crate::chartview::hit(app, geo, sh, p) } else { None };
|
||||
// A form control works on click unless it is selected (or Ctrl or Cmd is held).
|
||||
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 };
|
||||
let on_rotate = idle && crate::chartview::selected_rotate(app, geo, sh, p).is_some();
|
||||
if on_rotate {
|
||||
ctx.set_cursor_icon(CursorIcon::Crosshair);
|
||||
} else if let Some((o, _, h)) = object_handle {
|
||||
let deg = crate::chartview::frame_of(sh, o).0;
|
||||
ctx.set_cursor_icon(if deg == 0.0 { h.cursor(geo.rtl) } else { crate::frame::Handle { x: h.sides().0, y: h.sides().1 }.cursor(deg) });
|
||||
} else if let Some(h) = data_handle {
|
||||
ctx.set_cursor_icon(h.cursor(geo.rtl));
|
||||
} else if works {
|
||||
ctx.set_cursor_icon(CursorIcon::PointingHand);
|
||||
|
||||
@@ -136,6 +136,13 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
|
||||
if primary_drag || primary_clicked {
|
||||
// A drag is recognised only after the pointer has moved, so grab the object where the press began.
|
||||
let at = if primary_drag { pointer.press_origin().map(|p| geo.mirror_pos(p)).or(pos) } else { pos };
|
||||
if primary_drag
|
||||
&& let Some(p) = at
|
||||
&& let Some((obj, rect)) = crate::chartview::selected_rotate(app, geo, sh, p)
|
||||
{
|
||||
app.grid.drag = Drag::Rotate { obj, rect, stepped: false };
|
||||
return;
|
||||
}
|
||||
// The selected object's handles reach a little outside it, so they win over hit-testing.
|
||||
// Only they resize: a press anywhere on another object selects and moves it, as the
|
||||
// hover cursor shows.
|
||||
@@ -157,6 +164,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 +651,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 +771,11 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
scroll_by(app, auto);
|
||||
}
|
||||
Drag::Object { .. } => drag_object(app, geo, sh, p),
|
||||
Drag::Rotate { obj, rect, .. } => rotate_object(app, obj, rect, p, input.modifiers.shift),
|
||||
Drag::ChartData { .. } => {
|
||||
drag_chart_data(app, geo, sh, p);
|
||||
scroll_by(app, auto);
|
||||
}
|
||||
Drag::None => {}
|
||||
}
|
||||
}
|
||||
@@ -822,6 +856,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)));
|
||||
@@ -1159,6 +1210,52 @@ pub(super) fn hidden_row_edge(geo: &Geo, sh: &Sheet, y: f32) -> Option<u32> {
|
||||
row_edge(geo, sh, y).map(|(r, _)| r).filter(|&r| sh.row_height(r) <= 0.0)
|
||||
}
|
||||
|
||||
/// Arrow-key nudge of a selected object, sheet points (Ctrl/Alt: fine).
|
||||
const NUDGE: f32 = 6.0;
|
||||
|
||||
/// Arrow keys aimed at the selected object rather than the cells: they nudge it.
|
||||
pub(super) fn object_key(app: &mut SheetApp, sh: &Sheet, key: egui::Key, m: egui::Modifiers) -> bool {
|
||||
use egui::Key;
|
||||
let Some(o) = app.selected_object else { return false };
|
||||
let step = if m.ctrl || m.alt { 1.0 } else { NUDGE };
|
||||
// Arrows follow the screen: a right-to-left sheet is mirrored.
|
||||
let sx = if sh.right_to_left { -step } else { step };
|
||||
let d = match key {
|
||||
Key::ArrowLeft => vec2(-sx, 0.0),
|
||||
Key::ArrowRight => vec2(sx, 0.0),
|
||||
Key::ArrowUp => vec2(0.0, -step),
|
||||
Key::ArrowDown => vec2(0.0, step),
|
||||
_ => return false,
|
||||
};
|
||||
// On Windows and Linux egui sets `command` with `ctrl`: only the Mac Command key opts out.
|
||||
if m.shift || m.mac_cmd {
|
||||
return false;
|
||||
}
|
||||
let Some(a) = sh.object_anchor(o) else { return false };
|
||||
let x0 = (sh.col_left(a.cell.col) as f32 + a.dx + d.x).max(0.0);
|
||||
let y0 = (sh.row_top(a.cell.row) as f32 + a.dy + d.y).max(0.0);
|
||||
let nc = CellRef::new(sh.row_at(f64::from(y0)), sh.col_at(f64::from(x0)));
|
||||
let params =
|
||||
json!({"kind": o.kind.name(), "id": o.id, "at": nc.a1(), "dx": x0 - sh.col_left(nc.col) as f32, "dy": y0 - sh.row_top(nc.row) as f32});
|
||||
app.run_or_alert("object.move", params);
|
||||
true
|
||||
}
|
||||
|
||||
/// Turns the dragged shape so its rotation handle points at `p`; the drag is one undo step.
|
||||
fn rotate_object(app: &mut SheetApp, obj: ObjRef, rect: Rect, p: Pos2, snap: bool) {
|
||||
let deg = crate::frame::angle_to(rect, p, snap);
|
||||
let revision = app.session.active().map(|d| d.revision);
|
||||
let _ = app.session.run("object.move", json!({"kind": obj.kind.name(), "id": obj.id, "rotation": deg}));
|
||||
let Drag::Rotate { stepped, .. } = app.grid.drag else { return };
|
||||
if stepped {
|
||||
coalesce_last_undo(app);
|
||||
} else if app.session.active().map(|d| d.revision) != revision
|
||||
&& let Drag::Rotate { stepped, .. } = &mut app.grid.drag
|
||||
{
|
||||
*stepped = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the dragged object, or resizes it from the grabbed handle, to follow the pointer at `p`
|
||||
/// (logical coordinates). The whole drag coalesces into one undo step of its own.
|
||||
fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
|
||||
@@ -1167,7 +1264,16 @@ fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
|
||||
let (cell, dx, dy, w, h) = orig;
|
||||
let x0 = sh.col_left(cell.col) as f32 + dx;
|
||||
let y0 = sh.row_top(cell.row) as f32 + dy;
|
||||
let frame_deg = crate::chartview::frame_of(sh, obj).0;
|
||||
let [x0, y0, x1, y1] = match handle {
|
||||
Some(hd) if frame_deg != 0.0 => {
|
||||
let fh = crate::frame::Handle { x: hd.sides().0, y: hd.sides().1 };
|
||||
let r0 = Rect::from_min_max(pos2(x0, y0), pos2(x0 + w, y0 + h));
|
||||
let min = crate::objects::min_size(sh, obj);
|
||||
let r = crate::frame::resized_turned_by_min(r0, frame_deg, fh, d, min, false);
|
||||
let (nx, ny) = (r.min.x.max(0.0), r.min.y.max(0.0));
|
||||
[nx, ny, r.max.x.max(nx + min.x), r.max.y.max(ny + min.y)]
|
||||
}
|
||||
Some(hd) => crate::objects::resized([x0, y0, x0 + w, y0 + h], hd, d, crate::objects::min_size(sh, obj)),
|
||||
None => {
|
||||
let (x0, y0) = ((x0 + d.x).max(0.0), (y0 + d.y).max(0.0));
|
||||
@@ -1201,6 +1307,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 +1422,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)];
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
use super::geo::Geo;
|
||||
use super::interact::object_key;
|
||||
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 +17,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 +25,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 +39,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 +51,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,17 +71,20 @@ 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, .. } => {
|
||||
use egui::Key;
|
||||
if crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) {
|
||||
shortcut_ran = true;
|
||||
let nudged = object_key(app, sh, key, m);
|
||||
if nudged || crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) {
|
||||
shortcut_ran |= !nudged;
|
||||
continue;
|
||||
}
|
||||
let cmd = m.command;
|
||||
@@ -146,7 +162,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 +174,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());
|
||||
|
||||
@@ -99,13 +99,7 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_
|
||||
let apply = ui.button("Apply");
|
||||
ui.ctx().data_mut(|d| d.insert_temp(buttons_key, vec![ascending.id, descending.id, clear.id, apply.id]));
|
||||
if apply.clicked() || (enter && any) {
|
||||
let blanks = active_checks.iter().any(|(c, on)| *on && c.value.is_none());
|
||||
let vals: Vec<String> = active_checks.iter().filter(|(_, on)| *on).filter_map(|(c, _)| c.value.clone()).collect();
|
||||
let p = if active_checks.iter().all(|(_, b)| *b) {
|
||||
json!({"column": col_to_letters(col), "clear": true})
|
||||
} else {
|
||||
json!({"column": col_to_letters(col), "values": vals, "blanks": blanks})
|
||||
};
|
||||
let p = gridcraft_engine::cmd::data::filter_choices_params(&col_to_letters(col), &active_checks);
|
||||
let _ = app.run("data.filterBy", p);
|
||||
close = true;
|
||||
}
|
||||
@@ -199,12 +193,16 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
"ui:filterValue" => {
|
||||
if let Some(d) = app.session.active() {
|
||||
let a = d.selection.active;
|
||||
let text = d.wb.active().map(|sh| gridcraft_engine::display::cell_text(&d.wb, sh, a)).unwrap_or_default();
|
||||
let col = col_to_letters(a.col);
|
||||
let params =
|
||||
d.wb.active()
|
||||
.map(|sh| gridcraft_engine::cmd::data::filter_by_cell_params(&d.wb, sh, a, &col))
|
||||
.unwrap_or_else(|| json!({"column": col, "values": [], "blanks": true}));
|
||||
let has = d.wb.active().is_some_and(|sh| sh.autofilter.is_some());
|
||||
if !has {
|
||||
let _ = app.run("data.filter", json!({}));
|
||||
}
|
||||
app.run_or_alert("data.filterBy", json!({"column": col_to_letters(a.col), "values": [text]}));
|
||||
app.run_or_alert("data.filterBy", params);
|
||||
}
|
||||
}
|
||||
"edit.copy" | "edit.cut" => {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
|
||||
@@ -36,6 +36,7 @@ pub mod fonts;
|
||||
pub mod form_controls;
|
||||
pub mod formula_bar;
|
||||
mod formula_locale;
|
||||
pub mod frame;
|
||||
pub mod function_library;
|
||||
pub mod grid;
|
||||
pub mod i18n;
|
||||
|
||||
@@ -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:?})");
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Selecting, moving and resizing an inserted shape through real pointer input.
|
||||
|
||||
use egui::{Event, Modifiers, PointerButton, vec2};
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use gridcraft_engine::model::Anchor;
|
||||
use gridcraft_ui_egui::{SheetApp, grid::Geo};
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
fn fixture() -> (Harness, u32) {
|
||||
fixture_of("rectangle")
|
||||
}
|
||||
|
||||
fn fixture_of(kind: &str) -> (Harness, u32) {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let id = if kind == "ink" {
|
||||
session.execute("draw.stroke", json!({"points": [[300, 100], [420, 200]]})).unwrap();
|
||||
let sh = session.doc().unwrap().wb.active().unwrap();
|
||||
sh.shapes.iter().find(|s| s.kind == gridcraft_engine::model::ShapeKind::Ink).unwrap().id
|
||||
} else {
|
||||
let height = if matches!(kind, "line" | "arrow") { 0 } else { 100 };
|
||||
let shape = session.execute("insert.shape", json!({"kind": kind, "at": "D3", "width": 160, "height": height})).unwrap();
|
||||
shape["shape"].as_u64().unwrap() as u32
|
||||
};
|
||||
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);
|
||||
h.state_mut().selected_object = None;
|
||||
h.run_steps(2);
|
||||
(h, id)
|
||||
}
|
||||
|
||||
fn anchor(h: &Harness, id: u32) -> Anchor {
|
||||
h.state().session.doc().unwrap().wb.active().unwrap().shapes.iter().find(|s| s.id == id).unwrap().anchor
|
||||
}
|
||||
|
||||
fn rect(h: &Harness, id: u32) -> egui::Rect {
|
||||
let app = h.state();
|
||||
let sh = app.session.doc().unwrap().wb.active().unwrap();
|
||||
let geo = Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll);
|
||||
let a = anchor(h, id);
|
||||
let min = geo.cell_rect(sh, a.cell).min + vec2(a.dx, a.dy) * geo.z;
|
||||
egui::Rect::from_min_size(min, vec2(a.width, a.height) * geo.z)
|
||||
}
|
||||
|
||||
fn button(h: &mut Harness, pos: egui::Pos2, pressed: bool) {
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn drag(h: &mut Harness, from: egui::Pos2, to: egui::Pos2) {
|
||||
h.input_mut().events.push(Event::PointerMoved(from));
|
||||
h.run_steps(2);
|
||||
button(h, from, true);
|
||||
h.input_mut().events.push(Event::PointerMoved(to));
|
||||
h.run_steps(3);
|
||||
button(h, to, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_shape_selects_it() {
|
||||
let (mut h, id) = fixture();
|
||||
let c = rect(&h, id).center();
|
||||
h.input_mut().events.push(Event::PointerMoved(c));
|
||||
h.run_steps(2);
|
||||
button(&mut h, c, true);
|
||||
button(&mut h, c, false);
|
||||
assert_eq!(h.state().selected_object.map(|o| o.id), Some(id));
|
||||
assert_eq!(h.state().session.active().unwrap().selection.current().start, CellRef::parse("A1").unwrap());
|
||||
}
|
||||
|
||||
fn handle_at(h: &Harness, at: egui::Pos2) -> bool {
|
||||
h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Circle(k) if (k.center - at).length() < 1.0 && k.radius == 4.0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_shape_shows_its_handles() {
|
||||
let (mut h, id) = fixture();
|
||||
let r = rect(&h, id);
|
||||
assert!(!handle_at(&h, r.center_top()), "no handles before selecting");
|
||||
h.input_mut().events.push(Event::PointerMoved(r.center()));
|
||||
h.run_steps(2);
|
||||
button(&mut h, r.center(), true);
|
||||
button(&mut h, r.center(), false);
|
||||
for at in [r.left_top(), r.center_top(), r.right_bottom()] {
|
||||
assert!(handle_at(&h, at), "handle at {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_shape_moves_it() {
|
||||
let (mut h, id) = fixture();
|
||||
let before = rect(&h, id);
|
||||
drag(&mut h, before.center(), before.center() + vec2(120.0, 80.0));
|
||||
let after = rect(&h, id);
|
||||
assert!((after.min - before.min - vec2(120.0, 80.0)).length() < 4.0, "moved from {before:?} to {after:?}");
|
||||
assert_eq!(after.size(), before.size());
|
||||
}
|
||||
|
||||
fn select(h: &mut Harness, id: u32) {
|
||||
let c = rect(h, id).center();
|
||||
select_at(h, c);
|
||||
}
|
||||
|
||||
fn select_at(h: &mut Harness, c: egui::Pos2) {
|
||||
h.input_mut().events.push(Event::PointerMoved(c));
|
||||
h.run_steps(2);
|
||||
button(h, c, true);
|
||||
button(h, c, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_handle_shows_its_resize_cursor() {
|
||||
let (mut h, id) = fixture();
|
||||
select(&mut h, id);
|
||||
let r = rect(&h, id);
|
||||
for (at, cursor) in [
|
||||
(r.left_top(), egui::CursorIcon::ResizeNwSe),
|
||||
(r.right_top(), egui::CursorIcon::ResizeNeSw),
|
||||
(r.left_center(), egui::CursorIcon::ResizeHorizontal),
|
||||
(r.center_bottom(), egui::CursorIcon::ResizeVertical),
|
||||
] {
|
||||
h.input_mut().events.push(Event::PointerMoved(at));
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, cursor, "at {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_left_handle_moves_only_the_left_edge() {
|
||||
let (mut h, id) = fixture();
|
||||
select(&mut h, id);
|
||||
let before = rect(&h, id);
|
||||
drag(&mut h, before.left_center(), before.left_center() + vec2(-50.0, 40.0));
|
||||
let after = rect(&h, id);
|
||||
assert!((after.left() - (before.left() - 50.0)).abs() < 2.0, "{before:?} -> {after:?}");
|
||||
assert!((after.right() - before.right()).abs() < 2.0, "{before:?} -> {after:?}");
|
||||
assert!((after.top() - before.top()).abs() < 2.0 && (after.bottom() - before.bottom()).abs() < 2.0, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_top_left_handle_keeps_the_bottom_right_corner() {
|
||||
let (mut h, id) = fixture();
|
||||
select(&mut h, id);
|
||||
let before = rect(&h, id);
|
||||
drag(&mut h, before.left_top(), before.left_top() + vec2(30.0, 20.0));
|
||||
let after = rect(&h, id);
|
||||
assert!((after.right_bottom() - before.right_bottom()).length() < 2.0, "{before:?} -> {after:?}");
|
||||
assert!((after.left_top() - before.left_top() - vec2(30.0, 20.0)).length() < 2.0, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_corner_resizes_a_shape() {
|
||||
let (mut h, id) = fixture();
|
||||
select(&mut h, id);
|
||||
let before = rect(&h, id);
|
||||
drag(&mut h, before.right_bottom(), before.right_bottom() + vec2(60.0, 30.0));
|
||||
let after = rect(&h, id);
|
||||
assert!(after.width() > before.width() + 40.0 && after.height() > before.height() + 20.0, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
fn rotation(h: &Harness, id: u32) -> f32 {
|
||||
h.state().session.doc().unwrap().wb.active().unwrap().shapes.iter().find(|s| s.id == id).unwrap().rotation
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_rotation_handle_turns_the_shape() {
|
||||
let (mut h, id) = fixture();
|
||||
select(&mut h, id);
|
||||
let r = rect(&h, id);
|
||||
let knob = gridcraft_ui_egui::frame::rotate_handle(r, 0.0);
|
||||
assert!(handle_at(&h, knob), "the rotation handle shows");
|
||||
h.input_mut().events.push(Event::PointerMoved(knob));
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Crosshair);
|
||||
drag(&mut h, knob, r.center() + vec2(200.0, 0.0));
|
||||
assert_eq!(rotation(&h, id), 90.0);
|
||||
assert_eq!(rect(&h, id), r, "turning keeps the box");
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(rotation(&h, id), 0.0, "one drag is one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turned_shape_is_hit_inside_its_turned_outline() {
|
||||
let (mut h, id) = fixture();
|
||||
h.state_mut().run("object.move", json!({"kind": "shape", "id": id, "rotation": 90})).unwrap();
|
||||
h.run_steps(2);
|
||||
let r = rect(&h, id);
|
||||
// Turned 90°, the shape reaches half its width above and below its centre.
|
||||
let below = r.center() + vec2(0.0, r.width() / 2.0 - 5.0);
|
||||
assert!(!r.contains(below));
|
||||
h.input_mut().events.push(Event::PointerMoved(below));
|
||||
h.run_steps(2);
|
||||
button(&mut h, below, true);
|
||||
button(&mut h, below, false);
|
||||
assert_eq!(h.state().selected_object.map(|o| o.id), Some(id));
|
||||
}
|
||||
|
||||
fn key(h: &mut Harness, key: egui::Key, modifiers: Modifiers) {
|
||||
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_nudge_the_selected_shape_not_the_cell_cursor() {
|
||||
let (mut h, id) = fixture();
|
||||
select(&mut h, id);
|
||||
let before = anchor(&h, id);
|
||||
key(&mut h, egui::Key::ArrowRight, Modifiers::NONE);
|
||||
key(&mut h, egui::Key::ArrowDown, Modifiers { ctrl: true, command: true, ..Default::default() });
|
||||
let after = anchor(&h, id);
|
||||
let x = |a: &Anchor| h.state().session.doc().unwrap().wb.active().unwrap().col_left(a.cell.col) as f32 + a.dx;
|
||||
let y = |a: &Anchor| h.state().session.doc().unwrap().wb.active().unwrap().row_top(a.cell.row) as f32 + a.dy;
|
||||
assert!((x(&after) - x(&before) - 6.0).abs() < 0.01 && (y(&after) - y(&before) - 1.0).abs() < 0.01, "{before:?} -> {after:?}");
|
||||
assert_eq!(h.state().session.active().unwrap().selection.current().start, CellRef::parse("A1").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_deselects_the_shape() {
|
||||
let (mut h, id) = fixture();
|
||||
select(&mut h, id);
|
||||
key(&mut h, egui::Key::Escape, Modifiers::NONE);
|
||||
assert_eq!(h.state().selected_object, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_body_of_a_shape_shows_the_move_cursor() {
|
||||
let (mut h, id) = fixture();
|
||||
let c = rect(&h, id).center();
|
||||
h.input_mut().events.push(Event::PointerMoved(c));
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Move);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_a_flat_line_keeps_it_flat() {
|
||||
let (mut h, id) = fixture_of("line");
|
||||
select(&mut h, id);
|
||||
let before = rect(&h, id);
|
||||
assert_eq!(before.height(), 0.0, "a new line has no height");
|
||||
drag(&mut h, before.right_bottom(), before.right_bottom() + vec2(50.0, 40.0));
|
||||
let after = rect(&h, id);
|
||||
assert!(after.width() > before.width() + 40.0, "{before:?} -> {after:?}");
|
||||
assert_eq!(after.height(), 0.0, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_rotated_flat_lines_and_arrows_keeps_them_flat_and_undoes() {
|
||||
for kind in ["line", "arrow"] {
|
||||
let (mut h, id) = fixture_of(kind);
|
||||
h.state_mut().run("object.move", json!({"kind": "shape", "id": id, "rotation": 90})).unwrap();
|
||||
h.run_steps(2);
|
||||
h.state_mut().selected_object = Some(gridcraft_engine::model::ObjRef::new(gridcraft_engine::model::ObjKind::Shape, id));
|
||||
h.run_steps(2);
|
||||
|
||||
let before_anchor = anchor(&h, id);
|
||||
let before = rect(&h, id);
|
||||
assert_eq!(before.height(), 0.0, "{kind} starts flat: {before:?}");
|
||||
let handle = gridcraft_ui_egui::frame::Handle { x: 1, y: 1 }.at_turned(before, 90.0);
|
||||
drag(&mut h, handle, handle + vec2(0.0, 50.0));
|
||||
|
||||
let after = rect(&h, id);
|
||||
assert!(after.width() > before.width() + 40.0, "{kind}: {before:?} -> {after:?}");
|
||||
assert_eq!(after.height(), 0.0, "{kind}: {before:?} -> {after:?}");
|
||||
assert_eq!(rotation(&h, id), 90.0);
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(anchor(&h, id), before_anchor, "{kind} undo restores its anchor");
|
||||
assert_eq!(rotation(&h, id), 90.0, "{kind} undo preserves rotation");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_follow_the_screen_on_a_right_to_left_sheet() {
|
||||
let (mut h, id) = fixture();
|
||||
h.state_mut().session.execute("view.rightToLeft", json!({"on": true})).unwrap();
|
||||
h.run_steps(2);
|
||||
h.state_mut().selected_object = Some(gridcraft_engine::model::ObjRef::new(gridcraft_engine::model::ObjKind::Shape, id));
|
||||
h.run_steps(2);
|
||||
let x = |h: &Harness| {
|
||||
let a = anchor(h, id);
|
||||
h.state().session.doc().unwrap().wb.active().unwrap().col_left(a.cell.col) as f32 + a.dx
|
||||
};
|
||||
let before = x(&h);
|
||||
key(&mut h, egui::Key::ArrowRight, Modifiers::NONE);
|
||||
let moved = x(&h) - before;
|
||||
assert!((moved + 6.0).abs() < 0.01, "moved {moved}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ink_stroke_shows_no_resize_handles() {
|
||||
let (mut h, id) = fixture_of("ink");
|
||||
select(&mut h, id);
|
||||
let r = rect(&h, id);
|
||||
assert!(!handle_at(&h, r.right_bottom()), "ink does not scale with its frame");
|
||||
}
|
||||
@@ -20,6 +20,9 @@ gridcraft-math = { workspace = true }
|
||||
gridcraft-model = { workspace = true }
|
||||
craft-cfb = { workspace = true }
|
||||
craft-csv = { workspace = true }
|
||||
craft-drawingml = { workspace = true }
|
||||
craft-math = { workspace = true }
|
||||
craft-ods = { workspace = true }
|
||||
craft-offcrypto = { workspace = true }
|
||||
craft-opc = { workspace = true }
|
||||
craft-xls = { workspace = true }
|
||||
|
||||
@@ -20,7 +20,16 @@ pub const REL_COLORS: &str = "http://schemas.microsoft.com/office/2011/relations
|
||||
|
||||
/// Kinds written as chartex parts.
|
||||
pub fn is_chartex(k: ChartKind) -> bool {
|
||||
matches!(k, ChartKind::Histogram | ChartKind::BoxWhisker | ChartKind::Waterfall | ChartKind::Funnel | ChartKind::Treemap | ChartKind::Sunburst)
|
||||
use craft_drawingml::chart::ChartType;
|
||||
match k {
|
||||
ChartKind::Histogram => ChartType::Histogram.is_chartex(),
|
||||
ChartKind::BoxWhisker => ChartType::BoxWhisker.is_chartex(),
|
||||
ChartKind::Waterfall => ChartType::Waterfall.is_chartex(),
|
||||
ChartKind::Funnel => ChartType::Funnel.is_chartex(),
|
||||
ChartKind::Treemap => ChartType::Treemap.is_chartex(),
|
||||
ChartKind::Sunburst => ChartType::Sunburst.is_chartex(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `mc:Choice` requirement for a kind's drawing frame: (prefix, namespace). Funnel charts
|
||||
|
||||
@@ -227,7 +227,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
// shape (an ellipse, a filled rectangle) it, like any other warp, leaves the shape what its
|
||||
// geometry says.
|
||||
let word_art = prst == "rect"
|
||||
&& (tx_box || (sp.child("noFill").is_some() && !ln.is_some_and(|l| l.child("solidFill").is_some())))
|
||||
&& (tx_box || (sp.child("noFill").is_some() && ln.is_none_or(|l| l.child("solidFill").is_none())))
|
||||
&& obj.path(&["txBody", "bodyPr", "prstTxWarp"]).is_some_and(|w| w.attr("prst") == Some("textNoShape"));
|
||||
let kind = match prst {
|
||||
_ if word_art => ShapeKind::WordArt,
|
||||
@@ -266,6 +266,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
line: ink,
|
||||
text,
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
});
|
||||
}
|
||||
@@ -274,7 +275,13 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
let text = obj.child("txBody").map(body_text).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() })
|
||||
let rotation = sp
|
||||
.child("xfrm")
|
||||
.and_then(|x| x.attr("rot"))
|
||||
.and_then(|r| r.parse::<f64>().ok())
|
||||
.filter(|r| r.is_finite())
|
||||
.map_or(0.0, |r| ((r / 60000.0).rem_euclid(360.0)) as f32);
|
||||
Some(Shape { id: 0, kind, anchor, fill, line, text, format, rotation, math: Default::default() })
|
||||
}
|
||||
|
||||
/// A shape's text formatting: vertical anchor (`a:bodyPr anchor`), the first paragraph's
|
||||
@@ -452,8 +459,15 @@ fn anchor_open(sheet: &Sheet, a: &Anchor) -> (String, &'static str) {
|
||||
}
|
||||
|
||||
fn xfrm(a: &Anchor, tag: &str) -> String {
|
||||
xfrm_rot(a, tag, 0.0)
|
||||
}
|
||||
|
||||
/// `deg` is written as `rot`, in 60000ths of a degree.
|
||||
fn xfrm_rot(a: &Anchor, tag: &str, deg: f32) -> String {
|
||||
let e = |v: f32| ((v.max(0.0) as f64) * EMU_PER_PX).round() as i64;
|
||||
format!("<{tag}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{}\" cy=\"{}\"/></{tag}>", e(a.width), e(a.height))
|
||||
let rot = (f64::from(deg.rem_euclid(360.0)) * 60000.0).round() as i64;
|
||||
let rot = if rot > 0 { format!(" rot=\"{rot}\"") } else { String::new() };
|
||||
format!("<{tag}{rot}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{}\" cy=\"{}\"/></{tag}>", e(a.width), e(a.height))
|
||||
}
|
||||
|
||||
pub fn srgb(c: &Color, theme: &Theme) -> Option<String> {
|
||||
@@ -545,7 +559,7 @@ pub fn write_drawing(sheet: &Sheet, theme: &Theme, objs: &[Obj<'_>]) -> String {
|
||||
"<xdr:sp macro=\"\" textlink=\"\"><xdr:nvSpPr><xdr:cNvPr id=\"{id}\" name=\"Shape {}\"/><xdr:cNvSpPr{}/></xdr:nvSpPr><xdr:spPr>{}<a:prstGeom prst=\"{prst}\"><a:avLst/></a:prstGeom>",
|
||||
id - 1,
|
||||
if tx { " txBox=\"1\"" } else { "" },
|
||||
xfrm(&sh.anchor, "a:xfrm")
|
||||
xfrm_rot(&sh.anchor, "a:xfrm", sh.rotation)
|
||||
);
|
||||
if let Some(c) = srgb(&sh.fill, theme) {
|
||||
let _ = write!(s, "<a:solidFill>{c}</a:solidFill>");
|
||||
|
||||
@@ -187,6 +187,7 @@ pub(super) fn read(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
line,
|
||||
text,
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
+68
-510
@@ -4,38 +4,64 @@
|
||||
|
||||
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;
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
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);
|
||||
}
|
||||
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),
|
||||
}
|
||||
"oMath" => seq(e, &mut out, 0)?,
|
||||
_ => return None,
|
||||
}
|
||||
Some(out.trim().to_string())
|
||||
}
|
||||
|
||||
/// The first `m:oMath`/`m:oMathPara` under `e` (an `a14:m` element or a paragraph), searched to a
|
||||
@@ -178,33 +204,6 @@ 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"]),
|
||||
("fPr", &["type"]),
|
||||
@@ -221,446 +220,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::*;
|
||||
@@ -685,13 +244,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 +262,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 +278,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 +322,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 {
|
||||
@@ -59,19 +59,18 @@ fn filter_op(s: Option<&str>) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses an `<autoFilter>` element into model criteria, migrating legacy whitespace-only value entries to `blanks`.
|
||||
/// Parses an `<autoFilter>` element into model criteria.
|
||||
pub fn read_autofilter(cx: &mut Ctx<'_>, e: &El) -> Option<AutoFilter> {
|
||||
let range = e.attr("ref").and_then(RangeRef::parse)?;
|
||||
let mut criteria = vec![];
|
||||
for fc in e.kids("filterColumn") {
|
||||
let Some(col) = fc.attr_u32("colId") else { continue };
|
||||
let crit = if let Some(f) = fc.child("filters") {
|
||||
let mut values: Vec<String> = f.kids("filter").filter_map(|x| x.attr("val")).map(str::to_string).collect();
|
||||
let had_whitespace_only = values.iter().any(|v| v.trim().is_empty());
|
||||
if had_whitespace_only {
|
||||
values.retain(|v| !v.trim().is_empty());
|
||||
FilterCriterion::Values {
|
||||
values: f.kids("filter").filter_map(|x| x.attr("val")).map(str::to_string).collect(),
|
||||
blanks: f.flag("blank", false),
|
||||
identities: Vec::new(),
|
||||
}
|
||||
FilterCriterion::Values { values, blanks: f.flag("blank", false) || had_whitespace_only }
|
||||
} else if let Some(cf) = fc.child("customFilters") {
|
||||
let mut it = cf.kids("customFilter").map(|c| (filter_op(c.attr("operator")).to_string(), c.attr("val").unwrap_or("").to_string()));
|
||||
let Some(a) = it.next() else { continue };
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,19 +11,23 @@ use gridcraft_model::{
|
||||
|
||||
use crate::drawing::{Obj, image_content_type, image_ext};
|
||||
use crate::fmla::text_to_file;
|
||||
use crate::styles::{color_attrs, dxf_id};
|
||||
use crate::styles::{color_attrs, dxf_id, dxf_xml};
|
||||
use crate::tables::{paper_id, px_to_col_width, px_to_pt};
|
||||
use crate::write::{
|
||||
CT_CHART, CT_COMMENTS, CT_DRAWING, CT_TABLE, CT_THREADED_COMMENTS, NS_MAIN, NS_REL, NS_THREADED, Out, REL_THREADED_COMMENT, Rels, XML_DECL,
|
||||
x14_cf_rule_guid,
|
||||
};
|
||||
use crate::xml::{encode_xstring, esc, esc_attr, num, push_a1, push_u64};
|
||||
|
||||
/// The worksheet extension holding Excel 2010 conditional formats.
|
||||
const EXT_X14_CF: &str = "{78C0D931-6437-407d-A8EE-F0AAD7539E65}";
|
||||
|
||||
mod parts;
|
||||
mod rules;
|
||||
|
||||
pub(crate) use parts::password_attrs;
|
||||
use parts::{autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_name, table_xml, thread_ids, threaded_xml, vml_xml};
|
||||
use rules::{cf_rule_xml, solid_bar_id, validation_xml, x14_cfvo};
|
||||
use rules::{cf_rule_xml, solid_bar_x14, validation_xml, x14_cf_rule_xml};
|
||||
|
||||
fn sqref(ranges: &[RangeRef]) -> String {
|
||||
ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().join(" ")
|
||||
@@ -193,7 +197,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
|
||||
write_sheet_data(&mut s, SheetCellData { workbook: wb, index: si, sheet, overrides: &overrides, extra: &extra, dynamic: &dynamic }, &sid, out);
|
||||
|
||||
let prio = write_sheet_rules(&mut s, sheet, &mut rels, out);
|
||||
let x14_cf = write_sheet_rules(&mut s, sheet, &mut rels, out);
|
||||
let kept = write_sheet_printing(&mut s, sheet, &mut rels, out);
|
||||
|
||||
write_sheet_drawing(&mut s, wb, si, sheet, &mut rels, out);
|
||||
@@ -214,7 +218,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
}
|
||||
let _ = write!(s, "<tableParts count=\"{}\">{parts}</tableParts>", tables.len());
|
||||
}
|
||||
write_sheet_extensions(&mut s, sheet, &prio);
|
||||
write_sheet_extensions(&mut s, sheet, &x14_cf);
|
||||
s.push_str("</worksheet>");
|
||||
(s, rels)
|
||||
}
|
||||
@@ -228,31 +232,13 @@ struct CellWriteInput<'a> {
|
||||
dynamic_range: Option<&'a RangeRef>,
|
||||
}
|
||||
|
||||
fn write_sheet_extensions(s: &mut String, sheet: &Sheet, prio: &[u32]) {
|
||||
// Excel 2010 extensions: solid data bars, then sparklines.
|
||||
let solid_bars: Vec<(&CondFormat, u32)> = sheet
|
||||
.cond_formats
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, cf)| !cf.ranges.is_empty() && matches!(cf.rule, CfRule::DataBar { gradient: false, .. }))
|
||||
.map(|(i, cf)| (cf, prio.get(i).copied().unwrap_or(1)))
|
||||
.collect();
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
fn write_sheet_extensions(s: &mut String, sheet: &Sheet, x14_cf: &str) {
|
||||
// Excel 2010 extensions: conditional formats, then sparklines.
|
||||
if !x14_cf.is_empty() || !sheet.sparklines.is_empty() {
|
||||
s.push_str("<extLst>");
|
||||
}
|
||||
if !solid_bars.is_empty() {
|
||||
let _ = write!(
|
||||
s,
|
||||
"<ext uri=\"{{78C0D931-6437-407d-A8A1-0F90B4350D7D}}\" xmlns:x14=\"{X14_NS}\" xmlns:xm=\"{XM_NS}\"><x14:conditionalFormattings>"
|
||||
);
|
||||
for (cf, p) in &solid_bars {
|
||||
if let CfRule::DataBar { min, max, .. } = &cf.rule {
|
||||
let (id, lo, hi) = (solid_bar_id(*p), x14_cfvo(min), x14_cfvo(max));
|
||||
let _ = write!(s, "<x14:conditionalFormatting><x14:cfRule type=\"dataBar\" id=\"{id}\"><x14:dataBar gradient=\"0\">{lo}{hi}");
|
||||
let _ = write!(s, "</x14:dataBar></x14:cfRule><xm:sqref>{}</xm:sqref></x14:conditionalFormatting>", sqref(&cf.ranges));
|
||||
}
|
||||
}
|
||||
s.push_str("</x14:conditionalFormattings></ext>");
|
||||
if !x14_cf.is_empty() {
|
||||
let _ = write!(s, "<ext uri=\"{EXT_X14_CF}\" xmlns:x14=\"{X14_NS}\"><x14:conditionalFormattings>{x14_cf}</x14:conditionalFormattings></ext>");
|
||||
}
|
||||
if !sheet.sparklines.is_empty() {
|
||||
let _ = write!(s, "<ext uri=\"{{05C60535-1F16-4fd2-B633-F4F36F0B64E0}}\" xmlns:x14=\"{X14_NS}\"><x14:sparklineGroups xmlns:xm=\"{XM_NS}\">");
|
||||
@@ -275,7 +261,7 @@ fn write_sheet_extensions(s: &mut String, sheet: &Sheet, prio: &[u32]) {
|
||||
}
|
||||
s.push_str("</x14:sparklineGroups></ext>");
|
||||
}
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
if !x14_cf.is_empty() || !sheet.sparklines.is_empty() {
|
||||
s.push_str("</extLst>");
|
||||
}
|
||||
}
|
||||
@@ -470,7 +456,7 @@ fn write_sheet_printing<'a>(s: &mut String, sheet: &'a Sheet, rels: &mut Rels, o
|
||||
kept
|
||||
}
|
||||
|
||||
fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> Vec<u32> {
|
||||
fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> String {
|
||||
// sheetProtection
|
||||
if let Some(p) = &sheet.protection {
|
||||
s.push_str("<sheetProtection sheet=\"1\" objects=\"1\" scenarios=\"1\"");
|
||||
@@ -524,16 +510,34 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O
|
||||
*p = rank as u32 + 1;
|
||||
}
|
||||
}
|
||||
// Cell-value and formula rules referring to another sheet go to the Excel 2010 extension.
|
||||
// Excel for Mac 16.114 also writes cross-sheet expression rules there (the tested synthetic
|
||||
// files opened without a repair prompt), using this URI. It stores cross-sheet cfvo rules for
|
||||
// colour scales, data bars and icon sets only in x14; GridCraft writes those in the main
|
||||
// section, and drops x14-only forms on read with a warning. GridCraft-written test files with
|
||||
// those main-section rules also opened without a repair prompt.
|
||||
// A solid data bar is in both sections: the extension holds its fill.
|
||||
let mut x14_cf = String::new();
|
||||
for (i, cf) in sheet.cond_formats.iter().enumerate() {
|
||||
if cf.ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let _ = write!(
|
||||
s,
|
||||
"<conditionalFormatting sqref=\"{}\">{}</conditionalFormatting>",
|
||||
sqref(&cf.ranges),
|
||||
cf_rule_xml(cf, prio.get(i).copied().unwrap_or(1), out)
|
||||
);
|
||||
let priority = prio.get(i).copied().unwrap_or(1);
|
||||
let x14 = match x14_cf_rule_xml(cf, &sheet.name, priority, out) {
|
||||
Some(rule) => Some(rule),
|
||||
None => {
|
||||
let _ =
|
||||
write!(s, "<conditionalFormatting sqref=\"{}\">{}</conditionalFormatting>", sqref(&cf.ranges), cf_rule_xml(cf, priority, out));
|
||||
solid_bar_x14(cf, priority)
|
||||
}
|
||||
};
|
||||
if let Some(rule) = x14 {
|
||||
let _ = write!(
|
||||
x14_cf,
|
||||
"<x14:conditionalFormatting xmlns:xm=\"{XM_NS}\">{rule}<xm:sqref>{}</xm:sqref></x14:conditionalFormatting>",
|
||||
sqref(&cf.ranges)
|
||||
);
|
||||
}
|
||||
}
|
||||
let vals: Vec<&Validation> = sheet.validations.iter().filter(|v| !v.ranges.is_empty()).collect();
|
||||
if !vals.is_empty() {
|
||||
@@ -578,7 +582,7 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O
|
||||
}
|
||||
s.push_str("</hyperlinks>");
|
||||
}
|
||||
prio
|
||||
x14_cf
|
||||
}
|
||||
|
||||
struct SheetCellData<'a> {
|
||||
@@ -854,6 +858,11 @@ fn write_cell(s: &mut String, input: CellWriteInput<'_>, sid: &dyn Fn(gridcraft_
|
||||
Value::Number(n) => {
|
||||
let _ = write!(s, "><v>{}</v></c>", num(*n));
|
||||
}
|
||||
// Text inside a spill or array range is a cached formula result: Excel writes it as `t="str"`
|
||||
// and shows #VALUE! for a shared string there when it trusts the saved values.
|
||||
Value::Text(t) if extra.is_some() => {
|
||||
let _ = write!(s, " t=\"str\"><v>{}</v></c>", esc(&encode_xstring(t)));
|
||||
}
|
||||
Value::Text(t) => {
|
||||
let i = out.sst.index(t);
|
||||
let _ = write!(s, " t=\"s\"><v>{i}</v></c>");
|
||||
|
||||
@@ -66,7 +66,7 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)
|
||||
for (col, c) in criteria {
|
||||
let _ = write!(s, "<filterColumn colId=\"{col}\">");
|
||||
match c {
|
||||
FilterCriterion::Values { values, blanks } => {
|
||||
FilterCriterion::Values { values, blanks, .. } => {
|
||||
let _ = write!(s, "<filters{}>", if *blanks { " blank=\"1\"" } else { "" });
|
||||
for v in values {
|
||||
let _ = write!(s, "<filter val=\"{}\"/>", esc_attr(v));
|
||||
|
||||
@@ -183,6 +183,60 @@ pub(super) fn cf_rule_xml(cf: &CondFormat, priority: u32, out: &mut Out) -> Stri
|
||||
}
|
||||
}
|
||||
|
||||
/// The x14 rule a solid data bar's `cfRule` links to (it holds the fill); `None` for other rules.
|
||||
/// GridCraft draws negative values in the bar's colour from the low end, with no axis; the x14
|
||||
/// defaults are an automatic axis and a separate negative colour, so both are written out.
|
||||
pub(super) fn solid_bar_x14(cf: &CondFormat, priority: u32) -> Option<String> {
|
||||
let CfRule::DataBar { min, max, gradient: false, .. } = &cf.rule else { return None };
|
||||
let (id, lo, hi) = (solid_bar_id(priority), x14_cfvo(min), x14_cfvo(max));
|
||||
Some(format!(
|
||||
"<x14:cfRule type=\"dataBar\" id=\"{id}\"><x14:dataBar gradient=\"0\" negativeBarColorSameAsPositive=\"1\" axisPosition=\"none\">{lo}{hi}</x14:dataBar></x14:cfRule>"
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether formula `f` refers to a sheet other than `own`, and whether it refers to a 3-D span of
|
||||
/// sheets.
|
||||
fn sheet_refs(f: &str, own: &str) -> (bool, bool) {
|
||||
let Ok(e) = gridcraft_formula::parse(f.trim_start_matches('=')) else { return (false, false) };
|
||||
let refs = e.references();
|
||||
let other = refs.iter().any(|r| match &r.sheet {
|
||||
gridcraft_formula::SheetSel::Named(n) => !n.chars().flat_map(char::to_lowercase).eq(own.chars().flat_map(char::to_lowercase)),
|
||||
_ => false,
|
||||
});
|
||||
let span = refs.iter().any(|r| matches!(r.sheet, gridcraft_formula::SheetSel::Span(..)));
|
||||
(other, span)
|
||||
}
|
||||
|
||||
/// The Excel 2010 form (`x14:cfRule`, `xm:f` formulas, inline `x14:dxf`) of a cell-value or
|
||||
/// formula rule that refers to another sheet; `None` for rules that belong in the main section.
|
||||
/// MS-XLSX 2.6.27 (CT_CfRule) forbids 3-D spans (`sheet-range-reference`) in `xm:f`, so a rule
|
||||
/// with one stays in the main section.
|
||||
pub(super) fn x14_cf_rule_xml(cf: &CondFormat, own: &str, priority: u32, out: &mut Out) -> Option<String> {
|
||||
let (ty, extra, formulas, style): (&str, String, Vec<&str>, &Style) = match &cf.rule {
|
||||
CfRule::CellIs { op, a, b, style } => {
|
||||
("cellIs", format!(" operator=\"{}\"", cf_op_name(*op)), std::iter::once(a.as_str()).chain(b.as_deref()).collect(), style)
|
||||
}
|
||||
CfRule::Expression { formula, style } => ("expression", String::new(), vec![formula.as_str()], style),
|
||||
_ => return None,
|
||||
};
|
||||
let refs: Vec<(bool, bool)> = formulas.iter().map(|f| sheet_refs(f, own)).collect();
|
||||
if !refs.iter().any(|&(other, _)| other) || refs.iter().any(|&(_, span)| span) {
|
||||
return None;
|
||||
}
|
||||
out.x14_cf_rules += 1;
|
||||
let mut s = format!(
|
||||
"<x14:cfRule type=\"{ty}\" priority=\"{priority}\"{}{extra} id=\"{}\">",
|
||||
if cf.stop_if_true { " stopIfTrue=\"1\"" } else { "" },
|
||||
x14_cf_rule_guid(out.x14_cf_rules)
|
||||
);
|
||||
for f in formulas {
|
||||
let _ = write!(s, "<xm:f>{}</xm:f>", esc(&text_to_file(f)));
|
||||
}
|
||||
s.push_str(&dxf_xml("x14:dxf", style, &mut out.num_fmts));
|
||||
s.push_str("</x14:cfRule>");
|
||||
Some(s)
|
||||
}
|
||||
|
||||
fn validation_formula(f: &str) -> String {
|
||||
let f = f.trim();
|
||||
if f.starts_with('"') {
|
||||
|
||||
+61
-46
@@ -444,6 +444,14 @@ fn read_dxf<'a>(x: &'a El, palette: &[u32], fmts: &HashMap<u32, NumFmt>, inline_
|
||||
s
|
||||
}
|
||||
|
||||
/// An inline Excel 2010 `x14:dxf` differential format, resolving `numFmtId` against `cx.num_fmts`.
|
||||
pub fn read_x14_dxf(x: &El, palette: &[u32], fmts: &HashMap<u32, String>) -> Style {
|
||||
let shared: HashMap<u32, NumFmt> =
|
||||
x.child("numFmt").and_then(|n| n.attr_u32("numFmtId")).and_then(|id| fmts.get(&id).map(|c| (id, NumFmt::new(c)))).into_iter().collect();
|
||||
let mut inline_fmts = HashMap::new();
|
||||
read_dxf(x, palette, &shared, &mut inline_fmts)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- writing
|
||||
|
||||
pub fn color_attrs(c: &Color) -> String {
|
||||
@@ -639,14 +647,16 @@ fn intern<T: Clone + Eq + std::hash::Hash>(list: &mut Vec<T>, map: &mut HashMap<
|
||||
i
|
||||
}
|
||||
|
||||
/// Number format ids assigned while writing.
|
||||
struct NumFmts {
|
||||
/// Number format ids assigned while writing. Worksheets that carry inline differential formats
|
||||
/// (`x14:dxf`) assign ids first, through [`crate::write::Out`]; `styles.xml` lists them all.
|
||||
#[derive(Default)]
|
||||
pub struct NumFmts {
|
||||
custom: Vec<(u32, String)>,
|
||||
map: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
impl NumFmts {
|
||||
fn id(&mut self, code: &str) -> u32 {
|
||||
pub fn id(&mut self, code: &str) -> u32 {
|
||||
if let Some(id) = builtin_id(code) {
|
||||
return id;
|
||||
}
|
||||
@@ -662,10 +672,10 @@ impl NumFmts {
|
||||
|
||||
/// `styles.xml` for the workbook: one cell format per model style, in `StyleId` order (so a
|
||||
/// cell's `s` attribute is its style id), plus the given differential formats.
|
||||
/// `extra_fmts` are number formats used outside cell styles (PivotTable value fields); the
|
||||
/// returned map gives the id of every custom format written.
|
||||
pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (String, HashMap<String, u32>) {
|
||||
let mut nf = NumFmts { custom: vec![], map: HashMap::new() };
|
||||
/// `extra_fmts` are number formats used outside cell styles (PivotTable value fields); `nf`
|
||||
/// holds the ids worksheets already assigned. The returned map gives the id of every custom
|
||||
/// format written.
|
||||
pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String], mut nf: NumFmts) -> (String, HashMap<String, u32>) {
|
||||
let mut fonts: Vec<Font> = vec![];
|
||||
let mut font_map = HashMap::new();
|
||||
let mut fills: Vec<Fill> = vec![Fill::default(), Fill { pattern: PatternType::Gray125, fg: Color::Auto, bg: Color::Auto }];
|
||||
@@ -745,44 +755,7 @@ pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (St
|
||||
|
||||
let mut dx = String::new();
|
||||
for d in dxfs {
|
||||
dx.push_str("<dxf>");
|
||||
let def = Style::default();
|
||||
let st = &d.dxf_stated;
|
||||
if d.font.bold
|
||||
|| d.font.italic
|
||||
|| d.font.strike
|
||||
|| d.font.underline != Underline::None
|
||||
|| d.font.color != Color::Auto
|
||||
|| d.font.vert != VertAlign::Baseline
|
||||
|| d.font.size != def.font.size
|
||||
|| d.font.name != def.font.name
|
||||
|| st.bold
|
||||
|| st.italic
|
||||
|| st.strike
|
||||
|| st.underline
|
||||
|| st.size
|
||||
|| st.name
|
||||
|| st.scheme.is_some()
|
||||
{
|
||||
dx.push_str(&font_xml(&d.font, Some(st), false));
|
||||
}
|
||||
if d.num_fmt != def.num_fmt {
|
||||
let id = nf.id(d.num_fmt.as_str());
|
||||
let _ = write!(dx, "<numFmt numFmtId=\"{id}\" formatCode=\"{}\"/>", esc_attr(d.num_fmt.as_str()));
|
||||
}
|
||||
if d.fill != def.fill {
|
||||
dx.push_str(&fill_xml(&d.fill, true));
|
||||
}
|
||||
if let Some(a) = alignment_xml(&d.align) {
|
||||
dx.push_str(&a);
|
||||
}
|
||||
if d.borders != def.borders {
|
||||
dx.push_str(&border_xml(&d.borders));
|
||||
}
|
||||
if st.protection || d.protection != def.protection {
|
||||
let _ = write!(dx, "<protection locked=\"{}\" hidden=\"{}\"/>", d.protection.locked as u8, d.protection.hidden as u8);
|
||||
}
|
||||
dx.push_str("</dxf>");
|
||||
dx.push_str(&dxf_xml("dxf", d, &mut nf));
|
||||
}
|
||||
for f in extra_fmts {
|
||||
nf.id(f);
|
||||
@@ -820,6 +793,48 @@ pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (St
|
||||
(s, nf.map)
|
||||
}
|
||||
|
||||
/// A differential format element named `tag` (`dxf`, or `x14:dxf` inline in a worksheet rule).
|
||||
pub fn dxf_xml(tag: &str, d: &Style, nf: &mut NumFmts) -> String {
|
||||
let mut dx = format!("<{tag}>");
|
||||
let def = Style::default();
|
||||
if d.font.bold
|
||||
|| d.font.italic
|
||||
|| d.font.strike
|
||||
|| d.font.underline != Underline::None
|
||||
|| d.font.color != Color::Auto
|
||||
|| d.font.vert != VertAlign::Baseline
|
||||
|| d.font.size != def.font.size
|
||||
|| d.font.name != def.font.name
|
||||
|| d.dxf_stated.bold
|
||||
|| d.dxf_stated.italic
|
||||
|| d.dxf_stated.strike
|
||||
|| d.dxf_stated.underline
|
||||
|| d.dxf_stated.size
|
||||
|| d.dxf_stated.name
|
||||
|| d.dxf_stated.scheme.is_some()
|
||||
{
|
||||
dx.push_str(&font_xml(&d.font, Some(&d.dxf_stated), false));
|
||||
}
|
||||
if d.num_fmt != def.num_fmt {
|
||||
let id = nf.id(d.num_fmt.as_str());
|
||||
let _ = write!(dx, "<numFmt numFmtId=\"{id}\" formatCode=\"{}\"/>", esc_attr(d.num_fmt.as_str()));
|
||||
}
|
||||
if d.fill != def.fill {
|
||||
dx.push_str(&fill_xml(&d.fill, true));
|
||||
}
|
||||
if let Some(a) = alignment_xml(&d.align) {
|
||||
dx.push_str(&a);
|
||||
}
|
||||
if d.borders != def.borders {
|
||||
dx.push_str(&border_xml(&d.borders));
|
||||
}
|
||||
if d.dxf_stated.protection || d.protection != def.protection {
|
||||
let _ = write!(dx, "<protection locked=\"{}\" hidden=\"{}\"/>", d.protection.locked as u8, d.protection.hidden as u8);
|
||||
}
|
||||
let _ = write!(dx, "</{tag}>");
|
||||
dx
|
||||
}
|
||||
|
||||
/// Index of a differential format, adding it when new.
|
||||
pub fn dxf_id(dxfs: &mut Vec<Style>, s: &Style) -> u32 {
|
||||
if let Some(i) = dxfs.iter().position(|d| d == s) {
|
||||
@@ -856,7 +871,7 @@ mod tests {
|
||||
let mut wb = Workbook::new();
|
||||
wb.styles.intern(styles.xfs[1].clone());
|
||||
wb.cell_styles = styles.named.clone();
|
||||
let (xml, _) = write_styles(&wb, &styles.dxfs, &[]);
|
||||
let (xml, _) = write_styles(&wb, &styles.dxfs, &[], NumFmts::default());
|
||||
let root = crate::xml::parse(xml.as_bytes()).unwrap();
|
||||
for section in ["dxfs", "cellXfs", "cellStyleXfs"] {
|
||||
let orders: Vec<_> = root
|
||||
|
||||
@@ -111,6 +111,7 @@ pub fn paper_id(name: &str) -> Option<u32> {
|
||||
|
||||
/// Functions introduced after Excel 2007 that files store with the `_xlfn.` prefix. Entries with
|
||||
/// `_xlws.` get `_xlfn._xlws.`.
|
||||
/// NETWORKDAYS.INTL and WORKDAY.INTL are in the file format's own function list, so they're saved without `_xlfn.` (#3517).
|
||||
const FUTURE_FUNCTIONS: &[&str] = &[
|
||||
"ACOT",
|
||||
"ACOTH",
|
||||
@@ -207,7 +208,6 @@ const FUTURE_FUNCTIONS: &[&str] = &[
|
||||
"MODE.SNGL",
|
||||
"MUNIT",
|
||||
"NEGBINOM.DIST",
|
||||
"NETWORKDAYS.INTL",
|
||||
"NORM.DIST",
|
||||
"NORM.INV",
|
||||
"NORM.S.DIST",
|
||||
@@ -270,7 +270,6 @@ const FUTURE_FUNCTIONS: &[&str] = &[
|
||||
"VSTACK",
|
||||
"WEBSERVICE",
|
||||
"WEIBULL.DIST",
|
||||
"WORKDAY.INTL",
|
||||
"WRAPCOLS",
|
||||
"WRAPROWS",
|
||||
"XLOOKUP",
|
||||
@@ -381,8 +380,8 @@ mod tests {
|
||||
assert_eq!(file_function_name("stockhistory").as_deref(), Some("_xlfn.STOCKHISTORY"));
|
||||
assert_eq!(file_function_name("TRANSLATE").as_deref(), Some("_xlfn.TRANSLATE"));
|
||||
assert_eq!(file_function_name("DETECTLANGUAGE").as_deref(), Some("_xlfn.DETECTLANGUAGE"));
|
||||
assert_eq!(file_function_name("NETWORKDAYS.INTL").as_deref(), Some("_xlfn.NETWORKDAYS.INTL"));
|
||||
assert_eq!(file_function_name("WORKDAY.INTL").as_deref(), Some("_xlfn.WORKDAY.INTL"));
|
||||
assert_eq!(file_function_name("NETWORKDAYS.INTL"), None);
|
||||
assert_eq!(file_function_name("WORKDAY.INTL"), None);
|
||||
// Excel 16.0 build 20527 saves COPILOT as plain `COPILOT(...)` (it does not know the name yet).
|
||||
assert_eq!(file_function_name("COPILOT"), None);
|
||||
assert_eq!(file_function_name("SUM"), None);
|
||||
|
||||
@@ -623,3 +623,24 @@ fn long_flat_chains_are_scalar_formulas() {
|
||||
assert_dynamic(&sheet, "B4", "B4");
|
||||
assert_eq!(cell(&sheet, "B1").child("f").unwrap().text, refs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spilled_text_is_written_as_a_cached_string_not_a_shared_string() {
|
||||
let mut wb = Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
let mut anchor = Cell::formula(Formula::new("SORT({\"b\";\"a\";\"c\"})"));
|
||||
anchor.value = Value::text("a");
|
||||
sh.cells.set(at("K4"), anchor);
|
||||
sh.spill_ranges.insert(at("K4"), range("K4:K6"));
|
||||
sh.spill.insert(at("K5"), Value::text("b"));
|
||||
sh.spill.insert(at("K6"), Value::text("c"));
|
||||
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let mut pkg = Package::open(&bytes).unwrap();
|
||||
let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap();
|
||||
for (address, text) in [("K4", "a"), ("K5", "b"), ("K6", "c")] {
|
||||
let c = cell(&sheet, address);
|
||||
assert_eq!(c.attr("t"), Some("str"), "{address}");
|
||||
assert_eq!(c.child("v").unwrap().text, text, "{address}");
|
||||
}
|
||||
}
|
||||
@@ -360,6 +360,43 @@ fn the_cap_counts_the_bytes_the_cells_hold_and_accepted_exports_keep_every_posit
|
||||
assert_eq!(tabs.len(), 14);
|
||||
}
|
||||
|
||||
/// #2159: a record keeps at most one field per sheet column while it is read, not after; the rest
|
||||
/// of the line is still read through, so the next line starts the next record.
|
||||
#[test]
|
||||
fn fields_past_the_last_column_are_not_collected() {
|
||||
let src = format!("{}last\nnext,row\n", "x,".repeat(100_000));
|
||||
let mut records = vec![];
|
||||
parse_records(&src, ',', '"', MAX_COLS as usize, |rec| {
|
||||
records.push(rec);
|
||||
true
|
||||
});
|
||||
assert_eq!(records.len(), 2);
|
||||
assert_eq!(records[0].len(), 16_384);
|
||||
assert_eq!(records[1], vec!["next".to_string(), "row".to_string()]);
|
||||
// The same through the reader, and a quoted delimiter past the cap doesn't split the line.
|
||||
let src = format!("{}\"a,\nb\",z\nnext\n", "x,".repeat(20_000));
|
||||
let wb = read_csv(src.as_bytes(), &CsvOptions { delimiter: b',', ..CsvOptions::default() }).unwrap();
|
||||
assert_eq!(v(&wb, 0, 16_383), Value::text("x"));
|
||||
assert_eq!(v(&wb, 1, 0), Value::text("next"));
|
||||
assert_eq!(wb.sheet(0).unwrap().cells.len(), 16_385);
|
||||
}
|
||||
|
||||
/// #2159: a long field past the last column is skipped character by character, not collected
|
||||
/// and then thrown away; a quote inside it is a plain character, as in a kept field.
|
||||
#[test]
|
||||
fn a_long_field_past_the_last_column_is_not_stored() {
|
||||
let src = format!("{}{}a\"b,{}\nnext,row\n", "x,".repeat(16_384), "y".repeat(1_000_000), "z".repeat(1_000));
|
||||
let mut records = vec![];
|
||||
parse_records(&src, ',', '"', MAX_COLS as usize, |rec| {
|
||||
records.push(rec);
|
||||
true
|
||||
});
|
||||
assert_eq!(records.len(), 2, "the quote didn't open a quoted field across the line end");
|
||||
assert_eq!(records[0].len(), 16_384);
|
||||
assert!(records[0].iter().all(|f| f == "x"));
|
||||
assert_eq!(records[1], vec!["next".to_string(), "row".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_stops_collecting_fields_at_max_cols() {
|
||||
let extra = 50;
|
||||
|
||||
@@ -20,6 +20,7 @@ fn equation(id: u32, cell: &str, latex: &str, ink: Color) -> Shape {
|
||||
text: latex.into(),
|
||||
format: Default::default(),
|
||||
math: Default::default(),
|
||||
rotation: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +162,7 @@ fn a_text_box_stays_a_text_box_and_hostile_sources_survive() {
|
||||
text: "plain".into(),
|
||||
format: Default::default(),
|
||||
math: Default::default(),
|
||||
rotation: 0.0,
|
||||
});
|
||||
wb.sheets[0] = Arc::new(sh);
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
@@ -210,7 +212,7 @@ fn a_marker_over_garbage_office_math_falls_back_without_panicking() {
|
||||
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
|
||||
let mut d = drawing(&parts);
|
||||
let (m0, m1) = (d.find("<m:oMath>").unwrap(), d.find("</m:oMath>").unwrap());
|
||||
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:sPre/><m:f><m:num/></m:f><m:r/><m:t>junk</m:t><m:oMath/><m:e/></m:oMath>");
|
||||
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:unknown/><m:r/><m:t>junk</m:t><m:oMath/><m:e/></m:oMath>");
|
||||
parts.insert(name.clone(), d.into_bytes());
|
||||
let (back, _) = read_xlsx(&rezip(&parts)).unwrap();
|
||||
let s = shapes(&back);
|
||||
@@ -233,17 +235,14 @@ fn office_math_outside_the_subset_reads_the_fallback() {
|
||||
let mut parts = unzip(&write_xlsx(&wb).unwrap());
|
||||
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
|
||||
let mut d = drawing(&parts);
|
||||
// Another writer: no GridCraft source, Office Math the reader does not convert (a
|
||||
// pre-subscript), and a fallback text box with its own text.
|
||||
// Another writer: no GridCraft source, Office Math the reader does not convert,
|
||||
// and a fallback text box with its own text.
|
||||
while let Some(a) = d.find(" descr=\"gridcraft:latex:") {
|
||||
let b = d[a + 8..].find('"').unwrap() + a + 9;
|
||||
d.replace_range(a..b, "");
|
||||
}
|
||||
let (m0, m1) = (d.find("<m:oMath>").unwrap(), d.find("</m:oMath>").unwrap());
|
||||
d.replace_range(
|
||||
m0..m1 + "</m:oMath>".len(),
|
||||
"<m:oMath><m:sPre><m:sub><m:r><m:t>1</m:t></m:r></m:sub><m:sup><m:r><m:t>2</m:t></m:r></m:sup><m:e><m:r><m:t>y</m:t></m:r></m:e></m:sPre></m:oMath>",
|
||||
);
|
||||
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:unknown><m:e><m:r><m:t>y</m:t></m:r></m:e></m:unknown></m:oMath>");
|
||||
let fb = d.find("<mc:Fallback>").unwrap();
|
||||
let t = d[fb..].find("<a:t>x^2</a:t>").unwrap() + fb;
|
||||
d.replace_range(t..t + "<a:t>x^2</a:t>".len(), "<a:t>the writer's fallback</a:t>");
|
||||
|
||||
@@ -62,6 +62,7 @@ fn exported_ink_has_a_visible_unfilled_path_and_correct_stroke() {
|
||||
line: Color::Rgb(0xA12BCD),
|
||||
text: "-10.0,5.0;50.0,40.0;90.0,10.0".into(),
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -280,6 +280,119 @@ fn hostile_formula_text_does_not_overflow_the_stack() {
|
||||
assert_eq!(a_value, gridcraft_core::Value::Number(3.0));
|
||||
}
|
||||
|
||||
/// A one-sheet-per-entry workbook: `names` are the sheet names, every sheet sharing one part.
|
||||
fn many_sheets(names: &[String]) -> Vec<u8> {
|
||||
let sheets: String = names.iter().enumerate().map(|(i, n)| format!(r#"<sheet name="{n}" sheetId="{}" r:id="rId1"/>"#, i + 1)).collect();
|
||||
let wb = format!(
|
||||
r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>{sheets}</sheets></workbook>"#
|
||||
);
|
||||
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#;
|
||||
let sheet = r#"<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>"#;
|
||||
make_zip(&[
|
||||
("[Content_Types].xml", super::CT.as_bytes()),
|
||||
("_rels/.rels", super::ROOT_RELS.as_bytes()),
|
||||
("xl/workbook.xml", wb.as_bytes()),
|
||||
("xl/_rels/workbook.xml.rels", rels.as_bytes()),
|
||||
("xl/worksheets/sheet1.xml", sheet.as_bytes()),
|
||||
])
|
||||
}
|
||||
|
||||
/// #2159: a row of endless `<c>` is not built in memory: the part's kept-element cap
|
||||
/// ([`crate::xml::MAX_XML_NODES`]) stops it, and the sheet is reported as damaged.
|
||||
#[test]
|
||||
fn a_row_wider_than_the_grid_is_refused() {
|
||||
let row = |n: usize| format!(r#"<sheetData><row r="1">{}</row></sheetData>"#, "<c/>".repeat(n));
|
||||
let (wb, rep) = read_xlsx(&minimal(&row(crate::xml::MAX_XML_NODES + 1), &[], "", "")).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().cells.is_empty());
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("damaged")), "{:?}", rep.warnings);
|
||||
assert!(read_xlsx(&minimal(&row(16_384), &[], "", "")).is_ok());
|
||||
// Every other part has the cap too (a merge list of more than a million entries).
|
||||
let merges = format!("<sheetData/><mergeCells>{}</mergeCells>", r#"<mergeCell ref="A1:B2"/>"#.repeat(crate::xml::MAX_XML_NODES + 1));
|
||||
let (wb, rep) = read_xlsx(&minimal(&merges, &[], "", "")).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().merges.is_empty());
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("damaged")), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
/// #2159: overlapping `<col min=1 max=16384>` entries share one budget of column writes.
|
||||
#[test]
|
||||
fn overlapping_column_entries_have_a_budget() {
|
||||
let parts = [("xl/styles.xml", r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>"#)];
|
||||
let rels = r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>"#;
|
||||
let cols = format!("<cols>{}</cols><sheetData/>", r#"<col min="1" max="16384" width="20" customWidth="1"/>"#.repeat(300));
|
||||
assert!(matches!(read_xlsx(&minimal(&cols, &parts, rels, "")), Err(IoError::TooLarge(_))));
|
||||
// A normal list reads with no warning.
|
||||
let (wb, rep) = read_xlsx(&minimal(r#"<cols><col min="2" max="4" width="20" customWidth="1"/></cols><sheetData/>"#, &parts, rels, "")).unwrap();
|
||||
assert_eq!(wb.sheet(0).unwrap().cols.len(), 3);
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
/// #2159: the sheet count is capped, and renaming duplicate sheet names stays linear.
|
||||
#[test]
|
||||
fn sheet_count_is_capped_and_duplicate_names_are_renamed() {
|
||||
let names: Vec<String> = (0..4097).map(|i| format!("S{i}")).collect();
|
||||
assert!(matches!(read_xlsx(&many_sheets(&names)), Err(IoError::TooLarge(_))));
|
||||
let dups: Vec<String> = (0..300).map(|i| if i % 2 == 0 { "a".to_string() } else { "A".to_string() }).collect();
|
||||
let (wb, _) = read_xlsx(&many_sheets(&dups)).unwrap();
|
||||
assert_eq!(wb.sheets.len(), 300);
|
||||
assert_eq!(wb.sheets[0].name, "a");
|
||||
assert_eq!(wb.sheets[1].name, "A (2)");
|
||||
assert_eq!(wb.sheets[299].name, "A (300)");
|
||||
let distinct: std::collections::HashSet<String> = wb.sheets.iter().map(|s| s.name.to_ascii_lowercase()).collect();
|
||||
assert_eq!(distinct.len(), 300);
|
||||
// The name set alone: thousands of duplicates, with a suffixed name already taken.
|
||||
let mut taken = crate::read::SheetNames::default();
|
||||
assert_eq!(taken.unique("x (3)", 0), "x (3)");
|
||||
let got: Vec<String> = (0..4096).map(|i| taken.unique("X", i)).collect();
|
||||
assert_eq!(got[0], "X");
|
||||
assert_eq!(got[1], "X (2)");
|
||||
assert_eq!(got[2], "X (4)");
|
||||
assert_eq!(got.iter().map(|n| n.to_ascii_lowercase()).collect::<std::collections::HashSet<_>>().len(), 4096);
|
||||
assert_eq!(taken.unique("", 9), "Sheet10");
|
||||
// A 25-character name repeated past ` (999)` shortens its prefix so every name fits 31.
|
||||
let mut taken = crate::read::SheetNames::default();
|
||||
let base = "N".repeat(25);
|
||||
let got: Vec<String> = (0..4096).map(|i| taken.unique(&base, i)).collect();
|
||||
assert!(got.iter().all(|n| n.chars().count() <= 31), "{:?}", got.iter().find(|n| n.chars().count() > 31));
|
||||
assert_eq!(got[998], format!("{base} (999)"));
|
||||
assert_eq!(got[999], format!("{} (1000)", "N".repeat(24)));
|
||||
assert_eq!(got.iter().map(|n| n.to_ascii_lowercase()).collect::<std::collections::HashSet<_>>().len(), 4096);
|
||||
}
|
||||
|
||||
/// #2159: the shared-string count is capped (each string is an allocation of its own).
|
||||
#[test]
|
||||
fn too_many_shared_strings_are_refused() {
|
||||
let sst = |n: usize| format!(r#"<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">{}</sst>"#, "<si/>".repeat(n));
|
||||
let rels = r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>"#;
|
||||
let big = sst(4_000_001);
|
||||
assert!(matches!(read_xlsx(&minimal("<sheetData/>", &[("xl/sharedStrings.xml", &big)], rels, "")), Err(IoError::TooLarge(_))));
|
||||
let small = sst(3);
|
||||
assert!(read_xlsx(&minimal("<sheetData/>", &[("xl/sharedStrings.xml", &small)], rels, "")).is_ok());
|
||||
}
|
||||
|
||||
/// #2159: hyperlinks find their relationship by id (a map, not a scan per hyperlink); the first
|
||||
/// of duplicate ids wins, as before.
|
||||
#[test]
|
||||
fn hyperlinks_resolve_relationships_by_id() {
|
||||
let n = 5_000;
|
||||
let mut rels = String::from(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
|
||||
for i in 0..n {
|
||||
rels.push_str(&format!(
|
||||
r#"<Relationship Id="h{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/{i}" TargetMode="External"/>"#
|
||||
));
|
||||
}
|
||||
rels.push_str(r#"<Relationship Id="h0" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com/second" TargetMode="External"/>"#);
|
||||
rels.push_str("</Relationships>");
|
||||
let links: String = (0..n).map(|i| format!(r#"<hyperlink ref="A{}" r:id="h{i}"/>"#, i + 1)).collect();
|
||||
let body = format!(r#"<sheetData/><hyperlinks>{links}<hyperlink ref="B1" r:id="missing"/></hyperlinks>"#);
|
||||
let (wb, _) = read_xlsx(&minimal(&body, &[("xl/worksheets/_rels/sheet1.xml.rels", &rels)], "", "")).unwrap();
|
||||
let s = wb.sheet(0).unwrap();
|
||||
assert_eq!(s.hyperlinks.len(), n);
|
||||
let link = |a: &str| s.hyperlinks.get(&gridcraft_core::CellRef::parse(a).unwrap()).map(|h| h.target.clone());
|
||||
assert_eq!(link("A1").as_deref(), Some("https://example.com/0"));
|
||||
assert_eq!(link("A5000").as_deref(), Some("https://example.com/4999"));
|
||||
assert_eq!(link("B1"), None);
|
||||
}
|
||||
|
||||
/// #2173: a hyperlink is copied into every cell it covers, so oversized targets are dropped,
|
||||
/// ScreenTips are cut to 255 characters and the cell cap holds across `<hyperlinks>` blocks.
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user