From 8732325b589a91465cfe703adbe6243c37fb47a5 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Wed, 14 Oct 2026 15:42:49 -0500 Subject: [PATCH 01/95] ft-121.1.25: keep PivotTables whose source is in another workbook on XLSX save A PivotTable whose cache's worksheetSource has an r:id to an externalLinkPath relationship (range or defined name in another workbook) was read as a model pivot with an unresolvable source, and the writer then skipped it silently: the table, cache definition, records, the cache's link and the workbook's pivotCache entry were all lost. Such PivotTables are now reported by read_pivots instead of modelled and kept by the pass-through layer: the table parts with their sheet, the cache and records with the workbook and its original cacheId. Written pivot caches skip the kept ids, a cache no kept table uses is dropped, and the kept parts' dxfId and numFmtId references are renumbered to the rewritten styles part (Excel refuses to open the file otherwise). gridcraft-cli check counts kept PivotTables. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- apps/gridcraft-cli/src/check.rs | 9 +- crates/model/src/preserved.rs | 8 + crates/xlsx/src/passthrough.rs | 281 ++++++++++++++++++++- crates/xlsx/src/pivot.rs | 82 +++++- crates/xlsx/src/read.rs | 8 +- crates/xlsx/src/tests/passthrough_tests.rs | 244 ++++++++++++++++++ crates/xlsx/src/write.rs | 20 +- docs/file-format-parity.md | 5 +- 9 files changed, 630 insertions(+), 31 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..cb756e2aa7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** trivial (progress log: XLSX PivotTables on another workbook kept on save) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | @@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook kept on save | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | | 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) | diff --git a/apps/gridcraft-cli/src/check.rs b/apps/gridcraft-cli/src/check.rs index 2b85298765..3a398b86ac 100644 --- a/apps/gridcraft-cli/src/check.rs +++ b/apps/gridcraft-cli/src/check.rs @@ -593,6 +593,13 @@ fn cond_format_list(s: &Sheet) -> Vec { cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect() } +/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is +/// in another workbook). +fn pivot_count(s: &Sheet) -> usize { + let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count()); + s.pivots.len() + kept +} + fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) { if a != b { d.push(|| format!("{sheet}: {a} → {b}")); @@ -682,7 +689,7 @@ pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec BTreeSet { diff --git a/crates/model/src/preserved.rs b/crates/model/src/preserved.rs index eab8501577..2f76e52e54 100644 --- a/crates/model/src/preserved.rs +++ b/crates/model/src/preserved.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use crate::sheet::Visibility; +use crate::style::Style; /// A relationship from an owning part (the package root, the workbook or a sheet, or a kept part) /// to a kept part or to an external target. @@ -32,6 +33,13 @@ pub struct PreservedPart { pub data: Arc<[u8]>, /// The part's own relationships, ids unchanged (the part's bytes refer to them). pub rels: Vec, + /// Differential formats its XML refers to by `dxfId`, by their id in the source file's styles + /// part. GridCraft rewrites the styles part, so the ids are renumbered on save (kept + /// PivotTables). + pub dxfs: Vec<(u32, Style)>, + /// Custom number formats its XML refers to by `numFmtId` (code by id in the source file), + /// renumbered on save like [`Self::dxfs`] (kept PivotTables and pivot caches). + pub num_fmts: Vec<(u32, String)>, } /// A raw XML element of an owning part that refers to kept parts, re-emitted on save with its diff --git a/crates/xlsx/src/passthrough.rs b/crates/xlsx/src/passthrough.rs index dd881c1e9a..fbff953537 100644 --- a/crates/xlsx/src/passthrough.rs +++ b/crates/xlsx/src/passthrough.rs @@ -6,7 +6,10 @@ //! their ``, data connections, XML maps) and each sheet (query tables, cells //! mapped to XML elements, form controls, ActiveX controls, OLE objects, the sheet background and //! printer settings, with the sheet's ``, `` and `` XML, the `r:id` -//! of `` and the legacy VML shapes those controls need). The workbook also keeps its +//! of `` and the legacy VML shapes those controls need). PivotTables whose source is in +//! another workbook are kept too: the PivotTable parts with their sheet, the cache definition and +//! records parts (with the cache's link to the other workbook's path) with the workbook and its +//! `` entry, its `cacheId` unchanged. The workbook also keeps its //! `` and the calcFeatures extension, which Excel needs to trust the saved values. //! //! On write, kept parts get fresh part names where needed and new relationship ids; the `r:id`s in @@ -18,6 +21,7 @@ //! opened, followed or refreshed. A relative path to a linked workbook is rewritten when the //! workbook is saved into another folder ([`rebase_links`]), so it still names the same file. //! - Sheet content lives on the sheet: deleting the sheet drops it, Copy Sheet doesn't copy it. +//! A kept pivot cache no kept PivotTable uses any more is dropped with it. //! Cell references inside kept parts (a control's linked cell, a query table's range, a cell //! mapped to an XML element) are kept as they were, not adjusted to inserted or deleted rows. //! - Strict Open XML files are not passed through (their namespaces differ from what we write). @@ -37,6 +41,7 @@ use quick_xml::{Reader, Writer}; use crate::IoError; use crate::package::{self, normalize}; +use crate::pivot::{CT_PIVOT_CACHE_DEF, CT_PIVOT_TABLE, ExternalPivot}; use crate::read::Ctx; use crate::write::{NS_REL, Out, Rels, XML_DECL}; use crate::xml::{self, esc_attr}; @@ -93,6 +98,11 @@ const CALC_FEATURES_URI: &str = "{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}"; const NS_CALC_FEATURES: &str = "http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures"; /// Kept sheet elements, in schema order (all after ``, before ``). const SHEET_SLOTS: &[&str] = &["picture", "oleObjects", "controls"]; +/// Rewritten kinds a kept PivotTable (source in another workbook) reaches: the table, from the +/// sheet, and its cache, which the workbook keeps (several tables can share one cache). +const PIVOT_TABLE_GRAPH: &[&str] = &["pivotTable", "pivotCacheDefinition"]; +/// Rewritten kinds a kept pivot cache reaches. +const PIVOT_CACHE_GRAPH: &[&str] = &["pivotCacheDefinition", "pivotCacheRecords"]; /// Relationship kinds GridCraft reads and rewrites, or that depend on content it rewrites: /// kept content whose graph reaches one of them is dropped. @@ -231,6 +241,9 @@ pub struct KeptReader { overrides: HashMap, budget: usize, parts_left: usize, + /// Cache definition parts of the PivotTables kept with their sheets (source in another + /// workbook), kept with the workbook. + pivot_caches: Vec, } impl KeptReader { @@ -242,6 +255,7 @@ impl KeptReader { overrides: HashMap::new(), budget: kept_total(), parts_left: MAX_KEPT_PARTS, + pivot_caches: vec![], }; if let Ok(root) = raw_rels(cx, "") && root.iter().any(|r| r.rel_type.starts_with("http://purl.oclc.org/")) @@ -319,7 +333,12 @@ impl KeptReader { } queue.push_back((r.target.clone(), depth + 1)); } - parts.push(PreservedPart { name, content_type, data: Arc::from(data), rels }); + let (dxfs, num_fmts) = if content_type == CT_PIVOT_TABLE || content_type == CT_PIVOT_CACHE_DEF { + style_refs(cx, &data).ok_or_else(|| format!("{name} is damaged"))? + } else { + (vec![], vec![]) + }; + parts.push(PreservedPart { name, content_type, data: Arc::from(data), rels, dxfs, num_fmts }); } self.budget = self.budget.saturating_sub(bytes); self.parts_left = self.parts_left.saturating_sub(parts.len()); @@ -433,6 +452,7 @@ impl KeptReader { Err(why) => cx.warn(format!("links to external workbooks were dropped: {why}")), } } + self.keep_pivot_caches(cx, wb_xml, &wb_rels, &mut p, &mut seen); // Excel trusts the saved cell values only when both are present; without them it // recalculates everything on open, and links into closed workbooks come back as errors. if let Some(v) = wb_xml.child("fileVersion") { @@ -460,9 +480,37 @@ impl KeptReader { (!p.is_empty()).then(|| Arc::new(p)) } - /// Sheet-level content of the sheet part `part`. - pub fn sheet(&mut self, cx: &mut Ctx<'_>, part: &str, name: &str) -> Option> { + /// The caches of the kept PivotTables, each with its `` entry (original `cacheId` + /// and relationship id). + fn keep_pivot_caches(&mut self, cx: &mut Ctx<'_>, wb_xml: &xml::El, wb_rels: &[PreservedRel], p: &mut Preserved, seen: &mut HashSet) { + let caches = std::mem::take(&mut self.pivot_caches); + for cache in &caches { + let entry = wb_xml.child("pivotCaches").into_iter().flat_map(|c| c.kids("pivotCache")).find_map(|c| { + let id = c.attr_u32("cacheId")?; + let r = wb_rels.iter().find(|r| Some(r.id.as_str()) == c.attr("id") && !r.external && is_kind(r, &["pivotCacheDefinition"]))?; + (normalize(&r.target) == normalize(cache)).then(|| (id, r.clone())) + }); + let Some((id, r)) = entry else { + cx.warn(format!("the cache {cache} of a PivotTable on another workbook is not in the workbook's list; the PivotTable was dropped")); + continue; + }; + match self.keep_through(cx, p, std::slice::from_ref(&r), seen, PIVOT_CACHE_GRAPH) { + Ok(()) => p.elements.push(PreservedXml { + slot: "pivotCache".into(), + xml: format!("", esc_attr(&r.id)), + }), + Err(why) => cx.warn(format!("the cache of a PivotTable on another workbook was dropped with its PivotTables: {why}")), + } + } + } + + /// Sheet-level content of the sheet part `part`; `pivots` are its PivotTables whose source is + /// in another workbook. + pub fn sheet(&mut self, cx: &mut Ctx<'_>, part: &str, name: &str, pivots: &[ExternalPivot]) -> Option> { if !self.on { + if !pivots.is_empty() { + cx.warn(format!("sheet \"{name}\": PivotTables on another workbook are not kept on save in this file")); + } return None; } let rels = match raw_rels(cx, part) { @@ -482,6 +530,22 @@ impl KeptReader { if rels.iter().any(|r| is_kind(r, SHEET_ELEMENT_KINDS)) { self.sheet_elements(cx, part, name, &rels, &mut p, &mut seen); } + for ep in pivots { + let Some(r) = rels.iter().find(|r| r.id == ep.rel_id && !r.external && is_kind(r, &["pivotTable"])) else { continue }; + // The cache is kept with the workbook, not followed from here. + let mut scoped = seen.clone(); + scoped.insert(normalize(&ep.cache_part)); + match self.keep_through(cx, &mut p, std::slice::from_ref(r), &mut scoped, PIVOT_TABLE_GRAPH) { + Ok(()) => { + scoped.remove(&normalize(&ep.cache_part)); + seen = scoped; + if !self.pivot_caches.iter().any(|c| normalize(c) == normalize(&ep.cache_part)) { + self.pivot_caches.push(ep.cache_part.clone()); + } + } + Err(why) => cx.warn(format!("sheet \"{name}\": a PivotTable on another workbook was dropped: {why}")), + } + } (!p.is_empty()).then(|| Arc::new(p)) } @@ -571,11 +635,137 @@ impl KeptReader { let mut q = Preserved::default(); let roots: Vec = vrels.iter().filter(|r| !r.external).cloned().collect(); self.keep(cx, &mut q, &roots, seen)?; - let vml = PreservedPart { name: rel.target.clone(), content_type: CT_VML.into(), data: Arc::from(text.into_bytes()), rels: vrels }; + let vml = PreservedPart { + name: rel.target.clone(), + content_type: CT_VML.into(), + data: Arc::from(text.into_bytes()), + rels: vrels, + ..Default::default() + }; Ok((vml, q.parts)) } } +/// Attribute values of `local` (any prefix) in an XML part, in document order. `None` when the +/// XML is damaged. +fn attr_values(data: &[u8], local: &[&[u8]], mut f: impl FnMut(&[u8], &str)) -> Option<()> { + let text = xml::to_utf8(data); + let mut reader = Reader::from_reader(text.as_ref()); + let mut buf = vec![]; + loop { + match reader.read_event_into(&mut buf).ok()? { + Event::Eof => return Some(()), + Event::Start(e) | Event::Empty(e) => { + for a in e.attributes().with_checks(false) { + let a = a.ok()?; + let k = a.key.local_name(); + if let Some(name) = local.iter().find(|n| **n == k.as_ref()) + && let Ok(v) = std::str::from_utf8(&a.value) + { + f(name, v); + } + } + } + _ => {} + } + buf.clear(); + } +} + +/// The differential formats (`dxfId`) and custom number formats (`numFmtId`) of the source +/// styles part a kept PivotTable or pivot cache refers to. `None` when its XML is damaged. +type StyleRefs = (Vec<(u32, gridcraft_model::Style)>, Vec<(u32, String)>); +fn style_refs(cx: &Ctx<'_>, data: &[u8]) -> Option { + let mut dxfs: Vec<(u32, gridcraft_model::Style)> = vec![]; + let mut fmts: Vec<(u32, String)> = vec![]; + attr_values(data, &[b"dxfId", b"numFmtId"], |name, v| { + let Ok(id) = v.trim().parse::() else { return }; + if name == b"dxfId" { + if !dxfs.iter().any(|(i, _)| *i == id) + && let Some(s) = cx.dxfs.get(id as usize) + { + dxfs.push((id, s.clone())); + } + } else if !fmts.iter().any(|(i, _)| *i == id) + && let Some(code) = cx.num_fmts.get(&id) + { + fmts.push((id, code.clone())); + } + })?; + Some((dxfs, fmts)) +} + +/// Rewrites the values of `dxfId` and `numFmtId` attributes through the maps (ids not in a map +/// are kept). `None` when the XML is damaged. +fn map_style_ids(data: &[u8], dxfs: &HashMap, fmts: &HashMap) -> Option> { + let text = xml::to_utf8(data); + let mut reader = Reader::from_reader(text.as_ref()); + let mut writer = Writer::new(Vec::with_capacity(data.len())); + let mut buf = vec![]; + let map = |e: &BytesStart<'_>| -> Option> { + let name = String::from_utf8(e.name().as_ref().to_vec()).ok()?; + let mut out = BytesStart::new(name); + for a in e.attributes().with_checks(false) { + let a = a.ok()?; + let k = a.key.local_name(); + let table = match k.as_ref() { + b"dxfId" => Some(dxfs), + b"numFmtId" => Some(fmts), + _ => None, + }; + let new = table.and_then(|t| std::str::from_utf8(&a.value).ok()?.trim().parse::().ok().and_then(|id| t.get(&id))); + match new { + Some(n) => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(n.to_string().into_bytes()) }), + None => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(a.value.to_vec()) }), + } + } + Some(out) + }; + loop { + match reader.read_event_into(&mut buf).ok()? { + Event::Eof => break, + Event::Start(e) => writer.write_event(Event::Start(map(&e)?)).ok()?, + Event::Empty(e) => writer.write_event(Event::Empty(map(&e)?)).ok()?, + ev => writer.write_event(ev).ok()?, + } + buf.clear(); + } + Some(writer.into_inner()) +} + +/// Kept parts whose style ids are renumbered once the styles part is written. +#[derive(Default)] +pub struct StylePatches { + /// (written part name, source bytes, dxf id map, source number format id → code). + list: Vec<(String, Arc<[u8]>, HashMap, Vec<(u32, String)>)>, +} + +impl KeptOut { + /// Number format codes kept parts refer to (to be registered in the styles part). + pub fn num_fmt_codes(&self) -> Vec { + let mut v: Vec = vec![]; + for (_, _, _, fmts) in &self.patches.list { + for (_, code) in fmts { + if !v.contains(code) { + v.push(code.clone()); + } + } + } + v + } +} + +/// Renumbers the `dxfId` and `numFmtId` attributes of kept PivotTables and pivot caches to the +/// written styles part. `fmt_id` maps a number format code to its id there. +pub fn finish_style_ids(out: &mut Out, fmt_id: &dyn Fn(&str) -> Option) { + for (name, data, dxfs, fmts) in std::mem::take(&mut out.kept.patches.list) { + let fmts: HashMap = fmts.iter().filter_map(|(old, code)| Some((*old, fmt_id(code)?))).collect(); + if let Some(x) = map_style_ids(&data, &dxfs, &fmts) { + out.replace(&name, x); + } + } +} + /// What a sheet part holds for pass-through. struct SheetScan { /// (slot, XML with the namespace declarations it needs). @@ -839,6 +1029,10 @@ pub struct KeptOut { n: u32, /// Package-root relationships (type, target, external), added when `_rels/.rels` is written. root: Vec<(String, String, bool)>, + /// Names of the workbook's kept parts, which sheets' kept parts can refer to (the cache of a + /// kept PivotTable). + wb_names: NameMap, + patches: StylePatches, } impl KeptOut { @@ -892,18 +1086,27 @@ fn part_rels_xml(rels: &[PreservedRel], names: &NameMap) -> String { s } +/// Writes kept parts. Their relationships can also point at the workbook's kept parts. fn write_parts(out: &mut Out, parts: &[PreservedPart]) -> NameMap { let mut names = NameMap::new(); for p in parts { names.entry(normalize(&p.name)).or_insert_with(|| out.kept.claim(&p.name)); } + let own: HashSet = names.values().cloned().collect(); + for (k, v) in &out.kept.wb_names { + names.entry(k.clone()).or_insert_with(|| v.clone()); + } let mut written = HashSet::new(); for p in parts { let Some(new) = names.get(&normalize(&p.name)).cloned() else { continue }; - if !written.insert(new.clone()) { + if !own.contains(&new) || !written.insert(new.clone()) { continue; } out.part(&new, Some(&p.content_type), p.data.to_vec()); + if !p.dxfs.is_empty() || !p.num_fmts.is_empty() { + let dxfs = p.dxfs.iter().map(|(old, s)| (*old, crate::styles::dxf_id(&mut out.dxfs, s))).collect(); + out.kept.patches.list.push((new.clone(), p.data.clone(), dxfs, p.num_fmts.clone())); + } if !p.rels.is_empty() { out.part(&rels_part_name(&new), None, part_rels_xml(&p.rels, &names).into_bytes()); } @@ -941,9 +1144,25 @@ pub struct WorkbookKept { /// Workbook XML elements that go right after `` (``). pub elements: String, sheets: Vec, + /// Kept pivot caches: (`cacheId`, new relationship id). + pivot_caches: Vec<(u32, String)>, } impl WorkbookKept { + /// The `cacheId`s of the kept pivot caches (written PivotTables must not reuse them). + pub fn pivot_cache_ids(&self) -> Vec { + self.pivot_caches.iter().map(|(id, _)| *id).collect() + } + + /// The `` entries of the kept pivot caches. + pub fn pivot_cache_entries(&self) -> String { + let mut x = String::new(); + for (id, rid) in &self.pivot_caches { + let _ = write!(x, "", esc_attr(rid)); + } + x + } + /// Where the model's sheet `i` is in the file's sheet list: chart sheets come between worksheets. pub fn file_index(&self, i: usize) -> usize { i + self.sheets.iter().filter(|s| s.before <= i).count() @@ -1061,9 +1280,22 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb let Some(p) = wb.preserved.as_deref() else { return WorkbookKept::default() }; let (live, dropped): (Vec<&PreservedSheet>, Vec<&PreservedSheet>) = p.sheets.iter().partition(|s| chart_sheet_usable(wb, p, s)); let root_of = |s: &PreservedSheet| p.rels.iter().find(|r| r.id == s.rel_id); - let dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect(); - // Parts reached only by dropped chart sheets go with them. - let mut gone: HashSet = dropped.iter().filter_map(|s| root_of(s)).flat_map(|r| reachable(p, r)).collect(); + // Pivot caches no kept PivotTable of a sheet uses any more (their sheets were deleted). + let used_caches: HashSet = wb + .sheets + .iter() + .filter_map(|s| s.preserved.as_deref()) + .flat_map(|q| q.parts.iter().flat_map(|part| part.rels.iter())) + .filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"])) + .map(|r| normalize(&r.target)) + .collect(); + let unused_caches: Vec<&PreservedRel> = + p.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]) && !used_caches.contains(&normalize(&r.target))).collect(); + let mut dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect(); + dropped_ids.extend(unused_caches.iter().map(|r| r.id.as_str())); + // Parts reached only by dropped chart sheets and pivot caches go with them. + let mut gone: HashSet = + dropped.iter().filter_map(|s| root_of(s)).chain(unused_caches.iter().copied()).flat_map(|r| reachable(p, r)).collect(); if !gone.is_empty() { let others = p.rels.iter().filter(|r| !dropped_ids.contains(r.id.as_str())).flat_map(|r| reachable(p, r)); for n in others { @@ -1079,7 +1311,18 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb out.kept.root.push((r.rel_type.clone(), target, r.external)); } } + let pivot_caches = p + .elements + .iter() + .filter(|e| e.slot == "pivotCache") + .filter_map(|e| { + let x = xml::parse(e.xml.as_bytes()).ok()?; + Some((x.attr_u32("cacheId")?, ids.get(x.attr("id")?)?.clone())) + }) + .collect(); + out.kept.wb_names = names; WorkbookKept { + pivot_caches, elements: p.elements.iter().filter(|e| e.slot == "externalReferences").filter_map(|e| remap(&e.xml, &ids)).collect(), sheets: live .iter() @@ -1112,8 +1355,24 @@ impl<'a> SheetKept<'a> { /// Writes the sheet's kept parts and adds their relationships to the sheet's. pub fn write(sheet: &'a Sheet, rels: &mut Rels, out: &mut Out) -> SheetKept<'a> { let Some(p) = sheet.preserved.as_deref() else { return SheetKept { p: None, names: NameMap::new(), ids: HashMap::new() } }; - let names = write_parts(out, &p.parts); - let ids = attach(rels, &p.rels, &names); + // A kept PivotTable whose cache wasn't kept with the workbook is left out. + let wb_names = &out.kept.wb_names; + let orphan: HashSet = p + .parts + .iter() + .filter(|q| q.rels.iter().any(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]) && !wb_names.contains_key(&normalize(&r.target)))) + .map(|q| normalize(&q.name)) + .collect(); + let (parts, sheet_rels): (Cow<'_, [PreservedPart]>, Cow<'_, [PreservedRel]>) = if orphan.is_empty() { + (Cow::Borrowed(&p.parts), Cow::Borrowed(&p.rels)) + } else { + ( + p.parts.iter().filter(|q| !orphan.contains(&normalize(&q.name))).cloned().collect(), + p.rels.iter().filter(|r| r.external || !orphan.contains(&normalize(&r.target))).cloned().collect(), + ) + }; + let names = write_parts(out, &parts); + let ids = attach(rels, &sheet_rels, &names); SheetKept { p: Some(p), names, ids } } diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 609ae530e1..0d7a9cd3c7 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -10,6 +10,11 @@ //! Reading: the cache's source and field names plus the table's areas, functions, show-values-as, //! layout flags, grand totals and style become a model [`PivotTable`]. Anything we don't model //! (OLAP sources, calculated fields, numeric grouping…) becomes a warning. +//! +//! A PivotTable whose source is a range or name in another workbook (its cache's +//! `worksheetSource` has an `r:id` to an `externalLinkPath` relationship) is not modelled: +//! GridCraft never opens the other workbook, so it couldn't refresh it. [`read_pivots`] reports +//! it instead, and `passthrough` keeps its PivotTable, cache and records parts unchanged. use std::collections::HashMap; use std::fmt::Write as _; @@ -267,6 +272,11 @@ pub struct PivotWriter { caches: Vec<(u32, String)>, pending: Vec, tables: u32, + /// Cache ids taken by kept pivot caches (PivotTables on another workbook). + reserved: Vec, + /// `` entries of the kept caches. + kept_entries: String, + next_id: u32, } struct Pending { @@ -278,6 +288,21 @@ struct Pending { } impl PivotWriter { + /// A writer whose caches don't reuse the kept caches' ids; `kept_entries` (their + /// `` elements) are listed with the written ones. + pub fn new(reserved: Vec, kept_entries: String) -> PivotWriter { + PivotWriter { reserved, kept_entries, ..PivotWriter::default() } + } + + fn next_cache_id(&mut self) -> u32 { + loop { + self.next_id = self.next_id.saturating_add(1); + if !self.reserved.contains(&self.next_id) || self.next_id == u32::MAX { + return self.next_id; + } + } + } + /// Writes the caches of a sheet's PivotTables and adds the sheet's relationships to its /// PivotTable parts. Pivots whose source can't be resolved are not written. pub fn add_sheet(&mut self, wb: &Workbook, si: usize, out: &mut Out, rels: &mut Rels) { @@ -285,6 +310,7 @@ impl PivotWriter { for (idx, pt) in sheet.pivots.iter().enumerate() { let Some(cache) = build_cache(wb, pt, si) else { continue }; let n = self.caches.len() as u32 + 1; + let cache_id = self.next_cache_id(); let cache_part = format!("xl/pivotCache/pivotCacheDefinition{n}.xml"); let rec_rid = if let Some((count, xml)) = &cache.records { let mut r = Rels::default(); @@ -297,24 +323,25 @@ impl PivotWriter { None }; out.part(&cache_part, Some(CT_PIVOT_CACHE_DEF), cache_xml(&cache, rec_rid.as_deref(), wb.date_system).into_bytes()); - self.caches.push((n, format!("pivotCache/pivotCacheDefinition{n}.xml"))); + self.caches.push((cache_id, format!("pivotCache/pivotCacheDefinition{n}.xml"))); self.tables += 1; let t = self.tables; rels.add("pivotTable", &format!("../pivotTables/pivotTable{t}.xml")); let mut tr = Rels::default(); tr.add("pivotCacheDefinition", &format!("../pivotCache/pivotCacheDefinition{n}.xml")); out.part(&format!("xl/pivotTables/_rels/pivotTable{t}.xml.rels"), None, tr.xml().into_bytes()); - self.pending.push(Pending { part: format!("xl/pivotTables/pivotTable{t}.xml"), sheet: si, idx, cache_id: n, cache }); + self.pending.push(Pending { part: format!("xl/pivotTables/pivotTable{t}.xml"), sheet: si, idx, cache_id, cache }); } } /// Adds the workbook relationships to the caches; returns the `` element (empty /// when there are none). pub fn workbook_xml(&self, wb_rels: &mut Rels) -> String { - if self.caches.is_empty() { + if self.caches.is_empty() && self.kept_entries.is_empty() { return String::new(); } let mut s = String::from(""); + s.push_str(&self.kept_entries); for (id, target) in &self.caches { let rid = wb_rels.add("pivotCacheDefinition", target); let _ = write!(s, ""); @@ -1052,6 +1079,24 @@ impl FieldIn { struct CacheIn { source: String, fields: Vec, + /// The source is in another workbook: the PivotTables on this cache are kept, not modelled. + external: bool, +} + +/// A PivotTable whose source is in another workbook, kept unchanged for saving. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalPivot { + /// The id of the sheet's relationship to the PivotTable part. + pub rel_id: String, + /// The pivot cache definition part it uses. + pub cache_part: String, +} + +/// The PivotTables of a sheet: those modelled, and those kept as they are. +#[derive(Debug, Default)] +pub struct SheetPivots { + pub tables: Vec, + pub external: Vec, } /// Workbook-level pivot cache lookup, filled from ``; caches are parsed once. @@ -1102,12 +1147,18 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option return None; } let ws = src.and_then(|s| s.child("worksheetSource")); + // A source in another workbook: `r:id` names the cache's link to that workbook's path. + if let Some(rid) = ws.and_then(|w| w.attr("id")) { + let linked = cx.pkg.rels(part).ok().is_some_and(|rels| rels.iter().any(|r| r.id == rid && r.external && r.kind == "externalLinkPath")); + if !linked { + cx.warn("a PivotTable's source is in another workbook that its cache doesn't name; kept as plain cells"); + return None; + } + return Some(CacheIn { source: String::new(), fields: vec![], external: true }); + } let source = match ws { Some(w) if w.attr("name").is_some_and(|n| !n.trim().is_empty()) => w.attr("name").unwrap_or("").trim().to_string(), Some(w) => { - if w.attr("id").is_some() { - cx.warn("a PivotTable's source is in another workbook; its source reference may not resolve"); - } let r = w.attr("ref").map(|r| r.replace('$', "")).and_then(|r| RangeRef::parse(&r)); let Some(r) = r else { cx.warn("a PivotTable's source reference is missing or invalid; kept as plain cells"); @@ -1151,13 +1202,14 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option cx.warn("a PivotTable's cache has no fields; kept as plain cells"); return None; } - Some(CacheIn { source, fields }) + Some(CacheIn { source, fields, external: false }) } -/// Reads the PivotTables related to a worksheet part. -pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result, IoError> { +/// Reads the PivotTables related to a worksheet part. Those whose source is in another workbook +/// are listed in [`SheetPivots::external`] (with a warning), not modelled. +pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result { let rels = cx.pkg.rels(sheet_part)?; - let mut out = Vec::new(); + let mut out = SheetPivots::default(); for rel in rels.iter().filter(|r| r.kind == "pivotTable" && !r.external) { let Some(x) = cx.optional_xml(&rel.target)? else { continue }; if x.name != "pivotTableDefinition" { @@ -1184,9 +1236,17 @@ pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sh } }; let Some(cache) = cache else { continue }; + if cache.external { + let name = x.attr("name").unwrap_or(""); + cx.warn(format!( + "PivotTable \"{name}\" on sheet \"{sheet_name}\" gets its data from another workbook: it is kept for saving as it is, but can't be edited or refreshed here" + )); + out.external.push(ExternalPivot { rel_id: rel.id.clone(), cache_part }); + continue; + } if let Some(pt) = read_table(cx, &x, &cache, caches.next_id) { caches.next_id = caches.next_id.saturating_add(1); - out.push(pt); + out.tables.push(pt); } } Ok(out) diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 1a479081c2..99cb543b1a 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -227,12 +227,16 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { Sheet::new(name.clone()) } }; + let mut external_pivots = vec![]; match crate::pivot::read_pivots(&mut cx, &mut pivot_caches, &rel.target, &name) { - Ok(p) => sheet.pivots = p, + Ok(p) => { + sheet.pivots = p.tables; + external_pivots = p.external; + } Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)), Err(e) => cx.warn(format!("PivotTables on sheet \"{name}\" could not be read: {e}")), } - sheet.preserved = kept.sheet(&mut cx, &rel.target, &name); + sheet.preserved = kept.sheet(&mut cx, &rel.target, &name, &external_pivots); sheet.visibility = match se.attr("state") { Some("hidden") => Visibility::Hidden, Some("veryHidden") => Visibility::VeryHidden, diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index d844daa055..18b447ad88 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -572,6 +572,7 @@ fn rebased(target: &str, from: &str, to: &str) -> String { content_type: String::new(), data: Arc::from(&b""[..]), rels: vec![link("externalLinkPath"), link("hyperlink")], + ..Default::default() }; let mut wb = gridcraft_model::Workbook::new(); wb.preserved = Some(Arc::new(gridcraft_model::Preserved { parts: vec![part], ..Default::default() })); @@ -823,3 +824,246 @@ fn file_version_and_calc_features_survive_a_save() { let plain = Unpacked::new(&write_xlsx(&gridcraft_model::Workbook::new()).unwrap()).text("xl/workbook.xml"); assert!(!plain.contains("fileVersion") && !plain.contains("extLst"), "{plain}"); } + +// ---------------------------------------------------------------- PivotTables on another workbook + +const EXT_CACHE_RANGE: &str = r#""#; +const EXT_CACHE_NAME: &str = r#""#; +const EXT_LINK_TARGET: &str = "file:///C:/data/source.xlsx"; +const EXT_RECORDS: &str = r#""#; +/// Source styles: custom number format 170 and two differential formats (the second blue). +const EXT_STYLES: &str = r#""#; + +fn ext_cache(source: &str) -> String { + format!( + r#"{source}"# + ) +} + +fn ext_table(name: &str, cache_id: u32) -> String { + format!( + r#""# + ) +} + +/// Sheets "Report" and "More", each with a PivotTable on cache 1, whose source (a range, or a +/// name with `by_name`) is in another workbook; with `shared` both use one cache, otherwise only +/// "Report" has a PivotTable. `link_kind` is the type of the cache's relationship to the source. +fn ext_pivot_package(by_name: bool, shared: bool, link_kind: &str) -> Vec { + let workbook = format!( + r#""# + ); + let ct = |part: &str, ty: &str| format!(r#""#); + let content_types = format!( + r#"{}{}{}{}{}{}{}{}"#, + ct("xl/workbook.xml", "sheet.main"), + ct("xl/worksheets/sheet1.xml", "worksheet"), + ct("xl/worksheets/sheet2.xml", "worksheet"), + ct("xl/styles.xml", "styles"), + ct("xl/pivotTables/pivotTable1.xml", "pivotTable"), + ct("xl/pivotTables/pivotTable2.xml", "pivotTable"), + ct("xl/pivotCache/pivotCacheDefinition1.xml", "pivotCacheDefinition"), + ct("xl/pivotCache/pivotCacheRecords1.xml", "pivotCacheRecords"), + ); + let sheet = |v: &str| { + format!( + r#"x{v}"# + ) + }; + let (s1, s2) = (sheet("5"), sheet("6")); + let cache = ext_cache(if by_name { EXT_CACHE_NAME } else { EXT_CACHE_RANGE }); + let (t1, t2) = (ext_table("Ext1", 1), ext_table("Ext2", 1)); + let link = if link_kind.starts_with("http") { link_kind.to_string() } else { format!("{NS_R}/{link_kind}") }; + let cache_rels = rels(&[("rId1", "pivotCacheRecords", "pivotCacheRecords1.xml"), ("rId2", &link, EXT_LINK_TARGET)]); + let table_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition1.xml")]); + let wb_rels = rels(&[ + ("rId1", "worksheet", "worksheets/sheet1.xml"), + ("rId2", "worksheet", "worksheets/sheet2.xml"), + ("rId3", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition1.xml"), + ("rId4", "styles", "styles.xml"), + ]); + let s1_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable1.xml")]); + let s2_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable2.xml")]); + let mut parts: Vec<(&str, &[u8])> = vec![ + ("[Content_Types].xml", content_types.as_bytes()), + ("_rels/.rels", super::ROOT_RELS.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()), + ("xl/styles.xml", EXT_STYLES.as_bytes()), + ("xl/worksheets/sheet1.xml", s1.as_bytes()), + ("xl/worksheets/sheet2.xml", s2.as_bytes()), + ("xl/worksheets/_rels/sheet1.xml.rels", s1_rels.as_bytes()), + ("xl/pivotTables/pivotTable1.xml", t1.as_bytes()), + ("xl/pivotTables/_rels/pivotTable1.xml.rels", table_rels.as_bytes()), + ("xl/pivotCache/pivotCacheDefinition1.xml", cache.as_bytes()), + ("xl/pivotCache/_rels/pivotCacheDefinition1.xml.rels", cache_rels.as_bytes()), + ("xl/pivotCache/pivotCacheRecords1.xml", EXT_RECORDS.as_bytes()), + ]; + if shared { + parts.push(("xl/worksheets/_rels/sheet2.xml.rels", s2_rels.as_bytes())); + parts.push(("xl/pivotTables/pivotTable2.xml", t2.as_bytes())); + parts.push(("xl/pivotTables/_rels/pivotTable2.xml.rels", table_rels.as_bytes())); + } + make_zip(&parts) +} + +/// The written PivotTable parts of a sheet, through its relationships. +fn written_pivot_tables(u: &Unpacked, sheet: &str) -> Vec { + u.rels(&sheet_part(u, sheet)).into_iter().filter(|r| r.1.ends_with("/pivotTable")).map(|r| r.2).collect() +} + +/// `` entries of a written workbook: (cacheId, cache part). +fn written_pivot_caches(u: &Unpacked) -> Vec<(String, String)> { + let wb = xml::parse(u.parts.get("xl/workbook.xml").unwrap()).unwrap(); + wb.child("pivotCaches") + .map(|c| { + c.kids("pivotCache").map(|e| (e.attr("cacheId").unwrap().to_string(), u.target("xl/workbook.xml", e.attr("id").unwrap()).1)).collect() + }) + .unwrap_or_default() +} + +/// The font colour of `` number `dxf` and the code of number format `fmt` in written styles. +fn written_style(u: &Unpacked, dxf: &str, fmt: &str) -> (String, String) { + let st = xml::parse(u.parts.get("xl/styles.xml").unwrap()).unwrap(); + let d = st.child("dxfs").unwrap().kids("dxf").nth(dxf.parse().unwrap()).unwrap(); + let color = d.child("font").and_then(|f| f.child("color")).and_then(|c| c.attr("rgb")).unwrap_or("").to_string(); + let code = st.child("numFmts").unwrap().kids("numFmt").find(|n| n.attr("numFmtId") == Some(fmt)).unwrap().attr("formatCode").unwrap().to_string(); + (color, code) +} + +#[test] +fn pivot_tables_on_another_workbook_survive_a_save() { + for by_name in [false, true] { + let src = ext_pivot_package(by_name, false, "externalLinkPath"); + let (wb, rep) = read_xlsx(&src).unwrap(); + // Not modelled (GridCraft can't refresh it), but said so. + assert!(wb.sheets.iter().all(|s| s.pivots.is_empty())); + assert!(rep.warnings.iter().any(|w| w.contains("Ext1") && w.contains("another workbook")), "{:?}", rep.warnings); + assert!(!rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings); + let cache_src = ext_cache(if by_name { EXT_CACHE_NAME } else { EXT_CACHE_RANGE }); + // Twice: what the first save kept is read back and kept again. + let first = write_xlsx(&wb).unwrap(); + let (again, _) = read_xlsx(&first).unwrap(); + for saved in [first, write_xlsx(&again).unwrap()] { + let u = Unpacked::new(&saved); + u.assert_valid(); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 1, "{caches:?}"); + let (id, cache_part) = &caches[0]; + assert_eq!(id, "1", "the kept table refers to its cache by this id"); + assert_eq!(u.text(cache_part), cache_src); + let cache_rels = u.rels(cache_part); + let records = cache_rels.iter().find(|r| r.1.ends_with("/pivotCacheRecords")).unwrap(); + assert_eq!(u.text(&records.2), EXT_RECORDS); + assert!( + cache_rels.iter().any(|r| r.0 == "rId2" && r.1.ends_with("/externalLinkPath") && r.2 == EXT_LINK_TARGET && r.3), + "{cache_rels:?}" + ); + let tables = written_pivot_tables(&u, "Report"); + assert_eq!(tables.len(), 1); + assert!(written_pivot_tables(&u, "More").is_empty()); + let t = u.text(&tables[0]); + assert_eq!(u.rels(&tables[0]).iter().find(|r| r.1.ends_with("/pivotCacheDefinition")).unwrap().2, *cache_part); + // Style ids follow the rewritten styles part. + let (color, code) = written_style(&u, &attr_of(&t, "format", "dxfId"), &attr_of(&t, "dataField", "numFmtId")); + assert_eq!((color.as_str(), code.as_str()), ("FF0000FF", "0.0%"), "{t}"); + assert!(t.contains(r#"name="Ext1" cacheId="1""#), "{t}"); + // The report cells are plain cells and stay. + assert!(u.text(&sheet_part(&u, "Report")).contains("5")); + } + } +} + +#[test] +fn pivot_tables_sharing_a_cache_on_another_workbook_keep_one_cache() { + let (wb, _) = read_xlsx(&ext_pivot_package(false, true, "externalLinkPath")).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 1, "{caches:?}"); + assert_eq!(u.find(ext_cache(EXT_CACHE_RANGE).as_bytes()).len(), 1, "the cache is written once"); + for sheet in ["Report", "More"] { + let t = written_pivot_tables(&u, sheet); + assert_eq!(t.len(), 1, "{sheet}"); + assert_eq!(u.rels(&t[0])[0].2, caches[0].1, "{sheet}"); + } + + // Deleting one sheet keeps the cache for the other; when no kept table is left, it goes. + let mut one = wb.clone(); + one.sheets.remove(1); + let u = Unpacked::new(&write_xlsx(&one).unwrap()); + u.assert_valid(); + assert_eq!(written_pivot_caches(&u).len(), 1); + let mut none = wb.clone(); + none.sheets.iter_mut().for_each(|s| Arc::make_mut(s).preserved = None); + let u = Unpacked::new(&write_xlsx(&none).unwrap()); + u.assert_valid(); + assert!(written_pivot_caches(&u).is_empty()); + assert!(u.find(ext_cache(EXT_CACHE_RANGE).as_bytes()).is_empty() && u.find(EXT_RECORDS.as_bytes()).is_empty()); + assert!(!u.text("xl/workbook.xml").contains("pivotCaches")); +} + +#[test] +fn written_pivot_caches_do_not_reuse_kept_cache_ids() { + use gridcraft_core::{CellRef, Value}; + use gridcraft_model::{Cell, PivotField, PivotTable, PivotValue}; + let (mut wb, _) = read_xlsx(&ext_pivot_package(false, false, "externalLinkPath")).unwrap(); + // A PivotTable GridCraft models, on a list on "More". + { + let more = wb.sheet_mut(1).unwrap(); + for (a, v) in [("D1", Value::text("K")), ("E1", Value::text("V")), ("D2", Value::text("a")), ("E2", Value::number(2.0))] { + more.cells.set(CellRef::parse(a).unwrap(), Cell::value(v)); + } + more.pivots.push(PivotTable { + name: "Ours".into(), + source: "More!$D$1:$E$2".into(), + anchor: CellRef::parse("H3").unwrap(), + rows: vec![PivotField { source_col: "K".into(), ..Default::default() }], + values: vec![PivotValue { source_col: "V".into(), name: "Sum of V".into(), ..Default::default() }], + ..Default::default() + }); + } + let saved = write_xlsx(&wb).unwrap(); + let u = Unpacked::new(&saved); + u.assert_valid(); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 2, "{caches:?}"); + assert_ne!(caches[0].0, caches[1].0, "{caches:?}"); + let ours = written_pivot_tables(&u, "More"); + assert_eq!(ours.len(), 1); + let id = attr_of(&u.text(&ours[0]), "pivotTableDefinition", "cacheId"); + assert_ne!(id, "1"); + assert!(caches.iter().any(|(i, part)| *i == id && *part == u.rels(&ours[0])[0].2), "{caches:?}"); + let (back, _) = read_xlsx(&saved).unwrap(); + assert_eq!(back.sheet(1).unwrap().pivots.len(), 1); + assert_eq!(written_pivot_tables(&Unpacked::new(&write_xlsx(&back).unwrap()), "Report").len(), 1); +} + +#[test] +fn a_pivot_cache_naming_no_linked_workbook_is_not_kept() { + // The source `r:id` resolves to something other than a link to a workbook's path. + for kind in ["hyperlink", "http://example.com/unknown"] { + let (wb, rep) = read_xlsx(&ext_pivot_package(false, false, kind)).unwrap(); + assert!(wb.sheets.iter().all(|s| s.pivots.is_empty())); + assert!(rep.warnings.iter().any(|w| w.contains("another workbook") && w.contains("plain cells")), "{:?}", rep.warnings); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_caches(&u).is_empty() && written_pivot_tables(&u, "Report").is_empty()); + } +} + +#[test] +fn a_kept_pivot_table_whose_cache_is_not_listed_is_dropped() { + // The workbook doesn't list the cache: the table can't be written back without it. + let src = ext_pivot_package(false, false, "externalLinkPath"); + let mut parts = Unpacked::new(&src).parts; + let wbx = String::from_utf8(parts.remove("xl/workbook.xml").unwrap()).unwrap().replace(r#""#, ""); + parts.insert("xl/workbook.xml".into(), wbx.into_bytes()); + let list: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect(); + let (wb, rep) = read_xlsx(&make_zip(&list)).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_tables(&u, "Report").is_empty()); + assert!(written_pivot_caches(&u).is_empty()); +} diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 06761f01d2..d95d072da0 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -135,6 +135,12 @@ impl Out { } self.parts.push((name.to_string(), data)); } + /// Replaces the bytes of a part already added. + pub fn replace(&mut self, name: &str, data: Vec) { + if let Some(p) = self.parts.iter_mut().find(|(n, _)| n == name) { + p.1 = data; + } + } pub fn default_type(&mut self, ext: &str, ct: &str) { self.defaults.entry(ext.to_string()).or_insert_with(|| ct.to_string()); } @@ -226,7 +232,7 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { let mut wb_rels = Rels::default(); // Kept content first: the chart sheets among the worksheets need their relationship ids. let kept = crate::passthrough::write_workbook(wb, &mut wb_rels, &mut out); - let mut pivots = crate::pivot::PivotWriter::default(); + let mut pivots = crate::pivot::PivotWriter::new(kept.pivot_cache_ids(), kept.pivot_cache_entries()); let mut sheets_xml = String::new(); let mut sheet_id = 1usize; for (i, sheet) in wb.sheets.iter().enumerate() { @@ -358,8 +364,16 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { w.push_str(""); // Workbook-level parts. - let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &pivots.number_formats(wb)); - pivots.finish(wb, &mut out, &|code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied())); + let mut extra_fmts = pivots.number_formats(wb); + for code in out.kept.num_fmt_codes() { + if !extra_fmts.contains(&code) { + extra_fmts.push(code); + } + } + let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &extra_fmts); + let fmt_id = |code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied()); + pivots.finish(wb, &mut out, &fmt_id); + crate::passthrough::finish_style_ids(&mut out, &fmt_id); out.part("xl/styles.xml", Some("application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"), styles.into_bytes()); wb_rels.add("styles", "styles.xml"); if wb.styles.iter().any(|(_, st)| st.num_fmt.as_str() == "checkbox") { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9884724146..be5da4b727 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** trivial (XLSX chart sheets are kept on save (#727); previously minor: CSV save keeps the separator it was opened with) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (XLSX PivotTables whose source is in another workbook are kept on save; previously trivial: chart sheets are kept on save (#727)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -22,7 +22,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables) on a range, table or name of the same workbook, protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** PivotTables whose source is a range or name in another workbook (their PivotTable, cache definition and records parts and the cache's link to the other workbook's path, with the original `cacheId`; the `dxfId` and `numFmtId` style references are renumbered to the rewritten styles part; they aren't modelled, so they can't be edited or refreshed in GridCraft, their location isn't adjusted when rows or columns are inserted or deleted, and they are dropped with their sheet, a cache no kept PivotTable uses with them; checked in Excel: opens without repair and refreshes from the other workbook), custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures | @@ -85,6 +85,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | XLSX: PivotTables whose source is in another workbook are kept on save (they were dropped with their caches, and the PivotTable was lost); their style references follow the rewritten styles part | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | | 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) | From 8d90b1ea038005bc4bf55c89df4154a16b87e785 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 00:07:34 -0500 Subject: [PATCH 02/95] fix(functions): XIRR and IRR follow Excel's solvers XIRR returned the exact root (Newton with fallbacks and a bracketing search), so it differed from Excel at about 1e-8 and converged where Excel gives #NUM!. It now follows Excel's solver as reconstructed by observing Excel with synthetic inputs: a sign-only search that brackets the root from the guess (doubling; bisecting towards 0, halving towards 0 or stepping halfway to -100% when the root is lower), then bisection with the midpoint taken from the upper end, stopping when half the bracket is under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first value|, at most 100 XNPV evaluations. Dates before the first are allowed as in Excel; a guess at or below -1 is #NUM!. Answers match Excel bit for bit in 888 of 910 synthetic cases with an answer; 97.7% agreement on 1,283 cases. IRR now uses Newton on the discount factor 1/(1+rate), at most 100 steps, stopping at a step under 1e-8, which agrees with Excel's #NUM! cases far better (IRR of -100, 19 zeros, 1E-5 is #NUM!) and with its values to about 1e-12. A guess at or below -1 is #VALUE! like Excel. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/functions/src/financial.rs | 275 ++++++++++++++++++++++++++++-- docs/function-parity.md | 15 +- 3 files changed, 274 insertions(+), 20 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..4cbf9e65a1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** trivial (progress log: XIRR and IRR follow Excel's solvers) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root) and its `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | @@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | | 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) | diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 2758246ceb..5807d02c5d 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -236,8 +236,9 @@ fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { num_val(sum) } -/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. -fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { +/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. XNPV rejects a +/// date before the first; XIRR (`before_first`) takes it, as Excel does. +fn dated_flows(values: &Value, dates: &Value, before_first: bool) -> R<(Vec, Vec)> { let va = as_array(values); let da = as_array(dates); if va.data.len() != da.data.len() { @@ -259,7 +260,7 @@ fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { } } let d0 = *d.first().ok_or(CellError::Num)?; - if d.iter().any(|&x| x < d0 || x < 0.0) { + if d.iter().any(|&x| (x < d0 && !before_first) || x < 0.0) { return Err(CellError::Num); } Ok((v, d)) @@ -275,35 +276,199 @@ fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R { if rate <= -1.0 { return Err(CellError::Num); } - let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value, false)?; num_val(xnpv_calc(rate, &v, &d)) } +/// Excel's XIRR solver, reconstructed by observing Excel with synthetic inputs (not from its +/// code; its documentation says only "iteration", 100 tries and 0.000001 percent). It looks +/// only at the sign of XNPV until the end, so its answer is the root to about 1e-8, not to the +/// last digit: +/// +/// - Bracket the root from the guess (0 counts as 1e-5): double the rate while XNPV keeps the +/// sign it has at the guess and that sign differs from the first value (the root is higher). +/// Otherwise the root is lower: bisect towards 0 if XNPV changes sign there; halve the rate +/// towards 0 if XNPV is larger in size at 0 than at the guess; otherwise try minus the guess +/// and then step halfway to -100% each time. A negative guess only moves towards 0 (root +/// higher) or towards -100% (root lower). +/// - Bisect the bracket, taking the midpoint from the upper end, until half the bracket is +/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first value|; return that +/// midpoint. A zero XNPV counts as the upper side. +/// - Halving towards 0 that gets within that tolerance of 0 without a sign change goes on with +/// the negative side; at most 100 XNPV evaluations in all; a rate of -100% or an XNPV that +/// can't be computed (a negative base for fractional years) is #NUM!. +struct XirrSolver<'a> { + values: &'a [f64], + years: Vec, + evals: usize, + /// XNPV must be within this of 0 at the answer. + residual: f64, +} + +impl XirrSolver<'_> { + const MAX_EVALS: usize = 100; + + fn tol(rate: f64) -> f64 { + 1e-8 * (rate.abs() + 0.5) + } + + fn same_sign(a: f64, b: f64) -> bool { + a * b > 0.0 + } + + fn f(&mut self, rate: f64) -> R { + self.evals += 1; + if self.evals > Self::MAX_EVALS { + return Err(CellError::Num); + } + let base = 1.0 + rate; + if base == 0.0 { + return Err(CellError::Num); + } + let mut sum = 0.0; + for (x, t) in self.values.iter().zip(&self.years) { + sum += x / base.powf(*t); + } + if sum.is_finite() { Ok(sum) } else { Err(CellError::Num) } + } + + fn solve(&mut self, guess: f64) -> R { + let first = self.values.first().copied().unwrap_or(0.0); + let g = if guess == 0.0 { 1e-5 } else { guess }; + let fg = self.f(g)?; + let higher = fg * first < 0.0; + if g > 0.0 { + if higher { + return self.double(g, fg); + } + let f0 = self.f(0.0)?; + if !Self::same_sign(f0, fg) { + return self.bisect(g, fg, 0.0, f0); + } + if f0.abs() > fg.abs() { + return self.halve(g, fg, g, fg); + } + return self.negative_side(g, fg); + } + if higher { self.halve(g, fg, g, fg) } else { self.towards_minus_one(g, fg) } + } + + fn double(&mut self, mut x: f64, mut fx: f64) -> R { + loop { + let next = 2.0 * x; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + (x, fx) = (next, fnext); + } + } + + fn halve(&mut self, mut x: f64, mut fx: f64, g: f64, fg: f64) -> R { + loop { + let step = -x / 2.0; + let next = x + step; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + if step.abs() < Self::tol(next) { + if next < 0.0 { + return Err(CellError::Num); + } + return self.negative_side(g, fg); + } + (x, fx) = (next, fnext); + } + } + + fn negative_side(&mut self, g: f64, fg: f64) -> R { + let fm = self.f(-g)?; + if !Self::same_sign(fm, fg) { + return self.bisect(g, fg, -g, fm); + } + self.towards_minus_one(-g, fm) + } + + fn towards_minus_one(&mut self, mut x: f64, mut fx: f64) -> R { + loop { + let next = x + (-1.0 - x) / 2.0; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + (x, fx) = (next, fnext); + } + } + + fn bisect(&mut self, a: f64, fa: f64, b: f64, fb: f64) -> R { + let (mut lo, mut flo, mut hi) = if a < b { (a, fa, b) } else { (b, fb, a) }; + loop { + let mid = hi - (hi - lo) / 2.0; + let fm = self.f(mid)?; + if (hi - lo) / 2.0 < Self::tol(mid) && fm.abs() < self.residual { + return Ok(mid); + } + if Self::same_sign(fm, flo) { + (lo, flo) = (mid, fm); + } else { + hi = mid; + } + } + } +} + fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { - let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?; let guess = opt_num(a, 2, 0.1)?; - if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { + if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } - num_val(solve_rate(|r| xnpv_calc(r, &v, &d), guess)?) + let d0 = d.first().copied().unwrap_or(0.0); + let first = v.first().copied().unwrap_or(0.0); + let mut solver = XirrSolver { values: &v, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; + num_val(solver.solve(guess)?) +} + +/// Excel's IRR solver, approximated from observation (Excel's documentation says 20 tries and +/// 0.00001 percent): Newton's method on the discount factor 1/(1+rate), where the cash flows +/// are a polynomial, from 1/(1+guess) until a step moves less than 1e-8, for at most 100 steps. +/// Excel's answers agree with it to about 1e-12 on ordinary flows (the last digits differ) and +/// on which flows have no answer, apart from a few far from any guess. +fn irr_solve(v: &[f64], guess: f64) -> R { + let mut x = 1.0 / (1.0 + guess); + for _ in 0..100 { + let (mut s, mut ds) = (0.0, 0.0); + for c in v.iter().rev() { + ds = ds * x + s; + s = s * x + c; + } + if ds == 0.0 { + return Err(CellError::Num); + } + let next = x - s / ds; + if !next.is_finite() { + return Err(CellError::Num); + } + if (next - x).abs() < 1e-8 { + return if next > 0.0 { Ok(1.0 / next - 1.0) } else { Err(CellError::Num) }; + } + x = next; + } + Err(CellError::Num) } fn irr(a: &[Arg], _c: &mut dyn Ctx) -> R { let v = array_numbers(&a.first().ok_or(CellError::Value)?.value)?; let guess = opt_num(a, 1, 0.1)?; + // Excel: a guess at or below -100% is #VALUE! for IRR (#NUM! for XIRR). + if guess <= -1.0 { + return Err(CellError::Value); + } if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } - let f = |r: f64| { - let mut s = 0.0; - let mut d = 1.0; - for x in &v { - s += x / d; - d *= 1.0 + r; - } - s - }; - num_val(solve_rate(f, guess)?) + num_val(irr_solve(&v, guess)?) } fn mirr(a: &[Arg], _c: &mut dyn Ctx) -> R { @@ -1795,6 +1960,82 @@ mod tests { is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num); } + /// XIRR of `values` on `dates`, with an optional guess, as a number or an error. + fn xirr_of(values: &[f64], dates: &[f64], guess: Option) -> Value { + let mut args = vec![rf(col(values)), rf(col(dates))]; + args.extend(guess.map(n)); + ev("XIRR", args) + } + + #[track_caller] + fn xirr_is(values: &[f64], dates: &[f64], guess: Option, expected: f64) { + assert_eq!(xirr_of(values, dates, guess), Value::Number(expected), "XIRR{values:?} {dates:?} {guess:?}"); + } + + fn irr_of(values: &[f64], guess: Option) -> Value { + let mut args = vec![rf(col(values))]; + args.extend(guess.map(n)); + ev("IRR", args) + } + + /// Expected values observed in Excel 365 with these synthetic inputs. XIRR matches bit for + /// bit: its answer is a bisection midpoint, about 1e-8 from the exact root. + #[test] + fn xirr_follows_excel_bisection() { + let (b, y1, y2) = (43831.0, 44196.0, 44561.0); + // Root 10%: the bracket and so the answer depend on the guess, not on the flows. + xirr_is(&[-100.0, 110.0], &[b, y1], None, 0.099_999_994_039_535_52); + xirr_is(&[-100.0, 121.0], &[b, y2], None, 0.099_999_994_039_535_52); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.0), 0.099_999_995_117_187_5); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.25), 0.099_999_997_764_825_82); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(5.0), 0.100_000_002_421_438_7); + xirr_is(&[-100.0, 60.0, 60.0], &[b, y1, y2], None, 0.130_662_387_609_481_82); + xirr_is(&[-100.0, 150.0], &[b, y1], None, 0.499_999_994_039_535_54); + // Fractional dates are truncated. + xirr_is(&[-100.0, 60.0, 60.0], &[b, y1 + 0.9, y2 + 0.2], None, 0.130_662_387_609_481_82); + // Negative roots: minus the guess, then halfway to -100% each step. + xirr_is(&[-100.0, 73.0], &[b, y1], None, -0.269_999_996_572_733); + xirr_is(&[-100.0, 13.0], &[b, y1], None, -0.870_000_001_043_081_1); + xirr_is(&[-100.0, 1e-29], &[b, 45658.0], None, -0.999_999_359_104_708); + // A guess of 100% or more steps through rates below -100% (whole years only). + xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(2.0), -1.653_112_880_885_601); + xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(-0.3), -0.846_887_112_781_405_5); + is_err(xirr_of(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(1.0)), CellError::Num); + // One-day spans. + xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23); + xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34); + xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5); + // Dates before the first are allowed (time runs from the first date); in the second + // case the search finds no sign change. + xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b - 365.0, y2], None), CellError::Num); + // A negative guess never reaches a positive root; a guess at or below -1 is #NUM!. + is_err(xirr_of(&[-100.0, 110.0], &[b, y1], Some(-0.1)), CellError::Num); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, y1, y2], Some(-1.0)), CellError::Num); + // Two roots with the guess outside them; all dates the same. + is_err(xirr_of(&[-100.0, 300.0, -210.0], &[b, y1, y2], None), CellError::Num); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b, b], None), CellError::Num); + } + + /// IRR follows Excel's answers to about 1e-12 and its #NUM! cases. + #[test] + fn irr_follows_excel() { + assert_eq!(irr_of(&[-100.0, 110.0], None), Value::Number(0.100_000_000_000_000_09)); + close_tol(irr_of(&[-0.0001, 0.0, 0.0, 0.0, 100.0], None), 30.622_776_600_497_09, 1e-9); + let mut late = vec![-100.0]; + late.extend([0.0; 19]); + late.push(1e-5); + is_err(irr_of(&late, None), CellError::Num); + // ...but from a guess just above -100% Newton creeps down to the root. + let mut late18 = vec![-100.0]; + late18.extend([0.0; 18]); + late18.push(1e-5); + close_tol(irr_of(&late18, Some(-0.99)), -0.571_866_760_128_087_4, 1e-9); + close_tol(irr_of(&[-100.0, 300.0, -210.0], Some(0.9)), 0.887_298_334_620_741_5, 1e-12); + is_err(irr_of(&[-100.0, 60.0, 60.0], Some(-1.0)), CellError::Value); + close_tol(irr_of(&[-100.0, 60.0, 60.0], Some(-0.999_999)), 0.130_662_386_291_807_5, 1e-12); + } + #[test] fn cash_flows() { close_tol(ev("NPV", vec![n(0.1), n(-10000.0), n(3000.0), n(4200.0), n(6800.0)]), 1188.443412, 1e-9); diff --git a/docs/function-parity.md b/docs/function-parity.md index 760ffd6ac3..8f43325b80 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (USDOLLAR added as a compatibility function; MIRR, COUNTIF and INDIRECT edge cases match Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (XIRR follows Excel's bisection bit for bit; IRR uses Newton on the discount factor like Excel) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -92,7 +92,17 @@ assertions each, but there is no conformance suite against Excel-computed result reports keep finding edge cases: MIN() with no arguments (#138), COUNTBLANK past the used range (#137), ROUND at 15 digits and DATE(1900,2,29) (fixed 10-09), SUMIF sum-range sizing (fixed 10-09). Statistical distributions and financial functions with iterative solvers (RATE, IRR, -XIRR, YIELD) are the highest-risk for last-digit differences. +YIELD) are the highest-risk for last-digit differences. XIRR follows Excel's own solver, +reconstructed from observation: a sign-only search that brackets the root from the guess +(doubling, halving towards 0, or stepping halfway to -100%) and bisects until half the bracket is +under 1e-8 x (|rate| + 0.5) and XNPV is under 2e-8 x the first value, so its answer is the same +midpoint as Excel's, about 1e-8 from the exact root, bit for bit in 888 of 910 synthetic cases +with an answer (97.7% agreement on 1,283 cases including `#NUM!`). Known differences: flows with +several sign changes where Excel returns about 3e-9 (a halving that reached 0), or `#NUM!` for +two roots close to the guess. IRR uses Newton on the discount factor 1/(1+rate), at most 100 steps, +stopping at a step under 1e-8; Excel's last digits differ by about 1e-12 (its exact iteration is +not reconstructed) and a few far-from-guess cases differ in `#NUM!` (93.5% agreement on 708 +cases, from 88%). TEXT() and cell display share `crates/numfmt`; checked against Excel-cached results in number- and text-format test workbooks (352 TEXT cells), all match: @@ -108,6 +118,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | XIRR follows Excel's bisection (answers bit for bit, about 1e-8 from the exact root; dates before the first allowed; guess <= -1 is `#NUM!`); IRR uses Newton on the discount factor (`IRR` of -100, 19 zeros, 1E-5 is `#NUM!` like Excel; guess <= -1 is `#VALUE!`) | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | From e24a8631b448c42ca62d1c1a40d46c61e3fccbe0 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 02:59:25 -0500 Subject: [PATCH 03/95] Filter: SUBTOTAL over filtered table rows keeps its value after save and reopen A sheet AutoFilter that overlaps a table can't be saved (the file only holds a table's own filter there), so the writer dropped it. Its criteria were lost and the rows it hid reopened as rows hidden by hand, which SUBTOTAL 1-11 counts. - Save a sheet AutoFilter that starts on a table's header row as that table's filter (columns mapped to the table), merged with the table's own criteria. - Filtering inside a table takes over the criteria the table already had, so a reopened filtered table filtered again saves both. - From a cell outside a table, the filter range keeps off the table like Excel (observed: table B4:C8, AutoFilter from A1 covers A1:A3, from A6 A5:A8, from B3 A1:B3); an explicit range over part of a table is refused. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/data.rs | 40 ++++- crates/engine/src/selection.rs | 36 ++++- .../engine/tests/subtotal-filter-roundtrip.rs | 153 ++++++++++++++++++ crates/xlsx/src/sheet_write.rs | 31 +++- crates/xlsx/src/tests/mod.rs | 1 + crates/xlsx/src/tests/tablefilter.rs | 102 ++++++++++++ 6 files changed, 352 insertions(+), 11 deletions(-) create mode 100644 crates/engine/tests/subtotal-filter-roundtrip.rs create mode 100644 crates/xlsx/src/tests/tablefilter.rs diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 383624b70c..3fc27811ae 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -472,20 +472,48 @@ fn toggle_filter(s: &mut Session, p: &Json) -> Result { } /// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection. +/// +/// A sheet AutoFilter never overlaps a table, because a file can't hold one (Excel refuses +/// `Range("A1:C8").AutoFilter` over part of a table, and from a cell outside a table it leaves the +/// table's cells out of the region). Inside a table the filter covers the table from its header +/// row, which is saved as the table's own filter, and takes over the criteria the table already +/// had so there is one filter to save. fn install_filter(s: &mut Session, p: &Json) -> Result { let sheet = s.doc()?.wb.active_sheet; let mut r = data_range(s, p)?; - // A selected header row filters the data below it (#201). - if p.get("range").is_none() && r.height() == 1 { + { let d = s.doc()?; let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - let below = current_region(sh, r.start).end.row; - if below > r.end.row { - r = RangeRef::new(r.start, CellRef::new(below, r.end.col)); + if p.get("range").is_none() && sh.table_at(d.selection.active).is_none() && d.selection.current().is_single() { + r = crate::selection::current_region_outside_tables(sh, d.selection.active); + } + // A selected header row filters the data below it (#201). + if p.get("range").is_none() && r.height() == 1 { + let region = if sh.table_at(r.start).is_some() { + current_region(sh, r.start) + } else { + crate::selection::current_region_outside_tables(sh, r.start) + }; + if region.end.row > r.end.row { + r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col)); + } } } + let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; + // The table whose header row the filter starts on, when it lies inside that table. + let host = + sh.tables.iter().position(|t| t.header_row && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end)); + if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) { + return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); + } edit(s, |cx| { - cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] }); + let sh = cx.sheet_mut(sheet)?; + let mut criteria = vec![]; + if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) { + let shift = r.start.col.saturating_sub(t.range.start.col); + criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect(); + } + sh.autofilter = Some(AutoFilter { range: r, criteria }); Ok(json!({"filter": true, "range": r.a1()})) }) } diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 27418a21a1..9a8c0581b0 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -186,7 +186,41 @@ pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef { /// The contiguous data region around `c` (Ctrl+A / Ctrl+Shift+8, AutoSum, sort, tables). pub fn current_region(sheet: &Sheet, c: CellRef) -> RangeRef { - let filled = |c: CellRef| sheet.cell(c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()) || sheet.spill.contains_key(&c); + region_where(sheet, c, |_| true) +} + +/// The data region a sheet AutoFilter takes from `c`, a cell outside any table: the current +/// region, kept off the tables it reaches. Observed in Windows Excel 16 (table B4:C8, text in +/// A1:A3, A5:A8 and B3; the current region of A1 is A1:C8): from A1 the filter covers A1:A3, from +/// A6 A5:A8, from B3 A1:B3. So the region is cut to the columns on the cell's side of the table +/// when the cell is left or right of it, else to the rows above or below, and grown again from +/// the cell inside that window. +pub fn current_region_outside_tables(sheet: &Sheet, c: CellRef) -> RangeRef { + let (mut c0, mut c1, mut r0, mut r1) = (0, MAX_COLS - 1, 0, MAX_ROWS - 1); + let mut region = current_region(sheet, c); + for _ in 0..=sheet.tables.len() { + let Some(t) = sheet.tables.iter().find(|t| t.range.intersects(®ion)) else { break }; + let t = t.range; + if c.col < t.start.col { + c1 = c1.min(t.start.col - 1); + } else if c.col > t.end.col { + c0 = c0.max(t.end.col + 1); + } else if c.row < t.start.row { + r1 = r1.min(t.start.row - 1); + } else if c.row > t.end.row { + r0 = r0.max(t.end.row + 1); + } else { + return RangeRef::cell(c); + } + region = region_where(sheet, c, |x| x.col >= c0 && x.col <= c1 && x.row >= r0 && x.row <= r1 && sheet.table_at(x).is_none()); + } + region +} + +/// The current region around `c`, counting only filled cells that `counts` accepts. +fn region_where(sheet: &Sheet, c: CellRef, counts: impl Fn(CellRef) -> bool) -> RangeRef { + let filled = + |c: CellRef| (sheet.cell(c).is_some_and(|x| !x.value.is_empty() || x.formula.is_some()) || sheet.spill.contains_key(&c)) && counts(c); // Whether a row (or column) has a filled cell between two columns (rows), inclusive. let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col))); let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col))); diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs new file mode 100644 index 0000000000..f5e6b64805 --- /dev/null +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -0,0 +1,153 @@ +//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen (ft-3ir.10.24). +//! +//! Excel (observed in Windows Excel 16 with synthetic workbooks) saves rows a filter hides as plain +//! `hidden="1"` rows; a hidden row counts as filtered when it lies in an AutoFilter (sheet or table) +//! that has criteria. Excel can't hold a sheet AutoFilter that overlaps a table, so GridCraft saves +//! a table's filter in the table part and never creates a sheet AutoFilter over part of a table. + +use gridcraft_core::{CellRef, Value}; +use gridcraft_engine::calc::Calc; +use gridcraft_engine::model::Workbook; +use gridcraft_engine::{Session, io}; +use serde_json::{Value as Json, json}; + +fn reopened(wb: &Workbook) -> Workbook { + let bytes = io::save_bytes(wb, "t.xlsx").unwrap(); + let (mut back, _) = io::open_bytes("t.xlsx", &bytes).unwrap(); + Calc::new().recalc_all(&mut back); + back +} + +/// Every formula value in memory against the same cell after a save and reopen. +fn assert_values_survive(wb: &Workbook) { + let back = reopened(wb); + for (a, b) in wb.sheets.iter().zip(&back.sheets) { + for (c, cell) in a.cells.iter() { + if cell.formula.is_some() { + assert_eq!(cell.value, b.value(c), "{}!{} ({:?})", a.name, c.a1(), cell.formula.as_ref().map(|f| &f.text)); + } + } + } +} + +fn session(sample: &str, steps: &[(&str, Json)]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"sample": sample})).unwrap(); + for (id, p) in steps { + let _ = s.execute(id, p.clone()); + } + s +} + +fn wb(s: &Session) -> &Workbook { + &s.doc().unwrap().wb +} + +#[test] +fn bead_repro_filter_then_replace_on_the_sales_sample() { + let s = + session("sales", &[("data.filterBy", json!({"column":"G","top":{"count":2}})), ("edit.replace", json!({"all":true,"what":"1","with":""}))]); + let sh = wb(&s).active().unwrap(); + assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range)))); + assert_values_survive(wb(&s)); +} + +#[test] +fn bead_repro_subtotal_then_filter_on_the_grades_sample() { + let s = session( + "grades", + &[ + ("home.insertColumns", json!({})), + ("data.subtotal", json!({"columns":["G"],"function":"sum","groupBy":"J"})), + ("data.filterBy", json!({"column":"B","values":["x"]})), + ], + ); + let sh = wb(&s).active().unwrap(); + assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range)))); + assert_values_survive(wb(&s)); +} + +/// A table A1:B7 (Name, Qty = 1, 10, 100...) with SUBTOTAL(9) and SUBTOTAL(109) beside it. +fn table_book() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["Name","Qty"],["a",1],["b",10],["c",100],["d",1000],["e",10000],["f",100000]]})) + .unwrap(); + s.execute("insert.table", json!({"range":"A1:B7","header":true})).unwrap(); + s.execute("cell.set", json!({"cell":"E1","input":"=SUBTOTAL(9,B2:B7)"})).unwrap(); + s.execute("cell.set", json!({"cell":"E2","input":"=SUBTOTAL(109,B2:B7)"})).unwrap(); + s.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s +} + +fn e1_e2(wb: &Workbook) -> (Value, Value) { + let sh = wb.active().unwrap(); + (sh.value(CellRef::new(0, 4)), sh.value(CellRef::new(1, 4))) +} + +#[test] +fn table_filter_keeps_subtotal_and_criteria_through_save() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); + // Like Excel, a row hidden by hand inside an active filter range is left out by SUBTOTAL 9 too. + s.execute("home.hideRows", json!({"rows":"6:6"})).unwrap(); + assert_eq!(e1_e2(wb(&s)), (Value::Number(100101.0), Value::Number(100101.0))); + assert_values_survive(wb(&s)); + let back = reopened(wb(&s)); + assert_eq!(e1_e2(&back), (Value::Number(100101.0), Value::Number(100101.0))); + let t = &back.active().unwrap().tables[0]; + assert_eq!(t.filter.len(), 1, "the criteria are saved with the table: {:?}", t.filter); +} + +#[test] +fn rows_hidden_by_hand_without_a_filter_still_count_for_subtotal_9() { + let mut s = table_book(); + s.execute("home.hideRows", json!({"rows":"3:3"})).unwrap(); + s.execute("home.hideRows", json!({"rows":"5:5"})).unwrap(); + assert_eq!(e1_e2(wb(&s)), (Value::Number(111111.0), Value::Number(110101.0))); + let back = reopened(wb(&s)); + assert_eq!(e1_e2(&back), (Value::Number(111111.0), Value::Number(110101.0))); +} + +#[test] +fn filtering_a_reopened_table_again_keeps_both_criteria() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); + let back = reopened(wb(&s)); + let mut s = Session::new(); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into())); + s.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"B","custom":{"op":">","value":"50"}})).unwrap(); + let sh = wb(&s).active().unwrap(); + assert!(sh.tables[0].filter.is_empty(), "the table's criteria moved into the live filter"); + assert_eq!(sh.autofilter.as_ref().map(|af| af.criteria.len()), Some(2)); + assert_eq!(e1_e2(wb(&s)), (Value::Number(110100.0), Value::Number(110100.0))); + assert_values_survive(wb(&s)); + assert_eq!(reopened(wb(&s)).active().unwrap().tables[0].filter.len(), 2); +} + +#[test] +fn a_sheet_filter_from_outside_a_table_leaves_the_table_out() { + // Excel: table B4:C8 with text in A1:A3, A5:A8 and B3. AutoFilter from A1 covers A1:A3, from + // A6 A5:A8, from B3 A1:B3; an explicit range over part of the table is refused. + let layout = || { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["Title"],["x"],["y"]]})).unwrap(); + s.execute("cell.set", json!({"cell":"B3","input":"z"})).unwrap(); + s.execute("range.setValues", json!({"range":"B4","values":[["Name","Qty"],["n5","v5"],["n6","v6"],["n7","v7"],["n8","v8"]]})).unwrap(); + s.execute("range.setValues", json!({"range":"A5","values":[["a5"],["a6"],["a7"],["a8"]]})).unwrap(); + s.execute("insert.table", json!({"range":"B4:C8","header":true})).unwrap(); + s + }; + for (cell, want) in [("A1", "A1:A3"), ("A6", "A5:A8"), ("B3", "A1:B3")] { + let mut s = layout(); + s.execute("selection.set", json!({"cell": cell})).unwrap(); + s.execute("data.filter", json!({})).unwrap(); + let af = wb(&s).active().unwrap().autofilter.clone(); + assert_eq!(af.map(|a| a.range.a1()), Some(want.to_string()), "from {cell}"); + } + let mut s = layout(); + assert!(s.execute("data.filter", json!({"range":"A1:C8"})).is_err()); + assert!(wb(&s).active().unwrap().autofilter.is_none()); +} diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 78e1afaaef..63ed2e7989 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -569,7 +569,8 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( out.table_id += 1; let n = out.tables; let name = table_name(&t.name, &mut used_names, out.table_id); - let xml = table_xml(t, cols, &name, out.table_id, out); + let filter = table_filter(sheet, t); + let xml = table_xml(t, cols, &name, out.table_id, &filter, out); out.part(&format!("xl/tables/table{n}.xml"), Some(CT_TABLE), xml.into_bytes()); let rid = rels.add("table", &format!("../tables/table{n}.xml")); let _ = write!(parts, ""); @@ -1021,7 +1022,29 @@ fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)], out: &mu s } -fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, out: &mut Out) -> String { +/// The criteria saved in a table's ``: its own, plus those of a sheet AutoFilter +/// that starts on the table's header row. GridCraft filters a table through the sheet +/// AutoFilter, but a file can't hold a sheet AutoFilter that overlaps a table (the sheet element +/// is left out), so without this the criteria would be lost and the rows they hide would reopen +/// as rows hidden by hand, which SUBTOTAL 1-11 counts. +fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterion)> { + let mut criteria = t.filter.clone(); + let Some(af) = sheet.autofilter.as_ref().filter(|af| t.header_row && af.range.start.row == t.range.start.row && af.range.intersects(&t.range)) + else { + return criteria; + }; + for (off, c) in &af.criteria { + let Some(col) = af.range.start.col.checked_add(*off).and_then(|abs| abs.checked_sub(t.range.start.col)) else { continue }; + if col < t.range.width() { + criteria.retain(|(o, _)| *o != col); + criteria.push((col, c.clone())); + } + } + criteria.sort_by_key(|(o, _)| *o); + criteria +} + +fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter: &[(u32, FilterCriterion)], out: &mut Out) -> String { let mut s = format!("{XML_DECL} let _ = write!(s, " connectionId=\"{c}\""); } s.push('>'); - if t.header_row && t.filter_button { + if t.header_row && (t.filter_button || !filter.is_empty()) { let end_row = if t.totals_row { t.range.end.row.saturating_sub(1).max(t.range.start.row) } else { t.range.end.row }; let r = RangeRef::new(t.range.start, CellRef::new(end_row, t.range.end.col)); - s.push_str(&autofilter_xml(r, &t.filter, out)); + s.push_str(&autofilter_xml(r, filter, out)); } let _ = write!(s, "", cols.len()); for (i, name) in cols.iter().enumerate() { diff --git a/crates/xlsx/src/tests/mod.rs b/crates/xlsx/src/tests/mod.rs index 517113d0f6..b9f7b8ca34 100644 --- a/crates/xlsx/src/tests/mod.rs +++ b/crates/xlsx/src/tests/mod.rs @@ -15,6 +15,7 @@ mod richdata_tests; mod roundtrip; mod sheet_names; mod smooth_roundtrip; +mod tablefilter; mod trendline_roundtrip; mod xls_tests; mod xlsb_tests; diff --git a/crates/xlsx/src/tests/tablefilter.rs b/crates/xlsx/src/tests/tablefilter.rs new file mode 100644 index 0000000000..784361b7fd --- /dev/null +++ b/crates/xlsx/src/tests/tablefilter.rs @@ -0,0 +1,102 @@ +//! A sheet AutoFilter that filters a table is saved as the table's own filter (a file can't hold +//! a sheet AutoFilter that overlaps a table), so the rows it hides reopen as filtered rows. + +use gridcraft_core::{CellRef, RangeRef, Value}; +use gridcraft_model::*; + +use crate::{read_xlsx, write_xlsx}; + +fn rr(a: &str) -> RangeRef { + RangeRef::parse(a).unwrap() +} + +fn table(range: &str, cols: &[&str]) -> Table { + Table { + id: 1, + name: "T".into(), + range: rr(range), + header_row: true, + totals_row: false, + columns: cols + .iter() + .map(|n| TableColumn { name: (*n).into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None }) + .collect(), + style: String::new(), + banded_rows: true, + banded_cols: false, + first_col: false, + last_col: false, + filter_button: true, + filter: vec![], + table_type: None, + connection_id: None, + } +} + +/// Table B2:C6 (Name, Qty) with rows 4 and 6 hidden by a filter on Name. +fn filtered(af_range: &str, af_col: u32) -> Workbook { + let mut wb = Workbook::new(); + let s = wb.sheet_mut(0).unwrap(); + s.set_value(CellRef::new(1, 1), Value::text("Name")); + s.set_value(CellRef::new(1, 2), Value::text("Qty")); + for (i, n) in ["a", "b", "c", "d"].iter().enumerate() { + let row = 2 + i as u32; + s.set_value(CellRef::new(row, 1), Value::text(*n)); + s.set_value(CellRef::new(row, 2), Value::Number(10f64.powi(i as i32))); + } + let mut t = table("B2:C6", &["Name", "Qty"]); + // A criterion the table already had (from the file it was opened from) on the Qty column. + t.filter = vec![(1, FilterCriterion::Custom { a: (">".into(), "0".into()), b: None, and: true })]; + s.tables.push(t); + s.autofilter = Some(AutoFilter { + range: rr(af_range), + criteria: vec![(af_col, FilterCriterion::Values { values: vec!["a".into(), "c".into()], blanks: false })], + }); + for row in [3, 5] { + s.rows.entry(row).or_default().hidden = true; + } + wb +} + +#[test] +fn table_filter_through_the_sheet_autofilter_is_saved_with_the_table() { + let wb = filtered("B2:C6", 0); + assert!(wb.sheets[0].is_row_filtered(3)); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = back.sheet(0).unwrap(); + assert!(s.autofilter.is_none(), "no sheet AutoFilter over a table"); + let t = &s.tables[0]; + assert_eq!(t.filter.len(), 2, "{:?}", t.filter); + assert_eq!(t.filter[0].0, 0); + assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()])); + assert!(matches!(&t.filter[1].1, FilterCriterion::Custom { .. }), "the table's own criterion is kept"); + for row in [3, 5] { + assert!(s.is_row_filtered(row), "row {} reopens as filtered", row + 1); + } + assert!(!s.is_row_hidden(2) && !s.is_row_hidden(4)); +} + +#[test] +fn sheet_autofilter_starting_left_of_the_table_maps_its_columns() { + // The filter starts one column left of the table on its header row: Name is column 1 of the + // filter and column 0 of the table; a criterion on the column outside the table is dropped. + let mut wb = filtered("A2:C6", 1); + if let Some(af) = wb.sheet_mut(0).unwrap().autofilter.as_mut() { + af.criteria.push((0, FilterCriterion::Values { values: vec!["zz".into()], blanks: true })); + } + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let t = &back.sheet(0).unwrap().tables[0]; + let cols: Vec = t.filter.iter().map(|(c, _)| *c).collect(); + assert_eq!(cols, [0, 1]); + assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()])); +} + +#[test] +fn sheet_autofilter_not_on_the_header_row_is_not_folded() { + let wb = filtered("B1:C6", 0); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = back.sheet(0).unwrap(); + assert!(s.autofilter.is_none()); + let cols: Vec = s.tables[0].filter.iter().map(|(c, _)| *c).collect(); + assert_eq!(cols, [1], "only the table's own criterion"); +} From cdb3c163ec380f9bbbcb9673c2cecff087cd25c3 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 06:27:02 -0500 Subject: [PATCH 04/95] ft-3ir.2.1: keep PivotTables on a data connection or the Data Model on XLSX save A PivotTable whose cache has cacheSource type="external" (a data connection, or the workbook's Data Model: OLAP caches with saveData="0" and no records) was read as unsupported and dropped on save with its cache, and the Data Model part (xl/model/item.data) was never kept. Such PivotTables are now reported by read_pivots and kept by the pass-through layer like those on another workbook: table, cache and records parts unchanged, original cacheId, style ids renumbered. The connection is looked up in xl/connections.xml to tell the Data Model from a plain connection. The Data Model part is kept byte for byte whenever the workbook's connections are kept. A cache on a connection is kept only with the connections, one on the model only with the model; otherwise its PivotTable is left as plain cells with one warning. Checked in Excel with synthetic workbooks: Excel needs the table, cache, connections.xml and the hidden _xlcn. name of a worksheet connection to open the file, and item.data to refresh it; the x15:dataModel workbook extension is not needed and is not kept. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- apps/gridcraft-cli/src/check.rs | 2 +- crates/xlsx/src/passthrough.rs | 81 +++++-- crates/xlsx/src/pivot.rs | 93 ++++++-- crates/xlsx/src/read.rs | 1 + crates/xlsx/src/tests/passthrough_tests.rs | 256 +++++++++++++++++++++ docs/file-format-parity.md | 5 +- 7 files changed, 406 insertions(+), 36 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index cb756e2aa7..79f5019376 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** trivial (progress log: XLSX PivotTables on another workbook kept on save) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** trivial (progress log: XLSX PivotTables on a data connection or the Data Model kept on save) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-15 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it | | 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | @@ -194,6 +195,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save | | 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook kept on save | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | diff --git a/apps/gridcraft-cli/src/check.rs b/apps/gridcraft-cli/src/check.rs index 3a398b86ac..324abf0f12 100644 --- a/apps/gridcraft-cli/src/check.rs +++ b/apps/gridcraft-cli/src/check.rs @@ -594,7 +594,7 @@ fn cond_format_list(s: &Sheet) -> Vec { } /// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is -/// in another workbook). +/// in another workbook, a data connection or the Data Model). fn pivot_count(s: &Sheet) -> usize { let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count()); s.pivots.len() + kept diff --git a/crates/xlsx/src/passthrough.rs b/crates/xlsx/src/passthrough.rs index fbff953537..56d8e6e8f9 100644 --- a/crates/xlsx/src/passthrough.rs +++ b/crates/xlsx/src/passthrough.rs @@ -6,11 +6,14 @@ //! their ``, data connections, XML maps) and each sheet (query tables, cells //! mapped to XML elements, form controls, ActiveX controls, OLE objects, the sheet background and //! printer settings, with the sheet's ``, `` and `` XML, the `r:id` -//! of `` and the legacy VML shapes those controls need). PivotTables whose source is in -//! another workbook are kept too: the PivotTable parts with their sheet, the cache definition and -//! records parts (with the cache's link to the other workbook's path) with the workbook and its -//! `` entry, its `cacheId` unchanged. The workbook also keeps its -//! `` and the calcFeatures extension, which Excel needs to trust the saved values. +//! of `` and the legacy VML shapes those controls need). The workbook's Data Model +//! (`xl/model/item.data`) is kept with its data connections. PivotTables whose source is in +//! another workbook, a data connection or the Data Model are kept too: the PivotTable parts with +//! their sheet, the cache definition and records parts (with the cache's link to the other +//! workbook's path) with the workbook and its `` entry, its `cacheId` unchanged; a +//! cache on a connection only when the connections are kept, and on the Data Model only when the +//! model is kept. The workbook also keeps its `` and the calcFeatures extension, +//! which Excel needs to trust the saved values. //! //! On write, kept parts get fresh part names where needed and new relationship ids; the `r:id`s in //! kept XML are rewritten to match. Kept content is conservative: @@ -41,7 +44,7 @@ use quick_xml::{Reader, Writer}; use crate::IoError; use crate::package::{self, normalize}; -use crate::pivot::{CT_PIVOT_CACHE_DEF, CT_PIVOT_TABLE, ExternalPivot}; +use crate::pivot::{CT_PIVOT_CACHE_DEF, CT_PIVOT_TABLE, ExternalPivot, KeptSource}; use crate::read::Ctx; use crate::write::{NS_REL, Out, Rels, XML_DECL}; use crate::xml::{self, esc_attr}; @@ -103,6 +106,8 @@ const SHEET_SLOTS: &[&str] = &["picture", "oleObjects", "controls"]; const PIVOT_TABLE_GRAPH: &[&str] = &["pivotTable", "pivotCacheDefinition"]; /// Rewritten kinds a kept pivot cache reaches. const PIVOT_CACHE_GRAPH: &[&str] = &["pivotCacheDefinition", "pivotCacheRecords"]; +/// The workbook's Data Model part (Power Pivot), kept byte for byte when its connections are. +const DATA_MODEL_GRAPH: &[&str] = &["powerPivotData"]; /// Relationship kinds GridCraft reads and rewrites, or that depend on content it rewrites: /// kept content whose graph reaches one of them is dropped. @@ -168,6 +173,7 @@ const OWN_DIRS: &[&str] = &[ "xl/activex/", "xl/webextensions/", "xl/printersettings/", + "xl/model/", ]; fn kind(rel_type: &str) -> &str { @@ -242,8 +248,8 @@ pub struct KeptReader { budget: usize, parts_left: usize, /// Cache definition parts of the PivotTables kept with their sheets (source in another - /// workbook), kept with the workbook. - pivot_caches: Vec, + /// workbook, a data connection or the Data Model), kept with the workbook. + pivot_caches: Vec<(String, KeptSource)>, } impl KeptReader { @@ -409,6 +415,20 @@ impl KeptReader { cx.warn(format!("{} part {} was dropped: {why}", kind(&r.rel_type), r.target)); } } + // The Data Model: its tables are loaded through the workbook's connections, so it is kept + // only with them. + let connections = p.rels.iter().any(|r| is_kind(r, &["connections"])); + for r in wb_rels.iter().filter(|r| !r.external && is_kind(r, DATA_MODEL_GRAPH)).take(1) { + let kept = if connections { + self.keep_through(cx, &mut p, std::slice::from_ref(r), &mut seen, DATA_MODEL_GRAPH) + } else { + Err("the workbook's data connections were not kept".into()) + }; + match kept { + Ok(()) => cx.warn("the workbook's Data Model is kept for saving as it is; it can't be viewed, edited or refreshed here"), + Err(why) => cx.warn(format!("the workbook's Data Model was dropped: {why}")), + } + } // Chart sheets: the sheet entry (name, state, position) plus the chart sheet part and the // drawing, chart, style and colour parts behind it. for (worksheets, se) in chart_sheet_entries(wb_xml, &wb_rels, file_to_model) { @@ -484,14 +504,33 @@ impl KeptReader { /// and relationship id). fn keep_pivot_caches(&mut self, cx: &mut Ctx<'_>, wb_xml: &xml::El, wb_rels: &[PreservedRel], p: &mut Preserved, seen: &mut HashSet) { let caches = std::mem::take(&mut self.pivot_caches); - for cache in &caches { + // A cache names its connection by id in the kept connections part, and a Data Model cache + // reads the kept model: without them Excel refuses the file or can't refresh it. + let connections = p.rels.iter().any(|r| is_kind(r, &["connections"])); + let model = p.rels.iter().any(|r| is_kind(r, DATA_MODEL_GRAPH)); + let (mut no_connections, mut no_model) = (0usize, 0usize); + for (cache, source) in &caches { + match source { + KeptSource::Connection | KeptSource::DataModel if !connections => { + no_connections += 1; + continue; + } + KeptSource::DataModel if !model => { + no_model += 1; + continue; + } + _ => {} + } let entry = wb_xml.child("pivotCaches").into_iter().flat_map(|c| c.kids("pivotCache")).find_map(|c| { let id = c.attr_u32("cacheId")?; let r = wb_rels.iter().find(|r| Some(r.id.as_str()) == c.attr("id") && !r.external && is_kind(r, &["pivotCacheDefinition"]))?; (normalize(&r.target) == normalize(cache)).then(|| (id, r.clone())) }); let Some((id, r)) = entry else { - cx.warn(format!("the cache {cache} of a PivotTable on another workbook is not in the workbook's list; the PivotTable was dropped")); + cx.warn(format!( + "the cache {cache} of a PivotTable on {} is not in the workbook's list; the PivotTable was dropped", + source.describe() + )); continue; }; match self.keep_through(cx, p, std::slice::from_ref(&r), seen, PIVOT_CACHE_GRAPH) { @@ -499,9 +538,19 @@ impl KeptReader { slot: "pivotCache".into(), xml: format!("", esc_attr(&r.id)), }), - Err(why) => cx.warn(format!("the cache of a PivotTable on another workbook was dropped with its PivotTables: {why}")), + Err(why) => cx.warn(format!("the cache of a PivotTable on {} was dropped with its PivotTables: {why}", source.describe())), } } + if no_connections > 0 { + cx.warn(format!( + "{no_connections} PivotTable cache(s) on a data connection or the Data Model were dropped with their PivotTables (kept as plain cells): the workbook's data connections were not kept" + )); + } + if no_model > 0 { + cx.warn(format!( + "{no_model} PivotTable cache(s) on the workbook's Data Model were dropped with their PivotTables (kept as plain cells): the Data Model was not kept" + )); + } } /// Sheet-level content of the sheet part `part`; `pivots` are its PivotTables whose source is @@ -509,7 +558,9 @@ impl KeptReader { pub fn sheet(&mut self, cx: &mut Ctx<'_>, part: &str, name: &str, pivots: &[ExternalPivot]) -> Option> { if !self.on { if !pivots.is_empty() { - cx.warn(format!("sheet \"{name}\": PivotTables on another workbook are not kept on save in this file")); + cx.warn(format!( + "sheet \"{name}\": PivotTables on another workbook, a data connection or the Data Model are not kept on save in this file" + )); } return None; } @@ -539,11 +590,11 @@ impl KeptReader { Ok(()) => { scoped.remove(&normalize(&ep.cache_part)); seen = scoped; - if !self.pivot_caches.iter().any(|c| normalize(c) == normalize(&ep.cache_part)) { - self.pivot_caches.push(ep.cache_part.clone()); + if !self.pivot_caches.iter().any(|(c, _)| normalize(c) == normalize(&ep.cache_part)) { + self.pivot_caches.push((ep.cache_part.clone(), ep.source)); } } - Err(why) => cx.warn(format!("sheet \"{name}\": a PivotTable on another workbook was dropped: {why}")), + Err(why) => cx.warn(format!("sheet \"{name}\": a PivotTable on {} was dropped: {why}", ep.source.describe())), } } (!p.is_empty()).then(|| Arc::new(p)) diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 0d7a9cd3c7..e680660ee7 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -12,9 +12,12 @@ //! (OLAP sources, calculated fields, numeric grouping…) becomes a warning. //! //! A PivotTable whose source is a range or name in another workbook (its cache's -//! `worksheetSource` has an `r:id` to an `externalLinkPath` relationship) is not modelled: -//! GridCraft never opens the other workbook, so it couldn't refresh it. [`read_pivots`] reports -//! it instead, and `passthrough` keeps its PivotTable, cache and records parts unchanged. +//! `worksheetSource` has an `r:id` to an `externalLinkPath` relationship), a data connection or +//! the workbook's Data Model (`cacheSource type="external"` with a `connectionId` in +//! `xl/connections.xml`) is not modelled: GridCraft never opens the other workbook, runs the +//! connection or loads the model, so it couldn't refresh it. [`read_pivots`] reports it instead, +//! and `passthrough` keeps its PivotTable, cache and records parts unchanged (with the Data Model +//! for a PivotTable on the model). use std::collections::HashMap; use std::fmt::Write as _; @@ -1079,17 +1082,40 @@ impl FieldIn { struct CacheIn { source: String, fields: Vec, - /// The source is in another workbook: the PivotTables on this cache are kept, not modelled. - external: bool, + /// Set when the PivotTables on this cache are kept as they are, not modelled. + kept: Option, } -/// A PivotTable whose source is in another workbook, kept unchanged for saving. +/// Where the data of a PivotTable GridCraft keeps unchanged (doesn't model) comes from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeptSource { + /// A range or name in another workbook. + OtherWorkbook, + /// A data connection of the workbook (`xl/connections.xml`) other than its Data Model. + Connection, + /// The workbook's Data Model (Power Pivot), through its model connection. + DataModel, +} + +impl KeptSource { + pub(crate) fn describe(self) -> &'static str { + match self { + KeptSource::OtherWorkbook => "another workbook", + KeptSource::Connection => "a data connection", + KeptSource::DataModel => "the workbook's Data Model", + } + } +} + +/// A PivotTable GridCraft doesn't model (its data is in another workbook, a data connection or +/// the Data Model), kept unchanged for saving. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExternalPivot { /// The id of the sheet's relationship to the PivotTable part. pub rel_id: String, /// The pivot cache definition part it uses. pub cache_part: String, + pub source: KeptSource, } /// The PivotTables of a sheet: those modelled, and those kept as they are. @@ -1105,6 +1131,8 @@ pub struct CachesIn { by_id: HashMap, parsed: HashMap>, next_id: u32, + /// The workbook's data connections (`connectionId` → whether it is the Data Model's). + connections: HashMap, } impl CachesIn { @@ -1119,10 +1147,28 @@ impl CachesIn { } } } - CachesIn { by_id, parsed: HashMap::new(), next_id: 1 } + CachesIn { by_id, parsed: HashMap::new(), next_id: 1, connections: HashMap::new() } + } + + /// Reads the ids of the workbook's data connections (`xl/connections.xml`), which caches on a + /// connection or the Data Model name by `connectionId`. + pub fn read_connections(&mut self, cx: &mut Ctx<'_>, wb_rels: &[crate::package::Rel]) { + let Some(r) = wb_rels.iter().find(|r| r.kind == "connections" && !r.external) else { return }; + let Ok(Some(x)) = cx.optional_xml(&r.target) else { return }; + for c in x.kids("connection").take(MAX_CONNECTIONS) { + let Some(id) = c.attr_u32("id") else { continue }; + // The model connection: `` in its extension list (Excel + // also gives it ``). + let x15_model = c.child("extLst").is_some_and(|l| l.kids("ext").filter_map(|e| e.child("connection")).any(|x| x.flag("model", false))); + let dbpr_model = c.attr("type") == Some("5") && c.child("dbPr").and_then(|d| d.attr("command")) == Some("Model"); + self.connections.insert(id, x15_model || dbpr_model); + } } } +/// Most data connections read from `xl/connections.xml`. +const MAX_CONNECTIONS: usize = 100_000; + fn item_label_el(e: &El, sys: DateSystem) -> String { let v = e.attr("v").unwrap_or(""); match e.name.as_str() { @@ -1134,7 +1180,7 @@ fn item_label_el(e: &El, sys: DateSystem) -> String { } } -fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option { +fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str, connections: &HashMap) -> Option { let x = cx.optional_xml(part).ok().flatten()?; if x.name != "pivotCacheDefinition" { cx.warn(format!("{part} is not a pivot cache definition; its PivotTable was kept as plain cells")); @@ -1142,8 +1188,19 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option } let src = x.child("cacheSource"); let ty = src.and_then(|s| s.attr("type")).unwrap_or("worksheet"); + // A data connection or the Data Model (OLAP): kept as it is when the workbook has that + // connection. + if ty == "external" { + let model = src.and_then(|s| s.attr_u32("connectionId")).and_then(|id| connections.get(&id).copied()); + let Some(model) = model else { + cx.warn("a PivotTable's data connection is not in the workbook; kept as plain cells"); + return None; + }; + let kept = if model { KeptSource::DataModel } else { KeptSource::Connection }; + return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(kept) }); + } if ty != "worksheet" { - cx.warn(format!("PivotTables with a {ty} data source are not supported; kept as plain cells")); + cx.warn(format!("PivotTables with a data source of type \"{ty}\" are not supported; kept as plain cells")); return None; } let ws = src.and_then(|s| s.child("worksheetSource")); @@ -1154,7 +1211,7 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option cx.warn("a PivotTable's source is in another workbook that its cache doesn't name; kept as plain cells"); return None; } - return Some(CacheIn { source: String::new(), fields: vec![], external: true }); + return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(KeptSource::OtherWorkbook) }); } let source = match ws { Some(w) if w.attr("name").is_some_and(|n| !n.trim().is_empty()) => w.attr("name").unwrap_or("").trim().to_string(), @@ -1202,11 +1259,12 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option cx.warn("a PivotTable's cache has no fields; kept as plain cells"); return None; } - Some(CacheIn { source, fields, external: false }) + Some(CacheIn { source, fields, kept: None }) } -/// Reads the PivotTables related to a worksheet part. Those whose source is in another workbook -/// are listed in [`SheetPivots::external`] (with a warning), not modelled. +/// Reads the PivotTables related to a worksheet part. Those whose source is in another workbook, +/// a data connection or the Data Model are listed in [`SheetPivots::external`] (with a warning), +/// not modelled. pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result { let rels = cx.pkg.rels(sheet_part)?; let mut out = SheetPivots::default(); @@ -1230,18 +1288,19 @@ pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sh let cache = match caches.parsed.get(&cache_part) { Some(c) => c.clone(), None => { - let c = read_cache(cx, &cache_part, sheet_name); + let c = read_cache(cx, &cache_part, sheet_name, &caches.connections); caches.parsed.insert(cache_part.clone(), c.clone()); c } }; let Some(cache) = cache else { continue }; - if cache.external { + if let Some(source) = cache.kept { let name = x.attr("name").unwrap_or(""); + let from = source.describe(); cx.warn(format!( - "PivotTable \"{name}\" on sheet \"{sheet_name}\" gets its data from another workbook: it is kept for saving as it is, but can't be edited or refreshed here" + "PivotTable \"{name}\" on sheet \"{sheet_name}\" gets its data from {from}: it is kept for saving as it is, but can't be edited or refreshed here" )); - out.external.push(ExternalPivot { rel_id: rel.id.clone(), cache_part }); + out.external.push(ExternalPivot { rel_id: rel.id.clone(), cache_part, source }); continue; } if let Some(pt) = read_table(cx, &x, &cache, caches.next_id) { diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 99cb543b1a..d816468cc5 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -199,6 +199,7 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { // Sheets. `file_to_model[i]` maps the i-th to a model sheet index. let mut file_to_model: Vec> = vec![]; let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels); + pivot_caches.read_connections(&mut cx, &wb_rels); let sheet_els: Vec = wb_xml.child("sheets").map(|s| s.kids("sheet").cloned().collect()).unwrap_or_default(); for (i, se) in sheet_els.iter().enumerate() { let name = se.attr("name").unwrap_or("").to_string(); diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index 18b447ad88..f2849aa2e0 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -1067,3 +1067,259 @@ fn a_kept_pivot_table_whose_cache_is_not_listed_is_dropped() { assert!(written_pivot_tables(&u, "Report").is_empty()); assert!(written_pivot_caches(&u).is_empty()); } + +// ---------------------------------------------------------------- PivotTables on a data connection or the Data Model + +/// Bytes standing in for the Data Model (Excel's `xl/model/item.data`). +const MODEL_DATA: &[u8] = b"\x00\x01model bytes, not really a model\xFE\xFF"; +/// A larger stand-in, for running out of room to keep it. +static BIG_MODEL: [u8; 64 * 1024] = [7; 64 * 1024]; +const CT_MODEL: &str = "application/vnd.openxmlformats-officedocument.model+data"; +/// The model connection (id 1, as Excel writes it), a plain OLE DB connection (id 2) and a +/// worksheet connection loading a range into the model (id 3). +const MODEL_CONNECTIONS: &str = r#""#; +const CONN_RECORDS: &str = r#""#; + +/// An OLAP cache on the Data Model (no records: `saveData="0"`), on connection `id`. +fn model_cache(id: u32) -> String { + format!( + r#""# + ) +} + +/// A relational cache on connection `id`, with records. +fn conn_cache(id: u32) -> String { + format!( + r#""# + ) +} + +/// What a data-connection test package holds. +#[derive(Clone, Copy)] +struct ConnPkg { + /// The Data Model part and its workbook relationship. + model_part: bool, + /// The larger model stand-in. + big_model: bool, + /// `xl/connections.xml` and its workbook relationship. + connections: bool, + /// The connections part has a relationship to content GridCraft rewrites (so it can't be kept). + connections_blocked: bool, + /// The connection the Data Model cache names. + model_connection: u32, +} + +const CONN_PKG: ConnPkg = ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1 }; + +/// Sheet "Report" with a PivotTable on the Data Model (cache 3) and sheet "More" with one on the +/// plain connection (cache 4, with records), plus the hidden name a worksheet connection uses. +fn conn_pivot_package(o: ConnPkg) -> Vec { + let workbook = format!( + r#""# + ); + let ct = |part: &str, ty: &str| format!(r#""#); + let content_types = format!( + r#"{}{}{}{}{}{}{}{}{}{}"#, + ct("xl/workbook.xml", "sheet.main"), + ct("xl/worksheets/sheet1.xml", "worksheet"), + ct("xl/worksheets/sheet2.xml", "worksheet"), + ct("xl/styles.xml", "styles"), + ct("xl/connections.xml", "connections"), + ct("xl/pivotTables/pivotTable1.xml", "pivotTable"), + ct("xl/pivotTables/pivotTable2.xml", "pivotTable"), + ct("xl/pivotCache/pivotCacheDefinition1.xml", "pivotCacheDefinition"), + ct("xl/pivotCache/pivotCacheDefinition2.xml", "pivotCacheDefinition"), + ct("xl/pivotCache/pivotCacheRecords2.xml", "pivotCacheRecords"), + ); + let sheet = |v: &str| { + format!( + r#"x{v}"# + ) + }; + let (s1, s2) = (sheet("5"), sheet("6")); + let (c1, c2) = (model_cache(o.model_connection), conn_cache(2)); + let (t1, t2) = (ext_table("OnModel", 3), ext_table("OnConnection", 4)); + let mut wb_rels = vec![ + ("rId1", "worksheet", "worksheets/sheet1.xml"), + ("rId2", "worksheet", "worksheets/sheet2.xml"), + ("rId3", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition1.xml"), + ("rId4", "styles", "styles.xml"), + ("rId7", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition2.xml"), + ]; + if o.connections { + wb_rels.push(("rId5", "connections", "connections.xml")); + } + if o.model_part { + wb_rels.push(("rId6", "powerPivotData", "model/item.data")); + } + let wb_rels = rels(&wb_rels); + let t1_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition1.xml")]); + let t2_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition2.xml")]); + let c2_rels = rels(&[("rId1", "pivotCacheRecords", "pivotCacheRecords2.xml")]); + let s1_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable1.xml")]); + let s2_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable2.xml")]); + let conn_rels = rels(&[("rId1", "worksheet", "worksheets/sheet1.xml")]); + let mut parts: Vec<(&str, &[u8])> = vec![ + ("[Content_Types].xml", content_types.as_bytes()), + ("_rels/.rels", super::ROOT_RELS.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()), + ("xl/styles.xml", EXT_STYLES.as_bytes()), + ("xl/worksheets/sheet1.xml", s1.as_bytes()), + ("xl/worksheets/sheet2.xml", s2.as_bytes()), + ("xl/worksheets/_rels/sheet1.xml.rels", s1_rels.as_bytes()), + ("xl/worksheets/_rels/sheet2.xml.rels", s2_rels.as_bytes()), + ("xl/pivotTables/pivotTable1.xml", t1.as_bytes()), + ("xl/pivotTables/_rels/pivotTable1.xml.rels", t1_rels.as_bytes()), + ("xl/pivotTables/pivotTable2.xml", t2.as_bytes()), + ("xl/pivotTables/_rels/pivotTable2.xml.rels", t2_rels.as_bytes()), + ("xl/pivotCache/pivotCacheDefinition1.xml", c1.as_bytes()), + ("xl/pivotCache/pivotCacheDefinition2.xml", c2.as_bytes()), + ("xl/pivotCache/_rels/pivotCacheDefinition2.xml.rels", c2_rels.as_bytes()), + ("xl/pivotCache/pivotCacheRecords2.xml", CONN_RECORDS.as_bytes()), + ]; + if o.connections { + parts.push(("xl/connections.xml", MODEL_CONNECTIONS.as_bytes())); + } + if o.connections_blocked { + parts.push(("xl/_rels/connections.xml.rels", conn_rels.as_bytes())); + } + if o.model_part { + parts.push(("xl/model/item.data", if o.big_model { &BIG_MODEL[..] } else { MODEL_DATA })); + } + make_zip(&parts) +} + +/// The content type a written package gives a part. +fn content_type_of(u: &Unpacked, part: &str) -> String { + let types = xml::parse(u.parts.get("[Content_Types].xml").unwrap()).unwrap(); + if let Some(o) = types.kids("Override").find(|o| normalize(o.attr("PartName").unwrap()) == normalize(part)) { + return o.attr("ContentType").unwrap().to_string(); + } + let ext = part.rsplit('.').next().unwrap().to_ascii_lowercase(); + types.kids("Default").find(|d| d.attr("Extension").unwrap().eq_ignore_ascii_case(&ext)).unwrap().attr("ContentType").unwrap().to_string() +} + +/// Bytes kept by a read workbook. +fn kept_bytes(wb: &gridcraft_model::Workbook) -> usize { + wb.preserved.as_ref().map_or(0, |p| p.byte_len()) + wb.sheets.iter().filter_map(|s| s.preserved.as_ref()).map(|p| p.byte_len()).sum::() +} + +#[test] +fn pivot_tables_on_the_data_model_and_a_connection_survive_a_save() { + let (wb, rep) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap(); + assert!(wb.sheets.iter().all(|s| s.pivots.is_empty()), "not modelled: GridCraft can't refresh them"); + assert!(rep.warnings.iter().any(|w| w.contains("OnModel") && w.contains("Data Model")), "{:?}", rep.warnings); + assert!(rep.warnings.iter().any(|w| w.contains("OnConnection") && w.contains("a data connection")), "{:?}", rep.warnings); + assert!(rep.warnings.iter().any(|w| w.contains("Data Model is kept")), "{:?}", rep.warnings); + assert!(!rep.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep.warnings); + // Twice: what the first save kept is read back and kept again. + let first = write_xlsx(&wb).unwrap(); + let (again, rep2) = read_xlsx(&first).unwrap(); + assert!(!rep2.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep2.warnings); + for saved in [first, write_xlsx(&again).unwrap()] { + let u = Unpacked::new(&saved); + u.assert_valid(); + // The Data Model: same bytes, name and content type, related from the workbook. + assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA)); + assert_eq!(content_type_of(&u, "xl/model/item.data"), CT_MODEL); + let wb_rels = u.rels("xl/workbook.xml"); + assert!(wb_rels.iter().any(|r| r.1.ends_with("/powerPivotData") && r.2 == "xl/model/item.data"), "{wb_rels:?}"); + // The connections the caches name by id, and the hidden name a worksheet connection uses. + let conn = wb_rels.iter().find(|r| r.1.ends_with("/connections")).unwrap(); + assert_eq!(u.text(&conn.2), MODEL_CONNECTIONS); + assert!(u.text("xl/workbook.xml").contains("_xlcn.WorksheetConnection_T")); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 2, "{caches:?}"); + let cache = |id: &str| caches.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{caches:?}")).1.clone(); + assert_eq!(u.text(&cache("3")), model_cache(1)); + assert!(u.rels(&cache("3")).is_empty()); + assert_eq!(u.text(&cache("4")), conn_cache(2)); + let records = u.rels(&cache("4")).into_iter().find(|r| r.1.ends_with("/pivotCacheRecords")).unwrap(); + assert_eq!(u.text(&records.2), CONN_RECORDS); + for (sheet, name, id) in [("Report", "OnModel", "3"), ("More", "OnConnection", "4")] { + let t = written_pivot_tables(&u, sheet); + assert_eq!(t.len(), 1, "{sheet}"); + assert_eq!(u.rels(&t[0])[0].2, cache(id), "{sheet}"); + let x = u.text(&t[0]); + assert!(x.contains(&format!(r#"name="{name}" cacheId="{id}""#)), "{x}"); + let (color, code) = written_style(&u, &attr_of(&x, "format", "dxfId"), &attr_of(&x, "dataField", "numFmtId")); + assert_eq!((color.as_str(), code.as_str()), ("FF0000FF", "0.0%"), "{x}"); + } + } +} + +#[test] +fn the_data_model_is_kept_without_pivot_tables() { + let (mut wb, _) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap(); + wb.sheets.iter_mut().for_each(|s| Arc::make_mut(s).preserved = None); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA)); + // No kept table uses the caches any more: they go. + assert!(written_pivot_caches(&u).is_empty()); + assert!(u.find(model_cache(1).as_bytes()).is_empty() && u.find(CONN_RECORDS.as_bytes()).is_empty()); +} + +#[test] +fn data_model_pivot_tables_without_the_model_are_kept_as_plain_cells() { + // No model part, or no room left to keep it: the PivotTable on the model couldn't be + // refreshed and is dropped (its cells stay); the one on a plain connection is kept. + for too_large in [false, true] { + let pkg = ConnPkg { model_part: too_large, big_model: too_large, ..CONN_PKG }; + let src = conn_pivot_package(pkg); + let (wb, rep) = if too_large { + // Room for everything but the model: the caches are kept after it. + let all = kept_bytes(&read_xlsx(&src).unwrap().0); + crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(all - BIG_MODEL.len())); + let read = read_xlsx(&src); + crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(crate::passthrough::MAX_KEPT_TOTAL)); + let r = read.unwrap(); + assert!(r.1.warnings.iter().any(|w| w.contains("Data Model was dropped") && w.contains("too large")), "{:?}", r.1.warnings); + r + } else { + read_xlsx(&src).unwrap() + }; + let w = &rep.warnings; + assert!( + w.iter().any(|w| w.contains("1 PivotTable cache(s) on the workbook's Data Model were dropped") && w.contains("plain cells")), + "{w:?}" + ); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(!u.parts.contains_key("xl/model/item.data")); + assert!(written_pivot_tables(&u, "Report").is_empty()); + assert!(u.find(model_cache(1).as_bytes()).is_empty()); + assert!(u.text(&sheet_part(&u, "Report")).contains("5"), "the report cells stay"); + let caches = written_pivot_caches(&u); + assert_eq!(caches.iter().map(|c| c.0.as_str()).collect::>(), ["4"], "{caches:?}"); + assert_eq!(written_pivot_tables(&u, "More").len(), 1); + } +} + +#[test] +fn connection_pivot_tables_need_their_connections() { + // No connections part: the caches name connections that aren't there. + let (none, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, ..CONN_PKG })).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings); + // A cache naming a connection id the part doesn't have; the other cache is unaffected. + let (missing, rep) = read_xlsx(&conn_pivot_package(ConnPkg { model_connection: 9, ..CONN_PKG })).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings); + // A connections part that can't be kept: the model and every connection cache go with it. + let (blocked, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections_blocked: true, ..CONN_PKG })).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("Data Model was dropped")), "{:?}", rep.warnings); + assert!(rep.warnings.iter().any(|w| w.contains("2 PivotTable cache(s)") && w.contains("connections were not kept")), "{:?}", rep.warnings); + for (wb, all_gone) in [(none, true), (blocked, true), (missing, false)] { + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_tables(&u, "Report").is_empty()); + assert!(u.text(&sheet_part(&u, "Report")).contains("5")); + if all_gone { + assert!(written_pivot_tables(&u, "More").is_empty()); + assert!(written_pivot_caches(&u).is_empty()); + assert!(!u.parts.contains_key("xl/model/item.data")); + } else { + assert_eq!(written_pivot_tables(&u, "More").len(), 1); + } + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index be5da4b727..f7c3c56f6c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (XLSX PivotTables whose source is in another workbook are kept on save; previously trivial: chart sheets are kept on save (#727)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (XLSX PivotTables on a data connection or the Data Model, and the Data Model itself, are kept on save; previously minor: PivotTables whose source is in another workbook are kept on save) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -22,7 +22,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables) on a range, table or name of the same workbook, protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** PivotTables whose source is a range or name in another workbook (their PivotTable, cache definition and records parts and the cache's link to the other workbook's path, with the original `cacheId`; the `dxfId` and `numFmtId` style references are renumbered to the rewritten styles part; they aren't modelled, so they can't be edited or refreshed in GridCraft, their location isn't adjusted when rows or columns are inserted or deleted, and they are dropped with their sheet, a cache no kept PivotTable uses with them; checked in Excel: opens without repair and refreshes from the other workbook), custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables) on a range, table or name of the same workbook, protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** PivotTables whose source is a range or name in another workbook, a data connection (`connections.xml`) or the workbook's Data Model (OLAP caches, usually `saveData="0"` with no records) (their PivotTable, cache definition and records parts and the cache's link to the other workbook's path, with the original `cacheId`; the `dxfId` and `numFmtId` style references are renumbered to the rewritten styles part; they aren't modelled, so they can't be edited or refreshed in GridCraft, their location isn't adjusted when rows or columns are inserted or deleted, and they are dropped with their sheet, a cache no kept PivotTable uses with them; a cache on a connection is kept only when the connections are, one on the Data Model only when the model is, otherwise the PivotTable is left as plain cells with a warning; checked in Excel: opens without repair and refreshes, from the other workbook, the connection or the model), the Data Model (`xl/model/item.data`, byte for byte with its data connections, up to 64 MB like any kept part; Excel opens a Data Model PivotTable without it but can't refresh it; the `x15:dataModel` workbook extension is not kept, Excel rebuilds it; a worksheet connection names its table through a hidden `_xlcn.` defined name, and renaming or deleting that table in GridCraft leaves the kept connection stale: Excel refuses a file whose connection names a missing defined name; in one real Power Query model, refreshing a kept PivotTable in Excel re-runs the queries, which the original does not), custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures | @@ -85,6 +85,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | XLSX: PivotTables on a data connection or the Data Model are kept on save (they were dropped with their caches), with the Data Model part and the connections they name; dropped to plain cells with a warning when the model or connections can't be kept | | 2026-10-14 | minor | XLSX: PivotTables whose source is in another workbook are kept on save (they were dropped with their caches, and the PivotTable was lost); their style references follow the rewritten styles part | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | From c0ae95f721f9ffe3ab936b624528eb3c1e4ab449 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Tue, 20 Oct 2026 09:06:13 -0500 Subject: [PATCH 05/95] XIRR counts a blank cash flow as 0; XNPV errors like Excel for blanks A cash-flow column with unused (blank) rows made XIRR return #VALUE! where Excel returns the rate. Behaviour observed in Excel on synthetic workbooks: XIRR treats a blank value as 0 and ignores a blank date next to a blank or 0 flow (a nonzero flow without a date is #NUM!). XNPV is strict: a blank value is #NUM!, and so is a blank date next to a blank or 0 value (#VALUE! next to a nonzero one). Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/financial.rs | 45 ++++++++++++++++++++++++++----- docs/function-parity.md | 3 ++- 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 2758246ceb..6490efaaa2 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -237,7 +237,12 @@ fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { } /// Values and dates for XNPV/XIRR: both must be numeric and of equal length. -fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { +/// +/// Blank cells follow what Excel returns (observed on synthetic workbooks). With `lenient` (XIRR) +/// a blank value counts as 0 and a blank date is ignored when its value is blank or 0; a nonzero +/// value without a date is `#NUM!`. XNPV is strict: a blank value is `#NUM!`, and so is a blank +/// date next to a blank or 0 value (`#VALUE!` next to a nonzero one). +fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec, Vec)> { let va = as_array(values); let da = as_array(dates); if va.data.len() != da.data.len() { @@ -246,17 +251,22 @@ fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { let mut v = Vec::with_capacity(va.data.len()); let mut d = Vec::with_capacity(da.data.len()); for (x, y) in va.data.iter().zip(da.data.iter()) { - match x { - Value::Number(n) => v.push(*n), + let value = match x { + Value::Number(n) => *n, + Value::Empty if lenient => 0.0, + Value::Empty => return Err(CellError::Num), Value::Error(e) => return Err(*e), _ => return Err(CellError::Value), - } + }; match y { Value::Number(n) => d.push(n.trunc()), Value::Error(e) => return Err(*e), Value::Text(_) => d.push(y.to_number()?.trunc()), + Value::Empty if lenient && value == 0.0 => continue, + Value::Empty if lenient || value == 0.0 => return Err(CellError::Num), _ => return Err(CellError::Value), } + v.push(value); } let d0 = *d.first().ok_or(CellError::Num)?; if d.iter().any(|&x| x < d0 || x < 0.0) { @@ -275,12 +285,12 @@ fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R { if rate <= -1.0 { return Err(CellError::Num); } - let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value, false)?; num_val(xnpv_calc(rate, &v, &d)) } fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { - let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?; let guess = opt_num(a, 2, 0.1)?; if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); @@ -1795,6 +1805,29 @@ mod tests { is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num); } + #[test] + fn blank_cash_flows_follow_excel_for_xirr_and_xnpv() { + // Each result below was observed in Excel on a synthetic workbook: five rows, the first + // four -10000, 2750, 4250, 3250 on 39448, 39508, 39751, 39859; the last row varies. + let dates = col(&[39448.0, 39508.0, 39751.0, 39859.0, 39904.0]); + let gap = arr([39448.0, 39508.0, 39751.0, 39859.0].iter().map(|x| vec![nv(*x)]).chain([vec![Value::Empty]]).collect()); + let flows = |last: Value| arr([-10000.0, 2750.0, 4250.0, 3250.0].iter().map(|x| vec![nv(*x)]).chain([vec![last]]).collect()); + let rate = 0.033791377645041754; + // XIRR: a blank value counts as 0 and a blank date is ignored when its value is blank or 0. + close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(dates.clone())]), rate, 1e-9); + close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(dates.clone())]), rate, 1e-9); + close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(gap.clone())]), rate, 1e-9); + close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(gap.clone())]), rate, 1e-9); + is_err(ev("XIRR", vec![rf(flows(nv(2750.0))), rf(gap.clone())]), CellError::Num); + is_err(ev("XIRR", vec![rf(flows(tv("-"))), rf(dates.clone())]), CellError::Value); + // XNPV is strict: a blank value is #NUM! where 0 is a number. + close_tol(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(dates.clone())]), -382.66, 1e-2); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates)]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Value); + } + #[test] fn cash_flows() { close_tol(ev("NPV", vec![n(0.1), n(-10000.0), n(3000.0), n(4200.0), n(6800.0)]), 1188.443412, 1e-9); diff --git a/docs/function-parity.md b/docs/function-parity.md index 2343e0de94..0a96960d2e 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (MEDIAN and AGGREGATE median avoid intermediate overflow) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-20 · **Change:** minor (XIRR counts a blank cash flow as 0 and ignores a blank date next to a blank or 0 flow, as Excel does; XNPV errors like Excel); previously minor (MEDIAN and AGGREGATE median avoid intermediate overflow) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -114,6 +114,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` or `#VALUE!` Excel gives for blank values and dates (observed on synthetic workbooks) | | 2026-10-15 | minor | MEDIAN and AGGREGATE median use an overflow-safe midpoint (#1579); regressions cover finite extremes, tiny values and dependent recalculation | | 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | From 744c6cde44ba1b9ab65b630d0946eae139e0a88d Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:51:50 +0200 Subject: [PATCH 06/95] Tests: the table-filter AutoFit test measures the heading with the grid's font `table_filter_autofit_works_through_command_and_header_double_click` checked the fitted column against the engine's text estimate, but AutoFit measures with the font the grid draws (#1316). Where that font is installed (seen on Windows 11) it is narrower than the estimate, so the test failed there at 50% zoom; on Linux CI the font is missing and both fall back to the estimate. The test now measures the heading the way AutoFit and the grid do. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/header_autofit.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/header_autofit.rs b/crates/ui-egui/tests/header_autofit.rs index 5e123809fb..1dbf7d2751 100644 --- a/crates/ui-egui/tests/header_autofit.rs +++ b/crates/ui-egui/tests/header_autofit.rs @@ -183,7 +183,9 @@ fn table_filter_autofit_works_through_command_and_header_double_click() { let rect = geo.cell_rect(sheet, cell); let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell); let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell)); - let text_width = gridcraft_engine::cmd::format::approx_text_width("Quarterly Revenue", style.font.size, style.font.bold) * geo.z; + // The heading as the grid draws it: AutoFit measures with that font too (#1316), which + // is narrower than the engine's estimate wherever the font is installed. + let text_width = gridcraft_ui_egui::theme::cell_text_width(&h.ctx, "Quarterly Revenue", &style.font, true) * geo.z; assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}"); assert_eq!(app.session.active().unwrap().undo.len(), 1); h.state_mut().session.execute("edit.undo", json!({})).unwrap(); From 81e523e431d487acfe0892345eecfee673a609db Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:27:53 +0200 Subject: [PATCH 07/95] AutoFit: a table's header is measured in the table style's bold font AutoFit Column Width measured every cell in its own style, but the grid draws a table's cells in the table style, which makes the header row bold, so a bold heading could be fitted too narrow. AutoFit now measures a table cell in the font the table gives it. (Found by CodeRabbit on #2269.) The table-filter AutoFit test checked the fitted column against the engine's text estimate, while AutoFit measures with the font the grid draws (#1316); where that font is installed the estimate is wider, so the test failed off Linux. It now measures the heading as the grid draws it, in the table style's font. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 27 ++++++++++++++++--- crates/engine/tests/autofit_filter_buttons.rs | 3 +++ crates/ui-egui/tests/header_autofit.rs | 12 ++++++--- docs/ui-parity.md | 3 ++- 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index cd28cfbfa3..2bdb6df96a 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -1123,7 +1123,8 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result { edit(s, |cx| { let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) }; let mut widths = Vec::new(); - let mut measured: std::collections::HashMap> = Default::default(); + // Keyed by style and boldness: a table's style can make a cell bold (its header row). + let mut measured: std::collections::HashMap<(StyleId, bool), std::collections::HashMap> = Default::default(); let mut distinct = 0usize; let used = sh.used_range(); for (a, b) in lines { @@ -1137,22 +1138,26 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result { } let id = sh.style_id(cell); let st = cx.wb.styles.get(id); + // The font as the grid draws the cell: in a table, the table style's (a bold + // header row), not only the cell's own. + let table_font = sh.table_at(cell).map(|t| crate::tables::table_cell_style(&cx.wb, si, t, cell).font); + let font = table_font.as_ref().unwrap_or(&st.font); let text = crate::display::cell_text(&cx.wb, sh, cell); for line in text.lines() { let w = match &measure { Some(m) => { - let known = measured.entry(id).or_default(); + let known = measured.entry((id, font.bold)).or_default(); match known.get(line) { Some(w) => *w, None => { - let w = m(line, &st.font, distinct < EXACT_TEXT_WIDTHS); + let w = m(line, font, distinct < EXACT_TEXT_WIDTHS); known.insert(line.to_owned(), w); distinct += 1; w } } } - None => approx_text_width(line, st.font.size, st.font.bold), + None => approx_text_width(line, font.size, font.bold), }; max = max.max(w + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell)); } @@ -1274,6 +1279,20 @@ mod tests { assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["num_fmt"], "0.00"); } + /// A table draws its header row bold; AutoFit measures that, not the cell's own plain font. + #[test] + fn autofit_measures_a_table_header_in_the_table_style_font() { + let mut s = crate::Session::new(); + s.new_workbook(); + let heading = "Quarterly Revenue by Region"; + s.execute("range.setValues", json!({"range": "A1", "values": [[heading, heading], [1, 1]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:A2", "header": true})).unwrap(); + s.execute("home.autofitColumnWidth", json!({"cols": "A:B"})).unwrap(); + let sh = s.active().unwrap().wb.active().unwrap(); + let (table, plain) = (sh.col_width(0) - sh.filter_button_space(CellRef::new(0, 0)), sh.col_width(1)); + assert!(table > plain, "the bold table header is wider than the same plain text: {table} vs {plain}"); + } + #[test] fn width_units() { assert_eq!(chars_to_points(8.43), 64.0); diff --git a/crates/engine/tests/autofit_filter_buttons.rs b/crates/engine/tests/autofit_filter_buttons.rs index dbf25eced0..2b27ad2b8a 100644 --- a/crates/engine/tests/autofit_filter_buttons.rs +++ b/crates/engine/tests/autofit_filter_buttons.rs @@ -7,6 +7,9 @@ fn table() -> Session { s.new_workbook(); s.execute("range.setValues", json!({"range":"A1", "values":[["Quarterly Revenue"], ["1"]]})).unwrap(); s.execute("insert.table", json!({"range":"A1:A2", "header":true})).unwrap(); + // Bold in its own style too, so the table style's bold header row changes nothing here and + // these tests compare only the filter button's room, with or without the table. + s.execute("home.bold", json!({"range":"A1", "on": true})).unwrap(); s } diff --git a/crates/ui-egui/tests/header_autofit.rs b/crates/ui-egui/tests/header_autofit.rs index 1dbf7d2751..57e621c57c 100644 --- a/crates/ui-egui/tests/header_autofit.rs +++ b/crates/ui-egui/tests/header_autofit.rs @@ -182,10 +182,14 @@ fn table_filter_autofit_works_through_command_and_header_double_click() { let cell = gridcraft_engine::core::CellRef::new(0, 0); let rect = geo.cell_rect(sheet, cell); let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell); - let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell)); - // The heading as the grid draws it: AutoFit measures with that font too (#1316), which - // is narrower than the engine's estimate wherever the font is installed. - let text_width = gridcraft_ui_egui::theme::cell_text_width(&h.ctx, "Quarterly Revenue", &style.font, true) * geo.z; + // The heading as the grid draws it: in the table style's font, bold in the header row, + // measured as AutoFit measures (#1316), which is narrower than the engine's estimate + // wherever the font is installed. + let wb = &app.session.active().unwrap().wb; + let table = sheet.table_at(cell).expect("A1 is the table's header"); + let font = gridcraft_engine::tables::table_cell_style(wb, wb.active_sheet, table, cell).font; + assert!(font.bold, "the table style draws its header bold"); + let text_width = gridcraft_ui_egui::theme::cell_text_width(&h.ctx, "Quarterly Revenue", &font, true) * geo.z; assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}"); assert_eq!(app.session.active().unwrap().undo.len(), 1); h.state_mut().session.execute("edit.undo", json!({})).unwrap(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 07797d70d0..27ac154e50 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (AutoFit Column Width measures a table's header in the table style's bold font; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **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 @@ -176,6 +176,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | AutoFit Column Width measures a table's cells in the font the table style draws them in, so a bold header row is fitted bold; it measured the cell's own, plain font and could leave a bold heading too narrow | | 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 | From db2fffa9be7be607e46549c7fe08d21087651010 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 17:19:15 +0200 Subject: [PATCH 08/95] Print: Print Selection in File > Print > Settings, several selected areas print one after the other (fixes #2351) --- ROADMAP.md | 3 +- crates/engine/src/cmd/print.rs | 58 +++++++++++++----- crates/ui-egui/src/backstage.rs | 52 +++++++++++++---- crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/el.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 7 ++- crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/nl.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt.rs | 1 + crates/ui-egui/src/i18n/ro.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/sr.rs | 1 + crates/ui-egui/src/i18n/tr.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + crates/ui-egui/src/i18n/vi.rs | 1 + crates/ui-egui/src/i18n/zh.rs | 1 + crates/ui-egui/tests/print_selection.rs | 78 +++++++++++++++++++++++++ docs/gaps.md | 5 +- docs/ui-parity.md | 5 +- 24 files changed, 192 insertions(+), 33 deletions(-) create mode 100644 crates/ui-egui/tests/print_selection.rs diff --git a/ROADMAP.md b/ROADMAP.md index 1faf680ca3..873b1ee095 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-22 · **Change:** trivial (progress log: formula hardening, #2163/#2162; previously minor: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (File › Print › Settings: Print Selection; previously: progress log: formula hardening, #2163/#2162; previously minor: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel | | 2026-10-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-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 | diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 4c80f2fa90..a871937949 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Export as PDF", ["File", "Export"], None, - "{path?, sheets?: active|all, range?: \"A1:F40\" (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.", + "{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.", has_doc, export_pdf ), @@ -145,7 +145,8 @@ impl SheetLayout { #[derive(Clone, Debug, Default)] pub struct PrintOptions { pub all_sheets: bool, - pub range: Option, + /// Areas of the active sheet to print instead of its print area, in order (Print Selection). + pub ranges: Vec, pub fit_to_page: Option, } @@ -156,11 +157,13 @@ impl PrintOptions { Some("all") | Some("workbook") => true, Some(other) => return Err(bad(cmd, format!("`sheets` must be active or all, not `{other}`"))), }; - let range = match str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { - Some(r) => Some(RangeRef::parse(split_sheet(r).1).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?), - None => None, - }; - Ok(PrintOptions { all_sheets, range, fit_to_page: bool_param(p, "fitToPage") }) + let mut ranges = Vec::new(); + if let Some(r) = str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { + for part in split_sheet(r).1.split(',') { + ranges.push(RangeRef::parse(part.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?); + } + } + Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") }) } } @@ -376,14 +379,20 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec { if pages >= MAX_PAGES { break; } - let ovr = if si == wb.active_sheet { opts.range } else { None }; - if opts.all_sheets && ovr.is_none() && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) { + let areas: Vec> = + if si == wb.active_sheet && !opts.ranges.is_empty() { opts.ranges.iter().copied().map(Some).collect() } else { vec![None] }; + if opts.all_sheets && areas == [None] && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) { continue; } - if let Some(mut l) = layout_sheet(wb, si, opts, ovr) { - l.pages.truncate(MAX_PAGES - pages); - pages += l.pages.len(); - out.push(l); + for ovr in areas { + if pages >= MAX_PAGES { + break; + } + if let Some(mut l) = layout_sheet(wb, si, opts, ovr) { + l.pages.truncate(MAX_PAGES - pages); + pages += l.pages.len(); + out.push(l); + } } } if out.is_empty() && opts.all_sheets { @@ -1859,6 +1868,29 @@ mod tests { assert!(!cropped.contains("/Dest [")); } + fn preview_ranges(s: &mut Session, p: Json) -> Vec { + let r = s.execute("file.printPreview", p).unwrap(); + r["pageList"].as_array().unwrap().iter().map(|pg| pg["range"].as_str().unwrap().to_string()).collect() + } + + #[test] + fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("cell.set", json!({"cell": "H20", "input": "y"})).unwrap(); + s.execute("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap(); + assert_eq!(preview_ranges(&mut s, json!({})), ["F10:H20"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]); + // Several areas, like a multi-area selection: one run of pages each, in the order given. + assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]); + let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"})); + assert_eq!(pages, 2); + for bad in ["A1:B2,", "A1:B2,nope", ","] { + assert!(s.execute("file.printPreview", json!({"range": bad})).is_err(), "{bad}"); + } + } + #[test] fn header_sections_split_join_and_field_names() { let spec = "&L&\"Arial,Bold\"Sales &&Co&CPage &P of &N&R&D"; diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index c2acf025bf..a2b68b360c 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -102,20 +102,41 @@ const PROPERTIES: [(&str, &str); 6] = [ ("description", "Description"), ]; +/// What File › Print › Settings prints. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PrintScope { + ActiveSheets, + EntireWorkbook, + /// The selected cells of the active sheet. + Selection, +} + +impl PrintScope { + const ALL: [PrintScope; 3] = [PrintScope::ActiveSheets, PrintScope::EntireWorkbook, PrintScope::Selection]; + + fn label(self) -> &'static str { + match self { + PrintScope::ActiveSheets => "Print Active Sheets", + PrintScope::EntireWorkbook => "Print Entire Workbook", + PrintScope::Selection => "Print Selection", + } + } +} + /// The open Backstage view. #[derive(Clone, Debug)] pub struct Backstage { pub page: Page, /// Info: property drafts while a field is being edited (committed when it loses focus). props: [String; 6], - /// Print: the whole workbook rather than the active sheet. - pub print_all: bool, + /// Print: what to print (the Settings menu's first choice). + pub print_scope: PrintScope, /// Print: fit each sheet on one page. pub fit_to_page: bool, /// Print: the previewed page (0-based). preview_page: usize, - /// Print: the preview for (document, revision, whole workbook, fit to page). - preview: Option<((u64, u64, bool, bool), Json)>, + /// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page). + preview: Option<((u64, u64, PrintScope, String, bool), Json)>, /// Save As: the chosen file type (an extension from [`SAVE_TYPES`]). pub save_format: &'static str, /// Home and Open: when the recent workbooks were last changed. @@ -132,7 +153,7 @@ impl Backstage { Backstage { page, props: Default::default(), - print_all: false, + print_scope: PrintScope::ActiveSheets, fit_to_page: false, preview_page: 0, preview: None, @@ -703,11 +724,19 @@ fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) dim(ui, lang.tr("No workbook is open.")); return; }; - let mut params = json!({"sheets": if bs.print_all { "all" } else { "active" }}); + let mut params = json!({"sheets": if bs.print_scope == PrintScope::EntireWorkbook { "all" } else { "active" }}); + // The selection is not part of the document revision, so it goes in the preview's key. + let mut selection = String::new(); + if bs.print_scope == PrintScope::Selection + && let Some(d) = app.session.active() + { + selection = d.selection.a1(); + params["range"] = json!(selection); + } if bs.fit_to_page { params["fitToPage"] = json!(true); } - let key = (uid, revision, bs.print_all, bs.fit_to_page); + let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page); if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) { let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null); bs.preview = Some((key, preview)); @@ -727,11 +756,10 @@ fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcome) out.close = app.services.print_native.is_none(); } ui.add_space(16.0); - let scope = if bs.print_all { "Print Entire Workbook" } else { "Print Active Sheets" }; - egui::ComboBox::from_id_salt("backstage_print_scope").width(230.0).selected_text(lang.tr(scope)).show_ui(ui, |ui| { - for (all, label) in [(false, "Print Active Sheets"), (true, "Print Entire Workbook")] { - if ui.selectable_label(bs.print_all == all, lang.tr(label)).clicked() { - bs.print_all = all; + egui::ComboBox::from_id_salt("backstage_print_scope").width(230.0).selected_text(lang.tr(bs.print_scope.label())).show_ui(ui, |ui| { + for scope in PrintScope::ALL { + if ui.selectable_label(bs.print_scope == scope, lang.tr(scope.label())).clicked() { + bs.print_scope = scope; bs.preview_page = 0; } } diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index fc9181feb1..db89a29e6f 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -308,6 +308,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Uloží sešit pod jiným názvem nebo do jiné složky.", "Print Active Sheets" => "Vytisknout aktivní listy", "Print Entire Workbook" => "Vytisknout celý sešit", + "Print Selection" => "Vytisknout výběr", "Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku", "Page Setup…" => "Vzhled stránky…", "Page {page} of {pages}" => "Stránka {page} z {pages}", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 61c2292f49..cc31a117e4 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -313,6 +313,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { } "Print Active Sheets" => "Aktive Blätter drucken", "Print Entire Workbook" => "Gesamte Arbeitsmappe drucken", + "Print Selection" => "Auswahl drucken", "Fit Sheet on One Page" => "Blatt auf einer Seite darstellen", "Page Setup…" => "Seite einrichten…", "Page {page} of {pages}" => "Seite {page} von {pages}", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index e54416a6fd..287072b55b 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -284,6 +284,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Αποθηκεύστε το βιβλίο εργασίας με άλλο όνομα ή σε άλλον φάκελο.", "Print Active Sheets" => "Εκτύπωση ενεργών φύλλων", "Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας", + "Print Selection" => "Εκτύπωση επιλογής", "Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα", "Page Setup…" => "Διαμόρφωση σελίδας…", "Page {page} of {pages}" => "Σελίδα {page} από {pages}", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 36898c0985..e19a1ab16c 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -310,6 +310,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Guarda el libro con otro nombre o en otra carpeta.", "Print Active Sheets" => "Imprimir hojas activas", "Print Entire Workbook" => "Imprimir todo el libro", + "Print Selection" => "Imprimir selección", "Fit Sheet on One Page" => "Ajustar hoja en una página", "Page Setup…" => "Configurar página…", "Page {page} of {pages}" => "Página {page} de {pages}", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 317647c2f5..595b58bd52 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -395,6 +395,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Enregistrer le classeur sous un autre nom ou dans un autre dossier.", "Print Active Sheets" => "Imprimer les feuilles actives", "Print Entire Workbook" => "Imprimer tout le classeur", + "Print Selection" => "Imprimer la sélection", "Fit Sheet on One Page" => "Ajuster la feuille sur une page", "Page Setup…" => "Mise en page…", "Page {page} of {pages}" => "Page {page} sur {pages}", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 65f356669e..e6f3a3120f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -384,6 +384,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salva la cartella di lavoro con un altro nome o in un'altra cartella.", "Print Active Sheets" => "Stampa fogli attivi", "Print Entire Workbook" => "Stampa intera cartella di lavoro", + "Print Selection" => "Stampa selezione", "Fit Sheet on One Page" => "Adatta foglio a una pagina", "Page Setup…" => "Imposta pagina…", "Page {page} of {pages}" => "Pagina {page} di {pages}", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 482852d8d7..a75093de9c 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -391,6 +391,7 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Save the workbook under another name or in another folder.", "ブックを別の名前または別のフォルダーに保存します。"), ("Print Active Sheets", "作業中のシートを印刷"), ("Print Entire Workbook", "ブック全体を印刷"), + ("Print Selection", "選択した部分を印刷"), ("Fit Sheet on One Page", "シートを 1 ページに印刷"), ("Page Setup…", "ページ設定…"), ("Page {page} of {pages}", "{page} / {pages} ページ"), @@ -1236,9 +1237,9 @@ mod tests { assert!(seen.insert(*english), "duplicate key across CORE and DIALOGS: {english:?}"); } assert_eq!(seen.len(), catalog_keys().count()); - assert_eq!(CORE.len(), 392, "the shared reference set every catalog covers"); + assert_eq!(CORE.len(), 393, "the shared reference set every catalog covers"); assert_eq!(DIALOGS.len(), 562, "the dialog, message and menu strings beyond it"); - assert_eq!(catalog_keys().count(), 954); + assert_eq!(catalog_keys().count(), 955); } #[test] @@ -1256,7 +1257,7 @@ mod tests { #[test] fn covers_every_key_the_portuguese_catalog_translates() { let portuguese = portuguese_keys(); - assert_eq!(portuguese.len(), 954, "pt.rs's arms changed: add the new keys here and update the count"); + assert_eq!(portuguese.len(), 955, "pt.rs's arms changed: add the new keys here and update the count"); let japanese: HashSet<&str> = catalog_keys().collect(); for key in &portuguese { assert!(japanese.contains(key.as_str()), "the Portuguese catalog translates {key:?}, the Japanese one does not"); diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d3c440cf30..31f73b7d66 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -397,6 +397,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "통합 문서를 다른 이름 또는 다른 폴더에 저장합니다.", "Print Active Sheets" => "활성 시트 인쇄", "Print Entire Workbook" => "전체 통합 문서 인쇄", + "Print Selection" => "선택 영역 인쇄", "Fit Sheet on One Page" => "한 페이지에 시트 맞추기", "Page Setup…" => "페이지 설정…", "Page {page} of {pages}" => "{page}/{pages} 페이지", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index c1f952357f..8e568fc871 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -383,6 +383,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "De werkmap onder een andere naam of in een andere map opslaan.", "Print Active Sheets" => "Actieve bladen afdrukken", "Print Entire Workbook" => "Hele werkmap afdrukken", + "Print Selection" => "Selectie afdrukken", "Fit Sheet on One Page" => "Blad op één pagina passen", "Page Setup…" => "Pagina-instelling…", "Page {page} of {pages}" => "Pagina {page} van {pages}", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index e3185d55ae..231424cc0b 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -378,6 +378,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Zapisz skoroszyt pod inną nazwą lub w innym folderze.", "Print Active Sheets" => "Drukuj aktywne arkusze", "Print Entire Workbook" => "Drukuj cały skoroszyt", + "Print Selection" => "Drukuj zaznaczenie", "Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony", "Page Setup…" => "Ustawienia strony…", "Page {page} of {pages}" => "Strona {page} z {pages}", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 1b56ff5046..c984853f01 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -390,6 +390,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salve a pasta de trabalho com outro nome ou em outra pasta.", "Print Active Sheets" => "Imprimir planilhas ativas", "Print Entire Workbook" => "Imprimir toda a pasta de trabalho", + "Print Selection" => "Imprimir seleção", "Fit Sheet on One Page" => "Ajustar planilha em uma página", "Page Setup…" => "Configurar página…", "Page {page} of {pages}" => "Página {page} de {pages}", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 9e0d92516f..4fca840ed6 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -385,6 +385,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salvează registrul cu alt nume sau în alt folder.", "Print Active Sheets" => "Imprimare foi active", "Print Entire Workbook" => "Imprimare tot registrul", + "Print Selection" => "Imprimare selecție", "Fit Sheet on One Page" => "Încadrare foaie pe o pagină", "Page Setup…" => "Configurare pagină…", "Page {page} of {pages}" => "Pagina {page} din {pages}", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index ce675701ea..776292b413 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -397,6 +397,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Сохранить книгу под другим именем или в другой папке.", "Print Active Sheets" => "Напечатать активные листы", "Print Entire Workbook" => "Напечатать всю книгу", + "Print Selection" => "Напечатать выделенный диапазон", "Fit Sheet on One Page" => "Вписать лист на одну страницу", "Page Setup…" => "Параметры страницы…", "Page {page} of {pages}" => "Страница {page} из {pages}", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index c71ce53a87..0aa3311a2b 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -389,6 +389,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Sačuvaj radnu svesku pod drugim imenom ili u drugoj fascikli.", "Print Active Sheets" => "Štampaj aktivne listove", "Print Entire Workbook" => "Štampaj celu radnu svesku", + "Print Selection" => "Štampaj izbor", "Fit Sheet on One Page" => "Uklopi list na jednu stranicu", "Page Setup…" => "Podešavanje stranice…", "Page {page} of {pages}" => "Stranica {page} od {pages}", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index ce2bc8e1ec..0cdc8347ee 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -299,6 +299,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Çalışma kitabını başka bir adla veya başka bir klasöre kaydedin.", "Print Active Sheets" => "Etkin Sayfaları Yazdır", "Print Entire Workbook" => "Tüm Çalışma Kitabını Yazdır", + "Print Selection" => "Seçimi Yazdır", "Fit Sheet on One Page" => "Sayfayı Bir Sayfaya Sığdır", "Page Setup…" => "Sayfa Yapısı…", "Page {page} of {pages}" => "Sayfa {page} / {pages}", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 97659cc121..22ab200cc1 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -383,6 +383,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Зберегти книгу під іншим іменем або в іншій теці.", "Print Active Sheets" => "Надрукувати активні аркуші", "Print Entire Workbook" => "Надрукувати всю книгу", + "Print Selection" => "Надрукувати виділений діапазон", "Fit Sheet on One Page" => "Вмістити аркуш на одну сторінку", "Page Setup…" => "Параметри сторінки…", "Page {page} of {pages}" => "Сторінка {page} з {pages}", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 94c32b3a54..4b83941871 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -388,6 +388,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Lưu sổ làm việc với tên khác hoặc vào thư mục khác.", "Print Active Sheets" => "In các trang tính hiện hoạt", "Print Entire Workbook" => "In toàn bộ sổ làm việc", + "Print Selection" => "In vùng chọn", "Fit Sheet on One Page" => "Vừa trang tính trên một trang", "Page Setup…" => "Thiết lập trang…", "Page {page} of {pages}" => "Trang {page} / {pages}", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index c9d3ecb7d3..f4016724c9 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -389,6 +389,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "以其他名称或在其他文件夹中保存工作簿。", "Print Active Sheets" => "打印活动工作表", "Print Entire Workbook" => "打印整个工作簿", + "Print Selection" => "打印选定区域", "Fit Sheet on One Page" => "将工作表调整为一页", "Page Setup…" => "页面设置…", "Page {page} of {pages}" => "第 {page} 页,共 {pages} 页", diff --git a/crates/ui-egui/tests/print_selection.rs b/crates/ui-egui/tests/print_selection.rs new file mode 100644 index 0000000000..f715ea043f --- /dev/null +++ b/crates/ui-egui/tests/print_selection.rs @@ -0,0 +1,78 @@ +//! File › Print › Settings offers "Print Selection": only the selected cells are previewed and sent. +use std::{cell::RefCell, rc::Rc}; + +use egui_kittest::kittest::Queryable as _; +use gridcraft_engine::Session; +use gridcraft_ui_egui::{Services, SheetApp}; +use serde_json::json; + +fn contains(hay: &[u8], needle: &str) -> bool { + hay.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +/// A sheet whose print area (F10:H20, "Outside") is not where the selection (A1:B2, "Inside") is, +/// so printing the selection and printing the sheet give different pages. +fn harness(jobs: Rc>>>) -> egui_kittest::Harness<'static, SheetApp> { + let mut session = Session::new(); + session.new_workbook(); + let mut app = SheetApp::new(session, Services::default()); + app.run("cell.set", json!({"cell": "A1", "input": "Inside"})).unwrap(); + app.run("cell.set", json!({"cell": "D4", "input": "Second area"})).unwrap(); + app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap(); + app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap(); + app.run("selection.set", json!({"range": "A1:B2"})).unwrap(); + app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec()))); + app.run("ui.backstage", json!({"page": "print"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn choose_selection(h: &mut egui_kittest::Harness<'static, SheetApp>) { + h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("print scope combo").click(); + h.run_steps(3); + h.get_by_label("Print Selection").click(); + h.run_steps(4); +} + +#[test] +fn print_selection_previews_and_prints_only_the_selected_cells() { + let jobs = Rc::new(RefCell::new(Vec::new())); + let mut h = harness(jobs.clone()); + assert!(h.query_by_label("Sheet1 · F10:H20").is_some(), "the sheet prints its print area by default"); + choose_selection(&mut h); + assert!(h.query_by_label("Sheet1 · A1:B2").is_some(), "the preview shows the selection"); + assert!(h.query_by_label("Sheet1 · F10:H20").is_none()); + + h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click(); + h.run_steps(3); + let jobs = jobs.borrow(); + assert_eq!(jobs.len(), 1); + assert!(contains(&jobs[0], "(Inside) Tj"), "the selected cell is printed"); + assert!(!contains(&jobs[0], "(Outside) Tj"), "the print area is not"); +} + +#[test] +fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() { + let jobs = Rc::new(RefCell::new(Vec::new())); + let mut h = harness(jobs.clone()); + choose_selection(&mut h); + assert!(h.query_by_label("Sheet1 · A1:B2").is_some()); + + // Same document revision, other selection: the cached preview must not be reused. + h.state_mut().run("selection.set", json!({"range": "D4:E5"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label("Sheet1 · D4:E5").is_some(), "the preview is rebuilt for the new selection"); + assert!(h.query_by_label("Sheet1 · A1:B2").is_none()); + + // Two selected areas: Excel prints each area on its own page. + h.state_mut().run("selection.set", json!({"range": "A1:B2,D4:E5"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages"); +} diff --git a/docs/gaps.md b/docs/gaps.md index 7e2e40dc06..7a58a64f2e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (the Japanese catalog covers the dialogs, messages and menus) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (File › Print › Settings: Print Selection; previously: the Japanese catalog covers the dialogs, messages and menus) · **Target:** Microsoft Excel (Microsoft 365) Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open @@ -127,7 +127,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- ### 14. Page Layout view and print polish (U, F) - Page Layout view landed (#329): paper view with rulers and in-place header/footer editing. - Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print ranges and driver tray/options UI remain. **Estimate:** 5–10 h. + Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Driver tray/options UI remains. **Estimate:** 5–10 h. ### 15. Remaining functions and an oracle suite (F) - 18 missing, 9 stubs; no Excel-computed oracle corpus; #137, #138. **Estimate:** 16–26 h. @@ -178,6 +178,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | §14: Print Selection landed in File › Print › Settings (several selected areas print one after the other); "print ranges" removed from the remainder | | 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 | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c7cbc349ee..c88ec82930 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (File › Print › Settings: Print Selection; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **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 @@ -30,7 +30,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Task panes (Format Chart, Comments, Watch, Selection, PivotTable fields) | yes | yes; PivotTable source-field list scrollbar sits at the right edge of its pane | element-level Format pane for shapes and pictures missing | | Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | partial | Options dialog and template gallery missing | | Dark mode, system appearance | yes | yes | done (10-09); follows the system on first run, title-bar switch and File › Display theme (#194, #239) | -| 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) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has | +| 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, workbook or selection, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation) | 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 | margins drag on the rulers (#792, with header and footer margins); header/footer pictures, Different First Page / Odd & Even missing (1–3 h) | | Multiple windows per workbook | yes | no (#162) | see [hardware-parity.md](hardware-parity.md) | @@ -175,6 +175,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook: the preview and the printed PDF cover the selected cells, and a selection of several areas prints each area on its own pages, as in Excel (`file.print`, `file.exportPdf` and `file.printPreview` accept `range: "A1:B5,D1:E5"`). A single selected cell prints that cell | | 2026-10-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | | 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 | From df2b24dbfdc52ef8d18c793590b8a423ae43c920 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 19:12:21 +0200 Subject: [PATCH 09/95] Print Selection: split a multi-area range at its commas before dropping each Sheet! qualifier, so earlier unqualified areas are kept --- crates/engine/src/cmd/print.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index a871937949..a315e1f8c9 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -159,14 +159,33 @@ impl PrintOptions { }; let mut ranges = Vec::new(); if let Some(r) = str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { - for part in split_sheet(r).1.split(',') { - ranges.push(RangeRef::parse(part.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?); + for part in split_areas(r) { + ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?); } } Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") }) } } +/// Splits a multi-area reference at the commas outside quoted sheet names, so each area keeps +/// its own optional `Sheet!` prefix. +fn split_areas(r: &str) -> Vec<&str> { + let mut parts = Vec::new(); + let (mut start, mut quoted) = (0, false); + for (i, c) in r.char_indices() { + match c { + '\'' => quoted = !quoted, + ',' if !quoted => { + parts.push(&r[start..i]); + start = i + 1; + } + _ => {} + } + } + parts.push(&r[start..]); + parts +} + /// The range a sheet prints: its print area, else the used range grown to cover drawing /// objects. `None` when there is nothing to print. pub fn print_range(sh: &Sheet) -> Option { @@ -1891,6 +1910,15 @@ mod tests { } } + #[test] + fn a_sheet_qualifier_on_a_later_area_does_not_swallow_the_earlier_ones() { + let mut s = s(); + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]); + // A comma inside a quoted sheet name is not an area separator. + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,'a,b'!D4:E5"})), ["A1:B2", "D4:E5"]); + } + #[test] fn header_sections_split_join_and_field_names() { let spec = "&L&\"Arial,Bold\"Sales &&Co&CPage &P of &N&R&D"; From 17aae2da04d3cf94c113182711753afa5a7581f2 Mon Sep 17 00:00:00 2001 From: DerKarussellbremser <67138735+DerKarussellbremser@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:41:23 +0200 Subject: [PATCH 10/95] Grid: italic and bold in a one-face font are slanted and thickened, as in Excel Arial Black has a single face. A cell in Arial Black, bold italic, drew it upright and at its own weight; Excel slants it and thickens it (observed in its PDF: oblique by 1/3, outlined 0.23 pt at 9 pt). fonts.rs notes, while it binds a family's roles, which italic roles got an upright face and which bold roles got the plain face; the grid then lays such text out with egui's italics and paints it a second time about 1/36 of its size to the right. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KKbbMZpkzQuncTpqAyhkp9 --- crates/ui-egui/src/fonts.rs | 70 ++++++++++++++++++++++++++++++++++++- crates/ui-egui/src/grid.rs | 37 +++++++++++++++----- docs/ui-parity.md | 3 +- 3 files changed, 100 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 1a381b9d46..11125a9b04 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -325,6 +325,13 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face let mut bound: Vec = Vec::new(); for (bold, italic) in [(false, false), (true, false), (false, true), (true, true)] { let Some(primary) = pick_face(faces, bold, italic) else { continue }; + let role = role_key(family, bold, italic); + if italic && !primary.italic { + mark_synthetic(&role, SLANT); + } + if bold && pick_face(faces, false, italic).is_some_and(|plain| face_key(plain) == face_key(primary)) { + mark_synthetic(&role, BOLD); + } let mut chain: Vec = Vec::new(); for face in [Some(primary), pick_face(faces, false, false)] { let Some(face) = face else { continue }; @@ -344,7 +351,6 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face continue; } chain.extend(base.iter().cloned()); - let role = role_key(family, bold, italic); fonts.families.insert(egui::FontFamily::Name(role.clone().into()), chain); bound.push(role); } @@ -374,6 +380,35 @@ pub fn is_bound(role: &str) -> bool { bound().read().unwrap_or_else(|e| e.into_inner()).contains(role) } +/// Roles drawn with a face that lacks their slant or weight (Arial Black has one face only), as +/// `{role}|slant` and `{role}|bold`. Excel imitates the missing style (observed in its PDF: a cell in +/// Arial Black, bold italic, is slanted by 1/3 and outlined about 1/36 of its size thick). +static SYNTHETIC: OnceLock>> = OnceLock::new(); +const SLANT: &str = "slant"; +const BOLD: &str = "bold"; + +fn synthetic() -> &'static std::sync::RwLock> { + SYNTHETIC.get_or_init(|| std::sync::RwLock::new(HashSet::new())) +} + +fn mark_synthetic(role: &str, style: &str) { + synthetic().write().unwrap_or_else(|e| e.into_inner()).insert(format!("{role}|{style}")); +} + +fn is_synthetic(role: &str, style: &str) -> bool { + is_bound(role) && synthetic().read().unwrap_or_else(|e| e.into_inner()).contains(&format!("{role}|{style}")) +} + +/// Does italic text in this installed family have to be slanted when drawn (no italic face)? +pub fn is_slanted(family: &str, bold: bool) -> bool { + is_synthetic(&role_key(family, bold, true), SLANT) +} + +/// Does bold text in this installed family have to be thickened when drawn (no face of its own)? +pub fn is_emboldened(family: &str, italic: bool) -> bool { + is_synthetic(&role_key(family, true, italic), BOLD) +} + /// Serializes tests that mutate the process-wide bound-family registry. #[cfg(test)] pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -473,6 +508,39 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn styles_a_family_has_no_face_for_are_imitated() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("gridcraft-fonts-synthetic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + // One font file stands in for every face; each face is its own (path, index) by its name. + let face = |family: &str, file: &str, weight: f32, italic: bool| { + let path = dir.join(file); + std::fs::write(&path, epaint_default_fonts::UBUNTU_LIGHT).expect("write"); + Face { family: family.into(), names: vec![family.into()], path, index: 0, weight, italic } + }; + let mut fonts = egui::FontDefinitions::default(); + // Like Arial Black: one face, whatever its weight. + let mut bound = bind_faces(&mut fonts, "One Face", &[face("One Face", "one.ttf", 900.0, false)]); + let full = [ + face("Full", "full.ttf", 400.0, false), + face("Full", "full-b.ttf", 700.0, false), + face("Full", "full-i.ttf", 400.0, true), + face("Full", "full-bi.ttf", 700.0, true), + ]; + bound.extend(bind_faces(&mut fonts, "Full", &full)); + set_bound(bound); + assert!(is_slanted("One Face", false) && is_slanted("One Face", true)); + assert!(is_emboldened("One Face", false) && is_emboldened("One Face", true)); + assert!(!is_slanted("Full", false) && !is_slanted("Full", true), "its own italic faces are drawn as they are"); + assert!(!is_emboldened("Full", false) && !is_emboldened("Full", true), "its own bold faces are drawn as they are"); + assert!(!is_slanted("Not Bound", false) && !is_emboldened("Not Bound", false)); + set_bound([]); + assert!(!is_slanted("One Face", false) && !is_emboldened("One Face", false), "nothing is imitated once unbound"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A font that is just a table directory and a `name` table holding `records` as /// `(Windows language id, name id, text)`: all [`file_faces`] reads. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index b485104b1d..ce5545b8c6 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -1242,6 +1242,9 @@ pub(crate) fn paint_quadrant( let size = st.font.size * 96.0 / 72.0 * z; let fam = theme::cell_family(&st.font.name, st.font.bold, st.font.italic); let font = FontId::new(size, fam); + let slant = st.font.italic && crate::fonts::is_slanted(&st.font.name, st.font.bold); + let embolden = st.font.bold && crate::fonts::is_emboldened(&st.font.name, st.font.italic); + let bold_dx = if embolden { (size / 36.0).max(1.0 / p.ctx().pixels_per_point()) } else { 0.0 }; // Digits fit by the cell's own font and size, not the default 11pt (9pt marks in narrow columns). let char_w = p.layout_no_wrap("0".to_string(), font.clone(), Color32::PLACEHOLDER).size().x.max(1.0); let avail_w = rect.right() - text_left; @@ -1268,7 +1271,7 @@ pub(crate) fn paint_quadrant( // Rotated text wraps along its own direction (below), not across the column width. if !rotated && (st.align.wrap || st.align.h == HAlign::Justify) { let wrap_w = (rect.width() - 2.0 * pad - indent).max(4.0); - let mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, wrap_w); + let mut job = cell_job(text.clone(), font.clone(), color, wrap_w, slant); job.halign = match halign { HAlign::Center | HAlign::CenterAcross => egui::Align::Center, HAlign::Right => egui::Align::RIGHT, @@ -1281,7 +1284,7 @@ pub(crate) fn paint_quadrant( _ => text_left + pad + indent, }; let y = wrapped_cell_text_y(st.align.v, *rect, galley.size().y, z); - p.with_clip_rect(rect.intersect(p.clip_rect())).galley(pos2(x, y), galley, color); + paint_cell_galley(&p.with_clip_rect(rect.intersect(p.clip_rect())), pos2(x, y), galley, color, bold_dx); continue; } // Wrap Text off: Excel ignores the line breaks and draws the whole string on one line. @@ -1295,7 +1298,7 @@ pub(crate) fn paint_quadrant( .flatten(); let shrunk = small.is_some(); let font = small.unwrap_or(font); - let mut galley = p.layout_no_wrap(first_line.clone(), font.clone(), color); + let mut galley = p.layout_job(cell_job(first_line.clone(), font.clone(), color, f32::INFINITY, slant)); let mut w = galley.size().x; // Numbers and dates never overflow: they show #### when too narrow. let hashed = !shrunk && (numeric || matches!(v, Value::Number(_))) && w > avail_w - 2.0 * pad && st.align.h != HAlign::Fill; @@ -1303,7 +1306,7 @@ pub(crate) fn paint_quadrant( // Measured on `#` itself: it is wider than `0` in some fonts, and #### must fit its cell. let hash_w = p.layout_no_wrap("#".to_string(), font.clone(), color).size().x.max(1.0); let n = ((avail_w - 2.0 * pad) / hash_w).floor().max(1.0) as usize; - galley = p.layout_no_wrap("#".repeat(n), font.clone(), color); + galley = p.layout_job(cell_job("#".repeat(n), font.clone(), color, f32::INFINITY, slant)); w = galley.size().x; } // Repeat fill (`*` in number formats) / Fill alignment. A number already shown as #### keeps @@ -1319,7 +1322,7 @@ pub(crate) fn paint_quadrant( if first_line.is_char_boundary(pos) { s.insert_str(pos, &ch.to_string().repeat(n)); } - galley = p.layout_no_wrap(s, font.clone(), color); + galley = p.layout_job(cell_job(s, font.clone(), color, f32::INFINITY, slant)); w = galley.size().x; } // Center Across Selection: the text is centred over this cell and the empty cells to its right that also use it. @@ -1381,8 +1384,7 @@ pub(crate) fn paint_quadrant( let angle = -(st.align.rotation as f32).to_radians(); // Upright (±90°) wrapped text wraps to the row height: lines then stack across the column. let galley = if st.align.wrap && st.align.rotation.abs() == 90 { - let job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0)); - p.layout_job(job) + p.layout_job(cell_job(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0), slant)) } else { galley.clone() }; @@ -1391,7 +1393,7 @@ pub(crate) fn paint_quadrant( shape.angle = angle; cp.add(shape); } else { - cp.galley(pos2(x, y), galley.clone(), color); + paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx); } let baseline = y + gh * 0.82; match st.font.underline { @@ -1604,6 +1606,25 @@ fn merged_edges( out } +/// One cell's text as a layout job, wrapped at `wrap` (`f32::INFINITY`: one line). `slant` draws it +/// oblique, for an italic cell whose font has no italic face (see [`crate::fonts::is_slanted`]). +fn cell_job(text: String, font: FontId, color: Color32, wrap: f32, slant: bool) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::simple(text, font, color, wrap); + for section in &mut job.sections { + section.format.italics = slant; + } + job +} + +/// Paints one cell's text; `bold_dx` > 0 paints it again that far right, to thicken a bold cell +/// whose font has no bold face (see [`crate::fonts::is_emboldened`]). +fn paint_cell_galley(p: &Painter, pos: Pos2, galley: std::sync::Arc, color: Color32, bold_dx: f32) { + if bold_dx > 0.0 { + p.galley(pos + egui::vec2(bold_dx, 0.0), galley.clone(), color); + } + p.galley(pos, galley, color); +} + /// The smaller font that makes `text` fit in `room` points of width (Shrink to fit), or `None` /// when it already fits at its own size. fn shrink_font(p: &Painter, text: &str, font: &FontId, room: f32) -> Option { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5d5f1efeee..49c18d66bc 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; New Formatting Rule's formula box takes references clicked or dragged on the grid, #2348; Page Up and Ctrl+Up into frozen rows, Ctrl+Left and Alt+Page Up into frozen columns bring the scrolled area back; Auto Fill Options button after a left-drag of the fill handle (#1403); Show Outline Symbols, Ctrl+8; a too-wide number in a repeat-fill format such as Accounting shows #### instead of losing its leading digits; Esc and Enter close a data validation alert over the cell editor; Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846; Number Stored as Text indicator and Convert to Number) · **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 @@ -178,6 +178,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Italic and bold in an installed font that has no face for them (Arial Black has a single face) are imitated on the grid, as Excel does: the text is slanted and drawn a second time a little to the right (about 1/36 of the size, at least one pixel). Observed in Excel's PDF of a cell in Arial Black, bold italic: oblique by 1/3 and outlined 0.23 pt thick at 9 pt. egui's slant is fixed at about 1/4. Print and PDF still use the standard PDF fonts (`fonts.rs` test) | | 2026-10-23 | minor | Conditional Formatting ▸ New Rule, formula: clicking a cell on the grid writes its absolute reference at the formula box's caret (`=$B$2`, an empty box starts with `=`), a drag writes a range (`$B$2:$C$4`) and a second click replaces the reference just written, as in Excel ("Selecting cells on the worksheet inserts absolute cell references"). The selection the rule applies to doesn't move, and the box keeps the keyboard. After an operand (`=A1>5`) the click does nothing (#2348) | | 2026-10-23 | minor | Frozen panes: Page Up, Ctrl+Up and Shift variants that move from the scrolled rows into the frozen ones bring the scrolled rows back to the top, so the rows in between are seen again (Page Up from far down used to end on row 1 with the view still a page down); Ctrl+Left and Alt+Page Up do the same for frozen columns. Other ways of selecting a frozen cell (click, Find, Go To, Undo, formula pointing) leave the view where it is | | 2026-10-23 | minor | After a left-drag of the fill handle an Auto Fill Options button sits below the filled cells; its menu redoes the fill as Copy Cells, Fill Series, Fill Formatting Only or Fill Without Formatting (undoes the drag's fill, then `edit.autoFill` in that mode). It goes away when the workbook changes or the selection moves (#1403) | From c4ef580a22a5c276a76e94401085bef5b7a932db Mon Sep 17 00:00:00 2001 From: DerKarussellbremser <67138735+DerKarussellbremser@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:41:41 +0200 Subject: [PATCH 11/95] Grid: imitate the styles of the face actually drawn; bold for shrunk and rotated text Review fixes. The slant and bold markers are now set from the face the role is drawn in (the first whose file could be read), so a family whose bold or italic file is missing gets them imitated too, and a later binding that no longer needs a marker removes it. The bold offset follows the size that is painted after Shrink to Fit, and rotated text gets its second impression along its own direction. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KKbbMZpkzQuncTpqAyhkp9 --- crates/ui-egui/src/fonts.rs | 33 ++++++++++++++++++++++----------- crates/ui-egui/src/grid.rs | 15 ++++++++++++--- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 11125a9b04..a785c65b2e 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -326,13 +326,9 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face for (bold, italic) in [(false, false), (true, false), (false, true), (true, true)] { let Some(primary) = pick_face(faces, bold, italic) else { continue }; let role = role_key(family, bold, italic); - if italic && !primary.italic { - mark_synthetic(&role, SLANT); - } - if bold && pick_face(faces, false, italic).is_some_and(|plain| face_key(plain) == face_key(primary)) { - mark_synthetic(&role, BOLD); - } let mut chain: Vec = Vec::new(); + // The face the role's text is actually drawn in: the first one whose file could be read. + let mut drawn: Option<&Face> = None; for face in [Some(primary), pick_face(faces, false, false)] { let Some(face) = face else { continue }; let key = face_key(face); @@ -346,10 +342,14 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face fonts.font_data.insert(key.clone(), std::sync::Arc::new(fd)); } chain.push(key); + drawn.get_or_insert(face); } - if chain.is_empty() { - continue; - } + let Some(drawn) = drawn else { continue }; + // Imitate what the drawn face lacks: italic when it is upright; bold when it is the family's + // plain face (the family has no bold of its own, or the bold file couldn't be read). + let own_bold = pick_face(faces, false, italic).is_none_or(|plain| face_key(plain) != face_key(primary)); + set_synthetic(&role, SLANT, italic && !drawn.italic); + set_synthetic(&role, BOLD, bold && (face_key(drawn) != face_key(primary) || !own_bold)); chain.extend(base.iter().cloned()); fonts.families.insert(egui::FontFamily::Name(role.clone().into()), chain); bound.push(role); @@ -391,8 +391,14 @@ fn synthetic() -> &'static std::sync::RwLock> { SYNTHETIC.get_or_init(|| std::sync::RwLock::new(HashSet::new())) } -fn mark_synthetic(role: &str, style: &str) { - synthetic().write().unwrap_or_else(|e| e.into_inner()).insert(format!("{role}|{style}")); +fn set_synthetic(role: &str, style: &str, on: bool) { + let mut set = synthetic().write().unwrap_or_else(|e| e.into_inner()); + let key = format!("{role}|{style}"); + if on { + set.insert(key); + } else { + set.remove(&key); + } } fn is_synthetic(role: &str, style: &str) -> bool { @@ -530,9 +536,14 @@ mod tests { face("Full", "full-bi.ttf", 700.0, true), ]; bound.extend(bind_faces(&mut fonts, "Full", &full)); + // Bold and italic faces whose files can't be read: the regular face draws them, imitated. + let gone = |file: &str, weight: f32, italic: bool| Face { path: dir.join(file), ..face("Gone", "gone.ttf", weight, italic) }; + let broken = [face("Gone", "gone.ttf", 400.0, false), gone("missing-b.ttf", 700.0, false), gone("missing-i.ttf", 400.0, true)]; + bound.extend(bind_faces(&mut fonts, "Gone", &broken)); set_bound(bound); assert!(is_slanted("One Face", false) && is_slanted("One Face", true)); assert!(is_emboldened("One Face", false) && is_emboldened("One Face", true)); + assert!(is_slanted("Gone", false) && is_emboldened("Gone", false), "the regular face stands in, imitated"); assert!(!is_slanted("Full", false) && !is_slanted("Full", true), "its own italic faces are drawn as they are"); assert!(!is_emboldened("Full", false) && !is_emboldened("Full", true), "its own bold faces are drawn as they are"); assert!(!is_slanted("Not Bound", false) && !is_emboldened("Not Bound", false)); diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index ce5545b8c6..7bf2b15b4b 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -1244,7 +1244,9 @@ pub(crate) fn paint_quadrant( let font = FontId::new(size, fam); let slant = st.font.italic && crate::fonts::is_slanted(&st.font.name, st.font.bold); let embolden = st.font.bold && crate::fonts::is_emboldened(&st.font.name, st.font.italic); - let bold_dx = if embolden { (size / 36.0).max(1.0 / p.ctx().pixels_per_point()) } else { 0.0 }; + // How far the second impression of imitated bold sits from the first, by the size painted. + let ppp = p.ctx().pixels_per_point(); + let bold_dx = |size: f32| if embolden { (size / 36.0).max(1.0 / ppp) } else { 0.0 }; // Digits fit by the cell's own font and size, not the default 11pt (9pt marks in narrow columns). let char_w = p.layout_no_wrap("0".to_string(), font.clone(), Color32::PLACEHOLDER).size().x.max(1.0); let avail_w = rect.right() - text_left; @@ -1284,7 +1286,7 @@ pub(crate) fn paint_quadrant( _ => text_left + pad + indent, }; let y = wrapped_cell_text_y(st.align.v, *rect, galley.size().y, z); - paint_cell_galley(&p.with_clip_rect(rect.intersect(p.clip_rect())), pos2(x, y), galley, color, bold_dx); + paint_cell_galley(&p.with_clip_rect(rect.intersect(p.clip_rect())), pos2(x, y), galley, color, bold_dx(size)); continue; } // Wrap Text off: Excel ignores the line breaks and draws the whole string on one line. @@ -1389,11 +1391,18 @@ pub(crate) fn paint_quadrant( galley.clone() }; let pos = rotated_text_pos(*rect, galley.size(), angle, painted_halign(st.align.h, geo.rtl), st.align.v, pad, indent); + // Imitated bold: the second impression along the text's own direction. + let d = bold_dx(font.size); + if d > 0.0 { + let mut thick = egui::epaint::TextShape::new(pos + d * egui::vec2(angle.cos(), angle.sin()), galley.clone(), color); + thick.angle = angle; + cp.add(thick); + } let mut shape = egui::epaint::TextShape::new(pos, galley, color); shape.angle = angle; cp.add(shape); } else { - paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx); + paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx(font.size)); } let baseline = y + gh * 0.82; match st.font.underline { From 5e0fe2d28d6ce77099e469e8a38302f6de7398dd Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:57:26 -0500 Subject: [PATCH 12/95] XIRR: use the first nonzero cash flow for the search direction and residual A leading zero cash flow made the residual zero and the search direction wrong, so XIRR returned #NUM! for series a zero adds nothing to. --- crates/functions/src/financial.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 602e45a816..3a41159819 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -316,19 +316,21 @@ fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R { /// last digit: /// /// - Bracket the root from the guess (0 counts as 1e-5): double the rate while XNPV keeps the -/// sign it has at the guess and that sign differs from the first value (the root is higher). +/// sign it has at the guess and that sign differs from the first nonzero value (the root is higher). /// Otherwise the root is lower: bisect towards 0 if XNPV changes sign there; halve the rate /// towards 0 if XNPV is larger in size at 0 than at the guess; otherwise try minus the guess /// and then step halfway to -100% each time. A negative guess only moves towards 0 (root /// higher) or towards -100% (root lower). /// - Bisect the bracket, taking the midpoint from the upper end, until half the bracket is -/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first value|; return that +/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first nonzero value|; return that /// midpoint. A zero XNPV counts as the upper side. /// - Halving towards 0 that gets within that tolerance of 0 without a sign change goes on with /// the negative side; at most 100 XNPV evaluations in all; a rate of -100% or an XNPV that /// can't be computed (a negative base for fractional years) is #NUM!. struct XirrSolver<'a> { values: &'a [f64], + /// First nonzero value: sets the search direction and the residual scale. + first: f64, years: Vec, evals: usize, /// XNPV must be within this of 0 at the answer. @@ -363,10 +365,9 @@ impl XirrSolver<'_> { } fn solve(&mut self, guess: f64) -> R { - let first = self.values.first().copied().unwrap_or(0.0); let g = if guess == 0.0 { 1e-5 } else { guess }; let fg = self.f(g)?; - let higher = fg * first < 0.0; + let higher = fg * self.first < 0.0; if g > 0.0 { if higher { return self.double(g, fg); @@ -455,8 +456,8 @@ fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { return Err(CellError::Num); } let d0 = d.first().copied().unwrap_or(0.0); - let first = v.first().copied().unwrap_or(0.0); - let mut solver = XirrSolver { values: &v, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; + let first = v.iter().copied().find(|x| *x != 0.0).unwrap_or(0.0); + let mut solver = XirrSolver { values: &v, first, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; num_val(solver.solve(guess)?) } @@ -2030,6 +2031,9 @@ mod tests { xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23); xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34); xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5); + // A leading zero cash flow adds nothing, so the root is the one without it (10%). The + // exact Excel answer for this input is unobserved, so only the root is checked. + assert!(matches!(xirr_of(&[0.0, -100.0, 110.0], &[b, y1, y2], None), Value::Number(r) if (r - 0.1).abs() < 1e-7)); // Dates before the first are allowed (time runs from the first date); in the second // case the search finds no sign change. xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6); From 937634a31a6c1c6384c86e45053c478655d9bcf4 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:38:52 -0500 Subject: [PATCH 13/95] Test: drop internal tracker id from subtotal filter test header --- crates/engine/tests/subtotal-filter-roundtrip.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index f5e6b64805..6fcc09fd07 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -1,4 +1,4 @@ -//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen (ft-3ir.10.24). +//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen. //! //! Excel (observed in Windows Excel 16 with synthetic workbooks) saves rows a filter hides as plain //! `hidden="1"` rows; a hidden row counts as filtered when it lies in an AutoFilter (sheet or table) From 46bdd416bbc8878238404ee27fefa4e9f59cd105 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:48:11 -0500 Subject: [PATCH 14/95] Test: pass the trust level to DocState::new in the subtotal filter test --- crates/engine/tests/subtotal-filter-roundtrip.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index 6fcc09fd07..83987f8268 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -115,7 +115,7 @@ fn filtering_a_reopened_table_again_keeps_both_criteria() { s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); let back = reopened(wb(&s)); let mut s = Session::new(); - s.add_document(gridcraft_engine::DocState::new(back, None, "t".into())); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile)); s.execute("selection.set", json!({"cell":"A2"})).unwrap(); s.execute("data.filterBy", json!({"column":"B","custom":{"op":">","value":"50"}})).unwrap(); let sh = wb(&s).active().unwrap(); From 214ad973720ad58d42ada39a97f4f0c1c560d473 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:55:24 -0500 Subject: [PATCH 15/95] Test: a partial sheet filter folds into the table column it filters --- crates/xlsx/src/tests/roundtrip.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 5b79438dbb..bd53c22c85 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1418,9 +1418,9 @@ fn a_table_filter_criteria_survive_a_round_trip() { assert!(b.autofilter.is_none(), "a table's filter belongs to the table part, not the sheet"); } -/// Stored `colId` offsets are relative to the filter range's first column, so criteria of a filter -/// that starts right of the table's first column must not be folded into the table part, where -/// they would apply to the wrong column. +/// Stored `colId` offsets are relative to the table's first column, so criteria of a sheet filter +/// that starts right of the table's first column are moved to the column they filter (Region), not +/// kept at the filter's own offset (which would be Id). #[test] fn a_partial_sheet_filter_is_not_folded_into_a_table() { let mut wb = Workbook::new(); @@ -1454,6 +1454,10 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() { assert!(rep.warnings.is_empty(), "{:?}", rep.warnings); let b = back.sheet(0).unwrap(); let t = b.tables.first().expect("the table survived"); - assert!(t.filter.is_empty(), "the criteria landed on the wrong table column: {:?}", t.filter); + assert!( + matches!(t.filter.as_slice(), [(1, FilterCriterion::Values { values, .. })] if values == &["East".to_string()]), + "the criteria landed on the wrong table column: {:?}", + t.filter + ); assert!(b.autofilter.is_none(), "a sheet filter inside a table would be invalid"); } From 2d65676f5d4375fa73e6169d05155fccc2b21846 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:04:44 -0500 Subject: [PATCH 16/95] Filter: bound a table-header filter by the table, refuse a narrower range that would drop criteria, fail the test helper on errors --- crates/engine/src/cmd/data.rs | 14 ++++++++++---- crates/engine/tests/subtotal-filter-roundtrip.rs | 14 +++++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 944323e41a..38c3f0ccad 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -552,10 +552,9 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { } // A selected header row filters the data below it (#201). if p.get("range").is_none() && r.height() == 1 { - let region = if sh.table_at(r.start).is_some() { - current_region(sh, r.start) - } else { - crate::selection::current_region_outside_tables(sh, r.start) + let region = match sh.table_at(r.start) { + Some(t) => t.data_range().map(|dr| RangeRef::new(t.range.start, dr.end)).unwrap_or(t.range), + None => crate::selection::current_region_outside_tables(sh, r.start), }; if region.end.row > r.end.row { r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col)); @@ -569,6 +568,13 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) { return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); } + // A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them. + if let Some(t) = host.and_then(|i| sh.tables.get(i)) { + let shift = r.start.col.saturating_sub(t.range.start.col); + if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) { + return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width")); + } + } edit(s, |cx| { let sh = cx.sheet_mut(sheet)?; let mut criteria = vec![]; diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index 83987f8268..3f02b7606e 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -34,7 +34,7 @@ fn session(sample: &str, steps: &[(&str, Json)]) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"sample": sample})).unwrap(); for (id, p) in steps { - let _ = s.execute(id, p.clone()); + s.execute(id, p.clone()).unwrap(); } s } @@ -109,6 +109,18 @@ fn rows_hidden_by_hand_without_a_filter_still_count_for_subtotal_9() { assert_eq!(e1_e2(&back), (Value::Number(111111.0), Value::Number(110101.0))); } +#[test] +fn a_narrower_range_inside_a_filtered_table_is_refused_not_dropped() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + let back = reopened(wb(&s)); + let mut s = Session::new(); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile)); + s.execute("selection.set", json!({"cell":"D1"})).unwrap(); + assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err()); + assert_eq!(wb(&s).active().unwrap().tables[0].filter.len(), 1, "the table's criteria are kept"); +} + #[test] fn filtering_a_reopened_table_again_keeps_both_criteria() { let mut s = table_book(); From b97c27f2b310851db54be7a44c76d757c9e13ca0 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:10:53 -0500 Subject: [PATCH 17/95] Test: the repro helper tolerates refused steps again, with the reason in a comment --- crates/engine/tests/subtotal-filter-roundtrip.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/subtotal-filter-roundtrip.rs b/crates/engine/tests/subtotal-filter-roundtrip.rs index 3f02b7606e..4046713e17 100644 --- a/crates/engine/tests/subtotal-filter-roundtrip.rs +++ b/crates/engine/tests/subtotal-filter-roundtrip.rs @@ -34,7 +34,8 @@ fn session(sample: &str, steps: &[(&str, Json)]) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"sample": sample})).unwrap(); for (id, p) in steps { - s.execute(id, p.clone()).unwrap(); + // A refused step leaves the book as it was; the asserts check what survives. + let _ = s.execute(id, p.clone()); } s } From 95c0800c2224446e892298c15528af9d9e07e8bc Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:40:24 -0500 Subject: [PATCH 18/95] XLSX: password to modify (#921): kept on save, asked for on open or open read-only --- ROADMAP.md | 4 ++- crates/engine/src/cmd/file.rs | 17 +++++++++++-- crates/engine/src/io.rs | 4 +++ crates/engine/src/tests.rs | 40 ++++++++++++++++++++++++++++++ crates/model/src/lib.rs | 4 ++- crates/model/src/workbook.rs | 13 ++++++++++ crates/ui-egui/src/dialogs.rs | 19 +++++++++++++- crates/ui-egui/src/lib.rs | 7 ++++++ crates/xlsx/src/read.rs | 8 ++++++ crates/xlsx/src/tests/roundtrip.rs | 7 ++++++ crates/xlsx/src/write.rs | 17 +++++++++++++ docs/file-format-parity.md | 4 ++- 12 files changed, 138 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index da06359b56..03db59417b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-23 · **Change:** minor (accounting negatives such as `$(1,234)` read as numbers; INDEX with one index on a 2-D reference is #REF! as in Excel; earlier: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (accounting negatives such as `$(1,234)` read as numbers; INDEX with one index on a 2-D reference is #REF! as in Excel; earlier: Page Setup paper sizes: JIS B4/B5/B6, the Japanese postcards and envelopes, and A6; long flat operator chains up to Excel's formula limit) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) | | 2026-10-23 | 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) | @@ -226,6 +227,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | Progress log: password to modify (#921) | | 2026-10-23 | minor | Progress log: accounting negatives in number text | | 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! | | 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) | diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index b3e7309e2d..7f6e9e3663 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -8,7 +8,7 @@ use crate::DocState; pub fn specs() -> Vec { vec![ cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook), - cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open), + cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook, {modifyPassword} for one with a password to modify (or {readOnly: true} to open it without; Save then asks for a new file), and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open), cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save), cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as), cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes), @@ -57,6 +57,19 @@ fn open(s: &mut Session, p: &Json) -> Result { }; let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted; let (mut wb, warnings) = crate::io::open_bytes_with(&name, &bytes, str_param(p, "password"), bool_param(p, "csvAsText").unwrap_or(false))?; + // A password to modify: the right one or a read-only open, or the workbook doesn't open. + let mut read_only = false; + if let Some(hash) = wb.write_reservation.as_ref().and_then(|r| r.password.as_ref()) { + read_only = bool_param(p, "readOnly").unwrap_or(false); + match str_param(p, "modifyPassword") { + _ if read_only => {} + None => return Err(EngineError::Other(format!("'{name}' {}", crate::io::MODIFY_PASSWORD_REQUIRED))), + Some(pw) if !hash.verify(pw).map_err(|e| bad("file.open", e))? => { + return Err(EngineError::Other(crate::io::WRONG_PASSWORD.into())); + } + Some(_) => {} + } + } wb.source_dir = str_param(p, "path").and_then(crate::io::source_dir); // What `CELL("filename")` reports (#1489). A workbook opened from bytes knows its name but // never a folder, so it reports `[name]Sheet` with none; an import reports the file it came @@ -76,7 +89,7 @@ fn open(s: &mut Session, p: &Json) -> Result { // An import has no save target: ordinary Save must ask for a new destination. Neither does a // workbook decrypted with its password, so Save never replaces the encrypted original with // an unprotected copy. - let path = str_param(p, "path").filter(|_| !imported && !encrypted).map(str::to_string); + let path = str_param(p, "path").filter(|_| !imported && !encrypted && !read_only).map(str::to_string); // Replace an untouched blank Book1 like Excel does. if s.documents().len() == 1 && s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty())) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index be47e0a670..6453cec7a3 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -41,6 +41,10 @@ impl FileKind { /// The error for an encrypted workbook opened without a password contains this. The interface /// asks for the password when it sees it; programmatic callers pass `password` instead. pub const PASSWORD_REQUIRED: &str = "is password-protected. Enter its password to open it."; +/// The error for a workbook with a password to modify, opened with neither that password +/// (`modifyPassword`) nor `readOnly`, contains this. The interface asks for the password or a +/// read-only open when it sees it. +pub const MODIFY_PASSWORD_REQUIRED: &str = "is reserved by its author. Enter the password to modify it, or open it read-only."; /// The error for a wrong password contains this. pub const WRONG_PASSWORD: &str = "The password is incorrect."; /// The first open warning of a workbook decrypted with its password. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f4c47bb624..0a5da6bd60 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4142,6 +4142,46 @@ fn encrypted_book(password: &str) -> Vec { gridcraft_xlsx::testing::encrypt_workbook(&xlsx, password) } +#[test] +fn a_password_to_modify_asks_for_it_or_a_read_only_open() { + const PW: &str = "synthetic-modify-pw"; + let mut src = s(); + src.execute("cell.set", json!({"cell": "A1", "input": "42"})).unwrap(); + src.doc_mut().unwrap().wb.write_reservation = Some(gridcraft_model::WriteReservation { + password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), + ..Default::default() + }); + let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap(); + let b64 = crate::io::base64_encode(&bytes); + let open = |s: &mut Session, extra: serde_json::Value| { + let mut p = json!({"name": "Reserved.xlsx", "base64": b64}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("file.open", p) + }; + let mut s = Session::new(); + let err = open(&mut s, json!({})).unwrap_err().to_string(); + assert!(err.contains(crate::io::MODIFY_PASSWORD_REQUIRED), "{err}"); + assert!(s.take_ui_requests().is_empty(), "programmatic calls never open dialogs"); + for wrong in ["not-it", ""] { + let err = open(&mut s, json!({"modifyPassword": wrong})).unwrap_err().to_string(); + assert!(err.contains(crate::io::WRONG_PASSWORD), "{err}"); + } + assert!(s.documents().is_empty()); + + // Read-only: opens, keeps the reservation, but has no file to save over. + open(&mut s, json!({"readOnly": true})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(42.0)); + assert!(s.doc().unwrap().wb.write_reservation.is_some()); + + // The password: opens, and the reservation survives a save. + let mut s = Session::new(); + open(&mut s, json!({"modifyPassword": PW})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(42.0)); + let saved = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap(); + let (back, _) = crate::io::open_bytes("book.xlsx", &saved).unwrap(); + assert!(back.write_reservation.and_then(|r| r.password).is_some_and(|h| h.verify(PW) == Ok(true))); +} + #[test] fn encrypted_workbooks_open_with_their_password() { const PW: &str = "synthetic-pw-5521"; diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 071de683c2..f731422a86 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -25,7 +25,9 @@ pub use style::{ Alignment, BorderLine, BorderStyle, Borders, Color, Fill, Font, HAlign, NumFmt, PatternType, Style, StyleId, StyleTable, Theme, Underline, VAlign, VertAlign, }; -pub use workbook::{CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook}; +pub use workbook::{ + CalcMode, CalcSettings, DefinedName, DocProps, PhoneticProps, PhoneticRun, PhoneticString, ShowObjects, Workbook, WriteReservation, +}; /// Font used for new workbooks. Only a name: renderers substitute an available open font /// (e.g. the metric-compatible Carlito) when it isn't installed. diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index 3b943d295b..e930961b61 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -154,6 +154,9 @@ pub struct Workbook { /// Password of the structure protection (XLSX `workbookProtection`), never the password. #[serde(default, skip_serializing_if = "Option::is_none")] pub structure_password: Option, + /// "Password to modify" (XLSX `fileSharing`): the file opens read-only unless it is given. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub write_reservation: Option, /// Custom fill lists (Options › Custom Lists) beyond the built-in ones. pub custom_lists: Vec>, /// Named cell styles (Cell Styles gallery): name → style. @@ -205,6 +208,15 @@ impl Default for Workbook { } } +/// The write-reservation of a file (XLSX `fileSharing`): who reserved it, whether it asks to open +/// read-only, and the hash of its password to modify, never the password. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct WriteReservation { + pub user_name: String, + pub read_only_recommended: bool, + pub password: Option, +} + impl Workbook { /// A new workbook with one sheet, "Sheet1". pub fn new() -> Workbook { @@ -220,6 +232,7 @@ impl Workbook { props: DocProps::default(), protected_structure: false, structure_password: None, + write_reservation: None, custom_lists: vec![], cell_styles: vec![], phonetics: vec![], diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e83db2fa1a..6419db68e8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -347,6 +347,22 @@ impl Dialog { // An empty password from the start, so OK on the untouched field says "incorrect" // rather than asking for the password again. let mut values = params.clone(); + // A workbook with a password to modify asks for that, or a read-only open. + if p("modify").as_bool().unwrap_or(false) { + values["modifyPassword"] = json!(""); + values["readOnly"] = json!(false); + return Dialog::form( + "openPassword", + "Password", + "file.open", + vec![ + Note(format!("'{file}' is reserved by its author. Enter the password to modify it, or open it read-only.")), + Password { key: "modifyPassword", label: "Password:" }, + Check { key: "readOnly", label: "Read Only" }, + ], + values, + ); + } values["password"] = json!(""); Dialog::form( "openPassword", @@ -1504,7 +1520,8 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { } // A wrong password: say so, clear the field and stay open for another try. Err(e) if d.name == "openPassword" => { - d.values.insert("password".into(), json!("")); + let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; + d.values.insert(field.into(), json!("")); app.message = Some((d.title.clone(), crate::clean_error(&e))); } Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 14c4423310..4ba19a8e29 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -838,6 +838,9 @@ impl SheetApp { Ok(r) => self.after_open(Some(path), &r), // A password-protected workbook: ask for the password; the dialog opens it. Err(e) if e.contains(gridcraft_engine::io::PASSWORD_REQUIRED) => self.open_dialog("openPassword", json!({"path": path})), + Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + self.open_dialog("openPassword", json!({"path": path, "modify": true})) + } Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))), } self.after_engine(); @@ -1253,6 +1256,10 @@ impl SheetApp { self.backstage = None; self.open_dialog("openPassword", json!({"name": name, "base64": b64})); } + Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + self.backstage = None; + self.open_dialog("openPassword", json!({"name": name, "base64": b64, "modify": true})); + } Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))), } self.after_engine(); diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 774567bf8e..8900b22fdd 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -246,6 +246,14 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { wb.protected_structure = p.flag("lockStructure", false); wb.structure_password = if wb.protected_structure { crate::sheet_read::read_password(p, "workbook") } else { None }; } + if let Some(f) = wb_xml.child("fileSharing") { + // The iterated hash has bare attribute names; the legacy one is `reservationPassword`. + wb.write_reservation = Some(gridcraft_model::WriteReservation { + user_name: f.attr("userName").unwrap_or("").to_string(), + read_only_recommended: f.flag("readOnlyRecommended", false), + password: crate::sheet_read::read_password(f, "").or_else(|| crate::sheet_read::read_password(f, "reservation")), + }); + } let active_tab = wb_xml.path(&["bookViews", "workbookView"]).and_then(|v| v.attr_u32("activeTab")).unwrap_or(0) as usize; // Sheets. `file_to_model[i]` maps the i-th to a model sheet index. diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 5b79438dbb..462cb8449a 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -23,6 +23,11 @@ fn sample() -> Workbook { wb.calc = CalcSettings { mode: CalcMode::Manual, iterative: true, max_iterations: 42, max_change: 0.5, precision_as_displayed: true }; wb.protected_structure = true; wb.structure_password = Some(gridcraft_model::PasswordHash::new_sha512("s3cret", b"0123456789abcdef")); + wb.write_reservation = Some(gridcraft_model::WriteReservation { + user_name: "Ann & ".into(), + read_only_recommended: true, + password: Some(gridcraft_model::PasswordHash::new_sha512("modify-me", b"fedcba9876543210")), + }); wb.props = DocProps { title: "T & ".into(), subject: "S".into(), @@ -495,6 +500,8 @@ fn full_roundtrip() { assert!(back.protected_structure); assert_eq!(back.structure_password, wb.structure_password); assert!(back.structure_password.as_ref().unwrap().verify("s3cret").unwrap()); + assert_eq!(back.write_reservation, wb.write_reservation); + assert!(back.write_reservation.as_ref().and_then(|r| r.password.as_ref()).unwrap().verify("modify-me").unwrap()); assert_eq!(back.props, wb.props); assert_eq!(back.theme, wb.theme); assert_eq!(back.names, wb.names); diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index cf208d6cda..1a83730602 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -345,6 +345,23 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); w.push_str(if file_version.is_empty() { "" } else { &file_version }); + if let Some(r) = &wb.write_reservation { + w.push_str(" { + let _ = write!(w, " reservationPassword=\"{h:04X}\""); + } + Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), + None => {} + } + w.push_str("/>"); + } w.push_str(" {} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cf567f8bd6..bfbc51c9f6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-21 · **Change:** minor (.xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (.xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -60,6 +60,7 @@ values) is still dropped. | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | | `.ods` OpenDocument Spreadsheet | R/W | **values only** (#100) | no | Sheets, values, dates, merges, repeated cells, cached formula results; no formulas, formatting, charts; encrypted ODS refused | `ods_tests.rs` | | Password-encrypted workbooks (Agile/Standard encryption) | R | **yes** (#11): asks for the password on open; Agile (AES-128/192/256, SHA-1/256/384/512) and Standard (AES, SHA-1) | no (opens with no save path; Save As writes it without the password) | Clean-room from [MS-OFFCRYPTO] on the CFB reader. RC4, Extensible and certificate-only encryption refused with a message. Data-integrity HMAC not checked | `crypto/tests.rs`, `encrypted_tests.rs` | +| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open has no save target | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` | | `.xlw` Excel 4.0 workbook, `.wk*`, `.dbf` | open only (some) | no | no | Rare | — | ## Text and data formats @@ -110,6 +111,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921) | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters | From ae50127952243b594ffd54de41ac3b3f4a1bf6ae Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:44:33 -0500 Subject: [PATCH 19/95] XLSX password to modify: fix dialog return type and test's Arc workbook edit --- crates/engine/src/tests.rs | 2 +- crates/ui-egui/src/dialogs.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0a5da6bd60..f160b8a2a5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4147,7 +4147,7 @@ fn a_password_to_modify_asks_for_it_or_a_read_only_open() { const PW: &str = "synthetic-modify-pw"; let mut src = s(); src.execute("cell.set", json!({"cell": "A1", "input": "42"})).unwrap(); - src.doc_mut().unwrap().wb.write_reservation = Some(gridcraft_model::WriteReservation { + std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation { password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), ..Default::default() }); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6419db68e8..3c57ad7fdb 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -351,7 +351,7 @@ impl Dialog { if p("modify").as_bool().unwrap_or(false) { values["modifyPassword"] = json!(""); values["readOnly"] = json!(false); - return Dialog::form( + return Some(Dialog::form( "openPassword", "Password", "file.open", @@ -361,7 +361,7 @@ impl Dialog { Check { key: "readOnly", label: "Read Only" }, ], values, - ); + )); } values["password"] = json!(""); Dialog::form( From 38fa0dc050ef1f684fc08292405e34adf43c7681 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:02:07 -0500 Subject: [PATCH 20/95] XLSX password to modify: address review comments - A read-only open refuses Save to the file it came from; Save As to another file still works, so the reservation holds. - Verify SHA-1 password-to-modify hashes, as XLSX fileSharing allows. - An encrypted and reserved workbook asks for the password to modify after its decryption password, keeping the decryption password. --- Cargo.lock | 1 + crates/engine/src/cmd/file.rs | 6 ++++++ crates/engine/src/lib.rs | 4 ++++ crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ crates/model/Cargo.toml | 1 + crates/model/src/password.rs | 16 +++++++++++++++- crates/ui-egui/src/dialogs.rs | 9 +++++++++ docs/file-format-parity.md | 4 ++-- 8 files changed, 63 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7f52031881..ecf7a9ba41 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1627,6 +1627,7 @@ dependencies = [ "gridcraft-formula", "serde", "serde_json", + "sha1", "sha2", "thiserror 2.0.21", ] diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 7f6e9e3663..bd454a9ad7 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -98,6 +98,9 @@ fn open(s: &mut Session, p: &Json) -> Result { } // Someone else may have made the file: its active content asks before it runs. let mut doc = DocState::new(wb, path, title, crate::Trust::FromFile); + if read_only { + doc.read_only_source = str_param(p, "path").map(str::to_string); + } if crate::io::FileKind::from_path(&name).is_none() && gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Xlsx { doc.content_kind = Some(crate::io::FileKind::Xlsx); } @@ -125,6 +128,9 @@ fn save(s: &mut Session, p: &Json) -> Result { return ok(); } }; + if s.active().and_then(|d| d.read_only_source.as_deref()) == Some(path.as_str()) { + return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file.")); + } // A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the // document keeps its file and its unsaved changes. if std::path::Path::new(&path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b4ab60f3a9..f6b90d605f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -189,6 +189,9 @@ pub struct DocState { /// The format `path`'s content was recognised as when its extension doesn't name one (an /// XLSX called `budget.dat`): Save writes it back in that format. pub content_kind: Option, + /// The file a read-only open came from (`readOnly` on a workbook with a password to modify). + /// Save never writes over it, so the reservation holds; Save As to another file still works. + pub read_only_source: Option, /// Whether the scripts stored in this workbook may run (`automate.runScript`). A workbook /// that arrives already carrying scripts (opened from a file) starts untrusted until the /// user trusts it in this session (`automate.trustScripts`); one with no scripts starts @@ -283,6 +286,7 @@ impl DocState { sheet_selections: vec![], unlocked_ranges: vec![], content_kind: None, + read_only_source: None, scripts_trusted, trust, } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f160b8a2a5..fecb11fee7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4182,6 +4182,31 @@ fn a_password_to_modify_asks_for_it_or_a_read_only_open() { assert!(back.write_reservation.and_then(|r| r.password).is_some_and(|h| h.verify(PW) == Ok(true))); } +#[test] +fn a_read_only_open_never_saves_over_its_reserved_file() { + const PW: &str = "synthetic-modify-pw"; + let dir = std::env::temp_dir().join(format!("gridcraft-read-only-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("reserved.xlsx").to_string_lossy().into_owned(); + let copy = dir.join("copy.xlsx").to_string_lossy().into_owned(); + let mut src = s(); + std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation { + password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), + ..Default::default() + }); + let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap(); + std::fs::write(&path, &bytes).unwrap(); + + let mut s = Session::new(); + s.execute("file.open", json!({"path": path, "readOnly": true})).unwrap(); + let err = s.execute("file.save", json!({"path": path})).unwrap_err().to_string(); + assert!(err.contains("read-only"), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); + s.execute("file.saveAs", json!({"path": copy})).unwrap(); + assert!(std::fs::metadata(©).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn encrypted_workbooks_open_with_their_password() { const PW: &str = "synthetic-pw-5521"; diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index 761cf0093c..02c66415ab 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] gridcraft-core = { workspace = true } +sha1 = { workspace = true } sha2 = { workspace = true } gridcraft-formula = { workspace = true } serde = { workspace = true } diff --git a/crates/model/src/password.rs b/crates/model/src/password.rs index 59b9aafbaa..994cf324ef 100644 --- a/crates/model/src/password.rs +++ b/crates/model/src/password.rs @@ -49,6 +49,7 @@ impl PasswordHash { return Err("the stored password hash is damaged".into()); }; let got = match algorithm.to_ascii_uppercase().replace('_', "-").as_str() { + "SHA-1" => iterated::(password, &salt, *spin_count), "SHA-512" => iterated::(password, &salt, *spin_count), "SHA-384" => iterated::(password, &salt, *spin_count), "SHA-256" => iterated::(password, &salt, *spin_count), @@ -114,6 +115,19 @@ mod tests { assert_eq!(legacy_hash(""), 0xCE4B); } + #[test] + fn sha1_iterated_hash_verifies_the_correct_password() { + // Known answer for "s3cret", salt "0123456789abcdef", spin count 10, computed outside this code. + let h = PasswordHash::Iterated { + algorithm: "SHA-1".into(), + hash: "b2+ArdbduWEP3TNb+4NZg6qjkEk=".into(), + salt: crate::b64::encode(b"0123456789abcdef"), + spin_count: 10, + }; + assert!(h.verify("s3cret").unwrap()); + assert!(!h.verify("s3cret ").unwrap()); + } + #[test] fn iterated_hash_verifies_and_refuses_what_it_cannot_check() { let h = PasswordHash::new_sha512("s3cret", b"0123456789abcdef"); @@ -123,7 +137,7 @@ mod tests { let PasswordHash::Iterated { hash, salt, .. } = h else { return }; let other = |algorithm: &str, spin_count| PasswordHash::Iterated { algorithm: algorithm.into(), hash: hash.clone(), salt: salt.clone(), spin_count }; - assert!(other("SHA-1", 10).verify("s3cret").is_err()); + assert!(!other("SHA-1", 10).verify("s3cret").unwrap()); assert!(other("MD5", 10).verify("s3cret").is_err()); assert!(other("SHA-512", MAX_SPIN_COUNT + 1).verify("s3cret").is_err()); assert!(!other("SHA-256", 2).verify("s3cret").unwrap()); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3c57ad7fdb..99a417692a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1518,6 +1518,15 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => { d.values.insert("askOverwrite".into(), json!(true)); } + // Encrypted and reserved: the password opened it, so the form turns to the password to + // modify. The decryption password stays in the values for the retry. + Err(e) if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + let mut params = Json::Object(d.values.clone()); + params["modify"] = json!(true); + if let Some(next) = Dialog::open(app, "openPassword", params) { + d = Dialog { back: d.back.take(), ..next }; + } + } // A wrong password: say so, clear the field and stay open for another try. Err(e) if d.name == "openPassword" => { let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bfbc51c9f6..667abc55da 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -60,7 +60,7 @@ values) is still dropped. | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | | `.ods` OpenDocument Spreadsheet | R/W | **values only** (#100) | no | Sheets, values, dates, merges, repeated cells, cached formula results; no formulas, formatting, charts; encrypted ODS refused | `ods_tests.rs` | | Password-encrypted workbooks (Agile/Standard encryption) | R | **yes** (#11): asks for the password on open; Agile (AES-128/192/256, SHA-1/256/384/512) and Standard (AES, SHA-1) | no (opens with no save path; Save As writes it without the password) | Clean-room from [MS-OFFCRYPTO] on the CFB reader. RC4, Extensible and certificate-only encryption refused with a message. Data-integrity HMAC not checked | `crypto/tests.rs`, `encrypted_tests.rs` | -| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open has no save target | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` | +| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open never saves over its file | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-1/256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` | | `.xlw` Excel 4.0 workbook, `.wk*`, `.dbf` | open only (some) | no | no | Rare | — | ## Text and data formats @@ -111,7 +111,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| -| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921) | +| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921); a read-only open refuses Save to its own file; SHA-1 modify hashes verify; an encrypted and reserved file asks for the modify password after its decryption password | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | | 2026-10-20 | minor | A workbook theme's major/minor per-script typefaces (``, also Hebr, Jpan and the rest) are read and written back in file order after ``; they were dropped before. A hostile file is held to 64 entries of 256 characters | From ce64da3286516119304e7f7057567b2adbec1591 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:35:28 -0500 Subject: [PATCH 21/95] XLSX password to modify: compare the reserved file by identity on Save; keep a legacy hash only beside a userName (#2508) --- crates/engine/src/cmd/file.rs | 10 +++++++++- crates/engine/src/tests.rs | 4 ++++ crates/xlsx/src/tests/roundtrip.rs | 12 ++++++++++++ crates/xlsx/src/write.rs | 4 +++- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e3c23dd033..4fde819f3d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -120,6 +120,14 @@ fn open(s: &mut Session, p: &Json) -> Result { ) } +/// Whether two paths name one file, whatever their spelling (`./book.xlsx`, a symlink). +fn same_file(a: &str, b: &str) -> bool { + match (std::fs::canonicalize(a), std::fs::canonicalize(b)) { + (Ok(x), Ok(y)) => x == y, + _ => a == b, + } +} + fn save(s: &mut Session, p: &Json) -> Result { let path = match str_param(p, "path").map(str::to_string).or_else(|| s.active().and_then(|d| d.path.clone())) { Some(p) => p, @@ -128,7 +136,7 @@ fn save(s: &mut Session, p: &Json) -> Result { return ok(); } }; - if s.active().and_then(|d| d.read_only_source.as_deref()) == Some(path.as_str()) { + if s.active().and_then(|d| d.read_only_source.as_deref()).is_some_and(|src| same_file(src, &path)) { return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file.")); } // A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 98acfddd07..39928c7f9e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4423,6 +4423,10 @@ fn a_read_only_open_never_saves_over_its_reserved_file() { let err = s.execute("file.save", json!({"path": path})).unwrap_err().to_string(); assert!(err.contains("read-only"), "{err}"); assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); + let dotted = dir.join(".").join("reserved.xlsx").to_string_lossy().into_owned(); + let err = s.execute("file.save", json!({"path": dotted})).unwrap_err().to_string(); + assert!(err.contains("read-only"), "the same file under another spelling: {err}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); s.execute("file.saveAs", json!({"path": copy})).unwrap(); assert!(std::fs::metadata(©).is_ok()); std::fs::remove_dir_all(&dir).ok(); diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index e90ff1781b..35c73d568b 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1491,3 +1491,15 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() { assert!(t.filter.is_empty(), "the criteria landed on the wrong table column: {:?}", t.filter); assert!(b.autofilter.is_none(), "a sheet filter inside a table would be invalid"); } + +#[test] +fn legacy_reservation_password_is_written_with_a_user_name() { + let mut wb = sample(); + wb.write_reservation = + Some(WriteReservation { user_name: String::new(), read_only_recommended: false, password: Some(PasswordHash::Legacy(0x83AF)) }); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert!(back.write_reservation.is_some_and(|r| r.password.is_none()), "no userName, so no reservationPassword"); + wb.write_reservation.as_mut().unwrap().user_name = "Ann".into(); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert_eq!(back.write_reservation.and_then(|r| r.password), Some(PasswordHash::Legacy(0x83AF))); +} diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index c3ba698f33..34fb2ed890 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -352,9 +352,11 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) let _ = write!(w, " userName=\"{}\"", esc_attr(&r.user_name)); } match &r.password { - Some(gridcraft_model::PasswordHash::Legacy(h)) => { + // Office needs a userName beside a legacy reservationPassword; without one the hash is left out. + Some(gridcraft_model::PasswordHash::Legacy(h)) if !r.user_name.is_empty() => { let _ = write!(w, " reservationPassword=\"{h:04X}\""); } + Some(gridcraft_model::PasswordHash::Legacy(_)) => {} Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), None => {} } From d5b23a5e791479bbc45e37f59f95d57759a92aed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 15:50:34 -0700 Subject: [PATCH 22/95] Charts: 100% Stacked Line, with or without markers, draws values as shares of each category's total Insert > Line or Area and the All Charts list offer 100% Stacked Line and 100% Stacked Line with Markers, and insert.chart and chart.set take them as type line with subtype stacked100 or stacked100Markers. Each series' line is drawn at the running sum of its share of the category's total and the shares before it, so when no value is negative, the last series reaches the top in every category with a nonzero total. When every series on the value axis is 100% stacked and no value is negative, the axis runs from 0% to 100%. The with-markers kind draws a marker at each point. An XLSX line chart with percentStacked grouping now opens as 100% stacked, with markers unless every series has the marker symbol none or the group turns markers off, and is saved back as percentStacked. It used to open as a stacked line and was saved as stacked. A 100% stacked line series in a combo chart is still saved as a standard line. --- ROADMAP.md | 1 + crates/chart/src/render.rs | 20 ++++--- crates/chart/src/tests.rs | 60 ++++++++++++++++++- crates/engine/src/cmd/insert.rs | 4 +- .../engine/tests/it/chart_line_stacked100.rs | 38 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/mcp/src/tools.rs | 2 +- crates/model/src/features.rs | 2 + crates/ui-egui/src/dialogs.rs | 4 +- crates/ui-egui/src/i18n/el.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 2 + crates/ui-egui/src/i18n/pt.rs | 2 + crates/ui-egui/src/i18n/ro.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/ribbon.rs | 2 + crates/ui-egui/tests/it/interaction.rs | 41 +++++++++++++ crates/xlsx/src/chart.rs | 33 ++++++---- .../src/tests/chart_line_percent_stacked.rs | 57 ++++++++++++++++++ crates/xlsx/src/tests/mod.rs | 1 + crates/xlsx/src/tests/roundtrip.rs | 2 + docs/chart-parity.md | 7 ++- 23 files changed, 264 insertions(+), 25 deletions(-) create mode 100644 crates/engine/tests/it/chart_line_stacked100.rs create mode 100644 crates/xlsx/src/tests/chart_line_percent_stacked.rs diff --git a/ROADMAP.md b/ROADMAP.md index c9e746bc5a..7798603348 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-25 | Charts: 100% Stacked Line and 100% Stacked Line with Markers (`insert.chart` `{type: "line", subtype: "stacked100"}` and `"stacked100Markers"`), drawn as each value's share of its category's total; XLSX `percentStacked` line charts open as 100% stacked instead of stacked | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | diff --git a/crates/chart/src/render.rs b/crates/chart/src/render.rs index 3257082bb7..b19098794e 100644 --- a/crates/chart/src/render.rs +++ b/crates/chart/src/render.rs @@ -165,8 +165,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa .clone() .map(|s| { let sw = match plot_kind(chart, s) { - ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, - ChartKind::LineMarkers => Swatch::LineMarker, + ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => { + Swatch::Line + } + ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker, ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, _ => Swatch::Box, }; @@ -866,6 +868,7 @@ enum Fam { Col100, Line, LineStack, + Line100, Area, AreaStack, Area100, @@ -878,6 +881,7 @@ fn family(k: ChartKind) -> Fam { ColumnStacked100 | BarStacked100 => Fam::Col100, Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line, LineStacked => Fam::LineStack, + LineStacked100 | LineStacked100Markers => Fam::Line100, Area => Fam::Area, AreaStacked => Fam::AreaStack, AreaStacked100 => Fam::Area100, @@ -887,14 +891,14 @@ fn family(k: ChartKind) -> Fam { /// Families stacked to 100%: each category's values are shares of its total. fn is_100(f: Fam) -> bool { - matches!(f, Fam::Col100 | Fam::Area100) + matches!(f, Fam::Col100 | Fam::Line100 | Fam::Area100) } fn is_col(f: Fam) -> bool { matches!(f, Fam::Col | Fam::ColStack | Fam::Col100) } fn is_line(f: Fam) -> bool { - matches!(f, Fam::Line | Fam::LineStack) + matches!(f, Fam::Line | Fam::LineStack | Fam::Line100) } fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) { @@ -907,7 +911,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta let any_primary = data.series.iter().any(|s| !s.secondary); let sec: Vec = data.series.iter().map(|s| s.secondary && any_primary && !horizontal).collect(); - // Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart). + // Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart). let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); for (i, s) in data.series.iter().enumerate() { let fam = fams.get(i).copied().unwrap_or(Fam::Col); @@ -938,7 +942,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta for (i, s) in data.series.iter().enumerate() { let fam = fams.get(i).copied().unwrap_or(Fam::Col); let a = sec.get(i).copied().unwrap_or(false); - let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100); + let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::Line100 | Fam::AreaStack | Fam::Area100); let key = (a, fam); let si = if stacked { match stacks.iter().position(|(k, _, _)| *k == key) { @@ -964,7 +968,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta }), (Some((_, pos, _)), _) => { let v = v.unwrap_or(0.0); - let v = if fam == Fam::Area100 { share(key, j, v) } else { v }; + let v = if is_100(fam) { share(key, j, v) } else { v }; pos.get_mut(j).map(|acc| { let base = *acc; *acc = clean(*acc + v); @@ -1150,7 +1154,7 @@ fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizonta let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot)); let k = kinds.get(i).copied().unwrap_or(ChartKind::Line); - if k == ChartKind::LineMarkers && cw >= 3.0 { + if matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers) && cw >= 3.0 { draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); } if labels_on { diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index 3f1a068a23..4fa70d4bfc 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -5,7 +5,7 @@ use gridcraft_model::{Anchor, Chart, ChartKind, Color, LegendPos, Series, Sparkl use crate::*; -const ALL_KINDS: [ChartKind; 26] = [ +const ALL_KINDS: [ChartKind; 28] = [ ChartKind::ColumnClustered, ChartKind::ColumnStacked, ChartKind::ColumnStacked100, @@ -15,6 +15,8 @@ const ALL_KINDS: [ChartKind; 26] = [ ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked, + ChartKind::LineStacked100, + ChartKind::LineStacked100Markers, ChartKind::Pie, ChartKind::Doughnut, ChartKind::Area, @@ -1137,6 +1139,62 @@ fn hundred_percent_stacked_areas_fill_each_category_to_its_total() { assert!(frac(top(south, 2)).abs() < 1e-3, "Q3: South reaches {}", frac(top(south, 2))); } +#[test] +fn hundred_percent_stacked_lines_end_each_category_at_its_total() { + let (north_color, south_color) = ([20, 96, 130, 255], [25, 107, 36, 255]); + for kind in [ChartKind::LineStacked100, ChartKind::LineStacked100Markers] { + let d = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["Q1", "Q2", "Q3", "Q4"].iter().map(|s| s.to_string()).collect(), + series: vec![series("North", &[10.0, 30.0, 0.0, 5.0], north_color, kind), series("South", &[30.0, 10.0, 0.0, 15.0], south_color, kind)], + }; + let mut c = chart(kind); + c.data_labels = false; + let p = render(&c, &d, 640.0, 400.0, &ApproxMeasure); + let t = texts(&p); + assert!(t.contains(&"100%") && t.contains(&"0%"), "{kind:?}: {t:?}"); + assert!(!t.contains(&"40"), "{kind:?}: {t:?}"); + // The value axis labels sit on their gridlines. + let label_y = |s: &str| { + p.iter() + .find_map(|p| match p { + Prim::Text { text, y, .. } if text == s => Some(*y), + _ => None, + }) + .unwrap_or(f32::NAN) + }; + let (y0, y100) = (label_y("0%"), label_y("100%")); + assert!(y0 > y100, "{kind:?}: {y0} {y100}"); + let frac = |y: f32| (y0 - y) / (y0 - y100); + let line = |color: Rgba| { + p.iter() + .find_map(|p| match p { + // The series line is 2.25 wide; its legend swatch is 2.0. + Prim::Line { pts, color: c, width, .. } if *c == color && *width > 2.1 => { + Some(pts.iter().map(|q| frac(q[1])).collect::>()) + } + _ => None, + }) + .unwrap_or_default() + }; + let (north, south) = (line(north_color), line(south_color)); + assert_eq!((north.len(), south.len()), (4, 4), "{kind:?}: {north:?} {south:?}"); + // A category whose total is zero stays on the baseline. + for (j, (n, s)) in [(0.25, 1.0), (0.75, 1.0), (0.0, 0.0), (0.25, 1.0)].into_iter().enumerate() { + assert!((north[j] - n).abs() < 1e-3 && (south[j] - s).abs() < 1e-3, "{kind:?} Q{}: {} {}", j + 1, north[j], south[j]); + } + // Point markers have a white outline; the legend's marker swatches have none. + let circles = |outlined: bool| { + p.iter() + .filter(|p| matches!(p, Prim::Circle { fill: Some(f), stroke, .. } if (*f == north_color || *f == south_color) && stroke.is_some() == outlined)) + .count() + }; + let with_markers = kind == ChartKind::LineStacked100Markers; + assert_eq!((circles(true), circles(false)), if with_markers { (8, 2) } else { (0, 0) }, "{kind:?}"); + } +} + #[test] fn two_level_categories_resolve_and_draw() { let years = ["2023", "", "", "2024", "", ""]; diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 9719bf451b..4eb4cbe0a0 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "Insert Chart", ["Insert", "Charts"], None, - "{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers, title?, at?: \"H2\", width?, height?}", + "{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}", has_doc, insert_chart ), @@ -578,6 +578,8 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind { ("bar", _) => ChartKind::BarClustered, ("line", "markers") => ChartKind::LineMarkers, ("line", "stacked") => ChartKind::LineStacked, + ("line", "stacked100") => ChartKind::LineStacked100, + ("line", "stacked100Markers") => ChartKind::LineStacked100Markers, ("line", _) => ChartKind::Line, ("pie", _) => ChartKind::Pie, ("doughnut", _) => ChartKind::Doughnut, diff --git a/crates/engine/tests/it/chart_line_stacked100.rs b/crates/engine/tests/it/chart_line_stacked100.rs new file mode 100644 index 0000000000..68c6357c71 --- /dev/null +++ b/crates/engine/tests/it/chart_line_stacked100.rs @@ -0,0 +1,38 @@ +//! The 100% stacked line charts: `insert.chart` and `chart.set` take type `line` with subtype +//! `stacked100` or `stacked100Markers`. + +use gridcraft_engine::Session; +use gridcraft_model::ChartKind; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", "10", "30"], ["Q2", "30", "10"]]})).unwrap(); + s +} + +fn kinds(s: &Session) -> Vec { + s.doc().unwrap().wb.sheet(0).unwrap().charts.iter().map(|c| c.kind).collect() +} + +#[test] +fn insert_chart_makes_hundred_percent_stacked_lines() { + let mut s = session(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100"})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100Markers"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100, ChartKind::LineStacked100Markers]); +} + +#[test] +fn chart_set_changes_a_chart_to_a_hundred_percent_stacked_line_and_back() { + let mut s = session(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked]); + s.execute("chart.set", json!({"type": "line", "subtype": "stacked100Markers"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]); + s.execute("chart.set", json!({"type": "line", "subtype": "stacked100"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100]); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 4c91e58ac4..4bb0f7c533 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -3,6 +3,7 @@ mod autofit_filter_buttons; mod cf_formula_validate; mod chart_area_stacked100; +mod chart_line_stacked100; mod chart_workbook_names; mod command_sequence_fuzz; mod cross_sheet_cut; diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index a6879b3ff1..36d8e531a4 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -260,7 +260,7 @@ pub fn tool_definitions() -> Vec { json!({ "range": string("Source data range including headers, e.g. \"A1:C6\""), "type": enumeration("Chart type", CHART_TYPES), - "subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers"]), + "subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers", "stacked100Markers"]), "title": string("Chart title"), "at": string("Top-left anchor cell (default: right of the data)"), }), diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index 00db5e8796..1807570bf5 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -406,6 +406,8 @@ pub enum ChartKind { Line, LineMarkers, LineStacked, + LineStacked100, + LineStacked100Markers, Pie, Doughnut, Area, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 46b9b0b2e1..a1b3ffbee5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2646,7 +2646,7 @@ fn paste_name(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &m } /// Every chart type the All Charts tab offers: `(type, subtype, label)` for `insert.chart`. -const ALL_CHARTS: [(&str, &str, &str); 21] = [ +const ALL_CHARTS: [(&str, &str, &str); 23] = [ ("column", "", "Clustered Column"), ("column", "stacked", "Stacked Column"), ("column", "stacked100", "100% Stacked Column"), @@ -2656,6 +2656,8 @@ const ALL_CHARTS: [(&str, &str, &str); 21] = [ ("line", "", "Line"), ("line", "markers", "Line with Markers"), ("line", "stacked", "Stacked Line"), + ("line", "stacked100", "100% Stacked Line"), + ("line", "stacked100Markers", "100% Stacked Line with Markers"), ("pie", "", "Pie"), ("doughnut", "", "Doughnut"), ("area", "", "Area"), diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index d826b1eb85..993eb296be 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -881,6 +881,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Γραμμή", "Line with Markers" => "Γραμμή με δείκτες", "Stacked Line" => "Σωρευμένες γραμμές", + "100% Stacked Line" => "Σωρευμένες γραμμές 100%", + "100% Stacked Line with Markers" => "Σωρευμένες γραμμές 100% με δείκτες", "Pie" => "Πίτα", "Doughnut" => "Δακτύλιος", "Area" => "Περιοχή", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 7f79b40762..c60be7fa1d 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -765,6 +765,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Linee", "Line with Markers" => "Linee con indicatori", "Stacked Line" => "Linee in pila", + "100% Stacked Line" => "Linee in pila 100%", + "100% Stacked Line with Markers" => "Linee in pila 100% con indicatori", "Pie" => "Torta", "Doughnut" => "Anello", "Area" => "Area", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ea48f80744..5c35354061 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -777,6 +777,8 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Line", "折れ線"), ("Line with Markers", "マーカー付き折れ線"), ("Stacked Line", "積み上げ折れ線"), + ("100% Stacked Line", "100% 積み上げ折れ線"), + ("100% Stacked Line with Markers", "マーカー付き 100% 積み上げ折れ線"), ("Pie", "円"), ("Doughnut", "ドーナツ"), ("Area", "面"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 1a229f90df..02fb97c0ff 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -759,6 +759,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Liniowy", "Line with Markers" => "Liniowy ze znacznikami", "Stacked Line" => "Liniowy skumulowany", + "100% Stacked Line" => "Liniowy 100% skumulowany", + "100% Stacked Line with Markers" => "Liniowy 100% skumulowany ze znacznikami", "Pie" => "Kołowy", "Doughnut" => "Pierścieniowy", "Area" => "Warstwowy", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index d72ee2460a..a14243e173 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -780,6 +780,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Linhas", "Line with Markers" => "Linhas com Marcadores", "Stacked Line" => "Linhas Empilhadas", + "100% Stacked Line" => "Linhas 100% Empilhadas", + "100% Stacked Line with Markers" => "Linhas 100% Empilhadas com Marcadores", "Pie" => "Pizza", "Doughnut" => "Rosca", "Area" => "Área", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index e715768484..b96899d972 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -765,6 +765,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Linie", "Line with Markers" => "Linii cu marcaje", "Stacked Line" => "Linii stivuite", + "100% Stacked Line" => "Linii 100% stivuite", + "100% Stacked Line with Markers" => "Linii 100% stivuite cu marcaje", "Pie" => "Radială", "Doughnut" => "Inel", "Area" => "Arie", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 8055f77fc5..6a504cc304 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -762,6 +762,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Line", "Line with Markers" => "Line with Markers", "Stacked Line" => "Stacked Line", + "100% Stacked Line" => "100% Stacked Line", + "100% Stacked Line with Markers" => "100% Stacked Line with Markers", "Pie" => "Pie", "Doughnut" => "Doughnut", "Area" => "Area", diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 0305884ed0..6bf1742c65 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1739,6 +1739,8 @@ fn insert(app: &mut SheetApp, ui: &mut Ui) { ("Line", "line", ""), ("Line with Markers", "line", "markers"), ("Stacked Line", "line", "stacked"), + ("100% Stacked Line", "line", "stacked100"), + ("100% Stacked Line with Markers", "line", "stacked100Markers"), ("Area", "area", ""), ("Stacked Area", "area", "stacked"), ("100% Stacked Area", "area", "stacked100"), diff --git a/crates/ui-egui/tests/it/interaction.rs b/crates/ui-egui/tests/it/interaction.rs index a70efa782a..e95602132d 100644 --- a/crates/ui-egui/tests/it/interaction.rs +++ b/crates/ui-egui/tests/it/interaction.rs @@ -407,6 +407,29 @@ fn insert_column_or_bar_menu_inserts_a_hundred_percent_stacked_bar() { assert_eq!(kinds, [gridcraft_engine::model::ChartKind::BarStacked100]); } +#[test] +fn insert_line_or_area_menu_inserts_hundred_percent_stacked_lines() { + // Insert › Line or Area (keytip N, N1) lists both 100% stacked line types. + let mut s = blank(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", 10, 30], ["Q2", 30, 10]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:C3"})).unwrap(); + let mut h = harness(s); + for label in ["100% Stacked Line", "100% Stacked Line with Markers"] { + key(&mut h, Key::F10, Modifiers::NONE); + for (k, t) in [(Key::N, "n"), (Key::N, "n"), (Key::Num1, "1")] { + h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.input_mut().events.push(Event::Text(t.into())); + h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + h.run_steps(2); + h.get_by_role_and_label(egui::accesskit::Role::Button, label).click(); + h.run_steps(2); + } + let kinds: Vec<_> = h.state().session.active().unwrap().wb.active().unwrap().charts.iter().map(|c| c.kind).collect(); + assert_eq!(kinds, [gridcraft_engine::model::ChartKind::LineStacked100, gridcraft_engine::model::ChartKind::LineStacked100Markers]); +} + #[test] /// Every main ribbon tab and dark mode render with accessibility checks. fn renders_every_ribbon_tab_without_panicking() { @@ -622,6 +645,24 @@ fn all_charts_inserts_a_hundred_percent_stacked_area() { assert_eq!(kinds, [gridcraft_engine::model::ChartKind::AreaStacked100]); } +#[test] +fn all_charts_inserts_a_hundred_percent_stacked_line_with_markers() { + let mut s = blank(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", 10, 30], ["Q2", 30, 10]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:C3"})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("recommendedCharts", json!({"tab": "All Charts"})); + h.run_steps(4); + assert!(h.query_by_label("100% Stacked Line").is_some(), "the list has 100% Stacked Line"); + h.get_by_label("100% Stacked Line with Markers").click(); + h.run_steps(2); + key(&mut h, Key::Enter, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().dialog.is_none()); + let kinds: Vec<_> = h.state().session.active().unwrap().wb.active().unwrap().charts.iter().map(|c| c.kind).collect(); + assert_eq!(kinds, [gridcraft_engine::model::ChartKind::LineStacked100Markers]); +} + #[test] fn recommended_charts_command_without_a_type_opens_the_dialog() { // #1399: the ribbon button and the NR keytip ran the command directly and inserted the first diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 37bcf91b01..a174a9dae1 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -29,12 +29,15 @@ fn group_kind(g: &El) -> Option { } } "lineChart" | "line3DChart" => { - if stacked || pct { - ChartKind::LineStacked - } else { - let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); - let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none")); - if !group_markers || (all_none && g.kids("ser").next().is_some()) { ChartKind::Line } else { ChartKind::LineMarkers } + let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); + let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none")); + let markers = group_markers && !(all_none && g.kids("ser").next().is_some()); + match (stacked, pct, markers) { + (true, _, _) => ChartKind::LineStacked, + (_, true, true) => ChartKind::LineStacked100Markers, + (_, true, false) => ChartKind::LineStacked100, + (_, _, true) => ChartKind::LineMarkers, + (_, _, false) => ChartKind::Line, } } "pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie, @@ -284,6 +287,7 @@ pub fn read_chart(root: &El) -> Option { enum G { Bar { bar: bool, grouping: &'static str }, Line { stacked: bool, markers: bool }, + Line100 { markers: bool }, Pie, Doughnut, Area { grouping: &'static str }, @@ -303,6 +307,8 @@ fn group_for(k: ChartKind) -> G { ChartKind::Line => G::Line { stacked: false, markers: false }, ChartKind::LineMarkers => G::Line { stacked: false, markers: true }, ChartKind::LineStacked => G::Line { stacked: true, markers: false }, + ChartKind::LineStacked100 => G::Line100 { markers: false }, + ChartKind::LineStacked100Markers => G::Line100 { markers: true }, ChartKind::Pie => G::Pie, ChartKind::Doughnut => G::Doughnut, ChartKind::Area => G::Area { grouping: "standard" }, @@ -533,7 +539,7 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String } } let color = s.color.as_ref().and_then(|c: &Color| srgb(c, &wb.theme)); - let line_like = matches!(g, G::Line { .. } | G::Radar | G::Scatter { lines: true }); + let line_like = matches!(g, G::Line { .. } | G::Line100 { .. } | G::Radar | G::Scatter { lines: true }); match (&color, line_like) { (Some(c), true) => { let _ = write!(x, "{c}"); @@ -552,7 +558,9 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String } match g { G::Bar { .. } => x.push_str(""), - G::Line { markers: false, .. } | G::Scatter { lines: true } | G::Stock => x.push_str(""), + G::Line { markers: false, .. } | G::Line100 { markers: false } | G::Scatter { lines: true } | G::Stock => { + x.push_str("") + } G::Bubble => x.push_str(""), _ => {} } @@ -581,7 +589,7 @@ fn series_xml(s: &Series, idx: usize, g: G, wb: &Workbook, si: usize) -> String x.push_str(&cat_data(c, &s.values, wb, si)); } x.push_str(&num_data("val", Some(&s.values), wb, si)); - if matches!(g, G::Line { .. }) { + if matches!(g, G::Line { .. } | G::Line100 { .. }) { let _ = write!(x, "", s.smooth as u8); } } @@ -670,6 +678,9 @@ fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb "{sers}{dl}{ax}", if stacked { "stacked" } else { "standard" } ), + G::Line100 { .. } => { + format!("{sers}{dl}{ax}") + } G::Pie => format!("{sers}{dl}"), G::Doughnut => { format!("{sers}{dl}") @@ -766,7 +777,9 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str if ch.kind == ChartKind::Combo { // Series without a kind of their own: the first is a column, the others lines (as drawn). let kind = |i: usize, x: &Series| x.kind.filter(|k| *k != ChartKind::Combo).or((i > 0).then_some(ChartKind::Line)); - let is_line = |k: Option| matches!(k.map(group_for), Some(G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. })); + let is_line = |k: Option| { + matches!(k.map(group_for), Some(G::Line { .. } | G::Line100 { .. } | G::Area { .. } | G::Radar | G::Scatter { .. })) + }; let bars: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && !is_line(kind(*i, x))).copied().collect(); let lines: Vec<(usize, &Series)> = all.iter().filter(|(i, x)| !x.secondary && is_line(kind(*i, x))).copied().collect(); let sec: Vec<(usize, &Series)> = all.iter().filter(|(_, x)| x.secondary).copied().collect(); diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs new file mode 100644 index 0000000000..87c16a4acf --- /dev/null +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -0,0 +1,57 @@ +//! Line chart groups by `grouping` and markers: `percentStacked` opens as a 100% stacked line. + +use gridcraft_model::{ChartKind, Workbook}; + +use crate::chart::{read_chart, write_chart}; +use crate::xml::parse; + +/// Reads a line chart whose one group has `grouping` and whose one series holds `marker`. +fn kind(grouping: &str, marker: &str) -> ChartKind { + let xml = format!( + "\ + {marker}\ + Data!$A$1:$A$5\ + \ + " + ); + let root = parse(xml.as_bytes()).unwrap(); + read_chart(&root).unwrap().kind +} + +const NO_MARKER: &str = ""; + +#[test] +fn percent_stacked_lines_open_as_hundred_percent_stacked() { + assert_eq!(kind("percentStacked", NO_MARKER), ChartKind::LineStacked100); + assert_eq!(kind("percentStacked", ""), ChartKind::LineStacked100Markers); +} + +#[test] +fn standard_and_stacked_lines_keep_their_kinds() { + assert_eq!(kind("standard", NO_MARKER), ChartKind::Line); + assert_eq!(kind("standard", ""), ChartKind::LineMarkers); + assert_eq!(kind("stacked", NO_MARKER), ChartKind::LineStacked); + assert_eq!(kind("stacked", ""), ChartKind::LineStacked); +} + +#[test] +fn a_hundred_percent_stacked_line_series_in_a_combo_chart_is_saved_as_a_line() { + let ser = + |i: usize| format!("Data!$A$1:$A$5"); + let xml = format!( + "\ + {}\ + {}\ + ", + ser(0), + ser(1) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.kind, ChartKind::Combo); + assert_eq!(ch.series.iter().map(|s| s.kind).collect::>(), [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers)]); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + let kinds: Vec> = again.series.iter().map(|s| s.kind).collect(); + assert_eq!(kinds.first(), Some(&Some(ChartKind::ColumnClustered)), "{saved}"); + assert!(kinds.get(1).is_some_and(|k| !matches!(k, Some(ChartKind::ColumnClustered))), "the line series stays out of the column group: {saved}"); +} diff --git a/crates/xlsx/src/tests/mod.rs b/crates/xlsx/src/tests/mod.rs index a7f6f1eb71..8e0b32ba8d 100644 --- a/crates/xlsx/src/tests/mod.rs +++ b/crates/xlsx/src/tests/mod.rs @@ -5,6 +5,7 @@ mod cellmetadata; mod chart_book_names; mod chart_bool_default; mod chart_combo_kinds; +mod chart_line_percent_stacked; mod chart_ref_offsets; mod csv_tests; mod encrypted_tests; diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 14fc784f9e..61d7cf8a82 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -425,6 +425,8 @@ fn sample() -> Workbook { ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked, + ChartKind::LineStacked100, + ChartKind::LineStacked100Markers, ChartKind::Pie, ChartKind::Doughnut, ChartKind::Area, diff --git a/docs/chart-parity.md b/docs/chart-parity.md index f18283f453..1921350d85 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -1,6 +1,6 @@ # Chart parity -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-24 · **Change:** minor (100% stacked area charts) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-25 · **Change:** minor (100% stacked line charts) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's chart types and chart elements against GridCraft. Part of [target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated). @@ -15,7 +15,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate |---|---|---|---| | Column | clustered, stacked, 100% stacked, 3-D clustered/stacked/100%, 3-D column | 3 of 7 | no 3-D | | Bar | clustered, stacked, 100%, 3-D ×3 | 3 of 6 | no 3-D | -| Line | line, stacked, 100% stacked, with markers ×3, 3-D line | 3 of 7 (line, with markers, stacked) | no 100% stacked; smoothed lines landed (#62) | +| Line | line, stacked, 100% stacked, with markers ×3, 3-D line | 5 of 7 (line, with markers, stacked, 100% stacked, 100% stacked with markers) | no stacked with markers, no 3-D; 100% stacked drawn as shares of each category's total and kept as `percentStacked` in XLSX; smoothed lines landed (#62) | | Pie | pie, 3-D pie, pie of pie, bar of pie, doughnut | 2 of 5 (pie, doughnut) | no exploded, pie of pie, bar of pie | | Area | area, stacked, 100%, 3-D ×3 | 3 of 6 | no 3-D; 100% stacked drawn as shares of each category's total and kept as `percentStacked` in XLSX | | X Y (scatter) | markers, smooth lines (±markers), straight lines (±markers) | 2 of 5 | no smooth lines | @@ -31,7 +31,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Waterfall, Funnel | 2 | 2 of 2 | | | Filled map | 1 | 0 | needs geographic boundary data (licensing decision) | | Combo | custom combinations, secondary axis | yes (line on secondary axis) | | -| **Total** | ~60 subtypes | **26 (~43%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | +| **Total** | ~60 subtypes | **28 (~47%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | ## Chart elements and formatting @@ -90,6 +90,7 @@ are (#1686). Such series get no `numCache`/`strCache` on save (#1690). | Date | Change | Summary | |---|---|---| +| 2026-10-25 | minor | 100% Stacked Line and 100% Stacked Line with Markers: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` | | 2026-10-24 | minor | 100% Stacked Area: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` | | 2026-10-18 | trivial | Stale notes: stock/combo, treemap/sunburst, box and waterfall kinds survive XLSX round-trip (PRs #158, #161) | | 2026-10-16 | trivial | Series that refer to defined names (`[0]!Name`, `Sheet!Name`) resolve instead of showing `#NAME?`, and are saved qualified, as Excel needs (#1686) | From 1e3fc9ee37f42f3f11f30a721b4be7f2a20dadf5 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 06:52:05 -0500 Subject: [PATCH 23/95] XLSX: keep a legacy modify password on save when the workbook has no user name --- crates/xlsx/src/tests/roundtrip.rs | 4 +++- crates/xlsx/src/write.rs | 12 +++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 35c73d568b..0f89297111 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1498,7 +1498,9 @@ fn legacy_reservation_password_is_written_with_a_user_name() { wb.write_reservation = Some(WriteReservation { user_name: String::new(), read_only_recommended: false, password: Some(PasswordHash::Legacy(0x83AF)) }); let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); - assert!(back.write_reservation.is_some_and(|r| r.password.is_none()), "no userName, so no reservationPassword"); + let r = back.write_reservation.expect("the reservation survived"); + assert_eq!(r.password, Some(PasswordHash::Legacy(0x83AF)), "a nameless legacy password is kept, under a placeholder name"); + assert!(!r.user_name.is_empty()); wb.write_reservation.as_mut().unwrap().user_name = "Ann".into(); let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); assert_eq!(back.write_reservation.and_then(|r| r.password), Some(PasswordHash::Legacy(0x83AF))); diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 761c731ced..814e6dd5e4 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -348,15 +348,17 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) if r.read_only_recommended { w.push_str(" readOnlyRecommended=\"1\""); } - if !r.user_name.is_empty() { - let _ = write!(w, " userName=\"{}\"", esc_attr(&r.user_name)); + // Office needs a userName beside a legacy reservationPassword, so a nameless one gets a placeholder + // rather than losing the password. + let legacy = matches!(r.password, Some(gridcraft_model::PasswordHash::Legacy(_))); + let name = if r.user_name.is_empty() && legacy { "GridCraft" } else { r.user_name.as_str() }; + if !name.is_empty() { + let _ = write!(w, " userName=\"{}\"", esc_attr(name)); } match &r.password { - // Office needs a userName beside a legacy reservationPassword; without one the hash is left out. - Some(gridcraft_model::PasswordHash::Legacy(h)) if !r.user_name.is_empty() => { + Some(gridcraft_model::PasswordHash::Legacy(h)) => { let _ = write!(w, " reservationPassword=\"{h:04X}\""); } - Some(gridcraft_model::PasswordHash::Legacy(_)) => {} Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), None => {} } From 1fe4f79db6cfaf718375fc5c923451f3fb13b45c Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:22:28 -0500 Subject: [PATCH 24/95] Excel open check: save workbooks with the CLI and open them in real Excel, a repair counts as a failure --- ROADMAP.md | 4 +- docs/gaps.md | 4 +- packaging/windows/excel-open-check/README.md | 13 +++ .../windows/excel-open-check/charts.jsonl | 12 ++ packaging/windows/excel-open-check/check.ps1 | 109 ++++++++++++++++++ .../conditional-formats.jsonl | 8 ++ .../windows/excel-open-check/pivots.jsonl | 4 + .../excel-open-check/protection-sheets.jsonl | 9 ++ .../excel-open-check/shapes-pictures.jsonl | 5 + .../excel-open-check/tables-names.jsonl | 13 +++ .../windows/excel-open-check/validation.jsonl | 8 ++ 11 files changed, 187 insertions(+), 2 deletions(-) create mode 100644 packaging/windows/excel-open-check/README.md create mode 100644 packaging/windows/excel-open-check/charts.jsonl create mode 100644 packaging/windows/excel-open-check/check.ps1 create mode 100644 packaging/windows/excel-open-check/conditional-formats.jsonl create mode 100644 packaging/windows/excel-open-check/pivots.jsonl create mode 100644 packaging/windows/excel-open-check/protection-sheets.jsonl create mode 100644 packaging/windows/excel-open-check/shapes-pictures.jsonl create mode 100644 packaging/windows/excel-open-check/tables-names.jsonl create mode 100644 packaging/windows/excel-open-check/validation.jsonl diff --git a/ROADMAP.md b/ROADMAP.md index 6b9b0fce78..817ef74dfe 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (Excel open check script; AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | @@ -242,6 +243,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Progress log: Excel open check | | 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column | | 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! | diff --git a/docs/gaps.md b/docs/gaps.md index 97299acda0..cd026b845f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (§8: PivotTable Enable show details; earlier: PivotTable Show Details) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (§1: repeatable Excel open check; §8: PivotTable Enable show details; earlier: PivotTable Show Details) · **Target:** Microsoft Excel (Microsoft 365) Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open @@ -22,6 +22,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- - **Evidence:** round-trip tests cover our own files only (`crates/xlsx/src/tests/`); PivotTable round-trip noted as "unverified in real Excel" since 10-07; #64 (dynamic-array flag) shows the class of bug. +- **Check:** `packaging/windows/excel-open-check/check.ps1` saves workbooks with `gridcraft-cli` and opens each result in real Excel through COM with `CorruptLoad` = normal load, so a repair is a failure. The 0.12.1 run (18 public synthetic fixtures + 7 feature scenarios: charts, pivots with pivot chart and slicer, CF, validation, tables and names, shapes and pictures, sheets and protection) gave 24 of 25 saved files opening cleanly; the 25th (`gc_legacy_to_array`) is not a repair but Excel taking over 200 s on legacy formulas saved as whole-column array formulas (#410, open PRs #417, #1367, #1660). Still open: a run over a large real-world corpus. - **Impact:** the main format; a repair prompt or silent loss destroys trust. - **Estimate:** 15–25 h, plus owner time in Excel. [file-format-parity.md](file-format-parity.md) @@ -183,6 +184,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | §1: `packaging/windows/excel-open-check` opens saved workbooks in real Excel and records pass or the exact failure; first run: 24 of 25 open cleanly | | 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) | diff --git a/packaging/windows/excel-open-check/README.md b/packaging/windows/excel-open-check/README.md new file mode 100644 index 0000000000..a927997bb1 --- /dev/null +++ b/packaging/windows/excel-open-check/README.md @@ -0,0 +1,13 @@ +# Excel open check + +Saves workbooks with `gridcraft-cli` and opens each result in real Excel (COM), recording per file `PASS` or the +exact failure. Windows with Excel only. See `check.ps1` for the options. + +```powershell +.\check.ps1 -Cli C:\gridcraft\gridcraft-cli.exe -Inputs C:\workbooks -Csv result.csv +``` + +Inputs are any `.xlsx`/`.xlsm` (the synthetic `gridcraft/` fixtures in a public fixtures repo are a good start); each +`*.jsonl` here is a feature scenario run on the Sales sample. Add a scenario by dropping in another `.jsonl` +(`gridcraft-cli run --script` format). Results: `Original` is the input opened in Excel (so a file Excel itself +rejects or loads slowly isn't blamed on GridCraft), `Saved` is the GridCraft-saved copy. diff --git a/packaging/windows/excel-open-check/charts.jsonl b/packaging/windows/excel-open-check/charts.jsonl new file mode 100644 index 0000000000..3746a83e9c --- /dev/null +++ b/packaging/windows/excel-open-check/charts.jsonl @@ -0,0 +1,12 @@ +# One chart of each common kind over the sales table +insert.chart={"range":"B4:F8","type":"bar","at":"K36"} +insert.chart={"range":"B4:F8","type":"line","subtype":"markers","at":"S3"} +insert.chart={"range":"B4:F8","type":"area","subtype":"stacked","at":"S19"} +insert.chart={"range":"C5:D8","type":"scatter","at":"S36"} +insert.chart={"range":"B4:F8","type":"radar","at":"AA3"} +insert.chart={"range":"B4:C8","type":"doughnut","at":"AA19"} +insert.chart={"range":"B4:C8","type":"waterfall","at":"AA36"} +insert.chart={"range":"B4:C8","type":"treemap","at":"AI3"} +insert.chart={"range":"B4:C8","type":"histogram","at":"AI19"} +insert.sparkline={"range":"C5:F5","location":"J5","type":"line"} +insert.sparkline={"range":"C6:F6","location":"J6","type":"column"} diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 new file mode 100644 index 0000000000..08dff4f162 --- /dev/null +++ b/packaging/windows/excel-open-check/check.ps1 @@ -0,0 +1,109 @@ +<# +Excel open check: saves workbooks with GridCraft, opens each result in real Excel (COM) and records per +file whether Excel loads it as it is or has to repair it (docs/file-format-parity.md, "Excel open check"). + + check.ps1 -Cli C:\gridcraft\gridcraft-cli.exe [-Inputs C:\workbooks] [-Out C:\out] [-Csv result.csv] + [-TimeoutSec 120] + +Files saved: + - every .xlsx / .xlsm in -Inputs, opened and saved with `gridcraft-cli run --in --out` (the original + is opened in Excel too, so a file Excel itself dislikes or loads slowly is told apart from a + GridCraft regression); + - every *.jsonl scenario next to this script (one feature each), run on the Sales sample. + +Each file is opened read-only with CorruptLoad = xlNormalLoad (0), so a part Excel would repair is a +failure instead of a silent fix, with DisplayAlerts off and macros disabled so nothing waits on a prompt. +Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and +Excel started by this script is stopped. Nothing is written next to the inputs; Excel processes that were +already running are never touched. Exit code 1 when any saved file is not PASS. +#> +param( + [Parameter(Mandatory = $true)][string]$Cli, + [string]$Inputs, + [string]$Out = (Join-Path ([IO.Path]::GetTempPath()) 'gridcraft-excel-open-check'), + [string]$Csv, + [int]$TimeoutSec = 120 +) +$ErrorActionPreference = 'Stop' + +# Excel processes already running are the person's own work: only ones started after this point are ever killed. +$before = @(Get-Process EXCEL -ErrorAction SilentlyContinue | ForEach-Object Id) +function Stop-Excel { + Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id } | Stop-Process -Force -ErrorAction SilentlyContinue +} + +# Runs in a child PowerShell so a hang can be killed after $TimeoutSec without taking this script with it. +$probe = { + param($path) + $x = $null + try { + $x = New-Object -ComObject Excel.Application + $x.Visible = $false + $x.DisplayAlerts = $false + $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: never run macros + # Named arguments: PowerShell can't skip the optional ones in between positionally. + $wb = [System.__ComObject].InvokeMember('Open', [Reflection.BindingFlags]::InvokeMethod, $null, $x.Workbooks, + @($path, 0, $true, 0), $null, $null, @('Filename', 'UpdateLinks', 'ReadOnly', 'CorruptLoad')) + $sheets = $wb.Worksheets.Count + $wb.Chartsheets.Count + $wb.Close($false) + "PASS`t$sheets sheets" + } catch { + "FAIL`t" + ($_.Exception.Message -replace '\s+', ' ') + } finally { + if ($x) { try { $x.Quit() } catch {} } + } +} + +function Test-InExcel([string]$path) { + $clock = [Diagnostics.Stopwatch]::StartNew() + $job = Start-Job -ScriptBlock $probe -ArgumentList $path + if (Wait-Job $job -Timeout $TimeoutSec) { + $out = (Receive-Job $job) -join ' ' + if (-not $out) { $out = "CRASH`tno result (Excel died)" } + } else { + Stop-Job $job + $out = "TIMEOUT`tno answer in $TimeoutSec s" + } + Remove-Job $job -Force + # Next file only once this Excel has exited, else its first call can get RPC_E_SERVERCALL_RETRYLATER. + $deadline = (Get-Date).AddSeconds(15) + while ((Get-Date) -lt $deadline -and @(Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id }).Count) { Start-Sleep -Milliseconds 200 } + Stop-Excel + $state, $detail = $out -split "`t", 2 + [pscustomobject]@{ State = $state; Seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); Detail = $detail } +} + +$saved = Join-Path $Out 'saved' +Remove-Item $saved -Recurse -Force -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Path $saved -Force | Out-Null + +# (name, original or $null, saved) per file +$work = @() +if ($Inputs) { + foreach ($f in Get-ChildItem -Path $Inputs -File | Where-Object { $_.Extension -in '.xlsx', '.xlsm' } | Sort-Object Name) { + $work += , @($f.Name, $f.FullName, (Join-Path $saved $f.Name), @('run', '--in', $f.FullName, '--quiet')) + } +} +foreach ($s in Get-ChildItem -Path $PSScriptRoot -Filter *.jsonl | Sort-Object Name) { + $work += , @("scenario:$($s.BaseName)", $null, (Join-Path $saved "$($s.BaseName).xlsx"), @('run', '--sample', 'sales', '--script', $s.FullName, '--quiet')) +} + +$rows = @() +foreach ($w in $work) { + $name, $orig, $dest, $cliArgs = $w + # The CLI reports on stderr, which Stop would turn into an exception. + $ErrorActionPreference = 'Continue' + & $Cli @cliArgs --out $dest *> $null + $ErrorActionPreference = 'Stop' + $base = if ($orig) { (Test-InExcel $orig) } else { $null } + $r = if (Test-Path $dest) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $LASTEXITCODE" } } + $rows += [pscustomobject]@{ + File = $name; Original = if ($base) { $base.State } else { '-' }; Saved = $r.State + Seconds = $r.Seconds; Detail = $r.Detail + } +} +$rows | Format-Table -AutoSize -Wrap | Out-String -Width 220 | Write-Output +if ($Csv) { $rows | Export-Csv -NoTypeInformation -Path $Csv } +$bad = @($rows | Where-Object Saved -ne 'PASS').Count +"{0} of {1} saved files pass" -f ($rows.Count - $bad), $rows.Count +if ($bad) { exit 1 } diff --git a/packaging/windows/excel-open-check/conditional-formats.jsonl b/packaging/windows/excel-open-check/conditional-formats.jsonl new file mode 100644 index 0000000000..ebfb544fa9 --- /dev/null +++ b/packaging/windows/excel-open-check/conditional-formats.jsonl @@ -0,0 +1,8 @@ +# Colour scale, data bar, icon set, top 10, formula and text rules +home.conditionalFormat={"range":"C5:F8","rule":{"type":"colorScale"}} +home.conditionalFormat={"range":"C5:C8","rule":{"type":"dataBar"}} +home.conditionalFormat={"range":"D5:D8","rule":{"type":"iconSet"}} +home.conditionalFormat={"range":"E5:E8","rule":{"type":"top10","rank":2}} +home.conditionalFormat={"range":"F5:F8","rule":{"type":"cellIs","operator":"greaterThan","value":"60000","preset":"lightRedFill"}} +home.conditionalFormat={"range":"B5:B8","rule":{"type":"containsText","text":"th","preset":"yellowFill"}} +home.conditionalFormat={"range":"C5:F8","rule":{"type":"expression","formula":"=C5>AVERAGE($C$5:$F$8)","preset":"greenFill"}} diff --git a/packaging/windows/excel-open-check/pivots.jsonl b/packaging/windows/excel-open-check/pivots.jsonl new file mode 100644 index 0000000000..23315f9e8b --- /dev/null +++ b/packaging/windows/excel-open-check/pivots.jsonl @@ -0,0 +1,4 @@ +# PivotTable on the sales table, a pivot chart, a table slicer +insert.pivotTable={"source":"Sales","destination":"Sales!K40","rows":["Region"],"values":[{"field":"Q1","func":"sum"}]} +insert.pivotChart={"pivot":"Sales!K42","type":"column","at":"S50"} +insert.slicer={"table":"Sales","column":"Region","at":"AA50"} diff --git a/packaging/windows/excel-open-check/protection-sheets.jsonl b/packaging/windows/excel-open-check/protection-sheets.jsonl new file mode 100644 index 0000000000..f05bd57ce4 --- /dev/null +++ b/packaging/windows/excel-open-check/protection-sheets.jsonl @@ -0,0 +1,9 @@ +# Extra sheets (renamed, coloured, hidden), grouping and a protected sheet +home.insertSheet={} +sheet.rename={"name":"Second"} +sheet.tabColor={"color":"#FF0000"} +cell.set={"cell":"A1","input":"=Sales!B5&\" \"&Sales!C5"} +home.insertSheet={} +sheet.hide={} +sheet.activate={"sheet":"Sales"} +review.protectSheet={"formatCells":true} diff --git a/packaging/windows/excel-open-check/shapes-pictures.jsonl b/packaging/windows/excel-open-check/shapes-pictures.jsonl new file mode 100644 index 0000000000..ecfcfbbaef --- /dev/null +++ b/packaging/windows/excel-open-check/shapes-pictures.jsonl @@ -0,0 +1,5 @@ +# Shapes with text and a picture from base64 (a 1x1 PNG) +insert.shape={"kind":"rectangle","at":"K30","width":120,"height":40,"text":"Box","fill":"#FFC000"} +insert.shape={"kind":"ellipse","at":"O30","width":80,"height":40} +insert.shape={"kind":"arrow","at":"K33","width":80,"height":30} +insert.picture={"base64":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==","mime":"image/png","at":"B20","width":60,"height":60,"alt":"dot"} diff --git a/packaging/windows/excel-open-check/tables-names.jsonl b/packaging/windows/excel-open-check/tables-names.jsonl new file mode 100644 index 0000000000..98f07d0949 --- /dev/null +++ b/packaging/windows/excel-open-check/tables-names.jsonl @@ -0,0 +1,13 @@ +# Table style and total row, defined names, merged cells, frozen panes, hyperlink-free cell notes +selection.set={"cell":"C5"} +table.totalRow={} +table.style={"style":"TableStyleLight9"} +formulas.defineName={"name":"NorthQ1","refersTo":"=Sales!$C$5"} +formulas.defineName={"name":"AllRegions","refersTo":"=Sales!$B$5:$B$8"} +formulas.defineName={"name":"Rate","refersTo":"=0.2","comment":"tax rate"} +cell.set={"cell":"K14","input":"=SUM(AllRegions)"} +cell.set={"cell":"K15","input":"=NorthQ1*Rate"} +home.mergeCells={"range":"K16:M16"} +view.freezePanes={"cell":"C5"} +review.newNote={"cell":"C5","text":"checked"} +review.newComment={"cell":"D5","text":"threaded"} diff --git a/packaging/windows/excel-open-check/validation.jsonl b/packaging/windows/excel-open-check/validation.jsonl new file mode 100644 index 0000000000..cd7e2efa09 --- /dev/null +++ b/packaging/windows/excel-open-check/validation.jsonl @@ -0,0 +1,8 @@ +# One rule of each kind +data.validation={"range":"K2:K5","type":"list","formula1":"North,South,East,West"} +data.validation={"range":"K6:K8","type":"whole","operator":"between","formula1":"1","formula2":"100","inputTitle":"Count","inputMessage":"1 to 100","errorStyle":"warning"} +data.validation={"range":"L2:L5","type":"decimal","operator":"greaterThan","formula1":"0"} +data.validation={"range":"L6:L8","type":"date","operator":"greaterOrEqual","formula1":"2026-01-01"} +data.validation={"range":"M2:M5","type":"textLength","operator":"lessOrEqual","formula1":"10"} +data.validation={"range":"M6:M8","type":"custom","formula1":"=ISNUMBER(M6)"} +data.validation={"range":"N2:N5","type":"list","formula1":"=$B$5:$B$8"} From e3fa42607fd2b27caafafc048c5b0317c9f0add8 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:31:02 -0500 Subject: [PATCH 25/95] XIRR and XNPV: match Excel for blank first rows, blank dates, text values and a zero first flow --- crates/functions/src/financial.rs | 61 ++++++++++++++++++++++++++----- docs/function-parity.md | 6 ++- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 3a41159819..ba7a0027e0 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -271,20 +271,27 @@ fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec, Vec } let mut v = Vec::with_capacity(va.data.len()); let mut d = Vec::with_capacity(da.data.len()); - for (x, y) in va.data.iter().zip(da.data.iter()) { + for (i, (x, y)) in va.data.iter().zip(da.data.iter()).enumerate() { + // Excel (XNPV): a blank or text value or a blank date is #NUM!, except in the first row, + // where it is #VALUE!. + let strict_err = if i == 0 { CellError::Value } else { CellError::Num }; let value = match x { Value::Number(n) => *n, Value::Empty if lenient => 0.0, - Value::Empty => return Err(CellError::Num), + Value::Empty => return Err(strict_err), Value::Error(e) => return Err(*e), - _ => return Err(CellError::Value), + _ if lenient => return Err(CellError::Value), + _ => return Err(strict_err), }; match y { Value::Number(n) => d.push(n.trunc()), Value::Error(e) => return Err(*e), Value::Text(_) => d.push(y.to_number()?.trunc()), - Value::Empty if lenient && value == 0.0 => continue, - Value::Empty if lenient || value == 0.0 => return Err(CellError::Num), + Value::Empty if !lenient => return Err(strict_err), + // XIRR skips a blank date next to a 0 flow and reads one in the first row as day 0. + Value::Empty if value == 0.0 => continue, + Value::Empty if i == 0 => d.push(0.0), + Value::Empty => return Err(CellError::Num), _ => return Err(CellError::Value), } v.push(value); @@ -455,6 +462,22 @@ fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } + if v.first() == Some(&0.0) { + // Excel with a 0 (or blank) first flow: the residual scale is 0, so the search just + // halves the guess towards 0 until the step is under the tolerance; a negative guess is #NUM!. + if guess < 0.0 { + return Err(CellError::Num); + } + let mut x = if guess == 0.0 { 1e-5 } else { guess }; + // Bounded: a huge guess halves to the tolerance within about 1100 steps. + for _ in 0..1100 { + if x / 2.0 < XirrSolver::tol(x / 2.0) { + break; + } + x /= 2.0; + } + return num_val(x / 2.0); + } let d0 = d.first().copied().unwrap_or(0.0); let first = v.iter().copied().find(|x| *x != 0.0).unwrap_or(0.0); let mut solver = XirrSolver { values: &v, first, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; @@ -2031,9 +2054,16 @@ mod tests { xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23); xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34); xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5); - // A leading zero cash flow adds nothing, so the root is the one without it (10%). The - // exact Excel answer for this input is unobserved, so only the root is checked. - assert!(matches!(xirr_of(&[0.0, -100.0, 110.0], &[b, y1, y2], None), Value::Number(r) if (r - 0.1).abs() < 1e-7)); + // A leading zero cash flow scales the residual to 0: Excel halves the guess to a tiny + // number whatever the flows (observed), and a negative guess is #NUM!. + let z = [0.0, -100.0, 110.0]; + let zd = [b, y1, y2]; + xirr_is(&z, &zd, None, 2.980_232_238_769_531_4e-9); + xirr_is(&z, &zd, Some(0.2), 2.980_232_238_769_531_4e-9); + xirr_is(&z, &zd, Some(0.0), 4.882_812_5e-9); + xirr_is(&z, &zd, Some(5.0), 4.656_612_873_077_392_6e-9); + xirr_is(&[0.0, -100.0, 50.0], &zd, None, 2.980_232_238_769_531_4e-9); + is_err(xirr_of(&z, &zd, Some(-0.5)), CellError::Num); // Dates before the first are allowed (time runs from the first date); in the second // case the search finds no sign change. xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6); @@ -2121,7 +2151,20 @@ mod tests { is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates)]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num); - is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Value); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(tv("-"))), rf(dates.clone())]), CellError::Num); + // In the first row a blank value or date is #VALUE! for XNPV; XIRR reads a blank date there as day 0. + let first_row = |value: Value, date: Value| { + let cells = |x: Value, rest: [f64; 4]| arr(std::iter::once(vec![x]).chain(rest.iter().map(|y| vec![nv(*y)])).collect()); + (rf(cells(value, [2750.0, 4250.0, 3250.0, 500.0])), rf(cells(date, [39508.0, 39751.0, 39859.0, 39904.0]))) + }; + let (v0, d0) = first_row(Value::Empty, nv(39448.0)); + is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value); + let (v0, d0) = first_row(nv(0.0), Value::Empty); + is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value); + let (v0, d0) = first_row(nv(-10000.0), Value::Empty); + is_err(ev("XNPV", vec![n(0.09), v0.clone(), d0.clone()]), CellError::Value); + close_tol(ev("XIRR", vec![v0, d0]), 0.000_664_654_374_122_619_6, 1e-7); } #[test] diff --git a/docs/function-parity.md b/docs/function-parity.md index 6f8147058f..cad64cd1e1 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -107,7 +107,9 @@ reconstructed from observation: a sign-only search that brackets the root from t (doubling, halving towards 0, or stepping halfway to -100%) and bisects until half the bracket is under 1e-8 x (|rate| + 0.5) and XNPV is under 2e-8 x the first value, so its answer is the same midpoint as Excel's, about 1e-8 from the exact root, bit for bit in 888 of 910 synthetic cases -with an answer (97.7% agreement on 1,283 cases including `#NUM!`). Known differences: flows with +with an answer (97.7% agreement on 1,283 cases including `#NUM!`). A 0 or blank first flow +gives the tiny value Excel gives (the guess halved until the step is under the tolerance: about +2.98e-9 for the default guess, `#NUM!` for a negative guess). Known differences: flows with several sign changes where Excel returns about 3e-9 (a halving that reached 0), or `#NUM!` for two roots close to the guess. IRR uses Newton on the discount factor 1/(1+rate), at most 100 steps, stopping at a step under 1e-8; Excel's last digits differ by about 1e-12 (its exact iteration is @@ -142,7 +144,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | 2026-10-17 | minor | 15-significant-digit comparison moved from missing to done (#57), and the resolved caveats on the 3-D reference, dynamic-array and legacy-array rows cleared (#140, #133, #139, #156) | | 2026-10-16 | minor | FORECAST.ETS gap interpolation uses a forward-only known-point scan instead of rescanning each gap for every missing value; numerical behavior and missing-point limits are preserved (#1042) | | 2026-10-15 | minor | XIRR follows Excel's bisection (answers bit for bit, about 1e-8 from the exact root; dates before the first allowed; guess <= -1 is `#NUM!`); IRR uses Newton on the discount factor (`IRR` of -100, 19 zeros, 1E-5 is `#NUM!` like Excel; guess <= -1 is `#VALUE!`) | -| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` or `#VALUE!` Excel gives for blank values and dates (observed on synthetic workbooks) | +| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` Excel gives for a blank or text value or a blank date after the first row, and `#VALUE!` for a blank value or date in the first row (observed on synthetic workbooks); XIRR with a 0 or blank first flow returns Excel's tiny value (about 2.98e-9), and a first nonzero flow with a blank date reads the date as day 0 | | 2026-10-15 | minor | Iterative calculation: Maximum Iterations and Maximum Change are set in File › Options › Formulas (dropped "no Options dialog yet") | | 2026-10-15 | minor | MEDIAN and AGGREGATE median use an overflow-safe midpoint (#1579); regressions cover finite extremes, tiny values and dependent recalculation | | 2026-10-15 | minor | ADDRESS quotes a sheet name the way Excel does: names that read as an A1 cell (`A1`) or an R1C1 reference (`R1C1`, `RC`) and names starting with `.` get quotes; `TRUE` / `FALSE` stay bare (#1458) | From 2f86b52706f938f3f3d40f2b5419436958b10635 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:33:58 -0500 Subject: [PATCH 26/95] XNPV test: clone the dates range --- crates/functions/src/financial.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index ba7a0027e0..cc3716f03a 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -2148,7 +2148,7 @@ mod tests { is_err(ev("XIRR", vec![rf(flows(tv("-"))), rf(dates.clone())]), CellError::Value); // XNPV is strict: a blank value is #NUM! where 0 is a number. close_tol(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(dates.clone())]), -382.66, 1e-2); - is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates)]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Num); From cfcde5bfbd665ea22bf36c51e4130ef26a9a7409 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:35:56 -0500 Subject: [PATCH 27/95] Excel open check: stop only the Excel instance a probe started, found by its window's process id --- packaging/windows/excel-open-check/check.ps1 | 37 ++++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 08dff4f162..68c9b1afcd 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -14,8 +14,8 @@ Files saved: Each file is opened read-only with CorruptLoad = xlNormalLoad (0), so a part Excel would repair is a failure instead of a silent fix, with DisplayAlerts off and macros disabled so nothing waits on a prompt. Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and -Excel started by this script is stopped. Nothing is written next to the inputs; Excel processes that were -already running are never touched. Exit code 1 when any saved file is not PASS. +that instance (found by its window's process id) is stopped. Nothing is written next to the inputs; any other +Excel, such as one the person starts meanwhile, is never touched. Exit code 1 when any saved file is not PASS. #> param( [Parameter(Mandatory = $true)][string]$Cli, @@ -26,12 +26,6 @@ param( ) $ErrorActionPreference = 'Stop' -# Excel processes already running are the person's own work: only ones started after this point are ever killed. -$before = @(Get-Process EXCEL -ErrorAction SilentlyContinue | ForEach-Object Id) -function Stop-Excel { - Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id } | Stop-Process -Force -ErrorAction SilentlyContinue -} - # Runs in a child PowerShell so a hang can be killed after $TimeoutSec without taking this script with it. $probe = { param($path) @@ -39,6 +33,11 @@ $probe = { try { $x = New-Object -ComObject Excel.Application $x.Visible = $false + # Report this instance's process id so the caller can stop exactly it and nothing else. + Add-Type -Namespace Win -Name U -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);' + $xlPid = [uint32]0 + [void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid) + "PID`t$xlPid" $x.DisplayAlerts = $false $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: never run macros # Named arguments: PowerShell can't skip the optional ones in between positionally. @@ -57,18 +56,18 @@ $probe = { function Test-InExcel([string]$path) { $clock = [Diagnostics.Stopwatch]::StartNew() $job = Start-Job -ScriptBlock $probe -ArgumentList $path - if (Wait-Job $job -Timeout $TimeoutSec) { - $out = (Receive-Job $job) -join ' ' - if (-not $out) { $out = "CRASH`tno result (Excel died)" } - } else { - Stop-Job $job - $out = "TIMEOUT`tno answer in $TimeoutSec s" - } + $done = Wait-Job $job -Timeout $TimeoutSec + $lines = @(Receive-Job $job -Keep) + if (-not $done) { Stop-Job $job } Remove-Job $job -Force - # Next file only once this Excel has exited, else its first call can get RPC_E_SERVERCALL_RETRYLATER. - $deadline = (Get-Date).AddSeconds(15) - while ((Get-Date) -lt $deadline -and @(Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id }).Count) { Start-Sleep -Milliseconds 200 } - Stop-Excel + $xlPid = ($lines | Where-Object { $_ -like "PID`t*" } | Select-Object -First 1) -replace '^PID\t', '' + $out = $lines | Where-Object { $_ -notlike "PID`t*" } | Select-Object -Last 1 + if (-not $done) { $out = "TIMEOUT`tno answer in $TimeoutSec s" } elseif (-not $out) { $out = "CRASH`tno result (Excel died)" } + if ($xlPid) { + # A clean Quit lets Excel exit by itself; give it a moment, then stop only this instance. + Wait-Process -Id ([int]$xlPid) -Timeout 15 -ErrorAction SilentlyContinue + Stop-Process -Id ([int]$xlPid) -Force -ErrorAction SilentlyContinue + } $state, $detail = $out -split "`t", 2 [pscustomobject]@{ State = $state; Seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); Detail = $detail } } From 9bd604aa1201f3deaa7a9c1aebd7ad0645870a71 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:45:38 -0500 Subject: [PATCH 28/95] Correct the dated_flows doc comment for blank cells --- crates/functions/src/financial.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index cc3716f03a..9c54775211 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -261,8 +261,9 @@ fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { /// /// Blank cells follow what Excel returns (observed on synthetic workbooks). With `lenient` (XIRR) /// a blank value counts as 0 and a blank date is ignored when its value is blank or 0; a nonzero -/// value without a date is `#NUM!`. XNPV is strict: a blank value is `#NUM!`, and so is a blank -/// date next to a blank or 0 value (`#VALUE!` next to a nonzero one). +/// value without a date is `#NUM!`, except in the first row, where the date is read as day 0. +/// XNPV is strict: a blank (or text) value or a blank date is `#NUM!`, except in the first row, +/// where it is `#VALUE!`. fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec, Vec)> { let va = as_array(values); let da = as_array(dates); From 260b84d09352287812930ebae6906ebd78c5ee76 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:47:06 -0500 Subject: [PATCH 29/95] Excel open check: a failed probe job is a CRASH, not an error that ends the run --- packaging/windows/excel-open-check/check.ps1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 68c9b1afcd..c58a02fb5f 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -57,12 +57,13 @@ function Test-InExcel([string]$path) { $clock = [Diagnostics.Stopwatch]::StartNew() $job = Start-Job -ScriptBlock $probe -ArgumentList $path $done = Wait-Job $job -Timeout $TimeoutSec - $lines = @(Receive-Job $job -Keep) + $lines = @(Receive-Job $job -Keep -ErrorAction SilentlyContinue) + $failed = $job.State -eq 'Failed' if (-not $done) { Stop-Job $job } Remove-Job $job -Force $xlPid = ($lines | Where-Object { $_ -like "PID`t*" } | Select-Object -First 1) -replace '^PID\t', '' $out = $lines | Where-Object { $_ -notlike "PID`t*" } | Select-Object -Last 1 - if (-not $done) { $out = "TIMEOUT`tno answer in $TimeoutSec s" } elseif (-not $out) { $out = "CRASH`tno result (Excel died)" } + if (-not $done) { $out = "TIMEOUT`tno answer in $TimeoutSec s" } elseif ($failed -or -not $out) { $out = "CRASH`tno result (Excel died)" } if ($xlPid) { # A clean Quit lets Excel exit by itself; give it a moment, then stop only this instance. Wait-Process -Id ([int]$xlPid) -Timeout 15 -ErrorAction SilentlyContinue From dacff8ff9737a847fa656ee4c36d6de513dd57a2 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:10:26 -0500 Subject: [PATCH 30/95] IRR: an exact root with a zero slope is the answer, as in Excel --- crates/functions/src/financial.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 9c54775211..540b9b9f05 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -499,7 +499,9 @@ fn irr_solve(v: &[f64], guess: f64) -> R { s = s * x + c; } if ds == 0.0 { - return Err(CellError::Num); + // An exact root with a zero slope (a repeated root such as {1,-2,1} at guess 0) is + // still the answer: Excel returns 0 there. + return if s == 0.0 && x > 0.0 { Ok(1.0 / x - 1.0) } else { Err(CellError::Num) }; } let next = x - s / ds; if !next.is_finite() { @@ -2094,6 +2096,10 @@ mod tests { close_tol(irr_of(&[-100.0, 300.0, -210.0], Some(0.9)), 0.887_298_334_620_741_5, 1e-12); is_err(irr_of(&[-100.0, 60.0, 60.0], Some(-1.0)), CellError::Value); close_tol(irr_of(&[-100.0, 60.0, 60.0], Some(-0.999_999)), 0.130_662_386_291_807_5, 1e-12); + // An exact repeated root at the starting guess (zero slope) is the answer, as in Excel. + assert_eq!(irr_of(&[1.0, -2.0, 1.0], Some(0.0)), Value::Number(0.0)); + assert_eq!(irr_of(&[-1.0, 3.0, -3.0, 1.0], Some(0.0)), Value::Number(0.0)); + close_tol(irr_of(&[1.0, -2.0, 1.0], None), 1.09e-7, 1e-7); } /// PMT within about 4 ULPs of Excel's (Value2 of synthetic probes; libm differs by an ULP across From b023410ca4435e8a45db638b9a686418829af549 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:55:56 -0500 Subject: [PATCH 31/95] Excel open check: skip workbooks with Excel 4.0 macro sheets, require a zero CLI exit before opening the saved file --- packaging/windows/excel-open-check/check.ps1 | 21 ++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index c58a02fb5f..1faabf5bcb 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -12,7 +12,9 @@ Files saved: - every *.jsonl scenario next to this script (one feature each), run on the Sales sample. Each file is opened read-only with CorruptLoad = xlNormalLoad (0), so a part Excel would repair is a -failure instead of a silent fix, with DisplayAlerts off and macros disabled so nothing waits on a prompt. +failure instead of a silent fix, with DisplayAlerts off and VBA macros disabled so nothing waits on a prompt. +AutomationSecurity does not cover Excel 4.0 (XLM) macros, which would still prompt, so a workbook that +holds XLM macro sheets is never opened: it is reported as SKIP-XLM and the run does not pass. Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and that instance (found by its window's process id) is stopped. Nothing is written next to the inputs; any other Excel, such as one the person starts meanwhile, is never touched. Exit code 1 when any saved file is not PASS. @@ -39,7 +41,7 @@ $probe = { [void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid) "PID`t$xlPid" $x.DisplayAlerts = $false - $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: never run macros + $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: no VBA macros (XLM is screened by Test-HasXlm) # Named arguments: PowerShell can't skip the optional ones in between positionally. $wb = [System.__ComObject].InvokeMember('Open', [Reflection.BindingFlags]::InvokeMethod, $null, $x.Workbooks, @($path, 0, $true, 0), $null, $null, @('Filename', 'UpdateLinks', 'ReadOnly', 'CorruptLoad')) @@ -53,7 +55,16 @@ $probe = { } } +# True when the package holds Excel 4.0 macro sheets, which ForceDisable does not stop and Excel would prompt for. +function Test-HasXlm([string]$path) { + Add-Type -AssemblyName System.IO.Compression.FileSystem + # Not a zip at all: nothing to screen, Excel gets to report it. + try { $zip = [IO.Compression.ZipFile]::OpenRead($path) } catch { return $false } + try { return [bool]($zip.Entries | Where-Object { $_.FullName -like 'xl/macrosheets/*' }) } finally { $zip.Dispose() } +} + function Test-InExcel([string]$path) { + if (Test-HasXlm $path) { return [pscustomobject]@{ State = 'SKIP-XLM'; Seconds = 0; Detail = 'Excel 4.0 macro sheets; not opened' } } $clock = [Diagnostics.Stopwatch]::StartNew() $job = Start-Job -ScriptBlock $probe -ArgumentList $path $done = Wait-Job $job -Timeout $TimeoutSec @@ -92,11 +103,13 @@ $rows = @() foreach ($w in $work) { $name, $orig, $dest, $cliArgs = $w # The CLI reports on stderr, which Stop would turn into an exception. + Remove-Item $dest -Force -ErrorAction SilentlyContinue $ErrorActionPreference = 'Continue' & $Cli @cliArgs --out $dest *> $null + $code = $LASTEXITCODE $ErrorActionPreference = 'Stop' $base = if ($orig) { (Test-InExcel $orig) } else { $null } - $r = if (Test-Path $dest) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $LASTEXITCODE" } } + $r = if ($code -eq 0 -and (Test-Path $dest)) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $code" } } $rows += [pscustomobject]@{ File = $name; Original = if ($base) { $base.State } else { '-' }; Saved = $r.State Seconds = $r.Seconds; Detail = $r.Detail @@ -104,6 +117,6 @@ foreach ($w in $work) { } $rows | Format-Table -AutoSize -Wrap | Out-String -Width 220 | Write-Output if ($Csv) { $rows | Export-Csv -NoTypeInformation -Path $Csv } -$bad = @($rows | Where-Object Saved -ne 'PASS').Count +$bad = @($rows | Where-Object { $_.Saved -ne 'PASS' -or $_.Original -eq 'SKIP-XLM' }).Count "{0} of {1} saved files pass" -f ($rows.Count - $bad), $rows.Count if ($bad) { exit 1 } From 1053b66a0e8905b82a7ee04fca73c0358a9d6c5f Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:12:32 -0500 Subject: [PATCH 32/95] Excel open check: literal paths for saved workbooks and the input folder --- packaging/windows/excel-open-check/check.ps1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 1faabf5bcb..77cb82ecd1 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -85,13 +85,13 @@ function Test-InExcel([string]$path) { } $saved = Join-Path $Out 'saved' -Remove-Item $saved -Recurse -Force -ErrorAction SilentlyContinue +Remove-Item -LiteralPath $saved -Recurse -Force -ErrorAction SilentlyContinue New-Item -ItemType Directory -Path $saved -Force | Out-Null # (name, original or $null, saved) per file $work = @() if ($Inputs) { - foreach ($f in Get-ChildItem -Path $Inputs -File | Where-Object { $_.Extension -in '.xlsx', '.xlsm' } | Sort-Object Name) { + foreach ($f in Get-ChildItem -LiteralPath $Inputs -File | Where-Object { $_.Extension -in '.xlsx', '.xlsm' } | Sort-Object Name) { $work += , @($f.Name, $f.FullName, (Join-Path $saved $f.Name), @('run', '--in', $f.FullName, '--quiet')) } } @@ -103,13 +103,13 @@ $rows = @() foreach ($w in $work) { $name, $orig, $dest, $cliArgs = $w # The CLI reports on stderr, which Stop would turn into an exception. - Remove-Item $dest -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue $ErrorActionPreference = 'Continue' & $Cli @cliArgs --out $dest *> $null $code = $LASTEXITCODE $ErrorActionPreference = 'Stop' $base = if ($orig) { (Test-InExcel $orig) } else { $null } - $r = if ($code -eq 0 -and (Test-Path $dest)) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $code" } } + $r = if ($code -eq 0 -and (Test-Path -LiteralPath $dest)) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $code" } } $rows += [pscustomobject]@{ File = $name; Original = if ($base) { $base.State } else { '-' }; Saved = $r.State Seconds = $r.Seconds; Detail = $r.Detail From 15661dc97305b0acc265c74f915c3a336a3dca6e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:13:15 -0500 Subject: [PATCH 33/95] Cap text at 32,767 characters like Excel: & and CONCATENATE cut, CONCAT and TEXTJOIN give #CALC!, cell.set and CSV fields cut (#2635) --- ROADMAP.md | 1 + crates/calc/src/eval.rs | 8 +------ crates/calc/src/tests.rs | 10 ++++++++ crates/core/src/lib.rs | 2 +- crates/core/src/value.rs | 13 ++++++++++ crates/engine/src/cmd/edit.rs | 19 +++++++++++++++ crates/functions/src/text.rs | 38 ++++++++++++++++++++++-------- crates/xlsx/src/csv.rs | 4 ++-- crates/xlsx/src/tests/csv_tests.rs | 10 ++++++++ 9 files changed, 85 insertions(+), 20 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6b9b0fce78..faf1bf55a7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-26 | Text past 32,767 characters behaves like Excel (#2635): `&` and CONCATENATE cut their result there, CONCAT and TEXTJOIN give `#CALC!`, and a typed or CSV-read cell is cut, so GridCraft never writes a cell Excel refuses to open | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index 4bdb3a30d4..4ba0bf515e 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -1872,13 +1872,7 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste } }), BinOp::Concat => match (a.to_text(), b.to_text()) { - (Ok(x), Ok(y)) => { - if x.len() + y.len() > 32767 * 4 { - Value::Error(CellError::Value) - } else { - Value::text(x + &y) - } - } + (Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)), (Err(e), _) | (_, Err(e)) => Value::Error(e), }, BinOp::Eq => Value::Bool(compare(a, b) == Equal), diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5b9e900854..f2a2490567 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2274,3 +2274,13 @@ fn loan_schedule_residue_keeps_excels_sign() { } assert_eq!(t.get("P7"), Value::Text("".into())); } + +#[test] +fn concat_operator_cuts_at_the_cell_limit() { + // Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767. + let mut t = T::new(); + t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))"); + t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")"); + t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))"); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3")), (32767.0, 32767.0, 32767.0)); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 96f485cd93..574f78243c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,4 +14,4 @@ pub use addr::{ split_sheet, unquote_sheet, }; pub use date::DateSystem; -pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare}; +pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, compare, compare_numbers, compare_text, number_to_text, sort_compare}; diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index c531de4dc1..b5b820562d 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -462,3 +462,16 @@ mod tests { assert_eq!(row.get_broadcast(5, 1), Value::Number(2.0)); } } + +/// Longest text a cell can hold, in characters. +pub const MAX_TEXT_CHARS: usize = 32_767; + +/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. +pub fn cap_text(mut s: String) -> String { + if s.len() > MAX_TEXT_CHARS + && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) + { + s.truncate(i); + } + s +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 28ce338d6c..c7fa94dcf8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -123,6 +123,13 @@ pub fn specs() -> Vec { /// format, before parsing. Errors when the formula can't be parsed. pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result> { let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); + let capped; + let mut input = input; + if input.len() > gridcraft_core::MAX_TEXT_CHARS && !input.starts_with('=') { + // Excel cuts typed text to 32,767 characters. + capped = gridcraft_core::cap_text(input.to_string()); + input = &capped; + } if input.is_empty() { let c = Cell { value: Value::Empty, formula: None, style }; return Ok(if c.is_blank() { None } else { Some(c) }); @@ -2039,6 +2046,18 @@ mod tests { assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}"); } + #[test] + fn cell_set_cuts_text_to_32767_characters() { + // Excel cuts a 40,000-character entry to 32,767; a formula is left alone. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone(); + assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767)); + assert_eq!(get(&mut s, "A2"), json!(32767.0)); + } + #[test] fn cell_set_takes_numbers_for_input_and_value() { // #697: a JSON number for `input` used to clear the cell instead of entering it. diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index df125f022f..82b2654ca7 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -27,30 +27,41 @@ fn check_len(s: String) -> R { } /// Pushes `piece` onto `out`, failing once the result exceeds the cell limit. -fn push_capped(out: &mut String, piece: &str) -> R<()> { +fn push_capped(out: &mut String, piece: &str, over: CellError) -> R<()> { out.push_str(piece); if out.len() > MAX_TEXT * 4 { - return Err(CellError::Value); + return Err(over); } Ok(()) } +/// CONCATENATE cuts at the cell limit like `&`; CONCAT and TEXTJOIN give `#CALC!` past it. fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { - push_capped(&mut out, &scalar(x).to_text()?)?; + out.push_str(&scalar(x).to_text()?); + if out.len() > MAX_TEXT * 4 { + break; + } } - check_len(out) + text_val(gridcraft_core::cap_text(out)) +} + +fn check_calc(s: String) -> R { + if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT { + return Err(CellError::Calc); + } + text_val(s) } fn concat(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { for v in as_array(&x.value).iter() { - push_capped(&mut out, &v.to_text()?)?; + push_capped(&mut out, &v.to_text()?, CellError::Calc)?; } } - check_len(out) + check_calc(out) } fn textjoin(a: &[Arg], _c: &mut dyn Ctx) -> R { @@ -69,11 +80,11 @@ fn textjoin(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for (i, s) in items.iter().enumerate() { if i > 0 && !delims.is_empty() { - push_capped(&mut out, &delims[(i - 1) % delims.len()])?; + push_capped(&mut out, &delims[(i - 1) % delims.len()], CellError::Calc)?; } - push_capped(&mut out, s)?; + push_capped(&mut out, s, CellError::Calc)?; } - check_len(out) + check_calc(out) } fn count_arg(a: &[Arg], i: usize, default: f64) -> R { @@ -680,7 +691,7 @@ fn arraytotext(a: &[Arg], _c: &mut dyn Ctx) -> R { } else if c > 0 { out.push_str(if strict { "," } else { ", " }); } - push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict))?; + push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict), CellError::Value)?; } } if strict { @@ -1094,6 +1105,13 @@ mod tests { is_text(ev("TEXTJOIN", vec![t("-"), b(false), av(arr(vec![vec![tv("a"), tv(""), tv("b")]]))]), "a--b"); is_text(ev("TEXTJOIN", vec![av(row_t(&[",", ";"])), b(true), t("a"), t("b"), t("c")]), "a,b;c"); is_err(ev("CONCAT", vec![t("a"), e(CellError::NA)]), CellError::NA); + // Past 32,767 characters: CONCAT and TEXTJOIN are #CALC!, CONCATENATE cuts like `&` + // (checked in Excel: LEN(...) is #CALC!, #CALC! and 32767). + let x = || t(&"x".repeat(20_000)); + is_err(ev("CONCAT", vec![x(), x()]), CellError::Calc); + is_err(ev("TEXTJOIN", vec![t(","), b(false), x(), x()]), CellError::Calc); + assert_eq!(ev("CONCATENATE", vec![x(), x()]), Value::text("x".repeat(32_767))); + assert_eq!(ev("CONCAT", vec![x()]), Value::text("x".repeat(20_000))); // Lifting: CONCATENATE over an array. assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]); } diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index dfc694ea61..10d48024d1 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -276,7 +276,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { } let pos = CellRef::new(row, col as u32); let cell = if opts.parse_values { - let p = parse_input(&f, opts.date_system); + let p = parse_input(&gridcraft_core::cap_text(f), opts.date_system); let style = match p.format { Some(code) => match fmt_cache.iter().find(|(c, _)| *c == code) { Some((_, id)) => *id, @@ -290,7 +290,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { }; Cell { value: p.value, formula: None, style } } else { - Cell::value(Value::Text(Arc::from(f))) + Cell::value(Value::Text(Arc::from(gridcraft_core::cap_text(f)))) }; sheet.cells.set(pos, cell); } diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 066f507e07..2a1974588b 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -326,3 +326,13 @@ fn parser_stops_collecting_fields_at_max_cols() { }); assert_eq!(lens, vec![MAX_COLS as usize]); } + +#[test] +fn a_field_over_32767_characters_is_cut() { + let src = format!("{},{}", "x".repeat(40_000), "y".repeat(32_768)); + for parse_values in [true, false] { + let wb = read_csv(src.as_bytes(), &CsvOptions { parse_values, ..Default::default() }).unwrap(); + assert_eq!(v(&wb, 0, 0), Value::text("x".repeat(32_767))); + assert_eq!(v(&wb, 0, 1), Value::text("y".repeat(32_767))); + } +} From 0ddd8684efaeae2142f28e875d6b3342bfa370d1 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:24:42 -0500 Subject: [PATCH 34/95] Move cap_text above the test module --- crates/core/src/value.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index b5b820562d..66db292096 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -389,6 +389,19 @@ pub fn sci_text(n: f64, sig: usize) -> String { format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) } +/// Longest text a cell can hold, in characters. +pub const MAX_TEXT_CHARS: usize = 32_767; + +/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. +pub fn cap_text(mut s: String) -> String { + if s.len() > MAX_TEXT_CHARS + && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) + { + s.truncate(i); + } + s +} + #[cfg(test)] mod tests { use super::*; @@ -462,16 +475,3 @@ mod tests { assert_eq!(row.get_broadcast(5, 1), Value::Number(2.0)); } } - -/// Longest text a cell can hold, in characters. -pub const MAX_TEXT_CHARS: usize = 32_767; - -/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. -pub fn cap_text(mut s: String) -> String { - if s.len() > MAX_TEXT_CHARS - && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) - { - s.truncate(i); - } - s -} From c4920c463b33217b01fcce13811d5220d3f4e5df Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:30:56 -0500 Subject: [PATCH 35/95] Excel open check: count saved passes apart from the XLM gate --- packaging/windows/excel-open-check/check.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index 77cb82ecd1..c5687e778b 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -118,5 +118,6 @@ foreach ($w in $work) { $rows | Format-Table -AutoSize -Wrap | Out-String -Width 220 | Write-Output if ($Csv) { $rows | Export-Csv -NoTypeInformation -Path $Csv } $bad = @($rows | Where-Object { $_.Saved -ne 'PASS' -or $_.Original -eq 'SKIP-XLM' }).Count -"{0} of {1} saved files pass" -f ($rows.Count - $bad), $rows.Count +$savedBad = @($rows | Where-Object Saved -ne 'PASS').Count +"{0} of {1} saved files pass" -f ($rows.Count - $savedBad), $rows.Count if ($bad) { exit 1 } From 571bdf68adb16366b183338b0bc461f2fb2044ef Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:30:59 -0500 Subject: [PATCH 36/95] Keep the clipboard budget test within the cell limit --- crates/engine/src/tests.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13fbb9b3a4..077c787f4d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -675,11 +675,13 @@ fn rich_clipboard_omits_html_for_large_ranges_without_truncating_text() { #[test] fn rich_clipboard_omits_html_when_escaping_exceeds_byte_budget() { let mut s = s(); - let text = "&".repeat(1_000_000); - s.execute("range.setValues", json!({"range": "A1", "values": [[text]]})).unwrap(); - let copied = s.execute("edit.copy", json!({"range": "A1", "html": true})).unwrap(); + // Cells hold at most 32,767 characters, so 30 full cells of `&` (5 bytes each once escaped) + // pass the 4 MiB HTML budget while the plain text stays far below it. + let cell = "&".repeat(32_767); + s.execute("range.setValues", json!({"range": "A1", "values": [vec![cell; 30]]})).unwrap(); + let copied = s.execute("edit.copy", json!({"range": "A1:AD1", "html": true})).unwrap(); assert!(copied.get("html").is_none(), "an oversized escaped value must not produce partial HTML"); - assert_eq!(copied["text"].as_str().unwrap().len(), 1_000_001); + assert_eq!(copied["text"].as_str().unwrap().len(), 30 * 32_767 + 30); assert!(copied["text"].as_str().unwrap().ends_with("&\n")); } From 7155ced916be2860361fb6cad498c6ac2518c509 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:42:21 -0500 Subject: [PATCH 37/95] Cap text after parsing the apostrophe prefix and in text-formatted cells; keep CONCATENATE errors past the cap --- crates/core/src/lib.rs | 2 +- crates/core/src/value.rs | 8 ++++++++ crates/engine/src/cmd/edit.rs | 18 ++++++++++-------- crates/functions/src/text.rs | 10 +++++++--- crates/xlsx/src/csv.rs | 4 ++-- crates/xlsx/src/tests/csv_tests.rs | 5 ++++- 6 files changed, 32 insertions(+), 15 deletions(-) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 574f78243c..bf5d3fd3f5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,4 +14,4 @@ pub use addr::{ split_sheet, unquote_sheet, }; pub use date::DateSystem; -pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, compare, compare_numbers, compare_text, number_to_text, sort_compare}; +pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare}; diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index 66db292096..634b577468 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -402,6 +402,14 @@ pub fn cap_text(mut s: String) -> String { s } +/// `v` with text cut to [`MAX_TEXT_CHARS`] characters; other values pass through. +pub fn cap_value(v: Value) -> Value { + match v { + Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())), + v => v, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c7fa94dcf8..7ae7ab494a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -123,20 +123,13 @@ pub fn specs() -> Vec { /// format, before parsing. Errors when the formula can't be parsed. pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gridcraft_model::Workbook) -> Result> { let style = wb.sheet(sheet).map(|sh| sh.style_id(at)).unwrap_or_default(); - let capped; - let mut input = input; - if input.len() > gridcraft_core::MAX_TEXT_CHARS && !input.starts_with('=') { - // Excel cuts typed text to 32,767 characters. - capped = gridcraft_core::cap_text(input.to_string()); - input = &capped; - } if input.is_empty() { let c = Cell { value: Value::Empty, formula: None, style }; return Ok(if c.is_blank() { None } else { Some(c) }); } let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@"; if fmt_is_text { - return Ok(Some(Cell { value: Value::text(input), formula: None, style })); + return Ok(Some(Cell { value: gridcraft_core::cap_value(Value::text(input)), formula: None, style })); } let is_formula = input.starts_with('=') || (input.len() > 1 @@ -173,6 +166,8 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri return Ok(Some(cell)); } let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system); + // Excel cuts typed text to 32,767 characters (after any leading apostrophe is dropped). + parsed.value = gridcraft_core::cap_value(parsed.value); // Like Excel's automatic percent entry: a bare number of 1 or more typed into a cell already // formatted as a percentage is a percent (3 -> 3%); smaller numbers are taken as fractions. if parsed.format.is_none() @@ -2053,7 +2048,14 @@ mod tests { s.new_workbook(); s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap(); s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap(); + // An apostrophe prefix isn't text, and a text-formatted cell takes `=` as text. + s.execute("cell.set", json!({"cell": "B1", "input": format!("'{}", "x".repeat(40_000))})).unwrap(); + s.execute("home.numberFormat", json!({"range": "C1", "code": "@"})).unwrap(); + s.execute("cell.set", json!({"cell": "C1", "input": format!("={}", "x".repeat(40_000))})).unwrap(); let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone(); + for at in ["B1", "C1"] { + assert_eq!(get(&mut s, at).as_str().map(|t| t.chars().count()), Some(32_767), "{at}"); + } assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767)); assert_eq!(get(&mut s, "A2"), json!(32767.0)); } diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index 82b2654ca7..38a760db90 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -39,9 +39,10 @@ fn push_capped(out: &mut String, piece: &str, over: CellError) -> R<()> { fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { - out.push_str(&scalar(x).to_text()?); - if out.len() > MAX_TEXT * 4 { - break; + // Past the budget, later arguments are still converted so their errors propagate. + let piece = scalar(x).to_text()?; + if out.len() <= MAX_TEXT * 4 { + out.push_str(&piece); } } text_val(gridcraft_core::cap_text(out)) @@ -1112,6 +1113,9 @@ mod tests { is_err(ev("TEXTJOIN", vec![t(","), b(false), x(), x()]), CellError::Calc); assert_eq!(ev("CONCATENATE", vec![x(), x()]), Value::text("x".repeat(32_767))); assert_eq!(ev("CONCAT", vec![x()]), Value::text("x".repeat(20_000))); + // An error after the cut still propagates. + let big = || t(&"x".repeat(32_767)); + is_err(ev("CONCATENATE", vec![big(), big(), big(), big(), big(), e(CellError::NA)]), CellError::NA); // Lifting: CONCATENATE over an array. assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]); } diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index 10d48024d1..f7ce010ca8 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -276,7 +276,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { } let pos = CellRef::new(row, col as u32); let cell = if opts.parse_values { - let p = parse_input(&gridcraft_core::cap_text(f), opts.date_system); + let p = parse_input(&f, opts.date_system); let style = match p.format { Some(code) => match fmt_cache.iter().find(|(c, _)| *c == code) { Some((_, id)) => *id, @@ -288,7 +288,7 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result { }, None => StyleId::DEFAULT, }; - Cell { value: p.value, formula: None, style } + Cell { value: gridcraft_core::cap_value(p.value), formula: None, style } } else { Cell::value(Value::Text(Arc::from(gridcraft_core::cap_text(f)))) }; diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 2a1974588b..b840322087 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -329,10 +329,13 @@ fn parser_stops_collecting_fields_at_max_cols() { #[test] fn a_field_over_32767_characters_is_cut() { - let src = format!("{},{}", "x".repeat(40_000), "y".repeat(32_768)); + let src = format!("{},{},'{}", "x".repeat(40_000), "y".repeat(32_768), "z".repeat(40_000)); for parse_values in [true, false] { let wb = read_csv(src.as_bytes(), &CsvOptions { parse_values, ..Default::default() }).unwrap(); assert_eq!(v(&wb, 0, 0), Value::text("x".repeat(32_767))); assert_eq!(v(&wb, 0, 1), Value::text("y".repeat(32_767))); } + // The apostrophe is dropped before the cut when values are parsed. + let wb = read_csv(src.as_bytes(), &CsvOptions::default()).unwrap(); + assert_eq!(v(&wb, 0, 2), Value::text("z".repeat(32_767))); } From 9bbcb7ce908b3b734749b3160d3a4037e6d9ea6f Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:44:00 -0500 Subject: [PATCH 38/95] Excel open check: compile the helper before Excel starts so the PID line is not held up --- packaging/windows/excel-open-check/check.ps1 | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 index c5687e778b..1e82a48633 100644 --- a/packaging/windows/excel-open-check/check.ps1 +++ b/packaging/windows/excel-open-check/check.ps1 @@ -33,13 +33,14 @@ $probe = { param($path) $x = $null try { - $x = New-Object -ComObject Excel.Application - $x.Visible = $false - # Report this instance's process id so the caller can stop exactly it and nothing else. + # Compiled before Excel starts, so nothing between the start and the PID line can fail or stall on it. Add-Type -Namespace Win -Name U -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);' + $x = New-Object -ComObject Excel.Application + # Report this instance's process id so the caller can stop exactly it and nothing else. $xlPid = [uint32]0 [void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid) "PID`t$xlPid" + $x.Visible = $false $x.DisplayAlerts = $false $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: no VBA macros (XLM is screened by Test-HasXlm) # Named arguments: PowerShell can't skip the optional ones in between positionally. @@ -51,6 +52,7 @@ $probe = { } catch { "FAIL`t" + ($_.Exception.Message -replace '\s+', ' ') } finally { + # Also covers a failure before the PID line: this process's own instance is quit, no other is touched. if ($x) { try { $x.Quit() } catch {} } } } From 2fbe96820c326d2a5fbd8eec7c97372a02d00420 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:07:19 -0500 Subject: [PATCH 39/95] Cap range.setValues text when parse is false --- crates/engine/src/cmd/edit.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 7ae7ab494a..32a154a7b4 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -342,7 +342,7 @@ fn range_set_values(s: &mut Session, p: &Json) -> Result { if text.contains('\n') && !cx.wb.styles.get(style).align.wrap { style = cx.wb.styles.derive(style, |s| s.align.wrap = true); } - Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style }) + Some(Cell { value: gridcraft_core::cap_value(Value::Text(text.as_str().into())), formula: None, style }) } _ => input_to_cell(&input, sheet, at, &mut cx.wb)?, }; @@ -2120,6 +2120,11 @@ mod tests { assert!(s.execute("range.setValues", json!({"range": "A8", "parse": 0, "values": [["x"]]})).is_err()); // A line break still turns on Wrap Text. s.execute("range.setValues", json!({"range": "A9", "parse": false, "values": [["one\ntwo"]]})).unwrap(); + // Text stored as given still stops at Excel's 32,767-character cell limit. + let long = "x".repeat(40_000); + s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap(); + let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count())); + assert_eq!(len.flatten(), Some(32_767)); assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo")); let d = s.doc().unwrap(); let sh = d.wb.active().unwrap(); From a7a708d0f64ad20a76dcba4e00de8f2219411eb2 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Mon, 26 Oct 2026 13:22:28 -0500 Subject: [PATCH 40/95] #2641: cascade AutoFilter dropdown values --- crates/engine/src/cmd/data.rs | 145 ++++++++------ .../engine/tests/cascading_filter_values.rs | 183 ++++++++++++++++++ .../ui-egui/tests/cascading_filter_values.rs | 69 +++++++ docs/ui-parity.md | 20 +- 4 files changed, 360 insertions(+), 57 deletions(-) create mode 100644 crates/engine/tests/cascading_filter_values.rs create mode 100644 crates/ui-egui/tests/cascading_filter_values.rs diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index fcab9db713..de17bc54c8 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -679,17 +679,17 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { } } -/// Hides rows of the autofilter range that fail any criterion. -pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { - let Some(sh) = wb.sheet(sheet) else { return }; - let Some(af) = sh.autofilter.clone() else { return }; +/// Statistics use the original range, regardless of the other active criteria (as in Excel). +fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> std::collections::HashMap, f64)> { let r = af.range; - let mut hide = Vec::new(); // Precompute per-criterion top10 threshold and average once, not per row. let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); for (i, (off, c)) in af.criteria.iter().enumerate() { + if Some(*off) == excluded_offset { + continue; + } if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { - let col = r.start.col + off; + let Some(col) = r.start.col.checked_add(*off).filter(|col| *col <= r.end.col) else { continue }; let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::() / nums.len() as f64 }; let thr = match c { @@ -704,59 +704,84 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { col_stats.insert(i, (thr, avg)); } } - for row in r.start.row + 1..=r.end.row { - let mut visible = true; - for (i, (off, crit)) in af.criteria.iter().enumerate() { - let c = CellRef::new(row, r.start.col + off); - let v = sh.value(c); - let text = crate::display::cell_text(wb, sh, c); - let ok = match crit { - FilterCriterion::Values { values, blanks } => { - if filter_blank(&v) { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) + col_stats +} + +/// Evaluate criteria directly, without conflating manual visibility with filter results. +fn filter_row_matches( + wb: &Workbook, + sh: &Sheet, + af: &AutoFilter, + row: u32, + col_stats: &std::collections::HashMap, f64)>, + excluded_offset: Option, +) -> bool { + for (i, (off, crit)) in af.criteria.iter().enumerate() { + if Some(*off) == excluded_offset { + continue; + } + let Some(col) = af.range.start.col.checked_add(*off).filter(|col| *col <= af.range.end.col) else { continue }; + let c = CellRef::new(row, col); + let v = sh.value(c); + let text = crate::display::cell_text(wb, sh, c); + let ok = match crit { + FilterCriterion::Values { values, blanks } => { + if filter_blank(&v) { + *blanks + } else { + values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) + } + } + FilterCriterion::Custom { a, b, and } => { + let x = custom_ok(&v, &text, &a.0, &a.1); + match b { + Some(b) => { + let y = custom_ok(&v, &text, &b.0, &b.1); + if *and { x && y } else { x || y } } + None => x, + } + } + FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { + (Some(n), Some((thr, _))) => { + let thr = thr.unwrap_or(n); + if *bottom { n <= thr } else { n >= thr } } - FilterCriterion::Custom { a, b, and } => { - let x = custom_ok(&v, &text, &a.0, &a.1); - match b { - Some(b) => { - let y = custom_ok(&v, &text, &b.0, &b.1); - if *and { x && y } else { x || y } - } - None => x, + _ => false, + }, + FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { + (Some(n), Some((_, avg))) => { + if *above { + n > *avg + } else { + n < *avg } } - FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((thr, _))) => { - let thr = thr.unwrap_or(n); - if *bottom { n <= thr } else { n >= thr } - } - _ => false, - }, - FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((_, avg))) => { - if *above { - n > *avg - } else { - n < *avg - } - } - _ => false, - }, - FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, - FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, - // Icons are not evaluated here: the row keeps its current visibility. - FilterCriterion::Icon { .. } => !sh.is_row_hidden(row), - }; - if !ok { - visible = false; - break; - } + _ => false, + }, + FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, + FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, + // Icon criteria are retained from files but cannot be evaluated yet. + FilterCriterion::Icon { .. } => true, + }; + if !ok { + return false; } - hide.push((row, !visible)); } + true +} + +/// Hides rows of the autofilter range that fail any criterion. +pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { + let Some(sh) = wb.sheet(sheet) else { return }; + let Some(af) = sh.autofilter.clone() else { return }; + let r = af.range; + let col_stats = filter_stats(sh, &af, None); + // Reapplying a retained icon filter preserves visibility until icons can be evaluated. + let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. })); + let hide: Vec<_> = (r.start.row + 1..=r.end.row) + .map(|row| (row, !filter_row_matches(wb, sh, &af, row, &col_stats, None) || (has_icon && sh.is_row_hidden(row)))) + .collect(); let Some(shm) = wb.sheet_mut(sheet) else { return }; for (row, h) in hide { if h { @@ -789,14 +814,22 @@ fn reapply(s: &mut Session, _: &Json) -> Result { }) } -/// Distinct display values of a filter column (for the dropdown list). +/// Distinct display values from rows matching the other columns' criteria. +/// The current criterion only determines checkboxes, so its unchecked alternatives stay available. pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> { let Some(sh) = wb.sheet(sheet) else { return vec![] }; let Some(af) = &sh.autofilter else { return vec![] }; - let off = col.saturating_sub(af.range.start.col); + if col < af.range.start.col || col > af.range.end.col { + return vec![]; + } + let off = col - af.range.start.col; let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); + let col_stats = filter_stats(sh, af, Some(off)); let mut seen = std::collections::BTreeMap::new(); - for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) { + for row in af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)) { + if !filter_row_matches(wb, sh, af, row, &col_stats, Some(off)) { + continue; + } let c = CellRef::new(row, col); let v = sh.value(c); let blank = filter_blank(&v); diff --git a/crates/engine/tests/cascading_filter_values.rs b/crates/engine/tests/cascading_filter_values.rs new file mode 100644 index 0000000000..afaf720282 --- /dev/null +++ b/crates/engine/tests/cascading_filter_values.rs @@ -0,0 +1,183 @@ +use std::sync::Arc; + +use gridcraft_engine::{ + Session, + cmd::data::filter_values, + model::{Color, FilterCriterion}, +}; +use serde_json::json; + +#[test] +fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { + for (criterion, expected) in [ + (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"]), + (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"]), + (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"]), + (json!({"top": {"count": 2}}), vec!["high", "upper"]), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"]), + (json!({"aboveAverage": true}), vec!["high"]), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Amount"], ["low", 10], ["mid", 20], ["upper", 30], ["high", 100], ["blank", null], ["text", "n/a"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "A1:B7"})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}"); + // Statistics still come from the whole range even with another column filtered. + s.execute("data.filterBy", json!({"column": "A", "values": ["mid"]})).unwrap(); + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}, with the current column filtered"); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 1), + vec![("20".into(), true)], + "the numeric column's own criterion must be excluded: {criterion}" + ); + } +} + +#[test] +fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "B3", "values": [ + ["Company", "Job", "Status"], + ["East", "Alpha", "Open"], + ["East", "Beta", "Open"], + ["East", "Closed job", "Closed"], + ["West", "Other company", "Open"], + ["East", null, "Open"], + ["East", "=\"\"", "Open"], + ["East", "Outside range", "Open"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "B3:D9"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + s.execute("data.filterBy", json!({"column": "D", "values": ["Open"]})).unwrap(); + s.execute("data.filterBy", json!({"column": "C", "values": ["Alpha"]})).unwrap(); + + let choices = |s: &Session| filter_values(&s.doc().unwrap().wb, 0, 2); + let expected = + |beta: bool, blanks: bool| -> Vec<(String, bool)> { vec![("Alpha".into(), !beta), ("Beta".into(), beta), ("(Blanks)".into(), blanks)] }; + assert_eq!(choices(&s), expected(false, false)); + s.execute("data.filterBy", json!({"column": "C", "values": ["Beta"], "blanks": true})).unwrap(); + assert_eq!(choices(&s), expected(true, true)); + s.execute("data.filterBy", json!({"column": "C", "clear": true})).unwrap(); + assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]); + // Manual visibility is not a filter criterion, even when every eligible row is hidden. + s.execute("home.hideRows", json!({"rows": "4:10"})).unwrap(); + assert_eq!(choices(&s).len(), 3); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); + assert!(filter_values(&s.doc().unwrap().wb, 0, 4).is_empty()); +} + +#[test] +fn choices_respect_blank_and_formatted_value_criteria_on_other_columns() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Value"], ["empty", null], ["formula", "=\"\""], ["spaces", " "], ["number", 12], ["other", 30] + ]}), + ) + .unwrap(); + s.execute("home.numberFormat", json!({"range": "B5:B6", "code": "0.00"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".into(), true)]); + for value in ["12", "12.00"] { + s.execute("data.filterBy", json!({"column": "B", "values": [value]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("number".into(), true)]); + } + s.execute("data.filterBy", json!({"column": "B", "values": ["absent"]})).unwrap(); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); +} + +#[test] +fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Name", "Color"], ["red", 1], ["plain", 2]]})).unwrap(); + s.execute("home.fillColor", json!({"range": "B2", "color": "#FF0000"})).unwrap(); + s.execute("home.fontColor", json!({"range": "B2", "color": "#FF0000"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B3"})).unwrap(); + for criterion in [FilterCriterion::FillColor(Color::Rgb(0xFF0000)), FilterCriterion::FontColor(Color::Rgb(0xFF0000))] { + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(1, criterion)]; + s.execute("data.reapply", json!({})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("red".into(), true)]); + } + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(1, FilterCriterion::Icon { set: "3Arrows".into(), id: Some(0) })]; + s.execute("data.reapply", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2), "reapply preserves imported icon visibility"); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 0), + vec![("plain".into(), true), ("red".into(), true)], + "unsupported icon criteria cannot distinguish manual and current-column hiding" + ); +} + +#[test] +fn querying_a_table_backed_sheet_filter_is_read_only_and_preserves_xlsx_criteria() { + for table in [false, true] { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + if table { + s.execute("insert.table", json!({"range": "B3:C6", "header": true})).unwrap(); + } + s.execute("selection.set", json!({"cell": "B3"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + let before = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]); + assert_eq!(before, gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap()); + let (reopened, _) = gridcraft_xlsx::read_xlsx(&before).unwrap(); + let sh = reopened.active().unwrap(); + let criteria = if table { &sh.tables[0].filter } else { &sh.autofilter.as_ref().unwrap().criteria }; + assert_eq!(criteria, &vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false })]); + assert!(!sh.is_row_hidden(3) && !sh.is_row_hidden(4) && sh.is_row_hidden(5)); + } +} + +#[test] +fn an_unrelated_tables_criteria_do_not_restrict_the_sheet_filter_choices() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + s.execute("range.setValues", json!({"range": "F3", "values": [["Company", "Job"], ["West", "Unrelated"], ["East", "Separate"]]})).unwrap(); + s.execute("insert.table", json!({"range": "F3:G5", "header": true})).unwrap(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.tables[0].filter = vec![(0, FilterCriterion::Values { values: vec!["West".into()], blanks: false })]; + s.execute("selection.set", json!({"cell": "B3"})).unwrap(); + s.execute("data.filter", json!({"range": "B3:C6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]); +} + +#[test] +fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { + let mut s = Session::new(); + s.new_workbook(); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); + assert!(filter_values(&s.doc().unwrap().wb, 99, 0).is_empty()); + s.execute("range.setValues", json!({"range": "B1048574", "values": [["Company", "Job"], ["East", "Last East"], ["West", "Last West"]]})).unwrap(); + s.execute("data.filter", json!({"range": "B1048574:C1048576"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]); +} diff --git a/crates/ui-egui/tests/cascading_filter_values.rs b/crates/ui-egui/tests/cascading_filter_values.rs new file mode 100644 index 0000000000..c217d35fc4 --- /dev/null +++ b/crates/ui-egui/tests/cascading_filter_values.rs @@ -0,0 +1,69 @@ +#[path = "common/mod.rs"] +mod common; + +use egui::{Event, Key, Modifiers}; +use egui_kittest::kittest::Queryable; +use gridcraft_engine::Session; +use serde_json::json; + +fn key(h: &mut common::Harness, key: Key, modifiers: Modifiers) { + for pressed in [true, false] { + h.input_mut().events.push(Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }); + } + h.run_steps(3); +} + +#[test] +fn dropdown_can_change_and_clear_a_column_while_another_filter_stays_active() { + for table in [false, true] { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"], ["East", null] + ]}), + ) + .unwrap(); + if table { + session.execute("insert.table", json!({"range": "A1:B5", "header": true})).unwrap(); + } + session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + session.execute("data.filterBy", json!({"column": "B", "values": ["Alpha"]})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let screenshot = std::env::var("GRIDCRAFT_CASCADING_SNAPSHOT").ok().filter(|_| !table); + let mut h = if screenshot.is_some() { + common::harness_with( + common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)).wgpu(), + common::app(session), + 4, + ) + } else { + common::os_harness(session, egui::os::OperatingSystem::Windows) + }; + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_some(), "current-column filtering must not remove alternatives"); + assert!(h.query_by_label("(Blanks)").is_some()); + assert!(h.query_by_label("Other").is_none(), "the other company's job must not be listed"); + if let Some(path) = screenshot { + h.render().unwrap().save(path).unwrap(); + } + h.get_by_label("Alpha").click(); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(3); + let hidden = |h: &common::Harness| { + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + (1..=4).map(|row| sh.is_row_hidden(row)).collect::>() + }; + assert_eq!(hidden(&h), [true, false, true, true]); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.get_by_label("Clear Filter").click(); + h.run_steps(3); + assert_eq!(hidden(&h), [false, false, true, false], "clearing Job keeps Company filtered"); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f35899236b..dca4ea508e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (cascading AutoFilter choices) · **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,6 +60,7 @@ this logic, with one undo step. | 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) | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | +| AutoFilter value dropdowns | Choices come from rows satisfying the other columns' active criteria; the current column only determines checkbox state, including (Blanks), so its filter can be changed or cleared (#2641). Custom comparisons, Top 10, average and color criteria use the same evaluator as row filtering. Top 10 / average thresholds still use the original range. Manual hidden rows do not restrict choices; imported icon criteria remain unevaluated. | | Data › Advanced Filter | dialog offers in-place or copy-to filtering, list and optional criteria ranges, and unique records; Alt+A,Q opens it (#1622). The engine's copy-to path clears only the result footprint and rejects worksheet overflow (#1031). | | Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; Data › Outline › Settings (`data.outlineSettings`) puts summary rows above and summary columns left of their detail, saved as `outlinePr` (the dialog's Automatic styles check box and Apply Styles button are missing), View › Show Outline Symbols (Ctrl+8) hides the bands and is saved with the sheet, and a block of cells still groups rows without the Rows / Columns dialog | | Reorder selected whole columns by dragging their headers | done (10-11) | @@ -91,6 +92,22 @@ this logic, with one undo step. | Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; letters also work with left Alt held (Alt+H, O, A), as in Excel; each Borders letter (H, B, …) draws its own preset, H, B, M opens Format Cells on the Border tab, and Erase Border, Line Color and Line Style are reserved; QAT/Backstage excluded | | Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) | +### AutoFilter population and pending integrations + +[Microsoft's filtering guide](https://support.microsoft.com/en-us/excel/get-started/filter-data-in-a-range-or-table-in-excel) +describes additive column filters and restricting other dropdowns to the filtered range. The +current column is excluded from enumeration so its unchecked alternatives remain available. +The existing one-million-data-row enumeration limit and value sorting remain unchanged. + +This changes the population behind the pending row-count work (#1737, and its stacked Only +button #1741): a future count beside a choice should count eligible rows satisfying the other +columns, including rows rejected by the current column. It must not count the whole original +range or just currently visible rows. Search narrows the displayed choices, not that population. +These PRs are not incorporated here. Date grouping (#1509) should group this same eligible +population. Table filter activation / roundtrip ownership changes remain in #2506; enumeration +reads the active sheet AutoFilter used by the current table dropdown without changing criteria, +row visibility or the XLSX representation. + ### Shortcut audit (#110) Checked against Microsoft's published "Keyboard shortcuts in Excel" (Windows and Mac tables, @@ -187,6 +204,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); document pending counts, date grouping and table roundtrip integration | | 2026-10-25 | minor | AutoSum (Alt+=, Home › AutoSum) over a selected row puts its total to the right of the row, or in its last cell when that is empty, as in Excel; it wrote a one-cell total under each cell. A selection's empty last column takes each row's total and its empty last row each column's, with the block's total in the corner when both are empty | | 2026-10-25 | minor | Paste Name lays out only the names in view, so a workbook with thousands of names opens it at once; the arrow keys still scroll the chosen name into view. Go To matches a `Sheet2!Name` reference and hides a workbook name behind the active sheet's own name in any case and script (`Größe` = `GRÖSSE`), as formulas do. The two Page Layout view rows are one; the 0.7 in side margin used when Align with Page Margins is off is marked unverified | | 2026-10-24 | minor | Go To lists the named ranges on every sheet, as Excel's does ("The Go to popup window shows named ranges on every worksheet in your workbook"): a name scoped to another sheet appears as `Sheet2!Name`, and hidden names, constants and formulas are left out. It keeps the references entered (newest first, ten at most), and a double-click on an entry goes there. The Reference box and `edit.goTo` take several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30,H21:H29`) and select them all; `edit.goTo {list: true}` returns the list | From 1fcaffe7b7fdefe5885c819c8bc64d2e0bc3ef0e Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Mon, 26 Oct 2026 13:40:03 -0500 Subject: [PATCH 41/95] #2641: address review coverage and menu scan cost --- .../tests/{ => it}/cascading_filter_values.rs | 35 +++++++++++++++++-- crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/grid.rs | 6 ++-- .../tests/{ => it}/cascading_filter_values.rs | 3 +- crates/ui-egui/tests/it/main.rs | 1 + 5 files changed, 40 insertions(+), 6 deletions(-) rename crates/engine/tests/{ => it}/cascading_filter_values.rs (84%) rename crates/ui-egui/tests/{ => it}/cascading_filter_values.rs (98%) diff --git a/crates/engine/tests/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs similarity index 84% rename from crates/engine/tests/cascading_filter_values.rs rename to crates/engine/tests/it/cascading_filter_values.rs index afaf720282..5c39131d21 100644 --- a/crates/engine/tests/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -33,7 +33,7 @@ fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { s.execute("data.filterBy", params).unwrap(); let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); assert_eq!(actual, expected, "{criterion}"); - // Statistics still come from the whole range even with another column filtered. + // The current column's own criterion must not narrow its alternatives. s.execute("data.filterBy", json!({"column": "A", "values": ["mid"]})).unwrap(); let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); assert_eq!(actual, expected, "{criterion}, with the current column filtered"); @@ -45,6 +45,36 @@ fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { } } +#[test] +fn statistical_thresholds_use_the_original_range_not_other_columns_subset() { + for (criterion, names, expected) in [ + (json!({"top": {"count": 2}}), vec!["low", "mid", "upper"], vec!["upper"]), + (json!({"top": {"count": 50, "percent": true}}), vec!["low", "mid", "upper"], vec!["upper"]), + (json!({"top": {"count": 2, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]), + (json!({"aboveAverage": true}), vec!["low", "mid", "upper"], vec![]), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"], vec!["low", "mid", "upper"]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Amount", "Job"], ["low", 10, "low"], ["mid", 20, "mid"], ["upper", 30, "upper"], ["high", 100, "high"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "A1:C5"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": names})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + // A and B both remain active when enumerating C. Subset statistics produce different jobs. + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 2).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}"); + } +} + #[test] fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() { let mut s = Session::new(); @@ -176,7 +206,8 @@ fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { s.new_workbook(); assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); assert!(filter_values(&s.doc().unwrap().wb, 99, 0).is_empty()); - s.execute("range.setValues", json!({"range": "B1048574", "values": [["Company", "Job"], ["East", "Last East"], ["West", "Last West"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "B1048574", "values": [["Company", "Job"], ["West", "Before last"], ["East", "Last East"]]})) + .unwrap(); s.execute("data.filter", json!({"range": "B1048574:C1048576"})).unwrap(); s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 4c91e58ac4..23f03a14f0 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,6 +1,7 @@ //! The crate's integration tests, one module per file, built as one test binary. mod autofit_filter_buttons; +mod cascading_filter_values; mod cf_formula_validate; mod chart_area_stacked100; mod chart_workbook_names; diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 2f9a1ba6eb..1cdf58390c 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -3326,7 +3326,6 @@ fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool) } } let wb = app.session.active().map(|d| d.wb.clone()).unwrap_or(wb); - let values = gridcraft_engine::cmd::data::filter_values(&wb, si, col); let key = egui::Id::unique(("filter_sel", col)); let search_key = egui::Id::unique(("filter_search", col)); let buttons_key = egui::Id::unique(("filter_buttons", col)); @@ -3352,7 +3351,10 @@ fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_open: bool) } ui.separator(); ui.label(egui::RichText::new("Filter").strong()); - let mut checks: Vec<(String, bool)> = ui.ctx().data_mut(|d| d.get_temp::>(key)).unwrap_or(values.clone()); + let mut checks: Vec<(String, bool)> = ui + .ctx() + .data_mut(|d| d.get_temp::>(key)) + .unwrap_or_else(|| gridcraft_engine::cmd::data::filter_values(&wb, si, col)); // A search narrows the list; Select All and Apply then only cover the matches. let mut search: String = ui.ctx().data_mut(|d| d.get_temp(search_key)).unwrap_or_default(); let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text("Search").desired_width(f32::INFINITY)); diff --git a/crates/ui-egui/tests/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs similarity index 98% rename from crates/ui-egui/tests/cascading_filter_values.rs rename to crates/ui-egui/tests/it/cascading_filter_values.rs index c217d35fc4..0b4e2259bc 100644 --- a/crates/ui-egui/tests/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -1,5 +1,4 @@ -#[path = "common/mod.rs"] -mod common; +use crate::common; use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::Queryable; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 53625015ed..b8fa0baa11 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -11,6 +11,7 @@ mod advanced_filter; mod argument_names; mod autosave_persist; mod borders; +mod cascading_filter_values; mod cell_editor_caret; mod cell_pictures; mod cf_rule_pick; From 19bc9660ff3898c8e0540c38b1e30e508a3b6386 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:29:31 +0100 Subject: [PATCH 42/95] Tests: header_autofit reads the active sheet through Workbook::active_sheet() Main now keeps the active sheet in an ActiveSheet; the test took the field as an index. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/header_autofit.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/header_autofit.rs b/crates/ui-egui/tests/it/header_autofit.rs index e53dbf617f..7a1f4ad6b9 100644 --- a/crates/ui-egui/tests/it/header_autofit.rs +++ b/crates/ui-egui/tests/it/header_autofit.rs @@ -187,7 +187,7 @@ fn table_filter_autofit_works_through_command_and_header_double_click() { // wherever the font is installed. let wb = &app.session.active().unwrap().wb; let table = sheet.table_at(cell).expect("A1 is the table's header"); - let font = gridcraft_engine::tables::table_cell_style(wb, wb.active_sheet, table, cell).font; + let font = gridcraft_engine::tables::table_cell_style(wb, wb.active_sheet(), table, cell).font; assert!(font.bold, "the table style draws its header bold"); let text_width = gridcraft_ui_egui::theme::cell_text_width(&h.ctx, "Quarterly Revenue", &font, true) * geo.z; assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}"); From 843e09fb773f48941da33c757ffe9211ee98c795 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:18:00 -0500 Subject: [PATCH 43/95] Port the PivotTable keep-on-save code into the split passthrough modules --- crates/xlsx/src/passthrough.rs | 2 +- crates/xlsx/src/passthrough/read.rs | 71 --------------------------- crates/xlsx/src/passthrough/write.rs | 73 +++++++++++++++++++++++++++- crates/xlsx/src/pivot.rs | 2 +- 4 files changed, 74 insertions(+), 74 deletions(-) diff --git a/crates/xlsx/src/passthrough.rs b/crates/xlsx/src/passthrough.rs index 7e77c4805b..aefdd1f920 100644 --- a/crates/xlsx/src/passthrough.rs +++ b/crates/xlsx/src/passthrough.rs @@ -58,7 +58,7 @@ pub use read::KeptReader; pub use rebase::{SheetKept, rebase_links}; #[cfg(test)] pub(crate) use write::sheet_names_in; -pub use write::{KeptOut, SheetIds, workbook_elements, write_package_rels, write_workbook}; +pub use write::{KeptOut, SheetIds, finish_style_ids, workbook_elements, write_package_rels, write_workbook}; /// Most bytes kept for one workbook. pub const MAX_KEPT_TOTAL: usize = 256 * 1024 * 1024; diff --git a/crates/xlsx/src/passthrough/read.rs b/crates/xlsx/src/passthrough/read.rs index ce9cae730f..1d65e0a04e 100644 --- a/crates/xlsx/src/passthrough/read.rs +++ b/crates/xlsx/src/passthrough/read.rs @@ -571,77 +571,6 @@ fn style_refs(cx: &Ctx<'_>, data: &[u8]) -> Option { Some((dxfs, fmts)) } -/// Rewrites the values of `dxfId` and `numFmtId` attributes through the maps (ids not in a map -/// are kept). `None` when the XML is damaged. -fn map_style_ids(data: &[u8], dxfs: &HashMap, fmts: &HashMap) -> Option> { - let text = xml::to_utf8(data); - let mut reader = Reader::from_reader(text.as_ref()); - let mut writer = Writer::new(Vec::with_capacity(data.len())); - let mut buf = vec![]; - let map = |e: &BytesStart<'_>| -> Option> { - let name = String::from_utf8(e.name().as_ref().to_vec()).ok()?; - let mut out = BytesStart::new(name); - for a in e.attributes().with_checks(false) { - let a = a.ok()?; - let k = a.key.local_name(); - let table = match k.as_ref() { - b"dxfId" => Some(dxfs), - b"numFmtId" => Some(fmts), - _ => None, - }; - let new = table.and_then(|t| std::str::from_utf8(&a.value).ok()?.trim().parse::().ok().and_then(|id| t.get(&id))); - match new { - Some(n) => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(n.to_string().into_bytes()) }), - None => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(a.value.to_vec()) }), - } - } - Some(out) - }; - loop { - match reader.read_event_into(&mut buf).ok()? { - Event::Eof => break, - Event::Start(e) => writer.write_event(Event::Start(map(&e)?)).ok()?, - Event::Empty(e) => writer.write_event(Event::Empty(map(&e)?)).ok()?, - ev => writer.write_event(ev).ok()?, - } - buf.clear(); - } - Some(writer.into_inner()) -} - -/// Kept parts whose style ids are renumbered once the styles part is written. -#[derive(Default)] -pub struct StylePatches { - /// (written part name, source bytes, dxf id map, source number format id → code). - list: Vec<(String, Arc<[u8]>, HashMap, Vec<(u32, String)>)>, -} - -impl KeptOut { - /// Number format codes kept parts refer to (to be registered in the styles part). - pub fn num_fmt_codes(&self) -> Vec { - let mut v: Vec = vec![]; - for (_, _, _, fmts) in &self.patches.list { - for (_, code) in fmts { - if !v.contains(code) { - v.push(code.clone()); - } - } - } - v - } -} - -/// Renumbers the `dxfId` and `numFmtId` attributes of kept PivotTables and pivot caches to the -/// written styles part. `fmt_id` maps a number format code to its id there. -pub fn finish_style_ids(out: &mut Out, fmt_id: &dyn Fn(&str) -> Option) { - for (name, data, dxfs, fmts) in std::mem::take(&mut out.kept.patches.list) { - let fmts: HashMap = fmts.iter().filter_map(|(old, code)| Some((*old, fmt_id(code)?))).collect(); - if let Some(x) = map_style_ids(&data, &dxfs, &fmts) { - out.replace(&name, x); - } - } -} - /// What a sheet part holds for pass-through. struct SheetScan { /// (slot, XML with the namespace declarations it needs). diff --git a/crates/xlsx/src/passthrough/write.rs b/crates/xlsx/src/passthrough/write.rs index dffe0a2ffb..0ebc997dca 100644 --- a/crates/xlsx/src/passthrough/write.rs +++ b/crates/xlsx/src/passthrough/write.rs @@ -14,7 +14,7 @@ pub struct KeptOut { root: Vec<(String, String, bool)>, /// Names of the workbook's kept parts, which sheets' kept parts can refer to (the cache of a /// kept PivotTable). - wb_names: NameMap, + pub(super) wb_names: NameMap, patches: StylePatches, } @@ -58,6 +58,77 @@ impl KeptOut { } } +/// Rewrites the values of `dxfId` and `numFmtId` attributes through the maps (ids not in a map +/// are kept). `None` when the XML is damaged. +fn map_style_ids(data: &[u8], dxfs: &HashMap, fmts: &HashMap) -> Option> { + let text = xml::to_utf8(data); + let mut reader = Reader::from_reader(text.as_ref()); + let mut writer = Writer::new(Vec::with_capacity(data.len())); + let mut buf = vec![]; + let map = |e: &BytesStart<'_>| -> Option> { + let name = String::from_utf8(e.name().as_ref().to_vec()).ok()?; + let mut out = BytesStart::new(name); + for a in e.attributes().with_checks(false) { + let a = a.ok()?; + let k = a.key.local_name(); + let table = match k.as_ref() { + b"dxfId" => Some(dxfs), + b"numFmtId" => Some(fmts), + _ => None, + }; + let new = table.and_then(|t| std::str::from_utf8(&a.value).ok()?.trim().parse::().ok().and_then(|id| t.get(&id))); + match new { + Some(n) => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(n.to_string().into_bytes()) }), + None => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(a.value.to_vec()) }), + } + } + Some(out) + }; + loop { + match reader.read_event_into(&mut buf).ok()? { + Event::Eof => break, + Event::Start(e) => writer.write_event(Event::Start(map(&e)?)).ok()?, + Event::Empty(e) => writer.write_event(Event::Empty(map(&e)?)).ok()?, + ev => writer.write_event(ev).ok()?, + } + buf.clear(); + } + Some(writer.into_inner()) +} + +/// Kept parts whose style ids are renumbered once the styles part is written. +#[derive(Default)] +pub struct StylePatches { + /// (written part name, source bytes, dxf id map, source number format id → code). + pub(super) list: Vec<(String, Arc<[u8]>, HashMap, Vec<(u32, String)>)>, +} + +impl KeptOut { + /// Number format codes kept parts refer to (to be registered in the styles part). + pub fn num_fmt_codes(&self) -> Vec { + let mut v: Vec = vec![]; + for (_, _, _, fmts) in &self.patches.list { + for (_, code) in fmts { + if !v.contains(code) { + v.push(code.clone()); + } + } + } + v + } +} + +/// Renumbers the `dxfId` and `numFmtId` attributes of kept PivotTables and pivot caches to the +/// written styles part. `fmt_id` maps a number format code to its id there. +pub fn finish_style_ids(out: &mut Out, fmt_id: &dyn Fn(&str) -> Option) { + for (name, data, dxfs, fmts) in std::mem::take(&mut out.kept.patches.list) { + let fmts: HashMap = fmts.iter().filter_map(|(old, code)| Some((*old, fmt_id(code)?))).collect(); + if let Some(x) = map_style_ids(&data, &dxfs, &fmts) { + out.replace(&name, x); + } + } +} + /// Original part name (normalized) → written part name. pub(super) type NameMap = HashMap; diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 14575db642..593ffe0320 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -37,7 +37,7 @@ use crate::xml::{El, esc_attr}; mod read; mod write; -pub use read::{CachesIn, ExternalPivot, KeptSource, SheetPivots, read_pivots}; +pub use read::{CachesIn, ExternalPivot, KeptSource, read_pivots}; pub use write::PivotWriter; pub const CT_PIVOT_TABLE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml"; From 0b31398c0d359afc539cd28f2a2a2a3bda173ab0 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:20:32 -0500 Subject: [PATCH 44/95] Filter: a table filter must reach the table's last data row, and the table part keeps only such filters --- crates/engine/src/cmd/data/filter.rs | 3 +++ crates/xlsx/src/sheet_write/parts.rs | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 59643755b5..f56f9252b4 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -75,6 +75,9 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { } // A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them. if let Some(t) = host.and_then(|i| sh.tables.get(i)) { + if t.data_range().is_some_and(|data| r.end.row < data.end.row) { + return Err(bad("data.filter", "filter the table's full data range")); + } let shift = r.start.col.saturating_sub(t.range.start.col); if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) { return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width")); diff --git a/crates/xlsx/src/sheet_write/parts.rs b/crates/xlsx/src/sheet_write/parts.rs index 579733d6c3..87e0184655 100644 --- a/crates/xlsx/src/sheet_write/parts.rs +++ b/crates/xlsx/src/sheet_write/parts.rs @@ -107,8 +107,12 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion) /// as rows hidden by hand, which SUBTOTAL 1-11 counts. pub(super) fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterion)> { let mut criteria = t.filter.clone(); - let Some(af) = sheet.autofilter.as_ref().filter(|af| t.header_row && af.range.start.row == t.range.start.row && af.range.intersects(&t.range)) - else { + let Some(af) = sheet.autofilter.as_ref().filter(|af| { + t.header_row + && af.range.start.row == t.range.start.row + && af.range.intersects(&t.range) + && t.data_range().is_some_and(|d| af.range.end.row >= d.end.row) + }) else { return criteria; }; for (off, c) in &af.criteria { From 2e1a744c6cfbbc4c7799a19727c0712390cd4d27 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:24:32 -0500 Subject: [PATCH 45/95] Filter: turning a table's filter buttons off also drops the sheet AutoFilter on it, and a disabled table filter saves no criteria --- crates/engine/src/cmd/data/filter.rs | 12 ++++++++++++ crates/xlsx/src/sheet_write/parts.rs | 3 ++- crates/xlsx/src/tests/tablefilter.rs | 12 ++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index f56f9252b4..6d8c6ea95f 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -13,10 +13,22 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { if let Some(name) = in_table { return edit(s, |cx| { let sh = cx.sheet_mut(sheet)?; + let filtered: Vec = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect(); + let mut cleared = false; if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) { t.filter_button = !t.filter_button; if !t.filter_button { t.filter.clear(); + // The sheet AutoFilter hosted on this table's header row is the table's filter too. + cleared = sh.autofilter.as_ref().is_some_and(|af| af.range.start.row == t.range.start.row && af.range.intersects(&t.range)); + } + } + if cleared { + sh.autofilter = None; + for r in filtered { + if let Some(info) = sh.rows.get_mut(&r) { + info.hidden = false; + } } } Ok(Json::Null) diff --git a/crates/xlsx/src/sheet_write/parts.rs b/crates/xlsx/src/sheet_write/parts.rs index 87e0184655..eb348df707 100644 --- a/crates/xlsx/src/sheet_write/parts.rs +++ b/crates/xlsx/src/sheet_write/parts.rs @@ -109,6 +109,7 @@ pub(super) fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterio let mut criteria = t.filter.clone(); let Some(af) = sheet.autofilter.as_ref().filter(|af| { t.header_row + && t.filter_button && af.range.start.row == t.range.start.row && af.range.intersects(&t.range) && t.data_range().is_some_and(|d| af.range.end.row >= d.end.row) @@ -144,7 +145,7 @@ pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter: let _ = write!(s, " connectionId=\"{c}\""); } s.push('>'); - if t.header_row && (t.filter_button || !filter.is_empty()) { + if t.header_row && t.filter_button { let end_row = if t.totals_row { t.range.end.row.saturating_sub(1).max(t.range.start.row) } else { t.range.end.row }; let r = RangeRef::new(t.range.start, CellRef::new(end_row, t.range.end.col)); s.push_str(&autofilter_xml(r, filter, out)); diff --git a/crates/xlsx/src/tests/tablefilter.rs b/crates/xlsx/src/tests/tablefilter.rs index 784361b7fd..e8e9ff906d 100644 --- a/crates/xlsx/src/tests/tablefilter.rs +++ b/crates/xlsx/src/tests/tablefilter.rs @@ -100,3 +100,15 @@ fn sheet_autofilter_not_on_the_header_row_is_not_folded() { let cols: Vec = s.tables[0].filter.iter().map(|(c, _)| *c).collect(); assert_eq!(cols, [1], "only the table's own criterion"); } + +#[test] +fn disabled_table_filter_saves_no_autofilter_criteria() { + let mut wb = filtered("B2:C6", 0); + if let Some(t) = wb.sheet_mut(0).unwrap().tables.first_mut() { + t.filter_button = false; + t.filter.clear(); + } + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let t = &back.sheet(0).unwrap().tables[0]; + assert!(!t.filter_button && t.filter.is_empty(), "{:?}", t.filter); +} From 2cdffc628296f4681195207caf50f1f1bed591e3 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:45:35 -0500 Subject: [PATCH 46/95] XLSX: drop kept PivotTables that name a dropped cache by id; hash sets for style references --- crates/xlsx/src/passthrough/read.rs | 10 ++++++---- crates/xlsx/src/passthrough/rebase.rs | 13 +++++++++++-- crates/xlsx/src/passthrough/write.rs | 4 ++++ crates/xlsx/src/tests/passthrough_tests.rs | 21 ++++++++++++++++++++- 4 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/xlsx/src/passthrough/read.rs b/crates/xlsx/src/passthrough/read.rs index 1d65e0a04e..36bfc7c5d3 100644 --- a/crates/xlsx/src/passthrough/read.rs +++ b/crates/xlsx/src/passthrough/read.rs @@ -554,16 +554,18 @@ type StyleRefs = (Vec<(u32, gridcraft_model::Style)>, Vec<(u32, String)>); fn style_refs(cx: &Ctx<'_>, data: &[u8]) -> Option { let mut dxfs: Vec<(u32, gridcraft_model::Style)> = vec![]; let mut fmts: Vec<(u32, String)> = vec![]; + // Membership sets: a crafted part can name many distinct ids, so scanning the vectors would be quadratic. + let (mut seen_dxfs, mut seen_fmts) = (HashSet::new(), HashSet::new()); attr_values(data, &[b"dxfId", b"numFmtId"], |name, v| { let Ok(id) = v.trim().parse::() else { return }; if name == b"dxfId" { - if !dxfs.iter().any(|(i, _)| *i == id) - && let Some(s) = cx.dxfs.get(id as usize) + if let Some(s) = cx.dxfs.get(id as usize) + && seen_dxfs.insert(id) { dxfs.push((id, s.clone())); } - } else if !fmts.iter().any(|(i, _)| *i == id) - && let Some(code) = cx.num_fmts.get(&id) + } else if let Some(code) = cx.num_fmts.get(&id) + && seen_fmts.insert(id) { fmts.push((id, code.clone())); } diff --git a/crates/xlsx/src/passthrough/rebase.rs b/crates/xlsx/src/passthrough/rebase.rs index 9de3388a2b..a80717d60c 100644 --- a/crates/xlsx/src/passthrough/rebase.rs +++ b/crates/xlsx/src/passthrough/rebase.rs @@ -14,11 +14,20 @@ impl<'a> SheetKept<'a> { pub fn write(sheet: &'a Sheet, rels: &mut Rels, out: &mut Out) -> SheetKept<'a> { let Some(p) = sheet.preserved.as_deref() else { return SheetKept { p: None, names: NameMap::new(), ids: HashMap::new() } }; // A kept PivotTable whose cache wasn't kept with the workbook is left out. - let wb_names = &out.kept.wb_names; + let (wb_names, cache_ids) = (&out.kept.wb_names, &out.kept.cache_ids); let orphan: HashSet = p .parts .iter() - .filter(|q| q.rels.iter().any(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]) && !wb_names.contains_key(&normalize(&r.target)))) + .filter(|q| { + let direct = q.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"])); + // A table with no relationship to its cache names it by `cacheId` instead. + let by_id = || { + q.content_type == CT_PIVOT_TABLE + && crate::xml::parse(&q.data).ok().and_then(|x| x.attr_u32("cacheId")).is_some_and(|id| !cache_ids.contains(&id)) + }; + let mut direct = direct.peekable(); + if direct.peek().is_some() { direct.any(|r| !wb_names.contains_key(&normalize(&r.target))) } else { by_id() } + }) .map(|q| normalize(&q.name)) .collect(); let (parts, sheet_rels): (Cow<'_, [PreservedPart]>, Cow<'_, [PreservedRel]>) = if orphan.is_empty() { diff --git a/crates/xlsx/src/passthrough/write.rs b/crates/xlsx/src/passthrough/write.rs index 0ebc997dca..189edd885a 100644 --- a/crates/xlsx/src/passthrough/write.rs +++ b/crates/xlsx/src/passthrough/write.rs @@ -15,6 +15,9 @@ pub struct KeptOut { /// Names of the workbook's kept parts, which sheets' kept parts can refer to (the cache of a /// kept PivotTable). pub(super) wb_names: NameMap, + /// The `cacheId`s of the workbook's kept pivot caches: a kept PivotTable that names its cache + /// only by id is written only when its cache is among them. + pub(super) cache_ids: HashSet, patches: StylePatches, } @@ -416,6 +419,7 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb }) .collect(); out.kept.wb_names = names; + out.kept.cache_ids = pivot_caches.iter().map(|(id, _)| *id).collect(); WorkbookKept { pivot_caches, elements: p.elements.iter().filter(|e| e.slot == "externalReferences").filter_map(|e| remap(&e.xml, &ids)).collect(), diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index cc63bda783..2ac287d523 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -1210,9 +1210,12 @@ struct ConnPkg { connections_blocked: bool, /// The connection the Data Model cache names. model_connection: u32, + /// The PivotTables have relationships to their caches (otherwise they name them by `cacheId`). + table_rels: bool, } -const CONN_PKG: ConnPkg = ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1 }; +const CONN_PKG: ConnPkg = + ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1, table_rels: true }; /// Sheet "Report" with a PivotTable on the Data Model (cache 3) and sheet "More" with one on the /// plain connection (cache 4, with records), plus the hidden name a worksheet connection uses. @@ -1281,6 +1284,9 @@ fn conn_pivot_package(o: ConnPkg) -> Vec { ("xl/pivotCache/_rels/pivotCacheDefinition2.xml.rels", c2_rels.as_bytes()), ("xl/pivotCache/pivotCacheRecords2.xml", CONN_RECORDS.as_bytes()), ]; + if !o.table_rels { + parts.retain(|(name, _)| !name.starts_with("xl/pivotTables/_rels/")); + } if o.connections { parts.push(("xl/connections.xml", MODEL_CONNECTIONS.as_bytes())); } @@ -1400,6 +1406,19 @@ fn data_model_pivot_tables_without_the_model_are_kept_as_plain_cells() { } } +#[test] +fn pivot_tables_naming_their_cache_by_id_go_with_a_dropped_cache() { + // No connections part: both caches are dropped, and the tables that name them only by + // `cacheId` must not stay behind with an id the workbook no longer lists. + let (wb, _) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, table_rels: false, ..CONN_PKG })).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + for sheet in ["Report", "More"] { + assert!(written_pivot_tables(&u, sheet).is_empty(), "{sheet}"); + } + assert!(written_pivot_caches(&u).is_empty()); +} + #[test] fn connection_pivot_tables_need_their_connections() { // No connections part: the caches name connections that aren't there. From be8efa6d0bb49abebacda982a0dbbf177f1cf7d9 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:46:18 -0500 Subject: [PATCH 47/95] Filter: turning a table's filter off keeps rows another table's criteria still hide --- crates/engine/src/cmd/data/filter.rs | 5 +++- .../tests/it/subtotal_filter_roundtrip.rs | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 6d8c6ea95f..abfc70cdce 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -26,7 +26,10 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { if cleared { sh.autofilter = None; for r in filtered { - if let Some(info) = sh.rows.get_mut(&r) { + // Rows another table's criteria still hide stay hidden. + if !sh.is_row_filtered(r) + && let Some(info) = sh.rows.get_mut(&r) + { info.hidden = false; } } diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 4046713e17..14faa27262 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -164,3 +164,26 @@ fn a_sheet_filter_from_outside_a_table_leaves_the_table_out() { assert!(s.execute("data.filter", json!({"range":"A1:C8"})).is_err()); assert!(wb(&s).active().unwrap().autofilter.is_none()); } + +#[test] +fn turning_a_table_filter_off_keeps_rows_another_table_still_hides() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["K","V"],["k1",1],["k2",2],["k3",3],["k4",4],["k5",5]]})).unwrap(); + s.execute("range.setValues", json!({"range":"D1","values":[["X","Y"],["x1",1],["x2",2],["x3",3],["x4",4],["x5",5]]})).unwrap(); + s.execute("insert.table", json!({"range":"A1:B6","header":true})).unwrap(); + s.execute("insert.table", json!({"range":"D1:E6","header":true})).unwrap(); + // The second table's criteria are saved with it, so both tables hold a filter after reopening. + s.execute("selection.set", json!({"cell":"D2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap(); + let mut s2 = Session::new(); + s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s2.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s2.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap(); + s2.execute("data.filter", json!({})).unwrap(); + let sh = wb(&s2).active().unwrap(); + assert!(!sh.is_row_hidden(2), "only the first table hid row 3"); + for row in 3..6 { + assert!(sh.is_row_hidden(row), "row {} is still filtered out of the second table", row + 1); + } +} From d57d5cf2674fdfe7db152e458e2aa4e71374022a Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:57:20 -0500 Subject: [PATCH 48/95] XLSX: keep the cache of a kept PivotTable that names it only by cacheId --- crates/xlsx/src/passthrough/write.rs | 25 +++++++++++++++++----- crates/xlsx/src/tests/passthrough_tests.rs | 12 +++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/xlsx/src/passthrough/write.rs b/crates/xlsx/src/passthrough/write.rs index 189edd885a..c0a19658f3 100644 --- a/crates/xlsx/src/passthrough/write.rs +++ b/crates/xlsx/src/passthrough/write.rs @@ -379,14 +379,29 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb let (live, dropped): (Vec<&PreservedSheet>, Vec<&PreservedSheet>) = p.sheets.iter().partition(|s| chart_sheet_usable(wb, p, s)); let root_of = |s: &PreservedSheet| p.rels.iter().find(|r| r.id == s.rel_id); // Pivot caches no kept PivotTable of a sheet uses any more (their sheets were deleted). - let used_caches: HashSet = wb - .sheets - .iter() - .filter_map(|s| s.preserved.as_deref()) - .flat_map(|q| q.parts.iter().flat_map(|part| part.rels.iter())) + let sheet_parts = || wb.sheets.iter().filter_map(|s| s.preserved.as_deref()).flat_map(|q| q.parts.iter()); + let mut used_caches: HashSet = sheet_parts() + .flat_map(|part| part.rels.iter()) .filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"])) .map(|r| normalize(&r.target)) .collect(); + // A PivotTable can name its cache only by the workbook's `cacheId`. + let cache_of_id: HashMap = p + .elements + .iter() + .filter(|e| e.slot == "pivotCache") + .filter_map(|e| { + let x = xml::parse(e.xml.as_bytes()).ok()?; + let rel = p.rels.iter().find(|r| Some(r.id.as_str()) == x.attr("id"))?; + Some((x.attr_u32("cacheId")?, normalize(&rel.target))) + }) + .collect(); + used_caches.extend( + sheet_parts() + .filter(|part| part.content_type == CT_PIVOT_TABLE) + .filter_map(|part| xml::parse(&part.data).ok()?.attr_u32("cacheId")) + .filter_map(|id| cache_of_id.get(&id).cloned()), + ); let unused_caches: Vec<&PreservedRel> = p.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]) && !used_caches.contains(&normalize(&r.target))).collect(); let mut dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect(); diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index 2ac287d523..e62e38cf4d 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -1419,6 +1419,18 @@ fn pivot_tables_naming_their_cache_by_id_go_with_a_dropped_cache() { assert!(written_pivot_caches(&u).is_empty()); } +#[test] +fn pivot_tables_naming_their_cache_by_id_keep_it() { + let (wb, _) = read_xlsx(&conn_pivot_package(ConnPkg { table_rels: false, ..CONN_PKG })).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + for sheet in ["Report", "More"] { + assert_eq!(written_pivot_tables(&u, sheet).len(), 1, "{sheet}"); + } + let caches = written_pivot_caches(&u); + assert_eq!(caches.iter().map(|c| c.0.as_str()).collect::>(), ["3", "4"], "{caches:?}"); +} + #[test] fn connection_pivot_tables_need_their_connections() { // No connections part: the caches name connections that aren't there. From 10115f41ed658691f79d7b299d15f66baa8f12ff Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:03:15 -0500 Subject: [PATCH 49/95] XLSX: name the type of the kept cache list --- crates/xlsx/src/passthrough/write.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xlsx/src/passthrough/write.rs b/crates/xlsx/src/passthrough/write.rs index c0a19658f3..b4d69977c0 100644 --- a/crates/xlsx/src/passthrough/write.rs +++ b/crates/xlsx/src/passthrough/write.rs @@ -424,7 +424,7 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb out.kept.root.push((r.rel_type.clone(), target, r.external)); } } - let pivot_caches = p + let pivot_caches: Vec<(u32, String)> = p .elements .iter() .filter(|e| e.slot == "pivotCache") From a2e3f265c0953b2f5b2048181d077172f363b222 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:12:04 -0500 Subject: [PATCH 50/95] Filter: turning a table's filter off re-evaluates the criteria of the tables that keep one --- crates/engine/src/cmd/data/filter.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index abfc70cdce..64cb958f7b 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -26,13 +26,23 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { if cleared { sh.autofilter = None; for r in filtered { - // Rows another table's criteria still hide stay hidden. - if !sh.is_row_filtered(r) - && let Some(info) = sh.rows.get_mut(&r) - { + if let Some(info) = sh.rows.get_mut(&r) { info.hidden = false; } } + // Rows another table's criteria hide stay hidden: evaluate each such table's + // saved criteria through the live filter, then take the filter off again. + let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> = + sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect(); + for (range, criteria) in others { + if let Some(sh) = cx.wb.sheet_mut(sheet) { + sh.autofilter = Some(AutoFilter { range, criteria }); + } + apply_filter(&mut cx.wb, sheet); + } + if let Some(sh) = cx.wb.sheet_mut(sheet) { + sh.autofilter = None; + } } Ok(Json::Null) }); From f3c214b2dd7d3a30363a91785127940a4d493ffb Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:23:24 -0500 Subject: [PATCH 51/95] Filter: turning a table's filter off hides the union of the other tables' excluded rows and recalculates --- crates/engine/src/cmd/data/filter.rs | 13 ++++++-- .../tests/it/subtotal_filter_roundtrip.rs | 31 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 64cb958f7b..f1214d61b6 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -30,19 +30,28 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { info.hidden = false; } } - // Rows another table's criteria hide stay hidden: evaluate each such table's - // saved criteria through the live filter, then take the filter off again. + // Rows another table's criteria hide stay hidden: evaluate each such table's saved + // criteria through the live filter, then hide the union once (a later table would + // unhide what an earlier one excluded) and take the filter off again. let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> = sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect(); + let mut excluded: std::collections::HashSet = std::collections::HashSet::new(); for (range, criteria) in others { if let Some(sh) = cx.wb.sheet_mut(sheet) { sh.autofilter = Some(AutoFilter { range, criteria }); } apply_filter(&mut cx.wb, sheet); + if let Some(sh) = cx.wb.sheet(sheet) { + excluded.extend((range.start.row.saturating_add(1)..=range.end.row).filter(|r| sh.is_row_hidden(*r))); + } } if let Some(sh) = cx.wb.sheet_mut(sheet) { sh.autofilter = None; + for r in excluded { + sh.rows.entry(r).or_default().hidden = true; + } } + cx.structural = true; } Ok(Json::Null) }); diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 14faa27262..54931640f9 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -187,3 +187,34 @@ fn turning_a_table_filter_off_keeps_rows_another_table_still_hides() { assert!(sh.is_row_hidden(row), "row {} is still filtered out of the second table", row + 1); } } + +#[test] +fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() { + let mut s = Session::new(); + s.new_workbook(); + for (col, keys) in [("A", "k"), ("D", "x"), ("G", "z")] { + let rows: Vec = (1..=5).map(|n| json!([format!("{keys}{n}"), n])).collect(); + s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [json!(["K", "V"])].into_iter().chain(rows).collect::>()})) + .unwrap(); + } + for range in ["A1:B6", "D1:E6", "G1:H6"] { + s.execute("insert.table", json!({"range": range, "header": true})).unwrap(); + } + // Each filtered table's criteria are saved with it: reopening leaves both holding a filter. + s.execute("selection.set", json!({"cell":"D2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap(); + let mut s2 = Session::new(); + s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s2.execute("selection.set", json!({"cell":"G2"})).unwrap(); + s2.execute("data.filterBy", json!({"column":"G","values":["z1","z3"]})).unwrap(); + let mut s3 = Session::new(); + s3.add_document(gridcraft_engine::DocState::new(reopened(wb(&s2)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s3.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s3.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap(); + s3.execute("data.filter", json!({})).unwrap(); + let sh = wb(&s3).active().unwrap(); + assert!(!sh.is_row_hidden(1)); + for row in 2..6 { + assert!(sh.is_row_hidden(row), "row {} is excluded by one of the two other tables", row + 1); + } +} From 7b83509a93b27c3efd4be44598545d3dbd8e741a Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:28:43 -0500 Subject: [PATCH 52/95] Filter test: build the table rows outside json! so the test compiles --- crates/engine/tests/it/subtotal_filter_roundtrip.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 54931640f9..ddc868701a 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -193,9 +193,9 @@ fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() { let mut s = Session::new(); s.new_workbook(); for (col, keys) in [("A", "k"), ("D", "x"), ("G", "z")] { - let rows: Vec = (1..=5).map(|n| json!([format!("{keys}{n}"), n])).collect(); - s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [json!(["K", "V"])].into_iter().chain(rows).collect::>()})) - .unwrap(); + let mut values = vec![json!(["K", "V"])]; + values.extend((1..=5).map(|n| json!([format!("{keys}{n}"), n]))); + s.execute("range.setValues", json!({"range": format!("{col}1"), "values": values})).unwrap(); } for range in ["A1:B6", "D1:E6", "G1:H6"] { s.execute("insert.table", json!({"range": range, "header": true})).unwrap(); From dbacb4cc80ebe27eafd67c44528eb01b52c3887f Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:33:24 -0500 Subject: [PATCH 53/95] Filter: refuse a partial range over the active table; filtering a table re-enables its buttons --- crates/engine/src/cmd/data/filter.rs | 15 ++++++++++++++ .../tests/it/subtotal_filter_roundtrip.rs | 20 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index f1214d61b6..641314ceb8 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -11,6 +11,19 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { let has = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.autofilter.is_some()); let in_table = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.table_at(at).map(|t| t.name.clone())); if let Some(name) = in_table { + // An explicit range over part of the table is refused, as when installing a filter on it. + if p.get("range").is_some() + && let Some(sh) = s.doc()?.wb.sheet(sheet) + && let Some(t) = sh.tables.iter().find(|t| t.name == name) + && t.range.intersects(&r) + && !(t.header_row + && t.range.start.row == r.start.row + && t.range.contains(r.start) + && t.range.contains(r.end) + && t.data_range().is_none_or(|data| r.end.row >= data.end.row)) + { + return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); + } return edit(s, |cx| { let sh = cx.sheet_mut(sheet)?; let filtered: Vec = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect(); @@ -121,6 +134,8 @@ fn install_filter(s: &mut Session, p: &Json) -> Result { let sh = cx.sheet_mut(sheet)?; let mut criteria = vec![]; if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) { + // The criteria are saved with the table only while its filter buttons are on. + t.filter_button = true; let shift = r.start.col.saturating_sub(t.range.start.col); criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect(); } diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs index 54931640f9..f3379959b4 100644 --- a/crates/engine/tests/it/subtotal_filter_roundtrip.rs +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -218,3 +218,23 @@ fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() { assert!(sh.is_row_hidden(row), "row {} is excluded by one of the two other tables", row + 1); } } + +#[test] +fn filtering_a_table_whose_buttons_were_turned_off_turns_them_back_on() { + let mut s = table_book(); + s.execute("data.filter", json!({})).unwrap(); + assert!(!wb(&s).active().unwrap().tables[0].filter_button); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + assert!(wb(&s).active().unwrap().tables[0].filter_button); + let back = reopened(wb(&s)); + assert_eq!(back.active().unwrap().tables[0].filter.len(), 1, "the criteria are saved with the table"); +} + +#[test] +fn a_partial_range_inside_the_active_table_is_refused_not_a_toggle() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err()); + let sh = wb(&s).active().unwrap(); + assert!(sh.tables[0].filter_button && sh.autofilter.is_some(), "the filter is untouched"); +} From cf17534e7bb85041b5f10098aefcfa0623b97f68 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:47:30 -0500 Subject: [PATCH 54/95] Filter test: the sheet-prefix table toggle names the whole table, as a partial range over a table is refused --- crates/engine/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13fbb9b3a4..b82dc1d91e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1501,7 +1501,7 @@ fn filter_with_a_sheet_prefix_toggles_the_table_at_the_range() { wb.sheet(wb.sheet_index("Prices").unwrap()).unwrap().clone() }; assert!(prices(&s).tables[0].filter_button); - s.execute("data.filter", json!({"range": "Prices!A2:B3"})).unwrap(); + s.execute("data.filter", json!({"range": "Prices!A1:B3"})).unwrap(); assert!(!prices(&s).tables[0].filter_button); assert!(prices(&s).autofilter.is_none()); assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none()); From cc3858a394e14d78d88e1a64d65bbf5a6d8a1d7c Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:01:50 -0500 Subject: [PATCH 55/95] Filter: a range over only some of the active table's columns is refused too --- crates/engine/src/cmd/data/filter.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 641314ceb8..4bdbbe22fa 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -20,6 +20,8 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end) + && r.start.col == t.range.start.col + && r.end.col == t.range.end.col && t.data_range().is_none_or(|data| r.end.row >= data.end.row)) { return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); From b4b89a4e3624c404b46fa251ebcb27ba93c6707a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 04:03:37 -0700 Subject: [PATCH 56/95] Charts: Format Chart Area's Chart Type offers 100% Stacked Line with Markers The pane's Chart Type section listed 100% Stacked Line but not its marker variant, so a chart of that type showed no current type there and could not be changed to it from the pane. --- crates/ui-egui/src/panes.rs | 1 + crates/ui-egui/tests/it/format_chart_type.rs | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 54fa9ac02f..a21c69243b 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -193,6 +193,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) { ("Line", "line", "markers"), ("Stacked Line", "line", "stacked"), ("100% Stacked Line", "line", "stacked100"), + ("100% Stacked Line with Markers", "line", "stacked100Markers"), ("Area", "area", ""), ("Stacked Area", "area", "stacked"), ("100% Stacked Area", "area", "stacked100"), diff --git a/crates/ui-egui/tests/it/format_chart_type.rs b/crates/ui-egui/tests/it/format_chart_type.rs index ae19e1091d..b9ef69da4b 100644 --- a/crates/ui-egui/tests/it/format_chart_type.rs +++ b/crates/ui-egui/tests/it/format_chart_type.rs @@ -89,3 +89,14 @@ fn chart_type_marks_the_chart_s_current_type() { } } } + +#[test] +fn chart_type_offers_and_marks_the_hundred_percent_stacked_line_types() { + let (mut h, id) = open_chart_type("line", "stacked100Markers"); + assert!(marked(&h, "100% Stacked Line with Markers")); + assert!(!marked(&h, "100% Stacked Line")); + click(&mut h, "100% Stacked Line"); + assert_eq!(kind(&h, id), ChartKind::LineStacked100); + click(&mut h, "100% Stacked Line with Markers"); + assert_eq!(kind(&h, id), ChartKind::LineStacked100Markers); +} From 8e81dade3359433ad10d168afc37c0aab5ac5c5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:04:36 -0700 Subject: [PATCH 57/95] XLSX: combo charts keep 100% stacked line series and their order when saved A combo chart's 100% stacked line series were saved in the plain line group and reopened as ordinary lines. They now share one percentStacked group, each with its own markers, and reopening a combo chart puts its series back in their c:order order. --- crates/xlsx/src/chart.rs | 34 ++++++++++++++++--- .../src/tests/chart_line_percent_stacked.rs | 29 ++++++++++++++-- 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index a174a9dae1..dccbb60f55 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -228,19 +228,28 @@ pub fn read_chart(root: &El) -> Option { let (first, first_kind) = *groups.first()?; let first_axes = axis_ids(first); let mut series = vec![]; + let mut orders = vec![]; for (gi, (g, k)) in groups.iter().enumerate() { for s in g.kids("ser") { let mut ser = read_series(s); if groups.len() > 1 { // Every series of a combo chart keeps its own group's kind, the first group's included. - ser.kind = Some(*k); + let no_marker = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); + ser.kind = Some(if *k == ChartKind::LineStacked100Markers && no_marker { ChartKind::LineStacked100 } else { *k }); } if gi > 0 { ser.secondary = axis_ids(g) != first_axes; } + orders.push(s.child_val("order").and_then(|v| v.trim().parse::().ok())); series.push(ser); } } + // A combo chart lists its series group by group; `c:order` gives the order they are drawn in. + if groups.len() > 1 && orders.iter().all(Option::is_some) { + let mut keyed: Vec<(Option, Series)> = orders.into_iter().zip(series).collect(); + keyed.sort_by_key(|(o, _)| *o); + series = keyed.into_iter().map(|(_, s)| s).collect(); + } let kind = if groups.len() > 1 { ChartKind::Combo } else { first_kind }; let show_val = |e: &El| e.child("dLbls").is_some_and(|d| bool_val(d, "showVal")); let data_labels = groups.iter().any(|(g, _)| show_val(g) || g.kids("ser").any(show_val)); @@ -663,7 +672,17 @@ fn dlbls(show: bool) -> String { } fn group_xml(g: G, series: &[(usize, &Series)], ch: &Chart, axes: (u32, u32), wb: &Workbook, si: usize) -> String { - let sers: String = series.iter().map(|(i, s)| series_xml(s, *i, g, wb, si)).collect(); + let sers: String = series + .iter() + .map(|(i, s)| { + // In a combo chart's 100% stacked line group, each series writes its own markers. + let sg = match (g, s.kind.map(group_for)) { + (G::Line100 { .. }, Some(own @ G::Line100 { .. })) if ch.kind == ChartKind::Combo => own, + _ => g, + }; + series_xml(s, *i, sg, wb, si) + }) + .collect(); let dl = dlbls(ch.data_labels); let ax = format!("", axes.0, axes.1); match g { @@ -787,8 +806,15 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str if !bars.is_empty() || (lines.is_empty() && sec.is_empty()) { s.push_str(&group_xml(primary_g, &bars, ch, (1, 2), wb, si)); } - if !lines.is_empty() { - s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &lines, ch, (1, 2), wb, si)); + // 100% stacked line series share one percentStacked group, each with its own markers. + let pct = |i: usize, x: &Series| matches!(kind(i, x).map(group_for), Some(G::Line100 { .. })); + let plain: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); + let stacked: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); + if !plain.is_empty() { + s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &plain, ch, (1, 2), wb, si)); + } + if !stacked.is_empty() { + s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); } if !sec.is_empty() { let g = match sec.first().and_then(|(_, x)| x.kind).map(group_for) { diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 87c16a4acf..5ecba4049c 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -35,7 +35,7 @@ fn standard_and_stacked_lines_keep_their_kinds() { } #[test] -fn a_hundred_percent_stacked_line_series_in_a_combo_chart_is_saved_as_a_line() { +fn a_hundred_percent_stacked_line_series_in_a_combo_chart_keeps_its_kind_when_saved() { let ser = |i: usize| format!("Data!$A$1:$A$5"); let xml = format!( @@ -53,5 +53,30 @@ fn a_hundred_percent_stacked_line_series_in_a_combo_chart_is_saved_as_a_line() { let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); let kinds: Vec> = again.series.iter().map(|s| s.kind).collect(); assert_eq!(kinds.first(), Some(&Some(ChartKind::ColumnClustered)), "{saved}"); - assert!(kinds.get(1).is_some_and(|k| !matches!(k, Some(ChartKind::ColumnClustered))), "the line series stays out of the column group: {saved}"); + assert_eq!(kinds, [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers)], "{saved}"); +} + +#[test] +fn combo_line_series_keep_their_kinds_order_and_shared_percent_stack_when_saved() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + {}{}\ + ", + ser(0, ""), + ser(2, NO_MARKER), + ser(1, ""), + ser(3, NO_MARKER) + ); + let want = [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers), Some(ChartKind::Line), Some(ChartKind::LineStacked100)]; + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.series.iter().map(|s| s.kind).collect::>(), want); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + assert_eq!(saved.matches("percentStacked").count(), 1, "both 100% stacked series share one stack: {saved}"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); } From 4550a1eba7df4381b59612e5c18984e291a7ff33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:10:02 -0700 Subject: [PATCH 58/95] XLSX: 100% stacked lines on a combo chart's secondary axis keep their kind when saved --- crates/xlsx/src/chart.rs | 19 ++++++++++++------ .../src/tests/chart_line_percent_stacked.rs | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index dccbb60f55..17c945eac5 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -817,12 +817,19 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); } if !sec.is_empty() { - let g = match sec.first().and_then(|(_, x)| x.kind).map(group_for) { - Some(b @ G::Bar { .. }) => b, - _ => G::Line { stacked: false, markers: false }, - }; - s.push_str(&group_xml(g, &sec, ch, (3, 4), wb, si)); - secondary = Some(g); + if let Some(b @ G::Bar { .. }) = sec.first().and_then(|(_, x)| x.kind).map(group_for) { + s.push_str(&group_xml(b, &sec, ch, (3, 4), wb, si)); + secondary = Some(b); + } else { + let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); + let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); + for (g, members) in [(G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] { + if !members.is_empty() { + s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); + secondary.get_or_insert(g); + } + } + } } } else { primary_g = match group_for(ch.kind) { diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 5ecba4049c..b5c58faa5a 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -80,3 +80,23 @@ fn combo_line_series_keep_their_kinds_order_and_shared_percent_stack_when_saved( let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); } + +#[test] +fn a_hundred_percent_stacked_line_on_the_secondary_axis_keeps_its_kind_when_saved() { + let ser = + |i: usize| format!("Data!$A$1:$A$5"); + let xml = format!( + "\ + {}\ + {}\ + ", + ser(0), + ser(1) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert!(ch.series.get(1).is_some_and(|s| s.secondary && s.kind == Some(ChartKind::LineStacked100Markers))); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + let got: Vec<(Option, bool)> = again.series.iter().map(|s| (s.kind, s.secondary)).collect(); + assert_eq!(got, [(Some(ChartKind::ColumnClustered), false), (Some(ChartKind::LineStacked100Markers), true)], "{saved}"); +} From a6f9b80e43a7e9a5e60627a9ab784586a9e4349e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:39:04 -0700 Subject: [PATCH 59/95] Charts: move the marker check out of cartesian to keep it under the complexity limit --- crates/chart/src/render/cartesian.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index 99199deedd..fbb46e199e 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -53,6 +53,11 @@ fn is_line(f: Fam) -> bool { matches!(f, Fam::Line | Fam::LineStack | Fam::Line100) } +/// Line kinds that draw a marker at each point. +fn has_markers(k: ChartKind) -> bool { + matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers) +} + fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec>> { // Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart). let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); @@ -321,7 +326,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot)); let k = kinds.get(i).copied().unwrap_or(ChartKind::Line); - if matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers) && cw >= 3.0 { + if has_markers(k) && cw >= 3.0 { draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); } if labels_on { From 3adf6625787ec49257de67b30795761e417f589e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 06:49:07 -0700 Subject: [PATCH 60/95] XLSX: combo charts keep secondary columns, lines and 100% stacked lines in separate groups when saved --- crates/xlsx/src/chart.rs | 26 +++++++++------- .../src/tests/chart_line_percent_stacked.rs | 30 +++++++++++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 17c945eac5..2e611dcf59 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -817,17 +817,21 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); } if !sec.is_empty() { - if let Some(b @ G::Bar { .. }) = sec.first().and_then(|(_, x)| x.kind).map(group_for) { - s.push_str(&group_xml(b, &sec, ch, (3, 4), wb, si)); - secondary = Some(b); - } else { - let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); - let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); - for (g, members) in [(G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] { - if !members.is_empty() { - s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); - secondary.get_or_insert(g); - } + // Secondary bars, lines and 100% stacked lines each get their own group. + let bar_of = |x: &Series| match x.kind.map(group_for) { + Some(b @ G::Bar { .. }) => Some(b), + _ => None, + }; + let sec_bars: Vec<(usize, &Series)> = sec.iter().filter(|(_, x)| bar_of(x).is_some()).copied().collect(); + let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| bar_of(x).is_none() && !pct(*i, x)).copied().collect(); + let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); + let bar_g = sec_bars.first().and_then(|(_, x)| bar_of(x)).unwrap_or(G::Bar { bar: false, grouping: "clustered" }); + for (g, members) in + [(bar_g, sec_bars), (G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] + { + if !members.is_empty() { + s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); + secondary.get_or_insert(g); } } } diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index b5c58faa5a..8156dfb9d9 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -100,3 +100,33 @@ fn a_hundred_percent_stacked_line_on_the_secondary_axis_keeps_its_kind_when_save let got: Vec<(Option, bool)> = again.series.iter().map(|s| (s.kind, s.secondary)).collect(); assert_eq!(got, [(Some(ChartKind::ColumnClustered), false), (Some(ChartKind::LineStacked100Markers), true)], "{saved}"); } + +#[test] +fn secondary_columns_lines_and_hundred_percent_stacked_lines_keep_their_kinds_when_saved() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + {}\ + {}\ + ", + ser(0, ""), + ser(1, ""), + ser(2, ""), + ser(3, NO_MARKER) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let want = [ + (Some(ChartKind::ColumnClustered), false), + (Some(ChartKind::ColumnClustered), true), + (Some(ChartKind::LineStacked100Markers), true), + (Some(ChartKind::Line), true), + ]; + assert_eq!(ch.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), want); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), want, "{saved}"); +} From 9680794bc4eb91228f87734bdb73f00ae1d45979 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 08:00:31 -0700 Subject: [PATCH 61/95] XLSX: combo charts keep each area, marked line and column grouping in its own group when saved Lines and secondary series are written as one chart group per kind, so areas, lines with markers and columns with different groupings open again as the same kinds instead of plain lines or the first column's grouping. --- crates/xlsx/src/chart.rs | 51 +++++++++---------- .../src/tests/chart_line_percent_stacked.rs | 35 +++++++++++++ 2 files changed, 59 insertions(+), 27 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 2e611dcf59..bc82effe8a 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -767,6 +767,25 @@ fn strip_book(link: &str) -> &str { link.strip_prefix('[').and_then(|r| r.split_once(']')).map_or(link, |(_, rest)| rest) } +/// Splits a combo chart's series into one group per kind, in the order each kind first appears. +/// Columns, bars, lines and areas keep their own grouping and markers; 100% stacked lines share one group +/// whose series write their own markers; other kinds are written as plain lines. +fn combo_groups<'a>(series: &[(usize, &'a Series)], kind: impl Fn(usize, &Series) -> Option) -> Vec<(G, Vec<(usize, &'a Series)>)> { + let mut groups: Vec<(G, Vec<(usize, &'a Series)>)> = vec![]; + for &(i, x) in series { + let g = match kind(i, x).filter(|k| *k != ChartKind::Combo).map(group_for) { + Some(g @ (G::Bar { .. } | G::Line { .. } | G::Area { .. })) => g, + Some(G::Line100 { .. }) => G::Line100 { markers: true }, + _ => G::Line { stacked: false, markers: false }, + }; + match groups.iter_mut().find(|(k, _)| *k == g) { + Some((_, members)) => members.push((i, x)), + None => groups.push((g, vec![(i, x)])), + } + } + groups +} + /// Chart part XML for a model chart on sheet `si`. pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> String { let mut s = String::from( @@ -806,34 +825,12 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str if !bars.is_empty() || (lines.is_empty() && sec.is_empty()) { s.push_str(&group_xml(primary_g, &bars, ch, (1, 2), wb, si)); } - // 100% stacked line series share one percentStacked group, each with its own markers. - let pct = |i: usize, x: &Series| matches!(kind(i, x).map(group_for), Some(G::Line100 { .. })); - let plain: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| !pct(*i, x)).copied().collect(); - let stacked: Vec<(usize, &Series)> = lines.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); - if !plain.is_empty() { - s.push_str(&group_xml(G::Line { stacked: false, markers: false }, &plain, ch, (1, 2), wb, si)); + for (g, members) in combo_groups(&lines, |i, x| kind(i, x)) { + s.push_str(&group_xml(g, &members, ch, (1, 2), wb, si)); } - if !stacked.is_empty() { - s.push_str(&group_xml(G::Line100 { markers: true }, &stacked, ch, (1, 2), wb, si)); - } - if !sec.is_empty() { - // Secondary bars, lines and 100% stacked lines each get their own group. - let bar_of = |x: &Series| match x.kind.map(group_for) { - Some(b @ G::Bar { .. }) => Some(b), - _ => None, - }; - let sec_bars: Vec<(usize, &Series)> = sec.iter().filter(|(_, x)| bar_of(x).is_some()).copied().collect(); - let sec_plain: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| bar_of(x).is_none() && !pct(*i, x)).copied().collect(); - let sec_stacked: Vec<(usize, &Series)> = sec.iter().filter(|(i, x)| pct(*i, x)).copied().collect(); - let bar_g = sec_bars.first().and_then(|(_, x)| bar_of(x)).unwrap_or(G::Bar { bar: false, grouping: "clustered" }); - for (g, members) in - [(bar_g, sec_bars), (G::Line { stacked: false, markers: false }, sec_plain), (G::Line100 { markers: true }, sec_stacked)] - { - if !members.is_empty() { - s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); - secondary.get_or_insert(g); - } - } + for (g, members) in combo_groups(&sec, |_, x| x.kind) { + s.push_str(&group_xml(g, &members, ch, (3, 4), wb, si)); + secondary.get_or_insert(g); } } else { primary_g = match group_for(ch.kind) { diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 8156dfb9d9..20bdac29ed 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -130,3 +130,38 @@ fn secondary_columns_lines_and_hundred_percent_stacked_lines_keep_their_kinds_wh let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); assert_eq!(again.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), want, "{saved}"); } + +#[test] +fn combo_areas_marked_lines_and_mixed_column_groupings_keep_their_kinds_when_saved() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + {}\ + {}\ + {}\ + {}\ + {}\ + ", + ser(0, ""), + ser(1, ""), + ser(2, ""), + ser(3, ""), + ser(4, ""), + ser(5, ""), + ser(6, NO_MARKER) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let got: Vec<(Option, bool)> = ch.series.iter().map(|s| (s.kind, s.secondary)).collect(); + assert_eq!(got[1], (Some(ChartKind::AreaStacked), false)); + assert_eq!(got[3], (Some(ChartKind::ColumnStacked), true)); + assert_eq!(got[4], (Some(ChartKind::ColumnClustered), true)); + assert_eq!(got[5], (Some(ChartKind::AreaStacked100), true)); + assert_eq!(got[6], (Some(ChartKind::Line), true)); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), got, "{saved}"); +} From 04f8797ee46597200b9cc0c23da2e9d3d9eb8550 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 08:04:56 -0700 Subject: [PATCH 62/95] XLSX: a 100% stacked line group with mixed markers opens with each series' own markers A single percentStacked line group whose series differ in markers opens as a combo chart, so saving it keeps the marked and unmarked series as they were. --- crates/xlsx/src/chart.rs | 13 +++++++----- .../src/tests/chart_line_percent_stacked.rs | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index bc82effe8a..3b34095061 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -227,15 +227,18 @@ pub fn read_chart(root: &El) -> Option { let groups: Vec<(&El, ChartKind)> = plot.children.iter().filter_map(|g| group_kind(g).map(|k| (g, k))).collect(); let (first, first_kind) = *groups.first()?; let first_axes = axis_ids(first); + let no_marker = |s: &El| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); + // A 100% stacked line group whose series differ in markers opens as a combo chart, so each series keeps its own. + let mixed = first_kind == ChartKind::LineStacked100Markers && first.kids("ser").any(no_marker) && !first.kids("ser").all(no_marker); + let combo = groups.len() > 1 || mixed; let mut series = vec![]; let mut orders = vec![]; for (gi, (g, k)) in groups.iter().enumerate() { for s in g.kids("ser") { let mut ser = read_series(s); - if groups.len() > 1 { + if combo { // Every series of a combo chart keeps its own group's kind, the first group's included. - let no_marker = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); - ser.kind = Some(if *k == ChartKind::LineStacked100Markers && no_marker { ChartKind::LineStacked100 } else { *k }); + ser.kind = Some(if *k == ChartKind::LineStacked100Markers && no_marker(s) { ChartKind::LineStacked100 } else { *k }); } if gi > 0 { ser.secondary = axis_ids(g) != first_axes; @@ -245,12 +248,12 @@ pub fn read_chart(root: &El) -> Option { } } // A combo chart lists its series group by group; `c:order` gives the order they are drawn in. - if groups.len() > 1 && orders.iter().all(Option::is_some) { + if combo && orders.iter().all(Option::is_some) { let mut keyed: Vec<(Option, Series)> = orders.into_iter().zip(series).collect(); keyed.sort_by_key(|(o, _)| *o); series = keyed.into_iter().map(|(_, s)| s).collect(); } - let kind = if groups.len() > 1 { ChartKind::Combo } else { first_kind }; + let kind = if combo { ChartKind::Combo } else { first_kind }; let show_val = |e: &El| e.child("dLbls").is_some_and(|d| bool_val(d, "showVal")); let data_labels = groups.iter().any(|(g, _)| show_val(g) || g.kids("ser").any(show_val)); let val_axes: Vec<&El> = plot.kids("valAx").collect(); diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index 20bdac29ed..e9dcaed9d9 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -131,6 +131,26 @@ fn secondary_columns_lines_and_hundred_percent_stacked_lines_keep_their_kinds_wh assert_eq!(again.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), want, "{saved}"); } +#[test] +fn a_hundred_percent_stacked_line_group_with_mixed_markers_keeps_each_series_markers() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}{}\ + ", + ser(0, ""), + ser(1, NO_MARKER) + ); + let want = [Some(ChartKind::LineStacked100Markers), Some(ChartKind::LineStacked100)]; + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.series.iter().map(|s| s.kind).collect::>(), want); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); +} + #[test] fn combo_areas_marked_lines_and_mixed_column_groupings_keep_their_kinds_when_saved() { let ser = |i: usize, marker: &str| { From 2c976a6e6baa3560375cc672c3af9e77413c5954 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:51:09 -0500 Subject: [PATCH 63/95] Import engine error in file commands --- crates/engine/src/cmd/file.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index d11be60278..54ad9e4f2a 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -3,7 +3,7 @@ use serde_json::{Value as Json, json}; use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param}; -use crate::DocState; +use crate::{DocState, EngineError}; pub fn specs() -> Vec { vec![ From 2295cc71c65768d20bc6c944e169264a66d16178 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:51:45 -0500 Subject: [PATCH 64/95] Remove unused filter region import --- crates/engine/src/cmd/data/filter.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 74d3456396..8efc2d6d92 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -1,7 +1,7 @@ use super::sort::sort_key; use super::{ AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param, - current_region, data_target, edit, json, + data_target, edit, json, }; // ---------------------------------------------------------------- filter From 15eef6b4343a5ed9656686e7d0ccdaeb9ea4a278 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:59:52 -0500 Subject: [PATCH 65/95] Extract XLSX write validation helper --- crates/xlsx/src/write.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 8e025c8a82..0c9236063e 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -204,6 +204,16 @@ fn check_sheet_names(wb: &Workbook) -> Result<(), IoError> { /// Workbook name written in a PivotChart's link when the file name isn't known. const DEFAULT_BOOK_NAME: &str = "Workbook.xlsx"; +fn check_write_xlsx(wb: &Workbook) -> Result<(), IoError> { + if wb.sheets.is_empty() { + return Err(IoError::Format("a workbook needs at least one sheet".into())); + } + if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { + return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); + } + check_sheet_names(wb) +} + pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { write_xlsx_named(wb, kind, None) } @@ -211,13 +221,7 @@ pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { /// Writes the workbook for the file `book_name` (a bare file name). A PivotChart is bound to its /// PivotTable in Excel only when its link starts with the workbook in brackets. pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) -> Result, IoError> { - if wb.sheets.is_empty() { - return Err(IoError::Format("a workbook needs at least one sheet".into())); - } - if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { - return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); - } - check_sheet_names(wb)?; + check_write_xlsx(wb)?; let mut out = Out { parts: vec![], overrides: vec![], From 2506ba3ddbab4a6bc4ab6c391f2d641332dfc7f9 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:01:57 -0500 Subject: [PATCH 66/95] Factor kept style patch type --- crates/xlsx/src/passthrough/write.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/xlsx/src/passthrough/write.rs b/crates/xlsx/src/passthrough/write.rs index b4d69977c0..ff3e0d4d3e 100644 --- a/crates/xlsx/src/passthrough/write.rs +++ b/crates/xlsx/src/passthrough/write.rs @@ -103,9 +103,11 @@ fn map_style_ids(data: &[u8], dxfs: &HashMap, fmts: &HashMap #[derive(Default)] pub struct StylePatches { /// (written part name, source bytes, dxf id map, source number format id → code). - pub(super) list: Vec<(String, Arc<[u8]>, HashMap, Vec<(u32, String)>)>, + pub(super) list: Vec, } +pub(super) type StylePatch = (String, Arc<[u8]>, HashMap, Vec<(u32, String)>); + impl KeptOut { /// Number format codes kept parts refer to (to be registered in the styles part). pub fn num_fmt_codes(&self) -> Vec { From 496aa28ed30f27b01492783d4e0d3b1f0099bc34 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:03:33 -0500 Subject: [PATCH 67/95] Fix pivot cache eligibility filtering --- crates/xlsx/src/passthrough/rebase.rs | 4 ++-- crates/xlsx/src/tests/passthrough_tests.rs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/xlsx/src/passthrough/rebase.rs b/crates/xlsx/src/passthrough/rebase.rs index a80717d60c..a4b4ca4e3e 100644 --- a/crates/xlsx/src/passthrough/rebase.rs +++ b/crates/xlsx/src/passthrough/rebase.rs @@ -25,8 +25,8 @@ impl<'a> SheetKept<'a> { q.content_type == CT_PIVOT_TABLE && crate::xml::parse(&q.data).ok().and_then(|x| x.attr_u32("cacheId")).is_some_and(|id| !cache_ids.contains(&id)) }; - let mut direct = direct.peekable(); - if direct.peek().is_some() { direct.any(|r| !wb_names.contains_key(&normalize(&r.target))) } else { by_id() } + let direct_is_orphan = direct.into_iter().any(|r| !wb_names.contains_key(&normalize(&r.target))); + direct_is_orphan || by_id() }) .map(|q| normalize(&q.name)) .collect(); diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index 187c22df85..e073d59882 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -1183,6 +1183,19 @@ fn a_kept_pivot_table_whose_cache_is_not_listed_is_dropped() { assert!(written_pivot_caches(&u).is_empty()); } +#[test] +fn a_kept_pivot_table_with_an_unlisted_cache_id_is_dropped_even_with_a_cache_relationship() { + let src = ext_pivot_package(false, false, "externalLinkPath"); + let mut parts = Unpacked::new(&src).parts; + let table = String::from_utf8(parts.remove("xl/pivotTables/pivotTable1.xml").unwrap()).unwrap().replace(r#"cacheId="1""#, r#"cacheId="99""#); + parts.insert("xl/pivotTables/pivotTable1.xml".into(), table.into_bytes()); + let list: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect(); + let (wb, _) = read_xlsx(&make_zip(&list)).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_tables(&u, "Report").is_empty()); +} + // ---------------------------------------------------------------- PivotTables on a data connection or the Data Model /// Bytes standing in for the Data Model (Excel's `xl/model/item.data`). From cd6fe4f8bd81595f34a0cc4436c0291fd0a62ba7 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:05:24 -0500 Subject: [PATCH 68/95] Extract file sharing XML writer --- crates/xlsx/src/write.rs | 45 +++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 0c9236063e..ac08434c94 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -214,6 +214,29 @@ fn check_write_xlsx(wb: &Workbook) -> Result<(), IoError> { check_sheet_names(wb) } +fn append_file_sharing(w: &mut String, wb: &Workbook) { + let Some(r) = &wb.write_reservation else { return }; + w.push_str(" { + let _ = write!(w, " reservationPassword=\"{h:04X}\""); + } + Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), + None => {} + } + w.push_str("/>"); +} + pub fn write_xlsx(wb: &Workbook, kind: XlsxKind) -> Result, IoError> { write_xlsx_named(wb, kind, None) } @@ -263,27 +286,7 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); w.push_str(if file_version.is_empty() { "" } else { &file_version }); - if let Some(r) = &wb.write_reservation { - w.push_str(" { - let _ = write!(w, " reservationPassword=\"{h:04X}\""); - } - Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), - None => {} - } - w.push_str("/>"); - } + append_file_sharing(&mut w, wb); w.push_str(" {} From 91e6a41a63be4e67a12bfd22a8bbeff7b9ce1446 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 28 Oct 2026 23:50:52 -0500 Subject: [PATCH 69/95] #2641: Discard old filter-menu state when switching columns Clear the previous column checkbox, search and button caches after the grid interaction changes the open menu. Keep the new menu state intact. The real UI regression fails on the prior production code and passes with the fix. Validation: filter15, popup6, strict UI all-target Clippy, fmt and WASM pass. Aggregate CI rerun retains only the two unchanged Windows baseline diagnostics. Small CodeRabbit finding validated and fixed directly after the three medium merge-resolution reviews. --- crates/ui-egui/src/grid/show.rs | 9 ++++ .../tests/it/cascading_filter_values.rs | 54 ++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 193d8dc734..ba9b99881d 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -337,6 +337,15 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re crate::paper_view::interact(app, ui, resp, geo, sh, wb); interact(app, ui, resp, geo, sh, wb); } + if previous_popups.0 != app.grid.filter_menu + && let Some((col, _, _)) = previous_popups.0 + { + ui.ctx().data_mut(|d| { + d.remove::>(egui::Id::unique(("filter_sel", col))); + d.remove::(egui::Id::unique(("filter_search", col))); + d.remove::>(egui::Id::unique(("filter_buttons", col))); + }); + } update_cursor(app, ui, resp, geo, sh); crate::text_box::show(app, ui, geo, sh); if app.editor.as_ref().is_some_and(|e| !e.from_formula_bar) { diff --git a/crates/ui-egui/tests/it/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs index 0b4e2259bc..8b6a50341b 100644 --- a/crates/ui-egui/tests/it/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -1,8 +1,10 @@ use crate::common; -use egui::{Event, Key, Modifiers}; +use egui::{Event, Key, Modifiers, PointerButton}; use egui_kittest::kittest::Queryable; use gridcraft_engine::Session; +use gridcraft_engine::core::CellRef; +use gridcraft_ui_egui::grid; use serde_json::json; fn key(h: &mut common::Harness, key: Key, modifiers: Modifiers) { @@ -12,6 +14,56 @@ fn key(h: &mut common::Harness, key: Key, modifiers: Modifiers) { h.run_steps(3); } +fn click_filter(h: &mut common::Harness, cell: &str) { + let app = h.state(); + let sh = app.session.active().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let at = grid::filter_button_rect(&geo, sh, CellRef::parse(cell).unwrap()).center(); + h.input_mut().events.push(Event::PointerMoved(at)); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.run_steps(3); +} + +#[test] +fn switching_filter_columns_discards_old_edits_and_recomputes_eligible_choices() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"] + ]}), + ) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.get_by_label("Other").click(); + h.run_steps(2); + assert_eq!(h.ctx.data(|d| d.get_temp::(egui::Id::unique(("filter_search", 1u32)))).as_deref(), Some("")); + + click_filter(&mut h, "A1"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + h.ctx.data(|d| { + assert!(d.get_temp::>(egui::Id::unique(("filter_sel", 1u32))).is_none(), "old checkbox edits must be discarded"); + assert!(d.get_temp::(egui::Id::unique(("filter_search", 1u32))).is_none(), "old search must be discarded"); + assert!(d.get_temp::>(egui::Id::unique(("filter_buttons", 1u32))).is_none(), "old button focus IDs must be discarded"); + }); + assert!(h.query_by_label("East").is_some(), "the new column's choices must remain available"); + h.get_by_label("West").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(3); + click_filter(&mut h, "B1"); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_some(), "eligible alternatives must remain available"); + assert!(h.query_by_label("Other").is_none(), "the other column's new criterion must narrow the reopened list"); +} + #[test] fn dropdown_can_change_and_clear_a_column_while_another_filter_stays_active() { for table in [false, true] { From 0de56624d5dd4445d037c5816d25855a53bfd733 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Sun, 1 Nov 2026 01:05:32 -0500 Subject: [PATCH 70/95] 2641: cover header-only filter tables and manual visibility Exercise the real engine and header-button popup with a genuine header-only table. Verify that its installed AutoFilter offers neither header values nor a phantom blank row, and that the popup dismisses normally. Strengthen the existing manual-hide case to check exact values and selection state. Production filter matching, selection merging and popup caching are unchanged. Ten focused engine, eighteen filter UI and six popup tests, formatting and strict changed-target Clippy pass. Required aggregate CI retains the unchanged baseline Windows CLI lint failure; exact-new-head hosted CI remains pending. --- .../tests/it/cascading_filter_values.rs | 19 ++++++++++++++++++- .../tests/it/cascading_filter_values.rs | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 928f3eb0e2..c6d7f4d1e4 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -135,11 +135,28 @@ fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() { assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]); // Manual visibility is not a filter criterion, even when every eligible row is hidden. s.execute("home.hideRows", json!({"rows": "4:10"})).unwrap(); - assert_eq!(choices(&s).len(), 3); + assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]); assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); assert!(filter_values(&s.doc().unwrap().wb, 0, 4).is_empty()); } +#[test] +fn a_header_only_table_has_no_data_values_or_blank_choice() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap(); + s.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap(); + s.execute("data.filter", json!({"range": "B3:C3"})).unwrap(); + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert!(sh.tables[0].header_row); + assert_eq!(sh.tables[0].range.height(), 1); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3"); + for col in [1, 2] { + assert!(filter_values(&d.wb, 0, col).is_empty(), "headers are not values or blank data rows"); + } +} + #[test] fn choices_respect_blank_and_formatted_value_criteria_on_other_columns() { let mut s = Session::new(); diff --git a/crates/ui-egui/tests/it/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs index 6357cfb7b0..ed33019848 100644 --- a/crates/ui-egui/tests/it/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -26,6 +26,25 @@ fn click_filter(h: &mut common::Harness, cell: &str) { h.run_steps(3); } +#[test] +fn a_header_only_tables_popup_has_no_value_choices() { + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap(); + session.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap(); + session.execute("selection.set", json!({"cell": "B3"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + click_filter(&mut h, "B3"); + assert_eq!(h.state().grid.filter_menu.map(|(col, row, _)| (col, row)), Some((1, 2))); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + assert_eq!(sh.tables[0].range.height(), 1); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3"); + assert_eq!(h.ctx.data(|d| d.get_temp::>(egui::Id::unique(("filter_sel", 1u32)))), Some(vec![])); + assert!(h.query_by_label("(Blanks)").is_none()); + key(&mut h, Key::Escape, Modifiers::NONE); + assert!(h.state().grid.filter_menu.is_none()); +} + #[test] fn switching_filter_columns_discards_old_edits_and_recomputes_eligible_choices() { let mut session = Session::new(); From 6c447a808215d0a040206848fe8bfe34d34c0146 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Sun, 1 Nov 2026 22:58:40 -0600 Subject: [PATCH 71/95] #2641: Clarify AutoFilter documentation scope Move the AutoFilter population discussion into its own section before Keyboard while leaving Shortcut audit under Keyboard. State explicitly that separate table dropdowns outside the active sheet AutoFilter columns remain empty, retaining the separate #2506 activation/roundtrip scope. Update the existing feature history entry. Addresses both outside-diff comments in CodeRabbit5732175733. Documentation only; implementation, tests, dependencies, credits and workflows unchanged. Formatting/parity checks pass. Required local CI hits only the unchanged Windows CLI lint; actual preceding c9 Ubuntu run passed all10 gates and lock verification. New-head hosted CI remains required. Small review findings fixed directly without new agents or tests. --- docs/ui-parity.md | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bed023d49c..f3216bb4dd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -75,6 +75,24 @@ this logic, with one undo step. | Smooth scrolling, scrollbars | done; vertical scrollbar added 10-09 (#73); horizontal scrollbar in the tab bar (60/40 split, drag, track click pages) 10-13 (#176, #840); dragging the handle at the scrollbar's left edge gives the tabs more or less of the bar; each workbook keeps its share while it is open (not saved in the file) | | Text overflow into empty neighbours, wrap, rotation, shrink to fit | done | +## AutoFilter population and pending integrations + +[Microsoft's filtering guide](https://support.microsoft.com/en-us/excel/get-started/filter-data-in-a-range-or-table-in-excel) +describes additive column filters and restricting other dropdowns to the filtered range. The +current column is excluded from enumeration so its unchecked alternatives remain available. +The existing one-million-data-row enumeration limit and value sorting remain unchanged. + +This changes the population behind the pending row-count work (#1737, and its stacked Only +button #1741): a future count beside a choice should count eligible rows satisfying the other +columns, including rows rejected by the current column. It must not count the whole original +range or just currently visible rows. Search narrows the displayed choices, not that population; +Apply with a search excludes nonmatching values even when another filter hides them. +These PRs are not incorporated here. Date grouping (#1509) should group this same eligible +population. Table filter activation / roundtrip ownership changes remain in #2506. Enumeration +reads the active sheet AutoFilter without changing criteria, row visibility or the XLSX +representation. A separate table dropdown outside that AutoFilter's columns remains empty; +it does not receive choices from its own eligible-row population. + ## Keyboard | Area | Excel | GridCraft | @@ -93,23 +111,6 @@ this logic, with one undo step. | Sequential Alt access keys (Alt, H, N, …) on every ribbon tab | yes | 364-sequence keytip table for all tabs: per-control badges, prefix waiting, dropdowns open for editing (type/arrows/Enter), pending bindings for not-yet-built commands; letters also work with left Alt held (Alt+H, O, A), as in Excel; each Borders letter (H, B, …) draws its own preset, H, B, M opens Format Cells on the Border tab, and Erase Border, Line Color and Line Style are reserved; QAT/Backstage excluded | | Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) | -### AutoFilter population and pending integrations - -[Microsoft's filtering guide](https://support.microsoft.com/en-us/excel/get-started/filter-data-in-a-range-or-table-in-excel) -describes additive column filters and restricting other dropdowns to the filtered range. The -current column is excluded from enumeration so its unchecked alternatives remain available. -The existing one-million-data-row enumeration limit and value sorting remain unchanged. - -This changes the population behind the pending row-count work (#1737, and its stacked Only -button #1741): a future count beside a choice should count eligible rows satisfying the other -columns, including rows rejected by the current column. It must not count the whole original -range or just currently visible rows. Search narrows the displayed choices, not that population; -Apply with a search excludes nonmatching values even when another filter hides them. -These PRs are not incorporated here. Date grouping (#1509) should group this same eligible -population. Table filter activation / roundtrip ownership changes remain in #2506; enumeration -reads the active sheet AutoFilter used by the current table dropdown without changing criteria, -row visibility or the XLSX representation. - ### Shortcut audit (#110) Checked against Microsoft's published "Keyboard shortcuts in Excel" (Windows and Mac tables, @@ -214,7 +215,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| -| 2026-11-01 | minor | Filter popup checkbox edits, search and button state belong to their document window; switching columns in another window no longer discards an open popup's pending choices (#2641) | +| 2026-11-01 | minor | Filter popup checkbox edits, search and button state belong to their document window; switching columns in another window no longer discards an open popup's pending choices (#2641); the separate AutoFilter section documents the empty dropdown outside the active sheet filter columns (#2506) | | 2026-11-01 | minor | Chart Design › Add Chart Element offers Data Table with/no legend keys and None; Format Chart Area has a Data Table section with visibility, legend keys, horizontal/vertical borders and outline. Both use engine commands. | | 2026-11-01 | minor | Page Setup has a Page order choice (Down, then over, the default, or Over, then down) with a small picture of the order, also when Print Titles opens it on its Sheet tab; OK sets it with the margins in one undo step. Printing, PDF export, the print preview, Page Break Preview's page numbers and Page Layout view's headers and footers follow the order. The dialog is in German now too | | 2026-11-01 | minor | Formulas › Error Checking › Trace Error (`formulas.traceError`): red arrows from the cell an error starts in to the selected cell, through the first reference showing the same error at each step, and blue arrows from that cell's own references, as measured in Excel; the command returns the source and the arrows | From 5f1e609a698451deb386613a92c7c7db398f318e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 21:20:58 -0800 Subject: [PATCH 72/95] Charts: 100% stacked line kinds keep data tables --- crates/model/src/features.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index 6eb0a1cbbf..1763f3275f 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -597,6 +597,8 @@ impl Chart { | ChartKind::Line | ChartKind::LineMarkers | ChartKind::LineStacked + | ChartKind::LineStacked100 + | ChartKind::LineStacked100Markers | ChartKind::Area | ChartKind::AreaStacked | ChartKind::AreaStacked100 From 9c5b6b2dbeb35634bee3038039af62c9fb8d33f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 14:25:28 -0800 Subject: [PATCH 73/95] Charts: data table keys for 100% stacked line charts use line swatches --- crates/chart/src/render/table.rs | 4 ++-- crates/chart/src/tests/data_table.rs | 29 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index f0839dcfef..478f0ffd7b 100644 --- a/crates/chart/src/render/table.rs +++ b/crates/chart/src/render/table.rs @@ -71,8 +71,8 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; if settings.show_keys { let swatch = match plot_kind(chart, series) { - ChartKind::Line | ChartKind::LineStacked => Swatch::Line, - ChartKind::LineMarkers => Swatch::LineMarker, + ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 => Swatch::Line, + ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker, _ => Swatch::Box, }; draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color); diff --git a/crates/chart/src/tests/data_table.rs b/crates/chart/src/tests/data_table.rs index 13e2baf6c9..6ea4035567 100644 --- a/crates/chart/src/tests/data_table.rs +++ b/crates/chart/src/tests/data_table.rs @@ -119,3 +119,32 @@ fn dense_and_tiny_tables_are_bounded_and_explicit() { assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h); } } + +#[test] +fn table_keys_for_100_percent_stacked_lines_use_line_swatches() { + for (kind, marker) in [(ChartKind::LineStacked100, false), (ChartKind::LineStacked100Markers, true)] { + let mut c = chart(kind); + c.title = Some(String::new()); + c.legend = LegendPos::None; + c.data_labels = false; + c.data_table = Some(ChartDataTable::default()); + let color = [1, 2, 3, 255]; + let d = ChartData { + categories: ["Jan", "Feb"].map(String::from).to_vec(), + series: vec![series("Rate", &[1.0, 3.0], color, kind)], + ..Default::default() + }; + let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + let header_y = p + .iter() + .find_map(|p| match p { + Prim::Text { text, y, .. } if text == "Jan" => Some(*y), + _ => None, + }) + .unwrap(); + let key_circles = p.iter().filter(|p| matches!(p, Prim::Circle { cy, fill: Some(f), .. } if *f == color && *cy > header_y)).count(); + assert_eq!(key_circles, usize::from(marker), "{kind:?}"); + let key_box = p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y)); + assert!(!key_box, "{kind:?} key is a line swatch"); + } +} From 5f4f5ce4c55cde30b63c17386288905e587b8218 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:43:58 -0600 Subject: [PATCH 74/95] Count Excel text limits in UTF-16 units --- crates/calc/src/tests.rs | 5 ++++- crates/core/src/value.rs | 28 +++++++++++++++++++++------- crates/engine/src/cmd/edit/tests.rs | 6 ++++++ crates/functions/src/text.rs | 12 +++++++++--- crates/functions/src/util.rs | 6 +++--- 5 files changed, 43 insertions(+), 14 deletions(-) diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 136f91e9e7..0149609545 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2320,7 +2320,10 @@ fn concat_operator_cuts_at_the_cell_limit() { t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))"); t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")"); t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))"); - assert_eq!((t.num("A1"), t.num("A2"), t.num("A3")), (32767.0, 32767.0, 32767.0)); + t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")"); + t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))"); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16383.0)); + assert_eq!(t.get("A5"), Value::Error(CellError::Value)); } /// Makes `at` a Python cell showing `cached` (its value before this calculation), with `result` diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index 994d8f0c6a..7c045a749a 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -412,20 +412,24 @@ pub fn sci_text(n: f64, sig: usize) -> String { format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) } -/// Longest text a cell can hold, in characters. +/// Longest text a cell can hold, in UTF-16 code units. pub const MAX_TEXT_CHARS: usize = 32_767; -/// `s` cut to [`MAX_TEXT_CHARS`] characters, as Excel cuts typed text and `&` results. +/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value. pub fn cap_text(mut s: String) -> String { - if s.len() > MAX_TEXT_CHARS - && let Some((i, _)) = s.char_indices().nth(MAX_TEXT_CHARS) - { - s.truncate(i); + if s.len() > MAX_TEXT_CHARS { + let mut units = 0; + if let Some((i, _)) = s.char_indices().find(|(_, c)| { + units += c.len_utf16(); + units > MAX_TEXT_CHARS + }) { + s.truncate(i); + } } s } -/// `v` with text cut to [`MAX_TEXT_CHARS`] characters; other values pass through. +/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through. pub fn cap_value(v: Value) -> Value { match v { Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())), @@ -478,6 +482,16 @@ mod tests { assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater); } + #[test] + fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() { + let face = "😀"; + assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS)); + assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS)); + assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)); + assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1)); + assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383)); + } + #[test] fn errors() { for e in CellError::ALL { diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 2e9457cb12..57eb5a121b 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -143,6 +143,8 @@ fn cell_set_cuts_text_to_32767_characters() { } assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767)); assert_eq!(get(&mut s, "A2"), json!(32767.0)); + s.execute("cell.set", json!({"cell": "D1", "input": "😀".repeat(16_384)})).unwrap(); + assert_eq!(get(&mut s, "D1").as_str().map(|t| t.encode_utf16().count()), Some(32_766)); } #[test] @@ -210,6 +212,10 @@ fn set_values_can_store_strings_as_the_text_they_are() { s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap(); let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count())); assert_eq!(len.flatten(), Some(32_767)); + s.execute("range.setValues", json!({"range": "B10", "parse": false, "values": [["😀".repeat(16_384)]]})).unwrap(); + let emoji_len = + s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("B10").unwrap()).map(|c| c.value.as_text().map(|t| t.encode_utf16().count())); + assert_eq!(emoji_len.flatten(), Some(32_766)); assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo")); let d = s.doc().unwrap(); let sh = d.wb.active().unwrap(); diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index efd4cd310a..227124efb1 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -20,7 +20,7 @@ fn chars(s: &str) -> Vec { } fn check_len(s: String) -> R { - if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT { + if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT { return Err(CellError::Value); } text_val(s) @@ -49,7 +49,7 @@ fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { } fn check_calc(s: String) -> R { - if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT { + if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT { return Err(CellError::Calc); } text_val(s) @@ -234,7 +234,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R { return Err(CellError::Value); } let n = n.trunc(); - let total = s.chars().count() as f64 * n; + let total = s.encode_utf16().count() as f64 * n; if total > MAX_TEXT as f64 { return Err(CellError::Value); } @@ -1149,6 +1149,12 @@ mod tests { // An error after the cut still propagates. let big = || t(&"x".repeat(32_767)); is_err(ev("CONCATENATE", vec![big(), big(), big(), big(), big(), e(CellError::NA)]), CellError::NA); + let emoji = "😀"; + is_err(ev("CONCAT", vec![t(&emoji.repeat(16_384))]), CellError::Calc); + is_err(ev("TEXTJOIN", vec![t(""), b(false), t(&emoji.repeat(16_384))]), CellError::Calc); + assert_eq!(ev("CONCATENATE", vec![t(&emoji.repeat(16_384))]), Value::text(emoji.repeat(16_383))); + is_err(ev("REPT", vec![t(emoji), n(16_384.0)]), CellError::Value); + assert_eq!(ev("REPT", vec![t(emoji), n(16_383.0)]), Value::text(emoji.repeat(16_383))); // Lifting: CONCATENATE over an array. assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]); } diff --git a/crates/functions/src/util.rs b/crates/functions/src/util.rs index 14c6279370..4db1c94320 100644 --- a/crates/functions/src/util.rs +++ b/crates/functions/src/util.rs @@ -11,7 +11,7 @@ pub(crate) type R = Result; /// Largest array a function may build. pub(crate) const MAX_CELLS: usize = 10_000_000; -/// Longest text a cell can hold. +/// Longest text a cell can hold, in UTF-16 code units. pub(crate) const MAX_TEXT: usize = 32_767; /// Scalar-position lifting tables. @@ -20,11 +20,11 @@ pub(crate) const S: &[bool] = &[true]; pub(crate) const A: &[bool] = &[false]; /// Turns an implementation result into a cell value: errors become error values, non-finite -/// numbers become `#NUM!`, text longer than 32,767 characters becomes `#VALUE!`. +/// numbers become `#NUM!`, text longer than 32,767 UTF-16 code units becomes `#VALUE!`. pub(crate) fn finish(r: R) -> Value { match r { Ok(Value::Number(n)) => Value::number(n), - Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.chars().count() > MAX_TEXT => Value::Error(CellError::Value), + Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.encode_utf16().count() > MAX_TEXT => Value::Error(CellError::Value), Ok(v) => v, Err(e) => Value::Error(e), } From 1ac75eb85810f3649385439de60600c9b1edb974 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:59:43 -0600 Subject: [PATCH 75/95] Correct Unicode concat boundary expectation --- crates/calc/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 0149609545..ed4176759d 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2322,7 +2322,7 @@ fn concat_operator_cuts_at_the_cell_limit() { t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))"); t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")"); t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))"); - assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16383.0)); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0)); assert_eq!(t.get("A5"), Value::Error(CellError::Value)); } From e27bb51c58c78229c4400c9a2c3e95a107b85979 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:46:17 -0600 Subject: [PATCH 76/95] docs: clarify XLSX Data Model preservation --- docs/file-format-parity.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 11de60196e..fe84350812 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-24 · **Change:** minor (XLSX PivotTables on a data connection or the Data Model, and the Data Model itself, are kept on save; earlier: .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-03 · **Change:** minor (clarified that the XLSX Data Model is kept on save when its connections are kept; earlier: XLSX PivotTables on a data connection or the Data Model, and the Data Model itself, are kept on save; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -41,15 +41,15 @@ values) is still dropped. | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), pictures in headers and footers (`&G`, #1257: their VML drawing and images are written back unchanged; they are not shown, and can't be inserted), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state and their box's place and size, #1608) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** slicers and slicer caches, timelines, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), pictures in headers and footers (`&G`, #1257: their VML drawing and images are written back unchanged; they are not shown, and can't be inserted), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** slicers and slicer caches, timelines, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes (the major/minor `latin`, East Asian `ea` and complex-script `cs` typefaces and the per-script `` lists are kept through a save), merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), form controls, ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** slicers and slicer caches, timelines, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state and their box's place and size, #1608) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings. **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings. **Kept unchanged on save:** the Data Model when its workbook connections are kept. **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Strict Open XML | R/W | yes | no (writes transitional) | Excel also saves transitional by default | fixtures | | `.xlsm` Macro-Enabled Workbook | R/W | yes | yes, macros kept, not run | The VBA project is kept byte-for-byte and written back only into `.xlsm`/`.xltm` (#6); macros never run. Saved with the macro-enabled workbook content type | `roundtrip.rs` (`vba_project_roundtrip`, `package_kind_sets_workbook_content_type`), engine `io.rs` (`macros_are_saved_only_into_xlsm`) | | `.xltx` / `.xltm` templates | R/W | yes | partial | Saved with the template (and macro-enabled template) content type, chosen by extension; `.xltm` keeps a VBA project, `.xltx` drops it; "new from template" behaviour missing | `roundtrip.rs` (`package_kind_sets_workbook_content_type`), engine `io.rs` | @@ -120,6 +120,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-19 | minor | `.xls` import reads WINDOW2: right-to-left sheets (common in older Arabic and Hebrew files) open right-to-left, and hidden gridlines, headings and zero values and Show Formulas carry over | | 2026-10-19 | trivial | XLSX text boxes and shapes keep right-to-left paragraph direction (`a:pPr rtl`, ECMA-376 Part 1 §21.1.2.2.7): read from the first paragraph and written on every paragraph; output without it is unchanged | | 2026-10-18 | trivial | `file.open {csvAsText: true}` keeps every CSV/TSV/TXT field as the text the file holds, so identifiers (GTINs, SKUs, ZIP codes) keep their digits and leading zeros (#1808; a preference and a CLI flag are separate work) | +| 2026-11-03 | minor | XLSX Data Model: kept on save when its workbook connections are kept; it is not an editable or refreshable data source in GridCraft | | 2026-10-18 | trivial | XLSX PivotTables: `rowGrandTotals` is the Grand Total row and `colGrandTotals` the Grand Total column. Both were read and written the other way round, which a GridCraft round trip hid, so an Excel file with only one grand total opened showing the other | | 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` | | 2026-10-16 | trivial | XLSX charts: `[0]!Name` (a workbook-scoped defined name) in series references is read as the name, so the series resolve instead of showing `#NAME?`. Names in chart references are written qualified (`[0]!Name`, or `Sheet!Name` for a sheet-scoped name): Excel draws a chart with a bare name blank (#1686) | From 2be4be9dd2b5b35fc627c9ada4d594b78f4ce56e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:04:18 -0600 Subject: [PATCH 77/95] Reduce dialog display complexity --- crates/ui-egui/src/dialogs/show.rs | 42 ++++++++++++++++-------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index e0a24a548d..9b02051c4c 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -121,6 +121,27 @@ pub(crate) fn build_params(d: &Dialog) -> Json { v } +fn command_error(app: &mut SheetApp, d: &mut Dialog, e: String) { + if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) { + // Data Analysis asks before replacing data in its output range. + d.values.insert("askOverwrite".into(), json!(true)); + } else if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) { + // The decryption password opened an encrypted, reserved workbook; ask for the modify password. + let mut params = Json::Object(d.values.clone()); + params["modify"] = json!(true); + if let Some(next) = Dialog::open(app, "openPassword", params) { + *d = Dialog { back: d.back.take(), ..next }; + } + } else if d.name == "openPassword" { + // A wrong password: say so, clear the field and stay open for another try. + let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; + d.values.insert(field.into(), json!("")); + app.message = Some((d.title.clone(), crate::clean_error(&e))); + } else { + app.message = Some((d.title.clone(), crate::clean_error(&e))); + } +} + /// Takes and draws the active dialog, dispatches its body by name, consumes picture-inbox results, runs OK/confirm commands, handles Esc/close and restores the back-dialog stack. pub fn show(app: &mut SheetApp, ctx: &egui::Context) { let Some(mut d) = app.dialog.take() else { return }; @@ -431,26 +452,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { app.after_open(path.as_deref(), &r); } } - // Data Analysis asks before replacing data in its output range. - Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => { - d.values.insert("askOverwrite".into(), json!(true)); - } - // Encrypted and reserved: the password opened it, so the form turns to the password to - // modify. The decryption password stays in the values for the retry. - Err(e) if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { - let mut params = Json::Object(d.values.clone()); - params["modify"] = json!(true); - if let Some(next) = Dialog::open(app, "openPassword", params) { - d = Dialog { back: d.back.take(), ..next }; - } - } - // A wrong password: say so, clear the field and stay open for another try. - Err(e) if d.name == "openPassword" => { - let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; - d.values.insert(field.into(), json!("")); - app.message = Some((d.title.clone(), crate::clean_error(&e))); - } - Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))), + Err(e) => command_error(app, &mut d, e), } } else if confirm { open = false; From 25715e77c313f336fdc031729dbe2f0979116b5d Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:52:47 -0600 Subject: [PATCH 78/95] Format filtered table selection helper --- crates/engine/src/selection.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index afefb01010..ab40996447 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -249,9 +249,7 @@ pub fn current_region_outside_tables(sheet: &Sheet, c: CellRef) -> RangeRef { /// The current region around `c`, counting only filled cells that `counts` accepts. fn region_where(sheet: &Sheet, c: CellRef, counts: impl Fn(CellRef) -> bool) -> RangeRef { - let filled = |c: CellRef| { - (sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c)) && counts(c) - }; + let filled = |c: CellRef| (sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c)) && counts(c); // Whether a row (or column) has a filled cell between two columns (rows), inclusive. let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col))); let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col))); From 6856c3cfdf9e3b7e37e0caeb9c41d42faceaa5d3 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:55:30 -0600 Subject: [PATCH 79/95] Split XLSX workbook validation from writer --- crates/xlsx/src/write.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 9423d34a0e..c2ef8988f3 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -240,14 +240,18 @@ fn workbook_view_attrs(wb: &Workbook) -> String { /// Writes the workbook for the file `book_name` (a bare file name). A PivotChart is bound to its /// PivotTable in Excel only when its link starts with the workbook in brackets. -pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) -> Result, IoError> { +fn validate_xlsx_workbook(wb: &Workbook) -> Result<(), IoError> { if wb.sheets.is_empty() { return Err(IoError::Format("a workbook needs at least one sheet".into())); } if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); } - check_sheet_names(wb)?; + check_sheet_names(wb) +} + +pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) -> Result, IoError> { + validate_xlsx_workbook(wb)?; let mut out = Out { parts: vec![], overrides: vec![], From e5c66c0c56437d3155d4043c92db180113891c5c Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:04:33 -0600 Subject: [PATCH 80/95] Extract XLSX workbook XML writer helper --- crates/xlsx/src/write.rs | 140 +++++++++++++++++++++------------------ 1 file changed, 77 insertions(+), 63 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index c2ef8988f3..63e1309c25 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -289,69 +289,7 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) let names = write_defined_names(wb, &kept, &out.chart_names); - let mut w = format!("{XML_DECL}"); - // A workbook read from a file keeps its as it was: Excel trusts the saved values - // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. - let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); - w.push_str(if file_version.is_empty() { "" } else { &file_version }); - w.push_str(" {} - ShowObjects::Placeholders => w.push_str(" showObjects=\"placeholders\""), - ShowObjects::None => w.push_str(" showObjects=\"none\""), - } - if wb.date_system == gridcraft_core::DateSystem::D1904 { - w.push_str(" date1904=\"1\""); - } - if wb.remove_personal_info { - w.push_str(" filterPrivacy=\"1\""); - } - w.push_str("/>"); - if wb.protected_structure { - let pw = wb.structure_password.as_ref().map(|h| crate::sheet_write::password_attrs(h, "workbook")).unwrap_or_default(); - let _ = write!(w, ""); - } - let _ = write!(w, "{sheets_xml}"); - w.push_str(&kept.elements); - if !names.is_empty() { - let _ = write!(w, "{names}"); - } - w.push_str(" {} - CalcMode::Manual => w.push_str(" calcMode=\"manual\""), - CalcMode::AutomaticExceptTables => w.push_str(" calcMode=\"autoNoTable\""), - } - // CT_CalcPr defaults: iterate off, 100 iterations, 0.001 maximum change. The limits are kept - // while iteration is off, as Options keeps them. - let calc = &wb.calc; - if calc.iterative { - w.push_str(" iterate=\"1\""); - } - if calc.iterative || calc.max_iterations != CalcSettings::DEFAULT_ITERATIONS { - let _ = write!(w, " iterateCount=\"{}\"", calc.max_iterations); - } - if calc.iterative || calc.max_change != CalcSettings::DEFAULT_CHANGE { - let _ = write!(w, " iterateDelta=\"{}\"", crate::xml::num(calc.max_change)); - } - if wb.calc.precision_as_displayed { - w.push_str(" fullPrecision=\"0\""); - } - if wb.calc.r1c1 { - w.push_str(" refMode=\"R1C1\""); - } - if out.needs_calc { - w.push_str(" fullCalcOnLoad=\"1\""); - } - w.push_str("/>"); - w.push_str(&pivots.workbook_xml(&mut wb_rels)); - let exts = crate::passthrough::workbook_elements(wb, "ext"); - if !exts.is_empty() { - let _ = write!(w, "{exts}"); - } - w.push_str(""); + let w = write_workbook_xml(wb, active, &sheets_xml, &names, &kept, &mut pivots, &mut wb_rels, out.needs_calc); // Workbook-level parts. let mut extra_fmts = pivots.number_formats(wb); @@ -486,6 +424,82 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) zip.finish() } +fn write_workbook_xml( + wb: &Workbook, + active: usize, + sheets_xml: &str, + names: &str, + kept: &crate::passthrough::WorkbookKept, + pivots: &mut crate::pivot::PivotWriter, + wb_rels: &mut Rels, + needs_calc: bool, +) -> String { + let mut w = format!("{XML_DECL}"); + // A workbook read from a file keeps its as it was: Excel trusts the saved values + // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. + let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); + w.push_str(if file_version.is_empty() { "" } else { &file_version }); + w.push_str(" {} + ShowObjects::Placeholders => w.push_str(" showObjects=\"placeholders\""), + ShowObjects::None => w.push_str(" showObjects=\"none\""), + } + if wb.date_system == gridcraft_core::DateSystem::D1904 { + w.push_str(" date1904=\"1\""); + } + if wb.remove_personal_info { + w.push_str(" filterPrivacy=\"1\""); + } + w.push_str("/>"); + if wb.protected_structure { + let pw = wb.structure_password.as_ref().map(|h| crate::sheet_write::password_attrs(h, "workbook")).unwrap_or_default(); + let _ = write!(w, ""); + } + let _ = write!(w, "{sheets_xml}"); + w.push_str(&kept.elements); + if !names.is_empty() { + let _ = write!(w, "{names}"); + } + w.push_str(" {} + CalcMode::Manual => w.push_str(" calcMode=\"manual\""), + CalcMode::AutomaticExceptTables => w.push_str(" calcMode=\"autoNoTable\""), + } + // CT_CalcPr defaults: iterate off, 100 iterations, 0.001 maximum change. The limits are kept + // while iteration is off, as Options keeps them. + let calc = &wb.calc; + if calc.iterative { + w.push_str(" iterate=\"1\""); + } + if calc.iterative || calc.max_iterations != CalcSettings::DEFAULT_ITERATIONS { + let _ = write!(w, " iterateCount=\"{}\"", calc.max_iterations); + } + if calc.iterative || calc.max_change != CalcSettings::DEFAULT_CHANGE { + let _ = write!(w, " iterateDelta=\"{}\"", crate::xml::num(calc.max_change)); + } + if wb.calc.precision_as_displayed { + w.push_str(" fullPrecision=\"0\""); + } + if wb.calc.r1c1 { + w.push_str(" refMode=\"R1C1\""); + } + if needs_calc { + w.push_str(" fullCalcOnLoad=\"1\""); + } + w.push_str("/>"); + w.push_str(&pivots.workbook_xml(wb_rels)); + let exts = crate::passthrough::workbook_elements(wb, "ext"); + if !exts.is_empty() { + let _ = write!(w, "{exts}"); + } + w.push_str(""); + w +} + fn write_sheets( wb: &Workbook, out: &mut Out, From 73037efbc535e86a2e553a83bd331802e2f51796 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:08:21 -0600 Subject: [PATCH 81/95] Make pivot writer binding mutable --- crates/xlsx/src/write.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index 63e1309c25..fd6803b5c4 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -285,7 +285,7 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) }; let mut wb_rels = Rels::default(); - let (sheets_xml, kept, pivots) = write_sheets(wb, &mut out, active, &mut wb_rels); + let (sheets_xml, kept, mut pivots) = write_sheets(wb, &mut out, active, &mut wb_rels); let names = write_defined_names(wb, &kept, &out.chart_names); From ed365d95028dc0f2086d2066a534dae157dd9879 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:14:39 -0600 Subject: [PATCH 82/95] Keep workbook XML writer within lint limits --- crates/xlsx/src/write.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index fd6803b5c4..7cedac395e 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -289,7 +289,7 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) let names = write_defined_names(wb, &kept, &out.chart_names); - let w = write_workbook_xml(wb, active, &sheets_xml, &names, &kept, &mut pivots, &mut wb_rels, out.needs_calc); + let w = write_workbook_xml(WorkbookHeader { wb, active }, &sheets_xml, &names, &kept, &mut pivots, &mut wb_rels, out.needs_calc); // Workbook-level parts. let mut extra_fmts = pivots.number_formats(wb); @@ -424,9 +424,13 @@ pub fn write_xlsx_named(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>) zip.finish() } -fn write_workbook_xml( - wb: &Workbook, +struct WorkbookHeader<'a> { + wb: &'a Workbook, active: usize, +} + +fn write_workbook_xml( + header: WorkbookHeader<'_>, sheets_xml: &str, names: &str, kept: &crate::passthrough::WorkbookKept, @@ -434,6 +438,7 @@ fn write_workbook_xml( wb_rels: &mut Rels, needs_calc: bool, ) -> String { + let WorkbookHeader { wb, active } = header; let mut w = format!("{XML_DECL}"); // A workbook read from a file keeps its as it was: Excel trusts the saved values // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. From c01eb6cd2a0a4fb9af0652a6d284f74e903ae237 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 4 Nov 2026 22:24:34 -0600 Subject: [PATCH 83/95] #2641: Preserve active filter choices and index Values matching Root verified both findings, red/green regression, matcher semantics and all five quality axes; see review-4476435045-decisions.md. No additional delegate for small confirmed fixes. Fourteen scoped steps pass on the recorded tree, including engine/UI suites, strict Clippy and standalone gates. Required aggregate CI stops only at unchanged Windows CLI check.rs281; later stages skipped. Fresh hosted validation pending. --- crates/engine/src/cmd/data/filter.rs | 99 ++++++++++--------- .../tests/it/cascading_filter_values.rs | 92 +++++++++++++++-- docs/ui-parity.md | 9 +- 3 files changed, 139 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index c76701ad1d..18688e7412 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -3,6 +3,7 @@ use super::{ AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param, current_region, data_target, edit, json, }; +use std::collections::{HashMap, HashSet}; // ---------------------------------------------------------------- filter @@ -181,14 +182,11 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { } /// Statistics use the original range, regardless of the other active criteria. -fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> std::collections::HashMap, f64)> { +fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap, f64)> { let r = af.range; // Precompute per-criterion top10 threshold and average once, not per row. - let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); + let mut col_stats = HashMap::new(); for (i, (off, c)) in af.criteria.iter().enumerate() { - if Some(*off) == excluded_offset { - continue; - } if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { let Some(col) = r.start.col.checked_add(*off) else { continue }; let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); @@ -208,29 +206,46 @@ fn filter_stats(sh: &Sheet, af: &AutoFilter, excluded_offset: Option) -> st col_stats } -/// Evaluate criteria directly, without conflating manual visibility with filter results. -fn filter_row_matches( - wb: &Workbook, - sh: &Sheet, - af: &AutoFilter, - row: u32, - col_stats: &std::collections::HashMap, f64)>, - excluded_offset: Option, -) -> bool { - for (i, (off, crit)) in af.criteria.iter().enumerate() { - if Some(*off) == excluded_offset { - continue; - } - let Some(col) = af.range.start.col.checked_add(*off) else { continue }; +/// Shared row and checkbox matching, with thresholds and Values lookups prepared once per query. +struct FilterMatcher<'a> { + wb: &'a Workbook, + sh: &'a Sheet, + af: &'a AutoFilter, + stats: HashMap, f64)>, + values: HashMap>, +} + +impl<'a> FilterMatcher<'a> { + fn new(wb: &'a Workbook, sh: &'a Sheet, af: &'a AutoFilter) -> Self { + let values = af + .criteria + .iter() + .enumerate() + .filter_map(|(i, (_, crit))| match crit { + FilterCriterion::Values { values, .. } => Some((i, values.iter().map(|v| v.to_ascii_lowercase()).collect())), + _ => None, + }) + .collect(); + Self { wb, sh, af, stats: filter_stats(sh, af), values } + } + + fn row_matches(&self, row: u32, excluded_offset: Option) -> bool { + self.af.criteria.iter().enumerate().all(|(i, (off, crit))| Some(*off) == excluded_offset || self.criterion_matches(row, i, *off, crit)) + } + + fn criterion_matches(&self, row: u32, i: usize, off: u32, crit: &FilterCriterion) -> bool { + let Some(col) = self.af.range.start.col.checked_add(off) else { return true }; let c = CellRef::new(row, col); - let v = sh.value(c); - let text = crate::display::cell_text(wb, sh, c); - let ok = match crit { - FilterCriterion::Values { values, blanks } => { + let v = self.sh.value(c); + let text = crate::display::cell_text(self.wb, self.sh, c); + match crit { + FilterCriterion::Values { blanks, .. } => { if filter_blank(&v) { *blanks } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) + self.values + .get(&i) + .is_some_and(|values| values.contains(&text.to_ascii_lowercase()) || values.contains(&v.display().to_ascii_lowercase())) } } FilterCriterion::Custom { a, b, and } => { @@ -243,14 +258,14 @@ fn filter_row_matches( None => x, } } - FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { + FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), self.stats.get(&i)) { (Some(n), Some((thr, _))) => { let thr = thr.unwrap_or(n); if *bottom { n <= thr } else { n >= thr } } _ => false, }, - FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { + FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) { (Some(n), Some((_, avg))) => { if *above { n > *avg @@ -260,16 +275,12 @@ fn filter_row_matches( } _ => false, }, - FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, - FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, + FilterCriterion::FillColor(col) => self.wb.styles.get(self.sh.style_id(c)).fill.fg == *col, + FilterCriterion::FontColor(col) => self.wb.styles.get(self.sh.style_id(c)).font.color == *col, // Icon criteria are retained from files but cannot be evaluated yet. FilterCriterion::Icon { .. } => true, - }; - if !ok { - return false; } } - true } /// Hides rows of the autofilter range that fail any criterion. @@ -277,12 +288,11 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { let Some(sh) = wb.sheet(sheet) else { return }; let Some(af) = sh.autofilter.clone() else { return }; let r = af.range; - let col_stats = filter_stats(sh, &af, None); + let matcher = FilterMatcher::new(wb, sh, &af); // Reapplying a retained icon filter preserves visibility until icons can be evaluated. let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. })); - let hide: Vec<_> = (r.start.row + 1..=r.end.row) - .map(|row| (row, !filter_row_matches(wb, sh, &af, row, &col_stats, None) || (has_icon && sh.is_row_hidden(row)))) - .collect(); + let hide: Vec<_> = + (r.start.row + 1..=r.end.row).map(|row| (row, !matcher.row_matches(row, None) || (has_icon && sh.is_row_hidden(row)))).collect(); let Some(shm) = wb.sheet_mut(sheet) else { return }; for (row, h) in hide { if h { @@ -345,27 +355,18 @@ fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bo return vec![]; } let off = col - af.range.start.col; - let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); - let col_stats = if eligible_only { filter_stats(sh, af, Some(off)) } else { Default::default() }; + let selected = af.criteria.iter().enumerate().find(|(_, (o, _))| *o == off); + let matcher = FilterMatcher::new(wb, sh, af); let mut seen = std::collections::BTreeMap::new(); for row in af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)) { - if eligible_only && !filter_row_matches(wb, sh, af, row, &col_stats, Some(off)) { + if eligible_only && !matcher.row_matches(row, Some(off)) { continue; } let c = CellRef::new(row, col); let v = sh.value(c); let blank = filter_blank(&v); let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; - let on = match selected { - Some(FilterCriterion::Values { values, blanks }) => { - if blank { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&t)) - } - } - _ => true, - }; + let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit)); let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) }; seen.entry((key, t)).or_insert(on); } diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 45346b39a1..345c4f4da5 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -63,14 +63,14 @@ fn slicer_criteria_outside_the_sheet_filters_columns_are_still_applied() { #[test] fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { - for (criterion, expected) in [ - (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"]), - (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"]), - (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"]), - (json!({"top": {"count": 2}}), vec!["high", "upper"]), - (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"]), - (json!({"aboveAverage": true}), vec!["high"]), - (json!({"aboveAverage": false}), vec!["low", "mid", "upper"]), + for (criterion, expected, mid_checked) in [ + (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"], true), + (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"], false), + (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"], false), + (json!({"top": {"count": 2}}), vec!["high", "upper"], false), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"], true), + (json!({"aboveAverage": true}), vec!["high"], false), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"], true), ] { let mut s = Session::new(); s.new_workbook(); @@ -93,8 +93,8 @@ fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { assert_eq!(actual, expected, "{criterion}, with the current column filtered"); assert_eq!( filter_values(&s.doc().unwrap().wb, 0, 1), - vec![("20".into(), true)], - "the numeric column's own criterion must be excluded: {criterion}" + vec![("20".into(), mid_checked)], + "the numeric column's criterion sets checkboxes without excluding alternatives: {criterion}" ); } } @@ -220,6 +220,7 @@ fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() sh.autofilter.as_mut().unwrap().criteria = vec![(1, criterion)]; s.execute("data.reapply", json!({})).unwrap(); assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("red".into(), true)]); + assert_eq!(filter_selection(&s.doc().unwrap().wb, 0, 1, &[]), vec![("1".into(), true), ("2".into(), false)]); } let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); sh.autofilter.as_mut().unwrap().criteria = vec![(1, FilterCriterion::Icon { set: "3Arrows".into(), id: Some(0) })]; @@ -283,3 +284,74 @@ fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]); } + +#[test] +fn merging_hidden_choices_preserves_the_active_criterion() { + for (criterion, checked) in [ + (json!({"values": ["7"], "blanks": true}), [false, true, false, false, true]), + (json!({"custom": {"op": ">=", "value": 7}}), [false, true, true, true, false]), + (json!({"top": {"count": 2}}), [false, false, true, true, false]), + (json!({"aboveAverage": true}), [false, false, false, true, false]), + (json!({"aboveAverage": false}), [true, true, true, false, false]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["Region", "Amount"], ["East", 1], ["East", 9], ["West", 7], ["West", 20], ["West", null]]}), + ) + .unwrap(); + s.execute("home.numberFormat", json!({"range": "B2:B6", "code": "0.00"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + let doc = s.doc().unwrap(); + let choices = filter_values(&doc.wb, 0, 1); + let selection = filter_selection(&doc.wb, 0, 1, &choices); + let expected: Vec<_> = + ["1.00", "7.00", "9.00", "20.00", "(Blanks)"].into_iter().zip(checked).map(|(label, on)| (label.to_string(), on)).collect(); + assert_eq!(selection, expected, "unchanged eligible choices must preserve hidden matches: {criterion}"); + let values: Vec<_> = selection.iter().filter(|(label, on)| *on && label != "(Blanks)").map(|(label, _)| label.clone()).collect(); + s.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": checked[4]})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + for (row, on) in [checked[0], checked[2], checked[1], checked[3], checked[4]].into_iter().enumerate() { + assert_eq!(!sh.is_row_hidden(row as u32 + 1), on, "row after Apply and clearing the other filter: {criterion}"); + } + } +} + +#[test] +fn large_values_criteria_preserve_ascii_case_and_blank_matching() { + use gridcraft_engine::core::RangeRef; + use gridcraft_engine::model::AutoFilter; + let mut s = Session::new(); + s.new_workbook(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + let mut selected = Vec::new(); + for row in 1..=5_000 { + sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Text(format!("item-{row}").into()), ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Number(f64::from(row)), ..Default::default() }); + selected.push(format!("ITEM-{row}")); + } + selected.extend(["ITEM-1".into(), "Ä".into()]); + for (row, value, label) in [ + (5_001, Value::Text("Ä".into()), "unicode selected"), + (5_002, Value::Text("ä".into()), "unicode excluded"), + (5_003, Value::Empty, "blank row"), + ] { + sh.set_cell(CellRef::new(row, 0), Cell { value, ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Text(label.into()), ..Default::default() }); + } + sh.autofilter = Some(AutoFilter { + range: RangeRef::new(CellRef::new(0, 0), CellRef::new(5_003, 1)), + criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })], + }); + let choices = filter_values(&s.doc().unwrap().wb, 0, 1); + assert_eq!(choices.len(), 5_002); + assert!(choices.contains(&("unicode selected".into(), true))); + assert!(choices.contains(&("blank row".into(), true))); + assert!(!choices.iter().any(|(label, _)| label == "unicode excluded")); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c94ccb7550..eb86b356e7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (cascading AutoFilter choices and pending popup selections per document window; 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) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (AutoFilter checkbox state follows the active criterion and Values lookups are prepared once per query; earlier: cascading AutoFilter choices and pending popup selections per document window; 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) · **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 @@ -14,6 +14,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Element | Excel | GridCraft | Status | |---|---|---|---| +| 2026-11-04 | minor | AutoFilter checkboxes and hidden-choice merging use the active row criterion, including raw/formatted Values, custom comparisons, Top 10, averages and colors; Values criteria use one prepared ASCII-insensitive lookup per query (#2641) | | 2026-10-14 | minor | Dialogs (Find and Replace, Go To, Format Cells, Sort and the rest) move by their title bar instead of staying pinned to the centre (#1250) | | Title bar, Quick Access Toolbar, AutoSave toggle | yes | yes | done; macOS window controls misaligned (#170), Dock icon size (#169) | | Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow | @@ -86,6 +87,10 @@ this logic, with one undo step. describes additive column filters and restricting other dropdowns to the filtered range. The current column is excluded from enumeration so its unchecked alternatives remain available. The existing one-million-data-row enumeration limit and value sorting remain unchanged. +Checkbox state uses the row matcher for the active criterion, including raw and formatted +Values matches, custom comparisons, numeric thresholds and colors. Hidden choices retain +that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive +lookup sets once per query rather than scanning every selected value for each row. This changes the population behind the pending row-count work (#1737, and its stacked Only button #1741): a future count beside a choice should count eligible rows satisfying the other @@ -287,7 +292,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-31 | minor | Esc in a File-page text field leaves the field and cancels editing; the next Esc returns to the sheet (#3035) | | 2026-10-31 | minor | Recently Used lists the functions most recently entered in a formula from any source, kept with the preferences; the Insert Function dialog is titled as in Excel, its category list (Most Recently Used, All, each category) works, and its category column follows the widest name shown | | 2026-10-31 | minor | Formulas › Function Library: Insert Function, the AutoSum split button and three columns of labelled small buttons with category colours; category menus end with Insert Function…; More Functions cascades; Home › Editing shares the AutoSum menu; MR key tip for Recently Used | -| 2026-10-30 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); Apply without search preserves selected and excluded values and blanks hidden by other filters; searched Apply excludes hidden nonmatches while retaining hidden matches; document pending counts, date grouping and table roundtrip integration; retain slicer row filtering when its criterion is outside the sheet filter columns | +| 2026-10-30 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); Apply without search preserves selected and excluded values and blanks hidden by other filters; searched Apply excludes hidden nonmatches while retaining hidden matches; documents pending counts, date grouping and table roundtrip integration; retains slicer row filtering when its criterion is outside the sheet filter columns | | 2026-10-30 | minor | Checkbox cells print and export to PDF as boxes, as on screen: unchecked white with a grey outline, checked green with a white tick (#2972). They printed their value as TRUE or FALSE; other values in a checkbox cell still print as text | | 2026-10-29 | minor | Formula pointing from the keyboard: Ctrl+arrow (⌘arrow) moves the pointed cell to the edge of its data and Ctrl+Shift+arrow (⌘⇧arrow) extends the pointed range there, as the same keys move and extend the selection, so typing `=COUNTIF(`, clicking the top of a column and pressing ⌘⇧↓ points at the whole column of data; the keys used to move or extend by one cell. A range reaching the sheet edge is written as whole columns or rows (`A:B`). The editor reads the modifiers of the arrow's own key event, so a keystroke pressed and released within one frame (a control client's `ui.key`, an automation tool) keeps its Shift and Ctrl | | 2026-10-29 | minor | Insert Hyperlink opens with an existing link's address, display text and ScreenTip (#2876). An address-only edit preserves the cell's content and formula; Cancel leaves the link unchanged, and Undo restores the edit | From 1baac9125c76b349ef9316f6e8b43d6c13171a02 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 4 Nov 2026 22:54:44 -0600 Subject: [PATCH 84/95] #2641: Put the parity revision entry in its history table Move the existing Nov4 row intact out of Window and chrome. All other lines and all production/test/dependency trees are identical to the preceding head. Structural and fmt checks pass; required aggregate CI still stops only at the unchanged Windows CLI lint. Runtime suites are not repeated for this documentation-only move. --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index eb86b356e7..568fd86479 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -14,7 +14,6 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Element | Excel | GridCraft | Status | |---|---|---|---| -| 2026-11-04 | minor | AutoFilter checkboxes and hidden-choice merging use the active row criterion, including raw/formatted Values, custom comparisons, Top 10, averages and colors; Values criteria use one prepared ASCII-insensitive lookup per query (#2641) | | 2026-10-14 | minor | Dialogs (Find and Replace, Go To, Format Cells, Sort and the rest) move by their title bar instead of staying pinned to the centre (#1250) | | Title bar, Quick Access Toolbar, AutoSave toggle | yes | yes | done; macOS window controls misaligned (#170), Dock icon size (#169) | | Ribbon: tabs, groups, split buttons, galleries, contextual tabs | yes | yes (Table Design, Chart Design, Format, PivotTable, Header & Footer tabs); Fill Color, Font Color and the Format Cells colour pickers end with Recent Colors and More Colors… (#928); large split buttons (Formulas › AutoSum); arrows at the card's edges scroll a tab wider than the window | done; missing contextual tabs for pictures, shapes, sparklines, slicers; groups do not collapse when narrow | @@ -266,6 +265,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | AutoFilter checkboxes and hidden-choice merging use the active row criterion, including raw/formatted Values, custom comparisons, Top 10, averages and colors; Values criteria use one prepared ASCII-insensitive lookup per query (#2641) | | 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 | | 2026-11-03 | minor | Highlight the active cell's row: a global preference that tints the whole row, off by default | | 2026-11-03 | minor | The formula bar's bottom edge is a resize handle: dragging it sets the bar's height in whole lines, up to half the window, and dragging it to one line collapses it; expanding (the chevron, Ctrl+Shift+U) returns to the dragged height, which is kept with the UI preferences. `view.expandFormulaBar {lines}` sets it (#1246) | From f0de6913d1acbd9e4f8c96f7a5e918a282fe1013 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Wed, 4 Nov 2026 23:01:12 -0600 Subject: [PATCH 85/95] #2641: Assert every large Values filter choice Strengthen the existing fixture to check the complete sorted list and checkbox states. Production, docs, manifests and lock unchanged. Engine integration113, strict engine Clippy, fmt and diff checks pass. Required aggregate CI stops only at unchanged Windows CLI check.rs281; later aggregate stages skipped. --- crates/engine/tests/it/cascading_filter_values.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 345c4f4da5..125df8b5c6 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -350,8 +350,7 @@ fn large_values_criteria_preserve_ascii_case_and_blank_matching() { criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })], }); let choices = filter_values(&s.doc().unwrap().wb, 0, 1); - assert_eq!(choices.len(), 5_002); - assert!(choices.contains(&("unicode selected".into(), true))); - assert!(choices.contains(&("blank row".into(), true))); - assert!(!choices.iter().any(|(label, _)| label == "unicode excluded")); + let mut expected: Vec<_> = (1..=5_000).map(|n| (n.to_string(), true)).collect(); + expected.extend([("blank row".into(), true), ("unicode selected".into(), true)]); + assert_eq!(choices, expected); } From 5d578bef00919d072c9620edd24c366d0b310708 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:05:11 -0600 Subject: [PATCH 86/95] Record model SHA-1 dependency in lockfile --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index dfdde30e7d..1c69b16c3f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2150,6 +2150,7 @@ dependencies = [ "gridcraft-math", "serde", "serde_json", + "sha1 0.11.0", "sha2 0.11.1", "thiserror 2.0.21", ] From 30f24fd2399b32ce3180cbd52e5e50ce840c3f54 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:05:00 -0600 Subject: [PATCH 87/95] Pass series index to chart table lookup --- crates/chart/src/render/table.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index f0839dcfef..4f641afd25 100644 --- a/crates/chart/src/render/table.rs +++ b/crates/chart/src/render/table.rs @@ -70,7 +70,7 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay let y = top + (layout.headers as f32 + i as f32 + 0.5) * layout.row_height; let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; if settings.show_keys { - let swatch = match plot_kind(chart, series) { + let swatch = match plot_kind(chart, series, i) { ChartKind::Line | ChartKind::LineStacked => Swatch::Line, ChartKind::LineMarkers => Swatch::LineMarker, _ => Swatch::Box, From 19b8009d2a45b1b96d00537f1ccea928d144f0f0 Mon Sep 17 00:00:00 2001 From: TheRenegadeDev Date: Tue, 10 Nov 2026 08:04:37 -0600 Subject: [PATCH 88/95] 2641: preserve filter choices across colors and window actions Keep a duplicate value checked when any eligible row matches the current criterion. Stop processing outgoing popup state when a form button switches the active window during grid interaction. Add regressions for fill/font color duplicates, other-column exclusion, unchanged Apply, and a real button press preserving another window's search and checkbox edits. --- crates/engine/src/cmd/data/filter.rs | 3 +- .../tests/it/cascading_filter_values.rs | 39 +++++++++++++ crates/ui-egui/src/grid/show.rs | 5 ++ .../tests/it/cascading_filter_values.rs | 56 +++++++++++++++++++ docs/ui-parity.md | 8 ++- 5 files changed, 107 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index a94c0efcae..b9d794b56d 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -368,7 +368,8 @@ fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bo let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit)); let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) }; - seen.entry((key, t)).or_insert(on); + // One choice can represent rows with different colors; keep any matching row checked. + *seen.entry((key, t)).or_insert(false) |= on; } let mut values: Vec<_> = seen.into_iter().collect(); values.sort_by(|((a, ta), _), ((b, tb), _)| { diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs index 125df8b5c6..afd72ef00b 100644 --- a/crates/engine/tests/it/cascading_filter_values.rs +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -233,6 +233,45 @@ fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() ); } +#[test] +fn duplicate_color_choices_keep_any_eligible_match() { + for font in [false, true] { + for matching_cell in ["B2", "B3"] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["Company", "Color"], ["East", "Same"], ["East", "Same"], ["West", "Same"]]}), + ) + .unwrap(); + let command = if font { "home.fontColor" } else { "home.fillColor" }; + s.execute(command, json!({"range": "B4", "color": "#FF0000"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + let color = if font { FilterCriterion::FontColor(Color::Rgb(0xFF0000)) } else { FilterCriterion::FillColor(Color::Rgb(0xFF0000)) }; + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false }), (1, color)]; + s.execute("data.reapply", json!({})).unwrap(); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 1), + vec![("Same".into(), false)], + "an excluded red row cannot check an eligible choice" + ); + + s.execute(command, json!({"range": matching_cell, "color": "#FF0000"})).unwrap(); + s.execute("data.reapply", json!({})).unwrap(); + let choices = filter_values(&s.doc().unwrap().wb, 0, 1); + assert_eq!(choices, vec![("Same".into(), true)], "either eligible duplicate can supply the color match"); + let selected = filter_selection(&s.doc().unwrap().wb, 0, 1, &choices); + assert_eq!(selected, vec![("Same".into(), true)]); + let values: Vec<_> = selected.into_iter().filter_map(|(value, on)| on.then_some(value)).collect(); + s.execute("data.filterBy", json!({"column": "B", "values": values})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(!sh.is_row_hidden(CellRef::parse(matching_cell).unwrap().row), "unchanged Apply keeps the previously matching row"); + assert!(sh.is_row_hidden(3), "the other column still excludes West"); + } + } +} + #[test] fn querying_a_table_backed_sheet_filter_is_read_only_and_preserves_xlsx_criteria() { for table in [false, true] { diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 178039abe7..13aed13989 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -360,6 +360,7 @@ impl Geo> ActiveCellVisibility<'_, F> { } fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &Geo, sh: &Sheet, wb: &Workbook) { + let window = app.session.active_window(); let previous_popups = (app.grid.filter_menu, app.grid.list_picker, app.grid.header_menu, app.grid.fill_menu); // A pan the grid never saw end (it was hidden mid-drag) must not swallow the next press. if app.grid.touch_pan && !resp.dragged() && !resp.drag_stopped() { @@ -374,6 +375,10 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re crate::paper_view::interact(app, ui, resp, geo, sh, wb); interact(app, ui, resp, geo, sh, wb); } + // A form button can switch windows and swap GridState; the old popup and geometry belong to the outgoing window. + if app.session.active_window() != window { + return; + } if previous_popups.0 != app.grid.filter_menu && previous_popups.0.is_some() { app.grid.filter_checks = None; app.grid.filter_search.clear(); diff --git a/crates/ui-egui/tests/it/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs index ba7bc0abff..da6cc24d35 100644 --- a/crates/ui-egui/tests/it/cascading_filter_values.rs +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -4,6 +4,7 @@ use egui::{Event, Key, Modifiers, PointerButton}; use egui_kittest::kittest::{NodeT, Queryable}; use gridcraft_engine::Session; use gridcraft_engine::core::CellRef; +use gridcraft_engine::model::{ObjKind, ObjRef}; use gridcraft_ui_egui::grid; use serde_json::json; @@ -134,6 +135,61 @@ fn switching_filter_columns_keeps_another_windows_pending_choices() { assert!(h.state().session.active().unwrap().wb.active().unwrap().autofilter.as_ref().unwrap().criteria.is_empty(), "no filter was applied"); } +#[test] +fn a_form_button_window_switch_keeps_the_incoming_filter_edits() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute("range.setValues", json!({"range": "A1", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + let button = session.execute("insert.button", json!({"at": "E12", "text": "Other window"})).unwrap()["control"].as_u64().unwrap() as u32; + let image = std::env::var("GRIDCRAFT_FILTER_BUTTON_WINDOW_SNAPSHOT").ok(); + let builder = common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)); + let builder = if image.is_some() { builder.wgpu() } else { builder }; + let mut h = common::harness_with(builder, common::app(session), 4); + let first = h.state().session.active_window().unwrap(); + click_filter(&mut h, "A1"); + h.state_mut().run("view.newWindow", json!({})).unwrap(); + h.run_steps(3); + let second = h.state().session.active_window().unwrap(); + h.state_mut().run("control.assign", json!({"id": button, "command": "view.switchWindows", "params": {"window": second}})).unwrap(); + click_filter(&mut h, "B1"); + h.input_mut().events.push(Event::Text("Bet".into())); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + let checks = h.state().grid.filter_checks.clone(); + assert_eq!(h.state().grid.filter_search, "Bet"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = &image { + h.render().unwrap().save(std::path::Path::new(path).with_extension("before.png")).unwrap(); + } + + h.state_mut().enter_window(first); + h.run_steps(2); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let at = gridcraft_ui_egui::chartview::object_rect(&geo, sh, ObjRef::new(ObjKind::Control, button)).unwrap().center(); + for pressed in [true, false] { + h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE)); + h.input_mut().events.push(Event::PointerMoved(at)); + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + assert_eq!(h.state().session.active_window(), Some(second), "the real button action switches windows during grid interaction"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1)); + assert_eq!(h.state().grid.filter_search, "Bet", "the outgoing popup must not clear the incoming search"); + assert_eq!(h.state().grid.filter_checks, checks, "the incoming window keeps its unsaved checkbox edits"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = image { + h.render().unwrap().save(path).unwrap(); + } +} + #[test] fn applying_eligible_choices_preserves_values_and_blanks_hidden_by_another_filter() { for table in [false, true] { diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1aeb561b42..e40d721fff 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (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: AutoFilter checkbox state follows the active criterion and Values lookups are prepared once per query; earlier: cascading AutoFilter choices and pending popup selections per document window; 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) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (retain duplicate color-filter matches and pending popup edits across form-button window switches; 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: AutoFilter checkbox state follows the active criterion and Values lookups are prepared once per query; earlier: cascading AutoFilter choices and pending popup selections per document window; 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) · **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 @@ -87,8 +87,9 @@ describes additive column filters and restricting other dropdowns to the filtere current column is excluded from enumeration so its unchecked alternatives remain available. The existing one-million-data-row enumeration limit and value sorting remain unchanged. Checkbox state uses the row matcher for the active criterion, including raw and formatted -Values matches, custom comparisons, numeric thresholds and colors. Hidden choices retain -that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive +Values matches, custom comparisons, numeric thresholds and colors. A duplicate choice is +checked when any eligible row matches, including when those rows have different colors. +Hidden choices retain that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive lookup sets once per query rather than scanning every selected value for each row. This changes the population behind the pending row-count work (#1737, and its stacked Only @@ -290,6 +291,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Keep duplicate choices checked when any eligible row matches a color filter; a form-button window switch preserves the incoming window's pending filter search and checkbox edits (#2641) | | 2026-11-05 | minor | Reconcile upstream form-control coverage with the CJK baseline and cell-alignment updates | | 2026-11-04 | minor | Keep centered emoji and symbol fallback placement when a row starts with a fallback or contains only fallbacks; use primary or baseline-aligned glyphs to anchor cell alignment | | 2026-11-04 | minor | Preserve leading and trailing blank lines in wrapped cells when calculating vertical alignment; regression covers single, multiple and all-empty lines | From 2a506bfc851c6f0821e84be7c7d5acdab5ce722a Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 09:04:00 +0000 Subject: [PATCH 89/95] model::paper: one paper-size table for print layout and XLSX Paper names and sizes now live in one table, `gridcraft_model::paper` (`canonical`, `size_pt`, `for_size`). The engine's `known_paper` and the XLSX writer's alias list read it instead of keeping their own copies. - Page Setup and `pageLayout.size` store a known paper under its table name (`11x17` -> `Tabloid`, `b5-jis` -> `B5`), so every file format finds it. - XLSX paper id 34 (ECMA-376 "B5 envelope, 176 x 250 mm", the ISO B5 size) reads as `B5 (ISO)`; `B5 (ISO)` now saves with paperSize 34 instead of none. `Envelope B5` is still accepted as an alias. - Statement, Envelope #10 and Envelope DL print on their own size. - `PrintSettings::paper` documents an empty name as "the file stated no paper": layout falls back to Letter and XLSX writes no paperSize. New sheets still default to Letter. --- crates/engine/src/cmd/print.rs | 7 +- crates/engine/src/cmd/print/layout.rs | 39 +--------- crates/engine/src/cmd/print/tests.rs | 28 +++++++ crates/engine/src/cmd/view.rs | 4 +- crates/model/src/features/print.rs | 5 +- crates/model/src/lib.rs | 1 + crates/model/src/paper.rs | 108 ++++++++++++++++++++++++++ crates/xlsx/src/tables.rs | 26 ++----- crates/xlsx/src/tests/roundtrip.rs | 19 +++++ docs/architecture.md | 5 +- docs/file-format-parity.md | 3 +- 11 files changed, 181 insertions(+), 64 deletions(-) create mode 100644 crates/model/src/paper.rs diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index b3ce40d583..a76f45c5e8 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -39,7 +39,7 @@ type PicCache = std::collections::HashMap<(usize, usize), Option<(Vec, u32, use layout::bands; pub(crate) use layout::split_bands; pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range}; -use layout::{known_paper, seg_size, segments}; +use layout::{seg_size, segments}; use objects::draw_objects; #[cfg(test)] use text::{center_across_width, wrap_lines}; @@ -258,8 +258,9 @@ fn page_setup(s: &mut Session, p: &Json) -> Result { let paper = match str_param(p, "paper") { None => None, Some(name) => { - known_paper(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?; - Some(name.trim().to_string()) + // Stored under its table name, which every file format knows. + let paper = gridcraft_model::paper::canonical(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?; + Some(paper.to_string()) } }; let margin_src = p.get("margins").filter(|m| m.is_object()).unwrap_or(p); diff --git a/crates/engine/src/cmd/print/layout.rs b/crates/engine/src/cmd/print/layout.rs index 0f484f8755..3c21ed1154 100644 --- a/crates/engine/src/cmd/print/layout.rs +++ b/crates/engine/src/cmd/print/layout.rs @@ -9,43 +9,10 @@ pub(super) const DENSE_BLOCK: u64 = 60_000; // ---------------------------------------------------------------- paper -/// Paper size in points (portrait) for a paper name; unknown names fall back to Letter. +/// Paper size in points, as named (see `gridcraft_model::paper`); unknown names, and the empty +/// name of a file that stated no paper, fall back to Letter. pub fn paper_size(name: &str) -> (f32, f32) { - known_paper(name).unwrap_or((612.0, 792.0)) -} - -/// Paper sizes in points, portrait. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel and its -/// e-mail attachments use (257×364, 182×257 and 128×182 mm); the ISO B series stays reachable as -/// `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and envelopes are the JIS ones too. -pub(super) fn known_paper(name: &str) -> Option<(f32, f32)> { - // Spaces, hyphens, underscores and parentheses don't matter: `B5 (JIS)`, `b5-jis` and `b5` - // are one name. - let n = name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], ""); - Some(match n.as_str() { - "letter" | "usletter" => (612.0, 792.0), - "legal" | "uslegal" => (612.0, 1008.0), - "a4" => (595.28, 841.89), - "a3" => (841.89, 1190.55), - "a5" => (419.53, 595.28), - "a6" => (297.64, 419.53), - "tabloid" | "11x17" => (792.0, 1224.0), - "ledger" => (1224.0, 792.0), - "executive" => (522.0, 756.0), - "b4" | "b4jis" => (728.50, 1031.81), - "b5" | "b5jis" => (515.91, 728.50), - "b6" | "b6jis" => (362.83, 515.91), - "b4iso" => (708.66, 1000.63), - "b5iso" => (498.90, 708.66), - "b6iso" => (354.33, 498.90), - "japanesepostcard" | "postcard" => (283.46, 419.53), - "japanesedoublepostcard" | "doublepostcard" => (419.53, 566.93), - "japaneseenvelope#3" | "chou#3" => (340.16, 666.14), - // 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out. - "japaneseenvelope#4" | "chou#4" => (255.12, 581.10), - "japaneseenvelopekaku#2" | "kaku#2" => (680.31, 941.10), - "japaneseenvelopekaku#3" | "kaku#3" => (612.28, 785.20), - _ => return None, - }) + gridcraft_model::paper::size_pt(name).unwrap_or((612.0, 792.0)) } // ---------------------------------------------------------------- layout diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 3230604702..ee22e14e20 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -631,6 +631,34 @@ fn page_setup_paper_sizes_reach_the_pdf_page() { assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err()); } +/// An empty paper name means the file stated none; it prints on Letter. +#[test] +fn an_unstated_paper_prints_on_letter() { + let mut wb = gridcraft_model::Workbook::new(); + std::sync::Arc::make_mut(&mut wb.sheets[0]).set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into())); + std::sync::Arc::make_mut(&mut wb.sheets[0]).print.paper = String::new(); + let layouts = super::layout::layouts(&wb, &super::layout::PrintOptions::default()); + let l = &layouts[0]; + assert_eq!((l.page_w, l.page_h), (612.0, 792.0)); + assert_eq!(paper_size(""), (612.0, 792.0)); +} + +/// Both commands that set the paper store a known one under its table name, so every file +/// format finds it. +#[test] +fn paper_size_commands_store_the_table_name() { + let mut s = s(); + s.execute("pageLayout.size", json!({"paper": "b5-jis"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "B5"); + s.execute("pageLayout.pageSetup", json!({"paper": "11x17"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "Tabloid"); + // Statement and the envelopes Excel names now print on their own size. + s.execute("pageLayout.pageSetup", json!({"paper": "Envelope DL"})).unwrap(); + assert_eq!(paper_size("Statement"), (396.0, 612.0)); + // A new workbook still prints on Letter. + assert_eq!(gridcraft_model::Workbook::new().sheets[0].print.paper, "Letter"); +} + #[test] fn hostile_settings_never_panic_and_cap_pages() { let mut s = s(); diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 3631d0e561..d6d56b0509 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -296,7 +296,9 @@ fn orientation(s: &mut Session, p: &Json) -> Result { } fn paper(s: &mut Session, p: &Json) -> Result { - let paper = str_param(p, "paper").unwrap_or("Letter").to_string(); + // A known paper is stored under its table name; any other name is kept (it prints on Letter). + let name = str_param(p, "paper").unwrap_or("Letter"); + let paper = gridcraft_model::paper::canonical(name).unwrap_or(name).to_string(); edit(s, |cx| { let si = cx.sheet_index(); cx.sheet_mut(si)?.print.paper = paper.clone(); diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 694c2ac6da..049ac454d0 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -11,7 +11,10 @@ pub enum Orientation { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrintSettings { pub orientation: Orientation, - /// Paper size name (`Letter`, `A4`, `Legal`…). + /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]), or empty when the file + /// stated none: the printer's or locale's paper then, which an ODF file leaves to the + /// application. Print layout falls back to Letter and XLSX writes no `paperSize`. New sheets + /// default to Letter. pub paper: String, /// Margins in inches: left, right, top, bottom, header, footer. pub margins: [f32; 6], diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 35cfa315f8..65f2e819c7 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -9,6 +9,7 @@ pub mod cell; mod cellmap; pub mod features; pub mod macros; +pub mod paper; pub mod password; pub mod preserved; pub mod python; diff --git a/crates/model/src/paper.rs b/crates/model/src/paper.rs new file mode 100644 index 0000000000..b3068e6aab --- /dev/null +++ b/crates/model/src/paper.rs @@ -0,0 +1,108 @@ +//! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats +//! (XLSX paper ids, ODF page sizes) and print layout all read this one table. + +/// Paper names and sizes in points, width then height, as the paper is named: Ledger is +/// Tabloid turned on its side. Each size has one name, so a size reads back as the name it was +/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and +/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and +/// envelopes are the JIS ones too. +pub const PAPERS: [(&str, f32, f32); 24] = [ + ("Letter", 612.0, 792.0), + ("Legal", 612.0, 1008.0), + ("A4", 595.28, 841.89), + ("A3", 841.89, 1190.55), + ("A5", 419.53, 595.28), + ("A6", 297.64, 419.53), + ("Tabloid", 792.0, 1224.0), + ("Ledger", 1224.0, 792.0), + ("Executive", 522.0, 756.0), + ("Statement", 396.0, 612.0), + ("B4", 728.50, 1031.81), + ("B5", 515.91, 728.50), + ("B6", 362.83, 515.91), + ("B4 (ISO)", 708.66, 1000.63), + ("B5 (ISO)", 498.90, 708.66), + ("B6 (ISO)", 354.33, 498.90), + ("Envelope #10", 297.0, 684.0), + ("Envelope DL", 311.81, 623.62), + ("Japanese Postcard", 283.46, 419.53), + ("Japanese Double Postcard", 419.53, 566.93), + ("Japanese Envelope #3", 340.16, 666.14), + // 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out. + ("Japanese Envelope #4", 255.12, 581.10), + ("Japanese Envelope Kaku #2", 680.31, 941.10), + ("Japanese Envelope Kaku #3", 612.28, 785.20), +]; + +/// Other spellings of the names above, in [`key`] form. +const ALIASES: [(&str, &str); 13] = [ + // The B5 envelope is ISO B5 itself (176×250 mm): one size, one name. + ("envelopeb5", "B5 (ISO)"), + ("usletter", "Letter"), + ("uslegal", "Legal"), + ("11x17", "Tabloid"), + ("b4jis", "B4"), + ("b5jis", "B5"), + ("b6jis", "B6"), + ("postcard", "Japanese Postcard"), + ("doublepostcard", "Japanese Double Postcard"), + ("chou#3", "Japanese Envelope #3"), + ("chou#4", "Japanese Envelope #4"), + ("kaku#2", "Japanese Envelope Kaku #2"), + ("kaku#3", "Japanese Envelope Kaku #3"), +]; + +/// A name as compared: spaces, hyphens, underscores and parentheses don't matter, nor does case +/// (`B5 (JIS)`, `b5-jis` and `b5jis` are one name). +fn key(name: &str) -> String { + name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], "") +} + +/// The paper `name` stands for, under its table name. +pub fn canonical(name: &str) -> Option<&'static str> { + // No paper name is long; a huge one (from a file or a command) is not worth folding. + if name.len() > 64 { + return None; + } + let k = key(name); + PAPERS.iter().map(|(n, _, _)| *n).find(|n| key(n) == k).or_else(|| ALIASES.iter().find(|(a, _)| *a == k).map(|(_, n)| *n)) +} + +/// The size of paper `name` in points (width, height). +pub fn size_pt(name: &str) -> Option<(f32, f32)> { + let n = canonical(name)?; + PAPERS.iter().find(|(p, _, _)| *p == n).map(|(_, w, h)| (*w, *h)) +} + +/// The paper of a page `width` × `height` points, within 2 mm: as it stands, else turned. +pub fn for_size(width: f32, height: f32) -> Option<&'static str> { + let near = |a: f32, b: f32| (a - b).abs() < 5.67; + let find = |w: f32, h: f32| PAPERS.iter().find(|(_, pw, ph)| near(*pw, w) && near(*ph, h)).map(|(n, _, _)| *n); + find(width, height).or_else(|| find(height, width)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_sizes() { + assert_eq!(size_pt("b5-jis"), Some((515.91, 728.50))); + assert_eq!(size_pt("US Letter"), Some((612.0, 792.0))); + assert_eq!(size_pt("nonsense"), None); + assert_eq!(for_size(1224.0, 792.0), Some("Ledger")); + assert_eq!(for_size(792.0, 1224.0), Some("Tabloid")); + assert_eq!(for_size(842.0, 595.0), Some("A4")); + assert_eq!(canonical("ledger"), Some("Ledger")); + assert_eq!(canonical(""), None); + assert_eq!(canonical(&"A4".repeat(1000)), None); + } + + #[test] + fn every_size_reads_back_as_its_name() { + for (name, w, h) in PAPERS { + assert_eq!(for_size(w, h), Some(name), "{name}"); + } + assert_eq!(canonical("Envelope B5"), Some("B5 (ISO)")); + } +} diff --git a/crates/xlsx/src/tables.rs b/crates/xlsx/src/tables.rs index 3cfd84c2dc..2ad41e9d4f 100644 --- a/crates/xlsx/src/tables.rs +++ b/crates/xlsx/src/tables.rs @@ -57,7 +57,8 @@ pub use gridcraft_core::color::INDEXED; /// Paper sizes (`pageSetup paperSize`) we name. ID 12/13 are the JIS B4/B5 that /// `pageLayout.pageSetup` calls `B4`/`B5`; 42 is ISO B4, and 43–88 are the Japanese postcards, -/// envelopes and B6. The engine's `known_paper` uses the same names and sizes. +/// envelopes and B6. Their sizes are in `gridcraft_model::paper`, under the same names. 34 is +/// ECMA-376's "B5 envelope (176 mm by 250 mm)": the ISO B5 size, so it reads as `B5 (ISO)`. const PAPERS: [(u32, &str); 23] = [ (1, "Letter"), (3, "Tabloid"), @@ -72,7 +73,7 @@ const PAPERS: [(u32, &str); 23] = [ (13, "B5"), (20, "Envelope #10"), (27, "Envelope DL"), - (34, "Envelope B5"), + (34, "B5 (ISO)"), (42, "B4 (ISO)"), (43, "Japanese Postcard"), (69, "Japanese Double Postcard"), @@ -88,25 +89,10 @@ pub fn paper_name(id: u32) -> Option<&'static str> { PAPERS.iter().find(|(i, _)| *i == id).map(|(_, n)| *n) } -/// The file ID for a paper name. Spelling is loose like `known_paper`'s — spaces, hyphens, -/// underscores and parentheses don't matter, and the JIS/ISO and Japanese-envelope spellings the -/// page-setup commands take are folded onto the name in [`PAPERS`]. +/// The file ID for a paper name, spelled any way [`gridcraft_model::paper::canonical`] takes. pub fn paper_id(name: &str) -> Option { - let norm = |s: &str| s.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], ""); - let normalized = norm(name); - let alias = match normalized.as_str() { - "b4jis" => "b4", - "b5jis" => "b5", - "b6jis" => "b6", - "postcard" => "japanesepostcard", - "doublepostcard" => "japanesedoublepostcard", - "chou#3" => "japaneseenvelope#3", - "chou#4" => "japaneseenvelope#4", - "kaku#2" => "japaneseenvelopekaku#2", - "kaku#3" => "japaneseenvelopekaku#3", - other => other, - }; - PAPERS.iter().find(|(_, n)| norm(n) == alias).map(|(i, _)| *i) + let name = gridcraft_model::paper::canonical(name)?; + PAPERS.iter().find(|(_, n)| *n == name).map(|(i, _)| *i) } /// Functions introduced after Excel 2007 that files store with the `_xlfn.` prefix. Entries with diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 4eb6c3cfe2..4bcb39a041 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1421,6 +1421,25 @@ fn japanese_paper_sizes_round_trip() { assert_eq!(back.sheet(0).unwrap().print.paper, "B5"); } +/// The paper names every spelling folds onto keep their file id: `11x17` is Tabloid (3), and +/// ISO B5 is id 34 (ECMA-376's 176×250 mm "B5 envelope"), read back as `B5 (ISO)`. An empty +/// paper (the file stated none) writes no `paperSize`, so the reader's own paper applies. +#[test] +fn paper_names_keep_their_xlsx_id_and_an_unstated_paper_writes_none() { + for (paper, id, back_as) in [("11x17", 3, "Tabloid"), ("US Legal", 5, "Legal"), ("B5 (ISO)", 34, "B5 (ISO)"), ("Envelope B5", 34, "B5 (ISO)")] { + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().print.paper = paper.into(); + let bytes = write_xlsx(&wb).unwrap(); + assert!(sheet1_xml(&bytes).0.contains(&format!("paperSize=\"{id}\"")), "{paper}"); + let (back, _) = read_xlsx(&bytes).unwrap(); + assert_eq!(back.sheet(0).unwrap().print.paper, back_as); + } + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().print.paper = String::new(); + let (xml, _) = sheet1_xml(&write_xlsx(&wb).unwrap()); + assert!(!xml.contains("paperSize"), "{xml}"); +} + /// A table's dropdown filter lives in `sheet.autofilter` (the engine's only live filter state), /// not in `Table::filter`. Writing used to suppress the sheet `` because a table /// intersects it and write the table part from `Table::filter`, which was empty: the criteria diff --git a/docs/architecture.md b/docs/architecture.md index 68639541ea..df3e2ac134 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (paper names and sizes in one table, `model::paper`; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) How GridCraft is built today. Rules for contributors are in [`AGENTS.md`](../AGENTS.md). @@ -17,7 +17,7 @@ including tests, 2026-10-10. | L1 | `formula` | ~1.7k | Tokenizer, parser, AST, printer (A1 and R1C1), reference adjustment for copy, fill and structural edits | | L1 | `functions` | ~13.4k | The function library: `FnSpec` registry (name, arity, category, scalar args, signature, description) and pure implementations; automatic array lifting | | L1 | `math` | ~1.1k | Equations: LaTeX laid out by RaTeX (MIT, pinned) into plain glyph, rule and path data, and LaTeX to Office Math; every entry point capped and panic-guarded | -| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings, protection | +| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings (paper names and sizes in `paper`, the one table file formats and print layout read), protection | | L2 | `calc` | ~2.9k | Evaluator (references, names, tables, LET/LAMBDA, special forms like OFFSET/INDIRECT/SUBTOTAL) and dependency-graph recalculation with dynamic arrays, spills and cycle detection; single-threaded | | L2 | `xlsx` | ~10.7k | XLSX read/write (transitional and strict read), CSV/TSV, XLSB and ODS data import, PivotTable caches, DrawingML charts and drawings; byte slices only (WASM-safe); lenient reader that reports warnings | | L2 | `pdf` | ~1k | Small PDF 1.7 writer (14 standard fonts, vectors, images) for print and export | @@ -236,6 +236,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means the file stated none | | 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` | | 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused | | 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d2660dde02..981ddd3fa5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-03 · **Change:** minor (a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-11 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)`, and an empty paper name, a file that stated none, writes no `paperSize`; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -158,6 +158,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | One paper table (`model::paper`) behind XLSX `paperSize` and print layout; id 34 reads as `B5 (ISO)`, the ISO B5 size; `B5 (ISO)` and every alias save with their id; an empty paper writes no `paperSize` | | 2026-11-03 | minor | SYLK (`.slk`) import: values, R1C1 formulas as A1 (shared formulas too) with cached results, number formats and column widths; import only (#1481) | | 2026-11-03 | minor | Opening a web page (HTML) reads its first table as a sheet, whatever the file is called: a web app's "Export to Excel" saved as `.xls` no longer opens as lines of markup. Values read as in a CSV (or as text with `csvAsText`), `
` cells are bold and centred, `` names the sheet, and a page not named `.htm`/`.html` opens with a warning (#3166) | | 2026-11-03 | minor | XLSX `` (Remove personal information from file properties on save) is read and written back, and while it is on GridCraft saves no author (`dc:creator`) and no company, as Excel leaves them empty (#3089, file part) | From f21dc313dbe38bbf5b6530563501f98362c5de67 Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 10:28:45 +0000 Subject: [PATCH 90/95] model::paper: nearest-size match, new papers documented and tested - for_size picks the nearest paper within 2 mm (as it stands, else turned) instead of the first in table order: Letter and Japanese Envelope Kaku #3 are less than 4 mm apart. - Page Setup and Size list Statement, Envelope #10 and Envelope DL in their params docs; a test checks both commands store and print them. - Paper docs are format-neutral. --- crates/engine/src/cmd/print.rs | 2 +- crates/engine/src/cmd/print/tests.rs | 20 +++++++++++++--- crates/engine/src/cmd/view.rs | 2 +- crates/model/src/features/print.rs | 5 ++-- crates/model/src/paper.rs | 35 ++++++++++++++++++++++++---- docs/architecture.md | 2 +- docs/file-format-parity.md | 4 ++-- 7 files changed, 54 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index a76f45c5e8..6e3d888e45 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -78,7 +78,7 @@ pub fn specs() -> Vec { "Page Setup…", ["Page Layout", "Page Setup"], None, - "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings", + "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings", has_doc, page_setup ), diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index ee22e14e20..6457002d1b 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -652,9 +652,23 @@ fn paper_size_commands_store_the_table_name() { assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "B5"); s.execute("pageLayout.pageSetup", json!({"paper": "11x17"})).unwrap(); assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "Tabloid"); - // Statement and the envelopes Excel names now print on their own size. - s.execute("pageLayout.pageSetup", json!({"paper": "Envelope DL"})).unwrap(); - assert_eq!(paper_size("Statement"), (396.0, 612.0)); + // Statement and the envelopes XLSX names are accepted by both commands (Page Setup refused + // them before), stored under their table name and printed on their own size. + s.execute("range.setValues", json!({"range": "A1", "values": [["x"]]})).unwrap(); + let close = |v: &Json, want: f64| (v.as_f64().unwrap() - want).abs() < 0.01; + for (cmd, given, stored, w, h) in [ + ("pageLayout.pageSetup", "statement", "Statement", 396.0, 612.0), + ("pageLayout.pageSetup", "envelope #10", "Envelope #10", 297.0, 684.0), + ("pageLayout.pageSetup", "Envelope-DL", "Envelope DL", 311.81, 623.62), + ("pageLayout.size", "Statement", "Statement", 396.0, 612.0), + ("pageLayout.size", "envelope dl", "Envelope DL", 311.81, 623.62), + ] { + s.execute(cmd, json!({"paper": given})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, stored, "{cmd} {given}"); + let pv = s.execute("file.printPreview", json!({})).unwrap(); + let page = &pv["pageList"][0]; + assert!(close(&page["width"], w) && close(&page["height"], h), "{cmd} {given}: {page}"); + } // A new workbook still prints on Letter. assert_eq!(gridcraft_model::Workbook::new().sheets[0].print.paper, "Letter"); } diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index d6d56b0509..b01c8b71a8 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Size", ["Page Layout", "Page Setup"], None, - "{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes)}", + "{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}", has_doc, paper ), diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 049ac454d0..833588c734 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -12,9 +12,8 @@ pub enum Orientation { pub struct PrintSettings { pub orientation: Orientation, /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]), or empty when the file - /// stated none: the printer's or locale's paper then, which an ODF file leaves to the - /// application. Print layout falls back to Letter and XLSX writes no `paperSize`. New sheets - /// default to Letter. + /// stated none: the printer's or locale's paper then. Print layout falls back to Letter and + /// XLSX writes no `paperSize`. New sheets default to Letter. pub paper: String, /// Margins in inches: left, right, top, bottom, header, footer. pub margins: [f32; 6], diff --git a/crates/model/src/paper.rs b/crates/model/src/paper.rs index b3068e6aab..546c1d2577 100644 --- a/crates/model/src/paper.rs +++ b/crates/model/src/paper.rs @@ -1,5 +1,5 @@ //! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats -//! (XLSX paper ids, ODF page sizes) and print layout all read this one table. +//! (paper ids or page sizes) and print layout all read this one table. /// Paper names and sizes in points, width then height, as the paper is named: Ledger is /// Tabloid turned on its side. Each size has one name, so a size reads back as the name it was @@ -74,11 +74,22 @@ pub fn size_pt(name: &str) -> Option<(f32, f32)> { PAPERS.iter().find(|(p, _, _)| *p == n).map(|(_, w, h)| (*w, *h)) } -/// The paper of a page `width` × `height` points, within 2 mm: as it stands, else turned. +/// The paper of a page `width` × `height` points, within 2 mm on each side: the nearest one as it +/// stands, else the nearest one turned. Some papers are less than 4 mm apart (Letter and Japanese +/// Envelope Kaku #3), so the nearest wins, not the first in the table. pub fn for_size(width: f32, height: f32) -> Option<&'static str> { - let near = |a: f32, b: f32| (a - b).abs() < 5.67; - let find = |w: f32, h: f32| PAPERS.iter().find(|(_, pw, ph)| near(*pw, w) && near(*ph, h)).map(|(n, _, _)| *n); - find(width, height).or_else(|| find(height, width)) + const TOLERANCE: f32 = 5.67; // 2 mm + let nearest = |w: f32, h: f32| { + PAPERS + .iter() + .filter_map(|(n, pw, ph)| { + let (dw, dh) = ((pw - w).abs(), (ph - h).abs()); + (dw < TOLERANCE && dh < TOLERANCE).then_some((dw + dh, *n)) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, n)| n) + }; + nearest(width, height).or_else(|| nearest(height, width)) } #[cfg(test)] @@ -105,4 +116,18 @@ mod tests { } assert_eq!(canonical("Envelope B5"), Some("B5 (ISO)")); } + + /// Letter (612×792) and Japanese Envelope Kaku #3 (612.28×785.2) are within 2 mm of some + /// of the same sizes: the nearer paper wins, whichever comes first in the table. + #[test] + fn for_size_picks_the_nearest_paper() { + assert_eq!(for_size(612.2, 788.0), Some("Japanese Envelope Kaku #3")); + assert_eq!(for_size(612.0, 790.0), Some("Letter")); + assert_eq!(for_size(788.0, 612.2), Some("Japanese Envelope Kaku #3")); + // A wide page that is a paper as it stands is not read as another paper turned. + assert_eq!(for_size(1224.0, 792.0), Some("Ledger")); + assert_eq!(for_size(1000.0, 10.0), None); + assert_eq!(for_size(f32::NAN, 792.0), None); + assert_eq!(for_size(f32::INFINITY, f32::INFINITY), None); + } } diff --git a/docs/architecture.md b/docs/architecture.md index df3e2ac134..236b72238d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -236,7 +236,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| -| 2026-11-11 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means the file stated none | +| 2026-11-11 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means the file stated none; `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size | | 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` | | 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused | | 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 981ddd3fa5..c3d87732fc 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-11 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)`, and an empty paper name, a file that stated none, writes no `paperSize`; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-11 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)`, and an empty paper name, a file that stated none, writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -158,7 +158,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| -| 2026-11-11 | minor | One paper table (`model::paper`) behind XLSX `paperSize` and print layout; id 34 reads as `B5 (ISO)`, the ISO B5 size; `B5 (ISO)` and every alias save with their id; an empty paper writes no `paperSize` | +| 2026-11-11 | minor | One paper table (`model::paper`) behind XLSX `paperSize` and print layout; id 34 reads as `B5 (ISO)`, the ISO B5 size; `B5 (ISO)` and every alias save with their id; an empty paper writes no `paperSize`; Page Setup and Size now take Statement, Envelope #10 and Envelope DL (Page Setup refused them before) and print them on their own size | | 2026-11-03 | minor | SYLK (`.slk`) import: values, R1C1 formulas as A1 (shared formulas too) with cached results, number formats and column widths; import only (#1481) | | 2026-11-03 | minor | Opening a web page (HTML) reads its first table as a sheet, whatever the file is called: a web app's "Export to Excel" saved as `.xls` no longer opens as lines of markup. Values read as in a CSV (or as text with `csvAsText`), `` cells are bold and centred, `` names the sheet, and a page not named `.htm`/`.html` opens with a warning (#3166) | | 2026-11-03 | minor | XLSX `` (Remove personal information from file properties on save) is read and written back, and while it is on GridCraft saves no author (`dc:creator`) and no company, as Excel leaves them empty (#3089, file part) | From 8cb34cd3120c2e98e47f7ebdea9fe0acfe0507c1 Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 08:52:38 +0100 Subject: [PATCH 91/95] model::paper: say what an empty paper means today; every table paper keeps an XLSX id Review round 1. - PrintSettings::paper and the docs said an empty paper is "a file that stated none", but no reader produces it yet. They now say empty means no paper is stated, which a reader may set. - for_size documents that it names the page as it stands (17x11 in is Ledger), so a caller that also records landscape passes the size upright. - xlsx: a test that every paper in model::paper::PAPERS saves with an id and reads back as itself, so the two tables cannot drift. B6 (ISO) is the one exception (ECMA-376 has no upright ISO B6 id). --- crates/engine/src/cmd/print/tests.rs | 2 +- crates/model/src/features/print.rs | 7 ++++--- crates/model/src/paper.rs | 4 ++++ crates/xlsx/src/tables.rs | 14 ++++++++++++++ crates/xlsx/src/tests/roundtrip.rs | 2 +- docs/architecture.md | 2 +- docs/file-format-parity.md | 2 +- 7 files changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index c056a23f9e..2e198bd25f 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -631,7 +631,7 @@ fn page_setup_paper_sizes_reach_the_pdf_page() { assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err()); } -/// An empty paper name means the file stated none; it prints on Letter. +/// An empty paper name means no paper is stated; it prints on Letter. #[test] fn an_unstated_paper_prints_on_letter() { let mut wb = gridcraft_model::Workbook::new(); diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 833588c734..241b4b40e4 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -11,9 +11,10 @@ pub enum Orientation { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrintSettings { pub orientation: Orientation, - /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]), or empty when the file - /// stated none: the printer's or locale's paper then. Print layout falls back to Letter and - /// XLSX writes no `paperSize`. New sheets default to Letter. + /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]). Empty means no paper is + /// stated, so the printer's or locale's paper applies: a reader may leave it so for a file + /// that states none (none does yet). Print layout falls back to Letter and XLSX writes no + /// `paperSize`. New sheets default to Letter. pub paper: String, /// Margins in inches: left, right, top, bottom, header, footer. pub margins: [f32; 6], diff --git a/crates/model/src/paper.rs b/crates/model/src/paper.rs index 546c1d2577..2db5c28e84 100644 --- a/crates/model/src/paper.rs +++ b/crates/model/src/paper.rs @@ -77,6 +77,10 @@ pub fn size_pt(name: &str) -> Option<(f32, f32)> { /// The paper of a page `width` × `height` points, within 2 mm on each side: the nearest one as it /// stands, else the nearest one turned. Some papers are less than 4 mm apart (Letter and Japanese /// Envelope Kaku #3), so the nearest wins, not the first in the table. +/// +/// The name is the paper as the page stands: a 17×11 in page is `Ledger`. A caller that also +/// records a landscape orientation should pass the size upright (narrow side first), since +/// print layout turns the named paper once more for landscape. pub fn for_size(width: f32, height: f32) -> Option<&'static str> { const TOLERANCE: f32 = 5.67; // 2 mm let nearest = |w: f32, h: f32| { diff --git a/crates/xlsx/src/tables.rs b/crates/xlsx/src/tables.rs index 363ab9cedf..5427f31e01 100644 --- a/crates/xlsx/src/tables.rs +++ b/crates/xlsx/src/tables.rs @@ -323,6 +323,20 @@ pub const EMU_PER_PX: f64 = 9525.0; mod tests { use super::*; + /// Every paper in the shared table saves with an XLSX id, so it reopens as itself. ECMA-376 + /// has no upright ISO B6 id (35 is the B6 envelope stated wide), so `B6 (ISO)` alone has none. + #[test] + fn every_shared_paper_has_an_xlsx_id() { + for (name, _, _) in gridcraft_model::paper::PAPERS { + let id = paper_id(name); + if name == "B6 (ISO)" { + assert_eq!(id, None); + } else { + assert_eq!(id.and_then(paper_name), Some(name), "{name}"); + } + } + } + #[test] fn widths() { assert_eq!(col_width_to_px(9.140625), 64.0); diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 928ba0a597..668d154479 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1681,7 +1681,7 @@ fn japanese_paper_sizes_round_trip() { /// The paper names every spelling folds onto keep their file id: `11x17` is Tabloid (3), and /// ISO B5 is id 34 (ECMA-376's 176×250 mm "B5 envelope"), read back as `B5 (ISO)`. An empty -/// paper (the file stated none) writes no `paperSize`, so the reader's own paper applies. +/// paper (none stated) writes no `paperSize`, so the reader's own paper applies. #[test] fn paper_names_keep_their_xlsx_id_and_an_unstated_paper_writes_none() { for (paper, id, back_as) in [("11x17", 3, "Tabloid"), ("US Legal", 5, "Legal"), ("B5 (ISO)", 34, "B5 (ISO)"), ("Envelope B5", 34, "B5 (ISO)")] { diff --git a/docs/architecture.md b/docs/architecture.md index 341333718c..bbc7a05cae 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -242,7 +242,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| -| 2026-11-13 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means the file stated none; `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size | +| 2026-11-13 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means no paper is stated (no reader sets it yet); `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size | | 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` | | 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused | | 2026-11-01 | trivial | Equations: the layout cache answers for a source over the cap by its length alone, without hashing it | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 34b114bff7..15e10fb98b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-13 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)`, and an empty paper name, a file that stated none, writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-13 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)`, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** From 2f4b7025300ed8c50765c8aa04f359802edfb75b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:23:48 -0800 Subject: [PATCH 92/95] Charts: stacked and 100% stacked line groups on one axis open as a combo chart The chart reader reports both groupings as stacked lines, so a chart holding both read every series as a 100% stacked line. Each series now takes its own group's kind, and the chart opens as a combo chart when those kinds differ. --- crates/xlsx/src/chart.rs | 44 ++++++++++--------- .../src/tests/chart_line_percent_stacked.rs | 19 ++++++++ 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index 1fdf8f7e4a..6bce0c3a01 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -225,11 +225,24 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { let multi_axis = ser_els.iter().any(|(_, _, sec)| *sec); let base_kind = map_chart_type(dc.kind, &groups); let no_marker = |s: &El| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); - // A 100% stacked line chart whose series differ in markers opens as a combo chart, so each series keeps its own. - let mixed = base_kind == ChartKind::LineStacked100Markers - && ser_els.iter().any(|(s, _, _)| no_marker(s)) - && !ser_els.iter().all(|(s, _, _)| no_marker(s)); - let is_combo = dc.kind == ChartType::Combo || multi_axis || mixed; + // Series `i` takes its own plot group's kind; a 100% stacked line series without markers in a group with them keeps its own. + let own_kind = |i: usize, k: ChartType| { + let (sel, scope): (Option<&El>, &[&El]) = match ser_els.get(i) { + Some((el, g, _)) => (Some(*el), std::slice::from_ref(g)), + None => (None, &groups), + }; + match map_chart_type(k, scope) { + ChartKind::LineStacked100Markers if sel.is_some_and(no_marker) => ChartKind::LineStacked100, + own => own, + } + }; + // A 100% stacked line chart whose series differ in markers, or that also holds a plain stacked line group, opens as a + // combo chart, so each series keeps its own kind. + let own_kinds: Vec = dc.series.iter().enumerate().map(|(i, s)| own_kind(i, s.kind.unwrap_or(dc.kind))).collect(); + let split = dc.kind != ChartType::Combo + && own_kinds.iter().any(|k| matches!(k, ChartKind::LineStacked100 | ChartKind::LineStacked100Markers)) + && own_kinds.windows(2).any(|w| w[0] != w[1]); + let is_combo = dc.kind == ChartType::Combo || multi_axis || split; let kind = if is_combo { ChartKind::Combo } else { base_kind }; let series_labels = dc.series.iter().any(|s| s.data_labels == Some(true)); let mut keyed: Vec<(Option, Series)> = dc @@ -237,18 +250,9 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { .into_iter() .enumerate() .map(|(i, s)| { - let (sel, group, fallback_sec) = match ser_els.get(i).copied() { - Some((el, g, sec)) => (Some(el), Some(g), sec), - None => (None, None, false), - }; - // A series takes its own plot group's kind; a 100% stacked line series without markers in a group with them keeps its own. - let scope: &[&El] = match &group { - Some(g) => std::slice::from_ref(g), - None => &groups, - }; - let own_kind = |k: ChartType| match map_chart_type(k, scope) { - ChartKind::LineStacked100Markers if sel.is_some_and(no_marker) => ChartKind::LineStacked100, - own => own, + let (sel, fallback_sec) = match ser_els.get(i).copied() { + Some((el, _, sec)) => (Some(el), sec), + None => (None, false), }; let color = s .fill @@ -288,9 +292,9 @@ pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { color, secondary: is_combo && (s.secondary_axis || fallback_sec), kind: if dc.kind == ChartType::Combo { - s.kind.map(own_kind) - } else if multi_axis || mixed { - Some(own_kind(s.kind.unwrap_or(dc.kind))) + s.kind.map(|k| own_kind(i, k)) + } else if multi_axis || split { + own_kinds.get(i).copied() } else { None }, diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs index e9dcaed9d9..384d3a373c 100644 --- a/crates/xlsx/src/tests/chart_line_percent_stacked.rs +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -151,6 +151,25 @@ fn a_hundred_percent_stacked_line_group_with_mixed_markers_keeps_each_series_mar assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); } +#[test] +fn stacked_and_hundred_percent_stacked_line_groups_on_one_axis_keep_their_kinds() { + let ser = |i: usize| { + format!("{NO_MARKER}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + ", + ser(0), + ser(1) + ); + let want = [Some(ChartKind::LineStacked), Some(ChartKind::LineStacked100)]; + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.kind, ChartKind::Combo); + assert_eq!(ch.series.iter().map(|s| s.kind).collect::>(), want); +} + #[test] fn combo_areas_marked_lines_and_mixed_column_groupings_keep_their_kinds_when_saved() { let ser = |i: usize, marker: &str| { From a1b96711b6ba6328d037bc71b2d5b2739725ce50 Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 23 Nov 2026 10:36:04 +0100 Subject: [PATCH 93/95] PR4139: verify imported ISO B5 print dimensions --- crates/engine/src/cmd/print/tests.rs | 35 ++++++++++++++++++++++++++++ docs/file-format-parity.md | 3 ++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 6ef29e6c05..af06027c62 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -1264,3 +1264,38 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() { assert!(pics.chart((0, 1), || vec![line(1000)]).is_none()); assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1))); } + +/// XLSX id 34 is ISO B5 (176 × 250 mm), not the Letter fallback of the old name. +#[test] +fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() { + use std::io::{Cursor, Read, Write}; + let mut wb = gridcraft_model::Workbook::new(); + wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into())); + wb.sheet_mut(0).unwrap().print.paper = "Legal".into(); + let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap(); + let mut input = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let mut output = zip::ZipWriter::new(Cursor::new(Vec::new())); + for i in 0..input.len() { + let mut part = input.by_index(i).unwrap(); + let mut data = Vec::new(); + part.read_to_end(&mut data).unwrap(); + if part.name() == "xl/worksheets/sheet1.xml" { + let xml = String::from_utf8(data).unwrap(); + assert!(xml.contains(r#"paperSize="5""#)); + // Set the input id independently of the shared paper-name mapping under test. + data = xml.replace(r#"paperSize="5""#, r#"paperSize="34""#).into_bytes(); + } + output.start_file(part.name(), zip::write::SimpleFileOptions::default()).unwrap(); + output.write_all(&data).unwrap(); + } + let bytes = output.finish().unwrap().into_inner(); + let mut s = Session::new(); + s.execute("file.open", json!({"name": "iso-b5.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap(); + let preview = s.execute("file.printPreview", json!({})).unwrap(); + let page = &preview["pageList"][0]; + assert!((page["width"].as_f64().unwrap() - 498.90).abs() < 0.01, "{page}"); + assert!((page["height"].as_f64().unwrap() - 708.66).abs() < 0.01, "{page}"); + let (pdf, pages) = pdf_of(&mut s, json!({})); + assert_eq!(pages, 1); + assert!(contains(&pdf, "/MediaBox [0 0 498.9 708.66]")); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 719b55abca..df5ad00e0f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-13 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)`, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-23 · **Change:** minor (one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)` and prints at 176×250 mm instead of the old Letter fallback, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -163,6 +163,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-23 | minor | Clarify that imported XLSX paper id 34 changes printed output from the old Letter fallback to ISO B5 (176×250 mm); add import-to-preview/PDF regression coverage | | 2026-11-13 | minor | One paper table (`model::paper`) behind XLSX `paperSize` and print layout; id 34 reads as `B5 (ISO)`, the ISO B5 size; `B5 (ISO)` and every alias save with their id; an empty paper writes no `paperSize`; Page Setup and Size now take Statement, Envelope #10 and Envelope DL (Page Setup refused them before) and print them on their own size | | 2026-11-13 | minor | PDF of a right-to-left sheet keeps explicit Left and Right alignment on the side the grid shows them | | 2026-11-12 | minor | `.xls` files open with their data validation (drop-down lists, input messages, error alerts and the rules), read by craft-xls and mapped as the `.xlsx` reader maps the same rules. A rule Excel would refuse, or one past 65,536 in a workbook, is skipped with a warning (#3634, from #3636) | From 0f36a7aee31703dc70f32ea129055cc3ee13dfdb Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:34:27 +0700 Subject: [PATCH 94/95] print tests: read the zip entry name through main's fallible ZipFile::name() --- crates/engine/src/cmd/print/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 71f0a29fc9..918a94c2c5 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -1307,13 +1307,14 @@ fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() { let mut part = input.by_index(i).unwrap(); let mut data = Vec::new(); part.read_to_end(&mut data).unwrap(); - if part.name() == "xl/worksheets/sheet1.xml" { + let name = part.name().unwrap().to_string(); + if name == "xl/worksheets/sheet1.xml" { let xml = String::from_utf8(data).unwrap(); assert!(xml.contains(r#"paperSize="5""#)); // Set the input id independently of the shared paper-name mapping under test. data = xml.replace(r#"paperSize="5""#, r#"paperSize="34""#).into_bytes(); } - output.start_file(part.name(), zip::write::SimpleFileOptions::default()).unwrap(); + output.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); output.write_all(&data).unwrap(); } let bytes = output.finish().unwrap().into_inner(); From 916371a2b1063ddf1611afea5066351fcde7a4c0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:30:21 +0100 Subject: [PATCH 95/95] Drop newton and solve_rate: unused now that XIRR and IRR have their own solvers --- crates/functions/src/financial/tvm.rs | 66 --------------------------- 1 file changed, 66 deletions(-) diff --git a/crates/functions/src/financial/tvm.rs b/crates/functions/src/financial/tvm.rs index cd4626ef8a..16e1bd71db 100644 --- a/crates/functions/src/financial/tvm.rs +++ b/crates/functions/src/financial/tvm.rs @@ -152,72 +152,6 @@ pub(super) fn cumprinc(a: &[Arg], _c: &mut dyn Ctx) -> R { cumulative(a, true) } -/// Newton iteration with a numeric derivative, keeping the rate above -1. -fn newton(f: impl Fn(f64) -> f64, guess: f64) -> Option { - let mut x = guess; - for _ in 0..200 { - let y = f(x); - if !y.is_finite() { - return None; - } - let h = 1e-6 * x.abs().max(1e-3); - let d = (f(x + h) - f(x - h)) / (2.0 * h); - if d == 0.0 || !d.is_finite() { - return None; - } - let mut nx = x - y / d; - if nx <= -1.0 { - nx = (x - 1.0) / 2.0; - if nx <= -1.0 { - nx = -0.999_999_999; - } - } - if (nx - x).abs() < 1e-12 * nx.abs().max(1.0) { - return Some(nx); - } - x = nx; - } - None -} - -/// Tries Newton from the guess and a few fallback starting points; then bisection over a -/// bracket if one can be found. -fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R { - let check = |r: f64| f(r).is_finite() && f(r).abs() < 1e-7 * (1.0 + f(guess).abs().min(1e12)); - for g in [guess, 0.1, 0.01, 0.5, -0.5, 1.0, 0.001, 5.0, -0.9, 10.0] { - if let Some(r) = newton(&f, g) - && r > -1.0 - && check(r) - { - return Ok(r); - } - } - // Scan for a sign change and bisect. - let grid: Vec = [-0.999_999, -0.99, -0.9, -0.5, -0.2, 0.0, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0, 1000.0].to_vec(); - for w in grid.windows(2) { - let (mut lo, mut hi) = match w { - [a, b] => (*a, *b), - _ => continue, - }; - let (flo, fhi) = (f(lo), f(hi)); - if !(flo.is_finite() && fhi.is_finite()) || flo * fhi > 0.0 { - continue; - } - let lo_neg = flo < 0.0; - for _ in 0..200 { - let mid = 0.5 * (lo + hi); - let fm = f(mid); - if (fm < 0.0) == lo_neg { - lo = mid; - } else { - hi = mid; - } - } - return Ok(0.5 * (lo + hi)); - } - Err(CellError::Num) -} - /// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus /// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to /// judge how close to zero the first can get in floating point.