mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-26 07:43:05 -06:00
Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4b8aae4d4 | ||
|
|
1e6c3f2a61 | ||
|
|
168370bc2a | ||
|
|
6d12ac6720 | ||
|
|
7538c56868 | ||
|
|
8466440421 | ||
|
|
fe30de8f7f | ||
|
|
55222b8814 | ||
|
|
3f8d3930bf | ||
|
|
fde057f8c2 | ||
|
|
7436c503a9 | ||
|
|
c068f77254 | ||
|
|
45ac58cf03 | ||
|
|
aab0a9c385 | ||
|
|
dddc649a78 | ||
|
|
5e2bca0ae7 | ||
|
|
51ab33dbe3 | ||
|
|
dec0e1a6c0 | ||
|
|
5236d8e4ba | ||
|
|
7769efdbb9 | ||
|
|
2ae710e65b | ||
|
|
8aa01a7750 | ||
|
|
57de9d5d6f | ||
|
|
def4067247 | ||
|
|
51bc57b489 | ||
|
|
921cdc974f | ||
|
|
6aa6a9cee8 | ||
|
|
6fe8a65c5c | ||
|
|
de8f36ee33 | ||
|
|
d51a6de104 | ||
|
|
1f6adbe382 | ||
|
|
601cc60cfc | ||
|
|
132bd4e9a8 | ||
|
|
fdad356fd2 | ||
|
|
a8810d7a7a |
@@ -8,13 +8,13 @@ workflows:
|
||||
'.github/workflows/house-rules.yml': []
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/nix.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
'.github/workflows/release.yml': []
|
||||
'.github/workflows/sonarcloud.yml': []
|
||||
'.github/workflows/windows-arm64.yml': []
|
||||
@@ -24,8 +24,8 @@ dependencies:
|
||||
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
owner_id: 44036562
|
||||
repo_id: 197814629
|
||||
'step-security/harden-runner@v2.23.0':
|
||||
ref: 'v2.23.0'
|
||||
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
|
||||
'step-security/harden-runner@v2.22.4':
|
||||
ref: 'v2.22.4'
|
||||
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
|
||||
owner_id: 88700172
|
||||
repo_id: 422287306
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@4ec2a14646b538253fd5ebe109bf463a3d31b061
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
with:
|
||||
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
app-name: gridcraft
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@4ec2a14646b538253fd5ebe109bf463a3d31b061
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
with:
|
||||
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
app-name: gridcraft
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
Generated
+29
-50
@@ -211,15 +211,6 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -236,7 +227,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -923,6 +914,15 @@ version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie-factory"
|
||||
version = "0.3.3"
|
||||
@@ -1601,7 +1601,7 @@ dependencies = [
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip 9.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1709,7 +1709,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259e
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1843,17 +1843,6 @@ version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dify"
|
||||
version = "0.8.0"
|
||||
@@ -1907,7 +1896,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2314,7 +2303,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2912,7 +2901,7 @@ dependencies = [
|
||||
"log",
|
||||
"quick-xml 0.41.0",
|
||||
"serde_json",
|
||||
"zip 3.0.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2949,7 +2938,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"unicode-segmentation",
|
||||
"web-time",
|
||||
"zip 3.0.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3105,7 +3094,7 @@ dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zip 3.0.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4845,7 +4834,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5334,7 +5323,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5775,7 +5764,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5834,7 +5823,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6654,7 +6643,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7749,7 +7738,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8494,32 +8483,22 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "3.0.0"
|
||||
version = "9.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704"
|
||||
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
|
||||
dependencies = [
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"indexmap",
|
||||
"libc",
|
||||
"memchr",
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ web-time = "1.1.0"
|
||||
rayon = "1"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
|
||||
|
||||
@@ -110,12 +110,20 @@ fn resolve_target(source_dir: &str, target: &str) -> String {
|
||||
|
||||
type Zip<'a> = zip::ZipArchive<Cursor<&'a [u8]>>;
|
||||
|
||||
fn zip_names(zip: &mut Zip<'_>) -> Vec<String> {
|
||||
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| f.name().to_string())).collect()
|
||||
/// `(index, name)` of every file entry. Parts are read by index: two entries can decode to the
|
||||
/// same name, and looking up a CP437 name scans the whole archive.
|
||||
fn zip_names(zip: &mut Zip<'_>) -> Vec<(usize, String)> {
|
||||
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| (i, entry_name(&f)))).collect()
|
||||
}
|
||||
|
||||
fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
|
||||
let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
|
||||
/// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode
|
||||
/// is listed with its raw bytes made lossy, so the entry is still checked and reported.
|
||||
fn entry_name<R: std::io::Read>(f: &zip::read::ZipFile<'_, R>) -> String {
|
||||
f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned())
|
||||
}
|
||||
|
||||
fn read_zip_part(zip: &mut Zip<'_>, index: usize, name: &str) -> Result<Vec<u8>, String> {
|
||||
let f = zip.by_index(index).map_err(|e| format!("{name}: {e}"))?;
|
||||
let mut buf = Vec::new();
|
||||
f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?;
|
||||
Ok(buf)
|
||||
@@ -128,8 +136,8 @@ enum PartError {
|
||||
}
|
||||
|
||||
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
|
||||
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
|
||||
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
|
||||
fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Result<Vec<u8>, PartError> {
|
||||
let f = zip.by_index(index).map_err(|_| PartError::Unreadable)?;
|
||||
// One byte past what is left shows that the part doesn't fit.
|
||||
let limit = MAX_XML_PART.min(budget.saturating_add(1));
|
||||
let mut buf = Vec::new();
|
||||
@@ -150,10 +158,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Resu
|
||||
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
let Ok(mut zip) = zip::ZipArchive::new(Cursor::new(bytes)) else { return false };
|
||||
let names = zip_names(&mut zip);
|
||||
let find = |key: &str| names.iter().find(|n| part_key(n) == key).cloned();
|
||||
let find = |key: &str| names.iter().find(|(_, n)| part_key(n) == key).cloned();
|
||||
let mut workbook = "xl/workbook.xml".to_string();
|
||||
if let Some(rels) = find("_rels/.rels")
|
||||
&& let Ok(xml) = read_zip_part(&mut zip, &rels)
|
||||
if let Some((i, rels)) = find("_rels/.rels")
|
||||
&& let Ok(xml) = read_zip_part(&mut zip, i, &rels)
|
||||
&& let Ok(els) = xml_elements(&xml)
|
||||
&& let Some(target) = els
|
||||
.iter()
|
||||
@@ -162,8 +170,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
{
|
||||
workbook = resolve_target("", target);
|
||||
}
|
||||
let Some(name) = find(&part_key(&workbook)) else { return false };
|
||||
let Ok(xml) = read_zip_part(&mut zip, &name) else { return false };
|
||||
let Some((i, name)) = find(&part_key(&workbook)) else { return false };
|
||||
let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false };
|
||||
xml_elements(&xml)
|
||||
.ok()
|
||||
.into_iter()
|
||||
@@ -177,15 +185,15 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
|
||||
pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
|
||||
let names = zip_names(&mut zip);
|
||||
let parts: HashSet<String> = names.iter().map(|n| part_key(n)).collect();
|
||||
let mut read_part = |name: &str| read_zip_part(&mut zip, name);
|
||||
let parts: HashSet<String> = names.iter().map(|(_, n)| part_key(n)).collect();
|
||||
let mut read_part = |index: usize, name: &str| read_zip_part(&mut zip, index, name);
|
||||
let mut issues = Vec::new();
|
||||
let ct_name = names.iter().find(|n| part_key(n) == "[content_types].xml").cloned();
|
||||
let ct_name = names.iter().find(|(_, n)| part_key(n) == "[content_types].xml").cloned();
|
||||
let (mut defaults, mut overrides) = (HashSet::new(), HashSet::new());
|
||||
match ct_name {
|
||||
None => issues.push("no [Content_Types].xml".to_string()),
|
||||
Some(n) => {
|
||||
for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
|
||||
Some((i, n)) => {
|
||||
for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
|
||||
match el.as_str() {
|
||||
"Default" => {
|
||||
if let Some(x) = attr(&attrs, "Extension") {
|
||||
@@ -202,9 +210,9 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sorted: Vec<&String> = names.iter().collect();
|
||||
sorted.sort();
|
||||
for n in &sorted {
|
||||
let mut sorted: Vec<&(usize, String)> = names.iter().collect();
|
||||
sorted.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
|
||||
for (_, n) in &sorted {
|
||||
let key = part_key(n);
|
||||
if key == "[content_types].xml" {
|
||||
continue;
|
||||
@@ -219,7 +227,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
for p in missing_overrides {
|
||||
issues.push(format!("content type override for missing part /{p}"));
|
||||
}
|
||||
for n in sorted {
|
||||
for (i, n) in sorted {
|
||||
let key = part_key(n);
|
||||
let Some(rels_file) = key.strip_suffix(".rels") else { continue };
|
||||
// `dir/_rels/name.rels` describes `dir/name`; `_rels/.rels` the package itself.
|
||||
@@ -233,7 +241,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
issues.push(format!("{n} describes missing part {source}"));
|
||||
}
|
||||
let mut ids = HashSet::new();
|
||||
for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? {
|
||||
for (el, attrs) in xml_elements(&read_part(*i, n)?).map_err(|e| format!("{n}: {e}"))? {
|
||||
if el != "Relationship" {
|
||||
continue;
|
||||
}
|
||||
@@ -268,17 +276,17 @@ pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String
|
||||
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
|
||||
let names = zip_names(&mut zip);
|
||||
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
|
||||
let by_key: HashMap<String, &(usize, String)> = names.iter().map(|e| (part_key(&e.1), e)).collect();
|
||||
// Several relationships name the same part; each fresh check decompressed it again, so
|
||||
// repeated references to one highly compressible part multiplied the work. The verdict is
|
||||
// remembered per (part, named content) and the decompression the package can cause is
|
||||
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
|
||||
// would otherwise each spend a full per-part allowance.
|
||||
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
|
||||
let mut verdicts: HashMap<(usize, &'static str), bool> = HashMap::new();
|
||||
let mut kinds = BTreeMap::new();
|
||||
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
|
||||
for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) {
|
||||
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
|
||||
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
|
||||
let xml = match read_zip_part_within(&mut zip, *i, &mut budget) {
|
||||
Ok(xml) => xml,
|
||||
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
|
||||
Err(PartError::Unreadable) => continue,
|
||||
@@ -292,8 +300,8 @@ fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<S
|
||||
}
|
||||
let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External"));
|
||||
if !external
|
||||
&& let Some(part) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
|
||||
&& !holds_something(&mut zip, part, kind, &mut verdicts, &mut budget)
|
||||
&& let Some((index, _)) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
|
||||
&& !holds_something(&mut zip, *index, kind, &mut verdicts, &mut budget)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -314,7 +322,7 @@ fn rels_source_dir(key: &str) -> Option<String> {
|
||||
/// comes first) a comment, for VML a shape. Read only as far as needed; an unreadable part counts.
|
||||
/// `verdicts` remembers the answer per (part, named content); `budget` is the decompression this
|
||||
/// package's remaining checks may cause, and once it is spent the part counts as having content.
|
||||
fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'static str), bool>, budget: &mut u64) -> bool {
|
||||
fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool {
|
||||
let wanted: Option<&'static [u8]> = match kind.to_ascii_lowercase().as_str() {
|
||||
"comments" => Some(b"comment"),
|
||||
"vmldrawing" => Some(b"shape"),
|
||||
@@ -325,17 +333,17 @@ fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut Has
|
||||
Some(_) => "shape",
|
||||
None => "any",
|
||||
};
|
||||
if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) {
|
||||
if let Some(v) = verdicts.get(&(index, marker)) {
|
||||
return *v;
|
||||
}
|
||||
let v = holds_something_uncached(zip, name, marker, budget);
|
||||
verdicts.insert((name.to_ascii_lowercase(), marker), v);
|
||||
let v = holds_something_uncached(zip, index, marker, budget);
|
||||
verdicts.insert((index, marker), v);
|
||||
v
|
||||
}
|
||||
|
||||
fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool {
|
||||
fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool {
|
||||
use quick_xml::events::Event;
|
||||
let Ok(f) = zip.by_name(name) else { return true };
|
||||
let Ok(f) = zip.by_index(index) else { return true };
|
||||
if *budget == 0 {
|
||||
return true;
|
||||
}
|
||||
@@ -392,6 +400,57 @@ mod tests {
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
/// A package with two relationship parts whose names both read `xl/_rels/é.xml.rels`: the first
|
||||
/// stored as UTF-8 holding `first`, the second stored as CP437 (byte 0x82) holding `second`.
|
||||
fn same_name_rels(first: &str, second: &str) -> Vec<u8> {
|
||||
const PLACEHOLDER: &[u8] = b"xl/_rels/Q.xml.rels";
|
||||
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
z.start_file("xl/_rels/\u{e9}.xml.rels", opts).unwrap();
|
||||
z.write_all(first.as_bytes()).unwrap();
|
||||
z.start_file(String::from_utf8(PLACEHOLDER.to_vec()).unwrap(), opts).unwrap();
|
||||
z.write_all(second.as_bytes()).unwrap();
|
||||
let mut bytes = z.finish().unwrap().into_inner();
|
||||
// The name sits in the local header and in the central directory; both get the CP437 byte.
|
||||
let mut at = 0;
|
||||
let mut patched = 0;
|
||||
while let Some(i) = bytes.get(at..).and_then(|rest| rest.windows(PLACEHOLDER.len()).position(|w| w == PLACEHOLDER)) {
|
||||
bytes[at + i + 9] = 0x82;
|
||||
at += i + PLACEHOLDER.len();
|
||||
patched += 1;
|
||||
}
|
||||
assert_eq!(patched, 2);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn rels_xml(rels: &[(&str, &str)]) -> String {
|
||||
let body: String = rels
|
||||
.iter()
|
||||
.map(|(id, kind)| {
|
||||
format!(
|
||||
r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}" Target="https://example.com" TargetMode="External"/>"#
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
format!(r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{body}</Relationships>"#)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_with_the_same_decoded_name_are_each_validated() {
|
||||
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "custom"), ("rId1", "custom")]));
|
||||
let issues = validate_package(&bytes).unwrap();
|
||||
let duplicates = issues.iter().filter(|i| i.ends_with("duplicate relationship id rId1")).count();
|
||||
assert_eq!(duplicates, 1, "{issues:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_kinds_read_parts_with_the_same_decoded_name() {
|
||||
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "audio")]));
|
||||
let kinds = relationship_kinds(&bytes).unwrap();
|
||||
assert!(kinds.contains_key("custom"), "{kinds:?}");
|
||||
assert!(kinds.contains_key("audio"), "{kinds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_parts_count_against_the_decompression_budget() {
|
||||
// Each part fits the per-part allowance, but together they need more than the budget.
|
||||
|
||||
@@ -344,7 +344,7 @@ fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec
|
||||
let mut pending: Vec<(&str, &str)> = rels.to_vec();
|
||||
for i in 0..src.len() {
|
||||
let mut f = src.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut body = String::new();
|
||||
f.read_to_string(&mut body).unwrap();
|
||||
if let Some(at) = pending.iter().position(|(r, _)| *r == name) {
|
||||
|
||||
+138
-29
@@ -268,14 +268,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell a desktop user why a nightly launch was refused. A headless form (`--version` on a runner)
|
||||
/// never gets here: the version query is answered before this and before any profile work.
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// Tell a desktop user why a nightly launch was refused, in a native box where one renders without the
|
||||
/// app's event loop (Windows, X11/Wayland), and on standard error always. A headless form (`--version`
|
||||
/// on a runner) never gets here: the version query is answered before this and before any profile work.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("GridCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("GridCraft launch profile: {error}");
|
||||
return;
|
||||
@@ -330,6 +339,55 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
|
||||
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
|
||||
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
|
||||
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
|
||||
/// opened as a file.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct DesktopArgs {
|
||||
control_port: Option<u16>,
|
||||
control_token: Option<String>,
|
||||
sample: Option<String>,
|
||||
files: Vec<String>,
|
||||
}
|
||||
|
||||
fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Option<String>) -> DesktopArgs {
|
||||
let mut parsed = DesktopArgs { control_port, control_token, ..DesktopArgs::default() };
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--" => {
|
||||
parsed.files.extend(args[i + 1..].iter().cloned());
|
||||
break;
|
||||
}
|
||||
"--control" => {
|
||||
i += 1;
|
||||
parsed.control_port = args.get(i).and_then(|p| p.parse().ok());
|
||||
}
|
||||
"--control-token" => {
|
||||
i += 1;
|
||||
parsed.control_token = args.get(i).cloned();
|
||||
}
|
||||
"--sample" => {
|
||||
i += 1;
|
||||
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
|
||||
}
|
||||
a if a.starts_with("-psn_") => {}
|
||||
a => parsed.files.push(a.to_string()),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
/// A nightly owns no control channel, and only options count: everything after `--` is a file, so a
|
||||
/// document named `--control` is opened rather than read as a flag.
|
||||
fn nightly_control_refused(nightly: bool, args: &[String]) -> bool {
|
||||
let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len());
|
||||
nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token")
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
// A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from
|
||||
// this same executable) comes before everything else: it opens no window, writes no log, and
|
||||
@@ -392,34 +450,14 @@ fn main() -> eframe::Result<()> {
|
||||
}
|
||||
// The control channel is a stable-only service: a nightly window owns no port, writes no
|
||||
// token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`.
|
||||
if nightly && args.iter().any(|a| a == "--control" || a == "--control-token") {
|
||||
if nightly_control_refused(nightly, &args) {
|
||||
eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let mut control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
|
||||
let mut control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
|
||||
let mut sample: Option<String> = None;
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--control" => {
|
||||
i += 1;
|
||||
control_port = args.get(i).and_then(|p| p.parse().ok());
|
||||
}
|
||||
"--control-token" => {
|
||||
i += 1;
|
||||
control_token = args.get(i).cloned();
|
||||
}
|
||||
"--sample" => {
|
||||
i += 1;
|
||||
sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
|
||||
}
|
||||
a if a.starts_with("-psn_") => {}
|
||||
a => files.push(a.to_string()),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
|
||||
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
|
||||
let parsed = desktop_args(&args, control_port, control_token);
|
||||
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
|
||||
// The log file lives in the settings folder, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
// first. Runs without preferences (agents' test runs) log to standard error only, so they
|
||||
@@ -449,7 +487,6 @@ fn main() -> eframe::Result<()> {
|
||||
if !nightly {
|
||||
app.start_update_check();
|
||||
}
|
||||
let control_port = control_port;
|
||||
load_prefs(&mut app);
|
||||
// Stamp the startup workbook's author from the persisted user name.
|
||||
if app.session.documents().is_empty() {
|
||||
@@ -616,3 +653,75 @@ mod packaging_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod launch_separator_tests {
|
||||
use super::*;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
|
||||
/// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive
|
||||
/// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too.
|
||||
fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
|
||||
}
|
||||
|
||||
/// The argv the Launcher starts a nightly with, extended by `tail`, as the start then reads it.
|
||||
fn launcher_argv(tail: &[&str]) -> Vec<String> {
|
||||
let mut argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_platforms_root_spelling_is_refused_as_relative() {
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
|
||||
let argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launchers_separator_is_never_a_file() {
|
||||
let parsed = desktop_args(&launcher_argv(&[]), None, None);
|
||||
assert_eq!(parsed, DesktopArgs::default(), "the separator must not reach the file list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_after_the_separator_are_opened_in_order() {
|
||||
assert_eq!(desktop_args(&launcher_argv(&["a.file"]), None, None).files, ["a.file"]);
|
||||
let parsed = desktop_args(&launcher_argv(&["a.file", "--version", "--sample"]), None, None);
|
||||
assert_eq!(parsed.files, ["a.file", "--version", "--sample"], "after -- every word is a file");
|
||||
assert_eq!((parsed.sample, parsed.control_port), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_flag_after_the_separator_is_a_file_not_a_refusal() {
|
||||
let argv = launcher_argv(&["--control"]);
|
||||
assert!(!nightly_control_refused(true, &argv), "a document named --control must open, not refuse");
|
||||
let parsed = desktop_args(&argv, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_flag_before_the_separator_still_names_the_port() {
|
||||
let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()];
|
||||
assert!(nightly_control_refused(true, &with_file));
|
||||
let parsed = desktop_args(&with_file, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (Some(7979), vec!["a.file".to_string()]));
|
||||
let plain = vec!["--control".to_string(), "7979".to_string()];
|
||||
assert!(nightly_control_refused(true, &plain));
|
||||
let parsed = desktop_args(&plain, None, None);
|
||||
assert_eq!((parsed.control_port, parsed.files), (Some(7979), Vec::<String>::new()));
|
||||
assert!(!nightly_control_refused(false, &plain), "the stable app keeps its control channel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,13 @@ impl crate::DocState {
|
||||
// View state: set in place, so the workbook is neither copied nor made dirty.
|
||||
self.wb.set_active_sheet(i);
|
||||
self.selection = self.sheet_selections.get(i).cloned().unwrap_or_default();
|
||||
// A sheet's first visit starts at A1, which may be part of a merged cell: take it whole,
|
||||
// as a click would (#1348). A selection the sheet remembers comes back as it was.
|
||||
if self.selection == crate::Selection::default()
|
||||
&& let Some(sh) = self.wb.sheet(i)
|
||||
{
|
||||
self.selection.expand_merges(sh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -345,7 +345,11 @@ impl DocState {
|
||||
wb.refresh_equations();
|
||||
let scripts_trusted = !cmd::extra::has_scripts(&wb);
|
||||
let wb = Arc::new(wb);
|
||||
let sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
|
||||
let mut sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
|
||||
// A merged active cell is selected whole, as a click on it selects it (#1348).
|
||||
if let Some(sh) = wb.active() {
|
||||
sel.expand_merges(sh);
|
||||
}
|
||||
DocState {
|
||||
saved: wb.clone(),
|
||||
wb,
|
||||
|
||||
@@ -7792,6 +7792,49 @@ fn history_charges_the_storage_of_empty_comment_replies() {
|
||||
assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>());
|
||||
}
|
||||
|
||||
/// #1348: the selection a workbook opens with, and the one a sheet gets on its first visit, take
|
||||
/// a merged active cell whole, as a click on it does: a merge at A1 and one elsewhere. A
|
||||
/// selection the sheet remembers comes back as it was, even inside a merged cell.
|
||||
#[test]
|
||||
fn opening_and_switching_sheets_select_a_merged_active_cell_whole() {
|
||||
let mut wb = gridcraft_model::Workbook::new();
|
||||
let sh = wb.sheet_mut(0).unwrap();
|
||||
sh.set_value(CellRef::new(0, 0), Value::text("Timesheet"));
|
||||
sh.merges.push(gridcraft_core::RangeRef::parse("A1:AG1").unwrap());
|
||||
sh.merges.push(gridcraft_core::RangeRef::parse("C5:E6").unwrap());
|
||||
sh.view_active = CellRef::parse("C5").unwrap();
|
||||
let mut second = gridcraft_model::Sheet::new("Sheet2");
|
||||
second.merges.push(gridcraft_core::RangeRef::parse("A1:C2").unwrap());
|
||||
wb.sheets.push(std::sync::Arc::new(second));
|
||||
wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Sheet3")));
|
||||
let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap();
|
||||
let sel = |s: &Session| {
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
(sel.a1(), sel.active.a1())
|
||||
};
|
||||
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("file.open", json!({"name": "timesheet.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap();
|
||||
assert_eq!(sel(&s), pair("C5:E6", "C5"), "on open, a merge away from A1");
|
||||
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("A1:C2", "A1"), "first visit of a sheet, a merge at A1");
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet3"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("A1", "A1"), "an unmerged A1 stays a single cell");
|
||||
|
||||
// A remembered selection is not expanded again: set one inside Sheet2's merge directly.
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
|
||||
s.doc_mut().unwrap().selection = crate::Selection::at(CellRef::parse("B2").unwrap());
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("C5:E6", "C5"), "Sheet1's remembered selection");
|
||||
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("B2", "B2"), "a remembered selection comes back as it was");
|
||||
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
|
||||
assert_eq!(sel(&s), pair("B3", "B3"), "a remembered selection comes back as it was");
|
||||
}
|
||||
|
||||
/// Paste Link would write links to the cells a cut empties, losing them: a cut can't be pasted
|
||||
/// as links, and nothing changes.
|
||||
#[test]
|
||||
|
||||
@@ -531,7 +531,7 @@ fn edit_parts(bytes: &[u8], mut edit: impl FnMut(&str, String) -> String) -> Vec
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..zip.len() {
|
||||
let mut part = zip.by_index(i).unwrap();
|
||||
let name = part.name().to_string();
|
||||
let name = part.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
part.read_to_end(&mut data).unwrap();
|
||||
let data = match String::from_utf8(data) {
|
||||
|
||||
@@ -56,7 +56,7 @@ fn with_parts(bytes: &[u8], edit: impl Fn(&str, &str) -> String, add: &[(&str, &
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
if let Ok(text) = std::str::from_utf8(&data) {
|
||||
@@ -250,7 +250,7 @@ fn with_damaged_part(bytes: &[u8], name: &str, marker: &str) -> Vec<u8> {
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let entry = f.name().to_string();
|
||||
let entry = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
let options = zip::write::SimpleFileOptions::default();
|
||||
|
||||
@@ -60,7 +60,7 @@ fn edit_chart(bytes: &[u8], edit: impl Fn(String) -> String) -> Vec<u8> {
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_string();
|
||||
let name = f.name().unwrap().to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
if name == "xl/charts/chart1.xml" {
|
||||
|
||||
@@ -496,7 +496,16 @@ fn yearfrac(a: &[Arg], c: &mut dyn Ctx) -> R<Value> {
|
||||
let sys = c.date_system();
|
||||
let s = day_arg(a, 0, sys)?;
|
||||
let e = day_arg(a, 1, sys)?;
|
||||
let basis = if has(a, 2) { to_int(num(a, 2)?)? } else { 0 };
|
||||
let basis = if has(a, 2) {
|
||||
let raw = num(a, 2)?;
|
||||
// Excel rejects any negative basis before truncation: -0.9 would truncate to 0 and slip through.
|
||||
if raw < 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
to_int(raw)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
num_val(yearfrac_core(sys, s, e, basis)?)
|
||||
}
|
||||
|
||||
@@ -850,6 +859,19 @@ mod tests {
|
||||
close(ev("YEARFRAC", vec![n(d(2021.0, 2.0, 28.0)), n(d(2021.0, 2.0, 28.0)), n(0.0)]), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yearfrac_rejects_negative_fractional_basis() {
|
||||
// Excel rejects any negative basis: -0.9 must not truncate to 0.
|
||||
let (s, e) = (n(d(2024.0, 1.0, 15.0)), n(d(2025.0, 6.0, 30.0)));
|
||||
is_err(ev("YEARFRAC", vec![s.clone(), e.clone(), n(-0.9)]), CellError::Num);
|
||||
// A positive fraction still truncates to basis 0.
|
||||
let whole = match ev("YEARFRAC", vec![s.clone(), e.clone(), n(0.0)]) {
|
||||
Value::Number(x) => x,
|
||||
v => panic!("YEARFRAC basis 0 gave {v:?}"),
|
||||
};
|
||||
close_tol(ev("YEARFRAC", vec![s, e, n(0.9)]), whole, 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_lifting() {
|
||||
let v = ev("YEAR", vec![av(row(&[43831.0, 46302.0]))]);
|
||||
|
||||
@@ -24,7 +24,12 @@ fn serial(sys: DateSystem, y: i32, m: u32, d: u32) -> R<f64> {
|
||||
}
|
||||
|
||||
pub(super) fn basis_arg(a: &[Arg], i: usize) -> R<u32> {
|
||||
let b = opt_num(a, i, 0.0)?.trunc();
|
||||
let raw = opt_num(a, i, 0.0)?;
|
||||
// Excel rejects any negative basis before truncation: -0.9 would truncate to -0.0 and slip through.
|
||||
if raw < 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let b = raw.trunc();
|
||||
if !(0.0..=4.0).contains(&b) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
|
||||
@@ -273,6 +273,21 @@ fn number(v: Value) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// A negative fractional basis is #NUM!, not truncation toward zero (#4058).
|
||||
#[test]
|
||||
fn negative_fractional_basis_is_rejected() {
|
||||
let price = |basis: f64| ev("PRICE", vec![d(2024, 1, 15), d(2025, 6, 30), n(0.05), n(0.04), n(100.0), n(2.0), n(basis)]);
|
||||
is_err(price(-0.9), CellError::Num);
|
||||
is_err(ev("COUPDAYS", vec![d(2011, 1, 25), d(2011, 11, 15), n(2.0), n(-0.9)]), CellError::Num);
|
||||
is_err(ev("PRICEMAT", vec![d(2008, 2, 15), d(2008, 4, 13), d(2007, 11, 11), n(0.061), n(0.061), n(-0.9)]), CellError::Num);
|
||||
is_err(ev("ACCRINTM", vec![d(2008, 4, 1), d(2008, 6, 15), n(0.1), n(1000.0), n(-0.5)]), CellError::Num);
|
||||
// Controls: a positive fraction still truncates to basis 0, and -1 is still #NUM!.
|
||||
close_tol(price(0.9), 101.40114791702759, 1e-9);
|
||||
close_tol(price(0.0), 101.40114791702759, 1e-9);
|
||||
close(ev("COUPDAYS", vec![d(2011, 1, 25), d(2011, 11, 15), n(2.0), n(0.9)]), 180.0);
|
||||
is_err(price(-1.0), CellError::Num);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_periods() {
|
||||
// The worked examples on Microsoft's function pages (results as printed there).
|
||||
|
||||
@@ -131,6 +131,15 @@ impl SheetApp {
|
||||
if id == "file.exportPdf" && self.services.pick_save.is_some() && params.get("path").and_then(Json::as_str).is_none_or(str::is_empty) {
|
||||
return self.export_pdf_with_picker(params);
|
||||
}
|
||||
// Menu-style AutoSum on one cell proposes its formula in the editor with the range
|
||||
// pointed and selected, so a click, drag, arrow key or typing replaces it, as in Excel.
|
||||
// Programmatic callers use `run` and get the total entered.
|
||||
if id == "formulas.autoSum"
|
||||
&& params.get("range").and_then(Json::as_str).is_none()
|
||||
&& self.session.active().is_some_and(|d| d.selection.current().is_single())
|
||||
{
|
||||
return self.auto_sum_in_editor(params);
|
||||
}
|
||||
// Recommended Charts with no chart type named (ribbon button, keytip, command search) asks
|
||||
// which chart to insert; programmatic callers of `run` still get the first recommendation.
|
||||
if id == "insert.recommendedCharts" && params.get("type").is_none() {
|
||||
@@ -152,6 +161,24 @@ impl SheetApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs AutoSum on the active cell without entering it (`enter: false`) and points the
|
||||
/// proposed range in the editor that opens.
|
||||
fn auto_sum_in_editor(&mut self, params: Json) {
|
||||
let mut params = if params.is_object() { params } else { json!({}) };
|
||||
if let Some(map) = params.as_object_mut() {
|
||||
map.insert("enter".into(), Json::Bool(false));
|
||||
}
|
||||
if let Err(e) = self.run("formulas.autoSum", params) {
|
||||
return self.alert(e);
|
||||
}
|
||||
if let Some(ed) = self.editor.as_mut() {
|
||||
ed.point_last_argument();
|
||||
if ed.can_point() {
|
||||
self.session.mode = gridcraft_engine::Mode::Point;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a command error: a toast for an unavailable command, else a message box.
|
||||
pub(crate) fn alert(&mut self, e: String) {
|
||||
// Shown in the window the user ends up in, also after a command that switched windows.
|
||||
|
||||
@@ -56,6 +56,8 @@ pub struct EditState {
|
||||
pub completion: Option<String>,
|
||||
/// Move the caret to the end on the next frame.
|
||||
pub caret_to_end: bool,
|
||||
/// Select from this char index to `caret` when the caret is next pushed into the widget.
|
||||
pub select_from: Option<usize>,
|
||||
/// 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>,
|
||||
@@ -141,6 +143,7 @@ impl EditState {
|
||||
keep_selection: false,
|
||||
caret_to_end: true,
|
||||
completion: None,
|
||||
select_from: None,
|
||||
original,
|
||||
list: None,
|
||||
list_accept: false,
|
||||
@@ -497,6 +500,23 @@ impl EditState {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Points and selects the argument of the call that ends the text, as AutoSum proposes it
|
||||
/// (`=SUM(B1:B3)`): a click, drag, arrow key or typing replaces `B1:B3`. An arrow key moves
|
||||
/// from the range's first cell, as in Excel: ↑ on `=SUM(A2:A4)` gives `=SUM(A1)`. With no
|
||||
/// argument (`=SUM()`) the caret goes between the parentheses.
|
||||
pub fn point_last_argument(&mut self) {
|
||||
let Some(open) = self.text.rfind('(') else { return };
|
||||
let Some(close) = self.text.len().checked_sub(1).filter(|&c| c > open && self.text.ends_with(')')) else { return };
|
||||
let chars = |byte: usize| self.text.get(..byte).map_or(0, |t| t.chars().count());
|
||||
let (start, end) = (open + 1, close);
|
||||
self.caret = chars(end);
|
||||
self.point = (start < end).then_some((start, end));
|
||||
self.select_from = (start < end).then(|| chars(start));
|
||||
self.point_cell = self.text.get(start..end).and_then(RangeRef::parse).map(|r| r.start);
|
||||
self.caret_to_end = false;
|
||||
self.sync_caret = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// References in formula text with their byte spans and colour index (same reference text ⇒
|
||||
@@ -626,6 +646,29 @@ mod tests {
|
||||
assert!(!e2.can_point());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosum_points_and_selects_its_proposed_range() {
|
||||
// #1834: Excel leaves AutoSum's range ready to be replaced by pointing or typing.
|
||||
let mut e = EditState::new(1, 0, CellRef::new(3, 0), "=SUM(A1:A3)".into(), true, false);
|
||||
e.point_last_argument();
|
||||
assert!(e.can_point());
|
||||
assert_eq!((e.caret, e.select_from, e.point), (10, Some(5), Some((5, 10))));
|
||||
assert_eq!(e.point_cell, Some(CellRef::new(0, 0)), "arrow keys move from the range's first cell");
|
||||
e.insert_ref("A2");
|
||||
assert_eq!(e.text, "=SUM(A2)");
|
||||
// No proposal: the caret waits between the parentheses.
|
||||
let mut e = EditState::new(1, 0, CellRef::new(3, 0), "=SUMA()".into(), true, false);
|
||||
e.point_last_argument();
|
||||
assert!(e.can_point());
|
||||
assert_eq!((e.caret, e.select_from, e.point), (6, None, None));
|
||||
e.insert_ref("B2");
|
||||
assert_eq!(e.text, "=SUMA(B2)");
|
||||
// Text without a closing call is left alone.
|
||||
let mut e = EditState::new(1, 0, CellRef::new(3, 0), "=SUM(".into(), true, false);
|
||||
e.point_last_argument();
|
||||
assert_eq!((e.caret, e.point), (5, None));
|
||||
}
|
||||
|
||||
#[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);
|
||||
|
||||
@@ -568,8 +568,12 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font:
|
||||
resp.request_focus();
|
||||
}
|
||||
ed.request_focus = false;
|
||||
// Closing a dialog that changed nothing (Cancel) gives the selection back as it was.
|
||||
let range = if ed.keep_selection && !ed.sync_caret {
|
||||
// Closing a dialog that changed nothing (Cancel) gives the selection back as it was, and
|
||||
// AutoSum's proposed range comes selected (`select_from`).
|
||||
let range = if let Some(from) = ed.select_from.take() {
|
||||
ed.anchor = from;
|
||||
egui::text::CCursorRange::two(egui::text::CCursor::new(from), egui::text::CCursor::new(ed.caret))
|
||||
} else if ed.keep_selection && !ed.sync_caret {
|
||||
egui::text::CCursorRange::two(egui::text::CCursor::new(ed.anchor), egui::text::CCursor::new(ed.caret))
|
||||
} else {
|
||||
ed.anchor = ed.caret;
|
||||
|
||||
@@ -575,7 +575,8 @@ pub(super) fn home(app: &mut SheetApp, ui: &mut Ui) {
|
||||
|
||||
fn font_combo(app: &mut SheetApp, ui: &mut Ui, st: &Style) {
|
||||
let name = st.font.name.clone();
|
||||
let resp = ui.add_sized([150.0, 24.0], egui::Button::new(egui::RichText::new(&name).font(theme::ui_font(12.5))));
|
||||
// The trailing grow atom left-aligns the existing label inside the button.
|
||||
let resp = ui.add_sized([150.0, 24.0], egui::Button::new(egui::RichText::new(&name).font(theme::ui_font(12.5))).right_text(()));
|
||||
control_keytip(app, ui, &resp, "home.fontName");
|
||||
let forced = invoke(app, "home.fontName");
|
||||
let items: Vec<(&str, String)> = FONTS.iter().map(|f| (*f, f.to_string())).collect();
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! AutoSum from the ribbon or keyboard on one cell proposes its formula in the editor, with the
|
||||
//! range ready to be replaced by pointing or typing, as in Excel (#1834).
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2};
|
||||
use gridcraft_engine::core::{CellRef, Value};
|
||||
use gridcraft_engine::{Mode, Session};
|
||||
use gridcraft_ui_egui::grid::Geo;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::Harness;
|
||||
|
||||
/// 1, 2, 3 in A1:A3 and `selected` selected.
|
||||
fn harness(selected: &str) -> Harness {
|
||||
harness_at("A1", selected)
|
||||
}
|
||||
|
||||
/// 1, 2, 3 down from `first` and `selected` selected.
|
||||
fn harness_at(first: &str, selected: &str) -> Harness {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("range.setValues", json!({"range": first, "values": [[1], [2], [3]]})).unwrap();
|
||||
session.execute("selection.set", json!({"range": selected})).unwrap();
|
||||
crate::common::harness_with(crate::common::builder().with_size(egui::vec2(1200.0, 800.0)), crate::common::app(session), 4)
|
||||
}
|
||||
|
||||
/// The AutoSum button: a menu-style run.
|
||||
fn auto_sum(h: &mut Harness) {
|
||||
h.state_mut().run_or_alert("formulas.autoSum", json!({}));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn editing(h: &Harness) -> Option<String> {
|
||||
h.state().editor.as_ref().map(|e| e.text.clone())
|
||||
}
|
||||
|
||||
fn input(h: &Harness, cell: &str) -> String {
|
||||
h.state().session.active().unwrap().wb.active().unwrap().input_text(CellRef::parse(cell).unwrap())
|
||||
}
|
||||
|
||||
fn cell_center(h: &Harness, cell: &str) -> Pos2 {
|
||||
let app = h.state();
|
||||
let sheet = app.session.active().unwrap().wb.active().unwrap();
|
||||
let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll);
|
||||
geo.cell_rect(sheet, CellRef::parse(cell).unwrap()).center()
|
||||
}
|
||||
|
||||
fn pointer(h: &mut Harness, cell: &str, pressed: bool) {
|
||||
let pos = cell_center(h, cell);
|
||||
h.input_mut()
|
||||
.events
|
||||
.extend([Event::PointerMoved(pos), Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn enter(h: &mut Harness) {
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE });
|
||||
}
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosum_on_one_cell_proposes_its_range_in_the_editor() {
|
||||
let mut h = harness("A4");
|
||||
auto_sum(&mut h);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A3)"));
|
||||
assert_eq!(h.state().session.mode, Mode::Point);
|
||||
assert_eq!(input(&h, "A4"), "", "nothing is entered before Enter");
|
||||
enter(&mut h);
|
||||
assert_eq!(input(&h, "A4"), "=SUM(A1:A3)");
|
||||
assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse("A4").unwrap()), Value::Number(6.0));
|
||||
|
||||
// A `range` that isn't text is no range, for the engine and here alike.
|
||||
let mut h = harness("A4");
|
||||
h.state_mut().run_or_alert("formulas.autoSum", json!({"range": null}));
|
||||
h.run_steps(2);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A3)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_autosum_menu_functions_propose_theirs_the_same_way() {
|
||||
// Home › AutoSum ▾ Average (and Formulas › AutoSum ▾ once it has the menu, #658).
|
||||
let mut h = harness("A4");
|
||||
h.state_mut().run_or_alert("formulas.autoSum", json!({"function": "AVERAGE"}));
|
||||
h.run_steps(2);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=AVERAGE(A1:A3)"));
|
||||
pointer(&mut h, "A2", true);
|
||||
pointer(&mut h, "A2", false);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=AVERAGE(A2)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_or_drag_replaces_the_proposed_range() {
|
||||
let mut h = harness("A4");
|
||||
auto_sum(&mut h);
|
||||
pointer(&mut h, "A2", true);
|
||||
pointer(&mut h, "A2", false);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A2)"));
|
||||
|
||||
let mut h = harness("A4");
|
||||
auto_sum(&mut h);
|
||||
pointer(&mut h, "A1", true);
|
||||
let to = cell_center(&h, "A2");
|
||||
for pos in [to, to + egui::vec2(1.0, 0.0)] {
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
h.step();
|
||||
}
|
||||
pointer(&mut h, "A2", false);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A2)"));
|
||||
enter(&mut h);
|
||||
assert_eq!(input(&h, "A4"), "=SUM(A1:A2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arrow_key_points_from_the_proposed_range() {
|
||||
// Observed in Excel for the web: ↑ after AutoSum moves from the range's first cell.
|
||||
let mut h = harness_at("A2", "A5");
|
||||
auto_sum(&mut h);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A2:A4)"));
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(Event::Key { key: Key::ArrowUp, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE });
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A1)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_replaces_the_proposed_range() {
|
||||
let mut h = harness("A4");
|
||||
auto_sum(&mut h);
|
||||
h.input_mut().events.push(Event::Text("A2:A3".into()));
|
||||
h.run_steps(2);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A2:A3)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_to_sum_the_caret_waits_between_the_parentheses() {
|
||||
let mut h = harness("C10");
|
||||
auto_sum(&mut h);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM()"));
|
||||
pointer(&mut h, "A1", true);
|
||||
pointer(&mut h, "A1", false);
|
||||
assert_eq!(editing(&h).as_deref(), Some("=SUM(A1)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_and_programmatic_calls_enter_the_totals_at_once() {
|
||||
let mut h = harness("A1:A4");
|
||||
auto_sum(&mut h);
|
||||
assert!(h.state().editor.is_none());
|
||||
assert_eq!(input(&h, "A4"), "=SUM(A1:A3)");
|
||||
|
||||
// The control channel, CLI and MCP run commands with `run`: no editor.
|
||||
let mut h = harness("A4");
|
||||
h.state_mut().run("formulas.autoSum", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().editor.is_none());
|
||||
assert_eq!(input(&h, "A4"), "=SUM(A1:A3)");
|
||||
}
|
||||
@@ -136,6 +136,10 @@ fn autosum_runs_sum_and_its_arrow_opens_the_shared_menu() {
|
||||
}
|
||||
h.run_steps(2);
|
||||
click(&mut h, "AutoSum");
|
||||
// One cell: the proposed formula waits in the editor for Enter, as in Excel (#1834).
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("=SUM(A1:A3)"));
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(input(&h, "A4"), "=SUM(A1:A3)");
|
||||
h.state_mut().session.execute("selection.set", json!({"cell": "B4"})).unwrap();
|
||||
click(&mut h, "AutoSum options");
|
||||
@@ -143,6 +147,9 @@ fn autosum_runs_sum_and_its_arrow_opens_the_shared_menu() {
|
||||
h.get_by_label(item);
|
||||
}
|
||||
click(&mut h, "Count Numbers");
|
||||
assert_eq!(editor_text(&h).as_deref(), Some("=COUNT(B1:B3)"));
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(input(&h, "B4"), "=COUNT(B1:B3)");
|
||||
click(&mut h, "AutoSum options");
|
||||
click(&mut h, "More Functions…");
|
||||
|
||||
@@ -418,9 +418,10 @@ fn alt_equals_autosum_does_not_also_type_the_equals_sign() {
|
||||
for (selected, cell, formula) in [("A4", "A4", "=SUM(A1:A3)"), ("C3", "C3", "=SUM(A3:B3)"), ("A1:B3", "B4", "=SUM(B1:B3)")] {
|
||||
let mut h = harness(book(selected));
|
||||
alt_equals(&mut h);
|
||||
assert_eq!(input(&h, cell), formula, "Alt+= on {selected}");
|
||||
assert!(h.state().editor.is_none(), "Alt+= on {selected} started an edit");
|
||||
// Enter moves on: there is no stray `=` edit to commit.
|
||||
// One cell: the formula waits in the editor for Enter, as in Excel (#1834); a block gets
|
||||
// its totals at once. Either way without a stray `=`.
|
||||
let editing = h.state().editor.as_ref().map(|e| e.text.clone());
|
||||
assert_eq!(editing.as_deref(), (!selected.contains(':')).then_some(formula), "Alt+= on {selected}");
|
||||
key(&mut h, Key::Enter, Modifiers::NONE);
|
||||
assert!(h.state().message.is_none(), "Alt+= on {selected}: {:?}", h.state().message);
|
||||
assert_eq!(input(&h, cell), formula);
|
||||
|
||||
@@ -11,6 +11,7 @@ mod active_row_highlight;
|
||||
mod advanced_filter;
|
||||
mod argument_names;
|
||||
mod autosave_persist;
|
||||
mod autosum_edit;
|
||||
mod borders;
|
||||
mod cell_editor_caret;
|
||||
mod cell_pictures;
|
||||
|
||||
@@ -522,6 +522,30 @@ fn pending_sequences_go_live_when_the_command_lands() {
|
||||
assert_eq!(h.state().keytips.prefix(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_name_box_left_aligns_short_and_long_names() -> Result<(), String> {
|
||||
for name in ["Arial", "Calibri", "Times New Roman"] {
|
||||
let mut session = blank();
|
||||
session.execute("home.fontName", json!({"name": name})).map_err(|e| e.to_string())?;
|
||||
let h = harness(session);
|
||||
// Querying the original name also checks that the button keeps its accessible label.
|
||||
let rect = h.get_by_role_and_label(egui::accesskit::Role::Button, name).rect();
|
||||
assert!((rect.width() - 150.0).abs() < 0.1 && (rect.height() - 24.0).abs() < 0.1, "{name}: {rect:?}");
|
||||
let text_x = h
|
||||
.output()
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|shape| match &shape.shape {
|
||||
egui::Shape::Text(text) if text.galley.text() == name && rect.contains(text.pos) => Some(text.pos.x),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or("font name was not painted inside its button")?;
|
||||
let inset = text_x - rect.left();
|
||||
assert!((0.0..=10.0).contains(&inset), "{name}: expected a small left inset, got {inset}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_keytips_open_dropdowns_and_run_handlers() {
|
||||
// HFF routes to the font control: its dropdown opens (popup items queryable).
|
||||
|
||||
@@ -42,7 +42,7 @@ fn unzip(bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
m.insert(f.name().to_string(), b);
|
||||
m.insert(f.name().unwrap().to_string(), b);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
@@ -477,7 +477,7 @@ fn drawing_with_picture_and_chart() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut d = vec![];
|
||||
std::io::Read::read_to_end(&mut f, &mut d).unwrap();
|
||||
parts.push((f.name().to_string(), d));
|
||||
parts.push((f.name().unwrap().to_string(), d));
|
||||
}
|
||||
parts.push(("xl/media/image1.png".into(), png.to_vec()));
|
||||
let refs: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect();
|
||||
|
||||
@@ -163,7 +163,7 @@ fn hostile_threaded_comments_persons_and_note_vml() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut d = vec![];
|
||||
std::io::Read::read_to_end(&mut f, &mut d).unwrap();
|
||||
parts.push((f.name().to_string(), d));
|
||||
parts.push((f.name().unwrap().to_string(), d));
|
||||
}
|
||||
let ns = r#"xmlns="http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments""#;
|
||||
let deep = "<v:group>".repeat(300) + &"</v:group>".repeat(300);
|
||||
|
||||
@@ -26,7 +26,7 @@ fn package() -> Vec<u8> {
|
||||
/// The written VML part (GridCraft writes one per sheet with notes).
|
||||
fn written_vml(bytes: &[u8]) -> String {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let name = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).find(|n| n.ends_with(".vml")).expect("a VML part");
|
||||
let name = (0..z.len()).map(|i| z.by_index(i).unwrap().name().unwrap().to_string()).find(|n| n.ends_with(".vml")).expect("a VML part");
|
||||
let mut s = String::new();
|
||||
z.by_name(&name).unwrap().read_to_string(&mut s).unwrap();
|
||||
s
|
||||
|
||||
@@ -129,7 +129,7 @@ impl Unpacked {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut v = vec![];
|
||||
f.read_to_end(&mut v).unwrap();
|
||||
parts.insert(f.name().to_string(), v);
|
||||
parts.insert(f.name().unwrap().to_string(), v);
|
||||
}
|
||||
Unpacked { parts }
|
||||
}
|
||||
@@ -707,7 +707,7 @@ fn chart_sheet_entries_sharing_a_graph_are_checked_once() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
parts.push((f.name().to_string(), data));
|
||||
parts.push((f.name().unwrap().to_string(), data));
|
||||
}
|
||||
let extra: String = (0..3_000).map(|i| format!(r#"<sheet name="Copy{i}" sheetId="{}" r:id="rId2"/>"#, 100 + i)).collect();
|
||||
for (name, data) in &mut parts {
|
||||
|
||||
@@ -210,7 +210,7 @@ fn unzip(bytes: &[u8]) -> HashMap<String, Vec<u8>> {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let mut b = Vec::new();
|
||||
f.read_to_end(&mut b).unwrap();
|
||||
m.insert(f.name().to_string(), b);
|
||||
m.insert(f.name().unwrap().to_string(), b);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
@@ -634,7 +634,7 @@ fn assert_drawing_and_chart_roundtrip(a: &Sheet, b: &Sheet) {
|
||||
fn package_structure() {
|
||||
let bytes = write_xlsx(&sample()).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.name_for_index(i).unwrap().to_string()).collect();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.name_for_index(i).unwrap().unwrap().to_string()).collect();
|
||||
assert_eq!(names[0], "[Content_Types].xml");
|
||||
for n in [
|
||||
"_rels/.rels",
|
||||
@@ -928,7 +928,7 @@ fn vba_project_roundtrip() {
|
||||
assert_eq!(write_xlsx(&wb).unwrap(), bytes, "output is deterministic");
|
||||
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).unwrap();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.name_for_index(i).unwrap().to_string()).collect();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.name_for_index(i).unwrap().unwrap().to_string()).collect();
|
||||
assert!(names.iter().any(|x| x == "xl/vbaProject.bin"), "missing vbaProject.bin");
|
||||
let mut bin = vec![];
|
||||
z.by_name("xl/vbaProject.bin").unwrap().read_to_end(&mut bin).unwrap();
|
||||
|
||||
@@ -25,7 +25,7 @@ fn sheet_with(name: &str, pictures: &[(u32, &[u8])]) -> Arc<Sheet> {
|
||||
|
||||
fn names(bytes: &[u8]) -> Vec<String> {
|
||||
let z = zip::ZipArchive::new(std::io::Cursor::new(bytes.to_vec())).unwrap();
|
||||
z.file_names().map(str::to_string).collect()
|
||||
z.file_names().map(|n| n.unwrap().into_owned()).collect()
|
||||
}
|
||||
|
||||
fn text(bytes: &[u8], name: &str) -> String {
|
||||
|
||||
@@ -108,7 +108,7 @@ fn every_trendline_kind_round_trips_in_every_chart_group() {
|
||||
fn chart_parts(bytes: &[u8]) -> Vec<String> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.to_vec())).unwrap();
|
||||
let mut names: Vec<String> =
|
||||
(0..z.len()).map(|i| z.name_for_index(i).unwrap().to_string()).filter(|n| n.starts_with("xl/charts/chart")).collect();
|
||||
(0..z.len()).map(|i| z.name_for_index(i).unwrap().unwrap().to_string()).filter(|n| n.starts_with("xl/charts/chart")).collect();
|
||||
names.sort();
|
||||
names
|
||||
.iter()
|
||||
|
||||
@@ -17,7 +17,7 @@ fn package_starts_with_content_types_rels_and_workbook_before_any_large_part() {
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let names: Vec<String> = (0..zip.len()).filter_map(|i| zip.by_index(i).ok().map(|f| f.name().to_string())).collect();
|
||||
let names: Vec<String> = (0..zip.len()).filter_map(|i| zip.by_index(i).ok().map(|f| f.name().unwrap().to_string())).collect();
|
||||
assert_eq!(names.first().map(String::as_str), Some("[Content_Types].xml"), "{names:?}");
|
||||
assert_eq!(names.get(1).map(String::as_str), Some("_rels/.rels"), "{names:?}");
|
||||
assert_eq!(names.get(2).map(String::as_str), Some("xl/_rels/workbook.xml.rels"), "{names:?}");
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
# UI parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
|
||||
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
|
||||
@@ -60,9 +60,8 @@ this logic, with one undo step.
|
||||
| Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series; month patterns use the workbook's 1900 or 1904 date system); right-drag menu partial: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, and from a date Fill Days, Fill Weekdays, Fill Months and Fill Years, then Series…; a left-drag leaves an Auto Fill Options button with the same fill choices (gone once the workbook changes or the selection moves); Linear/Growth Trend and Flash Fill missing |
|
||||
| Drag-move and drag-copy cells (border drag, Ctrl/Option, Shift to insert) | border drag moves (M3) and asks "There's already data here. Do you want to replace it?" before replacing cells that hold data (`range.move`, #3136); Ctrl/Option to copy and Shift to insert are not wired to the border drag yet (reorder whole columns by their headers instead) |
|
||||
| In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done |
|
||||
| Point mode (click/drag/arrow references), reference colouring, F4 | done; dragging over row or column headers points at whole rows or columns (`A:C`, `2:5`); Command/Ctrl-click adds separate arguments with the edit's locale separator, and Shift-click extends the current reference from a fixed anchor on the same sheet. Pointer-event regressions cover repeated/reversed selections, manual separators, sheet switches and keyboard continuation. |
|
||||
| Point mode (click/drag/arrow references), reference colouring, F4 | done; dragging over row or column headers points at whole rows or columns (`A:C`, `2:5`); Command/Ctrl-click adds separate arguments with the edit's locale separator, and Shift-click extends the current reference from a fixed anchor on the same sheet. Pointer-event regressions cover repeated/reversed selections, manual separators, sheet switches and keyboard continuation. AutoSum on one cell leaves its proposed range pointed and selected (#1834) |
|
||||
| Number-format colors (`[Green]`, `[Color1]`–`[Color56]`) | Rendered in grid and PDF from shared RGB mappings (#1452) |
|
||||
| Point mode (click/drag/arrow references), reference colouring, F4 | done |
|
||||
| AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) |
|
||||
| Searchable data validation dropdown (typing filters the in-cell list) | done (10-21): entries with a word starting with the typed text, ignoring case and the accents of Latin letters (é, ç, ß, ł, ș, ǎ, Vietnamese ộ: Latin-1, Latin Extended-A and -B, Latin Extended Additional; other scripts keep their marks), in list order; Up/Down highlight, Enter/Tab/Ctrl+Enter/click commit the highlighted entry as the list spells it (other commits, such as clicking another cell, keep the typed text), Escape hides the list then cancels; `data.validationList {cell, search?}` gives agents the same search. The search reads at most 200,000 cells of the list's source and keeps at most 10,000 matches; past either, `truncated` is set and the popup says more entries aren't shown (validation itself still checks the whole list). Fuzzy matching isn't offered (Excel doesn't either); behaviour follows the documented Excel 365 feature, not yet measured against the app |
|
||||
| Header resize and double-click AutoFit | done (#42, #88 for header dividers) |
|
||||
@@ -271,6 +270,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-19 | minor | AutoSum from the ribbon or keyboard on one cell proposes `=SUM(range)` in the editor instead of entering it, with the range pointed and selected: a click, drag, arrow key or typing replaces it and Enter enters it, as in Excel. With nothing to sum the caret waits inside `=SUM()`. A block still gets its totals at once, and programmatic `formulas.autoSum` is unchanged (#1834) |
|
||||
| 2026-11-15 | minor | The rows of both validation list popups are drawn in slots of exactly the row height the popup scrolls by, so a font whose text is laid out a pixel taller than its nominal line height no longer pushes the last visible row under the "More entries not shown" note (seen with the pinned test fonts, not with the fonts of a desktop install). That note is translated in all 18 interface catalogs, and the validation-list UI tests run on the pinned font set |
|
||||
| 2026-11-14 | minor | The searched validation list measures its rows at their real height, like the dropdown arrow's list: it shows eight rows instead of six, the highlighted row stays in view and the last entries of a long list can be reached. It opens above the cell when it would run past the bottom of the window, measures its width once per search instead of every frame, and its "More entries not shown" note goes through the interface translations. Typing over the open dropdown drops the entries the dropdown had read |
|
||||
| 2026-11-13 | minor | The full list the dropdown arrow (or Alt+Down) opens reads its source once while it stays open, within the same 200,000-cell budget, and draws only the rows in view, so a list over a huge column no longer rereads and redraws every entry each frame; it says when entries aren't shown, and its rows are measured at their real height so eight show, as intended |
|
||||
|
||||
Reference in New Issue
Block a user