mirror of
https://github.com/storytold/gridcraft.git
synced 2026-10-26 03:36:54 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
66ed962ad1 | ||
|
|
bc881f6c4f |
Generated
+68
-264
@@ -195,6 +195,15 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -211,7 +220,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -733,15 +742,6 @@ dependencies = [
|
||||
"x509-cert",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cobs"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codespan-reporting"
|
||||
version = "0.13.1"
|
||||
@@ -877,41 +877,13 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
"icu_locale_core",
|
||||
"icu_locale_fallback",
|
||||
"icu_normalizer",
|
||||
"icu_plurals",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"icu_provider_adapters",
|
||||
"icu_provider_blob",
|
||||
"log",
|
||||
"objc2-foundation 0.3.2",
|
||||
"sys-locale",
|
||||
"unicode-bidi",
|
||||
"windows-registry",
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"miniz_oxide 0.9.1",
|
||||
"miniz_oxide 0.8.9",
|
||||
"roxmltree",
|
||||
"tempfile",
|
||||
"winprint",
|
||||
@@ -921,27 +893,15 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
"egui",
|
||||
"epaint",
|
||||
"js-sys",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"skrifa 0.44.0",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=495e5971bc024aa96e6ed318cb6e7cd3a0103184#495e5971bc024aa96e6ed318cb6e7cd3a0103184"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -960,18 +920,7 @@ dependencies = [
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b926b5c03e256c86ca10934f58d03f628810b5b7#b926b5c03e256c86ca10934f58d03f628810b5b7"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"wayland-client",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1098,6 +1047,17 @@ version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dify"
|
||||
version = "0.8.0"
|
||||
@@ -1408,7 +1368,7 @@ dependencies = [
|
||||
"parking_lot",
|
||||
"profiling",
|
||||
"self_cell",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"smallvec",
|
||||
"unicode-bidi",
|
||||
"unicode-general-category",
|
||||
@@ -1435,7 +1395,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1516,17 +1476,6 @@ version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
|
||||
|
||||
[[package]]
|
||||
name = "fixed_decimal"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"smallvec",
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fixedbitset"
|
||||
version = "0.5.7"
|
||||
@@ -1603,9 +1552,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.7"
|
||||
version = "0.12.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d"
|
||||
checksum = "6c92d9081c7ab3bd83ef1eecdfad090f3d966e3ce74106779664114cfe1a6274"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -1816,7 +1765,7 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
]
|
||||
@@ -1970,9 +1919,9 @@ dependencies = [
|
||||
"gridcraft-engine",
|
||||
"gridcraft-mcp",
|
||||
"log",
|
||||
"quick-xml 0.42.0",
|
||||
"quick-xml 0.41.0",
|
||||
"serde_json",
|
||||
"zip",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2004,7 +1953,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2062,7 +2011,6 @@ version = "0.12.1"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
"epaint_default_fonts",
|
||||
@@ -2073,7 +2021,7 @@ dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.48.0",
|
||||
"skrifa",
|
||||
"sys-locale",
|
||||
"toml",
|
||||
"web-sys",
|
||||
@@ -2105,11 +2053,11 @@ dependencies = [
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
"gridcraft-model",
|
||||
"quick-xml 0.42.0",
|
||||
"quick-xml 0.41.0",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2160,7 +2108,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2359,23 +2307,6 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_decimal"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9eb8f655bba2d0c0459e43a5b0e6cd3cd388109898fb3d85d048165e8b0abd08"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"fixed_decimal",
|
||||
"icu_locale_core",
|
||||
"icu_pattern",
|
||||
"icu_plurals",
|
||||
"icu_provider",
|
||||
"serde",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.3.0"
|
||||
@@ -2384,32 +2315,11 @@ checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"serde",
|
||||
"tinystr",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
|
||||
dependencies = [
|
||||
"icu_locale_core",
|
||||
"icu_locale_fallback_data",
|
||||
"icu_provider",
|
||||
"potential_utf",
|
||||
"tinystr",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer"
|
||||
version = "2.3.0"
|
||||
@@ -2421,9 +2331,6 @@ dependencies = [
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"smallvec",
|
||||
"utf16_iter",
|
||||
"utf8_iter",
|
||||
"write16",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
@@ -2433,32 +2340,6 @@ version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
|
||||
|
||||
[[package]]
|
||||
name = "icu_pattern"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc43ce0e76ee8cb0482dc6e2dbb9b76278e8038f45daabf2a2877577e2ceb18f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"either",
|
||||
"serde",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_plurals"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e475e6766ef87b1d3c1f97be6363995b0bfaeddbc789671615df598a97ff0593"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"fixed_decimal",
|
||||
"icu_provider",
|
||||
"serde",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties"
|
||||
version = "2.3.0"
|
||||
@@ -2488,9 +2369,6 @@ checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_locale_core",
|
||||
"postcard",
|
||||
"serde",
|
||||
"stable_deref_trait",
|
||||
"writeable",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
@@ -2498,30 +2376,6 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider_adapters"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df887bc4f55dbc773c7c45a0c7dfa75be886f7b7812830a71ab7271cc1801820"
|
||||
dependencies = [
|
||||
"icu_locale_fallback",
|
||||
"icu_provider",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider_blob"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5916b44fac319d3f58e4d8d805a627df19e27937b582cd99fcde3bb6b7ce1b0e"
|
||||
dependencies = [
|
||||
"icu_provider",
|
||||
"postcard",
|
||||
"serde",
|
||||
"writeable",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "1.1.0"
|
||||
@@ -2809,9 +2663,6 @@ name = "litemap"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "litrs"
|
||||
@@ -3437,7 +3288,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3686,24 +3537,12 @@ dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "postcard"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
|
||||
dependencies = [
|
||||
"cobs",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
@@ -3851,7 +3690,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3962,19 +3801,6 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.45.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4edc8db0d972de88e53a085b1f01fb3fbdae7bb0cb7a0ce2b2f8285a412fe3ef"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash 0.2.0",
|
||||
"font-types",
|
||||
"once_cell",
|
||||
"yoke",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.4.1"
|
||||
@@ -4123,12 +3949,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.2"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
@@ -4174,7 +3997,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4233,7 +4056,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4697,17 +4520,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5213b4825bac3587046330052d61bfac7bd3bd0d203c758d7c2ef726fcea034"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.45.1",
|
||||
"read-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4929,10 +4742,7 @@ version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4974,10 +4784,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix 1.1.5",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5080,7 +4890,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"serde_core",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
@@ -5415,12 +5224,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf16_iter"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246"
|
||||
|
||||
[[package]]
|
||||
name = "utf8-zero"
|
||||
version = "0.8.1"
|
||||
@@ -5936,7 +5739,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6281,20 +6084,11 @@ dependencies = [
|
||||
"wayland-protocols-wlr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write16"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x11-dl"
|
||||
@@ -6410,9 +6204,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.4"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"
|
||||
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
"yoke-derive",
|
||||
@@ -6605,20 +6399,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"serde_core",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec"
|
||||
version = "0.11.9"
|
||||
version = "0.11.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"
|
||||
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec-derive",
|
||||
@@ -6626,15 +6416,29 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zerovec-derive"
|
||||
version = "0.11.7"
|
||||
version = "0.11.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
|
||||
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.0"
|
||||
|
||||
+4
-9
@@ -24,9 +24,7 @@ gridcraft-engine = { path = "crates/engine" }
|
||||
gridcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
gridcraft-mcp = { path = "crates/mcp" }
|
||||
gridcraft-pdf = { path = "crates/pdf" }
|
||||
# Every craft-libs crate (craft-update and craft-window here, craft-ui in ui-egui, craft-print in
|
||||
# the app) comes from one storytold/craft-libs revision.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "b926b5c03e256c86ca10934f58d03f628810b5b7", version = "=0.1.0", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "495e5971bc024aa96e6ed318cb6e7cd3a0103184", features = ["egui"] }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -37,8 +35,8 @@ log = "0.4"
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
rayon = "1"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
|
||||
quick-xml = "0.42"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
# Decrypting password-protected workbooks ([MS-OFFCRYPTO]): AES and SHA-1, pure Rust (wasm-safe).
|
||||
aes = { version = "0.9", default-features = false }
|
||||
@@ -56,12 +54,9 @@ arboard = { version = "3.6", default-features = false }
|
||||
sys-locale = "0.3"
|
||||
# Font parser egui's epaint uses; the UI validates system font files with it before handing them
|
||||
# to egui, which panics on a file it can't parse. Same version as epaint's, so no second copy.
|
||||
skrifa = { version = "0.48", default-features = false, features = ["std"] }
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
# Real font bytes for tests (Ubuntu Light, compiled into epaint).
|
||||
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 = "b926b5c03e256c86ca10934f58d03f628810b5b7", default-features = false, features = ["egui"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
@@ -147,10 +147,6 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
|
||||
| 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row |
|
||||
| 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) |
|
||||
| 2026-10-22 | View › New Window and Arrange All on the ribbon. Arrange All tiles, stacks side by side or top to bottom, or cascades the native windows over the main window's monitor, the active one first. Two windows on one workbook show different sheets without copying the workbook or marking it changed; Save records the sheet of the window used last. A dialog stays in the window it was opened in |
|
||||
| 2026-10-22 | On the desktop every workbook window is a native window of its own: New, Open and New Window open one, each keeps its own cell draft, dialog and ribbon, and the macOS menu bar acts on the window focused last. Closing one of several windows on a workbook doesn't ask; closing a workbook's last window, or quitting, asks about unsaved changes in that window. The last window closed quits on Windows and Linux; macOS keeps running with the menu bar. First craft-libs `craft-window` use (window list and viewport driver) |
|
||||
| 2026-10-22 | View › New Window opens a second window on the same workbook (it used to open a copy whose Save overwrote the original): each window has its own selection, active sheet and scroll, titles read "Book1:1" / "Book1:2", and Switch Windows, Hide, Unhide and Close act per window. The control channel, CLI `send` and MCP tools take an optional `window` or `doc` id and default to the active window; `window.list` (MCP `list_windows`) lists the windows |
|
||||
| 2026-10-22 | Typing in a cell and then choosing File › New no longer strands the first workbook: the entry is committed into its own workbook before any File or window command (a refused entry stays open and stops the command), View › Switch Windows and the macOS Window menu list the open workbooks with unsaved markers, `view.switchWindows {doc}` switches by a stable workbook id, and the macOS Quit item asks about unsaved workbooks |
|
||||
| 2026-10-21 | Page Setup paper sizes match Japanese Excel: `B4`/`B5`/`B6` are the JIS sizes (ISO B4/B5/B6 stay reachable by name), so a Japanese B5 worksheet prints at 182×257 mm; Japanese Postcard (100×148 mm), Double Postcard (148×200 mm), Envelope #3/#4 (120×235/90×205 mm), Kaku #2/#3 (240×332/216×277 mm) and A6 are added, both sizes reach the PDF page (`file.exportPdf`/`file.print` MediaBox) and the size survives an XLSX round-trip; the Page Layout Size menu lists them. `B4`/`B5` used to be the ISO sizes, which is changed here |
|
||||
| 2026-10-20 | Japanese interface catalog covers every key the Brazilian Portuguese catalog translates: the 398-label shared core plus 545 dialog, message, Backstage and menu strings (943 total, ~43% of ~2,200). A test parses `pt.rs`'s source, so the two catalogs stay in step |
|
||||
| 2026-10-20 | Interface translated into Dutch (518 labels: ribbon, context menus, File view, dialog titles, Options); `nl`, `nl-NL`, `nl-BE` locale tags resolve to Dutch |
|
||||
@@ -246,10 +242,6 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-23 | minor | Progress log: accounting negatives in number text |
|
||||
| 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! |
|
||||
| 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) |
|
||||
| 2026-10-22 | minor | Progress log: Arrange All; two windows on one workbook without copying it |
|
||||
| 2026-10-22 | minor | Progress log: a native window per workbook window |
|
||||
| 2026-10-22 | minor | Progress log: New Window shares the workbook; window ids for scripts and MCP |
|
||||
| 2026-10-22 | minor | Progress log: drafts stay in their workbook, Switch Windows, macOS Quit asks to save |
|
||||
| 2026-10-21 | minor | Page Setup paper sizes: JIS B4/B5/B6 (ISO by name), Japanese postcards and envelopes, A6; PDF page size follows, XLSX round-trips |
|
||||
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
|
||||
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
|
||||
|
||||
@@ -28,9 +28,7 @@ winresource = "0.1"
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
|
||||
# Cargo.toml).
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "b926b5c03e256c86ca10934f58d03f628810b5b7" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f" }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true }
|
||||
|
||||
@@ -43,8 +43,7 @@ pub fn poll(inbox: &Inbox, app: &mut SheetApp, ctx: &egui::Context) {
|
||||
app.open_path(p);
|
||||
}
|
||||
}
|
||||
// Quit from the Dock or the system: each unsaved workbook is asked about in its window.
|
||||
Event::Quit => app.request_quit(ctx),
|
||||
Event::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,27 +23,24 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_ui_egui::doc_windows::DocWindows;
|
||||
use gridcraft_ui_egui::{Services, SheetApp};
|
||||
use serde_json::json;
|
||||
|
||||
/// The app, its native window per workbook window, and (macOS) the menu bar and Finder events.
|
||||
struct App(SheetApp, DocWindows, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>, #[cfg(target_os = "macos")] fmv_macos_events::Inbox);
|
||||
struct App(SheetApp, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>, #[cfg(target_os = "macos")] fmv_macos_events::Inbox);
|
||||
|
||||
impl eframe::App for App {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if self.2.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
|
||||
self.2 = Some(native_menu::NativeMenu::install(ctx));
|
||||
if self.1.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
|
||||
self.1 = Some(native_menu::NativeMenu::install(ctx));
|
||||
}
|
||||
if let Some(m) = &mut self.2 {
|
||||
m.poll(&mut self.0, ctx, self.1.focused_viewport());
|
||||
if let Some(m) = &self.1 {
|
||||
m.poll(&mut self.0, ctx);
|
||||
}
|
||||
apple_events::poll(&self.3, &mut self.0, ctx);
|
||||
apple_events::poll(&self.2, &mut self.0, ctx);
|
||||
}
|
||||
self.0.logic(ctx);
|
||||
self.1.logic(&mut self.0, ctx);
|
||||
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
@@ -59,7 +56,7 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.1.show(&mut self.0, ui);
|
||||
self.0.ui(ui);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
print::finish_pending_jobs();
|
||||
@@ -338,7 +335,6 @@ fn main() -> eframe::Result<()> {
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
let window_builder = viewport.clone();
|
||||
let options = eframe::NativeOptions { viewport, ..Default::default() };
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let mut options = options;
|
||||
@@ -388,10 +384,8 @@ fn main() -> eframe::Result<()> {
|
||||
Err(e) => log::error!("control channel on port {port}: {e}"),
|
||||
}
|
||||
}
|
||||
let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window());
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
windows,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::str::FromStr;
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use gridcraft_ui_egui::{OpenWindow, SheetApp};
|
||||
use gridcraft_ui_egui::SheetApp;
|
||||
use muda::accelerator::Accelerator;
|
||||
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
|
||||
use serde_json::{Value, json};
|
||||
@@ -168,16 +168,7 @@ fn tree() -> Vec<(&'static str, Vec<Entry>)> {
|
||||
("Calculate Now", "formulas.calculateNow", None),
|
||||
],
|
||||
),
|
||||
// The open workbooks follow the separator (`NativeMenu::sync_windows`).
|
||||
(
|
||||
"Window",
|
||||
vec![
|
||||
("New Window", "view.newWindow", None),
|
||||
("Next Sheet", "sheet.next", None),
|
||||
("Previous Sheet", "sheet.previous", None),
|
||||
("-", "", None),
|
||||
],
|
||||
),
|
||||
("Window", vec![("New Window", "view.newWindow", None), ("Next Sheet", "sheet.next", None), ("Previous Sheet", "sheet.previous", None)]),
|
||||
(
|
||||
"Help",
|
||||
vec![
|
||||
@@ -195,19 +186,8 @@ pub struct NativeMenu {
|
||||
_menu: Menu,
|
||||
events: Receiver<MenuEvent>,
|
||||
theme_items: Vec<(&'static str, CheckMenuItem)>,
|
||||
window_menu: Option<Submenu>,
|
||||
/// The Window menu's window items and what they last showed.
|
||||
window_items: Vec<CheckMenuItem>,
|
||||
windows: Vec<OpenWindow>,
|
||||
}
|
||||
|
||||
/// Menu id of the Window menu item that brings workbook `doc` forward.
|
||||
const WINDOW_ITEM: &str = "window:id:";
|
||||
|
||||
/// The Quit item: asks about each unsaved workbook in its window first
|
||||
/// (`SheetApp::request_quit`), which AppKit's own Quit (terminate:) would skip.
|
||||
const QUIT: &str = "app.quit";
|
||||
|
||||
fn select_theme(app: &mut SheetApp, id: &str) -> bool {
|
||||
let mode = match id {
|
||||
"theme:system" => "system",
|
||||
@@ -233,7 +213,7 @@ impl NativeMenu {
|
||||
&PredefinedMenuItem::hide_others(None),
|
||||
&PredefinedMenuItem::show_all(None),
|
||||
&PredefinedMenuItem::separator(),
|
||||
&MenuItem::with_id(QUIT, "Quit GridCraft", true, Accelerator::from_str("CMD+Q").ok()),
|
||||
&PredefinedMenuItem::quit(None),
|
||||
]);
|
||||
let _ = menu.append(&app_menu);
|
||||
let mut theme_items = Vec::new();
|
||||
@@ -268,7 +248,7 @@ impl NativeMenu {
|
||||
// NSApp's windowsMenu is where macOS adds Move & Resize, Fill and Center, the targets of the
|
||||
// system tiling shortcuts (Fn+Ctrl+arrows, Fn+F). Only once the menu is NSApp's: muda looks
|
||||
// the submenu up in the installed main menu.
|
||||
if let Some(window) = &window_menu {
|
||||
if let Some(window) = window_menu {
|
||||
window.set_as_windows_menu_for_nsapp();
|
||||
}
|
||||
let (tx, rx) = channel();
|
||||
@@ -277,54 +257,12 @@ impl NativeMenu {
|
||||
let _ = tx.send(e);
|
||||
ctx.request_repaint();
|
||||
}));
|
||||
NativeMenu { _menu: menu, events: rx, theme_items, window_menu, window_items: Vec::new(), windows: Vec::new() }
|
||||
NativeMenu { _menu: menu, events: rx, theme_items }
|
||||
}
|
||||
|
||||
/// Keeps the Window menu's list of open windows (title, unsaved bullet, active check) in
|
||||
/// step with the session.
|
||||
fn sync_windows(&mut self, app: &SheetApp) {
|
||||
let windows = app.open_windows();
|
||||
if windows != self.windows
|
||||
&& let Some(menu) = &self.window_menu
|
||||
{
|
||||
let same_windows = windows.len() == self.windows.len() && windows.iter().zip(&self.windows).all(|(a, b)| a.window == b.window);
|
||||
if same_windows {
|
||||
for (item, w) in self.window_items.iter().zip(&windows) {
|
||||
item.set_text(w.label());
|
||||
}
|
||||
} else {
|
||||
for item in self.window_items.drain(..) {
|
||||
let _ = menu.remove(&item);
|
||||
}
|
||||
for w in &windows {
|
||||
let item = CheckMenuItem::with_id(format!("{WINDOW_ITEM}{}", w.window), w.label(), true, w.active, None);
|
||||
let _ = menu.append(&item);
|
||||
self.window_items.push(item);
|
||||
}
|
||||
}
|
||||
self.windows = windows;
|
||||
}
|
||||
// AppKit flips a check item when it is chosen, so the active check is put back every poll.
|
||||
for (item, w) in self.window_items.iter().zip(&self.windows) {
|
||||
if item.is_checked() != w.active {
|
||||
item.set_checked(w.active);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the chosen menu items. Commands go to the active window, the most recently focused;
|
||||
/// `viewport` is its egui viewport, for the items that act on its input.
|
||||
pub fn poll(&mut self, app: &mut SheetApp, ctx: &egui::Context, viewport: egui::ViewportId) {
|
||||
pub fn poll(&self, app: &mut SheetApp, ctx: &egui::Context) {
|
||||
while let Ok(ev) = self.events.try_recv() {
|
||||
let id = ev.id.as_ref().to_string();
|
||||
if id == QUIT {
|
||||
app.request_quit(ctx);
|
||||
continue;
|
||||
}
|
||||
if let Some(window) = id.strip_prefix(WINDOW_ITEM).and_then(|w| w.parse::<u64>().ok()) {
|
||||
app.run_or_alert("view.switchWindows", json!({"window": window}));
|
||||
continue;
|
||||
}
|
||||
// Text selection belongs to the inline editor, not the worksheet clipboard/undo.
|
||||
if app.text_box_editor.is_some() {
|
||||
let clipboard = match id.as_str() {
|
||||
@@ -334,11 +272,11 @@ impl NativeMenu {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(command) = clipboard {
|
||||
ctx.send_viewport_cmd_to(viewport, command);
|
||||
ctx.send_viewport_cmd(command);
|
||||
continue;
|
||||
}
|
||||
if id == "edit.undo" || id == "edit.redo" {
|
||||
ctx.input_mut_for(viewport, |i| {
|
||||
ctx.input_mut(|i| {
|
||||
i.events.push(egui::Event::Key {
|
||||
key: egui::Key::Z,
|
||||
physical_key: None,
|
||||
@@ -384,7 +322,6 @@ impl NativeMenu {
|
||||
item.set_checked(checked);
|
||||
}
|
||||
}
|
||||
self.sync_windows(app);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+60
-53
@@ -927,6 +927,64 @@ impl Host for PassHost<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Strongly connected components of a graph given as adjacency lists (Tarjan, iterative): each
|
||||
/// node's component index, and the number of nodes in each component.
|
||||
fn components(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<usize>) {
|
||||
let n = edges.len();
|
||||
let (mut low, mut num) = (vec![0usize; n], vec![usize::MAX; n]);
|
||||
let (mut on_stack, mut stack, mut comp) = (vec![false; n], Vec::new(), vec![usize::MAX; n]);
|
||||
let (mut next, mut comps) = (0usize, 0usize);
|
||||
for root in 0..n {
|
||||
if num[root] != usize::MAX {
|
||||
continue;
|
||||
}
|
||||
let mut call: Vec<(usize, usize)> = vec![(root, 0)];
|
||||
num[root] = next;
|
||||
low[root] = next;
|
||||
next += 1;
|
||||
stack.push(root);
|
||||
on_stack[root] = true;
|
||||
while let Some(top) = call.last_mut() {
|
||||
let v = top.0;
|
||||
if let Some(&w) = edges.get(v).and_then(|e| e.get(top.1)) {
|
||||
top.1 += 1;
|
||||
if num[w] == usize::MAX {
|
||||
num[w] = next;
|
||||
low[w] = next;
|
||||
next += 1;
|
||||
stack.push(w);
|
||||
on_stack[w] = true;
|
||||
call.push((w, 0));
|
||||
} else if on_stack[w] {
|
||||
low[v] = low[v].min(num[w]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
call.pop();
|
||||
if let Some(&(u, _)) = call.last() {
|
||||
low[u] = low[u].min(low[v]);
|
||||
}
|
||||
if low[v] == num[v] {
|
||||
while let Some(w) = stack.pop() {
|
||||
on_stack[w] = false;
|
||||
comp[w] = comps;
|
||||
if w == v {
|
||||
break;
|
||||
}
|
||||
}
|
||||
comps += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut size = vec![0usize; comps];
|
||||
for &c in &comp {
|
||||
if let Some(s) = size.get_mut(c) {
|
||||
*s += 1;
|
||||
}
|
||||
}
|
||||
(comp, size)
|
||||
}
|
||||
|
||||
impl Calc {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
@@ -981,59 +1039,8 @@ impl Calc {
|
||||
e
|
||||
})
|
||||
.collect();
|
||||
// Tarjan's strongly connected components, iterative.
|
||||
let n = circ.len();
|
||||
let (mut low, mut num) = (vec![0usize; n], vec![usize::MAX; n]);
|
||||
let (mut on_stack, mut stack, mut comp) = (vec![false; n], Vec::new(), vec![usize::MAX; n]);
|
||||
let (mut next, mut comps) = (0usize, 0usize);
|
||||
for root in 0..n {
|
||||
if num[root] != usize::MAX {
|
||||
continue;
|
||||
}
|
||||
let mut call: Vec<(usize, usize)> = vec![(root, 0)];
|
||||
num[root] = next;
|
||||
low[root] = next;
|
||||
next += 1;
|
||||
stack.push(root);
|
||||
on_stack[root] = true;
|
||||
while let Some(top) = call.last_mut() {
|
||||
let v = top.0;
|
||||
if let Some(&w) = edges.get(v).and_then(|e| e.get(top.1)) {
|
||||
top.1 += 1;
|
||||
if num[w] == usize::MAX {
|
||||
num[w] = next;
|
||||
low[w] = next;
|
||||
next += 1;
|
||||
stack.push(w);
|
||||
on_stack[w] = true;
|
||||
call.push((w, 0));
|
||||
} else if on_stack[w] {
|
||||
low[v] = low[v].min(num[w]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
call.pop();
|
||||
if let Some(&(u, _)) = call.last() {
|
||||
low[u] = low[u].min(low[v]);
|
||||
}
|
||||
if low[v] == num[v] {
|
||||
while let Some(w) = stack.pop() {
|
||||
on_stack[w] = false;
|
||||
comp[w] = comps;
|
||||
if w == v {
|
||||
break;
|
||||
}
|
||||
}
|
||||
comps += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut size = vec![0usize; comps];
|
||||
for &c in &comp {
|
||||
if let Some(s) = size.get_mut(c) {
|
||||
*s += 1;
|
||||
}
|
||||
}
|
||||
// Loop members: nodes in a component of more than one, or with an edge to themselves.
|
||||
let (comp, size) = components(&edges);
|
||||
let on_loop = |i: usize| comp.get(i).and_then(|c| size.get(*c)).is_some_and(|s| *s > 1) || edges.get(i).is_some_and(|e| e.contains(&i));
|
||||
// A formula with dynamic references (INDIRECT, OFFSET) may close a loop the graph can't see.
|
||||
let mut out: Vec<Key> =
|
||||
|
||||
@@ -1182,7 +1182,7 @@ mod tests {
|
||||
fn v(s: &Session, a: &str) -> Value {
|
||||
let d = s.doc().unwrap();
|
||||
let (sh, body) = crate::cmd::split_sheet(a);
|
||||
let si = sh.map(|n| d.wb.sheet_index(&n).unwrap()).unwrap_or(d.wb.active_sheet());
|
||||
let si = sh.map(|n| d.wb.sheet_index(&n).unwrap()).unwrap_or(d.wb.active_sheet);
|
||||
d.wb.sheet(si).unwrap().value(CellRef::parse(body).unwrap())
|
||||
}
|
||||
fn n(s: &Session, a: &str) -> f64 {
|
||||
|
||||
@@ -167,7 +167,7 @@ fn data_target(s: &Session, p: &Json, cmd: &str) -> Result<(usize, RangeRef)> {
|
||||
{
|
||||
return Err(bad(cmd, format!("`{t}` names a sheet other than `sheet`")));
|
||||
}
|
||||
if sheet != d.wb.active_sheet() && p.get("range").is_none() {
|
||||
if sheet != d.wb.active_sheet && p.get("range").is_none() {
|
||||
return Err(bad(cmd, "missing `range`: the selection is on the active sheet"));
|
||||
}
|
||||
Ok((sheet, data_range(s, p)?))
|
||||
@@ -219,7 +219,7 @@ fn sort_target(s: &Session, p: &Json) -> Result<(usize, RangeRef)> {
|
||||
{
|
||||
return Err(bad("data.sort", format!("`{t}` names a sheet other than `sheet`")));
|
||||
}
|
||||
if sheet != d.wb.active_sheet() && p.get("range").is_none() {
|
||||
if sheet != d.wb.active_sheet && p.get("range").is_none() {
|
||||
return Err(bad("data.sort", "missing `range`: the selection is on the active sheet"));
|
||||
}
|
||||
Ok((sheet, data_range(s, p)?))
|
||||
@@ -511,7 +511,7 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (sheet, r) = data_target(s, p, "data.filter")?;
|
||||
super::refuse_unless_allowed(s, sheet, "Filtering", |p| p.autofilter)?;
|
||||
// The active cell belongs to the active sheet: on another sheet the table is the one at `range`.
|
||||
let at = if sheet == s.doc()?.wb.active_sheet() { s.doc()?.selection.active } else { r.start };
|
||||
let at = if sheet == s.doc()?.wb.active_sheet { s.doc()?.selection.active } else { r.start };
|
||||
let has = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.autofilter.is_some());
|
||||
let in_table = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.table_at(at).map(|t| t.name.clone()));
|
||||
if let Some(name) = in_table {
|
||||
@@ -563,7 +563,7 @@ fn install_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn filter_by(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
super::refuse_unless_allowed(s, sheet, "Filtering", |p| p.autofilter)?;
|
||||
let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) };
|
||||
let af = match &sh.autofilter {
|
||||
@@ -768,7 +768,7 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) {
|
||||
}
|
||||
|
||||
fn clear_filter(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
if let Some(a) = sh.autofilter.as_mut() {
|
||||
@@ -781,7 +781,7 @@ fn clear_filter(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn reapply(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
apply_filter(&mut cx.wb, sheet);
|
||||
cx.structural = true;
|
||||
@@ -1285,7 +1285,7 @@ fn validate_cmd(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let input = str_param(p, "input").unwrap_or("");
|
||||
match check_validation(&d.wb, d.wb.active_sheet(), at, input) {
|
||||
match check_validation(&d.wb, d.wb.active_sheet, at, input) {
|
||||
None => Ok(json!({"ok": true})),
|
||||
Some((dv, msg)) => Ok(json!({"ok": false, "message": msg, "title": dv.error_title, "style": format!("{:?}", dv.error_style)})),
|
||||
}
|
||||
@@ -1293,7 +1293,7 @@ fn validate_cmd(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn circle_invalid(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let Some(sh) = d.wb.sheet(sheet) else { return Err(EngineError::NoDocument) };
|
||||
let mut bad_cells = Vec::new();
|
||||
for dv in &sh.validations {
|
||||
@@ -1332,7 +1332,7 @@ fn outline_lines(s: &Session, p: &Json) -> Result<(bool, u32, u32)> {
|
||||
fn group(s: &mut Session, p: &Json, on: bool) -> Result<Json> {
|
||||
let si = target_sheet(s, p)?;
|
||||
// The selection belongs to the active sheet, so another sheet needs its lines.
|
||||
if si != s.doc()?.wb.active_sheet() && p.get("rows").is_none() && p.get("cols").is_none() {
|
||||
if si != s.doc()?.wb.active_sheet && p.get("rows").is_none() && p.get("cols").is_none() {
|
||||
return Err(bad(if on { "data.group" } else { "data.ungroup" }, "missing `rows` or `cols`: the selection is on the active sheet"));
|
||||
}
|
||||
let (rows, a, b) = outline_lines(s, p)?;
|
||||
|
||||
@@ -72,7 +72,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
str_param(p, "color").map(str::to_string).unwrap_or_else(|| if s.draw_color.is_empty() { "#1F5FC9".into() } else { s.draw_color.clone() });
|
||||
let width = f64_param(p, "width").map(|w| w as f32).unwrap_or(if s.draw_width <= 0.0 { 2.0 } else { s.draw_width }).clamp(0.5, 40.0);
|
||||
let d = s.doc()?;
|
||||
let si = d.wb.active_sheet();
|
||||
let si = d.wb.active_sheet;
|
||||
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
let cell = CellRef::new(sh.row_at(miny), sh.col_at(minx));
|
||||
let dx = (minx - sh.col_left(cell.col)) as f32;
|
||||
@@ -115,7 +115,7 @@ pub fn ink_points(sh: &Shape) -> Vec<[f32; 2]> {
|
||||
}
|
||||
|
||||
fn ink_to_shape(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let si = s.doc()?.wb.active_sheet();
|
||||
let si = s.doc()?.wb.active_sheet;
|
||||
let id = u32_param(p, "id");
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(si)?;
|
||||
|
||||
@@ -237,7 +237,7 @@ fn cell_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
{
|
||||
return Err(EngineError::Other(m));
|
||||
}
|
||||
let active_sheet = s.doc()?.wb.active_sheet();
|
||||
let active_sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
if array {
|
||||
// Legacy Ctrl+Shift+Enter array formula over the selection, when the selection holds
|
||||
@@ -438,18 +438,23 @@ fn selection_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
impl crate::DocState {
|
||||
/// Switches the active sheet, remembering each sheet's selection.
|
||||
pub fn wb_switch_sheet(&mut self, i: usize) {
|
||||
if i >= self.wb.sheets.len() || i == self.wb.active_sheet() {
|
||||
if i >= self.wb.sheets.len() || i == self.wb.active_sheet {
|
||||
return;
|
||||
}
|
||||
let cur = self.wb.active_sheet();
|
||||
let cur = self.wb.active_sheet;
|
||||
if self.sheet_selections.len() < self.wb.sheets.len() {
|
||||
self.sheet_selections.resize(self.wb.sheets.len(), crate::Selection::default());
|
||||
}
|
||||
if let Some(slot) = self.sheet_selections.get_mut(cur) {
|
||||
*slot = self.selection.clone();
|
||||
}
|
||||
// View state: set in place, so the workbook is neither copied nor made dirty.
|
||||
self.wb.set_active_sheet(i);
|
||||
// The active sheet is view state: change it without making the workbook dirty.
|
||||
let dirty = self.is_dirty();
|
||||
let wb = std::sync::Arc::make_mut(&mut self.wb);
|
||||
wb.active_sheet = i;
|
||||
if !dirty {
|
||||
self.saved = self.wb.clone();
|
||||
}
|
||||
self.selection = self.sheet_selections.get(i).cloned().unwrap_or_default();
|
||||
}
|
||||
}
|
||||
@@ -582,7 +587,7 @@ const GO_TO_NAME_DEPTH: usize = 8;
|
||||
pub(super) fn go_to(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if bool_param(p, "list") == Some(true) {
|
||||
let d = s.doc()?;
|
||||
return Ok(json!({"names": go_to_names(&d.wb, d.wb.active_sheet()), "recent": d.go_to_recent}));
|
||||
return Ok(json!({"names": go_to_names(&d.wb, d.wb.active_sheet), "recent": d.go_to_recent}));
|
||||
}
|
||||
let Some(reference) = str_param(p, "reference").or_else(|| str_param(p, "range")) else { return Err(bad("edit.goTo", "missing `reference`")) };
|
||||
let d = s.doc()?;
|
||||
@@ -590,7 +595,7 @@ pub(super) fn go_to(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let mut areas: Vec<RangeRef> = Vec::new();
|
||||
let mut named = false;
|
||||
for part in reference_parts(reference) {
|
||||
let Some((sheet, found, by_name)) = go_to_target(&d.wb, d.wb.active_sheet(), part, 0) else {
|
||||
let Some((sheet, found, by_name)) = go_to_target(&d.wb, d.wb.active_sheet, part, 0) else {
|
||||
return Err(EngineError::Other("Reference isn't valid.".into()));
|
||||
};
|
||||
// One selection holds the areas of one sheet.
|
||||
@@ -1696,7 +1701,7 @@ fn find(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let workbook = str_param(p, "within") == Some("workbook");
|
||||
s.last_find = Some(p.clone());
|
||||
let d = s.doc()?;
|
||||
let sheets: Vec<usize> = if workbook { (0..d.wb.sheets.len()).collect() } else { vec![d.wb.active_sheet()] };
|
||||
let sheets: Vec<usize> = if workbook { (0..d.wb.sheets.len()).collect() } else { vec![d.wb.active_sheet] };
|
||||
let mut hits: Vec<(usize, CellRef, String)> = Vec::new();
|
||||
for si in sheets {
|
||||
let Some(sh) = d.wb.sheet(si) else { continue };
|
||||
@@ -1726,7 +1731,7 @@ fn find(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Ok(json!({"count": list.len(), "results": list}));
|
||||
}
|
||||
// Next hit after the active cell.
|
||||
let cur = (d.wb.active_sheet(), d.selection.active);
|
||||
let cur = (d.wb.active_sheet, d.selection.active);
|
||||
let key = |si: usize, c: CellRef| if by_cols { (si, c.col, c.row) } else { (si, c.row, c.col) };
|
||||
let next = hits.iter().find(|(si, c, _)| key(*si, *c) > key(cur.0, cur.1)).or_else(|| hits.first()).cloned();
|
||||
let Some((si, c, t)) = next else { return Err(EngineError::Other("not found".into())) };
|
||||
@@ -1748,7 +1753,7 @@ fn replace(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let workbook = str_param(p, "within") == Some("workbook");
|
||||
let active = s.doc()?.selection.active;
|
||||
let n = edit(s, |cx| {
|
||||
let sheets: Vec<usize> = if workbook { (0..cx.wb.sheets.len()).collect() } else { vec![cx.wb.active_sheet()] };
|
||||
let sheets: Vec<usize> = if workbook { (0..cx.wb.sheets.len()).collect() } else { vec![cx.wb.active_sheet] };
|
||||
let mut n = 0;
|
||||
for si in sheets {
|
||||
let cells: Vec<(CellRef, String)> =
|
||||
@@ -1820,7 +1825,7 @@ fn replace_ci(text: &str, what: &str, with: &str) -> String {
|
||||
fn format_painter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let Some(dest) = str_param(p, "apply").and_then(RangeRef::parse) {
|
||||
let Some((wb, sheet, src, sticky)) = s.format_painter.clone() else { return Err(EngineError::Other("Pick up a format first.".into())) };
|
||||
let dest_sheet = s.doc()?.wb.active_sheet();
|
||||
let dest_sheet = s.doc()?.wb.active_sheet;
|
||||
let same = std::sync::Arc::ptr_eq(&wb, &s.doc()?.wb) || s.doc()?.wb.styles == wb.styles;
|
||||
edit(s, |cx| {
|
||||
let Some(src_sheet) = wb.sheet(sheet) else { return Ok(()) };
|
||||
@@ -1900,7 +1905,7 @@ fn format_painter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
let sticky = bool_param(p, "sticky").unwrap_or(false);
|
||||
let d = s.doc()?;
|
||||
s.format_painter = Some((d.wb.clone(), d.wb.active_sheet(), d.selection.current(), sticky));
|
||||
s.format_painter = Some((d.wb.clone(), d.wb.active_sheet, d.selection.current(), sticky));
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -1960,11 +1965,11 @@ mod tests {
|
||||
let mut s = go_to_workbook();
|
||||
let out = s.execute("edit.goTo", json!({"reference": "Sheet2!Local"})).unwrap();
|
||||
assert_eq!(out["selection"], "C3", "{out}");
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet(), 1);
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet, 1);
|
||||
// A name of several areas selects all of them.
|
||||
let out = s.execute("edit.goTo", json!({"reference": "Areas"})).unwrap();
|
||||
assert_eq!(out["selection"], "A1,C3:C4", "{out}");
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet(), 0);
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet, 0);
|
||||
}
|
||||
|
||||
/// A name matches in any case and any script, as a formula matches it.
|
||||
@@ -1991,7 +1996,7 @@ mod tests {
|
||||
assert_eq!(out["selection"], "B2:B5,D2:D5", "{out}");
|
||||
let out = s.execute("edit.goTo", json!({"reference": "Sheet2!$A$1,Sheet2!B2"})).unwrap();
|
||||
assert_eq!(out["selection"], "A1,B2", "{out}");
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet(), 1);
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet, 1);
|
||||
// Areas on two sheets, and a part that is not a reference, leave the selection alone.
|
||||
for bad in ["A1,Sheet1!B2", "A1,Rate", "A1,", "Total"] {
|
||||
assert!(s.execute("edit.goTo", json!({"reference": bad})).is_err(), "{bad}");
|
||||
@@ -2030,7 +2035,7 @@ mod tests {
|
||||
s.execute("selection.set", json!({"sheet": 1})).unwrap();
|
||||
let out = s.execute("edit.goTo", json!({"reference": "Sheet1!B14:C22,Sheet1!F19:G30", "record": true})).unwrap();
|
||||
assert_eq!(out["selection"], "B14:C22,F19:G30", "{out}");
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet(), 0);
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet, 0);
|
||||
for i in 0..GO_TO_RECENT + 2 {
|
||||
s.execute("edit.goTo", json!({"reference": format!("A{}", i + 1), "record": true})).unwrap();
|
||||
}
|
||||
|
||||
@@ -141,27 +141,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!(noundo "view.customViews", "Custom Views…", ["View", "Workbook Views"], None, "{save?: name, show?: name, delete?: name} → list", has_doc, custom_views),
|
||||
cmd!(noundo "view.split", "Split", ["View", "Window"], None, "{} (toggles a split at the active cell; shown as frozen panes in this version)", has_doc, split),
|
||||
cmd!(noundo "view.newWindow", "New Window", ["View", "Window"], None, "{} → {window, doc, title}: opens another window on the active workbook (the same workbook: saving from either window saves it)", has_doc, new_window),
|
||||
cmd!(
|
||||
noundo "view.arrangeAll",
|
||||
"Arrange All",
|
||||
["View", "Window"],
|
||||
None,
|
||||
"{arrange?: tiled|horizontal|vertical|cascade, activeWorkbook?: bool} → {arrange, windows}: lays out the visible windows (tiled by default; `activeWorkbook` only the active workbook's), the active window first",
|
||||
has_doc,
|
||||
arrange_all
|
||||
),
|
||||
cmd!(noundo "view.hideWindow", "Hide", ["View", "Window"], None, "{window?, doc?} (the active window by default)", has_doc, hide_window),
|
||||
cmd!(noundo "view.unhideWindow", "Unhide…", ["View", "Window"], None, "{window?, doc?, index?} (the most recently hidden window by default)", has_doc, unhide_window),
|
||||
cmd!(
|
||||
noundo "view.switchWindows",
|
||||
"Switch Windows",
|
||||
["View", "Window"],
|
||||
None,
|
||||
"{window?, doc?} → open windows [{window, doc, index, title, dirty, active, hidden}]; with `window` (an id from the list), or `doc` (a workbook id: its most recent window), shows and activates that window first",
|
||||
always,
|
||||
switch_windows
|
||||
),
|
||||
cmd!(noundo "view.newWindow", "New Window", ["View", "Window"], None, "{} opens a second window on the same workbook (a linked copy)", has_doc, new_window),
|
||||
cmd!(noundo "view.arrangeAll", "Arrange All", ["View", "Window"], None, "{}", has_doc, |_, _| ok()),
|
||||
cmd!(noundo "view.hideWindow", "Hide", ["View", "Window"], None, "{}", has_doc, hide_window),
|
||||
cmd!(noundo "view.unhideWindow", "Unhide…", ["View", "Window"], None, "{index?}", has_doc, unhide_window),
|
||||
cmd!(query "view.switchWindows", "Switch Windows", ["View", "Window"], None, "{} → open windows", always, switch_windows),
|
||||
cmd!(noundo "view.ruler", "Ruler", ["View", "Show"], None, "{on?} → {on}: rulers in Page Layout view (an application option)", has_doc, ruler),
|
||||
cmd!(query "view.macros", "Macros", ["View", "Macros"], None, "{} → scripts", has_doc, all_scripts),
|
||||
// Table tools
|
||||
@@ -310,7 +294,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
fn find_chart(s: &Session, p: &Json) -> Result<(usize, usize)> {
|
||||
let d = s.doc()?;
|
||||
let si = d.wb.active_sheet();
|
||||
let si = d.wb.active_sheet;
|
||||
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
let idx = match u32_param(p, "chart") {
|
||||
Some(id) => sh.charts.iter().position(|c| c.id == id),
|
||||
@@ -476,7 +460,7 @@ fn select_data(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (sheet_name, body) = split_sheet(range);
|
||||
let src_si = match sheet_name {
|
||||
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
|
||||
None => d.wb.active_sheet(),
|
||||
None => d.wb.active_sheet,
|
||||
};
|
||||
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "not a range"))?;
|
||||
if r.count() > 1_000_000 {
|
||||
@@ -498,7 +482,7 @@ fn select_data(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (sheet_name, body) = split_sheet(t);
|
||||
let si = match sheet_name {
|
||||
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad("chart.selectData", "no such sheet"))?,
|
||||
None => d.wb.active_sheet(),
|
||||
None => d.wb.active_sheet,
|
||||
};
|
||||
let r = RangeRef::parse(body).ok_or_else(|| bad("chart.selectData", "`categories` is not a range"))?;
|
||||
let name = d.wb.sheet(si).map(|sh| sh.name.clone()).ok_or(EngineError::NoDocument)?;
|
||||
@@ -580,7 +564,7 @@ fn shape_outline(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn with_shape(s: &mut Session, p: &Json, f: impl FnOnce(&mut Shape)) -> Result<Json> {
|
||||
let si = s.doc()?.wb.active_sheet();
|
||||
let si = s.doc()?.wb.active_sheet;
|
||||
let id = u32_param(p, "id");
|
||||
edit(s, |cx| {
|
||||
let shapes = &mut cx.sheet_mut(si)?.shapes;
|
||||
@@ -598,7 +582,7 @@ fn arrange(s: &mut Session, p: &Json, forward: bool) -> Result<Json> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad("arrange", "missing `id`"))?;
|
||||
let kind = str_param(p, "kind").unwrap_or("shape").to_string();
|
||||
let extreme = bool_param(p, "toFront").or(bool_param(p, "toBack")).unwrap_or(false);
|
||||
let si = s.doc()?.wb.active_sheet();
|
||||
let si = s.doc()?.wb.active_sheet;
|
||||
fn reorder<T>(v: &mut Vec<T>, i: usize, forward: bool, extreme: bool) {
|
||||
if i >= v.len() {
|
||||
return;
|
||||
@@ -664,7 +648,7 @@ fn align(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let ids: Vec<u32> =
|
||||
p.get("ids").and_then(Json::as_array).map(|a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect()).unwrap_or_default();
|
||||
let how = str_param(p, "align").unwrap_or("left").to_string();
|
||||
let si = s.doc()?.wb.active_sheet();
|
||||
let si = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
let sheet = cx.sheet_mut(si)?;
|
||||
let geo: Vec<(u32, f64, f64, f32, f32)> = {
|
||||
@@ -777,7 +761,7 @@ fn custom_views(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let mut views = stash_map(&d.wb, VIEWS_NAME);
|
||||
if let Some(name) = str_param(p, "save") {
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
views[name] = json!({"sheet": d.wb.active_sheet(), "selection": d.selection.a1(), "zoom": sh.zoom, "freeze": sh.freeze});
|
||||
views[name] = json!({"sheet": d.wb.active_sheet, "selection": d.selection.a1(), "zoom": sh.zoom, "freeze": sh.freeze});
|
||||
let v = views.clone();
|
||||
edit(s, |cx| {
|
||||
stash_set(&mut cx.wb, VIEWS_NAME, &v);
|
||||
@@ -824,71 +808,47 @@ fn split(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn new_window(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
let id = s.new_window()?;
|
||||
let doc = s.window(id).map(|w| w.doc_uid);
|
||||
Ok(json!({"window": id, "doc": doc, "title": s.window_title(id)}))
|
||||
let d = s.doc()?.clone();
|
||||
let mut copy = crate::DocState::new((*d.wb).clone(), d.path.clone(), format!("{}:2", d.display_title()), d.trust);
|
||||
copy.selection = d.selection.clone();
|
||||
copy.scripts_trusted = d.scripts_trusted;
|
||||
let i = s.add_document(copy);
|
||||
Ok(json!({"index": i}))
|
||||
}
|
||||
|
||||
/// The window a window command names: `window` (an id), else `doc` (a workbook id: its most
|
||||
/// recent window), else the active window.
|
||||
pub(crate) fn window_param(s: &Session, cmd: &str, p: &Json) -> Result<u64> {
|
||||
let t = crate::Target::from_json(p).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
s.target_window(t).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
/// View › Arrange All. The engine has no window geometry: it picks the windows and the layout,
|
||||
/// and the interface moves its native windows ([`Session::window_list`] order, active first).
|
||||
fn arrange_all(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let arrange = match str_param(p, "arrange").unwrap_or("tiled") {
|
||||
a @ ("tiled" | "horizontal" | "vertical" | "cascade") => a,
|
||||
other => return Err(bad("view.arrangeAll", format!("`arrange` must be tiled, horizontal, vertical or cascade, not `{other}`"))),
|
||||
};
|
||||
let active = s.active_window();
|
||||
let doc = active.and_then(|w| s.window(w)).map(|w| w.doc_uid);
|
||||
let only_active = p.get("activeWorkbook").and_then(Json::as_bool).unwrap_or(false);
|
||||
let mut windows: Vec<u64> = s.windows().iter().filter(|w| !w.hidden && (!only_active || Some(w.doc_uid) == doc)).map(|w| w.id).collect();
|
||||
if let Some(at) = windows.iter().position(|w| Some(*w) == active)
|
||||
&& let Some(first) = windows.get_mut(..=at)
|
||||
{
|
||||
first.rotate_right(1);
|
||||
fn hide_window(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
s.hidden_windows.push(s.active_index());
|
||||
let n = s.documents().len();
|
||||
if n > 1 {
|
||||
let next = (0..n).find(|i| !s.hidden_windows.contains(i)).unwrap_or(0);
|
||||
s.set_active(next);
|
||||
}
|
||||
Ok(json!({"arrange": arrange, "windows": windows}))
|
||||
}
|
||||
|
||||
fn hide_window(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = window_param(s, "view.hideWindow", p)?;
|
||||
s.hide_window(id);
|
||||
ok()
|
||||
}
|
||||
|
||||
fn unhide_window(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = if p.get("window").is_some_and(|v| !v.is_null()) || p.get("doc").is_some_and(|v| !v.is_null()) {
|
||||
Some(window_param(s, "view.unhideWindow", p)?)
|
||||
} else if let Some(i) = u32_param(p, "index") {
|
||||
// A workbook's position in the document list.
|
||||
let uid = s.documents().get(i as usize).map(|d| d.uid).ok_or_else(|| bad("view.unhideWindow", "no such window"))?;
|
||||
s.windows().iter().filter(|w| w.doc_uid == uid && w.hidden).map(|w| w.id).next_back().or_else(|| s.doc_window(uid))
|
||||
} else {
|
||||
s.last_hidden_window()
|
||||
};
|
||||
if let Some(id) = id {
|
||||
s.unhide_window(id);
|
||||
let i = u32_param(p, "index").map(|v| v as usize).or_else(|| s.hidden_windows.last().copied());
|
||||
if let Some(i) = i {
|
||||
s.hidden_windows.retain(|x| *x != i);
|
||||
s.set_active(i);
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
fn switch_windows(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if p.get("window").is_some_and(|v| !v.is_null()) || p.get("doc").is_some_and(|v| !v.is_null()) {
|
||||
let id = window_param(s, "view.switchWindows", p)?;
|
||||
s.unhide_window(id);
|
||||
}
|
||||
Ok(s.window_list())
|
||||
fn switch_windows(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
Ok(Json::Array(
|
||||
s.documents()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, d)| json!({"index": i, "title": d.display_title(), "active": i == s.active_index(), "hidden": s.hidden_windows.contains(&i)}))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?;
|
||||
let d = s.doc()?;
|
||||
let si = d.wb.active_sheet();
|
||||
let si = d.wb.active_sheet;
|
||||
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
let ti = match str_param(p, "table") {
|
||||
Some(n) => sh.tables.iter().position(|t| t.name.eq_ignore_ascii_case(n)),
|
||||
@@ -997,7 +957,7 @@ fn from_table_range(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let r = if r.is_single() { crate::selection::current_region(sh, r.start) } else { r };
|
||||
let text = crate::display::range_text(&d.wb, d.wb.active_sheet(), r);
|
||||
let text = crate::display::range_text(&d.wb, d.wb.active_sheet, r);
|
||||
from_csv(s, &json!({"text": text, "delimiter": "\t", "sheet": format!("{} (2)", sh.name).chars().take(31).collect::<String>()}))
|
||||
}
|
||||
|
||||
@@ -1076,7 +1036,7 @@ fn denied_script_step(id: &str, params: &Json) -> Option<String> {
|
||||
}
|
||||
// Scripts are scoped to their workbook: a step that switches the active window would
|
||||
// point every later step at another open document, so those are refused too.
|
||||
if id.starts_with("window.") || matches!(id, "view.switchWindows" | "view.newWindow" | "view.hideWindow" | "view.unhideWindow") {
|
||||
if id.starts_with("window.") {
|
||||
return Some(format!("scripts can't run `{id}`: it reaches outside the workbook"));
|
||||
}
|
||||
if params.get("path").is_some() {
|
||||
@@ -1247,7 +1207,7 @@ fn theme_fonts(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn background(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if bool_param(p, "clear").unwrap_or(false) {
|
||||
let si = s.doc()?.wb.active_sheet();
|
||||
let si = s.doc()?.wb.active_sheet;
|
||||
return edit(s, |cx| {
|
||||
cx.sheet_mut(si)?.images.retain(|i| i.alt != "Sheet background");
|
||||
Ok(Json::Null)
|
||||
@@ -1340,7 +1300,7 @@ fn watch_window(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let (sheet, body) = split_sheet(w);
|
||||
let si = sheet.and_then(|n| d.wb.sheet_index(&n)).unwrap_or(d.wb.active_sheet());
|
||||
let si = sheet.and_then(|n| d.wb.sheet_index(&n)).unwrap_or(d.wb.active_sheet);
|
||||
let c = CellRef::parse(body).unwrap_or_default();
|
||||
let sh = d.wb.sheet(si);
|
||||
json!({"cell": w, "value": sh.map(|s| s.value(c).display()), "formula": sh.and_then(|s| s.cell(c)).and_then(|x| x.formula.as_ref()).map(|f| format!("={}", f.text))})
|
||||
|
||||
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save),
|
||||
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as),
|
||||
cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes),
|
||||
cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{force?: bool, document?: bool} (closes the active window, or with `document` the workbook and all its windows; the workbook closes with its last window)", has_doc, close),
|
||||
cmd!(noundo "file.close", "Close", ["File"], Some("Cmd+W"), "{force?: bool}", has_doc, close),
|
||||
cmd!(noundo "file.exportCsv", "Export as CSV", ["File", "Export"], None, "{path, sheet?}", has_doc, |s, p| export(s, p, "csv")),
|
||||
cmd!(noundo "file.exportHtml", "Save as Web Page", ["File", "Export"], None, "{path}", has_doc, |s, p| export(s, p, "html")),
|
||||
cmd!("file.properties", "Properties", ["File"], None, "{title?, subject?, author?, company?, keywords?, description?}", has_doc, properties),
|
||||
@@ -25,9 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
options
|
||||
),
|
||||
cmd!(noundo "window.activate", "Switch Window", ["Window"], None, "{window} | {doc} | {index} (a window id, a workbook id, or the workbook's position in the list)", has_doc, activate_window),
|
||||
cmd!(noundo "window.close", "Close Window", ["Window"], None, "{window?, doc?, force?: bool} → {closed, document}: closes a window (the active one by default); its workbook closes with its last window, asking first when it has unsaved changes unless `force`", has_doc, close_window),
|
||||
cmd!(query "window.list", "Windows", ["Window"], None, "{} → [{window, doc, index, title, dirty, active, hidden}]", always, |s, _| Ok(s.window_list())),
|
||||
cmd!(noundo "window.activate", "Switch Window", ["Window"], None, "{index}", has_doc, activate_window),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -162,16 +160,7 @@ fn save_bytes(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Ok(json!({"name": name, "base64": crate::io::base64_encode(&bytes), "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
/// File › Close closes the active window; the workbook closes with its last window.
|
||||
fn close(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if !bool_param(p, "document").unwrap_or(false)
|
||||
&& let Some(id) = s.active_window()
|
||||
&& let Some(doc) = s.window(id).map(|w| w.doc_uid)
|
||||
&& s.windows().iter().filter(|w| w.doc_uid == doc).count() > 1
|
||||
{
|
||||
s.close_window(id);
|
||||
return Ok(json!({"closed": true, "document": false}));
|
||||
}
|
||||
let force = bool_param(p, "force").unwrap_or(false);
|
||||
let d = s.doc()?;
|
||||
if d.is_dirty() && !force {
|
||||
@@ -186,9 +175,9 @@ fn close(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn export(s: &mut Session, p: &Json, ext: &str) -> Result<Json> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("file.export", "missing `path`"))?.to_string();
|
||||
let d = s.doc()?;
|
||||
let wb = (*d.wb).clone();
|
||||
let mut wb = (*d.wb).clone();
|
||||
if p.get("sheet").is_some() {
|
||||
wb.set_active_sheet(target_sheet(s, p)?);
|
||||
wb.active_sheet = target_sheet(s, p)?;
|
||||
}
|
||||
let target = if path.ends_with(&format!(".{ext}")) { path.clone() } else { format!("{path}.{ext}") };
|
||||
let bytes = crate::io::save_bytes(&wb, &target)?;
|
||||
@@ -232,35 +221,10 @@ fn options(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn activate_window(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = match u32_param(p, "index").filter(|_| p.get("window").is_none_or(Json::is_null) && p.get("doc").is_none_or(Json::is_null)) {
|
||||
Some(i) => {
|
||||
let uid = s.documents().get(i as usize).map(|d| d.uid).ok_or_else(|| bad("window.activate", "no such window"))?;
|
||||
s.doc_window(uid).ok_or_else(|| bad("window.activate", "no such window"))?
|
||||
}
|
||||
None if p.get("window").is_none_or(Json::is_null) && p.get("doc").is_none_or(Json::is_null) => {
|
||||
return Err(bad("window.activate", "missing `window`"));
|
||||
}
|
||||
None => super::extra::window_param(s, "window.activate", p)?,
|
||||
};
|
||||
s.unhide_window(id);
|
||||
let i = u32_param(p, "index").ok_or_else(|| bad("window.activate", "missing `index`"))? as usize;
|
||||
if i >= s.documents().len() {
|
||||
return Err(bad("window.activate", "no such window"));
|
||||
}
|
||||
s.set_active(i);
|
||||
ok()
|
||||
}
|
||||
|
||||
fn close_window(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = super::extra::window_param(s, "window.close", p)?;
|
||||
let doc = s.window(id).map(|w| w.doc_uid).unwrap_or_default();
|
||||
if s.windows().iter().filter(|w| w.doc_uid == doc).count() > 1 {
|
||||
s.close_window(id);
|
||||
return Ok(json!({"closed": true, "document": false}));
|
||||
}
|
||||
let force = bool_param(p, "force").unwrap_or(false);
|
||||
let d = s.documents().iter().find(|d| d.uid == doc).ok_or(crate::EngineError::NoDocument)?;
|
||||
if d.is_dirty() && !force {
|
||||
let title = d.display_title();
|
||||
s.activate_window(id);
|
||||
s.ui_requests.push(crate::UiRequest::Dialog("saveChanges".into(), json!({"title": title})));
|
||||
return Ok(json!({"closed": false, "dirty": true}));
|
||||
}
|
||||
s.close_window(id);
|
||||
Ok(json!({"closed": true, "document": true}))
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ fn range_on(s: &Session, t: &str) -> Result<(usize, RangeRef)> {
|
||||
let (sh, body) = split_sheet(t);
|
||||
let si = match sh {
|
||||
Some(n) => d.wb.sheet_index(&n).ok_or_else(|| bad(CMD, format!("no sheet named `{n}`")))?,
|
||||
None => d.wb.active_sheet(),
|
||||
None => d.wb.active_sheet,
|
||||
};
|
||||
let r = RangeRef::parse(body.trim()).ok_or_else(|| bad(CMD, format!("not a range: `{t}`")))?;
|
||||
let r = if r.is_full_cols() || r.is_full_rows() {
|
||||
@@ -101,7 +101,7 @@ fn source(s: &Session, p: &Json) -> Result<(usize, Vec<CellRef>, Vec<CellRef>)>
|
||||
None => {
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let sel = d.selection.current();
|
||||
(d.wb.active_sheet(), if sel.is_single() { current_region(sh, d.selection.active) } else { sel })
|
||||
(d.wb.active_sheet, if sel.is_single() { current_region(sh, d.selection.active) } else { sel })
|
||||
}
|
||||
};
|
||||
if r.width() < 2 {
|
||||
@@ -307,7 +307,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let stats_col = width + 1;
|
||||
let chart_col = if opts.statistics { stats_col + 3 } else { width + 1 };
|
||||
|
||||
let at = s.doc()?.wb.active_sheet();
|
||||
let at = s.doc()?.wb.active_sheet;
|
||||
let index = edit(s, |cx| {
|
||||
let at = at.min(cx.wb.sheets.len());
|
||||
let bold = cx.wb.styles.derive(StyleId::DEFAULT, |st| st.font.bold = true);
|
||||
@@ -440,7 +440,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
*sc += 1;
|
||||
}
|
||||
}
|
||||
cx.wb.set_active_sheet(at);
|
||||
cx.wb.active_sheet = at;
|
||||
*cx.sel = crate::Selection::at(CellRef::new(0, 0));
|
||||
cx.structural = true;
|
||||
Ok(at)
|
||||
@@ -502,7 +502,7 @@ mod tests {
|
||||
assert_eq!(r["periods"], 4);
|
||||
let wb = &s.doc().unwrap().wb;
|
||||
// Inserted before the data sheet and activated.
|
||||
assert_eq!(wb.active_sheet(), 0);
|
||||
assert_eq!(wb.active_sheet, 0);
|
||||
let sh = wb.sheet(0).unwrap();
|
||||
assert_eq!(sh.name, r["sheet"].as_str().unwrap());
|
||||
assert_eq!(value(&s, 0, "C1"), Value::text("Forecast(Sales)"));
|
||||
|
||||
@@ -1027,7 +1027,7 @@ fn line_targets(s: &Session, p: &Json, rows: bool) -> Result<(usize, Vec<(u32, u
|
||||
return Ok((sheet, lines));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
if sheet != d.wb.active_sheet() {
|
||||
if sheet != d.wb.active_sheet {
|
||||
return Err(bad(key, format!("missing `{key}`: the selection is on the active sheet")));
|
||||
}
|
||||
Ok((sheet, d.selection.ranges.iter().map(|r| if rows { (r.start.row, r.end.row) } else { (r.start.col, r.end.col) }).collect()))
|
||||
|
||||
@@ -197,7 +197,7 @@ fn auto_sum(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
};
|
||||
if !sel.is_single() {
|
||||
let Some(writes) = selection_totals(sh, sel, &func)? else { return ok() };
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
for (c, f) in &writes {
|
||||
let cell = super::edit::input_to_cell(f, sheet, *c, &mut cx.wb)?.unwrap_or_default();
|
||||
@@ -498,7 +498,7 @@ fn name_manager(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
.iter()
|
||||
.filter(|n| !n.hidden)
|
||||
.map(|n| {
|
||||
let sheet = n.scope.unwrap_or(d.wb.active_sheet());
|
||||
let sheet = n.scope.unwrap_or(d.wb.active_sheet);
|
||||
// parse_name, not evaluate's parse: a name's top-level commas are unions.
|
||||
let v = gridcraft_formula::parse_name(&n.formula)
|
||||
.map_or(Value::Error(CellError::Name), |e| gridcraft_calc::recalc::evaluate_expr(&d.wb, sheet, CellRef::default(), &e));
|
||||
@@ -580,7 +580,7 @@ fn create_from_selection(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
/// active sheet's own, without hidden names, in alphabetical order. A sheet's name hides the
|
||||
/// workbook name it shares.
|
||||
pub fn pasteable_names(wb: &Workbook) -> Vec<(String, String)> {
|
||||
let sheet = wb.active_sheet();
|
||||
let sheet = wb.active_sheet;
|
||||
let shown = |local: bool| wb.names.iter().filter(move |n| !n.hidden && n.scope.is_some() == local && n.scope.is_none_or(|i| i == sheet));
|
||||
let local: std::collections::HashSet<String> = shown(true).map(|n| gridcraft_formula::fold_name(&n.name)).collect();
|
||||
let mut out: Vec<(String, String)> = shown(true).map(|n| (n.name.clone(), format!("={}", n.formula))).collect();
|
||||
@@ -614,7 +614,7 @@ fn paste_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if at.row.saturating_add(rows) > gridcraft_core::MAX_ROWS || at.col.saturating_add(2) > gridcraft_core::MAX_COLS {
|
||||
return Err(EngineError::Other("There isn't room on the sheet for the list of names.".into()));
|
||||
}
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let range = RangeRef::new(at, CellRef::new(at.row + rows - 1, at.col + 1));
|
||||
edit(s, |cx| {
|
||||
for (row, (name, refers)) in (at.row..).zip(&names) {
|
||||
@@ -634,7 +634,7 @@ fn paste_name(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn trace_precedents(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let areas = d.calc.graph.precedents_of((d.wb.active_sheet(), at));
|
||||
let areas = d.calc.graph.precedents_of((d.wb.active_sheet, at));
|
||||
let v: Vec<Json> = areas.iter().map(|a| json!({"sheet": d.wb.sheet(a.sheet).map(|s| s.name.clone()), "range": a.range.a1()})).collect();
|
||||
Ok(Json::Array(v))
|
||||
}
|
||||
@@ -643,7 +643,7 @@ fn trace_dependents(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let mut deps = Vec::new();
|
||||
d.calc.graph.dependents(d.wb.active_sheet(), at, &mut deps);
|
||||
d.calc.graph.dependents(d.wb.active_sheet, at, &mut deps);
|
||||
deps.sort();
|
||||
deps.dedup();
|
||||
let v: Vec<Json> = deps.iter().map(|(si, c)| json!({"sheet": d.wb.sheet(*si).map(|s| s.name.clone()), "cell": c.a1()})).collect();
|
||||
@@ -656,7 +656,7 @@ fn select_trace_cells(s: &mut Session, p: &Json, precedents: bool) -> Result<Jso
|
||||
use std::collections::BTreeSet;
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let all = bool_param(p, "all").unwrap_or(false);
|
||||
// (sheet, a1) pairs to select; direct level keeps whole precedent ranges, transitive cells.
|
||||
let mut found: BTreeSet<(usize, String)> = BTreeSet::new();
|
||||
@@ -727,7 +727,7 @@ fn select_dependents(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
fn show_formulas(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
let cur = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.show_formulas);
|
||||
let on = bool_param(p, "on").unwrap_or(!cur);
|
||||
edit(s, |cx| {
|
||||
@@ -797,7 +797,7 @@ fn error_checking(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
fn evaluate_formula(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let text = match str_param(p, "formula") {
|
||||
Some(f) => f.trim_start_matches('=').to_string(),
|
||||
None => {
|
||||
@@ -836,7 +836,7 @@ fn evaluate(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let expr = crate::cmd::edit::parse_typed_formula(f.strip_prefix('=').unwrap_or(f))?;
|
||||
crate::cmd::edit::check_arg_counts(&expr)?;
|
||||
let v = gridcraft_calc::recalc::evaluate_expr(&d.wb, d.wb.active_sheet(), at, &expr);
|
||||
let v = gridcraft_calc::recalc::evaluate_expr(&d.wb, d.wb.active_sheet, at, &expr);
|
||||
Ok(crate::cmd::inspect::value_json(&v))
|
||||
}
|
||||
|
||||
|
||||
@@ -371,7 +371,7 @@ fn find_table(s: &Session, p: &Json) -> Result<(usize, usize)> {
|
||||
if let Some(n) = str_param(p, "table") {
|
||||
return d.wb.table(n).ok_or_else(|| bad("table", format!("no table named `{n}`")));
|
||||
}
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
let ti = sh
|
||||
.tables
|
||||
@@ -835,7 +835,7 @@ fn insert_chart(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn find_chart(s: &Session, p: &Json) -> Result<(usize, usize)> {
|
||||
let d = s.doc()?;
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
let idx = match u32_param(p, "chart") {
|
||||
Some(id) => sh.charts.iter().position(|c| c.id == id),
|
||||
@@ -984,7 +984,7 @@ fn insert_sparkline(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
_ => SparklineKind::Line,
|
||||
};
|
||||
let markers = bool_param(p, "markers").unwrap_or(false);
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
sh.sparklines.retain(|x| x.cell != loc);
|
||||
@@ -1009,7 +1009,7 @@ fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if placement == "cell" {
|
||||
let mime = validate_cell_picture(&data)?;
|
||||
let d = s.doc()?;
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let at = match str_param(p, "at") {
|
||||
Some(a) => CellRef::parse(a).ok_or_else(|| bad("insert.picture", "invalid cell address"))?,
|
||||
@@ -1053,7 +1053,7 @@ fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
mime,
|
||||
alt: str_param(p, "alt").unwrap_or("").into(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.images.push(img);
|
||||
Ok(json!({"image": id}))
|
||||
@@ -1123,7 +1123,7 @@ fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
text: str_param(p, "text").unwrap_or("").into(),
|
||||
format: Default::default(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.shapes.push(shape);
|
||||
Ok(json!({"shape": id}))
|
||||
@@ -1141,7 +1141,7 @@ fn shape_set_text(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(bad("shape.setText", "`text` is longer than 32,767 characters"));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
let sh = d.wb.active().ok_or_else(|| bad("shape.setText", "no such text box"))?;
|
||||
let shape = sh.shapes.iter().find(|shape| shape.id == id).ok_or_else(|| bad("shape.setText", "no such text box"))?;
|
||||
if shape.kind != ShapeKind::TextBox {
|
||||
@@ -1164,7 +1164,7 @@ fn shape_set_text(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad("object.delete", "missing `id`"))?;
|
||||
let kind = str_param(p, "kind").unwrap_or("").to_string();
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
match kind.as_str() {
|
||||
@@ -1180,7 +1180,7 @@ fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad("object.move", "missing `id`"))?;
|
||||
let kind = str_param(p, "kind").unwrap_or("").to_string();
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
let at = cell_param(s, p, "at")?;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
@@ -1221,7 +1221,7 @@ fn set_anchor_mode(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(bad("object.setAnchorMode", "kind must be chart, image or shape"));
|
||||
}
|
||||
let mode = anchor_mode_param(p).ok_or_else(|| bad("object.setAnchorMode", "mode must be moveAndSize, moveOnly or absolute"))?;
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let anchor = match kind.as_str() {
|
||||
@@ -1730,7 +1730,7 @@ fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
text: name,
|
||||
format: Default::default(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.shapes.push(shape);
|
||||
Ok(json!({"shape": id}))
|
||||
|
||||
@@ -64,7 +64,7 @@ fn inspect(s: &mut Session, _: &Json) -> Result<Json> {
|
||||
"path": d.path,
|
||||
"dirty": d.is_dirty(),
|
||||
"trust": d.trust,
|
||||
"activeSheet": wb.active_sheet(),
|
||||
"activeSheet": wb.active_sheet,
|
||||
"sheets": sheets,
|
||||
"selection": d.selection.a1(),
|
||||
"activeCell": d.selection.active.a1(),
|
||||
|
||||
@@ -296,7 +296,7 @@ pub(crate) fn target_sheet(s: &Session, p: &Json) -> Result<usize> {
|
||||
{
|
||||
return d.wb.sheet_index(&sh).ok_or_else(|| bad("range", format!("no sheet named `{sh}`")));
|
||||
}
|
||||
Ok(d.wb.active_sheet())
|
||||
Ok(d.wb.active_sheet)
|
||||
}
|
||||
|
||||
pub(crate) use gridcraft_core::split_sheet;
|
||||
@@ -305,7 +305,7 @@ pub(crate) use gridcraft_core::split_sheet;
|
||||
/// a cell reference, or that names a sheet other than the active one, is an error rather than a
|
||||
/// silent fallback to some other cell.
|
||||
pub(crate) fn cell_param(s: &Session, p: &Json, key: &str) -> Result<Option<CellRef>> {
|
||||
cell_param_on(s, p, key, s.doc()?.wb.active_sheet())
|
||||
cell_param_on(s, p, key, s.doc()?.wb.active_sheet)
|
||||
}
|
||||
|
||||
/// Like [`cell_param`], for a command that operates on `sheet` (a `Sheet!` prefix must name it).
|
||||
@@ -593,7 +593,7 @@ pub fn auto_row_height(wb: &mut Workbook, si: usize, row: u32) {
|
||||
|
||||
impl Ctx<'_> {
|
||||
pub fn sheet_index(&self) -> usize {
|
||||
self.wb.active_sheet()
|
||||
self.wb.active_sheet
|
||||
}
|
||||
pub fn sheet_mut(&mut self, i: usize) -> Result<&mut gridcraft_model::Sheet> {
|
||||
self.wb.sheet_mut(i).ok_or_else(|| EngineError::Other("no such sheet".into()))
|
||||
|
||||
@@ -224,7 +224,7 @@ fn other(msg: impl Into<String>) -> EngineError {
|
||||
/// (sheet, index) of the pivot a call targets.
|
||||
fn find_pivot(s: &Session, p: &Json) -> Result<(usize, usize)> {
|
||||
let d = s.doc()?;
|
||||
let active = d.wb.active_sheet();
|
||||
let active = d.wb.active_sheet;
|
||||
if let Some(v) = p.get("pivot").filter(|v| !v.is_null()) {
|
||||
let mut order: Vec<usize> = vec![active];
|
||||
order.extend((0..d.wb.sheets.len()).filter(|i| *i != active));
|
||||
@@ -634,7 +634,7 @@ fn insert_pivot(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
return Err(other("The workbook is protected and cannot be changed."));
|
||||
}
|
||||
let source = source_param(s, p)?;
|
||||
let active = s.doc()?.wb.active_sheet();
|
||||
let active = s.doc()?.wb.active_sheet;
|
||||
// Validate the source now (header names, size).
|
||||
let src = pv::read_source(&s.doc()?.wb, &source, active).map_err(other)?;
|
||||
let name = match str_param(p, "name") {
|
||||
@@ -713,7 +713,7 @@ fn insert_pivot(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
sh.pivots.push(pt);
|
||||
let pi = sh.pivots.len() - 1;
|
||||
let area = pv::refresh(&mut cx.wb, si, pi, replace).map_err(other)?;
|
||||
cx.wb.set_active_sheet(si);
|
||||
cx.wb.active_sheet = si;
|
||||
*cx.sel = crate::Selection::at(anchor);
|
||||
cx.structural = true;
|
||||
let sheet_name = cx.wb.sheet(si).map(|s| s.name.clone()).unwrap_or_default();
|
||||
@@ -738,7 +738,7 @@ fn insert_pivot(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
/// Inserts a new, empty sheet before the active one (Excel's place for a new PivotTable or a
|
||||
/// Show Details sheet); returns its index.
|
||||
fn insert_sheet_before_active(cx: &mut Ctx) -> usize {
|
||||
let at = cx.wb.active_sheet().min(cx.wb.sheets.len());
|
||||
let at = cx.wb.active_sheet.min(cx.wb.sheets.len());
|
||||
let nm = cx.wb.next_sheet_name();
|
||||
cx.wb.sheets.insert(at, Arc::new(Sheet::new(nm)));
|
||||
for n in cx.wb.names.iter_mut() {
|
||||
@@ -756,7 +756,7 @@ fn insert_sheet_before_active(cx: &mut Ctx) -> usize {
|
||||
fn show_details(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let at = cell_param(s, p, "cell")?.unwrap_or(d.selection.active);
|
||||
let active = d.wb.active_sheet();
|
||||
let active = d.wb.active_sheet;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let pt = sh
|
||||
.pivots
|
||||
@@ -825,7 +825,7 @@ fn show_details(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
let name = sh.name.clone();
|
||||
cx.wb.set_active_sheet(si);
|
||||
cx.wb.active_sheet = si;
|
||||
*cx.sel = crate::Selection::at(CellRef::new(0, 0));
|
||||
cx.structural = true;
|
||||
Ok(json!({"sheet": name, "records": count}))
|
||||
@@ -1534,7 +1534,7 @@ fn chart_pivot(s: &Session, p: &Json) -> Result<(usize, usize)> {
|
||||
let sh = gridcraft_core::unquote_sheet(sh);
|
||||
(d.wb.sheet_index(&sh), a)
|
||||
}
|
||||
None => (Some(d.wb.active_sheet()), t),
|
||||
None => (Some(d.wb.active_sheet), t),
|
||||
};
|
||||
if let (Some(si), Some(c)) = (sheet, CellRef::parse(addr.trim().replace('$', "").as_str())) {
|
||||
let hit = d.wb.sheet(si).and_then(|sh| sh.pivots.iter().position(|pt| pt.last_range.is_some_and(|r| r.contains(c)) || pt.anchor == c));
|
||||
@@ -1668,7 +1668,7 @@ fn suggestions(wb: &Workbook, src: &pv::Source) -> Vec<Json> {
|
||||
|
||||
fn recommended(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let source = source_param(s, p)?;
|
||||
let active = s.doc()?.wb.active_sheet();
|
||||
let active = s.doc()?.wb.active_sheet;
|
||||
let src = pv::read_source(&s.doc()?.wb, &source, active).map_err(other)?;
|
||||
let list = suggestions(&s.doc()?.wb, &src);
|
||||
let Some(apply) = p.get("apply").and_then(Json::as_u64) else {
|
||||
@@ -1751,7 +1751,7 @@ mod tests {
|
||||
assert_eq!(r["fields"], json!(["Region", "Product", "Date", "Units", "Sales"]));
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.wb.sheets.len(), 2);
|
||||
assert_eq!(d.wb.active_sheet(), 0, "new sheet goes before the current one");
|
||||
assert_eq!(d.wb.active_sheet, 0, "new sheet goes before the current one");
|
||||
assert_eq!(d.wb.active().unwrap().name, "Sheet2");
|
||||
assert!(text(&s, "A3").starts_with("PivotTable1"));
|
||||
assert_eq!(pt(&s).source, "Sheet1!$A$1:$E$13");
|
||||
@@ -2132,7 +2132,7 @@ mod tests {
|
||||
}
|
||||
fn plotted(s: &Session) -> Vec<Vec<Option<f64>>> {
|
||||
let d = s.doc().unwrap();
|
||||
let data = gridcraft_chart::resolve(&d.wb, d.wb.active_sheet(), &pivot_chart(s));
|
||||
let data = gridcraft_chart::resolve(&d.wb, d.wb.active_sheet, &pivot_chart(s));
|
||||
data.series.into_iter().map(|x| x.values).collect()
|
||||
}
|
||||
|
||||
@@ -2530,7 +2530,7 @@ mod tests {
|
||||
assert_eq!(r["records"], 2);
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.wb.sheets.len(), 3);
|
||||
assert_eq!(d.wb.active_sheet(), 0, "the new sheet goes before the PivotTable's");
|
||||
assert_eq!(d.wb.active_sheet, 0, "the new sheet goes before the PivotTable's");
|
||||
assert_eq!(d.wb.active().unwrap().name, "Sheet3");
|
||||
assert_eq!(
|
||||
sheet_rows(&mut s),
|
||||
@@ -2670,7 +2670,7 @@ mod tests {
|
||||
s.execute("pivot.moveField", json!({"field": "Product", "from": "columns", "to": "rows"})).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
let si = d.wb.active_sheet();
|
||||
let si = d.wb.active_sheet;
|
||||
let pt = &d.wb.active().unwrap().pivots[0];
|
||||
let r = pt.last_range.unwrap();
|
||||
let cells = crate::pivot::detail_cells(&d.wb, pt, si).unwrap();
|
||||
@@ -2688,6 +2688,6 @@ mod tests {
|
||||
s.execute("range.setValues", json!({"range": "Sheet1!A2", "values": [["Central"]]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let pt = &d.wb.active().unwrap().pivots[0];
|
||||
assert!(crate::pivot::detail_cells(&d.wb, pt, d.wb.active_sheet()).unwrap_err().contains("out of date"));
|
||||
assert!(crate::pivot::detail_cells(&d.wb, pt, d.wb.active_sheet).unwrap_err().contains("out of date"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -388,13 +388,13 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
let sheets: Vec<usize> = if opts.all_sheets {
|
||||
(0..wb.sheets.len()).filter(|i| wb.sheet(*i).is_some_and(|s| s.visibility == Visibility::Visible)).collect()
|
||||
} else {
|
||||
vec![wb.active_sheet()]
|
||||
vec![wb.active_sheet]
|
||||
};
|
||||
for si in sheets {
|
||||
if pages >= MAX_PAGES {
|
||||
break;
|
||||
}
|
||||
let ovr = if si == wb.active_sheet() { opts.range } else { None };
|
||||
let ovr = if si == wb.active_sheet { opts.range } else { None };
|
||||
if opts.all_sheets && ovr.is_none() && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) {
|
||||
continue;
|
||||
}
|
||||
@@ -405,7 +405,7 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
|
||||
}
|
||||
}
|
||||
if out.is_empty() && opts.all_sheets {
|
||||
out.extend(layout_sheet(wb, wb.active_sheet(), opts, None));
|
||||
out.extend(layout_sheet(wb, wb.active_sheet, opts, None));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ fn has_comments(s: &Session) -> std::result::Result<(), String> {
|
||||
fn step_comment(s: &mut Session, forward: bool) -> Result<Json> {
|
||||
let list = comment_cells(s);
|
||||
let d = s.doc()?;
|
||||
let here = (d.wb.active_sheet(), d.selection.active);
|
||||
let here = (d.wb.active_sheet, d.selection.active);
|
||||
let target = if forward {
|
||||
list.iter().find(|c| **c > here).or_else(|| list.first())
|
||||
} else {
|
||||
@@ -374,7 +374,7 @@ mod tests {
|
||||
|
||||
fn at(s: &Session) -> (usize, String) {
|
||||
let d = s.doc().unwrap();
|
||||
(d.wb.active_sheet(), d.selection.active.a1())
|
||||
(d.wb.active_sheet, d.selection.active.a1())
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -443,7 +443,7 @@ mod tests {
|
||||
);
|
||||
let prot: SheetProtection = serde_json::from_str(&old).unwrap();
|
||||
assert_eq!((prot.legacy_password_hash, prot.password.is_none()), (Some(password_hash("old")), true));
|
||||
let i = s.doc().unwrap().wb.active_sheet();
|
||||
let i = s.doc().unwrap().wb.active_sheet;
|
||||
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
|
||||
std::sync::Arc::make_mut(&mut wb.sheets[i]).protection = Some(prot);
|
||||
assert!(s.execute("review.unprotectSheet", json!({"password": "new"})).is_err());
|
||||
|
||||
@@ -707,7 +707,7 @@ fn insert_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let before = p.get("before").and_then(Json::as_u64).map(|v| v as usize);
|
||||
let idx = edit_doc(d, |cx| {
|
||||
// Excel inserts before the active sheet; the "+" button appends after it.
|
||||
let at = before.unwrap_or(cx.wb.active_sheet() + 1).min(cx.wb.sheets.len());
|
||||
let at = before.unwrap_or(cx.wb.active_sheet + 1).min(cx.wb.sheets.len());
|
||||
cx.wb.sheets.insert(at, Arc::new(Sheet::new(name.clone())));
|
||||
// Names scoped to later sheets shift.
|
||||
for n in cx.wb.names.iter_mut() {
|
||||
@@ -717,7 +717,7 @@ fn insert_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
*sc += 1;
|
||||
}
|
||||
}
|
||||
cx.wb.set_active_sheet(at);
|
||||
cx.wb.active_sheet = at;
|
||||
*cx.sel = crate::Selection::default();
|
||||
cx.structural = true;
|
||||
Ok(at)
|
||||
@@ -805,8 +805,8 @@ fn delete_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if cx.wb.active_sheet() >= cx.wb.sheets.len() || cx.wb.active_sheet() > i {
|
||||
cx.wb.set_active_sheet(cx.wb.active_sheet().saturating_sub(1).min(cx.wb.sheets.len().saturating_sub(1)));
|
||||
if cx.wb.active_sheet >= cx.wb.sheets.len() || cx.wb.active_sheet > i {
|
||||
cx.wb.active_sheet = cx.wb.active_sheet.saturating_sub(1).min(cx.wb.sheets.len().saturating_sub(1));
|
||||
}
|
||||
*cx.sel = crate::Selection::default();
|
||||
cx.structural = true;
|
||||
@@ -920,12 +920,12 @@ fn move_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
cx.wb.names.extend(copies);
|
||||
cx.wb.sheets.insert(at, Arc::new(sh));
|
||||
cx.wb.set_active_sheet(at);
|
||||
cx.wb.active_sheet = at;
|
||||
} else {
|
||||
let sh = cx.wb.sheets.remove(i);
|
||||
let at = to.min(n - 1);
|
||||
cx.wb.sheets.insert(at, sh);
|
||||
cx.wb.set_active_sheet(at);
|
||||
cx.wb.active_sheet = at;
|
||||
// Sheet-level names follow their sheet.
|
||||
for nm in cx.wb.names.iter_mut() {
|
||||
if let Some(sc) = nm.scope.as_mut() {
|
||||
@@ -962,8 +962,8 @@ fn hide_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(i)?.visibility = Visibility::Hidden;
|
||||
if cx.wb.active_sheet() == i {
|
||||
cx.wb.set_active_sheet(cx.wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0));
|
||||
if cx.wb.active_sheet == i {
|
||||
cx.wb.active_sheet = cx.wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0);
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
@@ -984,7 +984,7 @@ fn unhide_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let i = target_sheet(s, p)?;
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(i)?.visibility = Visibility::Visible;
|
||||
cx.wb.set_active_sheet(i);
|
||||
cx.wb.active_sheet = i;
|
||||
Ok(Json::Null)
|
||||
})
|
||||
}
|
||||
@@ -998,7 +998,7 @@ fn activate(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn step_sheet(s: &mut Session, dir: isize) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let mut i = d.wb.active_sheet();
|
||||
let mut i = d.wb.active_sheet;
|
||||
while let Some(next) = i.checked_add_signed(dir) {
|
||||
let Some(sheet) = d.wb.sheet(next) else { break };
|
||||
if sheet.visibility == Visibility::Visible {
|
||||
|
||||
@@ -165,7 +165,7 @@ fn slicer_toggle(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (idx, id) = find_slicer(s, p)?;
|
||||
let value = str_param(p, "value").ok_or_else(|| bad("slicer.toggle", "missing `value`"))?.to_string();
|
||||
let multi = bool_param(p, "multi").unwrap_or(false);
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
let (table, column, current) = {
|
||||
let d = s.doc()?;
|
||||
let sl = d.wb.active().and_then(|sh| sh.slicers.get(idx)).ok_or_else(|| bad("slicer.toggle", "no slicer"))?;
|
||||
@@ -204,7 +204,7 @@ fn slicer_toggle(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn slicer_select_all(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (idx, id) = find_slicer(s, p)?;
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
edit(s, |cx| {
|
||||
if let Some(sl) = cx.sheet_mut(sheet)?.slicers.get_mut(idx) {
|
||||
sl.selected = None;
|
||||
@@ -217,7 +217,7 @@ fn slicer_select_all(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn slicer_delete(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (idx, id) = find_slicer(s, p)?;
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let sheet = s.doc()?.wb.active_sheet;
|
||||
// Absolute column of the slicer, so its filter criterion can be removed too.
|
||||
let abs_col = s.doc().ok().and_then(|d| {
|
||||
let sh = d.wb.active()?;
|
||||
|
||||
@@ -301,7 +301,7 @@ fn parse_model(s: &Session, p: &Json) -> Result<Model> {
|
||||
let d = s.doc()?;
|
||||
let wb = &d.wb;
|
||||
let obj_text = str_param(p, "objective").or_else(|| str_param(p, "setObjective")).or_else(|| str_param(p, "set")).unwrap_or("");
|
||||
let (sheet, obj) = cells_of(wb, obj_text, wb.active_sheet(), 1).map_err(|_| EngineError::Other("The objective must be a single cell.".into()))?;
|
||||
let (sheet, obj) = cells_of(wb, obj_text, wb.active_sheet, 1).map_err(|_| EngineError::Other("The objective must be a single cell.".into()))?;
|
||||
let objective = *obj.first().ok_or_else(|| EngineError::Other("The objective must be a single cell.".into()))?;
|
||||
let sh = wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
|
||||
if sh.cell(objective).is_none_or(|c| c.formula.is_none()) {
|
||||
@@ -1913,8 +1913,8 @@ fn write_reports(cx: &mut Ctx, at: usize, built: Vec<(String, Lines)>) -> Vec<St
|
||||
*sc += count;
|
||||
}
|
||||
}
|
||||
if cx.wb.active_sheet() >= at {
|
||||
cx.wb.set_active_sheet(cx.wb.active_sheet().saturating_add(count));
|
||||
if cx.wb.active_sheet >= at {
|
||||
cx.wb.active_sheet += count;
|
||||
}
|
||||
cx.structural = true;
|
||||
names
|
||||
@@ -1939,7 +1939,7 @@ fn report(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let params = match p.get("model") {
|
||||
Some(m @ Json::Object(_)) => m.clone(),
|
||||
Some(Json::Null) | None => {
|
||||
let mut params = saved_model(&d.wb, d.wb.active_sheet()).unwrap_or_else(|| json!({}));
|
||||
let mut params = saved_model(&d.wb, d.wb.active_sheet).unwrap_or_else(|| json!({}));
|
||||
if let (Some(base), Some(over)) = (params.as_object_mut(), p.as_object()) {
|
||||
for (k, v) in over {
|
||||
base.insert(k.clone(), v.clone());
|
||||
@@ -1988,7 +1988,7 @@ fn report(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
|
||||
fn run(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc()?;
|
||||
let active = d.wb.active_sheet();
|
||||
let active = d.wb.active_sheet;
|
||||
let mut params = p.clone();
|
||||
if bool_param(p, "saved").unwrap_or(false) {
|
||||
let saved = saved_model(&d.wb, active).ok_or_else(|| EngineError::Other("This sheet has no saved Solver model.".into()))?;
|
||||
@@ -2145,7 +2145,7 @@ mod tests {
|
||||
/// The first saved-model name scoped to the active sheet.
|
||||
fn saved(s: &Session) -> String {
|
||||
let d = s.doc().unwrap();
|
||||
d.wb.names.iter().find(|n| n.scope == Some(d.wb.active_sheet())).map(|n| n.name.clone()).unwrap_or_default()
|
||||
d.wb.names.iter().find(|n| n.scope == Some(d.wb.active_sheet)).map(|n| n.name.clone()).unwrap_or_default()
|
||||
}
|
||||
fn set(s: &mut Session, cells: &[(&str, &str)]) {
|
||||
for (c, v) in cells {
|
||||
|
||||
@@ -149,7 +149,7 @@ fn freeze_panes(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
let at = match cell_param_on(s, p, "cell", si)? {
|
||||
Some(c) => c,
|
||||
None if si == d.wb.active_sheet() => d.selection.active,
|
||||
None if si == d.wb.active_sheet => d.selection.active,
|
||||
// The selection belongs to the active sheet.
|
||||
None => return Err(bad("view.freezePanes", "missing `cell`: the selection is on the active sheet")),
|
||||
};
|
||||
@@ -225,7 +225,7 @@ fn zoom(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let d = s.doc_mut()?;
|
||||
let dirty = d.is_dirty();
|
||||
let wb = std::sync::Arc::make_mut(&mut d.wb);
|
||||
let si = wb.active_sheet();
|
||||
let si = wb.active_sheet;
|
||||
if let Some(sh) = wb.sheet_mut(si) {
|
||||
sh.zoom = z;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ fn cell_arg(s: &Session, p: &Json, key: &str, cmd: &str) -> Result<(usize, CellR
|
||||
let d = s.doc()?;
|
||||
let t = str_param(p, key).ok_or_else(|| bad(cmd, format!("missing `{key}`")))?;
|
||||
let (sh, body) = split_sheet(t);
|
||||
let si = sheet_named(&d.wb, sh, d.wb.active_sheet(), cmd)?;
|
||||
let si = sheet_named(&d.wb, sh, d.wb.active_sheet, cmd)?;
|
||||
let c = CellRef::parse(body.trim()).ok_or_else(|| bad(cmd, format!("`{key}` is not a cell: `{t}`")))?;
|
||||
Ok((si, c))
|
||||
}
|
||||
@@ -110,7 +110,7 @@ fn cell_arg(s: &Session, p: &Json, key: &str, cmd: &str) -> Result<(usize, CellR
|
||||
/// are trimmed to the used range.
|
||||
pub(crate) fn parse_range(wb: &Workbook, t: &str, cmd: &str) -> Result<(usize, RangeRef)> {
|
||||
let (sh, body) = split_sheet(t);
|
||||
let si = sheet_named(wb, sh, wb.active_sheet(), cmd)?;
|
||||
let si = sheet_named(wb, sh, wb.active_sheet, cmd)?;
|
||||
let r = RangeRef::parse(body.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{t}`")))?;
|
||||
Ok((si, trim_to_used(wb, si, r)))
|
||||
}
|
||||
@@ -152,7 +152,7 @@ fn cell_list(wb: &Workbook, t: &str, cmd: &str, cap: usize) -> Result<(usize, Ve
|
||||
return Err(bad(cmd, format!("too many cells (at most {cap})")));
|
||||
}
|
||||
}
|
||||
Ok((sheet.unwrap_or(wb.active_sheet()), out))
|
||||
Ok((sheet.unwrap_or(wb.active_sheet), out))
|
||||
}
|
||||
|
||||
/// What a JSON value typed into a cell is, as a constant.
|
||||
@@ -525,7 +525,7 @@ fn scenario_delete(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
fn scenario_summary(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
const CMD: &str = "data.scenarioSummary";
|
||||
let d = s.doc()?;
|
||||
let si = d.wb.active_sheet();
|
||||
let si = d.wb.active_sheet;
|
||||
let sh = d.wb.sheet(si).ok_or(EngineError::NoDocument)?;
|
||||
let scenarios: Vec<Scenario> = load_scenarios(&d.wb).into_iter().filter(|x| x.sheet.eq_ignore_ascii_case(&sh.name)).collect();
|
||||
if scenarios.is_empty() {
|
||||
@@ -799,7 +799,7 @@ fn advanced_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
Some(t) => parse_range(&d.wb, t, CMD)?,
|
||||
None => {
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
(d.wb.active_sheet(), crate::selection::current_region(sh, d.selection.active))
|
||||
(d.wb.active_sheet, crate::selection::current_region(sh, d.selection.active))
|
||||
}
|
||||
};
|
||||
let criteria = str_param(p, "criteria").filter(|t| !t.trim().is_empty()).map(|t| parse_range(&d.wb, t, CMD)).transpose()?;
|
||||
@@ -1024,7 +1024,7 @@ fn consolidate(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, r) = parse_range(&d.wb, t, CMD)?;
|
||||
(si, r.start)
|
||||
}
|
||||
None => (d.wb.active_sheet(), d.selection.active),
|
||||
None => (d.wb.active_sheet, d.selection.active),
|
||||
};
|
||||
let mut row_keys: Vec<Key> = Vec::new();
|
||||
let mut col_keys: Vec<Key> = Vec::new();
|
||||
@@ -1146,7 +1146,7 @@ mod tests {
|
||||
fn v(s: &Session, a: &str) -> Value {
|
||||
let d = s.doc().unwrap();
|
||||
let (sh, body) = super::split_sheet(a);
|
||||
let si = sh.map(|n| d.wb.sheet_index(&n).unwrap()).unwrap_or(d.wb.active_sheet());
|
||||
let si = sh.map(|n| d.wb.sheet_index(&n).unwrap()).unwrap_or(d.wb.active_sheet);
|
||||
d.wb.sheet(si).unwrap().value(CellRef::parse(body).unwrap())
|
||||
}
|
||||
fn n(s: &Session, a: &str) -> f64 {
|
||||
|
||||
@@ -234,7 +234,7 @@ pub fn save_bytes(wb: &Workbook, path: &str) -> Result<Vec<u8>> {
|
||||
|
||||
/// Encodes a workbook as `kind`, whatever `path`'s extension says.
|
||||
pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result<Vec<u8>> {
|
||||
let sheet = wb.active_sheet();
|
||||
let sheet = wb.active_sheet;
|
||||
match kind {
|
||||
// The extension picks the package kind; only the macro-enabled kinds (.xlsm, .xltm) carry
|
||||
// the VBA project, so any other name saves without it, as Excel does.
|
||||
|
||||
+11
-38
@@ -23,7 +23,6 @@ pub mod record;
|
||||
pub mod sample;
|
||||
pub mod selection;
|
||||
pub mod tables;
|
||||
pub mod windows;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -40,7 +39,6 @@ pub use gridcraft_formula as formula;
|
||||
pub use gridcraft_model as model;
|
||||
pub use gridcraft_numfmt as numfmt;
|
||||
pub use selection::Selection;
|
||||
pub use windows::{Target, TargetGuard, WindowState, WindowView};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
@@ -182,8 +180,6 @@ pub struct DocState {
|
||||
pub path: Option<String>,
|
||||
pub saved: Arc<Workbook>,
|
||||
pub revision: u64,
|
||||
/// Identifies this open workbook for the rest of the session: it never changes while the
|
||||
/// workbook is open (saving, renaming, reordering) and is never reused for another one.
|
||||
pub uid: u64,
|
||||
pub title: String,
|
||||
/// Per-sheet selection memory.
|
||||
@@ -310,14 +306,14 @@ impl DocState {
|
||||
!Arc::ptr_eq(&self.wb, &self.saved)
|
||||
}
|
||||
pub fn sheet_index(&self) -> usize {
|
||||
self.wb.active_sheet()
|
||||
self.wb.active_sheet
|
||||
}
|
||||
/// Records the view state that is saved with the file (`sheetView topLeftCell`, the active
|
||||
/// cell): the first visible cell of the scrolling area per sheet index in `tops`, and the
|
||||
/// active sheet's active cell. View state never makes the workbook dirty.
|
||||
pub fn store_view(&mut self, tops: &[(usize, CellRef)]) {
|
||||
let active = self.selection.active;
|
||||
let si = self.wb.active_sheet();
|
||||
let si = self.wb.active_sheet;
|
||||
let changed = tops.iter().any(|(i, c)| self.wb.sheets.get(*i).is_some_and(|sh| sh.view_top_left != *c))
|
||||
|| self.wb.sheets.get(si).is_some_and(|sh| sh.view_active != active);
|
||||
if !changed {
|
||||
@@ -429,15 +425,7 @@ pub type TextWidth = Arc<dyn Fn(&str, &model::Font, bool) -> f32 + Send + Sync>;
|
||||
#[derive(Default)]
|
||||
pub struct Session {
|
||||
docs: Vec<DocState>,
|
||||
/// Index in `docs` of the active window's workbook.
|
||||
active: usize,
|
||||
/// Windows on the open workbooks ([`windows`]); every workbook has at least one.
|
||||
windows: Vec<WindowState>,
|
||||
active_window: Option<u64>,
|
||||
/// Last window id handed out.
|
||||
next_window: u64,
|
||||
/// Window activation counter (most recently used order).
|
||||
activation: u64,
|
||||
pub clipboard: Option<Clipboard>,
|
||||
pub prefs: Prefs,
|
||||
pub mode: Mode,
|
||||
@@ -460,6 +448,8 @@ pub struct Session {
|
||||
pub recorder: Option<record::Recorder>,
|
||||
/// How many `execute` calls are running (0 between top-level commands).
|
||||
depth: u32,
|
||||
/// Windows hidden with View › Hide.
|
||||
pub hidden_windows: Vec<usize>,
|
||||
/// Draw tab tool: "" (select), "pen" or "eraser"; pen colour and width.
|
||||
pub draw_tool: String,
|
||||
pub draw_color: String,
|
||||
@@ -495,24 +485,14 @@ impl Session {
|
||||
pub fn active_index(&self) -> usize {
|
||||
self.active
|
||||
}
|
||||
/// Makes the workbook at `i` active, in its most recently active window (unless the active
|
||||
/// window already shows it).
|
||||
pub fn set_active(&mut self, i: usize) {
|
||||
let Some(uid) = self.docs.get(i).map(|d| d.uid) else { return };
|
||||
if self.active == i && self.active_window.and_then(|w| self.window(w)).is_some_and(|w| w.doc_uid == uid) {
|
||||
return;
|
||||
}
|
||||
if let Some(w) = self.doc_window(uid) {
|
||||
self.activate_window(w);
|
||||
if i < self.docs.len() {
|
||||
self.active = i;
|
||||
}
|
||||
}
|
||||
pub fn active(&self) -> Option<&DocState> {
|
||||
self.docs.get(self.active)
|
||||
}
|
||||
/// Where the open workbook with this [`DocState::uid`] is in [`Session::documents`].
|
||||
pub fn document_index(&self, uid: u64) -> Option<usize> {
|
||||
self.docs.iter().position(|d| d.uid == uid)
|
||||
}
|
||||
pub fn active_mut(&mut self) -> Option<&mut DocState> {
|
||||
self.docs.get_mut(self.active)
|
||||
}
|
||||
@@ -522,24 +502,17 @@ impl Session {
|
||||
pub fn doc_mut(&mut self) -> Result<&mut DocState> {
|
||||
self.active_mut().ok_or(EngineError::NoDocument)
|
||||
}
|
||||
/// Opens a workbook in a new window, which becomes the active one.
|
||||
pub fn add_document(&mut self, d: DocState) -> usize {
|
||||
let uid = d.uid;
|
||||
self.docs.push(d);
|
||||
let w = self.push_window(uid);
|
||||
self.activate_window(w);
|
||||
self.docs.len() - 1
|
||||
self.active = self.docs.len() - 1;
|
||||
self.active
|
||||
}
|
||||
/// Closes a workbook and its windows; the most recently active remaining window comes forward.
|
||||
pub fn close_document(&mut self, i: usize) {
|
||||
if i < self.docs.len() {
|
||||
let d = self.docs.remove(i);
|
||||
self.groups.retain(|g| g.doc != d.uid);
|
||||
self.windows.retain(|w| w.doc_uid != d.uid);
|
||||
if self.active_window.is_some_and(|w| self.window(w).is_none()) {
|
||||
self.activate_recent();
|
||||
} else if let Some(di) = self.active_window.and_then(|w| self.window(w)).and_then(|w| self.document_index(w.doc_uid)) {
|
||||
self.active = di;
|
||||
if self.active >= self.docs.len() {
|
||||
self.active = self.docs.len().saturating_sub(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -623,7 +596,7 @@ impl Session {
|
||||
};
|
||||
// The recorder keeps top-level calls with the place they ran in.
|
||||
let place = (self.depth == 0 && self.recorder.is_some()).then(|| match self.active() {
|
||||
Some(d) => (d.uid, d.wb.active_sheet(), d.wb.active().map(|sh| sh.name.clone()).unwrap_or_default(), d.selection.clone()),
|
||||
Some(d) => (d.uid, d.wb.active_sheet, d.wb.active().map(|sh| sh.name.clone()).unwrap_or_default(), d.selection.clone()),
|
||||
None => (0, 0, String::new(), Selection::default()),
|
||||
});
|
||||
let doc_uid = before.as_ref().map(|(uid, ..)| *uid);
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn build(name: &str) -> Option<Workbook> {
|
||||
return None;
|
||||
}
|
||||
let mut wb = (*s.doc().ok()?.wb).clone();
|
||||
wb.set_active_sheet(0);
|
||||
wb.active_sheet = 0;
|
||||
if let Some(sh) = wb.sheet_mut(0) {
|
||||
sh.view_active = gridcraft_core::CellRef::default();
|
||||
}
|
||||
|
||||
+5
-217
@@ -193,7 +193,7 @@ fn chart_category_axis_from_blank_corner_and_select_data() {
|
||||
assert_eq!(series(&s), [(Some("Sheet1!$D$2:$D$4".to_string()), "Sheet1!$E$2:$E$4".to_string())]);
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.active().unwrap();
|
||||
let data = gridcraft_chart::resolve(&d.wb, d.wb.active_sheet(), sh.charts.last().unwrap());
|
||||
let data = gridcraft_chart::resolve(&d.wb, d.wb.active_sheet, sh.charts.last().unwrap());
|
||||
assert_eq!(data.categories, ["2020", "2021", "2022"]);
|
||||
// The last series can't be removed; "" clears the labels.
|
||||
s.execute("chart.selectData", json!({"categories": "", "removeSeries": [0]})).unwrap();
|
||||
@@ -1818,7 +1818,7 @@ fn slicer_finds_a_named_table_on_another_sheet() {
|
||||
s.execute("insert.table", json!({"range": "A1:B3", "name": "Sales"})).unwrap();
|
||||
s.execute("home.insertSheet", json!({"name": "Report"})).unwrap();
|
||||
let report = s.doc().unwrap().wb.sheet_index("Report").unwrap();
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet(), report);
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet, report);
|
||||
|
||||
// With another sheet active, `table` still names the table, and the slicer goes on the table's sheet.
|
||||
let r = s.execute("insert.slicer", json!({"table": "Sales", "column": "Region", "at": "D2"})).unwrap();
|
||||
@@ -2774,10 +2774,7 @@ fn every_command_survives_empty_params() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": "sales"})).unwrap();
|
||||
for spec in crate::command_specs() {
|
||||
if matches!(
|
||||
spec.id,
|
||||
"file.close" | "window.close" | "file.open" | "file.save" | "file.saveAs" | "file.exportCsv" | "file.exportHtml" | "insert.picture"
|
||||
) {
|
||||
if matches!(spec.id, "file.close" | "file.open" | "file.save" | "file.saveAs" | "file.exportCsv" | "file.exportHtml" | "insert.picture") {
|
||||
continue;
|
||||
}
|
||||
let _ = s.execute(spec.id, json!({}));
|
||||
@@ -2944,7 +2941,7 @@ fn error_checking_quotes_sheet_names_in_circular_references() {
|
||||
assert_eq!(v(&s, "A1"), Value::Number(2.0));
|
||||
s.execute("edit.goTo", json!({"reference": reference})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!((d.wb.active_sheet(), d.selection.active.a1()), (1, "B2".to_string()));
|
||||
assert_eq!((d.wb.active_sheet, d.selection.active.a1()), (1, "B2".to_string()));
|
||||
}
|
||||
|
||||
/// Undo and redo put cells back without calculating them; the circular references listed are
|
||||
@@ -4209,7 +4206,7 @@ fn line_sizes_and_freeze_panes_take_a_sheet() {
|
||||
assert!(data.cols.get(&4).is_some_and(|c| c.hidden));
|
||||
assert_eq!(data.default_col_width, 80.0);
|
||||
assert_eq!(sheet(&s, 0), before, "the active sheet is untouched");
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet(), 0);
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet, 0);
|
||||
|
||||
s.execute("view.freezePanes", json!({"cell": "Data!B3"})).unwrap();
|
||||
assert_eq!(sheet(&s, 1).freeze, Some((2, 1)));
|
||||
@@ -4828,212 +4825,6 @@ fn html_export_without_pictures_or_charts_has_no_fixed_geometry() {
|
||||
let html = crate::io::to_html(&s.doc().unwrap().wb, 0).unwrap();
|
||||
assert!(!html.contains("<colgroup>") && !html.contains("table-layout") && !html.contains("<svg") && !html.contains("<img"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_windows_lists_workbooks_by_stable_id_and_switches_to_one() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "first"})).unwrap();
|
||||
let book1 = s.doc().unwrap().uid;
|
||||
s.execute("file.new", json!({})).unwrap();
|
||||
s.execute("file.new", json!({})).unwrap();
|
||||
let book3 = s.doc().unwrap().uid;
|
||||
let list = s.execute("view.switchWindows", json!({})).unwrap();
|
||||
let rows = list.as_array().unwrap();
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert_eq!((rows[0]["doc"].as_u64(), rows[0]["title"].as_str(), rows[0]["dirty"].as_bool()), (Some(book1), Some("Book1"), Some(true)));
|
||||
assert_eq!((rows[2]["dirty"].as_bool(), rows[2]["active"].as_bool()), (Some(false), Some(true)));
|
||||
|
||||
// Closing a workbook shifts the indexes but not the ids.
|
||||
s.execute("window.activate", json!({"index": 1})).unwrap();
|
||||
s.execute("file.close", json!({"force": true})).unwrap();
|
||||
assert_eq!(s.document_index(book3), Some(1));
|
||||
let list = s.execute("view.switchWindows", json!({"doc": book1})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().uid, book1);
|
||||
assert_eq!(v(&s, "A1"), Value::text("first"));
|
||||
assert_eq!(list[0]["active"].as_bool(), Some(true));
|
||||
s.execute("file.save", json!({"path": std::env::temp_dir().join(format!("gridcraft-uid-{}.xlsx", std::process::id()))})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().uid, book1, "saving keeps the id");
|
||||
let _ = std::fs::remove_file(std::env::temp_dir().join(format!("gridcraft-uid-{}.xlsx", std::process::id())));
|
||||
|
||||
assert!(s.execute("view.switchWindows", json!({"doc": book3 + 1000})).is_err());
|
||||
assert!(s.execute("view.switchWindows", json!({"doc": "Book1"})).is_err());
|
||||
assert_eq!(s.doc().unwrap().uid, book1, "a bad id leaves the active workbook alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_window_shares_the_workbook_and_closes_window_by_window() {
|
||||
let mut s = s();
|
||||
let book = s.doc().unwrap().uid;
|
||||
assert_eq!(s.windows().len(), 1, "a new workbook opens in one window");
|
||||
let first = s.active_window().unwrap();
|
||||
assert_eq!(s.window_title(first).as_deref(), Some("Book1"));
|
||||
|
||||
let r = s.execute("view.newWindow", json!({})).unwrap();
|
||||
let second = r["window"].as_u64().unwrap();
|
||||
assert_eq!(s.documents().len(), 1, "no copy of the workbook");
|
||||
assert_eq!((s.windows().len(), s.active_window()), (2, Some(second)));
|
||||
assert_eq!(s.window_title(first).as_deref(), Some("Book1:1"));
|
||||
assert_eq!(s.window_title(second).as_deref(), Some("Book1:2"));
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
|
||||
// An edit in window 2 is in window 1's workbook, and saving from window 2 saves it.
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "shared"})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("gridcraft-windows-{}.xlsx", std::process::id()));
|
||||
s.execute("file.save", json!({"path": path})).unwrap();
|
||||
s.execute("window.activate", json!({"window": first})).unwrap();
|
||||
assert_eq!((s.doc().unwrap().uid, v(&s, "A1")), (book, Value::text("shared")));
|
||||
assert!(!s.doc().unwrap().is_dirty(), "saved from the other window");
|
||||
assert_eq!(s.doc().unwrap().path.as_deref(), path.to_str());
|
||||
let _ = std::fs::remove_file(&path);
|
||||
|
||||
// Closing one window keeps the workbook and renumbers the titles; the last one closes it.
|
||||
s.execute("cell.set", json!({"cell": "A2", "input": "unsaved"})).unwrap();
|
||||
let r = s.execute("file.close", json!({})).unwrap();
|
||||
assert_eq!((r["closed"].as_bool(), r["document"].as_bool()), (Some(true), Some(false)), "no prompt for one of two windows");
|
||||
assert_eq!((s.windows().len(), s.active_window()), (1, Some(second)));
|
||||
assert_eq!(s.window_title(second).as_deref(), Some(s.doc().unwrap().display_title().as_str()));
|
||||
let r = s.execute("window.close", json!({})).unwrap();
|
||||
assert_eq!(r["closed"].as_bool(), Some(false), "the last window asks about unsaved changes");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
s.execute("window.close", json!({"force": true})).unwrap();
|
||||
assert!(s.documents().is_empty() && s.windows().is_empty() && s.active_window().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_windows_swaps_their_views_without_dirtying_the_workbook() {
|
||||
let mut s = s();
|
||||
s.execute("home.insertSheet", json!({})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("gridcraft-window-views-{}.xlsx", std::process::id()));
|
||||
s.execute("file.save", json!({"path": path})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2:C3"})).unwrap();
|
||||
let first = s.active_window().unwrap();
|
||||
let second = s.execute("view.newWindow", json!({})).unwrap()["window"].as_u64().unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 1})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "D4"})).unwrap();
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
|
||||
s.execute("window.activate", json!({"window": first})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!((d.wb.active_sheet(), d.selection.a1()), (0, "B2:C3".to_string()));
|
||||
assert!(!d.is_dirty(), "a window's sheet and selection are not document changes");
|
||||
s.execute("view.switchWindows", json!({"window": second})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!((d.wb.active_sheet(), d.selection.a1()), (1, "D4".to_string()));
|
||||
assert!(!d.is_dirty());
|
||||
|
||||
// A routed command acts in its window and leaves the active one showing.
|
||||
s.execute_in(crate::Target::Window(first), "cell.set", json!({"cell": "A1", "input": "in window 1"})).unwrap();
|
||||
assert_eq!(s.active_window(), Some(second));
|
||||
assert_eq!(s.doc().unwrap().wb.sheets[0].value(CellRef::parse("A1").unwrap()), Value::text("in window 1"));
|
||||
assert_eq!(s.doc().unwrap().selection.a1(), "D4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_swaps_share_the_workbook_and_save_records_the_latest_window_sheet() {
|
||||
let mut s = s();
|
||||
s.execute("home.insertSheet", json!({})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("gridcraft-window-arc-{}.xlsx", std::process::id()));
|
||||
s.execute("file.save", json!({"path": path})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "B2"})).unwrap();
|
||||
let first = s.active_window().unwrap();
|
||||
let second = s.execute("view.newWindow", json!({})).unwrap()["window"].as_u64().unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 1})).unwrap();
|
||||
s.execute("selection.set", json!({"range": "C3:D4"})).unwrap();
|
||||
|
||||
// Swapping windows, as the interface does before drawing each one, never copies the workbook.
|
||||
let before = s.doc().unwrap().wb.clone();
|
||||
for _ in 0..3 {
|
||||
s.show_window(first);
|
||||
assert_eq!((s.doc().unwrap().wb.active_sheet(), s.doc().unwrap().selection.a1()), (0, "B2".to_string()));
|
||||
s.activate_window(second);
|
||||
assert_eq!((s.doc().unwrap().wb.active_sheet(), s.doc().unwrap().selection.a1()), (1, "C3:D4".to_string()));
|
||||
s.execute("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": 1})).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &d.wb), "a window swap or sheet switch copied the workbook");
|
||||
assert!(!d.is_dirty());
|
||||
|
||||
// A command run in window 2 edits window 2's sheet at its selection.
|
||||
s.execute("cell.set", json!({"input": "two"})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.wb.sheets[1].value(CellRef::parse("C3").unwrap()), Value::text("two"));
|
||||
assert_eq!(d.wb.sheets[0].value(CellRef::parse("B2").unwrap()), Value::Empty);
|
||||
s.show_window(first);
|
||||
assert_eq!(s.doc().unwrap().wb.active_sheet(), 0);
|
||||
|
||||
// The most recently active window is window 2: the file records its sheet.
|
||||
s.execute_in(crate::Target::Window(second), "file.save", json!({"path": path})).unwrap();
|
||||
let mut t = Session::new();
|
||||
t.execute("file.open", json!({"path": path})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(t.doc().unwrap().wb.active_sheet(), 1);
|
||||
s.activate_window(first);
|
||||
s.execute("file.save", json!({"path": path})).unwrap();
|
||||
let mut t = Session::new();
|
||||
t.execute("file.open", json!({"path": path})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(t.doc().unwrap().wb.active_sheet(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrange_all_picks_the_visible_windows_active_first() {
|
||||
let mut s = s();
|
||||
let book1 = s.active_window().unwrap();
|
||||
let book1b = s.execute("view.newWindow", json!({})).unwrap()["window"].as_u64().unwrap();
|
||||
s.execute("file.new", json!({})).unwrap();
|
||||
let book2 = s.active_window().unwrap();
|
||||
let r = s.execute("view.arrangeAll", json!({})).unwrap();
|
||||
assert_eq!(r, json!({"arrange": "tiled", "windows": [book2, book1, book1b]}));
|
||||
s.execute("window.activate", json!({"window": book1b})).unwrap();
|
||||
s.execute("view.hideWindow", json!({"window": book2})).unwrap();
|
||||
let r = s.execute("view.arrangeAll", json!({"arrange": "cascade", "activeWorkbook": true})).unwrap();
|
||||
assert_eq!(r, json!({"arrange": "cascade", "windows": [book1b, book1]}));
|
||||
assert!(s.execute("view.arrangeAll", json!({"arrange": "diagonal"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_unhide_and_switch_by_window_id() {
|
||||
let mut s = s();
|
||||
let book1 = s.doc().unwrap().uid;
|
||||
let w1 = s.active_window().unwrap();
|
||||
let w2 = s.execute("view.newWindow", json!({})).unwrap()["window"].as_u64().unwrap();
|
||||
s.execute("file.new", json!({})).unwrap();
|
||||
let w3 = s.active_window().unwrap();
|
||||
s.execute("view.hideWindow", json!({})).unwrap();
|
||||
assert_eq!(s.active_window(), Some(w2), "the most recent visible window comes forward");
|
||||
let list = s.execute("window.list", json!({})).unwrap();
|
||||
let rows = list.as_array().unwrap();
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert_eq!((rows[0]["window"].as_u64(), rows[0]["title"].as_str(), rows[0]["doc"].as_u64()), (Some(w1), Some("Book1:1"), Some(book1)));
|
||||
assert_eq!((rows[2]["title"].as_str(), rows[2]["hidden"].as_bool()), (Some("Book2"), Some(true)));
|
||||
assert_eq!(rows[1]["active"].as_bool(), Some(true));
|
||||
s.execute("view.unhideWindow", json!({})).unwrap();
|
||||
assert_eq!(s.active_window(), Some(w3));
|
||||
assert!(!s.window(w3).unwrap().hidden);
|
||||
// A workbook id goes to that workbook's most recent window.
|
||||
s.execute("view.switchWindows", json!({"doc": book1})).unwrap();
|
||||
assert_eq!(s.active_window(), Some(w2));
|
||||
assert!(s.execute("window.activate", json!({"window": 999})).is_err());
|
||||
assert_eq!(s.active_window(), Some(w2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_replaces_an_untouched_blank_workbook_and_its_windows() {
|
||||
let mut s = s();
|
||||
s.execute("view.newWindow", json!({})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("gridcraft-open-blank-{}.csv", std::process::id()));
|
||||
std::fs::write(&path, "a,b\n1,2\n").unwrap();
|
||||
s.execute("file.open", json!({"path": path})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_eq!(s.windows().len(), 1, "the blank workbook's windows closed with it");
|
||||
assert_eq!(s.windows()[0].doc_uid, s.doc().unwrap().uid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_cells_permission_on_a_protected_sheet_cannot_unlock_cells() {
|
||||
// Formatting may be allowed on a protected sheet; the permission can't serve as a key to
|
||||
@@ -5084,9 +4875,6 @@ fn a_script_cannot_switch_windows() {
|
||||
s.execute("automate.trustScripts", json!({"trusted": true})).unwrap();
|
||||
let err = s.execute("automate.runScript", json!({"name": "t"})).expect_err("script switching windows");
|
||||
assert!(err.to_string().contains("window.activate"), "{err}");
|
||||
s.execute("automate.newScript", json!({"name": "sw", "commands": [{"command": "view.switchWindows", "params": {"doc": 1}}]})).unwrap();
|
||||
let err = s.execute("automate.runScript", json!({"name": "sw"})).expect_err("script switching windows from the View tab");
|
||||
assert!(err.to_string().contains("view.switchWindows"), "{err}");
|
||||
// A benign script runs.
|
||||
s.execute("automate.newScript", json!({"name": "ok", "commands": [{"command": "cell.set", "params": {"cell": "A1", "input": "=1+1"}}]})).unwrap();
|
||||
s.execute("automate.runScript", json!({"name": "ok"})).unwrap();
|
||||
|
||||
@@ -837,7 +837,7 @@ fn the_recorder_keeps_top_level_calls_with_where_they_ran() {
|
||||
assert_eq!(recorded_ids(&s), ["cell.set", "view.customViews", "view.customViews"]);
|
||||
let first = &s.recorder.as_ref().unwrap().steps[0];
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!((first.doc, first.sheet), (d.uid, d.wb.active_sheet()));
|
||||
assert_eq!((first.doc, first.sheet), (d.uid, d.wb.active_sheet));
|
||||
assert_eq!(first.sheet_name, d.wb.active().unwrap().name);
|
||||
assert_eq!(first.selection.a1(), "B2:C3", "the selection before the command ran");
|
||||
assert_eq!(first.params, json!({"cell": "B2", "input": "10"}));
|
||||
|
||||
@@ -1,348 +0,0 @@
|
||||
//! Windows on open workbooks.
|
||||
//!
|
||||
//! Every open workbook has one or more windows (View › New Window adds another on the same
|
||||
//! workbook). A window has its own selection, active sheet and per-sheet selections. The active
|
||||
//! window's view lives in its [`DocState`] (`selection`, `sheet_selections`) and in the workbook's
|
||||
//! active sheet ([`gridcraft_model::workbook::Workbook::active_sheet`]), where every command reads
|
||||
//! it; each other window keeps its view in [`WindowState`] until it is activated. Swapping a view
|
||||
//! in or out never copies the workbook or makes it dirty: the active sheet is set in place through
|
||||
//! the shared `Arc`, and selections live outside the workbook.
|
||||
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
use crate::{DocState, EngineError, Result, Selection, Session};
|
||||
|
||||
/// The view state one window keeps while another window on its workbook is showing.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct WindowView {
|
||||
pub selection: Selection,
|
||||
pub sheet: usize,
|
||||
/// The active sheet's name, so a sheet inserted, deleted or moved meanwhile in another
|
||||
/// window still finds it.
|
||||
pub sheet_name: String,
|
||||
pub sheet_selections: Vec<Selection>,
|
||||
}
|
||||
|
||||
/// One window on an open workbook.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WindowState {
|
||||
/// Identifies the window for the rest of the session; never reused.
|
||||
pub id: u64,
|
||||
/// The [`DocState::uid`] of the workbook it shows.
|
||||
pub doc_uid: u64,
|
||||
/// View › Hide.
|
||||
pub hidden: bool,
|
||||
/// `None` while this window's view is the one in the document (the active window, or the
|
||||
/// workbook's most recently active window); exactly one window per workbook has `None`.
|
||||
view: Option<WindowView>,
|
||||
/// Activation order: higher was active more recently.
|
||||
last_active: u64,
|
||||
}
|
||||
|
||||
impl WindowView {
|
||||
fn capture(d: &DocState) -> WindowView {
|
||||
WindowView {
|
||||
selection: d.selection.clone(),
|
||||
sheet: d.wb.active_sheet(),
|
||||
sheet_name: d.wb.sheets.get(d.wb.active_sheet()).map(|s| s.name.clone()).unwrap_or_default(),
|
||||
sheet_selections: d.sheet_selections.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(self, d: &mut DocState) {
|
||||
let sheets = &d.wb.sheets;
|
||||
let at = if sheets.get(self.sheet).is_some_and(|s| s.name == self.sheet_name) {
|
||||
self.sheet
|
||||
} else {
|
||||
sheets.iter().position(|s| s.name == self.sheet_name).unwrap_or(self.sheet)
|
||||
};
|
||||
d.wb.set_active_sheet(at.min(sheets.len().saturating_sub(1)));
|
||||
d.selection = self.selection;
|
||||
d.sheet_selections = self.sheet_selections;
|
||||
}
|
||||
}
|
||||
|
||||
/// Which window a command from a script or agent acts on.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Target {
|
||||
/// The active window.
|
||||
#[default]
|
||||
Active,
|
||||
/// A window by [`WindowState::id`].
|
||||
Window(u64),
|
||||
/// A workbook by [`DocState::uid`]: its most recently active window.
|
||||
Doc(u64),
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// Reads `window` or `doc` from a JSON object (control channel envelopes, MCP arguments).
|
||||
/// Neither present is [`Target::Active`]; a value that isn't an id is an error.
|
||||
pub fn from_json(p: &Json) -> Result<Target> {
|
||||
let id = |k: &str| -> Result<Option<u64>> {
|
||||
match p.get(k) {
|
||||
None | Some(Json::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| EngineError::Other(format!("`{k}` must be a window or workbook id number"))),
|
||||
}
|
||||
};
|
||||
Ok(match (id("window")?, id("doc")?) {
|
||||
(Some(w), _) => Target::Window(w),
|
||||
(None, Some(d)) => Target::Doc(d),
|
||||
(None, None) => Target::Active,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Session::leave_target`] restores.
|
||||
#[derive(Debug)]
|
||||
#[must_use]
|
||||
pub struct TargetGuard {
|
||||
id: u64,
|
||||
back: Option<u64>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The open windows, in the order they were opened.
|
||||
pub fn windows(&self) -> &[WindowState] {
|
||||
&self.windows
|
||||
}
|
||||
|
||||
/// The active window's id (`None` with no workbook open).
|
||||
pub fn active_window(&self) -> Option<u64> {
|
||||
self.active_window
|
||||
}
|
||||
|
||||
pub fn window(&self, id: u64) -> Option<&WindowState> {
|
||||
self.windows.iter().find(|w| w.id == id)
|
||||
}
|
||||
|
||||
/// A workbook's windows in opening order.
|
||||
fn windows_of(&self, doc: u64) -> impl Iterator<Item = &WindowState> {
|
||||
self.windows.iter().filter(move |w| w.doc_uid == doc)
|
||||
}
|
||||
|
||||
/// The window title: the workbook's name when it has one window, "Name:1", "Name:2"… in
|
||||
/// opening order when it has several.
|
||||
pub fn window_title(&self, id: u64) -> Option<String> {
|
||||
let w = self.window(id)?;
|
||||
let d = self.docs.iter().find(|d| d.uid == w.doc_uid)?;
|
||||
let name = d.display_title();
|
||||
let mut n = 0;
|
||||
let mut at = 0;
|
||||
for x in self.windows_of(w.doc_uid) {
|
||||
n += 1;
|
||||
if x.id == id {
|
||||
at = n;
|
||||
}
|
||||
}
|
||||
Some(if n > 1 { format!("{name}:{at}") } else { name })
|
||||
}
|
||||
|
||||
/// The most recently active window of a workbook, preferring one that isn't hidden.
|
||||
pub fn doc_window(&self, doc: u64) -> Option<u64> {
|
||||
self.windows_of(doc).max_by_key(|w| (!w.hidden, w.last_active)).map(|w| w.id)
|
||||
}
|
||||
|
||||
/// Resolves a [`Target`] to a window id.
|
||||
pub fn target_window(&self, t: Target) -> Result<u64> {
|
||||
match t {
|
||||
Target::Active => self.active_window.ok_or(EngineError::NoDocument),
|
||||
Target::Window(id) => self.window(id).map(|w| w.id).ok_or_else(|| EngineError::Other(format!("no open window has id {id}"))),
|
||||
Target::Doc(uid) => self.doc_window(uid).ok_or_else(|| EngineError::Other(format!("no open workbook has id {uid}"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn push_window(&mut self, doc_uid: u64) -> u64 {
|
||||
self.next_window = self.next_window.saturating_add(1);
|
||||
let id = self.next_window;
|
||||
self.windows.push(WindowState { id, doc_uid, hidden: false, view: None, last_active: 0 });
|
||||
id
|
||||
}
|
||||
|
||||
/// Makes a window active, swapping its view into its workbook. Unknown ids are ignored.
|
||||
pub fn activate_window(&mut self, id: u64) {
|
||||
self.enter_window(id, true);
|
||||
}
|
||||
|
||||
/// Makes a window the one commands act on while the interface draws it, without counting as
|
||||
/// an activation: the most recently active window of each workbook stays the same.
|
||||
pub fn show_window(&mut self, id: u64) {
|
||||
self.enter_window(id, false);
|
||||
}
|
||||
|
||||
fn enter_window(&mut self, id: u64, recent: bool) {
|
||||
let Some(wi) = self.windows.iter().position(|w| w.id == id) else { return };
|
||||
let Some(w) = self.windows.get(wi) else { return };
|
||||
let doc = w.doc_uid;
|
||||
if w.view.is_some()
|
||||
&& let Some(di) = self.document_index(doc)
|
||||
{
|
||||
let live = self.windows.iter().position(|x| x.doc_uid == doc && x.view.is_none());
|
||||
let incoming = self.windows.get_mut(wi).and_then(|w| w.view.take());
|
||||
if let Some(d) = self.docs.get_mut(di) {
|
||||
if let Some(li) = live
|
||||
&& let Some(lw) = self.windows.get_mut(li)
|
||||
{
|
||||
lw.view = Some(WindowView::capture(d));
|
||||
}
|
||||
if let Some(v) = incoming {
|
||||
v.apply(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
if recent {
|
||||
self.activation = self.activation.saturating_add(1);
|
||||
let stamp = self.activation;
|
||||
if let Some(w) = self.windows.get_mut(wi) {
|
||||
w.last_active = stamp;
|
||||
}
|
||||
}
|
||||
self.active_window = Some(id);
|
||||
if let Some(di) = self.document_index(doc) {
|
||||
self.active = di;
|
||||
}
|
||||
}
|
||||
|
||||
/// Activates the most recently active window that isn't hidden, else any window, else none.
|
||||
pub(crate) fn activate_recent(&mut self) {
|
||||
let next = self.windows.iter().max_by_key(|w| (!w.hidden, w.last_active)).map(|w| w.id);
|
||||
match next {
|
||||
Some(id) => self.activate_window(id),
|
||||
None => {
|
||||
self.active_window = None;
|
||||
self.active = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// View › New Window: another window on the active window's workbook, showing what it shows.
|
||||
pub fn new_window(&mut self) -> Result<u64> {
|
||||
let current = self.active_window.ok_or(EngineError::NoDocument)?;
|
||||
let doc = self.window(current).map(|w| w.doc_uid).ok_or(EngineError::NoDocument)?;
|
||||
let view = self.doc().map(WindowView::capture)?;
|
||||
// The new window takes over the live view (identical at this point); the old one keeps a copy.
|
||||
if let Some(w) = self.windows.iter_mut().find(|w| w.doc_uid == doc && w.view.is_none()) {
|
||||
w.view = Some(view);
|
||||
}
|
||||
let id = self.push_window(doc);
|
||||
self.activate_window(id);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Closes one window. The workbook stays open while it has another window; closing its last
|
||||
/// window closes the workbook (unsaved changes are the caller's to ask about).
|
||||
pub fn close_window(&mut self, id: u64) {
|
||||
let Some(wi) = self.windows.iter().position(|w| w.id == id) else { return };
|
||||
let doc = self.windows.get(wi).map(|w| w.doc_uid).unwrap_or_default();
|
||||
if self.windows_of(doc).count() <= 1 {
|
||||
if let Some(di) = self.document_index(doc) {
|
||||
self.close_document(di);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let closed = self.windows.remove(wi);
|
||||
if closed.view.is_none() {
|
||||
// Its view was the one in the document: the workbook's next window takes it over.
|
||||
if let Some(next) = self.windows.iter().filter(|w| w.doc_uid == doc).max_by_key(|w| w.last_active).map(|w| w.id) {
|
||||
let incoming = self.windows.iter_mut().find(|w| w.id == next).and_then(|w| w.view.take());
|
||||
if let Some(v) = incoming
|
||||
&& let Some(d) = self.docs.iter_mut().find(|d| d.uid == doc)
|
||||
{
|
||||
v.apply(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.active_window == Some(id) {
|
||||
self.activate_recent();
|
||||
}
|
||||
}
|
||||
|
||||
/// View › Hide on a window; the most recent visible window comes forward.
|
||||
pub fn hide_window(&mut self, id: u64) {
|
||||
let Some(w) = self.windows.iter_mut().find(|w| w.id == id) else { return };
|
||||
w.hidden = true;
|
||||
if self.active_window == Some(id) && self.windows.iter().any(|w| !w.hidden) {
|
||||
self.activate_recent();
|
||||
}
|
||||
}
|
||||
|
||||
/// View › Unhide: shows a hidden window and activates it.
|
||||
pub fn unhide_window(&mut self, id: u64) {
|
||||
let Some(w) = self.windows.iter_mut().find(|w| w.id == id) else { return };
|
||||
w.hidden = false;
|
||||
self.activate_window(id);
|
||||
}
|
||||
|
||||
/// The most recently hidden window.
|
||||
pub fn last_hidden_window(&self) -> Option<u64> {
|
||||
self.windows.iter().filter(|w| w.hidden).max_by_key(|w| w.last_active).map(|w| w.id)
|
||||
}
|
||||
|
||||
/// The windows as scripts and the Switch Windows lists see them:
|
||||
/// `[{window, doc, index, title, dirty, active, hidden}]`, `index` being the workbook's
|
||||
/// position in [`Session::documents`].
|
||||
pub fn window_list(&self) -> Json {
|
||||
Json::Array(
|
||||
self.windows
|
||||
.iter()
|
||||
.filter_map(|w| {
|
||||
let index = self.document_index(w.doc_uid)?;
|
||||
let d = self.docs.get(index)?;
|
||||
Some(json!({
|
||||
"window": w.id,
|
||||
"doc": w.doc_uid,
|
||||
"index": index,
|
||||
"title": self.window_title(w.id).unwrap_or_default(),
|
||||
"dirty": d.is_dirty(),
|
||||
"active": self.active_window == Some(w.id),
|
||||
"hidden": w.hidden,
|
||||
}))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs `f` with the target window active, then brings back the window that was active, so a
|
||||
/// script acting on another window doesn't change what the user is looking at. When `f`
|
||||
/// itself switched windows (`window.activate`, `file.new`, a close), its choice stands.
|
||||
pub fn with_target<T>(&mut self, t: Target, f: impl FnOnce(&mut Session) -> T) -> Result<T> {
|
||||
let guard = self.enter_target(t)?;
|
||||
let r = f(self);
|
||||
self.leave_target(guard);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The first half of [`Session::with_target`], for callers whose closure can't borrow the
|
||||
/// session alone (the UI runs commands through its app): activates the target window and
|
||||
/// returns what [`Session::leave_target`] needs to bring the previous one back.
|
||||
pub fn enter_target(&mut self, t: Target) -> Result<Option<TargetGuard>> {
|
||||
if t == Target::Active {
|
||||
return Ok(None);
|
||||
}
|
||||
let id = self.target_window(t)?;
|
||||
let back = self.active_window;
|
||||
self.activate_window(id);
|
||||
Ok(Some(TargetGuard { id, back }))
|
||||
}
|
||||
|
||||
pub fn leave_target(&mut self, guard: Option<TargetGuard>) {
|
||||
let Some(TargetGuard { id, back: Some(back) }) = guard else { return };
|
||||
if self.active_window == Some(id) && back != id && self.window(back).is_some() {
|
||||
self.activate_window(back);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Session::execute`] on a target window.
|
||||
pub fn execute_in(&mut self, t: Target, id: &str, params: Json) -> Result<Json> {
|
||||
self.with_target(t, |s| s.execute(id, params))?
|
||||
}
|
||||
|
||||
/// [`Session::execute_headless`] on a target window.
|
||||
pub fn execute_headless_in(&mut self, t: Target, id: &str, params: Json) -> Result<Json> {
|
||||
self.with_target(t, |s| s.execute_headless(id, params))?
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands that take `window`/`doc` as their own parameters rather than as a target.
|
||||
pub fn is_window_command(id: &str) -> bool {
|
||||
id.starts_with("window.") || matches!(id, "view.newWindow" | "view.hideWindow" | "view.unhideWindow" | "view.switchWindows")
|
||||
}
|
||||
@@ -59,8 +59,7 @@ const EXCLUDED: &[(&str, &str)] = &[
|
||||
("file.exportPdf", "renders a PDF: slow, and may write files"),
|
||||
("file.print", "renders a PDF: slow"),
|
||||
("window.activate", "switches documents"),
|
||||
("window.close", "closes the document under test"),
|
||||
("view.newWindow", "opens another window, whose view swaps with the first"),
|
||||
("view.newWindow", "opens another document"),
|
||||
("insert.picture", "reads files"),
|
||||
("pageLayout.background", "reads files"),
|
||||
("formulas.calculationOptions", "manual and iterative calculation differ from a full recalc by design"),
|
||||
@@ -373,8 +372,8 @@ fn structure_problem(wb: &Workbook, sel: &gridcraft_engine::Selection) -> Option
|
||||
if wb.sheets.is_empty() {
|
||||
return Some("no sheets left".into());
|
||||
}
|
||||
if wb.active_sheet() >= wb.sheets.len() {
|
||||
return Some(format!("active sheet {} of {}", wb.active_sheet(), wb.sheets.len()));
|
||||
if wb.active_sheet >= wb.sheets.len() {
|
||||
return Some(format!("active sheet {} of {}", wb.active_sheet, wb.sheets.len()));
|
||||
}
|
||||
let mut tables = BTreeSet::new();
|
||||
for (i, sh) in wb.sheets.iter().enumerate() {
|
||||
@@ -490,7 +489,7 @@ fn watch_list(wb: &Workbook) -> Option<&str> {
|
||||
/// reset: undo restores view state as it was, but switching sheets isn't an undoable edit.
|
||||
fn canonical(wb: &Workbook) -> Workbook {
|
||||
let mut wb = wb.clone();
|
||||
wb.set_active_sheet(0);
|
||||
wb.active_sheet = 0;
|
||||
wb.names.retain(|n| n.name != WATCH_NAME);
|
||||
for sh in wb.sheets.iter_mut() {
|
||||
let sh = Arc::make_mut(sh);
|
||||
|
||||
@@ -25,7 +25,7 @@ fn next_stays_on_the_last_visible_sheet() {
|
||||
for _ in 0..2 {
|
||||
session.execute("sheet.next", json!({})).unwrap();
|
||||
let doc = session.active().unwrap();
|
||||
assert_eq!(doc.wb.active_sheet(), 1);
|
||||
assert_eq!(doc.wb.active_sheet, 1);
|
||||
assert_eq!(doc.selection.active.a1(), "C7");
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ fn previous_stays_on_the_first_visible_sheet() {
|
||||
for _ in 0..2 {
|
||||
session.execute("sheet.previous", json!({})).unwrap();
|
||||
let doc = session.active().unwrap();
|
||||
assert_eq!(doc.wb.active_sheet(), 2);
|
||||
assert_eq!(doc.wb.active_sheet, 2);
|
||||
assert_eq!(doc.selection.active.a1(), "C7");
|
||||
}
|
||||
}
|
||||
@@ -45,10 +45,10 @@ fn previous_stays_on_the_first_visible_sheet() {
|
||||
fn navigation_skips_hidden_sheets_in_both_directions() {
|
||||
let mut session = workbook(&[1, 2], 0);
|
||||
session.execute("sheet.next", json!({})).unwrap();
|
||||
assert_eq!(session.active().unwrap().wb.active_sheet(), 3);
|
||||
assert_eq!(session.active().unwrap().wb.active_sheet, 3);
|
||||
session.execute("sheet.previous", json!({})).unwrap();
|
||||
let doc = session.active().unwrap();
|
||||
assert_eq!(doc.wb.active_sheet(), 0);
|
||||
assert_eq!(doc.wb.active_sheet, 0);
|
||||
assert_eq!(doc.selection.active.a1(), "C7");
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ fn navigation_with_one_visible_sheet_is_a_noop() {
|
||||
for command in ["sheet.previous", "sheet.next"] {
|
||||
session.execute(command, json!({})).unwrap();
|
||||
let doc = session.active().unwrap();
|
||||
assert_eq!(doc.wb.active_sheet(), 1);
|
||||
assert_eq!(doc.wb.active_sheet, 1);
|
||||
assert_eq!(doc.selection.active.a1(), "C7");
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,6 @@ fn very_hidden_sheets_are_skipped_at_interior_and_boundary_positions() {
|
||||
}
|
||||
for (command, expected) in [("sheet.next", 2), ("sheet.next", 2), ("sheet.previous", 0)] {
|
||||
session.execute(command, json!({})).unwrap();
|
||||
assert_eq!(session.active().unwrap().wb.active_sheet(), expected);
|
||||
assert_eq!(session.active().unwrap().wb.active_sheet, expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! An in-process engine session that answers the engine-level control-channel methods itself.
|
||||
|
||||
use gridcraft_engine::{Session, Target};
|
||||
use gridcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::backend::Backend;
|
||||
@@ -33,9 +33,9 @@ impl Headless {
|
||||
Self { session }
|
||||
}
|
||||
|
||||
fn execute(&mut self, target: Target, id: &str, params: Value) -> Result<Value, String> {
|
||||
fn execute(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
// Programmatic calls never open dialogs; anything a command queued for a UI is dropped.
|
||||
self.session.execute_headless_in(target, id, params).map_err(|e| e.to_string())
|
||||
self.session.execute_headless(id, params).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn commands(&self, params: &Value) -> Value {
|
||||
@@ -68,28 +68,14 @@ impl Backend for Headless {
|
||||
if !(p.is_object() || p.is_null()) {
|
||||
return Err(format!("engine.execute: `params` of `{id}` must be an object"));
|
||||
}
|
||||
let target = Target::from_json(¶ms).map_err(|e| e.to_string())?;
|
||||
self.execute(target, &id, p)
|
||||
self.execute(&id, p)
|
||||
}
|
||||
"engine.commands" => Ok(self.commands(¶ms)),
|
||||
"engine.journal" => Ok(Value::Array(self.session.journal.iter().map(|(id, p)| json!({"command": id, "params": p})).collect())),
|
||||
m if m.starts_with("ui.") || m.starts_with("app.screenshot") => Err(format!("{m}: {NO_UI}")),
|
||||
// Read-only engine methods (`document.inspect`, `sheet.read`, `cell.get`, …) are
|
||||
// commands with the same id.
|
||||
// Their params may name a `window` or `doc` to act in, except for the window commands,
|
||||
// whose own params those are.
|
||||
m if gridcraft_engine::find_command(m).is_some() => {
|
||||
if gridcraft_engine::windows::is_window_command(m) {
|
||||
return self.execute(Target::Active, m, params);
|
||||
}
|
||||
let target = Target::from_json(¶ms).map_err(|e| e.to_string())?;
|
||||
let mut params = params;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.remove("window");
|
||||
o.remove("doc");
|
||||
}
|
||||
self.execute(target, m, params)
|
||||
}
|
||||
m if gridcraft_engine::find_command(m).is_some() => self.execute(m, params),
|
||||
other => Err(format!("unknown method `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +106,6 @@ fn tools_list_has_schemas() {
|
||||
"redo",
|
||||
"screenshot",
|
||||
"list_functions",
|
||||
"list_windows",
|
||||
] {
|
||||
assert!(names.contains(&want), "missing tool {want}");
|
||||
}
|
||||
@@ -596,31 +595,3 @@ fn invalid_sort_keys_are_invalid_params() {
|
||||
}
|
||||
ok(&mut s, "sort_range", json!({"range": "A1:A3", "keys": ["A", {"column": "A", "order": "desc"}]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_argument_routes_tools_to_that_window() {
|
||||
let mut s = server();
|
||||
ok(&mut s, "set_cell", json!({"cell": "A1", "input": "book one"}));
|
||||
ok(&mut s, "new_workbook", json!({}));
|
||||
let windows = ok(&mut s, "list_windows", json!({}));
|
||||
let rows = windows.as_array().unwrap();
|
||||
assert_eq!(rows.len(), 2, "{windows}");
|
||||
let (w1, book1) = (rows[0]["window"].as_u64().unwrap(), rows[0]["doc"].as_u64().unwrap());
|
||||
assert_eq!((rows[0]["title"].as_str(), rows[1]["active"].as_bool()), (Some("Book1"), Some(true)));
|
||||
|
||||
// Book2 stays active; reads and writes go to Book1's window.
|
||||
ok(&mut s, "set_cell", json!({"cell": "B1", "input": "=A1", "window": w1}));
|
||||
let got = ok(&mut s, "get_cell", json!({"cell": "B1", "doc": book1}));
|
||||
assert!(got.to_string().contains("book one"), "{got}");
|
||||
let book2 = ok(&mut s, "read_range", json!({"range": "A1:B1"}));
|
||||
assert!(!book2.to_string().contains("book one"), "{book2}");
|
||||
let info = ok(&mut s, "inspect_workbook", json!({"window": w1}));
|
||||
assert!(info.to_string().contains("Book1"), "{info}");
|
||||
assert!(fails(&mut s, "get_cell", json!({"cell": "A1", "window": 999})).contains("no open window"));
|
||||
|
||||
// A second window on Book1 gets a numbered title.
|
||||
ok(&mut s, "execute_command", json!({"command": "view.newWindow", "window": w1}));
|
||||
let titles: Vec<String> =
|
||||
ok(&mut s, "list_windows", json!({})).as_array().unwrap().iter().map(|r| r["title"].as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(titles, ["Book1:1", "Book2", "Book1:2"]);
|
||||
}
|
||||
|
||||
+2
-62
@@ -106,26 +106,8 @@ const BORDER_PRESETS: &[&str] = &[
|
||||
"diagonalUp",
|
||||
];
|
||||
|
||||
/// Tools that don't act on one workbook, so they take no `window`/`doc` target.
|
||||
const UNTARGETED: &[&str] = &["list_commands", "list_functions", "list_windows", "new_workbook", "open_workbook", "screenshot"];
|
||||
|
||||
/// All tools, in `tools/list` order. Tools that act on a workbook take an optional `window` or
|
||||
/// `doc` id (from list_windows) and default to the active window.
|
||||
/// All tools, in `tools/list` order.
|
||||
pub fn tool_definitions() -> Vec<Value> {
|
||||
let mut tools = base_tool_definitions();
|
||||
for t in &mut tools {
|
||||
if UNTARGETED.iter().any(|n| t["name"] == *n) {
|
||||
continue;
|
||||
}
|
||||
if let Some(props) = t["inputSchema"]["properties"].as_object_mut() {
|
||||
props.insert("window".into(), int("Window id from list_windows (default: the active window)"));
|
||||
props.insert("doc".into(), int("Workbook id from list_windows: its most recent window (default: the active window)"));
|
||||
}
|
||||
}
|
||||
tools
|
||||
}
|
||||
|
||||
fn base_tool_definitions() -> Vec<Value> {
|
||||
let empty = || obj(json!({}), &[]);
|
||||
vec![
|
||||
// ----- generic -----
|
||||
@@ -143,14 +125,6 @@ fn base_tool_definitions() -> Vec<Value> {
|
||||
),
|
||||
false,
|
||||
),
|
||||
tool(
|
||||
"list_windows",
|
||||
"List windows",
|
||||
"List the open windows: window id, workbook (`doc`) id, title (\"Book1\", or \"Book1:2\" for a workbook's second \
|
||||
window), unsaved changes, active and hidden. Pass a `window` or `doc` id to other tools to act there.",
|
||||
empty(),
|
||||
true,
|
||||
),
|
||||
tool(
|
||||
"list_commands",
|
||||
"List commands",
|
||||
@@ -634,7 +608,6 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<Value, String>
|
||||
exec(b, cmd, p)
|
||||
}
|
||||
"list_commands" => b.call("engine.commands", pick(a, &["search"])),
|
||||
"list_windows" => exec(b, "window.list", json!({})),
|
||||
"inspect_workbook" => b.call("document.inspect", json!({})),
|
||||
"read_range" => b.call("sheet.read", pick(a, &["range", "sheet", "formulas", "formatted"])),
|
||||
"write_range" => exec(b, "range.setValues", pick(a, &["range", "values"])),
|
||||
@@ -665,35 +638,6 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<Value, String>
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends every engine call of one tool to the window its `window`/`doc` argument names.
|
||||
struct Targeted<'a> {
|
||||
inner: &'a mut dyn Backend,
|
||||
target: Map<String, Value>,
|
||||
}
|
||||
|
||||
impl Backend for Targeted<'_> {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
let envelope = if method == "engine.execute" {
|
||||
params
|
||||
} else if gridcraft_engine::find_command(method).is_some() {
|
||||
json!({"command": method, "params": params})
|
||||
} else {
|
||||
return self.inner.call(method, params);
|
||||
};
|
||||
let mut envelope = envelope;
|
||||
if let Some(o) = envelope.as_object_mut() {
|
||||
o.extend(self.target.clone());
|
||||
}
|
||||
self.inner.call("engine.execute", envelope)
|
||||
}
|
||||
fn has_ui(&self) -> bool {
|
||||
self.inner.has_ui()
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
self.inner.describe()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one tool. Failures become `isError` results with a readable message.
|
||||
pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
|
||||
let empty = Map::new();
|
||||
@@ -702,11 +646,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
|
||||
Value::Null => &empty,
|
||||
_ => return ToolResult::error("tool arguments must be a JSON object"),
|
||||
};
|
||||
let target: Map<String, Value> =
|
||||
["window", "doc"].iter().filter_map(|k| a.get(*k).filter(|v| !v.is_null()).map(|v| (k.to_string(), v.clone()))).collect();
|
||||
let r =
|
||||
if target.is_empty() || UNTARGETED.contains(&name) { dispatch(b, name, a) } else { dispatch(&mut Targeted { inner: b, target }, name, a) };
|
||||
match r {
|
||||
match dispatch(b, name, a) {
|
||||
Ok(v) => ToolResult::json(&v),
|
||||
Err(e) => ToolResult::error(format!("{name}: {e}")),
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Workbooks.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use gridcraft_core::DateSystem;
|
||||
use gridcraft_formula::Expr;
|
||||
@@ -148,8 +147,7 @@ pub struct Workbook {
|
||||
pub calc: CalcSettings,
|
||||
#[serde(default, skip_serializing_if = "is_all")]
|
||||
pub show_objects: ShowObjects,
|
||||
/// Read and set with [`Workbook::active_sheet`] and [`Workbook::set_active_sheet`].
|
||||
pub active_sheet: ActiveSheet,
|
||||
pub active_sheet: usize,
|
||||
pub props: DocProps,
|
||||
/// Workbook structure protection.
|
||||
pub protected_structure: bool,
|
||||
@@ -207,57 +205,6 @@ impl Default for Workbook {
|
||||
}
|
||||
}
|
||||
|
||||
/// The active sheet index of a [`Workbook`].
|
||||
///
|
||||
/// Every other part of a workbook value is immutable once shared (the engine keeps versions as
|
||||
/// `Arc<Workbook>` and tells unsaved changes by pointer). The active sheet is the exception: it
|
||||
/// is the view state of the window showing the workbook, and several windows on one workbook
|
||||
/// swap their own sheet into it whenever one of them becomes the one commands act on. Keeping it
|
||||
/// in an atomic lets that swap happen through the shared `Arc` without cloning the workbook.
|
||||
/// Copies (undo versions, a cloned workbook) take the value at the time of the copy.
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
#[serde(from = "usize", into = "usize")]
|
||||
pub struct ActiveSheet(AtomicUsize);
|
||||
|
||||
impl ActiveSheet {
|
||||
pub fn get(&self) -> usize {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
pub fn set(&self, i: usize) {
|
||||
self.0.store(i, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl From<usize> for ActiveSheet {
|
||||
fn from(i: usize) -> ActiveSheet {
|
||||
ActiveSheet(AtomicUsize::new(i))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ActiveSheet> for usize {
|
||||
fn from(a: ActiveSheet) -> usize {
|
||||
a.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for ActiveSheet {
|
||||
fn clone(&self) -> ActiveSheet {
|
||||
ActiveSheet::from(self.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ActiveSheet {
|
||||
fn eq(&self, other: &ActiveSheet) -> bool {
|
||||
self.get() == other.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ActiveSheet {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.get().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Workbook {
|
||||
/// A new workbook with one sheet, "Sheet1".
|
||||
pub fn new() -> Workbook {
|
||||
@@ -269,7 +216,7 @@ impl Workbook {
|
||||
date_system: DateSystem::D1900,
|
||||
calc: CalcSettings::default(),
|
||||
show_objects: ShowObjects::All,
|
||||
active_sheet: ActiveSheet::default(),
|
||||
active_sheet: 0,
|
||||
props: DocProps::default(),
|
||||
protected_structure: false,
|
||||
structure_password: None,
|
||||
@@ -292,17 +239,8 @@ impl Workbook {
|
||||
pub fn sheet_index(&self, name: &str) -> Option<usize> {
|
||||
self.sheets.iter().position(|s| s.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// The index of the sheet the workbook's window shows (the file's active tab).
|
||||
pub fn active_sheet(&self) -> usize {
|
||||
self.active_sheet.get()
|
||||
}
|
||||
/// Changes the active sheet in place, also through a shared `Arc<Workbook>`: it is view state,
|
||||
/// so switching sheets or windows neither copies the workbook nor makes it a new version.
|
||||
pub fn set_active_sheet(&self, i: usize) {
|
||||
self.active_sheet.set(i);
|
||||
}
|
||||
pub fn active(&self) -> Option<&Sheet> {
|
||||
self.sheet(self.active_sheet())
|
||||
self.sheet(self.active_sheet)
|
||||
}
|
||||
/// A fresh sheet name `SheetN` not in use.
|
||||
pub fn next_sheet_name(&self) -> String {
|
||||
|
||||
@@ -9,9 +9,9 @@ description = "GridCraft egui frontend (Excel-style UI); swappable — nothing b
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# The shared capture slot (`craft_ui::capture`) comes from the one craft-libs revision every
|
||||
# craft-libs dependency uses (see the root Cargo.toml).
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b926b5c03e256c86ca10934f58d03f628810b5b7" }
|
||||
# The shared capture slot (`craft_ui::capture`) comes from the same reviewed immutable
|
||||
# craft-libs revision as the desktop's craft-print dependency.
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f" }
|
||||
gridcraft-engine = { workspace = true }
|
||||
gridcraft-chart = { workspace = true }
|
||||
# `monochrome_emoji_fonts` restores the Noto Emoji and emoji-icon faces that 0.37 moved behind
|
||||
@@ -39,7 +39,6 @@ gridcraft-xlsx = { workspace = true, features = ["test-support"] }
|
||||
craft-update = { workspace = true }
|
||||
# The desktop's preferred language for the first-run interface language.
|
||||
sys-locale = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# Read the browser's preferred language for the first-run web interface language.
|
||||
|
||||
@@ -122,7 +122,7 @@ fn main() {
|
||||
app.open_dialog(name, p);
|
||||
}
|
||||
// Page Layout view: edit the first page's centre header (or footer) section.
|
||||
let active = app.session.active().and_then(|d| d.wb.active().cloned().map(|s| (d.wb.active_sheet(), s)));
|
||||
let active = app.session.active().and_then(|d| d.wb.active().cloned().map(|s| (d.wb.active_sheet, s)));
|
||||
if let (Some(part), Some((si, sh))) = (&hf_edit, active) {
|
||||
let zone = gridcraft_engine::paper::HfZone { footer: part == "footer", section: 1 };
|
||||
gridcraft_ui_egui::paper_view::begin(&mut app, si, &sh, (0, 0), zone);
|
||||
|
||||
@@ -957,6 +957,35 @@ pub fn export_as(app: &mut SheetApp, fmt: &str) -> bool {
|
||||
fn options(app: &mut SheetApp, ui: &mut Ui) {
|
||||
let lang = app.ui.language;
|
||||
section(ui, lang, "Options|General");
|
||||
general_options(app, ui, lang);
|
||||
ui.add_space(6.0);
|
||||
let mut formula_bar = app.session.prefs.formula_bar;
|
||||
if ui.checkbox(&mut formula_bar, lang.tr("Show formula bar")).changed() {
|
||||
app.run_or_alert("view.formulaBar", json!({"on": formula_bar}));
|
||||
}
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Options|Editing");
|
||||
let mut autocomplete = app.ui.autocomplete;
|
||||
if ui.checkbox(&mut autocomplete, lang.tr("Enable AutoComplete for cell values")).changed() {
|
||||
app.run_or_alert("options.autoComplete", json!({"on": autocomplete}));
|
||||
}
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Options|Save");
|
||||
let mut autosave = app.ui.autosave;
|
||||
if ui.checkbox(&mut autosave, lang.tr("Save .xlsx workbooks automatically after every change")).changed() {
|
||||
app.toggle_autosave();
|
||||
}
|
||||
let Some(calc) = app.session.active().map(|d| d.wb.calc.clone()) else { return };
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Formulas");
|
||||
ui.label(lang.tr("Workbook calculation"));
|
||||
calc_options(app, ui, lang, &calc);
|
||||
ui.add_space(6.0);
|
||||
dim(ui, lang.tr("Calculation settings are saved with the workbook."));
|
||||
}
|
||||
|
||||
/// The display theme and interface language controls of the General section.
|
||||
fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
|
||||
egui::Grid::new("backstage_options_general").num_columns(2).spacing(vec2(18.0, 10.0)).show(ui, |ui| {
|
||||
let label = ui.label(lang.tr("Display theme"));
|
||||
let mode = app.ui.theme_mode();
|
||||
@@ -993,27 +1022,10 @@ fn options(app: &mut SheetApp, ui: &mut Ui) {
|
||||
.labelled_by(label.id);
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
let mut formula_bar = app.session.prefs.formula_bar;
|
||||
if ui.checkbox(&mut formula_bar, lang.tr("Show formula bar")).changed() {
|
||||
app.run_or_alert("view.formulaBar", json!({"on": formula_bar}));
|
||||
}
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Options|Editing");
|
||||
let mut autocomplete = app.ui.autocomplete;
|
||||
if ui.checkbox(&mut autocomplete, lang.tr("Enable AutoComplete for cell values")).changed() {
|
||||
app.run_or_alert("options.autoComplete", json!({"on": autocomplete}));
|
||||
}
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Options|Save");
|
||||
let mut autosave = app.ui.autosave;
|
||||
if ui.checkbox(&mut autosave, lang.tr("Save .xlsx workbooks automatically after every change")).changed() {
|
||||
app.toggle_autosave();
|
||||
}
|
||||
let Some(calc) = app.session.active().map(|d| d.wb.calc.clone()) else { return };
|
||||
ui.add_space(18.0);
|
||||
section(ui, lang, "Formulas");
|
||||
ui.label(lang.tr("Workbook calculation"));
|
||||
}
|
||||
|
||||
/// The calculation mode, and iterative calculation, of the active workbook.
|
||||
fn calc_options(app: &mut SheetApp, ui: &mut Ui, lang: Language, calc: &gridcraft_engine::model::CalcSettings) {
|
||||
use gridcraft_engine::model::CalcMode;
|
||||
for (mode, id, label) in [
|
||||
(CalcMode::Automatic, "automatic", "Automatic"),
|
||||
@@ -1030,6 +1042,13 @@ fn options(app: &mut SheetApp, ui: &mut Ui) {
|
||||
app.run_or_alert("formulas.calculationOptions", json!({"iterative": iterative}));
|
||||
}
|
||||
// Maximum Iterations and Maximum Change apply only while iteration is on, as in Excel.
|
||||
iteration_options(app, ui, lang, calc, iterative);
|
||||
// TODO: add "Set precision as displayed" here once `formulas.calculationOptions` takes
|
||||
// `precisionAsDisplayed` (PR #1366); the model already stores it.
|
||||
}
|
||||
|
||||
/// Maximum Iterations and Maximum Change, live only while iterative calculation is on.
|
||||
fn iteration_options(app: &mut SheetApp, ui: &mut Ui, lang: Language, calc: &gridcraft_engine::model::CalcSettings, iterative: bool) {
|
||||
ui.add_enabled_ui(iterative, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(24.0);
|
||||
@@ -1070,10 +1089,6 @@ fn options(app: &mut SheetApp, ui: &mut Ui) {
|
||||
});
|
||||
});
|
||||
});
|
||||
// TODO: add "Set precision as displayed" here once `formulas.calculationOptions` takes
|
||||
// `precisionAsDisplayed` (PR #1366); the model already stores it.
|
||||
ui.add_space(6.0);
|
||||
dim(ui, lang.tr("Calculation settings are saved with the workbook."));
|
||||
}
|
||||
|
||||
/// Refuses a typed setting with a message, leaving the workbook as it was. The Enter that
|
||||
|
||||
@@ -78,6 +78,32 @@ pub fn highlight(text: &str, lang: Lang) -> Vec<(Range<usize>, Token)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// End (exclusive, in chars) of the Python string literal opening with quote `c` at char `i`.
|
||||
fn python_string_end(chars: &[(usize, char)], i: usize, c: char) -> usize {
|
||||
let triple = chars.get(i + 1).is_some_and(|(_, d)| *d == c) && chars.get(i + 2).is_some_and(|(_, d)| *d == c);
|
||||
let mut j = if triple { i + 3 } else { i + 1 };
|
||||
loop {
|
||||
match chars.get(j) {
|
||||
None => break,
|
||||
Some((_, '\\')) => j += 2,
|
||||
Some((_, '\n')) if !triple => break,
|
||||
Some((_, d)) if *d == c => {
|
||||
if !triple {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
if chars.get(j + 1).is_some_and(|(_, d)| *d == c) && chars.get(j + 2).is_some_and(|(_, d)| *d == c) {
|
||||
j += 3;
|
||||
break;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
Some(_) => j += 1,
|
||||
}
|
||||
}
|
||||
j.min(chars.len())
|
||||
}
|
||||
|
||||
fn python(text: &str) -> Vec<(Range<usize>, Token)> {
|
||||
let chars: Vec<(usize, char)> = text.char_indices().collect();
|
||||
let end_of = |i: usize| chars.get(i).map(|(b, _)| *b).unwrap_or(text.len());
|
||||
@@ -92,28 +118,7 @@ fn python(text: &str) -> Vec<(Range<usize>, Token)> {
|
||||
out.push((start..end_of(j), Token::Comment));
|
||||
i = j;
|
||||
} else if c == '"' || c == '\'' {
|
||||
let triple = chars.get(i + 1).is_some_and(|(_, d)| *d == c) && chars.get(i + 2).is_some_and(|(_, d)| *d == c);
|
||||
let mut j = if triple { i + 3 } else { i + 1 };
|
||||
loop {
|
||||
match chars.get(j) {
|
||||
None => break,
|
||||
Some((_, '\\')) => j += 2,
|
||||
Some((_, '\n')) if !triple => break,
|
||||
Some((_, d)) if *d == c => {
|
||||
if !triple {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
if chars.get(j + 1).is_some_and(|(_, d)| *d == c) && chars.get(j + 2).is_some_and(|(_, d)| *d == c) {
|
||||
j += 3;
|
||||
break;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
Some(_) => j += 1,
|
||||
}
|
||||
}
|
||||
let j = j.min(chars.len());
|
||||
let j = python_string_end(&chars, i, c);
|
||||
out.push((start..end_of(j), Token::String));
|
||||
i = j;
|
||||
} else if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(|(_, d)| d.is_ascii_digit())) {
|
||||
|
||||
@@ -407,38 +407,6 @@ fn run(app: &mut SheetApp, id: &str, params: Json) -> Result<Json, String> {
|
||||
r
|
||||
}
|
||||
|
||||
/// [`run`] in another window (`window` or `doc` from the request), bringing back the active
|
||||
/// window afterwards unless the command itself switched windows.
|
||||
fn run_in(app: &mut SheetApp, target: gridcraft_engine::Target, id: &str, params: Json) -> Result<Json, String> {
|
||||
let guard = app.session.enter_target(target).map_err(|e| e.to_string())?;
|
||||
let r = run(app, id, params);
|
||||
app.session.leave_target(guard);
|
||||
r
|
||||
}
|
||||
|
||||
/// A command called by its id as the method. Its params may name a `window` or `doc` to act in,
|
||||
/// except for the window commands, whose own params those are.
|
||||
fn direct(app: &mut SheetApp, id: &str, p: &Json, via_app: bool) -> Result<Json, String> {
|
||||
let mut params = p.clone();
|
||||
let target = if gridcraft_engine::windows::is_window_command(id) {
|
||||
gridcraft_engine::Target::Active
|
||||
} else {
|
||||
let t = gridcraft_engine::Target::from_json(p).map_err(|e| e.to_string())?;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.remove("window");
|
||||
o.remove("doc");
|
||||
}
|
||||
t
|
||||
};
|
||||
if via_app {
|
||||
return run_in(app, target, id, params);
|
||||
}
|
||||
let guard = app.session.enter_target(target).map_err(|e| e.to_string())?;
|
||||
let r = app.session.run(id, params);
|
||||
app.session.leave_target(guard);
|
||||
r
|
||||
}
|
||||
|
||||
pub fn inspect(app: &SheetApp, ctx: &egui::Context) -> Json {
|
||||
let r = ctx.content_rect();
|
||||
let v = app.view();
|
||||
@@ -455,8 +423,6 @@ pub fn inspect(app: &SheetApp, ctx: &egui::Context) -> Json {
|
||||
"mode": format!("{:?}", app.session.mode),
|
||||
"documents": app.session.documents().iter().map(|d| json!({"title": d.display_title(), "dirty": d.is_dirty()})).collect::<Vec<_>>(),
|
||||
"activeDocument": app.session.active_index(),
|
||||
"windows": app.session.window_list(),
|
||||
"activeWindow": app.session.active_window(),
|
||||
"perf": {"frameMs": app.perf.frame_ms, "gridMs": app.perf.grid_ms, "fps": app.perf.fps},
|
||||
})
|
||||
}
|
||||
@@ -622,11 +588,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
"engine.execute" | "command" | "ui.menu.invoke" => {
|
||||
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
|
||||
let params = p.get("params").cloned().unwrap_or(json!({}));
|
||||
let target = match gridcraft_engine::Target::from_json(p) {
|
||||
Ok(t) => t,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
wrap(run_in(app, target, id, if params.is_null() { json!({}) } else { params }))
|
||||
wrap(run(app, id, if params.is_null() { json!({}) } else { params }))
|
||||
}
|
||||
"engine.commands" => {
|
||||
let mut v: Vec<Json> = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect();
|
||||
@@ -662,7 +624,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
ok(Json::Array(filter_commands(v, s("search"))))
|
||||
}
|
||||
"engine.journal" => ok(json!(app.session.journal.iter().map(|(id, p)| json!({"command": id, "params": p})).collect::<Vec<_>>())),
|
||||
"document.inspect" | "sheet.read" | "cell.get" | "selection.stats" => wrap(direct(app, method, p, false)),
|
||||
"document.inspect" | "sheet.read" | "cell.get" | "selection.stats" => wrap(app.session.run(method, p.clone())),
|
||||
"ui.inspect" => ok(inspect(app, ctx)),
|
||||
"ui.ribbon" => {
|
||||
app.ui.ribbon_tab = s("tab").unwrap_or("Home").to_string();
|
||||
@@ -711,10 +673,9 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
Some(d) => match d.command {
|
||||
Some(cmd) => {
|
||||
let params = crate::dialogs::build_params(&d);
|
||||
let home = app.ui_window();
|
||||
let r = app.run(cmd, params);
|
||||
if r.is_err() {
|
||||
app.return_dialog(home, d);
|
||||
app.dialog = Some(d);
|
||||
}
|
||||
wrap(r)
|
||||
}
|
||||
@@ -853,7 +814,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
|
||||
ok(Json::Null)
|
||||
}
|
||||
// Anything else that names a command runs it.
|
||||
other if gridcraft_engine::find_command(other).is_some() => wrap(direct(app, other, p, true)),
|
||||
other if gridcraft_engine::find_command(other).is_some() => wrap(run(app, other, p.clone())),
|
||||
other => err(format!("unknown method `{other}`")),
|
||||
};
|
||||
ctx.request_repaint();
|
||||
|
||||
@@ -113,7 +113,7 @@ impl Dialog {
|
||||
pub fn pick_reference(&mut self, cell: CellRef, active_sheet: &str, extend: bool) {
|
||||
let Some(pick) = self.pick.as_mut() else { return };
|
||||
let text = self.values.get(pick.key).and_then(Json::as_str).unwrap_or("").to_string();
|
||||
let mut ed = crate::editor::EditState::new(0, 0, cell, text, true, false);
|
||||
let mut ed = crate::editor::EditState::new(0, cell, text, true, false);
|
||||
ed.caret = pick.caret.min(ed.text.chars().count());
|
||||
ed.point = pick.point;
|
||||
if ed.text.trim().is_empty() {
|
||||
@@ -199,20 +199,6 @@ impl Dialog {
|
||||
}],
|
||||
json!({"shift": "down"}),
|
||||
),
|
||||
"arrangeAll" => Dialog::form(
|
||||
"arrangeAll",
|
||||
"Arrange Windows",
|
||||
"view.arrangeAll",
|
||||
vec![
|
||||
Choice {
|
||||
key: "arrange",
|
||||
label: "Arrange",
|
||||
options: vec![("tiled", "Tiled"), ("horizontal", "Horizontal"), ("vertical", "Vertical"), ("cascade", "Cascade")],
|
||||
},
|
||||
Check { key: "activeWorkbook", label: "Windows of active workbook" },
|
||||
],
|
||||
json!({"arrange": "tiled", "activeWorkbook": false}),
|
||||
),
|
||||
"insertPaste" => Dialog::form(
|
||||
"insertPaste",
|
||||
"Insert Paste",
|
||||
@@ -619,7 +605,7 @@ impl Dialog {
|
||||
}
|
||||
"solver" => {
|
||||
// Starts from the sheet's saved model, else the active cell as objective.
|
||||
let saved = app.session.active().and_then(|doc| gridcraft_engine::cmd::solver::saved_model(&doc.wb, doc.wb.active_sheet()));
|
||||
let saved = app.session.active().and_then(|doc| gridcraft_engine::cmd::solver::saved_model(&doc.wb, doc.wb.active_sheet));
|
||||
let mut values = json!({"objective": active, "goal": "max", "value": "0", "variables": "", "constraints": [], "nonNegative": true, "method": "grg"});
|
||||
if let (Some(m), Some(v)) = (saved.as_ref().and_then(Json::as_object), values.as_object_mut()) {
|
||||
for (k, x) in m {
|
||||
@@ -900,7 +886,7 @@ impl Dialog {
|
||||
// Chart Design › Select Data: data range, series to keep, category axis labels.
|
||||
let id = p("chart").as_u64();
|
||||
let found = app.session.active().and_then(|doc| {
|
||||
let si = doc.wb.active_sheet();
|
||||
let si = doc.wb.active_sheet;
|
||||
let sh = doc.wb.sheet(si)?;
|
||||
let ch = sh.charts.iter().find(|c| Some(u64::from(c.id)) == id)?;
|
||||
let data = gridcraft_chart::resolve(&doc.wb, si, ch);
|
||||
@@ -1268,7 +1254,6 @@ pub(crate) fn build_params(d: &Dialog) -> Json {
|
||||
/// Takes and draws the active dialog, dispatches its body by name, consumes picture-inbox results, runs OK/confirm commands, handles Esc/close and restores the back-dialog stack.
|
||||
pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let Some(mut d) = app.dialog.take() else { return };
|
||||
let home = app.ui_window();
|
||||
if d.name == "pasteSpecial" {
|
||||
paste_special_shortcuts(&mut d, ctx);
|
||||
}
|
||||
@@ -1454,14 +1439,29 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
}
|
||||
"saveChanges" => {
|
||||
ui.label(format!("Do you want to save the changes you made to {}?", d.values.get("title").and_then(Json::as_str).unwrap_or("this workbook")));
|
||||
// Asked while quitting: once answered, the next unsaved workbook is asked about.
|
||||
let quitting = d.values.get("quit").and_then(Json::as_bool) == Some(true);
|
||||
ui.horizontal(|ui| {
|
||||
for (label, answer) in
|
||||
[("Don't Save", crate::SaveAnswer::DontSave), ("Cancel", crate::SaveAnswer::Cancel), ("Save", crate::SaveAnswer::Save)]
|
||||
{
|
||||
if ui.button(label).clicked() && app.answer_save_changes(answer, quitting, ui.ctx()) {
|
||||
open = false;
|
||||
if ui.button("Don't Save").clicked() {
|
||||
app.run_or_alert("file.close", json!({"force": true}));
|
||||
if quitting {
|
||||
app.continue_quit(ui.ctx());
|
||||
}
|
||||
open = false;
|
||||
}
|
||||
if ui.button("Cancel").clicked() {
|
||||
open = false;
|
||||
}
|
||||
// File operations must include the cell the user is still editing (as the File > Save menu item already does).
|
||||
if ui.button("Save").clicked() && app.commit_edit(0, 0, false, false) {
|
||||
app.run_or_alert("file.save", json!({}));
|
||||
if app.session.active().is_some_and(|x| !x.is_dirty()) {
|
||||
app.run_or_alert("file.close", json!({"force": true}));
|
||||
if quitting {
|
||||
app.continue_quit(ui.ctx());
|
||||
}
|
||||
}
|
||||
open = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1546,15 +1546,6 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
} else if confirm {
|
||||
open = false;
|
||||
}
|
||||
if app.ui_window() != home {
|
||||
// A command run from the dialog switched windows: whatever it opened shows in the new
|
||||
// window, and this dialog (or the one it returns to) stays in its own.
|
||||
let keep = if open { Some(d) } else { d.back.take().map(|b| *b) };
|
||||
if let Some(keep) = keep {
|
||||
app.return_dialog(home, keep);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(child) = app.dialog.as_mut() {
|
||||
// The body opened another dialog (Name Manager › New…). It takes over; this one waits
|
||||
// behind it and comes back when it closes, as Excel returns to the Name Manager. Go To
|
||||
@@ -2210,7 +2201,7 @@ fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confir
|
||||
let mut open = true;
|
||||
ok_cancel(ui, confirm, &mut open);
|
||||
if *confirm && let Some(n) = hits.get(d.list_index).and_then(|f| f["name"].as_str()) {
|
||||
let n = app.session.active().map(|doc| crate::formula_locale::completion_name(n, locale, &doc.wb, doc.wb.active_sheet())).unwrap_or(n);
|
||||
let n = app.session.active().map(|doc| crate::formula_locale::completion_name(n, locale, &doc.wb, doc.wb.active_sheet)).unwrap_or(n);
|
||||
let cur = app.editor.as_ref().map(|e| e.text.clone());
|
||||
let text = match cur {
|
||||
Some(t) if t.starts_with('=') => format!("{t}{n}("),
|
||||
@@ -2374,7 +2365,7 @@ fn go_to_entries(app: &SheetApp) -> Vec<String> {
|
||||
app.session
|
||||
.active()
|
||||
.map(|doc| {
|
||||
let mut v = gridcraft_engine::cmd::edit::go_to_names(&doc.wb, doc.wb.active_sheet());
|
||||
let mut v = gridcraft_engine::cmd::edit::go_to_names(&doc.wb, doc.wb.active_sheet);
|
||||
v.extend(doc.go_to_recent.iter().cloned());
|
||||
v
|
||||
})
|
||||
|
||||
@@ -1,297 +0,0 @@
|
||||
//! Desktop: each workbook window is a native window of its own.
|
||||
//!
|
||||
//! The engine owns the windows ([`Session::windows`]); [`DocWindows`] mirrors the visible ones in
|
||||
//! a [`WindowList`] and draws each through [`Viewports`]: the root viewport shows one window and
|
||||
//! every other window is an immediate viewport. Before a window draws, it becomes the engine's
|
||||
//! window and its interface state is swapped in ([`SheetApp::show_window`]); after the frame the
|
||||
//! focused window is active again, so menu commands, scripts and shortcuts outside a window's own
|
||||
//! input go to the window the user worked in last.
|
||||
//!
|
||||
//! Close and quit:
|
||||
//! - A window's close button closes that window (`window.close`): one of several windows on a
|
||||
//! workbook closes without asking; a workbook's last window asks Save / Don't Save / Cancel when
|
||||
//! it has unsaved changes.
|
||||
//! - Quit ([`SheetApp::request_quit`]) asks about each unsaved workbook in its window; Cancel stops.
|
||||
//! - When the root's window closes while others are open, another window moves into the root.
|
||||
//! - With no window left, the app quits, or (macOS) keeps running with its root hidden and the
|
||||
//! menu bar showing until a workbook is created or opened.
|
||||
//!
|
||||
//! [`Session::windows`]: gridcraft_engine::Session::windows
|
||||
|
||||
use craft_window::{CASCADE_STEP, Frame, Rect, Viewports, WindowEvent, WindowId, WindowList, cascade};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::SheetApp;
|
||||
|
||||
/// The native windows (see the module docs).
|
||||
pub struct DocWindows {
|
||||
/// Engine window id per native window.
|
||||
list: WindowList<u64>,
|
||||
viewports: Viewports,
|
||||
/// The builder new windows start from: the root window's size, icon and frame settings.
|
||||
base: egui::ViewportBuilder,
|
||||
/// Quit when the last window closes (Windows, Linux); macOS keeps running without a window.
|
||||
quit_with_last_window: bool,
|
||||
/// The root viewport is hidden because no window is open.
|
||||
root_hidden: bool,
|
||||
}
|
||||
|
||||
impl DocWindows {
|
||||
/// Takes over `app`'s windows. `base` is the root window's builder, used for new windows.
|
||||
pub fn new(app: &mut SheetApp, base: egui::ViewportBuilder, quit_with_last_window: bool) -> DocWindows {
|
||||
app.native_windows = true;
|
||||
// The root window keeps the desktop's frame, so every window does.
|
||||
DocWindows { list: WindowList::new(), viewports: Viewports::new(Frame::Desktop), base, quit_with_last_window, root_hidden: false }
|
||||
}
|
||||
|
||||
/// The platform default for the last window closing: macOS keeps running, others quit.
|
||||
pub fn platform_quits_with_last_window() -> bool {
|
||||
!cfg!(target_os = "macos")
|
||||
}
|
||||
|
||||
/// The native window showing engine window `window`.
|
||||
fn find(&self, window: u64) -> Option<WindowId> {
|
||||
self.list.find(|w| *w == window)
|
||||
}
|
||||
|
||||
/// The engine window drawn in the root viewport.
|
||||
pub fn root_window(&self) -> Option<u64> {
|
||||
self.viewports.root().and_then(|w| self.list.get(w).copied())
|
||||
}
|
||||
|
||||
/// The engine windows that have a native window, in opening order.
|
||||
pub fn shown_windows(&self) -> Vec<u64> {
|
||||
self.list.iter().map(|(_, w)| *w).collect()
|
||||
}
|
||||
|
||||
/// The egui viewport showing engine window `window`.
|
||||
pub fn viewport_of(&self, window: u64) -> Option<egui::ViewportId> {
|
||||
self.find(window).map(|id| self.viewports.viewport_id(id))
|
||||
}
|
||||
|
||||
/// The egui viewport of the focused window, where menu commands that act on input (copy,
|
||||
/// paste, undo in a text box) go.
|
||||
pub fn focused_viewport(&self) -> egui::ViewportId {
|
||||
self.list.active().map(|w| self.viewports.viewport_id(w)).unwrap_or(egui::ViewportId::ROOT)
|
||||
}
|
||||
|
||||
/// Call each frame after [`SheetApp::logic`], also while the root is hidden (eframe runs only
|
||||
/// the logic then): shows windows created or opened by menu commands, files and scripts.
|
||||
pub fn logic(&mut self, app: &mut SheetApp, ctx: &egui::Context) {
|
||||
self.sync(app, ctx);
|
||||
if let Some((arrange, windows)) = app.arrange_windows.take() {
|
||||
self.arrange(ctx, &arrange, &windows);
|
||||
}
|
||||
}
|
||||
|
||||
/// View › Arrange All: moves and sizes the native windows of `windows` (engine ids, the first
|
||||
/// on top or at the top left) over the root window's monitor.
|
||||
fn arrange(&self, ctx: &egui::Context, arrange: &str, windows: &[u64]) {
|
||||
let ids: Vec<WindowId> = windows.iter().filter_map(|w| self.find(*w)).collect();
|
||||
let (monitor, infos) = ctx.input(|i| (i.viewport().monitor_size, i.raw.viewports.clone()));
|
||||
// Platforms that don't report the monitor (Wayland, tests) get a common laptop screen.
|
||||
let size = monitor.filter(|m| m.x > 0.0 && m.y > 0.0).unwrap_or(egui::vec2(1280.0, 800.0));
|
||||
let mut rects = arrange_rects(arrange, ids.len(), Rect::new(0.0, 0.0, size.x, size.y));
|
||||
if arrange == "cascade" {
|
||||
// The active window goes in front: the last step of the cascade.
|
||||
rects.reverse();
|
||||
}
|
||||
for (id, r) in ids.iter().zip(rects) {
|
||||
let vp = self.viewports.viewport_id(*id);
|
||||
// Inner size is what can be set: take off the frame the window has now.
|
||||
let frame = infos.get(&vp).and_then(|v| Some(v.outer_rect?.size() - v.inner_rect?.size())).unwrap_or(egui::Vec2::ZERO);
|
||||
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::OuterPosition(egui::pos2(r.x, r.y)));
|
||||
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::InnerSize((egui::vec2(r.width, r.height) - frame).max(egui::vec2(240.0, 160.0))));
|
||||
}
|
||||
if let Some(first) = ids.first() {
|
||||
self.viewports.focus(ctx, *first);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirrors the engine's visible windows: closed or hidden windows lose their native window
|
||||
/// (the root adopting another), new ones get one, and a window a command activated comes to
|
||||
/// the front. With no window left, quits or hides the root.
|
||||
fn sync(&mut self, app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let visible = visible_windows(app);
|
||||
let gone: Vec<WindowId> = self.list.iter().filter(|(_, w)| !visible.contains(w)).map(|(id, _)| id).collect();
|
||||
let mut root_closed = false;
|
||||
for id in gone {
|
||||
root_closed |= self.viewports.root() == Some(id);
|
||||
self.list.close(id);
|
||||
}
|
||||
if root_closed {
|
||||
// The window the engine brought forward, else the most recently focused.
|
||||
let next = app.session.active_window().and_then(|w| self.find(w)).or_else(|| self.list.active());
|
||||
match next {
|
||||
Some(id) => self.viewports.adopt(ctx, &self.list, id),
|
||||
None => self.viewports.set_root(None),
|
||||
}
|
||||
}
|
||||
for w in visible {
|
||||
if self.find(w).is_none() {
|
||||
self.list.open(w);
|
||||
}
|
||||
}
|
||||
if self.viewports.root().is_none() {
|
||||
let first = app.session.active_window().and_then(|w| self.find(w)).or_else(|| self.list.active());
|
||||
self.viewports.set_root(first);
|
||||
}
|
||||
if self.list.is_empty() {
|
||||
if self.quit_with_last_window {
|
||||
if !app.allow_close {
|
||||
app.allow_close = true;
|
||||
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close);
|
||||
}
|
||||
} else if !self.root_hidden {
|
||||
self.root_hidden = true;
|
||||
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Visible(false));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.root_hidden {
|
||||
self.root_hidden = false;
|
||||
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Visible(true));
|
||||
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus);
|
||||
}
|
||||
// A command or script activated another window: bring its native window forward.
|
||||
if let Some(id) = app.session.active_window().and_then(|w| self.find(w))
|
||||
&& self.list.active() != Some(id)
|
||||
{
|
||||
self.list.focus(id);
|
||||
self.viewports.focus(ctx, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws every window. Call from the root viewport's UI each frame, in place of
|
||||
/// [`SheetApp::ui`].
|
||||
pub fn show(&mut self, app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
self.sync(app, &ctx);
|
||||
let focused = self.list.active().and_then(|id| self.list.get(id).copied());
|
||||
let titles: std::collections::HashMap<u64, String> = self.list.iter().map(|(_, w)| (*w, window_title(app, *w))).collect();
|
||||
let base = &self.base;
|
||||
// The window a command run in some window's UI activated (File › New, Switch Windows, a close).
|
||||
let mut requested: Option<u64> = None;
|
||||
let events = self.viewports.show(
|
||||
ui,
|
||||
&mut self.list,
|
||||
|_, w| base.clone().with_title(titles.get(w).cloned().unwrap_or_default()),
|
||||
|ui, _, w| {
|
||||
app.show_window(*w);
|
||||
// Files dropped on a window open as workbooks (the root's arrive through the app's
|
||||
// raw input hook; a child window's input reaches only its own pass).
|
||||
let dropped: Vec<String> = ui
|
||||
.ctx()
|
||||
.input(|i| i.raw.dropped_files.iter().filter_map(|f| f.path().to_str().map(str::to_string)).filter(|p| !p.is_empty()).collect());
|
||||
for path in dropped {
|
||||
app.open_path(&path);
|
||||
}
|
||||
app.ui(ui);
|
||||
if app.session.active_window() != Some(*w) {
|
||||
requested = app.session.active_window();
|
||||
}
|
||||
},
|
||||
);
|
||||
for event in events {
|
||||
match event {
|
||||
WindowEvent::Focused(_) => {}
|
||||
WindowEvent::CloseRequested(id) => {
|
||||
if let Some(w) = self.close_requested(app, &ctx, id) {
|
||||
requested = Some(w);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let target = requested.or_else(|| self.list.active().and_then(|id| self.list.get(id).copied()));
|
||||
if let Some(target) = target.filter(|w| app.session.window(*w).is_some()) {
|
||||
if requested.is_none()
|
||||
&& let Some(previous) = focused.filter(|p| *p != target && app.session.window(*p).is_some())
|
||||
{
|
||||
// The user moved to another window: the previous window's draft is entered there,
|
||||
// as Enter would. One its workbook refuses stays open in that window.
|
||||
app.enter_window(previous);
|
||||
let _ = app.settle_drafts();
|
||||
}
|
||||
app.enter_window(target);
|
||||
}
|
||||
self.sync(app, &ctx);
|
||||
}
|
||||
|
||||
/// A window's close button. Returns the window to bring forward when the close needs an
|
||||
/// answer (or moved focus); `None` when nothing changed.
|
||||
fn close_requested(&mut self, app: &mut SheetApp, ctx: &egui::Context, id: WindowId) -> Option<u64> {
|
||||
let is_root = self.viewports.root() == Some(id);
|
||||
if app.allow_close {
|
||||
// Quitting: every workbook has been answered for; the root's close ends the app.
|
||||
return None;
|
||||
}
|
||||
if is_root {
|
||||
// eframe would end the app with the root window; closing it is the app's decision.
|
||||
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
let window = *self.list.get(id)?;
|
||||
app.enter_window(window);
|
||||
app.run_or_alert("window.close", json!({"window": window}));
|
||||
app.session.active_window()
|
||||
}
|
||||
}
|
||||
|
||||
/// The windows that get a native window: every window not hidden (View › Hide), or the active one
|
||||
/// when all are hidden, so the app still has a window to unhide them from.
|
||||
fn visible_windows(app: &SheetApp) -> Vec<u64> {
|
||||
let shown: Vec<u64> = app.session.windows().iter().filter(|w| !w.hidden).map(|w| w.id).collect();
|
||||
if shown.is_empty() { app.session.active_window().into_iter().collect() } else { shown }
|
||||
}
|
||||
|
||||
/// A native window's title: the window's ("Book1", "Book1:2"), marked while its workbook has
|
||||
/// unsaved changes.
|
||||
fn window_title(app: &SheetApp, window: u64) -> String {
|
||||
let title = app.session.window_title(window).unwrap_or_default();
|
||||
let dirty = app.session.window(window).and_then(|w| app.session.documents().iter().find(|d| d.uid == w.doc_uid)).is_some_and(|d| d.is_dirty());
|
||||
if dirty { format!("{title} — Edited") } else { title }
|
||||
}
|
||||
|
||||
/// Outer rectangles for `n` windows arranged within `bounds` as View › Arrange All's `arrange`
|
||||
/// says: `tiled` (a grid, the last row's windows widened to fill it), `horizontal` (stacked top
|
||||
/// to bottom), `vertical` (side by side) or `cascade` (each one title bar below and right of the
|
||||
/// previous, wrapping at the edges).
|
||||
pub fn arrange_rects(arrange: &str, n: usize, bounds: Rect) -> Vec<Rect> {
|
||||
if n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
let count = n as f32;
|
||||
match arrange {
|
||||
"horizontal" => {
|
||||
let h = bounds.height / count;
|
||||
(0..n).map(|i| Rect::new(bounds.x, bounds.y + h * i as f32, bounds.width, h)).collect()
|
||||
}
|
||||
"vertical" => {
|
||||
let w = bounds.width / count;
|
||||
(0..n).map(|i| Rect::new(bounds.x + w * i as f32, bounds.y, w, bounds.height)).collect()
|
||||
}
|
||||
"cascade" => {
|
||||
let shift = CASCADE_STEP * (count - 1.0);
|
||||
let size = [(bounds.width - shift).max(bounds.width * 0.5), (bounds.height - shift).max(bounds.height * 0.5)];
|
||||
let mut previous = Rect::new(bounds.x - CASCADE_STEP, bounds.y - CASCADE_STEP, size[0], size[1]);
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
previous = cascade(previous, size, bounds, CASCADE_STEP);
|
||||
previous
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
_ => {
|
||||
let cols = (count.sqrt().ceil() as usize).max(1);
|
||||
let rows = n.div_ceil(cols);
|
||||
let h = bounds.height / rows as f32;
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let (row, col) = (i / cols, i % cols);
|
||||
let in_row = if row + 1 == rows { n - row * cols } else { cols };
|
||||
let w = bounds.width / in_row as f32;
|
||||
Rect::new(bounds.x + w * col as f32, bounds.y + h * row as f32, w, h)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,6 @@ pub const REF_COLOR_COUNT: usize = 8;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EditState {
|
||||
/// The workbook (`DocState::uid`) the draft belongs to: it is drawn and committed only there.
|
||||
pub doc: u64,
|
||||
/// The window it was typed in: switching to another window, even on the same workbook,
|
||||
/// commits it there first (`None` until the app sets it).
|
||||
pub window: Option<u64>,
|
||||
pub sheet: usize,
|
||||
/// Syntax of this edit, captured when it starts (prevents a language switch reinterpreting it).
|
||||
pub locale: gridcraft_engine::formula::FormulaLocale,
|
||||
@@ -44,18 +39,12 @@ pub struct EditState {
|
||||
pub completion: Option<String>,
|
||||
/// Move the caret to the end on the next frame.
|
||||
pub caret_to_end: bool,
|
||||
/// The cell's text when an F2-style edit began. Committing it unchanged leaves the cell alone
|
||||
/// (no undo step, the workbook stays clean). `None` for an edit started by typing.
|
||||
pub original: Option<String>,
|
||||
}
|
||||
|
||||
impl EditState {
|
||||
pub fn new(doc: u64, sheet: usize, cell: CellRef, text: String, enter_mode: bool, from_formula_bar: bool) -> EditState {
|
||||
pub fn new(sheet: usize, cell: CellRef, text: String, enter_mode: bool, from_formula_bar: bool) -> EditState {
|
||||
let caret = text.chars().count();
|
||||
let original = (!enter_mode).then(|| text.clone());
|
||||
EditState {
|
||||
doc,
|
||||
window: None,
|
||||
sheet,
|
||||
locale: Default::default(),
|
||||
cell,
|
||||
@@ -74,7 +63,6 @@ impl EditState {
|
||||
keep_selection: false,
|
||||
caret_to_end: true,
|
||||
completion: None,
|
||||
original,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,7 +384,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn point_mode() {
|
||||
let mut e = EditState::new(1, 0, CellRef::new(0, 0), "=SUM(".into(), true, false);
|
||||
let mut e = EditState::new(0, CellRef::new(0, 0), "=SUM(".into(), true, false);
|
||||
assert!(e.can_point());
|
||||
e.insert_ref("A1");
|
||||
assert_eq!(e.text, "=SUM(A1");
|
||||
@@ -406,13 +394,13 @@ mod tests {
|
||||
e.caret += 1;
|
||||
e.point = None;
|
||||
assert!(e.can_point());
|
||||
let e2 = EditState::new(1, 0, CellRef::new(0, 0), "hello".into(), true, false);
|
||||
let e2 = EditState::new(0, CellRef::new(0, 0), "hello".into(), true, false);
|
||||
assert!(!e2.can_point());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_name_replaces_the_selected_text() {
|
||||
let mut e = EditState::new(1, 0, CellRef::new(0, 0), "=OldName+1".into(), false, false);
|
||||
let mut e = EditState::new(0, CellRef::new(0, 0), "=OldName+1".into(), false, false);
|
||||
e.sync_caret = false;
|
||||
(e.anchor, e.caret) = (8, 1);
|
||||
e.autocomplete = vec!["SUM".into()];
|
||||
@@ -428,12 +416,12 @@ mod tests {
|
||||
#[test]
|
||||
fn autocomplete_and_hints() {
|
||||
let names: Vec<String> = ["SUM", "SUMIF", "SUMPRODUCT", "AVERAGE"].iter().map(|s| s.to_string()).collect();
|
||||
let mut e = EditState::new(1, 0, CellRef::new(0, 0), "=su".into(), true, false);
|
||||
let mut e = EditState::new(0, CellRef::new(0, 0), "=su".into(), true, false);
|
||||
e.update_autocomplete(&names);
|
||||
assert_eq!(e.autocomplete.len(), 3);
|
||||
assert!(e.accept_autocomplete());
|
||||
assert_eq!(e.text, "=SUM(");
|
||||
let e = EditState::new(1, 0, CellRef::new(0, 0), "=IF(A1>0,SUM(B1,".into(), true, false);
|
||||
let e = EditState::new(0, CellRef::new(0, 0), "=IF(A1>0,SUM(B1,".into(), true, false);
|
||||
assert_eq!(e.current_function(), Some(("SUM".into(), 1)));
|
||||
}
|
||||
|
||||
@@ -469,7 +457,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn inserting_a_union_keeps_each_reference_separately_pointed() {
|
||||
let mut edit = EditState::new(1, 0, CellRef::new(0, 0), "=SUM(".into(), true, false);
|
||||
let mut edit = EditState::new(0, CellRef::new(0, 0), "=SUM(".into(), true, false);
|
||||
edit.insert_ref("C:C");
|
||||
edit.append_ref("E:E");
|
||||
assert_eq!(edit.text, "=SUM(C:C,E:E");
|
||||
|
||||
@@ -120,7 +120,7 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
let galley = child.painter().layout(text, font.clone(), color, inner.width());
|
||||
let lines = galley.rows.len();
|
||||
// Each cell's view starts at its top: the offset is kept per cell, not per bar.
|
||||
let shown = app.session.active().map(|d| (d.uid, d.wb.active_sheet(), d.selection.active.row, d.selection.active.col));
|
||||
let shown = app.session.active().map(|d| (d.uid, d.wb.active_sheet, d.selection.active.row, d.selection.active.col));
|
||||
egui::ScrollArea::vertical().id_salt(id.with(("view", shown))).max_height(inner.height()).auto_shrink([false, true]).show(
|
||||
&mut child,
|
||||
|ui| {
|
||||
@@ -169,7 +169,7 @@ fn active_input(app: &SheetApp) -> String {
|
||||
}
|
||||
return sh
|
||||
.cell(anchor)
|
||||
.map(|c| crate::formula_locale::display(&c.input_text(), app.ui.language.formula_locale(), &d.wb, d.wb.active_sheet()))
|
||||
.map(|c| crate::formula_locale::display(&c.input_text(), app.ui.language.formula_locale(), &d.wb, d.wb.active_sheet))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
if let Some(c) = sh.cell(a) {
|
||||
@@ -177,7 +177,7 @@ fn active_input(app: &SheetApp) -> String {
|
||||
return String::new();
|
||||
}
|
||||
return if let Some(f) = &c.formula {
|
||||
let shown = crate::formula_locale::display(&c.input_text(), app.ui.language.formula_locale(), &d.wb, d.wb.active_sheet());
|
||||
let shown = crate::formula_locale::display(&c.input_text(), app.ui.language.formula_locale(), &d.wb, d.wb.active_sheet);
|
||||
// A legacy array formula shows in braces (`{=A1:A2*2}`), as `Cell::bar_text` does.
|
||||
if f.array.is_some() { format!("{{{shown}}}") } else { shown }
|
||||
} else {
|
||||
@@ -218,7 +218,7 @@ fn name_box(app: &mut SheetApp, ui: &mut egui::Ui, t: &Tokens) -> Rect {
|
||||
if !target.is_empty() && target != shown {
|
||||
// A new name for the selection, or a place to go.
|
||||
let is_ref = gridcraft_engine::core::RangeRef::parse(target.split('!').next_back().unwrap_or("")).is_some();
|
||||
let known = app.session.active().is_some_and(|d| d.wb.name(&target, d.wb.active_sheet()).is_some() || d.wb.table(&target).is_some());
|
||||
let known = app.session.active().is_some_and(|d| d.wb.name(&target, d.wb.active_sheet).is_some() || d.wb.table(&target).is_some());
|
||||
let r = if is_ref || known {
|
||||
app.run("edit.goTo", json!({"reference": target}))
|
||||
} else {
|
||||
|
||||
+24
-26
@@ -131,7 +131,7 @@ pub struct Trace {
|
||||
impl Trace {
|
||||
/// A trace of the active cell, just run.
|
||||
pub fn new(app: &SheetApp, items: serde_json::Value) -> Option<Trace> {
|
||||
app.session.active().map(|d| Trace { uid: d.uid, revision: d.revision, sheet: d.wb.active_sheet(), cell: d.selection.active, items })
|
||||
app.session.active().map(|d| Trace { uid: d.uid, revision: d.revision, sheet: d.wb.active_sheet, cell: d.selection.active, items })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -614,7 +614,7 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
app.grid.rect = Some(rect);
|
||||
let Some(d) = app.session.active() else { return };
|
||||
let wb: Arc<Workbook> = d.wb.clone();
|
||||
let si = wb.active_sheet();
|
||||
let si = wb.active_sheet;
|
||||
let Some(sh) = wb.sheet(si) else { return };
|
||||
let sel = d.selection.clone();
|
||||
let place = (d.uid, si);
|
||||
@@ -1828,7 +1828,6 @@ pub(crate) fn paint_selection(
|
||||
// Editing a formula: outline its references instead of the selection.
|
||||
if let Some(ed) = &app.editor
|
||||
&& ed.is_formula()
|
||||
&& app.session.active().is_some_and(|d| d.uid == ed.doc)
|
||||
{
|
||||
let origin = app.session.active().and_then(|d| d.wb.sheet(ed.sheet)).map_or(sh.name.as_str(), |o| o.name.as_str());
|
||||
for (_, _, r, sheet, idx) in crate::editor::formula_refs(&ed.text) {
|
||||
@@ -1887,7 +1886,7 @@ pub(crate) fn paint_selection(
|
||||
}
|
||||
// Marching ants around the copied range.
|
||||
if let Some(clip) = &app.session.clipboard
|
||||
&& app.session.active().is_some_and(|d| d.uid == clip.doc_uid && d.wb.active_sheet() == clip.sheet)
|
||||
&& app.session.active().is_some_and(|d| d.uid == clip.doc_uid && d.wb.active_sheet == clip.sheet)
|
||||
&& range_in_pane(clip.range, rows, cols)
|
||||
{
|
||||
// A multi-area copy marks each area as selected.
|
||||
@@ -2213,7 +2212,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &
|
||||
if primary_clicked
|
||||
&& !resp.drag_started()
|
||||
&& let Some(p) = pos
|
||||
&& let Some((id, act)) = crate::chartview::slicer_click(geo, sh, wb, wb.active_sheet(), p)
|
||||
&& let Some((id, act)) = crate::chartview::slicer_click(geo, sh, wb, wb.active_sheet, p)
|
||||
{
|
||||
app.selected_chart = Some(id);
|
||||
match act {
|
||||
@@ -2423,13 +2422,13 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &
|
||||
&& ed.can_point()
|
||||
{
|
||||
let anchor = if mods.shift && ed.point_at_caret() {
|
||||
ed.point_anchor.filter(|(sheet, _)| *sheet == wb.active_sheet()).map(|(_, cell)| cell).unwrap_or(c)
|
||||
ed.point_anchor.filter(|(sheet, _)| *sheet == wb.active_sheet).map(|(_, cell)| cell).unwrap_or(c)
|
||||
} else {
|
||||
c
|
||||
};
|
||||
let range = RangeRef::new(anchor, c);
|
||||
let text = if range.is_single() { c.a1() } else { range.a1() };
|
||||
let sheet_name = (ed.sheet != wb.active_sheet()).then(|| sh.name.clone());
|
||||
let sheet_name = (ed.sheet != wb.active_sheet).then(|| sh.name.clone());
|
||||
let r = match sheet_name {
|
||||
Some(n) => format!("{}!{text}", gridcraft_engine::formula::quote_sheet(&n)),
|
||||
None => text,
|
||||
@@ -2441,7 +2440,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &
|
||||
}
|
||||
ed.request_focus = true;
|
||||
ed.point_cell = Some(c);
|
||||
ed.point_anchor = Some((wb.active_sheet(), anchor));
|
||||
ed.point_anchor = Some((wb.active_sheet, anchor));
|
||||
app.grid.drag = Drag::Select;
|
||||
app.grid.drag_select = true;
|
||||
if resp.drag_started()
|
||||
@@ -2757,7 +2756,7 @@ fn format_painter_apply(app: &mut SheetApp) {
|
||||
fn point_header(app: &mut SheetApp, wb: &Workbook, sh: &Sheet, range: RangeRef, extend: bool, add: bool) -> bool {
|
||||
let Some(ed) = app.editor.as_mut().filter(|ed| ed.can_point()) else { return false };
|
||||
let edit_sheet = ed.sheet;
|
||||
let active_sheet = wb.active_sheet();
|
||||
let active_sheet = wb.active_sheet;
|
||||
let range = if extend {
|
||||
ed.point
|
||||
.and_then(|point| crate::editor::formula_refs(&ed.text).into_iter().find(|(start, end, ..)| (*start, *end) == point))
|
||||
@@ -2779,8 +2778,7 @@ fn point_header(app: &mut SheetApp, wb: &Workbook, sh: &Sheet, range: RangeRef,
|
||||
range
|
||||
};
|
||||
let reference = range.a1();
|
||||
let reference =
|
||||
if ed.sheet != wb.active_sheet() { format!("{}!{reference}", gridcraft_engine::formula::quote_sheet(&sh.name)) } else { reference };
|
||||
let reference = if ed.sheet != wb.active_sheet { format!("{}!{reference}", gridcraft_engine::formula::quote_sheet(&sh.name)) } else { reference };
|
||||
if add {
|
||||
ed.append_ref(&reference);
|
||||
} else {
|
||||
@@ -2802,13 +2800,13 @@ fn select_to_pointer(app: &mut SheetApp, geo: &Geo, sh: &Sheet, wb: &Workbook, p
|
||||
} else if let Some(ed) = app.editor.as_mut()
|
||||
&& ed.point.is_some()
|
||||
{
|
||||
if let Some(start) = ed.point_anchor.filter(|(sheet, _)| *sheet == wb.active_sheet()).map(|(_, cell)| cell).or(ed.point_cell) {
|
||||
if let Some(start) = ed.point_anchor.filter(|(sheet, _)| *sheet == wb.active_sheet).map(|(_, cell)| cell).or(ed.point_cell) {
|
||||
let range = RangeRef::new(start, cell);
|
||||
let text = if range.is_single() { range.start.a1() } else { range.a1() };
|
||||
let text = if ed.sheet != wb.active_sheet() { format!("{}!{text}", gridcraft_engine::formula::quote_sheet(&sh.name)) } else { text };
|
||||
let text = if ed.sheet != wb.active_sheet { format!("{}!{text}", gridcraft_engine::formula::quote_sheet(&sh.name)) } else { text };
|
||||
ed.insert_ref(&text);
|
||||
ed.point_cell = Some(cell);
|
||||
ed.point_anchor = Some((wb.active_sheet(), start));
|
||||
ed.point_anchor = Some((wb.active_sheet, start));
|
||||
}
|
||||
} else if let Some(d) = app.session.active() {
|
||||
// Read the current anchor: starting a drag may have just replaced the selection.
|
||||
@@ -3216,7 +3214,7 @@ fn editor_width(text_w: f32, cell_w: f32, size: f32) -> f32 {
|
||||
/// Draws the in-cell editor, growing and wrapping with its text, mirroring for right-to-left sheets, choosing contrasting caret ink and clipping cells hidden under frozen panes.
|
||||
fn in_cell_editor(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet, wb: &Workbook) {
|
||||
let Some(ed) = app.editor.as_ref() else { return };
|
||||
if app.view_key() != Some((ed.doc, ed.sheet)) {
|
||||
if ed.sheet != wb.active_sheet {
|
||||
return;
|
||||
}
|
||||
let cell = ed.cell;
|
||||
@@ -3303,7 +3301,7 @@ fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool)
|
||||
let Some((col, row, at)) = app.grid.filter_menu else { return };
|
||||
let Some(d) = app.session.active() else { return };
|
||||
let wb = d.wb.clone();
|
||||
let si = wb.active_sheet();
|
||||
let si = wb.active_sheet;
|
||||
let Some(sh) = wb.sheet(si) else { return };
|
||||
let _ = geo;
|
||||
// Tables get an autofilter on demand.
|
||||
@@ -3517,7 +3515,7 @@ fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
/// and no cell does while the PivotTable's Enable show details option is off.
|
||||
fn show_details_offered(app: &mut SheetApp) -> bool {
|
||||
let Some(d) = app.session.active() else { return false };
|
||||
let (si, at) = (d.wb.active_sheet(), d.selection.active);
|
||||
let (si, at) = (d.wb.active_sheet, d.selection.active);
|
||||
let Some((pi, pt)) = d.wb.active().and_then(|sh| sh.pivots.iter().enumerate().find(|(_, pt)| pt.last_range.is_some_and(|r| r.contains(at))))
|
||||
else {
|
||||
return false;
|
||||
@@ -3549,14 +3547,14 @@ const DATE_FILL_MODES: [(&str, &str); 4] = [("Fill Days", "days"), ("Fill Weekda
|
||||
|
||||
/// The fill modes the menus list for a fill from `src` on the active sheet.
|
||||
fn fill_modes(app: &SheetApp, src: RangeRef) -> Vec<(&'static str, &'static str)> {
|
||||
let dates = app.session.active().is_some_and(|d| gridcraft_engine::fill::starts_with_date(&d.wb, d.wb.active_sheet(), src));
|
||||
let dates = app.session.active().is_some_and(|d| gridcraft_engine::fill::starts_with_date(&d.wb, d.wb.active_sheet, src));
|
||||
FILL_MODES.into_iter().chain(DATE_FILL_MODES.into_iter().filter(|_| dates)).collect()
|
||||
}
|
||||
|
||||
/// Remembers the fill just made so the Auto Fill Options button can offer the other ways.
|
||||
fn set_fill_tag(app: &mut SheetApp, src: RangeRef, target: RangeRef) {
|
||||
app.grid.fill_tag =
|
||||
app.session.active().map(|d| FillTag { src, target, uid: d.uid, sheet: d.wb.active_sheet(), revision: d.revision, undo_len: d.undo.len() });
|
||||
app.session.active().map(|d| FillTag { src, target, uid: d.uid, sheet: d.wb.active_sheet, revision: d.revision, undo_len: d.undo.len() });
|
||||
}
|
||||
|
||||
/// The Auto Fill Options button below the bottom-right corner of cells a left-drag of the fill
|
||||
@@ -3568,7 +3566,7 @@ fn fill_options_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet
|
||||
let Some(tag) = app.grid.fill_tag.clone() else { return };
|
||||
let current = app.session.active().is_some_and(|d| {
|
||||
d.uid == tag.uid
|
||||
&& d.wb.active_sheet() == tag.sheet
|
||||
&& d.wb.active_sheet == tag.sheet
|
||||
&& d.revision == tag.revision
|
||||
&& d.undo.len() == tag.undo_len
|
||||
&& d.selection.ranges.len() == 1
|
||||
@@ -3767,12 +3765,12 @@ pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, exte
|
||||
)
|
||||
})
|
||||
.unwrap_or(from);
|
||||
ed.point_anchor.filter(|(sheet, _)| *sheet == d.wb.active_sheet()).map(|(_, cell)| cell).unwrap_or(inferred_anchor)
|
||||
ed.point_anchor.filter(|(sheet, _)| *sheet == d.wb.active_sheet).map(|(_, cell)| cell).unwrap_or(inferred_anchor)
|
||||
} else {
|
||||
to
|
||||
};
|
||||
let text = if extend { RangeRef::new(anchor, to).a1() } else { to.a1() };
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sheet = d.wb.active_sheet;
|
||||
ed.insert_ref(&text);
|
||||
ed.point_cell = Some(to);
|
||||
ed.point_anchor = Some((sheet, anchor));
|
||||
@@ -3921,7 +3919,7 @@ fn list_picker(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool)
|
||||
let Some(c) = app.grid.list_picker else { return };
|
||||
let Some(d) = app.session.active() else { return };
|
||||
let wb = d.wb.clone();
|
||||
let si = wb.active_sheet();
|
||||
let si = wb.active_sheet;
|
||||
let Some(sh) = wb.sheet(si) else { return };
|
||||
let Some(dv) = sh.validations.iter().find(|x| x.ranges.iter().any(|r| r.contains(c))).cloned() else {
|
||||
app.grid.list_picker = None;
|
||||
@@ -4059,7 +4057,7 @@ fn is_checkbox(sh: &Sheet, app: &SheetApp) -> bool {
|
||||
|
||||
fn paint_pages(app: &mut SheetApp, p: &Painter, geo: &Geo, sh: &Sheet) {
|
||||
let Some(d) = app.session.active() else { return };
|
||||
let key = (d.uid, d.revision, d.wb.active_sheet());
|
||||
let key = (d.uid, d.revision, d.wb.active_sheet);
|
||||
if app.grid.pages.as_ref().is_none_or(|(k, _)| *k != key) {
|
||||
let pages: Vec<(RangeRef, u32)> = app
|
||||
.session
|
||||
@@ -4692,7 +4690,7 @@ mod trace_arrow_tests {
|
||||
/// The arrows `paint_overlays` draws on the active sheet, as (tail, head) points.
|
||||
fn arrows(app: &mut SheetApp) -> (Geo, Vec<(Pos2, Pos2)>) {
|
||||
let d = app.session.active().unwrap();
|
||||
let (wb, si, sel) = (d.wb.clone(), d.wb.active_sheet(), d.selection.clone());
|
||||
let (wb, si, sel) = (d.wb.clone(), d.wb.active_sheet, d.selection.clone());
|
||||
let sh = wb.sheet(si).unwrap();
|
||||
let geo = Geo::new(sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0)), vec2(0.0, 0.0));
|
||||
let ctx = egui::Context::default();
|
||||
@@ -4716,7 +4714,7 @@ mod trace_arrow_tests {
|
||||
|
||||
fn center(app: &SheetApp, geo: &Geo, cell: &str) -> Pos2 {
|
||||
let d = app.session.active().unwrap();
|
||||
let sh = d.wb.sheet(d.wb.active_sheet()).unwrap();
|
||||
let sh = d.wb.sheet(d.wb.active_sheet).unwrap();
|
||||
geo.cell_rect(sh, CellRef::parse(cell).unwrap()).center()
|
||||
}
|
||||
|
||||
|
||||
@@ -356,7 +356,7 @@ pub const SEQUENCES: &[(&str, Entry)] = &[
|
||||
("WVH", Entry::Finish(Action::Command("view.headings"))), // Excel: Toggle Headings; containment(Headings)
|
||||
("WVN", Entry::Finish(Action::Pending("view.navigation"))), // pending; Excel: Navigation; Navigation pane; reserved until the command lands
|
||||
("WVR", Entry::Finish(Action::Command("view.ruler"))), // Excel: Ruler
|
||||
("WW", Entry::Finish(Action::Control("view.switchWindows"))), // Excel: Switch Windows
|
||||
("WW", Entry::Finish(Action::Command("view.switchWindows"))), // Excel: Switch Windows
|
||||
("JAM", Entry::Finish(Action::Command("chart.formatSelection"))), // Excel: Chart format: Format Selection pane; containment(Format Selection)
|
||||
("JCA", Entry::Finish(Action::Command("chart.addElement"))), // Excel: Chart: Add Chart Element; containment(Add Chart Element)
|
||||
("JCC", Entry::Finish(Action::Command("chart.changeType"))), // Excel: Chart: Change Chart Type; containment(Change Chart Type)
|
||||
|
||||
@@ -2471,7 +2471,7 @@
|
||||
},
|
||||
{
|
||||
"seq": "WW",
|
||||
"kind": "control",
|
||||
"kind": "command",
|
||||
"target": "view.switchWindows",
|
||||
"excel": "Switch Windows",
|
||||
"note": ""
|
||||
|
||||
+54
-295
@@ -15,8 +15,6 @@ pub mod control;
|
||||
mod craft_fonts_policy;
|
||||
pub mod credits;
|
||||
pub mod dialogs;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod doc_windows;
|
||||
pub mod editor;
|
||||
mod floating_pictures;
|
||||
pub mod fonts;
|
||||
@@ -40,9 +38,6 @@ pub mod theme;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod updates_ui;
|
||||
pub mod widgets;
|
||||
mod window_ui;
|
||||
|
||||
pub use window_ui::WindowUi;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -183,34 +178,6 @@ pub struct Notice {
|
||||
pub action: Option<(String, String)>,
|
||||
}
|
||||
|
||||
/// An answer to the Save Changes question.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SaveAnswer {
|
||||
Save,
|
||||
DontSave,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// One open window, as View › Switch Windows and the macOS Window menu list it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct OpenWindow {
|
||||
/// The window's id, the `window` param of `view.switchWindows`.
|
||||
pub window: u64,
|
||||
/// Its workbook's `DocState::uid`.
|
||||
pub doc: u64,
|
||||
pub title: String,
|
||||
pub dirty: bool,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
impl OpenWindow {
|
||||
/// The title ("Book1", or "Book1:2" for a workbook's second window), with a bullet after it
|
||||
/// while the workbook has unsaved changes.
|
||||
pub fn label(&self) -> String {
|
||||
if self.dirty { format!("{} •", self.title) } else { self.title.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Host services the platform shell provides (file pickers, opening URLs).
|
||||
#[derive(Default)]
|
||||
pub struct Services {
|
||||
@@ -284,7 +251,6 @@ pub struct SheetApp {
|
||||
pub ui: UiState,
|
||||
/// The window chrome to draw (see [`Chrome`]).
|
||||
pub chrome: Chrome,
|
||||
/// Scroll position per (window id, sheet index).
|
||||
pub views: HashMap<(u64, usize), SheetView>,
|
||||
pub editor: Option<editor::EditState>,
|
||||
pub text_box_editor: Option<text_box::EditState>,
|
||||
@@ -317,8 +283,8 @@ pub struct SheetApp {
|
||||
prepared_fonts: bool,
|
||||
/// Workbook fonts bound into the current font set; a change rebinds (installed fonts only).
|
||||
fonts_bound: Vec<String>,
|
||||
/// The open workbooks' (uid, revision), folded, that `fonts_bound` was computed for, so the
|
||||
/// style tables are walked only when a workbook changes.
|
||||
/// The (doc uid, revision) `fonts_bound` was computed for, so the style table is walked only
|
||||
/// when the workbook changes.
|
||||
fonts_seen: (u64, u64),
|
||||
/// Set while a font-set change is pending activation: skip this frame's paint, like the
|
||||
/// startup `fonts_ready` gate (egui applies new definitions at the next pass).
|
||||
@@ -362,20 +328,6 @@ pub struct SheetApp {
|
||||
/// Every unsaved workbook has been answered for quitting (or `app.quit` asked): the next
|
||||
/// window close goes through.
|
||||
pub allow_close: bool,
|
||||
/// View › Switch Windows opens its list on the next frame the View tab draws (asked for by a
|
||||
/// key tip, the command search or a menu, possibly while another tab was showing).
|
||||
pub(crate) open_switch_windows: bool,
|
||||
/// The window whose interface state the per-window fields above hold (see [`WindowUi`]).
|
||||
ui_window: Option<u64>,
|
||||
/// The other windows' interface state, by window id.
|
||||
parked: HashMap<u64, WindowUi>,
|
||||
/// Each window is a native window of its own ([`doc_windows`] on the desktop): a window's
|
||||
/// close button closes that window, and quitting is asked for separately. Without it (web,
|
||||
/// tests, embedding hosts) one window shows the active workbook window, and its close button
|
||||
/// quits.
|
||||
pub native_windows: bool,
|
||||
/// View › Arrange All's layout and windows, waiting for the native windows to move.
|
||||
pub arrange_windows: Option<(String, Vec<u64>)>,
|
||||
/// The update check, the startup prompt and a running self-update (desktop only).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: updates_ui::Runtime,
|
||||
@@ -432,11 +384,6 @@ impl SheetApp {
|
||||
tab_run: None,
|
||||
started: now_ms(),
|
||||
allow_close: false,
|
||||
open_switch_windows: false,
|
||||
ui_window: None,
|
||||
parked: HashMap::new(),
|
||||
native_windows: false,
|
||||
arrange_windows: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: Default::default(),
|
||||
}
|
||||
@@ -469,15 +416,14 @@ impl SheetApp {
|
||||
self.fonts_rebind = false;
|
||||
self.fonts_han = Some(theme::HanOrder::of(self.ui.language));
|
||||
self.fonts_bound = self.used_fonts();
|
||||
self.fonts_seen = self.fonts_key();
|
||||
self.fonts_seen = self.session.active().map(|d| (d.uid, d.revision)).unwrap_or((0, 0));
|
||||
}
|
||||
|
||||
/// The font names the open workbooks use: every style's font plus the theme's heading/body
|
||||
/// fonts. These are the families [`fonts`] binds an installed file for. Every workbook's, as
|
||||
/// each may be showing in a window of its own.
|
||||
/// The font names the active workbook uses: every style's font plus the theme's heading/body
|
||||
/// fonts. These are the families [`fonts`] binds an installed file for.
|
||||
pub fn used_fonts(&self) -> Vec<String> {
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for d in self.session.documents() {
|
||||
if let Some(d) = self.session.active() {
|
||||
names.extend(d.wb.styles.iter().map(|(_, s)| s.font.name.clone()));
|
||||
names.push(d.wb.theme.major_font.clone());
|
||||
names.push(d.wb.theme.minor_font.clone());
|
||||
@@ -487,14 +433,6 @@ impl SheetApp {
|
||||
names
|
||||
}
|
||||
|
||||
/// The open workbooks' (uid, revision), folded: [`Self::used_fonts`] changes only with it.
|
||||
fn fonts_key(&self) -> (u64, u64) {
|
||||
self.session
|
||||
.documents()
|
||||
.iter()
|
||||
.fold((0u64, 0u64), |(uid, rev), d| (uid.wrapping_mul(31).wrapping_add(d.uid), rev.wrapping_mul(31).wrapping_add(d.revision)))
|
||||
}
|
||||
|
||||
/// Runs an engine command (or a UI command) and handles UI requests it makes.
|
||||
pub fn run(&mut self, id: &str, params: Json) -> Result<Json, String> {
|
||||
let r = self.run_command(id, params);
|
||||
@@ -508,52 +446,37 @@ impl SheetApp {
|
||||
}
|
||||
|
||||
fn run_command(&mut self, id: &str, params: Json) -> Result<Json, String> {
|
||||
let switches_window = id.starts_with("window.")
|
||||
|| matches!(id, "view.newWindow" | "view.hideWindow" | "view.unhideWindow")
|
||||
|| (id == "view.switchWindows" && ["window", "doc"].iter().any(|k| params.get(*k).is_some_and(|d| !d.is_null())));
|
||||
if id.starts_with("file.") || switches_window {
|
||||
self.settle_drafts()?;
|
||||
}
|
||||
if matches!(id, "file.save" | "file.saveAs" | "file.saveBytes") {
|
||||
self.store_view_state();
|
||||
}
|
||||
if matches!(
|
||||
id,
|
||||
"sheet.activate"
|
||||
| "sheet.next"
|
||||
| "sheet.previous"
|
||||
| "sheet.move"
|
||||
| "sheet.hide"
|
||||
| "sheet.unhide"
|
||||
| "home.insertSheet"
|
||||
| "home.deleteSheet"
|
||||
| "edit.undo"
|
||||
| "edit.redo"
|
||||
| "object.delete"
|
||||
| "object.move"
|
||||
) {
|
||||
if id.starts_with("file.")
|
||||
|| matches!(
|
||||
id,
|
||||
"window.activate"
|
||||
| "sheet.activate"
|
||||
| "sheet.next"
|
||||
| "sheet.previous"
|
||||
| "sheet.move"
|
||||
| "sheet.hide"
|
||||
| "sheet.unhide"
|
||||
| "view.newWindow"
|
||||
| "view.hideWindow"
|
||||
| "view.unhideWindow"
|
||||
| "home.insertSheet"
|
||||
| "home.deleteSheet"
|
||||
| "edit.undo"
|
||||
| "edit.redo"
|
||||
| "object.delete"
|
||||
| "object.move"
|
||||
)
|
||||
{
|
||||
self.commit_text_box_edit()?;
|
||||
}
|
||||
if let Some(r) = self.run_ui_command(id, ¶ms) {
|
||||
return r;
|
||||
}
|
||||
let before = self.session.active_window();
|
||||
let r = self.session.run(id, params);
|
||||
if id.starts_with("file.") && self.session.active_window() != before {
|
||||
// File › New or Open from the Backstage view: the window it was in goes back to its sheet.
|
||||
self.backstage = None;
|
||||
}
|
||||
// Requests the command made (a dialog, a draft) belong to the window it left active.
|
||||
self.follow_active_window();
|
||||
self.after_engine();
|
||||
if id == "view.arrangeAll"
|
||||
&& self.native_windows
|
||||
&& let Ok(r) = &r
|
||||
{
|
||||
let arrange = r.get("arrange").and_then(Json::as_str).unwrap_or("tiled").to_string();
|
||||
let windows = r.get("windows").and_then(Json::as_array).map(|a| a.iter().filter_map(Json::as_u64).collect()).unwrap_or_default();
|
||||
self.arrange_windows = Some((arrange, windows));
|
||||
}
|
||||
// The new chart is selected, as after inserting any object, so Delete removes it, not its data.
|
||||
if id == "insert.chart"
|
||||
&& let Ok(r) = &r
|
||||
@@ -682,19 +605,8 @@ impl SheetApp {
|
||||
if id == "insert.recommendedCharts" && params.get("type").is_none() {
|
||||
return self.open_dialog("recommendedCharts", json!({}));
|
||||
}
|
||||
// Switch Windows with no window named (key tip, command search) opens the View tab's
|
||||
// list to choose from; programmatic callers of `run` get the list back.
|
||||
if id == "view.switchWindows" && ["window", "doc"].iter().all(|k| params.get(*k).is_none_or(Json::is_null)) {
|
||||
self.ui.ribbon_tab = "View".into();
|
||||
self.ui.ribbon_collapsed = false;
|
||||
self.open_switch_windows = true;
|
||||
return;
|
||||
}
|
||||
match self.run(id, params) {
|
||||
// A refused cell draft already shows its own message (with the rule's title).
|
||||
Err(e) if self.message.as_ref().is_some_and(|(_, m)| *m == e) => {}
|
||||
Err(e) => self.alert(e),
|
||||
Ok(_) => {}
|
||||
if let Err(e) = self.run(id, params) {
|
||||
self.alert(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -723,8 +635,6 @@ impl SheetApp {
|
||||
|
||||
/// Shows a command error: a toast for an unavailable command, else a message box.
|
||||
fn alert(&mut self, e: String) {
|
||||
// Shown in the window the user ends up in, also after a command that switched windows.
|
||||
self.follow_active_window();
|
||||
if e.contains("is not available right now") {
|
||||
self.toast = Some((e, now_ms()));
|
||||
} else {
|
||||
@@ -884,8 +794,6 @@ impl SheetApp {
|
||||
|
||||
/// Picks up requests commands made (dialogs, edit mode…).
|
||||
pub fn after_engine(&mut self) {
|
||||
// The requests belong to the window the command left active.
|
||||
self.follow_active_window();
|
||||
for req in self.session.take_ui_requests() {
|
||||
match req {
|
||||
UiRequest::Dialog(name, params) => self.open_dialog(&name, params),
|
||||
@@ -894,7 +802,7 @@ impl SheetApp {
|
||||
let text = text.map(|text| {
|
||||
self.session
|
||||
.active()
|
||||
.map(|d| formula_locale::display_template(&text, self.ui.language.formula_locale(), &d.wb, d.wb.active_sheet()))
|
||||
.map(|d| formula_locale::display_template(&text, self.ui.language.formula_locale(), &d.wb, d.wb.active_sheet))
|
||||
.unwrap_or(text)
|
||||
});
|
||||
self.begin_edit(text, false);
|
||||
@@ -1012,9 +920,6 @@ impl SheetApp {
|
||||
/// most important one (a preserved VBA project outranks, say, a skipped optional part).
|
||||
/// Kept deliberately generic: any open-time warning can reach the user this way.
|
||||
pub fn show_open_warnings(&mut self, r: &Json) {
|
||||
// The opened workbook's window shows them, however it was opened (a script may have run
|
||||
// `file.open` on the session directly).
|
||||
self.follow_active_window();
|
||||
let Some(list) = r.get("warnings").and_then(Json::as_array) else {
|
||||
self.notice = None;
|
||||
return;
|
||||
@@ -1045,36 +950,16 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The open windows in order, for the Switch Windows lists.
|
||||
pub fn open_windows(&self) -> Vec<OpenWindow> {
|
||||
let active = self.session.active_window();
|
||||
self.session
|
||||
.windows()
|
||||
.iter()
|
||||
.filter_map(|w| {
|
||||
let d = self.session.documents().iter().find(|d| d.uid == w.doc_uid)?;
|
||||
let title = self.session.window_title(w.id)?;
|
||||
Some(OpenWindow { window: w.id, doc: d.uid, title, dirty: d.is_dirty(), active: active == Some(w.id) })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The active workbook and sheet: what drafts, text boxes and picture targets belong to.
|
||||
pub fn view_key(&self) -> Option<(u64, usize)> {
|
||||
self.session.active().map(|d| (d.uid, d.wb.active_sheet()))
|
||||
}
|
||||
|
||||
/// The active window and sheet: each window scrolls on its own.
|
||||
fn scroll_key(&self) -> Option<(u64, usize)> {
|
||||
Some((self.session.active_window()?, self.session.active()?.wb.active_sheet()))
|
||||
self.session.active().map(|d| (d.uid, d.wb.active_sheet))
|
||||
}
|
||||
|
||||
pub fn view(&self) -> SheetView {
|
||||
self.scroll_key().and_then(|k| self.views.get(&k).copied()).unwrap_or_else(|| self.saved_view())
|
||||
self.view_key().and_then(|k| self.views.get(&k).copied()).unwrap_or_else(|| self.saved_view())
|
||||
}
|
||||
|
||||
pub fn view_mut(&mut self) -> Option<&mut SheetView> {
|
||||
let k = self.scroll_key()?;
|
||||
let k = self.view_key()?;
|
||||
let saved = self.saved_view();
|
||||
Some(self.views.entry(k).or_insert(saved))
|
||||
}
|
||||
@@ -1096,11 +981,10 @@ impl SheetApp {
|
||||
/// cell to the engine so a save writes them (`sheetView topLeftCell`). Normal view only:
|
||||
/// Page Layout view scrolls over pages, not cells.
|
||||
pub fn store_view_state(&mut self) {
|
||||
let window = self.session.active_window();
|
||||
let Some(d) = self.session.active_mut() else { return };
|
||||
let mut tops = Vec::new();
|
||||
for (&(w, si), v) in &self.views {
|
||||
let Some(sh) = d.wb.sheets.get(si).filter(|sh| Some(w) == window && sh.view == gridcraft_engine::model::SheetViewMode::Normal) else {
|
||||
for (&(uid, si), v) in &self.views {
|
||||
let Some(sh) = d.wb.sheets.get(si).filter(|sh| uid == d.uid && sh.view == gridcraft_engine::model::SheetViewMode::Normal) else {
|
||||
continue;
|
||||
};
|
||||
let (fr, fc) = sh.freeze.unwrap_or((0, 0));
|
||||
@@ -1137,7 +1021,7 @@ impl SheetApp {
|
||||
String::new()
|
||||
} else {
|
||||
match sh.cell(at) {
|
||||
Some(c) if c.formula.is_some() => formula_locale::display(&c.input_text(), locale, &d.wb, d.wb.active_sheet()),
|
||||
Some(c) if c.formula.is_some() => formula_locale::display(&c.input_text(), locale, &d.wb, d.wb.active_sheet),
|
||||
_ => gridcraft_engine::display::edit_text(&d.wb, sh, at),
|
||||
}
|
||||
};
|
||||
@@ -1145,8 +1029,7 @@ impl SheetApp {
|
||||
Some(t) => (t, true),
|
||||
None => (current.clone(), false),
|
||||
};
|
||||
let mut ed = editor::EditState::new(d.uid, d.wb.active_sheet(), at, text, replace, from_formula_bar);
|
||||
ed.window = self.session.active_window();
|
||||
let mut ed = editor::EditState::new(d.wb.active_sheet, at, text, replace, from_formula_bar);
|
||||
ed.locale = locale;
|
||||
if replace && self.ui.autocomplete && !ed.is_formula() {
|
||||
ed.completion = editor::column_completion(sh, at, &ed.text);
|
||||
@@ -1156,63 +1039,13 @@ impl SheetApp {
|
||||
}
|
||||
|
||||
/// Commits the edit; `then` moves the selection (dr, dc) afterwards.
|
||||
///
|
||||
/// The draft goes into the window and workbook it was typed in. If another window is
|
||||
/// showing, that window stays active afterwards; a draft its own workbook refuses
|
||||
/// (validation, a bad formula) brings its window back to the front with the draft still open.
|
||||
pub fn commit_edit(&mut self, dr: i64, dc: i64, array: bool, fill_selection: bool) -> bool {
|
||||
let Some((doc, window)) = self.editor.as_ref().map(|ed| (ed.doc, ed.window)) else { return true };
|
||||
if !self.draft_elsewhere() {
|
||||
return self.commit_edit_here(dr, dc, array, fill_selection);
|
||||
}
|
||||
// Its window, or (when that window closed) its workbook's most recent one.
|
||||
let Some(owner) = window.filter(|w| self.session.window(*w).is_some()).or_else(|| self.session.doc_window(doc)) else {
|
||||
self.cancel_edit();
|
||||
return true;
|
||||
};
|
||||
let back = self.session.active_window();
|
||||
self.session.activate_window(owner);
|
||||
if !self.commit_edit_here(dr, dc, array, fill_selection) {
|
||||
// Refused: its window stays in front with the draft open and the reason shown.
|
||||
return false;
|
||||
}
|
||||
if let Some(back) = back {
|
||||
self.session.activate_window(back);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The cell draft belongs to a window or workbook other than the one showing.
|
||||
fn draft_elsewhere(&self) -> bool {
|
||||
self.editor.as_ref().is_some_and(|ed| {
|
||||
self.session.active().map(|d| d.uid) != Some(ed.doc) || ed.window.is_some_and(|w| self.session.active_window() != Some(w))
|
||||
})
|
||||
}
|
||||
|
||||
/// Commits the cell and text-box drafts, as Enter would, before a command that can show
|
||||
/// another workbook or write this one to a file, so a draft never lands in another workbook.
|
||||
/// A draft its workbook refuses stays open with the reason shown, and the command doesn't run.
|
||||
pub(crate) fn settle_drafts(&mut self) -> Result<(), String> {
|
||||
if !self.commit_edit(0, 0, false, false) {
|
||||
return Err(self.message.as_ref().map(|(_, m)| m.clone()).unwrap_or_else(|| "The cell being edited can't be entered.".into()));
|
||||
}
|
||||
self.commit_text_box_edit()
|
||||
}
|
||||
|
||||
fn commit_edit_here(&mut self, dr: i64, dc: i64, array: bool, fill_selection: bool) -> bool {
|
||||
let Some(ed) = self.editor.take() else { return true };
|
||||
self.session.mode = gridcraft_engine::Mode::Ready;
|
||||
let text = match &ed.completion {
|
||||
Some(full) if full.to_lowercase().starts_with(&ed.text.to_lowercase()) => full.clone(),
|
||||
_ => ed.text.clone(),
|
||||
};
|
||||
// F2 then Enter (or a file command) on an untouched draft: nothing to write.
|
||||
if !fill_selection && !array && ed.original.as_ref() == Some(&text) {
|
||||
if dr != 0 || dc != 0 {
|
||||
self.move_after_enter(dr, dc);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
let text = match self.session.active().map(|d| formula_locale::canonical(&text, ed.locale, &d.wb, ed.sheet, ed.cell)) {
|
||||
Some(Ok(text)) => text,
|
||||
Some(Err(error)) => {
|
||||
@@ -1237,7 +1070,7 @@ impl SheetApp {
|
||||
self.toast = Some((msg, now_ms()));
|
||||
}
|
||||
// Point mode can leave another sheet active; the edit belongs to the sheet it started on.
|
||||
if self.session.active().is_some_and(|d| d.wb.active_sheet() != ed.sheet)
|
||||
if self.session.active().is_some_and(|d| d.wb.active_sheet != ed.sheet)
|
||||
&& let Err(e) = self.session.run("sheet.activate", json!({"sheet": ed.sheet}))
|
||||
{
|
||||
self.message = Some(("GridCraft".into(), clean_error(&e)));
|
||||
@@ -1298,7 +1131,7 @@ impl SheetApp {
|
||||
let multi = self.session.active().is_some_and(|d| !d.selection.is_single_cell());
|
||||
// Any other move (arrows, clicks, another sheet) leaves the selection off the cell the
|
||||
// last Tab landed on, which ends the run.
|
||||
let here = self.session.active().map(|d| (d.uid, d.wb.active_sheet(), d.selection.active));
|
||||
let here = self.session.active().map(|d| (d.uid, d.wb.active_sheet, d.selection.active));
|
||||
let run = self.tab_run.take().filter(|&(uid, sheet, _, at)| here == Some((uid, sheet, at)));
|
||||
if multi {
|
||||
let fwd = dr > 0 || dc > 0;
|
||||
@@ -1311,7 +1144,7 @@ impl SheetApp {
|
||||
if dr == 0 && dc != 0 {
|
||||
let start = run.map(|r| r.2);
|
||||
self.tab_run = self.session.active().and_then(|d| {
|
||||
let (uid, sheet) = (d.uid, d.wb.active_sheet());
|
||||
let (uid, sheet) = (d.uid, d.wb.active_sheet);
|
||||
let col = start.or(here.map(|h| h.2.col))?;
|
||||
Some((uid, sheet, col, d.selection.active))
|
||||
});
|
||||
@@ -1345,7 +1178,7 @@ impl SheetApp {
|
||||
/// Holds back a window close (the close button, Alt+F4, the OS quitting the app) while a
|
||||
/// workbook has unsaved changes, and asks about them first.
|
||||
fn guard_window_close(&mut self, ctx: &egui::Context) {
|
||||
if self.native_windows || self.allow_close || !ctx.input(|i| i.viewport().close_requested()) {
|
||||
if self.allow_close || !ctx.input(|i| i.viewport().close_requested()) {
|
||||
return;
|
||||
}
|
||||
// A cell still being edited is part of the workbook, as for File › Close.
|
||||
@@ -1366,75 +1199,21 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks about the next unsaved workbook before quitting, in its window, or closes the app
|
||||
/// once none is left.
|
||||
/// Asks about the next unsaved workbook before quitting, or closes the window once none is left.
|
||||
pub(crate) fn continue_quit(&mut self, ctx: &egui::Context) {
|
||||
let dirty = self.session.documents().iter().find(|d| d.is_dirty()).map(|d| d.uid);
|
||||
match dirty.and_then(|uid| self.session.doc_window(uid)) {
|
||||
Some(window) => {
|
||||
// Its window comes forward (the native window too: see `doc_windows`).
|
||||
self.enter_window(window);
|
||||
match self.session.documents().iter().position(|d| d.is_dirty()) {
|
||||
Some(i) => {
|
||||
self.session.set_active(i);
|
||||
let title = self.session.active().map(|d| d.display_title()).unwrap_or_default();
|
||||
self.open_dialog("saveChanges", json!({"title": title, "quit": true}));
|
||||
}
|
||||
None => {
|
||||
self.allow_close = true;
|
||||
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close);
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the Save Changes question about the active workbook (its buttons). While quitting,
|
||||
/// the next unsaved workbook is asked about once this one is answered; Cancel stops the quit.
|
||||
/// Returns whether the question is settled: Save keeps it open when the cell being edited
|
||||
/// can't be entered.
|
||||
pub fn answer_save_changes(&mut self, answer: SaveAnswer, quitting: bool, ctx: &egui::Context) -> bool {
|
||||
match answer {
|
||||
SaveAnswer::Cancel => {}
|
||||
SaveAnswer::DontSave => {
|
||||
self.run_or_alert("file.close", json!({"force": true, "document": true}));
|
||||
if quitting {
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
}
|
||||
SaveAnswer::Save => {
|
||||
// File operations include the cell still being edited, as File › Save does.
|
||||
if !self.commit_edit(0, 0, false, false) {
|
||||
return false;
|
||||
}
|
||||
self.run_or_alert("file.save", json!({}));
|
||||
if self.session.active().is_some_and(|x| !x.is_dirty()) {
|
||||
self.run_or_alert("file.close", json!({"force": true, "document": true}));
|
||||
if quitting {
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Quit (the macOS app menu, ⌘Q): commits every window's cell draft as Enter would, then asks
|
||||
/// about each unsaved workbook in its window; Cancel on any of them stops the quit. A draft its
|
||||
/// workbook refuses stops the quit too, with its window in front and the reason shown.
|
||||
pub fn request_quit(&mut self, ctx: &egui::Context) {
|
||||
while let Some(window) = self.parked_window_with_draft() {
|
||||
self.enter_window(window);
|
||||
if self.settle_drafts().is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if self.settle_drafts().is_err() {
|
||||
return;
|
||||
}
|
||||
if let Some(d) = self.dialog.as_mut().filter(|d| d.name() == "saveChanges") {
|
||||
// Already asking about a workbook (File › Close): answering it goes on to quit.
|
||||
d.values.insert("quit".into(), json!(true));
|
||||
return;
|
||||
}
|
||||
self.continue_quit(ctx);
|
||||
}
|
||||
|
||||
/// Per-frame logic (control channel, screenshots). Call before `ui`.
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
self.ensure_text_width(ctx);
|
||||
@@ -1473,12 +1252,9 @@ impl SheetApp {
|
||||
self.autosave(ctx);
|
||||
self.update_title(ctx);
|
||||
self.request_hidden_paint(ctx);
|
||||
// One window always shows a workbook, unless each workbook has a native window of its own
|
||||
// (`doc_windows` decides what having none left means).
|
||||
if self.session.active().is_none() && !self.native_windows {
|
||||
if self.session.active().is_none() {
|
||||
self.session.new_workbook();
|
||||
}
|
||||
self.follow_active_window();
|
||||
}
|
||||
|
||||
/// Installs the text-width closure once, on the first frame.
|
||||
@@ -1534,9 +1310,9 @@ impl SheetApp {
|
||||
|
||||
/// Binds the workbook's installed fonts once the background scan has finished. Adding fonts
|
||||
/// re-applies the font set, which egui activates at the next pass, so skip this frame's paint
|
||||
/// (same one-frame cost as startup). Only when an open workbook changed.
|
||||
/// (same one-frame cost as startup). Only when the workbook changed.
|
||||
fn rebind_workbook_fonts(&mut self, ctx: &egui::Context) {
|
||||
let seen = self.fonts_key();
|
||||
let seen = self.session.active().map(|d| (d.uid, d.revision)).unwrap_or((0, 0));
|
||||
if seen == self.fonts_seen {
|
||||
return;
|
||||
}
|
||||
@@ -1576,10 +1352,9 @@ impl SheetApp {
|
||||
ctx.options_mut(|o| o.zoom_with_keyboard = false);
|
||||
}
|
||||
// egui closes the window on Ctrl+Q (and with Shift or Alt held too) without asking to save
|
||||
// (#1443). Excel for Windows has no such key (Ctrl+Q is Quick Analysis). With a native
|
||||
// window per workbook egui's Cmd+Q would close only the window it was typed in: the menu
|
||||
// bar's Quit item has the key instead (it asks about unsaved workbooks first).
|
||||
if (ctx.os() != egui::os::OperatingSystem::Mac || self.native_windows) && ctx.options(|o| !o.quit_shortcuts.is_empty()) {
|
||||
// (#1443). Excel for Windows has no such key (Ctrl+Q is Quick Analysis); macOS keeps Cmd+Q,
|
||||
// the app's Quit there.
|
||||
if ctx.os() != egui::os::OperatingSystem::Mac && ctx.options(|o| !o.quit_shortcuts.is_empty()) {
|
||||
ctx.options_mut(|o| o.quit_shortcuts.clear());
|
||||
}
|
||||
let zoom = self.ui.zoom_factor();
|
||||
@@ -1653,10 +1428,6 @@ impl SheetApp {
|
||||
/// Window title, next to the close/autosave state: `ViewportCommand::Title` is valid outside a
|
||||
/// pass and a control-channel rename while hidden updates it on return.
|
||||
fn update_title(&mut self, ctx: &egui::Context) {
|
||||
// Native windows get theirs from `doc_windows`.
|
||||
if self.native_windows {
|
||||
return;
|
||||
}
|
||||
let Some(d) = self.session.active() else { return };
|
||||
let title = format!("{}{}", d.display_title(), if d.is_dirty() { " — Edited" } else { "" });
|
||||
if self.grid.last_title.as_deref() != Some(title.as_str()) {
|
||||
@@ -1729,15 +1500,7 @@ impl SheetApp {
|
||||
return;
|
||||
}
|
||||
let t0 = now_ms();
|
||||
// A script may have switched windows since the last frame.
|
||||
self.follow_active_window();
|
||||
text_box::before_ui(self, &ctx);
|
||||
// Another window came forward without going through a command (which settles drafts
|
||||
// first): the draft goes into its own window instead of floating over this one. If its
|
||||
// workbook refuses it, its window comes back to the front with the draft open.
|
||||
if self.draft_elsewhere() {
|
||||
self.commit_edit(0, 0, false, false);
|
||||
}
|
||||
// The language the widgets translate with this frame (see `i18n::current`).
|
||||
i18n::set_current(&ctx, self.ui.language);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1778,10 +1541,7 @@ impl SheetApp {
|
||||
dialogs::show(self, &ctx);
|
||||
widgets::message_box(self, &ctx);
|
||||
widgets::toast(self, &ctx);
|
||||
// Requests are admitted in `logic`, for the root viewport, so only its pass issues them.
|
||||
if ctx.viewport_id() == egui::ViewportId::ROOT {
|
||||
control::issue_screenshots(self, &ctx);
|
||||
}
|
||||
control::issue_screenshots(self, &ctx);
|
||||
if !ctx.input(|i| i.focused) {
|
||||
// Nothing else to do.
|
||||
}
|
||||
@@ -1798,8 +1558,7 @@ impl SheetApp {
|
||||
// same frame must not offer it again (grid sizing calls `ui` more than once per frame);
|
||||
// provenance is the injected pass number, so only a pass that missed input handling is
|
||||
// re-offered by `raw_input_hook`.
|
||||
// Synthetic input reaches the root viewport only (`raw_input_hook`), so its pass consumes it.
|
||||
if self.synthetic_pending && ctx.viewport_id() == egui::ViewportId::ROOT {
|
||||
if self.synthetic_pending {
|
||||
self.synthetic.pop_front();
|
||||
self.synthetic_pending = false;
|
||||
self.synthetic_injected_at_pass = None;
|
||||
|
||||
@@ -235,7 +235,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) {
|
||||
});
|
||||
});
|
||||
ui.collapsing("Series", |ui| {
|
||||
let data = app.session.active().map(|d| gridcraft_chart::resolve(&d.wb, d.wb.active_sheet(), &chart));
|
||||
let data = app.session.active().map(|d| gridcraft_chart::resolve(&d.wb, d.wb.active_sheet, &chart));
|
||||
for (i, s) in chart.series.iter().enumerate() {
|
||||
let name = data.as_ref().and_then(|d| d.series.get(i)).map(|x| x.name.clone()).unwrap_or_else(|| format!("Series {}", i + 1));
|
||||
let col =
|
||||
|
||||
@@ -280,14 +280,14 @@ pub(crate) fn paint_headers_footers(app: &SheetApp, ui: &egui::Ui, p: &Painter,
|
||||
pub(crate) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &Geo, sh: &Sheet, wb: &Workbook) {
|
||||
// Leaving the sheet or the view commits.
|
||||
if let Some(e) = &app.grid.hf_edit
|
||||
&& (e.sheet != wb.active_sheet() || sh.view != SheetViewMode::PageLayout || geo.paper.is_none())
|
||||
&& (e.sheet != wb.active_sheet || sh.view != SheetViewMode::PageLayout || geo.paper.is_none())
|
||||
{
|
||||
commit(app);
|
||||
}
|
||||
let Some(pg) = geo.paper.clone() else { return };
|
||||
ruler_margins(app, ui, geo, &pg, sh, wb.active_sheet());
|
||||
ruler_margins(app, ui, geo, &pg, sh, wb.active_sheet);
|
||||
if std::mem::take(&mut app.grid.hf_start) {
|
||||
begin(app, wb.active_sheet(), sh, (pg.data_rows.0, pg.data_cols.0), HfZone { footer: false, section: 1 });
|
||||
begin(app, wb.active_sheet, sh, (pg.data_rows.0, pg.data_cols.0), HfZone { footer: false, section: 1 });
|
||||
}
|
||||
if resp.clicked_by(egui::PointerButton::Primary)
|
||||
&& let Some(p) = ui.input(|i| i.pointer.interact_pos())
|
||||
@@ -295,7 +295,7 @@ pub(crate) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
|
||||
let (x, y) =
|
||||
(geo.scroll.x as f64 + ((p.x - geo.cells.left()) / geo.z) as f64, geo.scroll.y as f64 + ((p.y - geo.cells.top()) / geo.z) as f64);
|
||||
match pg.hf_zone_at(x, y) {
|
||||
Some((page, zone)) if geo.cells.contains(p) => begin(app, wb.active_sheet(), sh, page, zone),
|
||||
Some((page, zone)) if geo.cells.contains(p) => begin(app, wb.active_sheet, sh, page, zone),
|
||||
_ => {
|
||||
// A click anywhere else ends the edit; the grid then handles the click.
|
||||
if app.grid.hf_edit.is_some() {
|
||||
|
||||
@@ -2080,7 +2080,7 @@ fn formulas(app: &mut SheetApp, ui: &mut Ui) {
|
||||
{
|
||||
let locale = app.ui.language.formula_locale();
|
||||
let name =
|
||||
app.session.active().map(|d| crate::formula_locale::completion_name(n, locale, &d.wb, d.wb.active_sheet())).unwrap_or(n);
|
||||
app.session.active().map(|d| crate::formula_locale::completion_name(n, locale, &d.wb, d.wb.active_sheet)).unwrap_or(n);
|
||||
let desc = crate::formula_locale::description(n, locale, app.ui.language).unwrap_or_default();
|
||||
if ui.button(name).on_hover_text(desc).clicked() {
|
||||
app.run_or_alert("formulas.insertFunction", json!({"name": n}));
|
||||
@@ -2109,7 +2109,7 @@ fn formulas(app: &mut SheetApp, ui: &mut Ui) {
|
||||
// The menu lists the names Paste Names lists; clicking one runs `formulas.useInFormula`, which puts it at the caret.
|
||||
// Listed when the menu opens, and again only after the workbook changes.
|
||||
let cache = egui::Id::unique("gridcraft.use_in_formula_names");
|
||||
let key = app.session.active().map(|d| (d.uid, d.revision, d.wb.active_sheet()));
|
||||
let key = app.session.active().map(|d| (d.uid, d.revision, d.wb.active_sheet));
|
||||
let cached = ui.ctx().data(|m| m.get_temp::<(Option<(u64, u64, usize)>, std::sync::Arc<Vec<String>>)>(cache)).filter(|(k, _)| *k == key);
|
||||
let names = match cached {
|
||||
Some((_, names)) => names,
|
||||
@@ -2513,16 +2513,6 @@ fn view(app: &mut SheetApp, ui: &mut Ui) {
|
||||
act(app, "view.zoomToSelection", json!({"viewWidth": r.width(), "viewHeight": r.height()}));
|
||||
}
|
||||
sep(ui);
|
||||
let __k = big_button(ui, Icon::NewFile, "New\nWindow", "New Window", false);
|
||||
control_keytip(app, ui, &__k, "view.newWindow");
|
||||
if __k.clicked() {
|
||||
act(app, "view.newWindow", json!({}));
|
||||
}
|
||||
let __k = big_button(ui, Icon::Table, "Arrange\nAll", "Arrange All", false);
|
||||
control_keytip(app, ui, &__k, "view.arrangeAll");
|
||||
if __k.clicked() {
|
||||
app.open_dialog("arrangeAll", json!({}));
|
||||
}
|
||||
let fp = big_button(ui, Icon::Freeze, "Freeze\nPanes", "Freeze Panes", true);
|
||||
for sequence in
|
||||
keytip_table::group_extension(app.keytips.prefix().unwrap_or_default(), &["view.freezePanes", "view.freezeTopRow", "view.freezeFirstColumn"])
|
||||
@@ -2541,7 +2531,6 @@ fn view(app: &mut SheetApp, ui: &mut Ui) {
|
||||
],
|
||||
);
|
||||
});
|
||||
switch_windows(app, ui);
|
||||
ui.vertical(|ui| {
|
||||
let label_response = ui.label(lang.tr("Display theme"));
|
||||
let mode = app.ui.theme_mode();
|
||||
@@ -2606,24 +2595,6 @@ fn view(app: &mut SheetApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// View › Switch Windows: the open workbooks, the active one checked and unsaved ones marked;
|
||||
/// choosing one brings it forward.
|
||||
fn switch_windows(app: &mut SheetApp, ui: &mut Ui) {
|
||||
let anchor = big_button(ui, Icon::Book, "Switch\nWindows", "Switch Windows", true);
|
||||
anchor.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), "Switch Windows"));
|
||||
control_keytip(app, ui, &anchor, "view.switchWindows");
|
||||
let forced = std::mem::take(&mut app.open_switch_windows) | invoke(app, "view.switchWindows");
|
||||
egui::Popup::menu(&anchor).open_memory(popup_command(forced, anchor.clicked())).show(|ui| {
|
||||
for w in app.open_windows() {
|
||||
let label = theme::available_text(ui, &format!("{}{}", if w.active { "✓ " } else { " " }, w.label()));
|
||||
if ui.add(egui::Button::selectable(w.active, label).min_size(vec2(220.0, 22.0))).clicked() {
|
||||
act(app, "view.switchWindows", json!({"window": w.window}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn automate(app: &mut SheetApp, ui: &mut Ui) {
|
||||
if big_button(ui, Icon::Script, "Macros", "Macros and scripts in this workbook (Alt+F8)", false).clicked() {
|
||||
app.open_dialog("macros", json!({}));
|
||||
|
||||
@@ -115,7 +115,7 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) {
|
||||
let all = crate::widgets::icon_button(ui, Icon::SheetList, t.text_dim, app.ui.language.tr("All sheets"), vec2(24.0, 24.0));
|
||||
all.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, app.ui.language.tr("All sheets")));
|
||||
let items = app.session.active().map(|d| navigator_items(&d.wb.sheets)).unwrap_or_default();
|
||||
let active = app.session.active().map(|d| d.wb.active_sheet().to_string()).unwrap_or_default();
|
||||
let active = app.session.active().map(|d| d.wb.active_sheet.to_string()).unwrap_or_default();
|
||||
let rows: Vec<(&str, String)> = items.iter().map(|(i, name)| (i.as_str(), name.clone())).collect();
|
||||
if let crate::ribbon::ComboResult::Picked(i) = crate::ribbon::editable_combo(ui, &all, "sheet_navigator", &active, &rows, false)
|
||||
&& let Ok(i) = i.parse::<usize>()
|
||||
@@ -135,7 +135,7 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| s.visibility == Visibility::Visible)
|
||||
.map(|(i, s)| (i, s.name.clone(), s.tab_color.and_then(|c| c.resolve(&d.wb.theme)), i == d.wb.active_sheet()))
|
||||
.map(|(i, s)| (i, s.name.clone(), s.tab_color.and_then(|c| c.resolve(&d.wb.theme)), i == d.wb.active_sheet))
|
||||
.collect();
|
||||
// Keep worksheet tabs in their own horizontally scrollable viewport. As in Excel, the
|
||||
// tabs get up to 60% of the bar and the grid's horizontal scrollbar the rest; a strip
|
||||
@@ -148,7 +148,7 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) {
|
||||
};
|
||||
// Reveal the selected sheet after navigation or layout changes, but
|
||||
// allow browsing other tabs without snapping back on every frame.
|
||||
let reveal_key = egui::Id::unique((d.uid, d.wb.active_sheet(), &sheets, tabs_width.to_bits()));
|
||||
let reveal_key = egui::Id::unique((d.uid, d.wb.active_sheet, &sheets, tabs_width.to_bits()));
|
||||
let reveal_id = ui.scope_id().with("worksheet_tabs_reveal");
|
||||
let reveal_active = ui.ctx().data_mut(|data| {
|
||||
let changed = data.get_temp::<egui::Id>(reveal_id) != Some(reveal_key);
|
||||
@@ -352,7 +352,7 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) {
|
||||
if !d.calc.circular.is_empty() {
|
||||
ui.add_space(12.0);
|
||||
// Only a loop on the active sheet is named, so the address needs no sheet.
|
||||
let label = match d.calc.circular.iter().find(|(si, _)| *si == d.wb.active_sheet()) {
|
||||
let label = match d.calc.circular.iter().find(|(si, _)| *si == d.wb.active_sheet) {
|
||||
Some((_, c)) => format!("Circular References: {}", c.a1()),
|
||||
None => "Circular References".to_owned(),
|
||||
};
|
||||
@@ -586,11 +586,11 @@ mod tests {
|
||||
let mut app = crate::SheetApp::new(session, Default::default());
|
||||
app.begin_edit(Some("99".into()), false);
|
||||
activate_sheet(&mut app, 1);
|
||||
assert_eq!(app.session.active().unwrap().wb.active_sheet(), 0, "a value the validation stops must not leave its sheet");
|
||||
assert_eq!(app.session.active().unwrap().wb.active_sheet, 0, "a value the validation stops must not leave its sheet");
|
||||
assert!(app.editor.is_some(), "the edit stays open to be corrected");
|
||||
app.editor.as_mut().unwrap().text = "7".into();
|
||||
activate_sheet(&mut app, 1);
|
||||
assert_eq!(app.session.active().unwrap().wb.active_sheet(), 1, "the corrected value commits and the sheet changes");
|
||||
assert_eq!(app.session.active().unwrap().wb.active_sheet, 1, "the corrected value commits and the sheet changes");
|
||||
let a1 = gridcraft_engine::core::CellRef::parse("A1").unwrap();
|
||||
assert!(app.session.active().unwrap().wb.sheet(0).unwrap().cell(a1).is_some(), "the value lands on the first sheet");
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ impl SheetApp {
|
||||
id,
|
||||
text: shape.text.clone(),
|
||||
uid: d.uid,
|
||||
sheet: d.wb.active_sheet(),
|
||||
sheet: d.wb.active_sheet,
|
||||
original: shape.text.clone(),
|
||||
request_focus: true,
|
||||
rect: None,
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
//! The interface state each window keeps for itself.
|
||||
//!
|
||||
//! [`SheetApp`]'s per-window fields (the cell draft, dialog, Backstage view, grid gestures…) hold
|
||||
//! the state of one window: the engine's active window. Every other window's state is parked in a
|
||||
//! [`WindowUi`] and swapped in when that window is activated or drawn, the way the engine swaps a
|
||||
//! window's selection and sheet into its workbook. So a draft, a dialog or a message stays in the
|
||||
//! window it belongs to.
|
||||
|
||||
use gridcraft_engine::core::CellRef;
|
||||
|
||||
use crate::{Notice, SheetApp, backstage, dialogs, editor, grid, keytips, text_box};
|
||||
|
||||
/// One window's parked interface state (see the module docs).
|
||||
#[derive(Default)]
|
||||
pub struct WindowUi {
|
||||
editor: Option<editor::EditState>,
|
||||
text_box_editor: Option<text_box::EditState>,
|
||||
dialog: Option<dialogs::Dialog>,
|
||||
backstage: Option<backstage::Backstage>,
|
||||
message: Option<(String, String)>,
|
||||
toast: Option<(String, f64)>,
|
||||
notice: Option<Notice>,
|
||||
grid: grid::GridState,
|
||||
name_box: Option<String>,
|
||||
keytips: keytips::KeyTips,
|
||||
selected_chart: Option<u32>,
|
||||
tab_run: Option<(u64, usize, u32, CellRef)>,
|
||||
open_switch_windows: bool,
|
||||
/// The status bar's Ready/Enter/Edit, which follows the window's cell draft.
|
||||
mode: gridcraft_engine::Mode,
|
||||
}
|
||||
|
||||
impl WindowUi {
|
||||
/// A new window's state. The last border, fill and font colour picked carry over, as they are
|
||||
/// the user's recent choices rather than the window's.
|
||||
fn fresh(like: &grid::GridState) -> WindowUi {
|
||||
WindowUi {
|
||||
grid: grid::GridState {
|
||||
last_border: like.last_border.clone(),
|
||||
last_fill: like.last_fill.clone(),
|
||||
last_font_color: like.last_font_color.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SheetApp {
|
||||
/// Exchanges the per-window fields with `w`. Destructured in full, so a field added to
|
||||
/// [`WindowUi`] can't be left out of the swap.
|
||||
fn swap_window_ui(&mut self, w: &mut WindowUi) {
|
||||
let WindowUi {
|
||||
editor,
|
||||
text_box_editor,
|
||||
dialog,
|
||||
backstage,
|
||||
message,
|
||||
toast,
|
||||
notice,
|
||||
grid,
|
||||
name_box,
|
||||
keytips,
|
||||
selected_chart,
|
||||
tab_run,
|
||||
open_switch_windows,
|
||||
mode,
|
||||
} = w;
|
||||
std::mem::swap(&mut self.editor, editor);
|
||||
std::mem::swap(&mut self.text_box_editor, text_box_editor);
|
||||
std::mem::swap(&mut self.dialog, dialog);
|
||||
std::mem::swap(&mut self.backstage, backstage);
|
||||
std::mem::swap(&mut self.message, message);
|
||||
std::mem::swap(&mut self.toast, toast);
|
||||
std::mem::swap(&mut self.notice, notice);
|
||||
std::mem::swap(&mut self.grid, grid);
|
||||
std::mem::swap(&mut self.name_box, name_box);
|
||||
std::mem::swap(&mut self.keytips, keytips);
|
||||
std::mem::swap(&mut self.selected_chart, selected_chart);
|
||||
std::mem::swap(&mut self.tab_run, tab_run);
|
||||
std::mem::swap(&mut self.open_switch_windows, open_switch_windows);
|
||||
std::mem::swap(&mut self.session.mode, mode);
|
||||
}
|
||||
|
||||
/// The window whose interface state is in the per-window fields.
|
||||
pub fn ui_window(&self) -> Option<u64> {
|
||||
self.ui_window
|
||||
}
|
||||
|
||||
/// Brings the per-window fields in line with the engine's active window, after a command (or
|
||||
/// a script) switched windows: the previous window's state is parked, the active one's swapped
|
||||
/// in (a window never seen before starts fresh). A closed window's state is dropped.
|
||||
pub fn follow_active_window(&mut self) {
|
||||
let active = self.session.active_window();
|
||||
if active == self.ui_window {
|
||||
return;
|
||||
}
|
||||
let Some(previous) = self.ui_window else {
|
||||
// The first window: the fields are already its state.
|
||||
self.ui_window = active;
|
||||
return;
|
||||
};
|
||||
let mut outgoing = WindowUi::fresh(&self.grid);
|
||||
self.swap_window_ui(&mut outgoing);
|
||||
if self.session.window(previous).is_some() {
|
||||
self.parked.insert(previous, outgoing);
|
||||
}
|
||||
if let Some(mut incoming) = active.and_then(|w| self.parked.remove(&w)) {
|
||||
self.swap_window_ui(&mut incoming);
|
||||
}
|
||||
self.ui_window = active;
|
||||
let session = &self.session;
|
||||
self.parked.retain(|w, _| session.window(*w).is_some());
|
||||
}
|
||||
|
||||
/// Activates window `id` (it becomes the most recently active) with its interface state.
|
||||
pub fn enter_window(&mut self, id: u64) {
|
||||
self.session.activate_window(id);
|
||||
self.follow_active_window();
|
||||
}
|
||||
|
||||
/// Makes window `id` and its interface state current while it is drawn, without changing
|
||||
/// which window counts as most recently active.
|
||||
pub fn show_window(&mut self, id: u64) {
|
||||
self.session.show_window(id);
|
||||
self.follow_active_window();
|
||||
}
|
||||
|
||||
/// Puts back a dialog that was taken out of window `home`'s fields while it ran. A command
|
||||
/// run from the dialog may have switched windows meanwhile; the dialog stays in the window it
|
||||
/// was opened in (dropped if that window closed).
|
||||
pub(crate) fn return_dialog(&mut self, home: Option<u64>, d: dialogs::Dialog) {
|
||||
if home == self.ui_window {
|
||||
self.dialog = Some(d);
|
||||
} else if let Some(w) = home.and_then(|h| self.parked.get_mut(&h))
|
||||
&& w.dialog.is_none()
|
||||
{
|
||||
w.dialog = Some(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a window other than the current one has a cell or text-box draft open.
|
||||
pub fn parked_window_with_draft(&self) -> Option<u64> {
|
||||
self.parked.iter().filter(|(_, w)| w.editor.is_some() || w.text_box_editor.is_some()).map(|(id, _)| *id).min()
|
||||
}
|
||||
}
|
||||
@@ -1,422 +0,0 @@
|
||||
//! One native window per workbook window: each window keeps its own interface state, and closing
|
||||
//! or quitting asks about unsaved workbooks only when a workbook would close.
|
||||
//!
|
||||
//! The windows are drawn through a test backend that, like eframe, runs each immediate viewport
|
||||
//! as a nested pass with its own input, so a close button can be pressed on one window.
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use egui::{Context, RawInput, ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
|
||||
use gridcraft_engine::{Session, core::CellRef, core::Value};
|
||||
use gridcraft_ui_egui::doc_windows::DocWindows;
|
||||
use gridcraft_ui_egui::{SaveAnswer, SheetApp};
|
||||
use serde_json::json;
|
||||
|
||||
thread_local! {
|
||||
/// Each viewport's input for the next frame (focus, close button).
|
||||
static INFOS: RefCell<egui::ViewportIdMap<ViewportInfo>> = RefCell::new(egui::ViewportIdMap::default());
|
||||
/// The viewport commands the app sent this frame.
|
||||
static SENT: RefCell<Vec<(ViewportId, ViewportCommand)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn record(mut out: egui::FullOutput) {
|
||||
out.textures_delta.clear(); // not painted
|
||||
SENT.with(|s| {
|
||||
let mut s = s.borrow_mut();
|
||||
for (id, v) in &out.viewport_output {
|
||||
s.extend(v.commands.iter().map(|c| (*id, c.clone())));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
struct Desk {
|
||||
ctx: Context,
|
||||
app: SheetApp,
|
||||
windows: DocWindows,
|
||||
}
|
||||
|
||||
impl Desk {
|
||||
fn new(quit_with_last_window: bool) -> Desk {
|
||||
INFOS.with(|i| i.borrow_mut().clear());
|
||||
let ctx = Context::default();
|
||||
ctx.set_embed_viewports(false);
|
||||
Context::set_immediate_viewport_renderer(|ctx, viewport| {
|
||||
let id = viewport.ids.this;
|
||||
let mut input = RawInput { viewport_id: id, ..RawInput::default() };
|
||||
input.viewports = INFOS.with(|i| i.borrow().clone());
|
||||
input.viewports.entry(id).or_default().parent = Some(viewport.ids.parent);
|
||||
let mut cb = viewport.viewport_ui_cb;
|
||||
record(ctx.run_ui(input, |ui| cb(ui)));
|
||||
});
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
let windows = DocWindows::new(&mut app, egui::ViewportBuilder::default(), quit_with_last_window);
|
||||
let mut desk = Desk { ctx, app, windows };
|
||||
desk.frames(3);
|
||||
desk
|
||||
}
|
||||
|
||||
/// One frame as eframe runs it; `act` runs first, inside the frame. Returns the viewport
|
||||
/// commands sent.
|
||||
fn frame_with(&mut self, act: impl FnOnce(&mut SheetApp, &Context)) -> Vec<(ViewportId, ViewportCommand)> {
|
||||
SENT.with(|s| s.borrow_mut().clear());
|
||||
let mut input = RawInput { viewport_id: ViewportId::ROOT, ..RawInput::default() };
|
||||
input.viewports = INFOS.with(|i| i.borrow().clone());
|
||||
input.viewports.entry(ViewportId::ROOT).or_default();
|
||||
let Desk { ctx, app, windows } = self;
|
||||
let mut act = Some(act);
|
||||
let out = ctx.clone().run_ui(input, |ui| {
|
||||
let ctx = ui.ctx().clone();
|
||||
if let Some(act) = act.take() {
|
||||
act(app, &ctx);
|
||||
}
|
||||
app.logic(&ctx);
|
||||
windows.logic(app, &ctx);
|
||||
windows.show(app, ui);
|
||||
});
|
||||
record(out);
|
||||
// Close buttons are one-shot events.
|
||||
INFOS.with(|i| i.borrow_mut().values_mut().for_each(|v| v.events.clear()));
|
||||
SENT.with(|s| s.borrow().clone())
|
||||
}
|
||||
|
||||
fn frames(&mut self, n: usize) -> Vec<(ViewportId, ViewportCommand)> {
|
||||
(0..n).flat_map(|_| self.frame_with(|_, _| {})).collect()
|
||||
}
|
||||
|
||||
fn viewport(&self, window: u64) -> ViewportId {
|
||||
self.windows.viewport_of(window).unwrap_or_else(|| panic!("window {window} has no native window"))
|
||||
}
|
||||
|
||||
/// The user presses window `window`'s close button.
|
||||
fn close(&mut self, window: u64) -> Vec<(ViewportId, ViewportCommand)> {
|
||||
let vp = self.viewport(window);
|
||||
INFOS.with(|i| i.borrow_mut().entry(vp).or_default().events.push(ViewportEvent::Close));
|
||||
let mut sent = self.frame_with(|_, _| {});
|
||||
sent.extend(self.frames(2));
|
||||
sent
|
||||
}
|
||||
|
||||
/// Answers the Save Changes question showing in the active window, as its button does.
|
||||
fn answer(&mut self, answer: SaveAnswer) -> Vec<(ViewportId, ViewportCommand)> {
|
||||
let mut sent = self.frame_with(|app, ctx| {
|
||||
let d = app.dialog.take().unwrap_or_else(|| panic!("no question is showing"));
|
||||
assert_eq!(d.name(), "saveChanges");
|
||||
let quitting = d.values.get("quit").and_then(serde_json::Value::as_bool) == Some(true);
|
||||
app.answer_save_changes(answer, quitting, ctx);
|
||||
});
|
||||
sent.extend(self.frames(2));
|
||||
sent
|
||||
}
|
||||
|
||||
fn window_of(&self, doc: usize) -> u64 {
|
||||
let uid = self.app.session.documents()[doc].uid;
|
||||
self.app.session.doc_window(uid).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
fn sent_to(sent: &[(ViewportId, ViewportCommand)], vp: ViewportId, cmd: &ViewportCommand) -> bool {
|
||||
sent.iter().any(|(id, c)| *id == vp && c == cmd)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_window_keeps_its_own_selection_and_draft() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("file.new", json!({})).unwrap();
|
||||
desk.frames(3);
|
||||
let (w1, w2) = (desk.window_of(0), desk.window_of(1));
|
||||
assert_eq!(desk.windows.shown_windows(), [w1, w2], "a native window per workbook");
|
||||
assert_ne!(desk.viewport(w1), desk.viewport(w2));
|
||||
|
||||
desk.app.enter_window(w1);
|
||||
desk.app.run("selection.set", json!({"range": "B2"})).unwrap();
|
||||
desk.app.begin_edit(Some("one".into()), false);
|
||||
desk.frames(2);
|
||||
desk.app.enter_window(w2);
|
||||
desk.app.run("selection.set", json!({"range": "D4"})).unwrap();
|
||||
desk.app.begin_edit(Some("two".into()), false);
|
||||
desk.frames(3);
|
||||
|
||||
for (w, cell, text) in [(w1, "B2", "one"), (w2, "D4", "two")] {
|
||||
desk.app.enter_window(w);
|
||||
assert_eq!(desk.app.editor.as_ref().map(|ed| ed.text.as_str()), Some(text), "window {w} keeps its draft");
|
||||
assert!(desk.app.grid.rect.is_some(), "window {w} drew its own grid");
|
||||
assert_eq!(desk.app.session.doc().unwrap().selection.active, CellRef::parse(cell).unwrap(), "window {w} keeps its selection");
|
||||
}
|
||||
assert!(desk.app.session.documents().iter().all(|d| !d.is_dirty()), "drawing the other window commits no draft");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_one_of_two_windows_on_a_workbook_does_not_ask() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "42"})).unwrap();
|
||||
desk.app.run("view.newWindow", json!({})).unwrap();
|
||||
desk.frames(3);
|
||||
let windows = desk.windows.shown_windows();
|
||||
assert_eq!(windows.len(), 2, "New Window opens a native window");
|
||||
let child = windows.iter().copied().find(|w| Some(*w) != desk.windows.root_window()).unwrap();
|
||||
|
||||
let sent = desk.close(child);
|
||||
assert!(desk.app.dialog.is_none(), "the workbook stays open in its other window: nothing to ask");
|
||||
assert_eq!(desk.app.session.documents().len(), 1);
|
||||
assert_eq!(desk.app.session.windows().len(), 1);
|
||||
assert!(desk.app.session.documents()[0].is_dirty(), "its changes are kept");
|
||||
assert_eq!(desk.windows.shown_windows().len(), 1);
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "{sent:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_last_window_of_an_unsaved_workbook_asks_and_the_app_quits_after() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "42"})).unwrap();
|
||||
desk.frames(2);
|
||||
let w = desk.window_of(0);
|
||||
let sent = desk.close(w);
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::CancelClose), "the window stays open to ask: {sent:?}");
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert_eq!(desk.app.session.documents().len(), 1);
|
||||
|
||||
let sent = desk.answer(SaveAnswer::Cancel);
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Cancel keeps it open");
|
||||
assert_eq!(desk.app.session.documents().len(), 1);
|
||||
|
||||
desk.close(w);
|
||||
let sent = desk.answer(SaveAnswer::DontSave);
|
||||
assert!(desk.app.session.documents().is_empty());
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "the last window closed: the app quits: {sent:?}");
|
||||
assert!(desk.app.allow_close);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_quitting_on_the_last_window_the_app_hides_and_new_shows_it_again() {
|
||||
let mut desk = Desk::new(false);
|
||||
let w = desk.window_of(0);
|
||||
let sent = desk.close(w);
|
||||
assert!(desk.app.session.documents().is_empty(), "a clean workbook closes without asking");
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Visible(false)), "{sent:?}");
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "the app keeps running: {sent:?}");
|
||||
assert!(desk.app.session.documents().is_empty(), "and doesn't make a workbook of its own");
|
||||
|
||||
let sent = desk.frame_with(|app, _| app.run_or_alert("file.new", json!({})));
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Visible(true)), "{sent:?}");
|
||||
assert_eq!(desk.windows.root_window(), Some(desk.window_of(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quit_asks_about_each_unsaved_workbook_in_its_window_and_cancel_stops() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
|
||||
desk.app.run("file.new", json!({})).unwrap();
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "2"})).unwrap();
|
||||
desk.frames(3);
|
||||
let (w1, w2) = (desk.window_of(0), desk.window_of(1));
|
||||
assert_eq!(desk.app.session.active_window(), Some(w2));
|
||||
|
||||
let sent = desk.frame_with(|app, ctx| app.request_quit(ctx));
|
||||
assert_eq!(desk.app.session.active_window(), Some(w1), "Book1's window comes forward to ask");
|
||||
assert!(sent_to(&sent, desk.viewport(w1), &ViewportCommand::Focus), "{sent:?}");
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
let sent = desk.answer(SaveAnswer::Cancel);
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Cancel stops the quit: {sent:?}");
|
||||
assert_eq!(desk.app.session.documents().len(), 2);
|
||||
assert!(desk.app.dialog.is_none());
|
||||
|
||||
desk.frame_with(|app, ctx| app.request_quit(ctx));
|
||||
let sent = desk.answer(SaveAnswer::DontSave);
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "Book2 is still unsaved: {sent:?}");
|
||||
assert_eq!(desk.app.session.active_window(), Some(w2), "then Book2's window asks");
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
let sent = desk.answer(SaveAnswer::DontSave);
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "both answered: the app quits: {sent:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_root_adopts_the_remaining_window_with_its_workbook_and_state() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("file.new", json!({})).unwrap();
|
||||
desk.frames(3);
|
||||
let (w1, w2) = (desk.window_of(0), desk.window_of(1));
|
||||
assert_eq!(desk.windows.root_window(), Some(w1));
|
||||
let book2 = desk.app.session.documents()[1].uid;
|
||||
desk.app.enter_window(w2);
|
||||
desk.app.run("selection.set", json!({"range": "C3"})).unwrap();
|
||||
desk.app.begin_edit(Some("kept".into()), false);
|
||||
desk.frames(2);
|
||||
|
||||
let sent = desk.close(w1);
|
||||
assert!(sent_to(&sent, ViewportId::ROOT, &ViewportCommand::CancelClose), "closing the root's window doesn't end the app: {sent:?}");
|
||||
assert!(!sent_to(&sent, ViewportId::ROOT, &ViewportCommand::Close), "{sent:?}");
|
||||
assert_eq!(desk.windows.root_window(), Some(w2), "Book2's window moves into the root");
|
||||
assert_eq!(desk.windows.shown_windows(), [w2]);
|
||||
assert_eq!(desk.app.session.documents().len(), 1);
|
||||
assert_eq!(desk.app.session.doc().unwrap().uid, book2);
|
||||
assert_eq!(desk.app.editor.as_ref().map(|ed| ed.text.as_str()), Some("kept"), "its draft is still open");
|
||||
assert_eq!(desk.app.session.doc().unwrap().selection.active, CellRef::parse("C3").unwrap());
|
||||
assert_eq!(desk.app.session.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C3").unwrap()), Value::Empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_commands_follow_the_focused_window_and_leaving_a_window_enters_its_draft() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("file.new", json!({})).unwrap();
|
||||
desk.frames(3);
|
||||
let (w1, w2) = (desk.window_of(0), desk.window_of(1));
|
||||
desk.app.begin_edit(Some("typed".into()), false);
|
||||
desk.frames(2);
|
||||
assert_eq!(desk.app.session.active_window(), Some(w2));
|
||||
|
||||
// The user clicks into Book1's window.
|
||||
let (v1, v2) = (desk.viewport(w1), desk.viewport(w2));
|
||||
INFOS.with(|i| {
|
||||
let mut i = i.borrow_mut();
|
||||
i.entry(v1).or_default().focused = Some(true);
|
||||
i.entry(v2).or_default().focused = Some(false);
|
||||
});
|
||||
desk.frames(2);
|
||||
assert_eq!(desk.app.session.active_window(), Some(w1), "commands from the menu bar go to the window focused last");
|
||||
assert!(desk.app.editor.is_none(), "Book1's window has no draft");
|
||||
let book2 = &desk.app.session.documents()[1];
|
||||
assert_eq!(book2.wb.active().unwrap().value(CellRef::new(0, 0)), Value::text("typed"), "the draft was entered in its own window");
|
||||
desk.app.run("cell.set", json!({"cell": "B1", "input": "menu"})).unwrap();
|
||||
assert_eq!(desk.app.session.documents()[0].wb.active().unwrap().value(CellRef::new(0, 1)), Value::text("menu"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_from_opening_a_workbook_shows_in_its_new_window() {
|
||||
let mut desk = Desk::new(true);
|
||||
desk.app.run("cell.set", json!({"cell": "A1", "input": "kept"})).unwrap();
|
||||
desk.frames(2);
|
||||
let book1 = desk.window_of(0);
|
||||
let mut wb = gridcraft_engine::model::Workbook::new();
|
||||
wb.vba_project = Some(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1 fake OLE2 vbaProject".to_vec().into());
|
||||
let b64 = gridcraft_engine::io::base64_encode(&gridcraft_engine::io::save_bytes(&wb, "macros.xlsm").unwrap());
|
||||
desk.frame_with(|app, _| {
|
||||
// A script opening the file on the session, then the interface reporting on it.
|
||||
let r = app.session.run("file.open", json!({"name": "macros.xlsm", "base64": b64})).unwrap();
|
||||
app.show_open_warnings(&r);
|
||||
app.run_or_alert("no.such.command", json!({}));
|
||||
});
|
||||
desk.frames(2);
|
||||
let opened = desk.window_of(1);
|
||||
assert_eq!(desk.windows.shown_windows(), [book1, opened]);
|
||||
assert_eq!(desk.app.session.active_window(), Some(opened));
|
||||
assert_eq!(desk.app.notice.as_ref().map(|n| n.kind), Some(gridcraft_ui_egui::NoticeKind::Warning), "the macro notice shows in the opened window");
|
||||
assert!(desk.app.message.is_some(), "and so does the alert");
|
||||
desk.app.enter_window(book1);
|
||||
assert!(desk.app.notice.is_none() && desk.app.message.is_none(), "Book1's window shows neither");
|
||||
}
|
||||
|
||||
/// Book1 with two sheets, saved, shown in two windows: window 1 on Sheet1 at B2, window 2 on
|
||||
/// Sheet2 at D4. Returns the window ids.
|
||||
fn two_windows_on_one_workbook(desk: &mut Desk) -> (u64, u64) {
|
||||
desk.app.run("home.insertSheet", json!({})).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("gridcraft-two-windows-{}-{:?}.xlsx", std::process::id(), std::thread::current().id()));
|
||||
desk.app.run("file.save", json!({"path": path})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
desk.app.run("sheet.activate", json!({"sheet": 0})).unwrap();
|
||||
desk.app.run("selection.set", json!({"range": "B2"})).unwrap();
|
||||
desk.frames(2);
|
||||
let w1 = desk.app.session.active_window().unwrap();
|
||||
desk.app.run("view.newWindow", json!({})).unwrap();
|
||||
desk.frames(3);
|
||||
let w2 = desk.app.session.active_window().unwrap();
|
||||
desk.app.run("sheet.activate", json!({"sheet": 1})).unwrap();
|
||||
desk.app.run("selection.set", json!({"range": "D4"})).unwrap();
|
||||
desk.frames(3);
|
||||
(w1, w2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_windows_on_one_workbook_show_their_own_sheet_and_each_others_edits() {
|
||||
let mut desk = Desk::new(true);
|
||||
let (w1, w2) = two_windows_on_one_workbook(&mut desk);
|
||||
assert_eq!(desk.windows.shown_windows(), [w1, w2], "New Window opens a native window");
|
||||
assert_ne!(desk.viewport(w1), desk.viewport(w2));
|
||||
let titles: Vec<String> = [w1, w2].iter().map(|w| desk.app.session.window_title(*w).unwrap()).collect();
|
||||
assert!(titles[0].ends_with(".xlsx:1") && titles[1].ends_with(".xlsx:2"), "{titles:?}");
|
||||
|
||||
// Drawing both windows every frame swaps their views without copying the workbook.
|
||||
let wb = desk.app.session.doc().unwrap().wb.clone();
|
||||
desk.frames(3);
|
||||
assert!(std::sync::Arc::ptr_eq(&wb, &desk.app.session.doc().unwrap().wb), "a window swap copied the workbook");
|
||||
assert!(!desk.app.session.doc().unwrap().is_dirty());
|
||||
for (w, sheet, cell) in [(w1, 0, "B2"), (w2, 1, "D4")] {
|
||||
desk.app.enter_window(w);
|
||||
let d = desk.app.session.doc().unwrap();
|
||||
assert_eq!((d.wb.active_sheet(), d.selection.active), (sheet, CellRef::parse(cell).unwrap()), "window {w}'s sheet and selection");
|
||||
assert!(desk.app.grid.rect.is_some(), "window {w} drew its grid");
|
||||
}
|
||||
|
||||
// Window 1 refers to Sheet2!D4; window 2 types there; window 1 shows it on the next frame.
|
||||
desk.app.enter_window(w1);
|
||||
desk.app.run("cell.set", json!({"cell": "B2", "input": "=Sheet2!D4*2"})).unwrap();
|
||||
desk.frames(1);
|
||||
desk.app.enter_window(w2);
|
||||
desk.app.run("cell.set", json!({"input": "21"})).unwrap();
|
||||
desk.frames(1);
|
||||
desk.app.enter_window(w1);
|
||||
let d = desk.app.session.doc().unwrap();
|
||||
assert_eq!(d.wb.active_sheet(), 0);
|
||||
assert_eq!(d.wb.active().unwrap().value(CellRef::parse("B2").unwrap()), Value::Number(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_stays_with_its_window_across_a_switch() {
|
||||
let mut desk = Desk::new(true);
|
||||
let (w1, w2) = two_windows_on_one_workbook(&mut desk);
|
||||
desk.app.enter_window(w1);
|
||||
desk.app.open_dialog("zoom", json!({}));
|
||||
desk.frames(2);
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("zoom"));
|
||||
|
||||
// From the menu bar.
|
||||
desk.app.run("view.switchWindows", json!({"window": w2})).unwrap();
|
||||
desk.frames(3);
|
||||
assert_eq!(desk.app.session.active_window(), Some(w2));
|
||||
assert!(desk.app.dialog.is_none(), "window 2 shows no dialog");
|
||||
|
||||
// The user clicks into window 1, then back into window 2.
|
||||
for (w, other) in [(w1, w2), (w2, w1)] {
|
||||
let (v, o) = (desk.viewport(w), desk.viewport(other));
|
||||
INFOS.with(|i| {
|
||||
let mut i = i.borrow_mut();
|
||||
i.entry(v).or_default().focused = Some(true);
|
||||
i.entry(o).or_default().focused = Some(false);
|
||||
});
|
||||
desk.frames(2);
|
||||
assert_eq!(desk.app.session.active_window(), Some(w));
|
||||
let expected = if w == w1 { Some("zoom") } else { None };
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), expected, "window {w}'s dialog");
|
||||
}
|
||||
|
||||
// A script switching windows while the dialog is open.
|
||||
desk.frame_with(|app, ctx| {
|
||||
let _ = gridcraft_ui_egui::control::handle(app, ctx, "engine.execute", &json!({"command": "window.activate", "params": {"window": w1}}));
|
||||
});
|
||||
desk.frames(2);
|
||||
assert_eq!(desk.app.dialog.as_ref().map(|d| d.name()), Some("zoom"));
|
||||
desk.app.enter_window(w2);
|
||||
assert!(desk.app.dialog.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrange_all_lays_out_the_native_windows_active_first() {
|
||||
let mut desk = Desk::new(true);
|
||||
let (w1, w2) = two_windows_on_one_workbook(&mut desk);
|
||||
INFOS.with(|i| i.borrow_mut().entry(ViewportId::ROOT).or_default().monitor_size = Some(egui::vec2(1000.0, 800.0)));
|
||||
desk.app.run("view.arrangeAll", json!({"arrange": "vertical"})).unwrap();
|
||||
let sent = desk.frames(1);
|
||||
let at = |x: f32| ViewportCommand::OuterPosition(egui::pos2(x, 0.0));
|
||||
assert!(sent_to(&sent, desk.viewport(w2), &at(0.0)), "the active window goes left: {sent:?}");
|
||||
assert!(sent_to(&sent, desk.viewport(w1), &at(500.0)));
|
||||
assert!(sent_to(&sent, desk.viewport(w1), &ViewportCommand::InnerSize(egui::vec2(500.0, 800.0))));
|
||||
|
||||
// Without parameters, as a script calls it: tiled.
|
||||
let r = desk.app.run("view.arrangeAll", json!({})).unwrap();
|
||||
assert_eq!(r["arrange"], "tiled");
|
||||
let tiled = gridcraft_ui_egui::doc_windows::arrange_rects("tiled", 3, craft_window::Rect::new(0.0, 0.0, 1000.0, 800.0));
|
||||
let r = |x, y, w, h| craft_window::Rect::new(x, y, w, h);
|
||||
assert_eq!(tiled, [r(0.0, 0.0, 500.0, 400.0), r(500.0, 0.0, 500.0, 400.0), r(0.0, 400.0, 1000.0, 400.0)]);
|
||||
}
|
||||
@@ -34,7 +34,7 @@ fn commit_after_pointing_on_another_sheet_writes_to_the_origin_sheet() {
|
||||
assert!(h.state_mut().commit_edit(0, 0, false, false));
|
||||
let at = CellRef::parse("F8").unwrap();
|
||||
let wb = &h.state().session.active().unwrap().wb;
|
||||
assert_eq!(wb.active_sheet(), 0, "the origin sheet is shown again");
|
||||
assert_eq!(wb.active_sheet, 0, "the origin sheet is shown again");
|
||||
assert!(wb.sheet(0).unwrap().cell(at).is_some_and(|c| c.formula.is_some()), "formula written on the origin sheet");
|
||||
assert!(wb.sheet(1).unwrap().cell(at).is_none(), "the pointed-at sheet is untouched");
|
||||
}
|
||||
@@ -44,7 +44,7 @@ fn ctrl_enter_after_pointing_on_another_sheet_fills_the_origin_selection() {
|
||||
let mut h = pointing_on_second_sheet("B2:C3");
|
||||
assert!(h.state_mut().commit_edit(0, 0, false, true));
|
||||
let wb = &h.state().session.active().unwrap().wb;
|
||||
assert_eq!(wb.active_sheet(), 0, "the origin sheet is shown again");
|
||||
assert_eq!(wb.active_sheet, 0, "the origin sheet is shown again");
|
||||
for a1 in ["B2", "C2", "B3", "C3"] {
|
||||
let at = CellRef::parse(a1).unwrap();
|
||||
assert!(wb.sheet(0).unwrap().cell(at).is_some_and(|c| c.formula.is_some()), "{a1} filled on the origin sheet");
|
||||
|
||||
@@ -112,7 +112,7 @@ fn circular_references_lists_the_loops_and_selects_the_cell_picked() {
|
||||
h.run_steps(4);
|
||||
let app = h.state();
|
||||
let d = app.session.active().unwrap();
|
||||
assert_eq!(d.wb.active_sheet(), 1, "picking a cell on Q1 Data goes to Q1 Data");
|
||||
assert_eq!(d.wb.active_sheet, 1, "picking a cell on Q1 Data goes to Q1 Data");
|
||||
assert_eq!(format!("'Q1 Data'!{}", d.selection.active.a1()), other);
|
||||
}
|
||||
|
||||
|
||||
@@ -279,113 +279,6 @@ fn closing_the_window_can_save_first_and_a_saved_workbook_closes_at_once() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting_with_one_of_two_workbooks_unsaved_asks_once() {
|
||||
let mut h = harness(Services::default());
|
||||
h.state_mut().run("cell.set", serde_json::json!({"cell": "A1", "input": "42"})).unwrap();
|
||||
h.state_mut().run("file.new", serde_json::json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
|
||||
let sent = request_window_close(&mut h);
|
||||
assert!(sent.contains(&egui::ViewportCommand::CancelClose), "{sent:?}");
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("saveChanges"));
|
||||
assert_eq!(h.state().session.active_index(), 0, "the unsaved workbook comes forward");
|
||||
let sent = click_commands(&mut h, "Cancel");
|
||||
assert!(!sent.contains(&egui::ViewportCommand::Close), "Cancel stops the quit");
|
||||
assert_eq!(h.state().session.documents().len(), 2, "Cancel keeps both workbooks");
|
||||
|
||||
request_window_close(&mut h);
|
||||
let sent = click_commands(&mut h, "Don't Save");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "the saved workbook isn't asked about: {sent:?}");
|
||||
assert!(h.state().dialog.is_none());
|
||||
}
|
||||
|
||||
/// Book1 has a cell being typed when File › New runs (the macOS menu runs the command directly).
|
||||
fn typing_in_book1_then_new(h: &mut egui_kittest::Harness<'static, SheetApp>) -> u64 {
|
||||
h.input_mut().events.push(egui::Event::Text("hello".into()));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_some());
|
||||
let book1 = h.state().session.doc().unwrap().uid;
|
||||
h.state_mut().run_or_alert("file.new", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
book1
|
||||
}
|
||||
|
||||
fn a1(h: &egui_kittest::Harness<'static, SheetApp>, doc: usize) -> Value {
|
||||
h.state().session.documents()[doc].wb.active().unwrap().value(CellRef::new(0, 0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_workbook_keeps_the_typed_cell_in_the_first_and_switch_windows_brings_it_back() {
|
||||
let mut h = harness(Services::default());
|
||||
let book1 = typing_in_book1_then_new(&mut h);
|
||||
assert!(h.state().editor.is_none(), "the draft doesn't follow into Book2");
|
||||
assert_eq!(h.state().session.documents().len(), 2);
|
||||
assert_eq!(h.state().session.active_index(), 1);
|
||||
assert_eq!(a1(&h, 0), Value::text("hello"), "the draft is committed into Book1, as Enter would");
|
||||
assert!(h.state().session.documents()[0].is_dirty(), "so quitting asks about Book1");
|
||||
assert_eq!(a1(&h, 1), Value::Empty);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(a1(&h, 1), Value::Empty, "Enter in Book2 writes nothing left over");
|
||||
|
||||
// The key tip or command search opens the View tab's list; Book1 shows its unsaved bullet.
|
||||
h.state_mut().run_or_alert("view.switchWindows", serde_json::json!({}));
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().ui.ribbon_tab, "View");
|
||||
h.get_by_label_contains("Book1 •").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().session.doc().unwrap().uid, book1);
|
||||
assert_eq!(h.state().session.documents().len(), 2);
|
||||
assert!(h.state().message.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_draft_its_workbook_refuses_stops_the_switch_and_stays_open() {
|
||||
let mut h = harness(Services::default());
|
||||
let book1 = typing_in_book1_then_new(&mut h);
|
||||
let book2 = h.state().session.doc().unwrap().uid;
|
||||
h.state_mut().session.execute("data.validation", serde_json::json!({"range": "A1", "type": "list", "formula1": "\"Red,Green\""})).unwrap();
|
||||
h.input_mut().events.push(egui::Event::Text("Purple".into()));
|
||||
h.run_steps(2);
|
||||
h.state_mut().run_or_alert("view.switchWindows", serde_json::json!({"doc": book1}));
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.doc().unwrap().uid, book2, "the switch doesn't happen");
|
||||
assert_eq!(h.state().editor.as_ref().map(|ed| ed.text.as_str()), Some("Purple"), "the draft stays open to fix");
|
||||
assert_eq!(a1(&h, 1), Value::Empty, "Book2 is unchanged");
|
||||
assert!(h.state().message.is_some(), "the refusal is reported");
|
||||
|
||||
// Esc drops the draft; then the switch goes through.
|
||||
h.state_mut().message = None;
|
||||
h.state_mut().cancel_edit();
|
||||
h.state_mut().run_or_alert("view.switchWindows", serde_json::json!({"doc": book1}));
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.doc().unwrap().uid, book1);
|
||||
assert!(h.state().message.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untouched_f2_draft_leaves_the_workbook_clean_on_a_file_command() {
|
||||
let dir = std::env::temp_dir().join(format!("gridcraft-f2-draft-{}", 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("cell.set", serde_json::json!({"cell": "A1", "input": "=1+2"})).unwrap();
|
||||
h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap();
|
||||
h.run_steps(2);
|
||||
let undo = h.state().session.doc().unwrap().undo.len();
|
||||
h.key_press(egui::Key::F2);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().editor.as_ref().map(|ed| ed.text.as_str()), Some("=1+2"));
|
||||
h.state_mut().run_or_alert("file.new", serde_json::json!({}));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_none());
|
||||
let book1 = &h.state().session.documents()[0];
|
||||
assert!(!book1.is_dirty(), "nothing was typed, so nothing changed");
|
||||
assert_eq!(book1.undo.len(), undo, "and no undo step was added");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn pdf_picker_harness(dir: &std::path::Path) -> (Arc<Mutex<Vec<String>>>, egui_kittest::Harness<'static, SheetApp>) {
|
||||
let asked = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let (capture, target) = (asked.clone(), dir.to_path_buf());
|
||||
@@ -585,65 +478,3 @@ fn save_a_copy_with_a_bare_name_asks_where_to_save_it() {
|
||||
assert_eq!(asked.lock().unwrap().len(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_window_shows_the_same_workbook_and_a_draft_settles_in_its_own_window() {
|
||||
let mut h = harness(Services::default());
|
||||
h.state_mut().run("selection.set", serde_json::json!({"range": "B2"})).unwrap();
|
||||
let first = h.state().session.active_window().unwrap();
|
||||
h.state_mut().run_or_alert("view.newWindow", serde_json::json!({}));
|
||||
h.run_steps(2);
|
||||
let second = h.state().session.active_window().unwrap();
|
||||
let book = h.state().session.doc().unwrap().uid;
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(h.state().session.documents().len(), 1, "one workbook, two windows");
|
||||
let titles: Vec<String> = h.state().open_windows().iter().map(|w| w.title.clone()).collect();
|
||||
assert_eq!(titles, ["Book1:1", "Book1:2"]);
|
||||
|
||||
// A draft typed in window 2 is entered in window 2's cell before window 1 comes forward.
|
||||
h.state_mut().run("selection.set", serde_json::json!({"range": "D4"})).unwrap();
|
||||
h.input_mut().events.push(egui::Event::Text("typed".into()));
|
||||
h.run_steps(2);
|
||||
h.state_mut().run_or_alert("view.switchWindows", serde_json::json!({"window": first}));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_none(), "the draft doesn't follow into window 1");
|
||||
assert_eq!(h.state().session.active_window(), Some(first));
|
||||
let d = h.state().session.doc().unwrap();
|
||||
assert_eq!(d.wb.active().unwrap().value(CellRef::parse("D4").unwrap()), Value::text("typed"));
|
||||
assert_eq!(d.selection.active, CellRef::parse("B2").unwrap(), "window 1 keeps its own selection");
|
||||
|
||||
// Quitting asks once about the workbook, whichever window shows it.
|
||||
request_window_close(&mut h);
|
||||
let sent = click_commands(&mut h, "Don't Save");
|
||||
assert!(sent.contains(&egui::ViewportCommand::Close), "{sent:?}");
|
||||
assert!(h.state().session.document_index(book).is_none(), "both windows closed with the workbook");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_requests_route_to_a_window_and_list_windows() {
|
||||
use gridcraft_ui_egui::control::{Outcome, handle};
|
||||
let mut h = harness(Services::default());
|
||||
let first = h.state().session.active_window().unwrap();
|
||||
h.state_mut().run_or_alert("file.new", serde_json::json!({}));
|
||||
h.run_steps(2);
|
||||
let ctx = h.ctx.clone();
|
||||
let call = |h: &mut egui_kittest::Harness<'static, SheetApp>, method: &str, p: serde_json::Value| match handle(h.state_mut(), &ctx, method, &p) {
|
||||
Outcome::Done(v) => v,
|
||||
Outcome::Screenshot { .. } => serde_json::Value::Null,
|
||||
};
|
||||
let r = call(&mut h, "engine.execute", serde_json::json!({"command": "cell.set", "params": {"cell": "A1", "input": "one"}, "window": first}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert_eq!(a1(&h, 0), Value::text("one"));
|
||||
assert_eq!(a1(&h, 1), Value::Empty);
|
||||
assert_eq!(h.state().session.active_index(), 1, "Book2 stays in front");
|
||||
let r = call(&mut h, "cell.get", serde_json::json!({"cell": "A1", "window": first}));
|
||||
assert!(r["result"].to_string().contains("one"), "{r}");
|
||||
|
||||
let r = call(&mut h, "window.list", serde_json::json!({}));
|
||||
let rows = r["result"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 2, "{r}");
|
||||
assert_eq!((rows[0]["window"].as_u64(), rows[0]["title"].as_str(), rows[0]["dirty"].as_bool()), (Some(first), Some("Book1"), Some(true)));
|
||||
assert_eq!(rows[1]["active"].as_bool(), Some(true));
|
||||
let r = call(&mut h, "engine.execute", serde_json::json!({"command": "cell.get", "params": {"cell": "A1"}, "window": 999}));
|
||||
assert_eq!(r["ok"], false, "{r}");
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ fn double_click(h: &mut Harness, label: &str) {
|
||||
|
||||
fn place(h: &Harness) -> (usize, String) {
|
||||
let d = h.state().session.active().unwrap();
|
||||
(d.wb.active_sheet(), d.selection.a1())
|
||||
(d.wb.active_sheet, d.selection.a1())
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2647,8 +2647,7 @@ fn keytip_wvr_() {
|
||||
fn keytip_ww_() {
|
||||
let mut h = harness(blank());
|
||||
sequence(&mut h, "WW", false);
|
||||
assert!(h.state().message.is_none() && h.state().toast.is_none(), "WW must route to its control without an error box");
|
||||
assert_eq!(h.state().keytips.prefix(), None);
|
||||
assert!(h.state().message.is_none() && h.state().toast.is_none(), "WW must run view.switchWindows cleanly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -113,7 +113,7 @@ fn the_cell_menu_computes_the_report_once_for_all_its_cells() {
|
||||
// West goes away behind the session's back, so the revision stays the same. A menu that
|
||||
// computed the report again for D4 would find it out of date and offer Show Details there.
|
||||
let doc = h.state_mut().session.active_mut().unwrap();
|
||||
let si = doc.wb.active_sheet();
|
||||
let si = doc.wb.active_sheet;
|
||||
std::sync::Arc::make_mut(&mut doc.wb).sheet_mut(si).unwrap().set_value(CellRef::parse("A3").unwrap(), Value::text("East"));
|
||||
right_click(&mut h, "D4");
|
||||
assert!(h.query_by_label("Show Details").is_none(), "D4 is a label of the report computed for E4");
|
||||
|
||||
@@ -106,7 +106,7 @@ fn filter_closes_when_clicking_another_table_or_sheet() {
|
||||
click(&mut h, outside, PointerButton::Primary);
|
||||
assert!(!is_open(&h, Menu::Filter), "filter stayed open after switching table/sheet");
|
||||
if sheet {
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 1);
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet, 1);
|
||||
} else {
|
||||
assert_eq!(h.state().session.active().unwrap().selection.active.a1(), "H2");
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ fn harness() -> egui_kittest::Harness<'static, SheetApp> {
|
||||
#[test]
|
||||
fn typing_a_name_and_enter_activates_that_sheet() {
|
||||
let mut h = harness();
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 0);
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet, 0);
|
||||
h.get_by_label("All sheets").click();
|
||||
h.run_steps(4);
|
||||
h.input_mut().events.push(Event::Text("summ".into()));
|
||||
@@ -40,5 +40,5 @@ fn typing_a_name_and_enter_activates_that_sheet() {
|
||||
h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet(), 3, "Enter on the filtered row must activate Summary");
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active_sheet, 3, "Enter on the filtered row must activate Summary");
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ fn navigation_arrows_reveal_the_selected_tab() {
|
||||
for _ in 0..29 {
|
||||
click(&mut h, next);
|
||||
}
|
||||
assert_eq!(h.state().session.doc().unwrap().wb.active_sheet(), 29);
|
||||
assert_eq!(h.state().session.doc().unwrap().wb.active_sheet, 29);
|
||||
assert_visible(&h, "Tab29");
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ fn hidden_sheets_long_names_and_window_resize_keep_active_tab_visible() {
|
||||
h.set_size(vec2(1000.0, 120.0));
|
||||
h.run_steps(20);
|
||||
assert_visible(&h, name);
|
||||
assert_eq!(h.state().session.doc().unwrap().wb.active_sheet(), 29);
|
||||
assert_eq!(h.state().session.doc().unwrap().wb.active_sheet, 29);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -190,7 +190,7 @@ fn right_clicking_a_tab_activates_its_sheet_so_the_menu_acts_on_it() {
|
||||
h.step();
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(20);
|
||||
assert_eq!(h.state().session.doc().unwrap().wb.active_sheet(), 3, "right-clicking Tab03 should activate it");
|
||||
assert_eq!(h.state().session.doc().unwrap().wb.active_sheet, 3, "right-clicking Tab03 should activate it");
|
||||
// The menu now offers Unprotect for the protected sheet that was clicked, not Protect for the one that was active.
|
||||
let texts: Vec<String> = h
|
||||
.output()
|
||||
|
||||
@@ -98,11 +98,11 @@ fn cross_sheet_precedents_jump_to_the_other_sheet() {
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "=Src!B2*2"})).unwrap();
|
||||
// Back on the first sheet, Ctrl+[ from A1 jumps to Src!B2.
|
||||
let d = s.active().unwrap();
|
||||
let first = d.wb.active_sheet();
|
||||
let first = d.wb.active_sheet;
|
||||
s.execute("selection.set", json!({"range": "A1"})).unwrap();
|
||||
let mut h = harness(s);
|
||||
key(&mut h, Key::OpenBracket, Modifiers::CTRL);
|
||||
let d = h.state().session.active().unwrap();
|
||||
assert_ne!(d.wb.active_sheet(), first, "selection jumped to the precedent's sheet");
|
||||
assert_ne!(d.wb.active_sheet, first, "selection jumped to the precedent's sheet");
|
||||
assert_eq!(d.selection.active, CellRef { row: 1, col: 1 }, "B2 on the Src sheet");
|
||||
}
|
||||
|
||||
@@ -299,7 +299,7 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
cx.warn("the workbook has no worksheets; added an empty sheet");
|
||||
wb.sheets.push(Arc::new(Sheet::new("Sheet1")));
|
||||
}
|
||||
wb.set_active_sheet(file_to_model.get(active_tab).copied().flatten().unwrap_or(0));
|
||||
wb.active_sheet = file_to_model.get(active_tab).copied().flatten().unwrap_or(0);
|
||||
|
||||
// Defined names. Chartex parts refer to their data through hidden `_xlchart.*` names.
|
||||
let mut chart_names: Vec<(String, String)> = vec![];
|
||||
|
||||
@@ -244,8 +244,8 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>)
|
||||
|
||||
// Which sheet is active (must be visible), and at least one visible sheet.
|
||||
let any_visible = wb.sheets.iter().any(|s| s.visibility == Visibility::Visible);
|
||||
let active = if wb.sheets.get(wb.active_sheet()).is_some_and(|s| s.visibility == Visibility::Visible) {
|
||||
wb.active_sheet()
|
||||
let active = if wb.sheets.get(wb.active_sheet).is_some_and(|s| s.visibility == Visibility::Visible) {
|
||||
wb.active_sheet
|
||||
} else {
|
||||
wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0)
|
||||
};
|
||||
|
||||
@@ -206,7 +206,7 @@ pub(crate) fn read_xls_with(bytes: &[u8], mut budget: Budget) -> Result<(Workboo
|
||||
}
|
||||
wb.calc.precision_as_displayed = g.precision_as_displayed;
|
||||
defined_names(&g, &model_index, &mut wb, &mut report);
|
||||
wb.set_active_sheet(wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0));
|
||||
wb.active_sheet = wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0);
|
||||
// The overview comes first.
|
||||
report.warnings.insert(
|
||||
0,
|
||||
|
||||
@@ -120,7 +120,7 @@ pub fn read_xlsb(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
if wb.sheets.is_empty() {
|
||||
return Err(invalid("no supported worksheets"));
|
||||
}
|
||||
wb.set_active_sheet(wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0));
|
||||
wb.active_sheet = wb.sheets.iter().position(|s| s.visibility == Visibility::Visible).unwrap_or(0);
|
||||
Ok((wb, report))
|
||||
}
|
||||
|
||||
|
||||
@@ -50,14 +50,13 @@ connection; nothing sent after it runs. Blank lines are skipped.
|
||||
|
||||
| Method | Params | What it does |
|
||||
|---|---|---|
|
||||
| `engine.execute` | `{command, params, window?, doc?}` | Runs any engine command (see `engine.commands` or `gridcraft-cli commands`) in the active window, or in the window named by `window` (a window id) or `doc` (a workbook id: its most recent window). The active window stays in front afterwards unless the command itself switches windows. `edit.goTo`, `edit.goToSpecial`, `selection.set` and `selection.move` scroll the active cell into view, as Go To does in the window |
|
||||
| `window.list` | | The open windows: `[{window, doc, index, title, dirty, active, hidden}]`. `title` is the workbook name, or "Book1:1", "Book1:2"… when a workbook has several windows; `index` is the workbook's position among the open workbooks |
|
||||
| `engine.execute` | `{command, params}` | Runs any engine command (see `engine.commands` or `gridcraft-cli commands`). `edit.goTo`, `edit.goToSpecial`, `selection.set` and `selection.move` scroll the active cell into view, as Go To does in the window |
|
||||
| `engine.commands` | `{search?}` | Every command: id, label, ribbon path, shortcut, params doc, enabled; `search` keeps those whose id, label or ribbon path contains it (case-insensitive) |
|
||||
| `engine.journal` | | Commands run so far (replayable). Passwords (`password`, `…Password` params) are left out, so a replayed Protect Sheet has no password. Capped at 10,000 entries and 64 MB (serialized); past either cap the oldest entries go |
|
||||
| `document.inspect` | | Workbook summary: sheets, used ranges, tables, charts, names, selection, undo labels |
|
||||
| `sheet.read` | `{range?, sheet?, formulas?, formatted?}` | Values (or formulas / displayed text) of a range |
|
||||
| `cell.get` | `{cell?}` | One cell: value, formula, displayed text, style, merge, comment, link |
|
||||
| `ui.inspect` | | UI state: ribbon tab, editor, open dialog, Backstage page, message, grid rect, scroll, perf, `windows` (as `window.list`) and `activeWindow` |
|
||||
| `ui.inspect` | | UI state: ribbon tab, editor, open dialog, Backstage page, message, grid rect, scroll, perf |
|
||||
| `ui.click` / `ui.drag` / `ui.move` | `{x, y, toX?, toY?, button?, count?, shift?, cmd?, alt?}` | Real pointer input in window points; refused with an error if it would leave more than 10,000 synthetic events or 8 MiB of synthetic input queued (pointer, key, text and move events share this budget) |
|
||||
| `ui.cell.click` / `ui.cell.drag` | `{cell}` / `{from, to}` | Pointer input at a cell's centre (works in point mode while editing); same shared queue limits |
|
||||
| `ui.key` / `ui.text` | `{key, shift?, cmd?, alt?, ctrl?}` / `{text}` | Keyboard input (typing in the grid starts editing); same shared queue limits, and one `ui.text` string may be at most 1 MiB |
|
||||
@@ -84,20 +83,7 @@ fits. `path` writes the PNG to a file instead of returning base64 text and so av
|
||||
base64 costs, but it does not bypass the per-image, aggregate, encoding-working-set or peak
|
||||
limits.
|
||||
|
||||
Any other method name that is a command id (e.g. `home.bold`) runs that command. Its params may
|
||||
include `window` or `doc` to run it in that window, as with `engine.execute`; the window commands
|
||||
(`window.*`, `view.newWindow`, `view.hideWindow`, `view.unhideWindow`, `view.switchWindows`) read
|
||||
them as their own parameters.
|
||||
|
||||
### Windows
|
||||
|
||||
Every open workbook has one or more windows; View › New Window (`view.newWindow`) adds another
|
||||
on the same workbook, and saving from any of them saves that workbook. Each window has its own
|
||||
selection, active sheet and scroll position; switching windows never marks the workbook as
|
||||
changed. `window.activate {window}`, `view.switchWindows {window}` and `view.unhideWindow
|
||||
{window}` bring a window forward; `window.close {window?, force?}` closes one (the workbook
|
||||
closes with its last window, asking about unsaved changes unless `force`); `file.close` closes
|
||||
the active window, or with `{document: true}` the workbook and all its windows.
|
||||
Any other method name that is a command id (e.g. `home.bold`) runs that command.
|
||||
|
||||
Use `engine.execute` with `{command: "view.theme", params: {mode: "system"}}`
|
||||
to choose the display theme; `mode` accepts `"system"`, `"light"`, or `"dark"`.
|
||||
|
||||
+1
-4
@@ -159,9 +159,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
**Estimate:** 15–23 h.
|
||||
|
||||
### 20. Multiple windows; pen pressure (H)
|
||||
- Desktop windows done: a native window per workbook window, New Window on the same workbook,
|
||||
Switch Windows, Arrange All. Left: Arrange All across monitors, one window on the web, no
|
||||
pressure or tilt in ink. **Estimate:** 5–8 h.
|
||||
- One window (#162, PR #171); no pressure or tilt in ink. **Estimate:** 10–14 h.
|
||||
[hardware-parity.md](hardware-parity.md)
|
||||
|
||||
### 21. Automation and add-ins (F)
|
||||
@@ -185,7 +183,6 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
|---|---|---|
|
||||
| 2026-10-24 | minor | §8: PivotTable Enable show details: `pivot.options` `enableShowDetails` turns Show Details off for a PivotTable, read and written in XLSX as `enableDrill` |
|
||||
| 2026-10-23 | minor | §8: PivotTable Show Details: double-clicking a value cell lists its source records on a new sheet (#2364) |
|
||||
| 2026-10-22 | minor | §20: a native window per workbook window, New Window on the same workbook and Arrange All on the desktop; left: Arrange All across monitors, the web's one window, pen pressure (estimate 10–14 h → 5–8 h) |
|
||||
| 2026-10-20 | minor | §11: the Japanese catalog covers the dialogs, messages and menus — 943 keys (~43%), matching the pt-BR coverage; a test keeps the two catalogs in step |
|
||||
| 2026-10-17 | minor | §6: the five reports it tracked are closed and their PRs merged (#57, #133, #139, #140, #134; PRs #148, #155, #156, #157); the entry stays open for §15's oracle suite |
|
||||
| 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Hardware parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Arrange All) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (direct desktop printing through craft-print) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
The hardware Excel uses, per platform, against GridCraft. Part of
|
||||
[target-app-parity.md](target-app-parity.md). **Hardware: ~40% ready, 25–40 h** (estimated).
|
||||
@@ -11,7 +11,7 @@ The hardware Excel uses, per platform, against GridCraft. Part of
|
||||
| GPU rendering of the grid and charts | DirectX / Metal accelerated drawing | wgpu: Metal · DirectX 12 (default since 10-08; OpenGL when DirectX 12 has no GPU driver or fails to start; Vulkan only on request, so the Intel UHD `igvk64.dll` crash (#120) can't happen; shaders compiled with FXC, so no DXC runtime is needed, #339) · Vulkan/GL · Vulkan/GL · WebGPU or WebGL2 | At parity in kind. Driver problems: screen flashing on Windows 11 (#76): 2–4 h |
|
||||
| Pen and touch (Draw tab) | Pen pressure and tilt, eraser end, touch mode, Ink to Shape, ink replay | Pen, highlighter, eraser, Ink to Shape with mouse/pen input; **no pressure or tilt**, no touch mode | Pressure-sensitive strokes where winit reports force; touch-friendly ribbon spacing: 4–6 h |
|
||||
| Trackpad and mouse | Smooth scrolling, pinch zoom, horizontal scroll, Magic Mouse | Smooth scrolling and zoom via egui | Verify pinch zoom on each platform: 1–2 h |
|
||||
| Multiple windows and monitors | One window per workbook, New Window for the same workbook, per-monitor DPI | A native window per workbook window on the desktop, New Window for the same workbook; new windows cascade from the last one on its monitor; View › Arrange All tiles, stacks or cascades them over the main window's monitor (web: one window) | Arrange All across monitors; verify per-monitor DPI with windows on two monitors: 2–3 h |
|
||||
| Multiple windows and monitors | One window per workbook, New Window for the same workbook, per-monitor DPI | One window; multiple workbooks switch inside it (#162; PR #171) | Native window per workbook, New Window, Arrange All across monitors: 6–8 h |
|
||||
| High-DPI and display scaling | yes | yes (display scale matched to desktop density; View › Interface size 75–200 % on top, #230) | — |
|
||||
| Accessibility hardware (screen readers, braille displays, switch control) | Narrator, JAWS, NVDA, VoiceOver | AccessKit enabled in eframe; grid cells and ribbon not yet exposed as an accessible tree | Counted under UI ([ui-parity.md](ui-parity.md)) |
|
||||
| Printers | System print with driver options | Desktop submits through craft-print with printer choice, copies, duplex and grayscale; web browser printing | Counted under print |
|
||||
@@ -20,8 +20,6 @@ The hardware Excel uses, per platform, against GridCraft. Part of
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-22 | minor | View › Arrange All over the main window's monitor. |
|
||||
| 2026-10-22 | minor | Multiple windows: each workbook window is a native window of its own (desktop). |
|
||||
| 2026-10-12 | minor | Desktop File > Print now discovers printers and submits PDF jobs through pinned craft-print with printer choice, copies, duplex and grayscale; browser printing and PDF export remain available. Remaining print parity includes page ranges and driver-specific tray/options UI; physical printer fidelity needs hardware validation. |
|
||||
| 2026-10-11 | trivial | Windows: DirectX 12 shaders compiled with FXC, no DXC runtime needed (#339, #354) |
|
||||
| 2026-10-11 | trivial | Windows: OpenGL fallback when DirectX 12 has no GPU or fails to start; Vulkan never by default (#120) |
|
||||
|
||||
@@ -41,7 +41,6 @@ with a file open.
|
||||
|---|---|---|
|
||||
| `execute_command` | `command`, `params?` | Runs **any** engine command (`cell.set`, `home.bold`, `data.removeDuplicates`, …). |
|
||||
| `list_commands` | `search?` | Command ids, labels, ribbon paths, shortcuts and parameter docs. |
|
||||
| `list_windows` | — | Open windows: window id, workbook (`doc`) id, title ("Book1", or "Book1:2" for a workbook's second window), unsaved changes, active, hidden. |
|
||||
| `inspect_workbook` | — | Sheets, used ranges, tables, charts, names, selection, history. |
|
||||
| `read_range` | `range?`, `sheet?`, `formulas?`, `formatted?` | Rows of values (default: the used range). |
|
||||
| `write_range` | `range`, `values` (2-D) | `range.setValues`; strings starting with `=` are formulas. |
|
||||
@@ -58,10 +57,6 @@ with a file open.
|
||||
| `screenshot` | `path` | PNG of the window (Remote only). |
|
||||
| `list_functions` | `search?`, `category?` | Worksheet functions with signatures. |
|
||||
|
||||
Every tool that acts on a workbook (all but `list_commands`, `list_functions`, `list_windows`, `open_workbook`,
|
||||
`new_workbook` and `screenshot`) also takes `window` or `doc`, an id from `list_windows`, and acts in that window
|
||||
(for `doc`, the workbook's most recent window) without bringing it forward. Without them it acts in the active window.
|
||||
|
||||
Results are one text block holding pretty JSON; failures set `isError: true` with a readable message. Unknown tools,
|
||||
missing required arguments and wrong argument types are JSON-RPC `-32602` errors; malformed JSON is `-32700`; unknown
|
||||
methods `-32601`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Target-app parity: GridCraft vs Microsoft Excel
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-22 · **Change:** minor (several windows: a native window per workbook window, New Window on the same workbook, Arrange All; no score change) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (Page Setup paper sizes match Japanese Excel: B4/B5/B6 are the JIS sizes, with ISO B4/B5/B6 by name and the Japanese postcards, envelopes and A6 added; no score change) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
This is the authoritative parity assessment. [`ROADMAP.md`](../ROADMAP.md) summarizes it,
|
||||
[`gaps.md`](gaps.md) lists every shortfall, and the area checklists hold the detail:
|
||||
@@ -102,11 +102,11 @@ performance 8, stability 8, localization 4, hardware 2, platforms 2, ecosystem 2
|
||||
|---|---|---|---|---|
|
||||
| Features | 45 | ~59% | 300–485 | Table above |
|
||||
| File formats | 15 | ~50% | 80–120 | XLSX read/write is broad but unproven on a real corpus and in Excel; XLSB and ODS are values-only import; no XLS, XML Spreadsheet 2003, SYLK, DIF, PRN; VBA dropped; 100 MB XLSX fails (#175). [file-format-parity.md](file-format-parity.md) |
|
||||
| UI/UX fidelity | 12 | ~55% | 50–80 | Excel-style ribbon, galleries, dialogs, formula bar, status bar; 59 commands with shortcuts vs Excel's 200+; key tips on part of the Home tab only; short context menu; a native window per workbook window on the desktop (one on the web). [ui-parity.md](ui-parity.md) |
|
||||
| UI/UX fidelity | 12 | ~55% | 50–80 | Excel-style ribbon, galleries, dialogs, formula bar, status bar; 59 commands with shortcuts vs Excel's 200+; key tips on part of the Home tab only; short context menu; single window. [ui-parity.md](ui-parity.md) |
|
||||
| Performance | 8 | ~35% | 35–55 | [Performance](#performance) |
|
||||
| Stability | 8 | ~60% | 15–25 | Never-crash rules enforced by lint, every command fuzzed with hostile params, random command sequences fuzzed against undo/redo, XLSX round-trip and full-recalc invariants, last-resort guard in `Session::execute`. Field reports: Windows Intel GPU crash (#120), error on close (#117), freeze opening from Finder (#166), screen flashing (#76) |
|
||||
| Localization | 4 | ~10% | 100–165 | Ribbon-only catalog in five languages (ja, zh, ko, pt-BR, ru; ~12% of strings each), CJK/Thai/Hebrew font fallback, no shaping or RTL. [localization-parity.md](localization-parity.md) |
|
||||
| Hardware | 2 | ~40% | 25–40 | GPU UI via wgpu; single-threaded calc; no pen pressure; a native window per workbook window, Arrange All on one monitor. [hardware-parity.md](hardware-parity.md) |
|
||||
| Hardware | 2 | ~40% | 25–40 | GPU UI via wgpu; single-threaded calc; no pen pressure; one window. [hardware-parity.md](hardware-parity.md) |
|
||||
| Platforms | 2 | ~80% | 30–60 | [Platforms](#platforms) |
|
||||
| Ecosystem / add-ins | 2 | ~10% | 25–40 | [Ecosystem and AI](#ecosystem-and-ai) |
|
||||
| AI features | 2 | ~15% | 30–50 | [Ecosystem and AI](#ecosystem-and-ai) |
|
||||
@@ -144,7 +144,7 @@ Discounts for what still stops real work:
|
||||
|
||||
| Discount | Factor | Evidence |
|
||||
|---|---|---|
|
||||
| Interaction fidelity | × 0.90 | 59 command shortcuts vs Excel's 200+; key tips only on part of the Home tab (#43); rectangular selection bug (#28); charts can't be resized (#190); missing horizontal scrollbar report (#176) |
|
||||
| Interaction fidelity | × 0.90 | 59 command shortcuts vs Excel's 200+; key tips only on part of the Home tab (#43); rectangular selection bug (#28); charts can't be resized (#190); one window (#162); missing horizontal scrollbar report (#176) |
|
||||
| Stability on real machines | × 0.92 | Never-crash lints, fuzzed commands and the `Session::execute` guard; but field reports of a startup crash on Intel UHD (#120), an error on close (#117), a freeze opening from Finder (#166) and screen flashing (#76) |
|
||||
| File exchange with Excel users | × 0.88 | Excel opening our output is unverified across features; unmodelled parts dropped on save; advanced chart kinds lose their type; 100 MB files fail (#175); `.xls` and encrypted files are refused with a clear message (#17) rather than opened. Harsher than a drawing app's discount because spreadsheets are exchanged constantly |
|
||||
|
||||
@@ -334,7 +334,6 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-22 | minor | Several windows on the desktop: a native window per workbook window, New Window on the same workbook, Switch Windows and Arrange All; "one window" removed from UI/UX fidelity, Hardware and the interaction-fidelity discount; no score change |
|
||||
| 2026-10-21 | minor | Page Setup paper sizes: `B4`/`B5`/`B6` are the JIS sizes Japanese Excel uses (ISO B4/B5/B6 by name), and Japanese Postcard, Japanese Double Postcard, the chou/kaku envelopes and A6 are added; PDF MediaBox and `file.print` follow, and the Size menu lists them |
|
||||
| 2026-10-18 | trivial | Stale chart notes: all chart kinds survive XLSX round-trip (PRs #158, #161) and trendlines landed |
|
||||
| 2026-10-16 | minor | Advanced Filter copy-to clears only its actual output and rejects overflow without changing cells (#1031) |
|
||||
|
||||
+1
-6
@@ -34,8 +34,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes
|
||||
| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet or workbook, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has |
|
||||
| Dark mode, system appearance | yes | yes | done (10-09) |
|
||||
| Page Layout view (paper view with rulers and header editing) | yes | yes (#329, 10-11): per-sheet view saved in XLSX, pages with margins and gaps on the print pagination, "Click to add data" pages, rulers (inches or centimetres), headers and footers drawn and edited in place with a Header & Footer tab, whose Different First Page and Different Odd & Even Pages give the first page and the even pages their own header and footer (#344), and whose Scale with Document and Align with Page Margins set whether header and footer text follows the print scale and the side margins, on paper and in the view | margins drag on the rulers (#792, with header and footer margins); header/footer pictures missing (1–3 h). Unverified: with Align with Page Margins off, header and footer text sits 0.7 in from the paper edge, a value not yet measured in the target app |
|
||||
| Multiple windows per workbook | yes | yes (10-22, desktop): each workbook window is a native window of its own (New, Open and New Window open one; titles "Book1", or "Book1:1" / "Book1:2" for a workbook's second window, with " — Edited" while unsaved). Each window keeps its own cell draft, dialog, Backstage view, message and grid state, and its ribbon acts on it; on macOS the menu bar acts on the window focused last. Leaving a window enters its draft as Enter would. A window's close button closes that window: one of several on a workbook closes without asking, a workbook's last asks Save / Don't Save / Cancel when unsaved. Quit asks about each unsaved workbook in its window, and Cancel stops it. The last window closed quits on Windows and Linux; macOS keeps running with the menu bar until New or Open. View › Arrange All (dialog: Tiled, Horizontal, Vertical, Cascade, Windows of active workbook; `view.arrangeAll` tiles by default) lays the visible windows out over the main window's monitor, the active one first. Web: one window | Arrange All uses one monitor; a hidden window (View › Hide) has no native window; every window repaints when one does; see [hardware-parity.md](hardware-parity.md) |
|
||||
| Switch Windows, New Window, unsaved workbooks on quit | yes | yes (10-22): View › New Window opens another window on the same workbook (no copy: saving from either saves it), each with its own selection, active sheet and scroll (showing different sheets copies nothing and leaves the workbook unchanged; Save records the sheet of the window used last); a workbook with several windows titles them "Book1:1", "Book1:2"; File › Close closes one of them without asking and asks only for the last; View › Switch Windows and the macOS Window menu list the open windows (active one checked, unsaved ones marked •) and bring the chosen one forward (`view.switchWindows {window}`, or `{doc}` for a workbook's most recent window); a cell being typed is entered into its own window and workbook before New, Open, Close, Save, Print and window switches (also between two windows on one workbook), and a refused entry stays open and stops the command; quitting (Cmd+Q, the macOS Quit item, the Dock) asks Save / Don't Save / Cancel for each unsaved workbook | |
|
||||
| Multiple windows per workbook | yes | no (#162) | see [hardware-parity.md](hardware-parity.md) |
|
||||
|
||||
## Grid interaction
|
||||
|
||||
@@ -202,10 +201,6 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
| 2026-10-24 | minor | When the fill starts from a date, the right-drag fill menu and the Auto Fill Options button also offer Fill Days, Fill Weekdays (Saturday and Sunday skipped), Fill Months and Fill Years (`edit.autoFill` with `mode` set to `days`, `weekdays`, `months` or `years`). A lone date steps by one unit; two or more dates step by the difference between the first two in that unit, or one unit when they fall in the same one. Fill Months and Fill Years keep the day of the month, clamped to the month's last day. Every fill by months or years (these two, a drag of dates a month apart, and Series by Month or Year) keeps the time of day of a date with a time, which used to be dropped |
|
||||
| 2026-10-22 | minor | Show Outline Symbols (`view.showOutlineSymbols`, Ctrl+8): a sheet can hide the outline's level buttons and brackets while keeping its outline, as Excel saves with `showOutlineSymbols="0"` (read and written); the grid then gives the bands no room |
|
||||
| 2026-10-22 | minor | A number in a repeat-fill format (`*`, as in the Accounting format) that is too wide for its column shows #### like any other number, instead of the fill rebuilding the value so its leading digits were cut off (2,509.00 CHF drawn as "509.00 CHF") |
|
||||
| 2026-10-22 | minor | View › New Window and Arrange All on the View ribbon; Arrange All tiles, stacks or cascades the native windows; two windows on one workbook keep their own sheet without copying the workbook; a dialog opened in one window stays there when a command run from it switches windows |
|
||||
| 2026-10-22 | minor | One native window per workbook window on the desktop: per-window drafts, dialogs and ribbons; menu bar commands go to the focused window; closing one of several windows on a workbook doesn't ask; Quit asks in each unsaved workbook's window; the last window closed quits (Windows, Linux) or leaves macOS running |
|
||||
| 2026-10-22 | minor | New Window opens a second window on the same workbook instead of a copy that saved over the original; windows keep their own selection, sheet and scroll; titles Name:1 / Name:2; Switch Windows, Hide and Unhide work by window; File › Close closes one window of several without asking |
|
||||
| 2026-10-22 | minor | New workbook no longer loses the first one: the cell being typed is entered into its own workbook before any File or window command (an entry the workbook refuses stays open and the command doesn't run; an untouched F2 draft changes nothing), the editor is tied to its workbook, View › Switch Windows and the macOS Window menu list the open workbooks, and the macOS Quit item asks about unsaved workbooks like the close button |
|
||||
| 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel |
|
||||
| 2026-10-21 | minor | Paste Special laid out as Excel's: Paste and Operation options each in two columns inside a frame, Skip blanks and Transpose side by side, Paste Link as a button that pastes references at once; labels translated (the generic form didn't translate them) and the window no longer runs past the screen |
|
||||
| 2026-10-21 | minor | Form dialogs (conditional-format quick rules, New Name, Remove Duplicates, Text to Columns and every other `Dialog::form`) fit their content: OK and Cancel sit in a row under the last field instead of a right-to-left layout that took the screen's whole height and left the buttons floating halfway down |
|
||||
|
||||
+50
-38
@@ -116,6 +116,55 @@ pub fn catalog_keys(source: &str) -> BTreeSet<String> {
|
||||
keys
|
||||
}
|
||||
|
||||
/// The character a `\u{...}` escape stands for, if it names a valid code point.
|
||||
fn unicode_escape(chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>) -> Option<char> {
|
||||
let mut hex = String::new();
|
||||
for (_, c) in chars.by_ref() {
|
||||
match c {
|
||||
'}' => break,
|
||||
'{' => {}
|
||||
c => hex.push(c),
|
||||
}
|
||||
}
|
||||
u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)
|
||||
}
|
||||
|
||||
/// The value of a string literal whose opening quote was just read, and the byte offset past
|
||||
/// its closing quote (`len`, the source's length, when it is never closed).
|
||||
fn string_literal(chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>, len: usize) -> (String, usize) {
|
||||
let mut value = String::new();
|
||||
let mut end = len;
|
||||
while let Some((j, c)) = chars.next() {
|
||||
match c {
|
||||
'"' => {
|
||||
end = j + 1;
|
||||
break;
|
||||
}
|
||||
'\\' => match chars.next().map(|(_, c)| c) {
|
||||
Some('n') => value.push('\n'),
|
||||
Some('t') => value.push('\t'),
|
||||
Some('r') => value.push('\r'),
|
||||
Some('0') => value.push('\0'),
|
||||
Some(c @ ('\\' | '"' | '\'')) => value.push(c),
|
||||
Some('u') => {
|
||||
if let Some(c) = unicode_escape(chars) {
|
||||
value.push(c);
|
||||
}
|
||||
}
|
||||
// A line continuation skips the newline and the next line's indentation.
|
||||
Some('\n') => {
|
||||
while chars.peek().is_some_and(|(_, c)| c.is_whitespace()) {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
c => value.push(c),
|
||||
}
|
||||
}
|
||||
(value, end)
|
||||
}
|
||||
|
||||
/// Every string literal outside `//` comments: its decoded value, and the byte range from its
|
||||
/// opening quote to just past its closing one.
|
||||
fn literals(source: &str) -> Vec<(String, usize, usize)> {
|
||||
@@ -133,44 +182,7 @@ fn literals(source: &str) -> Vec<(String, usize, usize)> {
|
||||
if c != '"' {
|
||||
continue;
|
||||
}
|
||||
let mut value = String::new();
|
||||
let mut end = source.len();
|
||||
while let Some((j, c)) = chars.next() {
|
||||
match c {
|
||||
'"' => {
|
||||
end = j + 1;
|
||||
break;
|
||||
}
|
||||
'\\' => match chars.next().map(|(_, c)| c) {
|
||||
Some('n') => value.push('\n'),
|
||||
Some('t') => value.push('\t'),
|
||||
Some('r') => value.push('\r'),
|
||||
Some('0') => value.push('\0'),
|
||||
Some(c @ ('\\' | '"' | '\'')) => value.push(c),
|
||||
Some('u') => {
|
||||
let mut hex = String::new();
|
||||
for (_, c) in chars.by_ref() {
|
||||
match c {
|
||||
'}' => break,
|
||||
'{' => {}
|
||||
c => hex.push(c),
|
||||
}
|
||||
}
|
||||
if let Some(c) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
|
||||
value.push(c);
|
||||
}
|
||||
}
|
||||
// A line continuation skips the newline and the next line's indentation.
|
||||
Some('\n') => {
|
||||
while chars.peek().is_some_and(|(_, c)| c.is_whitespace()) {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
c => value.push(c),
|
||||
}
|
||||
}
|
||||
let (value, end) = string_literal(&mut chars, source.len());
|
||||
out.push((value, i, end));
|
||||
}
|
||||
out
|
||||
|
||||
Reference in New Issue
Block a user