From 8732325b589a91465cfe703adbe6243c37fb47a5 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Wed, 14 Oct 2026 15:42:49 -0500 Subject: [PATCH 01/71] 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 43ccb39ba3f1ee35126866daa906f5f486d98371 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 04:17:26 -0500 Subject: [PATCH 02/71] Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection F8 toggles Extend Selection: arrows, Page Up/Down, Ctrl+arrows, Home and Ctrl+Home/End extend from the anchor as if Shift were held, and a click extends like Shift+click. Shift+F8 toggles Add or Remove Selection: arrows move the active cell and keep the selected areas, Shift+arrows grow a new area from there, and a click adds an area or removes a selected one, like Ctrl+click. The status bar names the mode (translated in every catalog). The key again, Esc or editing a cell ends it. UI-only command ui.selectionMode sets or reports the mode for agents. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/ui-egui/src/control.rs | 5 + crates/ui-egui/src/grid.rs | 130 ++++++++++++++++-- crates/ui-egui/src/i18n.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 2 + crates/ui-egui/src/i18n/sr.rs | 2 + crates/ui-egui/src/i18n/zh.rs | 2 + crates/ui-egui/src/lib.rs | 14 ++ crates/ui-egui/src/tabs.rs | 5 + crates/ui-egui/tests/keyboard_shortcuts.rs | 149 ++++++++++++++++++++- docs/ui-parity.md | 8 +- 17 files changed, 321 insertions(+), 14 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..097e4c9f67 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:** minor (F8 / Shift+F8 selection modes) · **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 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends 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-15 | minor | Progress log: F8 and Shift+F8 selection modes | | 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/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2ea5cfae01..6035323cf3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -184,6 +184,11 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) - ("options.autoComplete", "Enable AutoComplete for cell values", "{on?: bool} (toggles without it) → {on}"), ("view.interfaceScale", "Interface Size", "{percent: 75–200 | \"auto\"} (100 = auto; clamped)"), ("ui.dialog", "Open Dialog", ""), + ( + "ui.selectionMode", + "Extend or Add to Selection", + "{mode?: \"extend\" (F8) | \"add\" (Shift+F8) | \"off\"} → {mode}; {} reports the mode", + ), ("ui.backstage", "File (Backstage view)", "{page?: home|new|open|info|saveAs|print|export|options|close}"), ( "ui.printSettings", diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 97b787ef33..b5a536a6fc 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -149,6 +149,65 @@ pub struct GridState { pub hscroll: Option, /// Ctrl+wheel zoom in progress (see [`WheelZoom`]). pub wheel_zoom: Option, + /// F8 Extend Selection or Shift+F8 Add or Remove Selection mode (see [`SelectionMode`]). + pub selection_mode: SelectionMode, + /// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next + /// arrow moves it again instead of keeping it. + pub add_pending: bool, +} + +/// Excel's keyboard selection modes, shown in the status bar. In Extend mode (F8) arrow keys and +/// clicks extend from the anchor as if Shift were held. In Add mode (Shift+F8) arrow keys move the +/// active cell without dropping the selected areas, Shift+arrows grow a new area from there, and a +/// click adds an area (or removes one already selected) as Ctrl+click does. Esc, the same key +/// again, or editing a cell turns the mode off. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SelectionMode { + #[default] + Off, + Extend, + Add, +} + +impl SelectionMode { + /// The id the `ui.selectionMode` command takes and returns. + pub fn id(self) -> &'static str { + match self { + Self::Off => "off", + Self::Extend => "extend", + Self::Add => "add", + } + } + + pub fn parse(id: &str) -> Option { + match id.trim().to_ascii_lowercase().as_str() { + "off" | "none" => Some(Self::Off), + "extend" => Some(Self::Extend), + "add" => Some(Self::Add), + _ => None, + } + } + + /// The status bar text (an i18n catalog key), when the mode shows one. + pub fn status_text(self) -> Option<&'static str> { + match self { + Self::Off => None, + Self::Extend => Some("Extend Selection"), + Self::Add => Some("Add or Remove Selection"), + } + } +} + +impl GridState { + /// Turns `mode` on, or off when it is already on (F8 / Shift+F8); the other mode ends. + pub fn toggle_selection_mode(&mut self, mode: SelectionMode) { + self.set_selection_mode(if self.selection_mode == mode { SelectionMode::Off } else { mode }); + } + + pub fn set_selection_mode(&mut self, mode: SelectionMode) { + self.selection_mode = mode; + self.add_pending = false; + } } /// Ctrl+wheel zoom for one (doc uid, sheet). egui eases a notch in over several frames and @@ -1784,6 +1843,14 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & let primary_clicked = resp.clicked_by(egui::PointerButton::Primary); let pointer = ctx.input(|i| i.pointer.clone()); let mods = ctx.input(|i| i.modifiers); + // Selecting with the pointer: Extend mode (F8) clicks as if Shift were held, Add mode + // (Shift+F8) as if Ctrl were. + let mut sel_mods = mods; + match app.grid.selection_mode { + SelectionMode::Extend => sel_mods.shift = true, + SelectionMode::Add => sel_mods.command = true, + SelectionMode::Off => {} + } // Hit-testing works in logical coordinates (see `Geo::rtl`). let pos = pointer.interact_pos().or(pointer.hover_pos()).map(|p| geo.mirror_pos(p)); let in_cells = pos.is_some_and(|p| geo.in_cells(p)); @@ -2020,7 +2087,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } if resp.drag_started() - && !mods.any() + && !sel_mods.any() && sel.ranges.len() == 1 && sel.current().is_full_cols() && sel.current().contains(CellRef::new(0, c)) @@ -2028,9 +2095,9 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & app.grid.drag = Drag::MoveCols { source: sel.current(), before: None }; return; } - let range = if mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) }; - select_ranges(app, range, mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c)); - app.grid.drag = Drag::Cols(if mods.shift { sel.anchor.col } else { c }); + let range = if sel_mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) }; + select_ranges(app, range, sel_mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c)); + app.grid.drag = Drag::Cols(if sel_mods.shift { sel.anchor.col } else { c }); return; } if in_row_header { @@ -2042,9 +2109,9 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & if point_header(app, wb, sh, RangeRef::rows(r, r)) { return; } - let range = if mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) }; - select_ranges(app, range, mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0))); - app.grid.drag = Drag::Rows(if mods.shift { sel.anchor.row } else { r }); + let range = if sel_mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) }; + select_ranges(app, range, sel_mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0))); + app.grid.drag = Drag::Rows(if sel_mods.shift { sel.anchor.row } else { r }); return; } if !in_cells { @@ -2108,12 +2175,12 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } app.grid.last_click = Some((c, now)); - if mods.shift { + if sel_mods.shift { let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { d.selection.anchor = sel.anchor; } - } else if mods.command { + } else if sel_mods.command { select_ranges(app, RangeRef::cell(c), true, c); } else { let _ = app.session.run("selection.set", json!({"cell": c.a1()})); @@ -2553,7 +2620,37 @@ fn toggled_ranges(mut ranges: Vec, clicked: String, add: bool) -> Vec>().join(","); + let _ = app.session.run("selection.set", json!({"range": range, "active": active.a1()})); + app.grid.add_pending = !kept; +} + fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { + // A clicked area is kept: the next Add mode arrow starts a new one. + app.grid.add_pending = false; let current: Vec = if add { app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() } else { vec![] }; let clicked = r.a1(); @@ -2609,12 +2706,22 @@ fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: } egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => { use egui::Key; + let navigation = matches!( + key, + Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight | Key::PageUp | Key::PageDown | Key::Home | Key::End + ); + // Extend mode (F8): navigation keys extend from the anchor as if Shift were held. + let m = if navigation && app.grid.selection_mode == SelectionMode::Extend { egui::Modifiers { shift: true, ..m } } else { m }; if crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) { continue; } let cmd = m.command; let shift = m.shift; let mv = |app: &mut SheetApp, dr: i64, dc: i64| { + if app.grid.selection_mode == SelectionMode::Add { + add_mode_move(app, dr, dc, shift, cmd); + return; + } let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": shift, "jump": cmd})); app.grid.ensure_visible = true; app.grid.reveal_moving_end = shift; @@ -2673,8 +2780,13 @@ fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: Key::Escape => { app.session.clipboard = None; app.session.format_painter = None; + app.grid.set_selection_mode(SelectionMode::Off); } Key::Space if !cmd && !shift && is_checkbox(sh, app) => app.run_or_alert("cell.toggleCheckbox", json!({})), + // F8 Extend Selection, Shift+F8 Add or Remove Selection: each toggles its mode. + Key::F8 if !m.alt && !cmd => { + app.grid.toggle_selection_mode(if shift { SelectionMode::Add } else { SelectionMode::Extend }); + } Key::F8 if m.alt => { app.open_dialog("macros", json!({})); } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 061698df9b..72c0042dfc 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -457,6 +457,8 @@ const JAPANESE: &[(&str, &str)] = &[ ("Point", "ポイント"), ("Calculate", "計算"), ("Select destination and press Enter or choose Paste", "貼り付け先を選び、Enter キーを押すか [貼り付け] を選びます"), + ("Extend Selection", "選択範囲の拡張"), + ("Add or Remove Selection", "選択範囲の追加または削除"), ("General", "標準"), ("Number", "数値"), ("Currency", "通貨"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 7ed8372c7d..581038d078 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -385,6 +385,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Výběr odkazu", "Calculate" => "Přepočítat", "Select destination and press Enter or choose Paste" => "Vyberte cíl a stiskněte Enter nebo zvolte Vložit", + "Extend Selection" => "Rozšířit výběr", + "Add or Remove Selection" => "Přidat nebo odebrat výběr", "General" => "Obecný", "Number" => "Číslo", "Currency" => "Měna", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index c20c7d1b36..77a9314189 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -383,6 +383,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Zeigen", "Calculate" => "Berechnen", "Select destination and press Enter or choose Paste" => "Ziel auswählen und die Eingabetaste drücken oder „Einfügen“ wählen", + "Extend Selection" => "Markierung erweitern", + "Add or Remove Selection" => "Markierung hinzufügen oder entfernen", "General" => "Standard", "Number" => "Zahl", "Currency" => "Währung", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4ce231bcad..07ffcfc1c2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -382,6 +382,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Señalar", "Calculate" => "Calcular", "Select destination and press Enter or choose Paste" => "Seleccione el destino y presione Entrar o elija Pegar", + "Extend Selection" => "Extender selección", + "Add or Remove Selection" => "Agregar o quitar selección", "General" => "General", "Number" => "Número", "Currency" => "Moneda", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5d20ab0ca2..616db6fc28 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -284,6 +284,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Point", "Calculate" => "Calculer", "Select destination and press Enter or choose Paste" => "Sélectionnez la destination et appuyez sur Entrée ou choisissez Coller", + "Extend Selection" => "Étendre la sélection", + "Add or Remove Selection" => "Ajouter ou supprimer la sélection", "General" => "Standard", "Number" => "Nombre", "Currency" => "Monétaire", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 1902ad3015..17b1d0ba06 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -273,6 +273,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "가리키기", "Calculate" => "계산", "Select destination and press Enter or choose Paste" => "대상을 선택하고 Enter 키를 누르거나 [붙여넣기]를 선택하세요", + "Extend Selection" => "선택 영역 확장", + "Add or Remove Selection" => "선택 영역 추가 또는 제거", "General" => "일반", "Number" => "숫자", "Currency" => "통화", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index fb9236cdb6..9adf19256d 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -274,6 +274,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Apontar", "Calculate" => "Calcular", "Select destination and press Enter or choose Paste" => "Selecione o destino e pressione Enter ou escolha Colar", + "Extend Selection" => "Estender Seleção", + "Add or Remove Selection" => "Adicionar ou Remover Seleção", "General" => "Geral", "Number" => "Número", "Currency" => "Moeda", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 765f6bb326..1669676b7d 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -273,6 +273,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Указание", "Calculate" => "Вычисление", "Select destination and press Enter or choose Paste" => "Выберите место вставки и нажмите Enter или выберите «Вставить»", + "Extend Selection" => "Расширить выделение", + "Add or Remove Selection" => "Добавить или удалить выделение", "General" => "Общий", "Number" => "Числовой", "Currency" => "Денежный", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index cbf18d4c46..80e1acd214 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -276,6 +276,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Pokaži", "Calculate" => "Izračunavanje", "Select destination and press Enter or choose Paste" => "Izaberi odredište i pritisni Enter ili izaberi Nalepi", + "Extend Selection" => "Proširi izbor", + "Add or Remove Selection" => "Dodaj ili ukloni izbor", "General" => "Opšte", "Number" => "Broj", "Currency" => "Valuta", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 00175925e6..516ea4ee72 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -273,6 +273,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "指向", "Calculate" => "计算", "Select destination and press Enter or choose Paste" => "选择目标位置并按 Enter,或选择“粘贴”", + "Extend Selection" => "扩展式选定", + "Add or Remove Selection" => "添加或删除所选内容", "General" => "常规", "Number" => "数值", "Currency" => "货币", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f96cdac3c0..ce2cea4820 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -663,6 +663,18 @@ impl SheetApp { self.open_dialog(name, p.clone()); Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())})) } + "ui.selectionMode" => { + // `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode. + match p.get("mode").and_then(Json::as_str) { + Some(id) => match grid::SelectionMode::parse(id) { + Some(mode) => self.grid.set_selection_mode(mode), + None => return Some(Err(format!("unknown selection mode {id:?} (use \"extend\", \"add\" or \"off\")"))), + }, + None if p.get("mode").is_some_and(|v| !v.is_null()) => return Some(Err("`mode` must be \"extend\", \"add\" or \"off\"".into())), + None => {} + } + Ok(json!({"mode": self.grid.selection_mode.id()})) + } "ui.message.dismiss" => { self.message = None; Ok(Json::Null) @@ -867,6 +879,8 @@ impl SheetApp { self.message = Some(("Text Box".into(), clean_error(&e))); return; } + // Editing a cell ends Extend and Add mode, as in Excel. + self.grid.set_selection_mode(grid::SelectionMode::Off); let Some(d) = self.session.active() else { return }; let Some(sh) = d.wb.active() else { return }; let at = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active); diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index b77524bb96..89b021c176 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -237,6 +237,11 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { gridcraft_engine::Mode::Point => "Point", }; ui.label(egui::RichText::new(app.ui.language.tr(mode)).font(theme::ui_font(12.5)).color(t.text_dim)); + // F8 / Shift+F8 selection mode. + if let Some(text) = app.grid.selection_mode.status_text() { + ui.add_space(12.0); + ui.label(egui::RichText::new(app.ui.language.tr(text)).font(theme::ui_font(12.5)).color(t.text_dim)); + } if let Some(d) = app.session.active() { if d.wb.vba_project.is_some() { ui.add_space(12.0); diff --git a/crates/ui-egui/tests/keyboard_shortcuts.rs b/crates/ui-egui/tests/keyboard_shortcuts.rs index c0a1307b3d..3f39850324 100644 --- a/crates/ui-egui/tests/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/keyboard_shortcuts.rs @@ -1,10 +1,12 @@ //! Excel keyboard shortcuts (crate::keymap) dispatched through real egui key events. -use egui::{Event, Key, Modifiers}; +use egui::{Event, Key, Modifiers, PointerButton}; +use egui_kittest::kittest::Queryable as _; use gridcraft_engine::Session; use gridcraft_engine::core::CellRef; use gridcraft_engine::model::BorderStyle; use gridcraft_ui_egui::SheetApp; +use gridcraft_ui_egui::grid::{Geo, SelectionMode}; use gridcraft_ui_egui::keymap::{Shortcut, lookup}; use serde_json::json; @@ -86,6 +88,151 @@ fn copy_formula_from_above_and_function_keys() { assert_eq!(h.state().session.active().unwrap().wb.sheets[0].zoom, 110); } +fn selection_a1(h: &Harness) -> String { + h.state().session.active().unwrap().selection.a1() +} + +fn active_a1(h: &Harness) -> String { + h.state().session.active().unwrap().selection.active.a1() +} + +fn mode(h: &Harness) -> SelectionMode { + h.state().grid.selection_mode +} + +#[test] +fn f8_extend_selection_extends_from_the_anchor_until_turned_off() { + let mut h = harness(book("A1")); + assert!(h.query_by_label("Extend Selection").is_none()); + key(&mut h, Key::F8, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Extend); + assert!(h.query_by_label("Extend Selection").is_some(), "the status bar shows the mode"); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:B2"); + assert_eq!(active_a1(&h), "A1", "the active cell stays on the anchor"); + // Ctrl+arrow extends to the edge of the data, as Ctrl+Shift+arrow does. + key(&mut h, Key::ArrowDown, CTRL); + assert_eq!(selection_a1(&h), "A1:B3"); + // F8 again ends the mode: arrows move again. + key(&mut h, Key::F8, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Off); + assert!(h.query_by_label("Extend Selection").is_none()); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B1"); + // Esc ends it too, and keeps the extended selection. + key(&mut h, Key::F8, Modifiers::NONE); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + key(&mut h, Key::Escape, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Off); + assert_eq!(selection_a1(&h), "B1:C1"); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2"); +} + +#[test] +fn shift_f8_add_to_selection_builds_areas_with_arrow_keys() { + let mut h = harness(book("A1:A2")); + key(&mut h, Key::F8, Modifiers::SHIFT); + assert_eq!(mode(&h), SelectionMode::Add); + assert!(h.query_by_label("Add or Remove Selection").is_some(), "the status bar shows the mode"); + assert!(h.query_by_label("Extend Selection").is_none()); + // Arrows move the active cell and keep A1:A2; the next arrow moves the new cell again. + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:A2,B1"); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:A2,C1"); + assert_eq!(active_a1(&h), "C1"); + // Shift+arrow grows that area from it and keeps it. + key(&mut h, Key::ArrowRight, Modifiers::SHIFT); + assert_eq!(selection_a1(&h), "A1:A2,C1:D1"); + assert_eq!(active_a1(&h), "C1"); + // The next arrow starts a third area. + key(&mut h, Key::ArrowDown, Modifiers::NONE); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "A1:A2,C1:D1,C3"); + // F8 switches to Extend mode, and Shift+F8 twice ends Add mode. + key(&mut h, Key::F8, Modifiers::NONE); + assert_eq!(mode(&h), SelectionMode::Extend); + key(&mut h, Key::F8, Modifiers::SHIFT); + assert_eq!(mode(&h), SelectionMode::Add); + key(&mut h, Key::F8, Modifiers::SHIFT); + assert_eq!(mode(&h), SelectionMode::Off); + assert!(h.query_by_label("Add or Remove Selection").is_none()); + key(&mut h, Key::ArrowRight, Modifiers::NONE); + assert_eq!(selection_a1(&h), "D3", "with the mode off an arrow drops the areas"); +} + +#[test] +fn editing_a_cell_ends_the_selection_mode() { + let mut h = harness(book("A1")); + key(&mut h, Key::F8, Modifiers::NONE); + key(&mut h, Key::F2, Modifiers::NONE); + assert!(h.state().editor.is_some()); + assert_eq!(mode(&h), SelectionMode::Off); + key(&mut h, Key::Escape, Modifiers::NONE); + key(&mut h, Key::F8, Modifiers::SHIFT); + h.input_mut().events.push(Event::Text("7".into())); + h.run_steps(2); + assert!(h.state().editor.is_some(), "typing starts an edit"); + assert_eq!(mode(&h), SelectionMode::Off); +} + +fn click(h: &mut Harness, a1: &str) { + let at = { + let app = h.state(); + let sheet = app.session.active().unwrap().wb.active().unwrap(); + Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll).cell_rect(sheet, CellRef::parse(a1).unwrap()).center() + }; + h.input_mut().events.push(Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(1); +} + +#[test] +fn clicks_extend_or_add_in_the_selection_modes() { + let mut h = harness(book("B2")); + key(&mut h, Key::F8, Modifiers::NONE); + click(&mut h, "D4"); + assert_eq!(selection_a1(&h), "B2:D4", "in Extend mode a click extends from the anchor"); + assert_eq!(mode(&h), SelectionMode::Extend, "the mode stays on"); + key(&mut h, Key::F8, Modifiers::SHIFT); + click(&mut h, "F6"); + assert_eq!(selection_a1(&h), "B2:D4,F6", "in Add mode a click adds an area"); + // (Not a double-click: that would edit the cell.) + h.state_mut().grid.last_click = None; + click(&mut h, "F6"); + assert_eq!(selection_a1(&h), "B2:D4", "and a click on a selected area removes it"); + // An arrow after a click keeps the clicked areas. + click(&mut h, "H8"); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2:D4,H8,H9"); + // Moving back onto the kept H8 and off again keeps it. + key(&mut h, Key::ArrowUp, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2:D4,H8"); + key(&mut h, Key::ArrowDown, Modifiers::NONE); + assert_eq!(selection_a1(&h), "B2:D4,H8,H9"); +} + +#[test] +fn selection_mode_command_sets_and_reports_without_a_dialog() { + let mut h = harness(book("A1")); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({})), Ok(json!({"mode": "off"}))); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "extend"})), Ok(json!({"mode": "extend"}))); + h.run_steps(2); + assert!(h.query_by_label("Extend Selection").is_some()); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "add"})), Ok(json!({"mode": "add"}))); + assert!(h.state_mut().run("ui.selectionMode", json!({"mode": "sideways"})).is_err()); + assert!(h.state_mut().run("ui.selectionMode", json!({"mode": 3})).is_err()); + assert_eq!(mode(&h), SelectionMode::Add, "a bad mode changes nothing"); + assert_eq!(h.state_mut().run("ui.selectionMode", json!({"mode": "off"})), Ok(json!({"mode": "off"}))); + assert!(h.state().dialog.is_none()); +} + #[test] fn windows_and_mac_variants() { let cmd = CTRL; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 22e221e698..cb4ee67988 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-13 · **Change:** minor (horizontal scrollbar in the sheet tab bar, #840) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (F8 Extend Selection and Shift+F8 Add or Remove Selection) · **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 @@ -75,7 +75,7 @@ this logic, with one undo step. | Shortcuts bound to commands | 200+ documented shortcuts per platform | audited below (#110): shortcuts whose feature exists are bound, with the exceptions listed; the rest wait for their features | | Ctrl+arrow, Ctrl+Shift+arrow, Ctrl+Home/End, Ctrl+Shift+Home/End, Page Up/Down, Alt+Page | yes | done | | Ctrl+1, Ctrl+; and Ctrl+Shift+; , Ctrl+D/R, Ctrl+E, Ctrl+T/L, Ctrl+K, Ctrl+Shift+L, Ctrl+Shift+~!@#$%^&_ | yes | done | -| F2, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F11 chart sheet, F8 extend mode, F3 Paste Name, F4 Repeat missing | +| F2, F4, F5, F7, F9 family, Shift+F2/F3/F10/F11, F12 | yes | done; F8 / Shift+F8 extend and add modes with their status bar text; F11 chart sheet, F3 Paste Name, F4 Repeat missing | | Mac-specific (Cmd variants, Control variants, Fn keys) | yes | done where a feature exists (`keymap.rs` picks the Mac variant) | | 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; QAT/Backstage excluded | | Requests | — | #110 (more shortcuts and hot keys), #33 (sequential Alt; initial support landed in #43) | @@ -123,7 +123,8 @@ otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, w | Shift+F3, Ctrl+F3, Ctrl+Shift+F3 | Shift+F3, Cmd+F3 (Define Name), Cmd+Shift+F3 | Insert Function, Name Manager, Create from Selection | **added** | | F5, Shift+F5 (Mac), F7, Shift+F9, Ctrl+Alt+F9, F12, Ctrl+F4 | same | Go To, Find, Spelling, calculate sheet / all, Save As, close | **added** | | Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** | -| F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | +| F8, Shift+F8 | same | Extend Selection (arrows, Page keys, Ctrl+arrows, Home and clicks extend from the anchor) and Add or Remove Selection (arrows move the active cell and keep the areas, Shift+arrows grow a new area, a click adds or removes an area); the status bar names the mode; the key again, Esc or editing a cell ends it (`ui.selectionMode`) | **added** | +| F1, F3, F4 (repeat), F6 / Shift+F6, F11, End mode | same | help, Paste Name, Repeat, pane cycling, chart sheet | missing (no such feature yet) | | Ctrl+6, Ctrl+8, Ctrl+Q, Ctrl+Shift+A, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, outline symbols, Quick Analysis, argument names, Function Arguments, formula bar height, tooltips | missing | | Ctrl+Shift+Page Up / Down, Ctrl+Alt+5, Ctrl+Shift+F1, Ctrl+F5–F10, Alt+F8 / F11 / F12 | same | group sheets, shape cycling, full screen, window keys, macros, VBA, Power Query | missing | | — | Cmd+= (calculate), Cmd+T (references while editing; F4 works), Shift+F7, Cmd+Shift+L | Mac-only extras | missing (Cmd+= is egui's zoom key; no thesaurus or Modify Cell Style) | @@ -160,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. ## Revision history | Date | Change | Summary | +| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | |---|---|---| | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | | 2026-10-13 | minor | Horizontal scrollbar in the sheet tab bar: drag, track click pages, frozen columns excluded from the page (#840) | From 5a72aff0c5be9cc94edecbf0719ff51fd8fe5e08 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 05:08:00 -0500 Subject: [PATCH 03/71] Resize Table: refuse another table, merged cells, a PivotTable or an array; keep header names in step table.resize grew a table over a neighbouring table without checking, leaving two overlapping tables that Excel refuses to open as is. It now refuses, as Excel does, a new range that takes in another table, a merged area, a PivotTable report or a multi-cell array formula. A spilled formula is still allowed (Excel allows it too). The columns a resize added were named by position ("Column{i+1}"), which could repeat a name already in the header row (a table whose third column is Column3, resized to start there, got a second Column3). The header row and the column names then drifted apart and the reader made the name unique on reopen ("Column32"). New columns are now named the way Excel names them (observed): an empty header continues a ColumnN on its left, otherwise takes the lowest free ColumnN, and a repeated header gets the next free suffix. The names are written into the header row as text. A table without a header row keeps its column names by position. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/extra.rs | 131 +++++++++++++++--- crates/engine/tests/table_resize_overlap.rs | 139 ++++++++++++++++++++ 2 files changed, 255 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 01e2ac6e63..a939e227c3 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -826,27 +826,78 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { } .ok_or_else(|| bad("table.resize", "select a cell in a table"))?; edit(s, |cx| { - let sheet = cx.sheet_mut(si)?; - let headers: Vec = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect(); - let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?; + let wb = &cx.wb; + let sheet = wb.sheet(si).ok_or(EngineError::NoDocument)?; + let t = sheet.tables.get(ti).ok_or_else(|| bad("table", "gone"))?; if r.start.row != t.range.start.row || !r.intersects(&t.range) { return Err(EngineError::Other( "The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(), )); } - let mut cols = Vec::new(); - for (i, h) in headers.iter().enumerate() { - let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() }; - let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned(); - cols.push(existing.unwrap_or(TableColumn { - name, - totals: TotalsFn::None, - totals_label: None, - formula: None, - unique_name: None, - xml: None, - })); + // Like Excel, the new range can't take in another table, a merged area, a PivotTable or a + // multi-cell array formula (a spill is fine: it shows #SPILL! inside the table). + if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) { + return Err(EngineError::Other("A table can't overlap another table.".into())); } + if sheet.merges.iter().any(|m| m.intersects(&r)) { + return Err(EngineError::Other("A table can't overlap merged cells.".into())); + } + if sheet.pivots.iter().any(|pt| pt.last_range.unwrap_or_else(|| RangeRef::new(pt.anchor, pt.anchor)).intersects(&r)) { + return Err(EngineError::Other("A table can't overlap a PivotTable report.".into())); + } + if sheet.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r))) { + return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into())); + } + // Header text per new column (`None`: empty). Without a header row, a column that stays + // keeps its name. + let texts: Vec> = (r.start.col..=r.end.col) + .map(|c| { + if !t.header_row { + return c.checked_sub(t.range.start.col).and_then(|i| t.columns.get(i as usize)).map(|x| x.name.clone()); + } + let at = CellRef::new(r.start.row, c); + let v = sheet.value(at); + let text = match v.as_text() { + Some(x) => x.to_string(), + None => crate::display::cell_text(wb, sheet, at), + }; + (!text.trim().is_empty()).then_some(text) + }) + .collect(); + let names = resized_column_names(&texts); + let old = t.range; + let old_cols = t.columns.clone(); + let header_row = t.header_row; + let mut cols = Vec::with_capacity(names.len()); + for (c, name) in (r.start.col..=r.end.col).zip(&names) { + // A column that stays keeps its settings (totals, calculated formula): with a header + // row it's found by name, without one by position. + let existing = if header_row { + old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name)) + } else if c >= old.start.col && c <= old.end.col { + old_cols.get((c - old.start.col) as usize) + } else { + None + }; + cols.push(match existing { + Some(x) => TableColumn { name: name.clone(), ..x.clone() }, + None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None }, + }); + } + let sheet = cx.sheet_mut(si)?; + if header_row { + // Headers hold constant text: a generated or de-duplicated name is written into its + // cell, so the header row and the column names never disagree. + for (c, col) in (r.start.col..=r.end.col).zip(&cols) { + let at = CellRef::new(r.start.row, c); + let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none()); + if !constant_text { + let style = sheet.style_id(at); + sheet.cells.set(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() }); + } + } + } + let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?; t.columns = cols; t.range = r; cx.structural = true; @@ -854,6 +905,56 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { }) } +/// Unique column names for a resized table, from each column's header text (`None` = empty), the +/// way Excel names them: a repeated header gets the lowest free suffix (`Qty`, `Qty2`, `Qty3`, +/// compared without case), and an empty header continues a `ColumnN` neighbour on its left +/// (`Column3` → `Column4`, or `Column32` when `Column4` is taken) or else takes the lowest free +/// `ColumnN`. +fn resized_column_names(texts: &[Option]) -> Vec { + use std::collections::{HashMap, HashSet}; + let mut taken: HashSet = HashSet::new(); + let mut next_suffix: HashMap = HashMap::new(); + // The lowest `ColumnN` not yet tried, so many empty headers stay linear. + let mut lowest = 1u64; + let mut names: Vec = Vec::with_capacity(texts.len()); + let dedupe = |base: &str, taken: &HashSet, next_suffix: &mut HashMap| { + let k = next_suffix.entry(base.to_lowercase()).or_insert(2); + let mut n = base.to_string(); + while taken.contains(&n.to_lowercase()) { + n = format!("{base}{k}"); + *k = k.saturating_add(1); + } + n + }; + for text in texts { + let name = match text { + Some(t) => dedupe(t, &taken, &mut next_suffix), + None => { + let left = names.last().and_then(|l| { + l.strip_prefix("Column") + .filter(|d| !d.starts_with('0') && !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())) + .and_then(|d| d.parse::().ok()) + }); + match left { + Some(n) => { + let cand = format!("Column{}", n.saturating_add(1)); + if taken.contains(&cand.to_lowercase()) { dedupe(&format!("Column{n}"), &taken, &mut next_suffix) } else { cand } + } + None => { + while taken.contains(&format!("column{lowest}")) { + lowest = lowest.saturating_add(1); + } + format!("Column{lowest}") + } + } + } + }; + taken.insert(name.to_lowercase()); + names.push(name); + } + names +} + fn from_csv(s: &mut Session, p: &Json) -> Result { let bytes = if let Some(t) = str_param(p, "text") { t.as_bytes().to_vec() diff --git a/crates/engine/tests/table_resize_overlap.rs b/crates/engine/tests/table_resize_overlap.rs index f8442cc016..31738024ae 100644 --- a/crates/engine/tests/table_resize_overlap.rs +++ b/crates/engine/tests/table_resize_overlap.rs @@ -27,3 +27,142 @@ fn resize_to_overlapping_range_still_works() { s.execute("table.resize", json!({"table":"T", "range":"B1:C2"})).unwrap(); assert_eq!(table_range(&s), "B1:C2"); } + +fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet { + s.doc().unwrap().wb.active().unwrap() +} + +fn names(s: &Session, table: usize) -> Vec { + sheet(s).tables[table].columns.iter().map(|c| c.name.clone()).collect() +} + +fn headers(s: &Session, table: usize) -> Vec { + let sh = sheet(s); + let r = sh.tables[table].range; + (r.start.col..=r.end.col).map(|c| sh.value(gridcraft_core::CellRef::new(r.start.row, c)).display()).collect() +} + +fn with_headers(range: &str, row: &[&str]) -> Session { + let mut s = Session::new(); + s.new_workbook(); + let rows = vec![row.iter().map(|h| json!(h)).collect::>(), row.iter().map(|_| json!(1)).collect(), row.iter().map(|_| json!(2)).collect()]; + s.execute("range.setValues", json!({"range": range, "values": rows})).unwrap(); + s.execute("insert.table", json!({"range": range, "header": true, "name": "T"})).unwrap(); + s +} + +#[test] +fn resize_onto_another_table_is_rejected() { + // ft-3ir.10.23: from the sales sample, growing Table2 over Table1 left two overlapping tables. + let mut s = Session::new(); + s.execute("file.new", json!({"sample": "sales"})).unwrap(); + s.execute("insert.table", json!({"header": true, "range": "M2:N5"})).unwrap(); + s.execute("insert.table", json!({"header": true, "range": "P2:Q5"})).unwrap(); + let e = s.execute("table.resize", json!({"range": "M2:Q5", "table": "Table2"})).unwrap_err().to_string(); + assert!(e.contains("overlap another table"), "{e}"); + let ranges: Vec = sheet(&s).tables.iter().map(|t| t.range.a1()).collect(); + assert!(ranges.contains(&"M2:N5".to_string()) && ranges.contains(&"P2:Q5".to_string()), "{ranges:?}"); + // Down over a table below, or around a whole table, is refused too; next to it is fine. + let mut s = table(); + s.execute("range.setValues", json!({"range": "A5", "values": [["c"], ["1"]]})).unwrap(); + s.execute("insert.table", json!({"range": "A5:A6", "header": true, "name": "U"})).unwrap(); + assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:B5"})).is_err()); + assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:C9"})).is_err()); + s.execute("table.resize", json!({"table": "T", "range": "A1:B4"})).unwrap(); + assert_eq!(table_range(&s), "A1:B4"); +} + +#[test] +fn resize_onto_merged_cells_pivot_or_array_is_rejected() { + let mut s = table(); + s.execute("home.mergeCenter", json!({"range": "D2:E2"})).unwrap(); + let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string(); + assert!(e.contains("merged"), "{e}"); + assert_eq!(table_range(&s), "A1:B2"); + + let mut s = table(); + s.execute("selection.set", json!({"range": "D1:D2"})).unwrap(); + s.execute("cell.set", json!({"cell": "D1", "input": "=ROW(1:2)", "array": true})).unwrap(); + let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string(); + assert!(e.contains("array"), "{e}"); + assert_eq!(table_range(&s), "A1:B2"); + + let mut s = table(); + s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D1", "rows": ["k"], "values": ["v"]})).unwrap(); + assert!(!sheet(&s).pivots.is_empty()); + let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string(); + assert!(e.contains("PivotTable"), "{e}"); + assert_eq!(table_range(&s), "A1:B2"); +} + +#[test] +fn resize_onto_a_spill_is_allowed() { + // Excel lets a table take in a spilled formula (the spill then shows #SPILL!). + let mut s = table(); + s.execute("cell.set", json!({"cell": "D2", "input": "=SEQUENCE(1,2)"})).unwrap(); + s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap(); + assert_eq!(table_range(&s), "A1:D2"); +} + +#[test] +fn resized_in_columns_get_excel_names_written_into_the_header_row() { + // ft-3ir.10.26: a resize whose new columns repeated a name left the header row and the column + // names out of step ("Column3" in memory, "Column32" after reopening). + let mut s = Session::new(); + s.execute("file.new", json!({"sample": "grades"})).unwrap(); + s.execute("home.formatAsTable", json!({"header": "x", "range": "I3:K9", "style": false})).unwrap(); + s.execute("table.resize", json!({"range": "K3:N7", "table": "Table1"})).unwrap(); + let ti = sheet(&s).tables.iter().position(|t| t.name == "Table1").unwrap(); + assert_eq!(names(&s, ti), headers(&s, ti)); + let mut seen = std::collections::HashSet::new(); + assert!(names(&s, ti).iter().all(|n| seen.insert(n.to_lowercase())), "{:?}", names(&s, ti)); + let bytes = gridcraft_engine::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap(); + let (back, _) = gridcraft_engine::io::open_bytes("t.xlsx", &bytes).unwrap(); + let t = back.active().unwrap().tables.iter().find(|t| t.name == "Table1").unwrap(); + assert_eq!(t.columns.iter().map(|c| c.name.clone()).collect::>(), names(&s, ti)); + + // Names Excel gives (observed): an empty header continues a ColumnN on its left, else takes + // the lowest free ColumnN; a repeated header gets the next free suffix. + let cases: [(&str, &[&str], &str, &[&str]); 5] = [ + ("A1:B3", &["a", "b"], "A1:E3", &["a", "b", "Column1", "Column2", "Column3"]), + ("A1:C3", &["Column2", "b", "c"], "A1:F3", &["Column2", "b", "c", "Column1", "Column12", "Column13"]), + ("A1:B3", &["Column3", "b"], "A1:E3", &["Column3", "b", "Column1", "Column2", "Column22"]), + ("A1:B3", &["Column1", "b"], "A1:D3", &["Column1", "b", "Column2", "Column3"]), + ("A1:C3", &["Column1", "Column2", "Column3"], "C1:F3", &["Column3", "Column4", "Column5", "Column6"]), + ]; + for (range, row, to, want) in cases { + let mut s = with_headers(range, row); + s.execute("table.resize", json!({"table": "T", "range": to})).unwrap(); + assert_eq!(names(&s, 0), want.iter().map(|w| w.to_string()).collect::>(), "{row:?} -> {to}"); + assert_eq!(headers(&s, 0), names(&s, 0), "{row:?} -> {to}"); + } + + // Headers already in the new columns are kept, made unique and turned into text. + let mut s = with_headers("A1:B3", &["x", "y"]); + s.execute("range.setValues", json!({"range": "C1", "values": [["X", "x", 5]]})).unwrap(); + s.execute("cell.set", json!({"cell": "F1", "input": "=1+1"})).unwrap(); + s.execute("table.resize", json!({"table": "T", "range": "A1:F3"})).unwrap(); + assert_eq!(names(&s, 0), ["x", "y", "X2", "x3", "5", "2"]); + assert_eq!(headers(&s, 0), names(&s, 0)); + assert!(sheet(&s).cell(gridcraft_core::CellRef::new(0, 5)).is_some_and(|c| c.formula.is_none())); +} + +#[test] +fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() { + let mut s = with_headers("A1:B3", &["a", "b"]); + // As a file can have it: the table starts at its first data row (A2:B3), with no header row. + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + let t = &mut std::sync::Arc::make_mut(&mut wb.sheets[0]).tables[0]; + t.header_row = false; + t.range.start.row = 1; + } + let r = sheet(&s).tables[0].range; + assert!(!sheet(&s).tables[0].header_row); + let to = gridcraft_core::RangeRef::new(r.start, gridcraft_core::CellRef::new(r.end.row, r.end.col + 1)); + let first = sheet(&s).value(r.start).display(); + s.execute("table.resize", json!({"table": "T", "range": to.a1()})).unwrap(); + assert_eq!(names(&s, 0), ["a", "b", "Column1"]); + assert_eq!(sheet(&s).value(r.start).display(), first); +} From cdb3c163ec380f9bbbcb9673c2cecff087cd25c3 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 06:27:02 -0500 Subject: [PATCH 04/71] 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 f3a7c72bb61336a3d742a6dbc65ea3d90a010ead Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:09:19 +0200 Subject: [PATCH 05/71] Format: number formats widen columns that weren't sized by hand (#1077) Increase/Decrease Decimal and the ribbon's other number formats widened the format but never the column, so the number turned into ####. A column nobody sized by hand now widens to the widest number in the target, as observed in Excel 16.0: AutoFit counts as automatic, Column Width (or dragging the border) as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen; columns never narrow. LineInfo::custom now marks columns set by hand too. XLSX reads and writes it as Excel does (customWidth without bestFit = by hand; automatic widths get bestFit and customWidth), and .xls reads COLINFO's fUserSet and fBestFit the same way. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 117 +++++++++++++++++++++++++++- crates/model/src/features.rs | 3 +- crates/ui-egui/tests/interaction.rs | 33 ++++++++ crates/xlsx/src/sheet_read.rs | 3 + crates/xlsx/src/sheet_write.rs | 4 +- crates/xlsx/src/tests/fixtures.rs | 23 ++++++ crates/xlsx/src/tests/roundtrip.rs | 3 +- crates/xlsx/src/xls/mod.rs | 1 + docs/decisions.md | 30 ++++++- docs/file-format-parity.md | 3 +- docs/ui-parity.md | 3 +- 11 files changed, 216 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index cd28cfbfa3..2619f59bdc 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -708,7 +708,64 @@ fn number_format(s: &mut Session, p: &Json) -> Result { fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result { let nf = NumFmt::new(code); - apply_style(s, p, |st| st.num_fmt = nf.clone()) + apply_style(s, p, |st| st.num_fmt = nf.clone())?; + widen_for_numbers(s, p) +} + +/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…), +/// a column nobody sized by hand widens so the formatted numbers in the target fit, instead of +/// showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or +/// widened this way before widens to the widest number in the range, also with Wrap Text and a large +/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden +/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen, +/// and columns never narrow. +fn widen_for_numbers(s: &mut Session, p: &Json) -> Result { + let sheet = target_sheet(s, p)?; + let ranges = target_ranges(s, p)?; + let measure = s.text_width.clone(); + edit(s, |cx| { + let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) }; + let Some(used) = sh.used_range() else { return Ok(Json::Null) }; + if sh.show_formulas { + return Ok(Json::Null); + } + let mut need: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // Measured as AutoFit Column Width measures (the UI's font when it supplies one). + let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default(); + for r in ranges.iter().filter_map(|r| r.intersection(&used)) { + if r.count() > 4_000_000 { + continue; + } + for (c, cell) in sh.cells.iter_range(r) { + if !matches!(cell.value, gridcraft_core::Value::Number(_)) + || sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden) + || sh.merge_at(c).is_some_and(|m| !m.is_single()) + { + continue; + } + let id = sh.style_id(c); + let st = cx.wb.styles.get(id); + if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill { + continue; + } + let text = crate::display::cell_text(&cx.wb, sh, c); + let exact = measured.len() < EXACT_TEXT_WIDTHS; + let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure { + Some(m) => m(t, &st.font, exact), + None => approx_text_width(t, st.font.size, st.font.bold), + }); + let w = w + 6.0 + st.align.indent as f32 * 9.0; + let e = need.entry(c.col).or_insert(0.0); + *e = e.max(w); + } + } + let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect(); + let sh = cx.sheet_mut(sheet)?; + for (c, w) in widen { + sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0)); + } + Ok(Json::Null) + }) } /// Adds or removes one decimal place in the number format (Increase/Decrease Decimal). @@ -1076,6 +1133,7 @@ fn col_width(s: &mut Session, p: &Json) -> Result { let e = sh.cols.entry(c).or_default(); e.size = Some(w as f32); e.hidden = w == 0.0; + e.custom = true; } } Ok(Json::Null) @@ -1167,6 +1225,7 @@ fn autofit_cols(s: &mut Session, p: &Json) -> Result { let e = sh.cols.entry(c).or_default(); e.size = Some(w.ceil()); e.hidden = false; + e.custom = false; // AutoFit makes a width set by hand automatic again (Excel). } Ok(Json::Null) }) @@ -1260,6 +1319,62 @@ mod tests { assert_eq!(adjust_decimals("0%", &v, 1), "0.0%"); } + fn col(s: &crate::Session, c: u32) -> (f32, bool) { + let sh = s.active().unwrap().wb.active().unwrap(); + (sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom)) + } + + /// #1077: Increase Decimal widened the format but not the column, so the number turned into ####. + #[test] + fn increase_decimal_widens_a_column_nobody_sized() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap(); + let (default, _) = col(&s, 0); + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + let (w, custom) = col(&s, 0); + let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string(); + assert_eq!(text, "3.141592650"); + assert!(w > default, "the column widens for {text}: {w} vs {default}"); + assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it"); + assert!(!custom, "it isn't a width set by hand, so it can widen again"); + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + assert!(col(&s, 0).0 > w, "one more decimal, a little wider again"); + let wide = col(&s, 0).0; + s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap(); + assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it"); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step"); + } + + #[test] + fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap(); + s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap(); + assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand"); + s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap(); + for a in ["A1", "B1", "D1"] { + s.execute("home.comma", json!({"range": a})).unwrap(); + } + s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap(); + let (default, _) = col(&s, 4); + assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel"); + assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89"); + assert_eq!(col(&s, 2).0, default, "General rounds to fit instead"); + assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden"); + // AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening. + s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap(); + assert!(!col(&s, 0).1); + s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap(); + let fitted = col(&s, 0).0; + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again"); + } + #[test] fn format_cells_takes_the_documented_keys() { let mut s = crate::Session::new(); diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index aa250b9b0d..14d9549cae 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -925,7 +925,8 @@ pub struct LineInfo { pub outline: u8, pub collapsed: bool, pub style: Option, - /// The size was set by the user (rows): automatic heights follow the content. + /// The size was set by the user. Rows without it follow their content's height; columns + /// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…). #[serde(default)] pub custom: bool, } diff --git a/crates/ui-egui/tests/interaction.rs b/crates/ui-egui/tests/interaction.rs index 46e981d0aa..6679af1d4b 100644 --- a/crates/ui-egui/tests/interaction.rs +++ b/crates/ui-egui/tests/interaction.rs @@ -963,6 +963,39 @@ fn general_numbers_fit_by_the_cells_own_font() { assert_eq!(texts.iter().filter(|t| t.starts_with('#')).count(), 1, "{texts:?}"); } +/// #1077: after Increase Decimal and the other ribbon number formats the column widens enough for +/// the real font, so the number is drawn instead of ####, at the default size and a large bold one. +#[test] +fn ribbon_number_formats_widen_the_column_enough_to_draw_the_number() { + let mut s = blank(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1.23456789, 1234567.891, 98765.4321], [0.5, 1, 2]]})).unwrap(); + s.execute("home.fontSize", json!({"range": "C1", "size": 20})).unwrap(); + s.execute("home.bold", json!({"range": "C1", "on": true})).unwrap(); + for _ in 0..4 { + s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap(); + } + s.execute("home.comma", json!({"range": "B1"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "C1", "format": "Currency"})).unwrap(); + s.execute("selection.set", json!({"cell": "E5"})).unwrap(); + let want: Vec = + ["A1", "B1", "C1"].iter().map(|a| s.execute("cell.get", json!({"cell": a})).unwrap()["text"].as_str().unwrap().trim().to_string()).collect(); + assert_eq!(want, ["1.234567890000", "1,234,567.89", "$98,765.43"]); + let h = harness(s); + let texts: Vec = h + .output() + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) => Some(t.galley.job.text.clone()), + _ => None, + }) + .collect(); + for t in &want { + assert!(texts.iter().any(|x| x.trim() == t), "{t} drawn in full: {texts:?}"); + } + assert!(!texts.iter().any(|t| t.starts_with('#')), "no ####: {texts:?}"); +} + fn text_shapes(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::epaint::TextShape, egui::Rect)>) { match shape { egui::Shape::Text(t) => out.push((t.clone(), clip)), diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 83955ee1fe..71600c920a 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -314,6 +314,9 @@ fn read_cols(cx: &Ctx<'_>, e: &El, sheet: &mut Sheet, remaining: &mut u64) -> Re // A width without `customWidth` that equals the default is just the default. if let Some(w) = c.attr_f64("width") { let px = col_width_to_px(w); + // Excel writes customWidth for every width it stores, and bestFit as well for one that + // AutoFit or a number format sized: only customWidth without bestFit was set by hand. + info.custom = c.flag("customWidth", false) && !c.flag("bestFit", false); if c.flag("customWidth", false) || px != sheet.default_col_width { info.size = Some(px); } diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index daac03daaa..ba499b765c 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -250,8 +250,10 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( if i.hidden { s.push_str(" hidden=\"1\""); } + // As Excel writes them: a width that AutoFit or a number format sized is bestFit too, so + // it keeps widening when the file is opened again; one set by hand is customWidth only. if i.size.is_some() { - s.push_str(" customWidth=\"1\""); + s.push_str(if i.custom { " customWidth=\"1\"" } else { " bestFit=\"1\" customWidth=\"1\"" }); } if i.outline > 0 { let _ = write!(s, " outlineLevel=\"{}\"", i.outline.min(7)); diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 0294f378f4..d9396bfef3 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -169,7 +169,9 @@ fn styles_theme_and_sizes() { assert!(s.cols.get(&2).unwrap().hidden); assert_eq!(s.cols.get(&2).unwrap().size, Some(145.0)); assert_eq!(s.cols.get(&2).unwrap().outline, 1); + assert!(s.cols.get(&2).unwrap().custom, "customWidth: a width set by hand"); assert_ne!(s.cols.get(&3).unwrap().style, None); + assert!(!s.cols.get(&3).unwrap().custom, "no customWidth: not set by hand"); assert_eq!(s.rows.get(&0).unwrap().size, Some(40.0)); let r2 = s.rows.get(&1).unwrap(); assert!(r2.hidden); @@ -250,6 +252,27 @@ fn dxf_border_is_written_before_protection() { assert!(b.is_some() && p.is_some() && b < p, "{dx}"); } +/// Which stored widths were set by hand, as Excel 16.0 treats them when a number format makes a +/// number wider (#1077): only customWidth without bestFit keeps its width; the others widen. +#[test] +fn column_widths_set_by_hand() { + let body = r#" + + "#; + let (wb, _) = read_xlsx(&minimal(body, &[], "", "")).unwrap(); + let s = wb.sheet(0).unwrap(); + let custom: Vec = (0..5).map(|c| s.cols.get(&c).is_some_and(|i| i.custom)).collect(); + assert_eq!(custom, [false, true, false, false, true]); + assert_eq!(s.col_width(4), s.default_col_width, "E: the default width, but set by hand"); + // Written back the way Excel writes them. + let bytes = crate::write_xlsx(&wb).unwrap(); + let mut pkg = crate::package::Package::open(&bytes).unwrap(); + let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap(); + let flags: Vec<(bool, bool)> = + sheet.child("cols").unwrap().kids("col").map(|c| (c.flag("customWidth", false), c.flag("bestFit", false))).collect(); + assert_eq!(flags, [(true, true), (true, false), (true, true), (true, false)], "C and D are one run"); +} + #[test] fn strict_namespace_and_shared_strings() { let ct = super::CT; diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 5b79438dbb..0f66119923 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -103,7 +103,8 @@ fn sample() -> Workbook { s.spill.insert(at("H3"), Value::Number(3.0)); s.cols.insert(0, LineInfo { size: Some(100.0), ..Default::default() }); - s.cols.insert(1, LineInfo { size: Some(100.0), ..Default::default() }); + // Column B was sized by hand (customWidth), A widened by itself; both come back as they were. + s.cols.insert(1, LineInfo { size: Some(100.0), custom: true, ..Default::default() }); s.cols.insert(3, LineInfo { hidden: true, outline: 1, ..Default::default() }); s.cols.insert(5, LineInfo { style: Some(money), ..Default::default() }); s.rows.insert(0, LineInfo { size: Some(30.0), ..Default::default() }); diff --git a/crates/xlsx/src/xls/mod.rs b/crates/xlsx/src/xls/mod.rs index ceaf3e26d3..363715d5dd 100644 --- a/crates/xlsx/src/xls/mod.rs +++ b/crates/xlsx/src/xls/mod.rs @@ -698,6 +698,7 @@ fn sheet_record(rec: &Record<'_>, st: &mut SheetState<'_>, budget: &mut Budget, } let mut info = LineInfo::default(); let px = col_width_to_px(f64::from(width) / 256.0); + info.custom = flags & 0x0002 != 0 && flags & 0x0004 == 0; // fUserSet without fBestFit if flags & 0x0002 != 0 || px != st.sheet.default_col_width { info.size = Some(px); } diff --git a/docs/decisions.md b/docs/decisions.md index 2aa18069f6..d624f44c84 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -79,4 +79,32 @@ to 115% or 100%. That's a large relative step at low zoom and a small one near 4 relative steps keep each notch feeling the same, and the doublings land on 25, 50, 100, 200 and 400%. The status bar's Zoom In / Zoom Out buttons and Ctrl+Alt+= / Ctrl+Alt+- keep their 10% steps, so the wheel and the buttons now step differently. Whether they should share one ladder -(this one, Excel's, or another) is left to the maintainers. \ No newline at end of file +(this one, Excel's, or another) is left to the maintainers. +## Number formats widen columns that weren't sized by hand (#1077) + +Increase/Decrease Decimal and the ribbon's other number formats (the Number Format list, Accounting, +Percent, Comma) widen a column so the formatted numbers in the target fit, instead of showing `####`. +Microsoft's support article "Stop showing rounded numbers" says only that "the column width adjusts +automatically", so the rule comes from observing Excel 16.0 (build 17932, Windows) with synthetic +workbooks: + +- A column at the default width, AutoFitted, or widened this way before widens to the widest number + in the formatted range, also with Wrap Text and a large bold font. It never narrows. +- A width set with Column Width (or by dragging the border) stays, even when it equals the default: + the number shows `####`. AutoFit makes such a column automatic again. +- Hidden columns, text, General numbers (they round to fit instead), merged cells and shrink-to-fit + cells don't widen. +- In XLSX, Excel writes `customWidth="1"` for every width it stores and adds `bestFit="1"` for widths + that AutoFit or a number format set. Only `customWidth` without `bestFit` is read as set by hand: a + width with no flags, `bestFit` alone, or both, keeps widening after the file is opened again. + +`LineInfo::custom`, already used for rows set by hand, now marks columns set by hand too; GridCraft +writes and reads the two flags as Excel does (and `.xls` COLINFO's fUserSet and fBestFit alike). +Files that earlier GridCraft versions saved have `customWidth` without `bestFit` on every stored +width, so those columns open as set by hand and keep their width. + +The engine has no font metrics, so the width is the same estimate AutoFit Column Width uses, which +errs on the wide side; a UI test checks that the real font then draws the number, not `####`. +Excel also widens when a number format is set another way (observed through the `NumberFormat` +property, as Format Cells sets it); GridCraft's Format Cells doesn't yet. That, and typing a number +into a formatted cell, are left for later. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cf567f8bd6..668f54c40d 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-22 · **Change:** minor (XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; .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** @@ -110,6 +110,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet and fBestFit alike (#1077) | | 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 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 07797d70d0..3ea4097d59 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 (ribbon number formats widen columns nobody sized by hand, #1077; 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 | Increase/Decrease Decimal and the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never 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 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/71] 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 f30c206a05419bcf559542471e1f1503a61f3e00 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:20:40 +0200 Subject: [PATCH 07/71] Format: Format Cells' number formats widen columns too, as in Excel (#1077) Observed in Excel 16.0: a number format applied to a number widens a column not sized by hand, whether it comes from the ribbon or the NumberFormat property (as Format Cells sets it); a value entered into an already formatted cell doesn't. shrink_to_fit's #### case now sets its column's width by hand, as Excel would otherwise widen it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 26 ++++++++++++++++++++++---- crates/ui-egui/tests/shrink_to_fit.rs | 2 ++ docs/decisions.md | 11 ++++++----- docs/ui-parity.md | 2 +- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 2619f59bdc..f6b92562c9 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -528,7 +528,12 @@ fn format_cells(s: &mut Session, p: &Json) -> Result { { *st = new; } - }) + })?; + // A number format set here widens columns as the ribbon's do (observed: Excel 16.0). + if patch.get("num_fmt").is_some() { + widen_for_numbers(s, p)?; + } + ok() } /// The style patch with camelCase keys (`numFmt`, `diagDown`, as documented) renamed to the @@ -712,9 +717,9 @@ fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result { widen_for_numbers(s, p) } -/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…), -/// a column nobody sized by hand widens so the formatted numbers in the target fit, instead of -/// showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or +/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…) or +/// Format Cells, a column nobody sized by hand widens so the formatted numbers in the target fit, +/// instead of showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or /// widened this way before widens to the widest number in the range, also with Wrap Text and a large /// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden /// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen, @@ -1375,6 +1380,19 @@ mod tests { assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again"); } + #[test] + fn format_cells_widens_for_a_number_format_only() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891]]})).unwrap(); + let (default, _) = col(&s, 0); + s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"bold": true}}})).unwrap(); + assert_eq!(col(&s, 1).0, default, "no number format, no widening"); + s.execute("home.formatCells", json!({"range": "A1", "style": {"numFmt": "#,##0.000000"}})).unwrap(); + assert!(col(&s, 0).0 > default, "A widens for 1,234,567.891000, as Excel's Format Cells does"); + assert!(!col(&s, 0).1); + } + #[test] fn format_cells_takes_the_documented_keys() { let mut s = crate::Session::new(); diff --git a/crates/ui-egui/tests/shrink_to_fit.rs b/crates/ui-egui/tests/shrink_to_fit.rs index a9428fa23a..2d17ca1334 100644 --- a/crates/ui-egui/tests/shrink_to_fit.rs +++ b/crates/ui-egui/tests/shrink_to_fit.rs @@ -15,6 +15,8 @@ fn harness() -> Harness { s.execute("cell.set", json!({"cell": "A1", "input": "Executive Producer"})).unwrap(); s.execute("home.formatCells", json!({"range": "A1", "style": shrink})).unwrap(); s.execute("cell.set", json!({"cell": "A2", "input": "Control Producer"})).unwrap(); + // Column A's width set by hand (to the default), so the numbers formatted below keep it. + s.execute("home.columnWidth", json!({"cols": "A:A", "width": 64})).unwrap(); s.execute("cell.set", json!({"cell": "A4", "input": "123456789012"})).unwrap(); s.execute("home.formatCells", json!({"range": "A4", "style": {"num_fmt": "#,##0", "align": {"shrink": true}}})).unwrap(); s.execute("cell.set", json!({"cell": "A5", "input": "123456789012"})).unwrap(); diff --git a/docs/decisions.md b/docs/decisions.md index d624f44c84..1535230406 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -82,8 +82,9 @@ steps, so the wheel and the buttons now step differently. Whether they should sh (this one, Excel's, or another) is left to the maintainers. ## Number formats widen columns that weren't sized by hand (#1077) -Increase/Decrease Decimal and the ribbon's other number formats (the Number Format list, Accounting, -Percent, Comma) widen a column so the formatted numbers in the target fit, instead of showing `####`. +Increase/Decrease Decimal, the ribbon's other number formats (the Number Format list, Accounting, +Percent, Comma) and a number format set in Format Cells widen a column so the formatted numbers in +the target fit, instead of showing `####`. Microsoft's support article "Stop showing rounded numbers" says only that "the column width adjusts automatically", so the rule comes from observing Excel 16.0 (build 17932, Windows) with synthetic workbooks: @@ -105,6 +106,6 @@ width, so those columns open as set by hand and keep their width. The engine has no font metrics, so the width is the same estimate AutoFit Column Width uses, which errs on the wide side; a UI test checks that the real font then draws the number, not `####`. -Excel also widens when a number format is set another way (observed through the `NumberFormat` -property, as Format Cells sets it); GridCraft's Format Cells doesn't yet. That, and typing a number -into a formatted cell, are left for later. +Excel doesn't widen when a value is entered into a cell that already has the format (observed through +the `Value` property: the cell shows `####`), and neither does GridCraft. Typing into such a cell +wasn't observed. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3ea4097d59..bb02254f57 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -176,7 +176,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| -| 2026-10-22 | minor | Increase/Decrease Decimal and the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow | +| 2026-10-22 | minor | Increase/Decrease Decimal, the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) and Format Cells' number formats widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never 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 6ce1ce9c6d4919a8c3588bedf6b95fa214893162 Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:20:08 +0200 Subject: [PATCH 08/71] Format: widening looks at the target's stored cells and spills, and indexes its merges (#1077) Review of #2271. A target over 4,000,000 positions was skipped whole, so whole columns with a number a million rows down didn't widen: the stored cells looked at are capped instead (1,000,000). Spilled numbers are measured as the grid shows them; before, a spill child's empty stored cell hid its number. Merged areas are checked through per-column row intervals built once per command, not a scan of every merge for every number. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/format.rs | 80 ++++++++++++++++++++++++++++++--- 1 file changed, 73 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index f6b92562c9..ad089f1dfd 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -724,6 +724,9 @@ fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result { /// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden /// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen, /// and columns never narrow. +/// How many stored cells [`widen_for_numbers`] looks at in one command. +const MAX_WIDEN_CELLS: usize = 1_000_000; + fn widen_for_numbers(s: &mut Session, p: &Json) -> Result { let sheet = target_sheet(s, p)?; let ranges = target_ranges(s, p)?; @@ -734,17 +737,43 @@ fn widen_for_numbers(s: &mut Session, p: &Json) -> Result { if sh.show_formulas { return Ok(Json::Null); } + let targets: Vec = ranges.iter().filter_map(|r| r.intersection(&used)).collect(); + // Merged areas over the targets as sorted row intervals per column, so each cell is checked + // with a binary search rather than a scan of every merge. + let mut merged: std::collections::HashMap> = Default::default(); + for m in sh.merges.iter().filter(|m| !m.is_single()) { + for x in targets.iter().filter_map(|r| m.intersection(r)) { + for col in x.start.col..=x.end.col { + merged.entry(col).or_default().push((m.start.row, m.end.row)); + } + } + } + for v in merged.values_mut() { + v.sort_unstable(); + v.dedup(); + } + let in_merge = |c: CellRef| { + merged.get(&c.col).is_some_and(|v| { + let i = v.partition_point(|&(r0, _)| r0 <= c.row); + i > 0 && v.get(i - 1).is_some_and(|&(_, r1)| c.row <= r1) + }) + }; let mut need: std::collections::BTreeMap = std::collections::BTreeMap::new(); // Measured as AutoFit Column Width measures (the UI's font when it supplies one). let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default(); - for r in ranges.iter().filter_map(|r| r.intersection(&used)) { - if r.count() > 4_000_000 { - continue; - } - for (c, cell) in sh.cells.iter_range(r) { - if !matches!(cell.value, gridcraft_core::Value::Number(_)) + // The stored cells looked at are capped, not the area: a sparse target as tall as the sheet + // still widens for the numbers it holds. Spilled values count as the grid shows them. + let mut budget = MAX_WIDEN_CELLS; + for r in &targets { + let spilled = sh.spill.range(r.start..=r.end).map(|(c, _)| *c).filter(|c| r.contains(*c)); + for c in sh.cells.iter_range(*r).map(|(c, _)| c).chain(spilled) { + if budget == 0 { + break; + } + budget -= 1; + if !matches!(sh.value_ref(c), Some(gridcraft_core::Value::Number(_))) || sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden) - || sh.merge_at(c).is_some_and(|m| !m.is_single()) + || in_merge(c) { continue; } @@ -1380,6 +1409,43 @@ mod tests { assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again"); } + fn book() -> (crate::Session, f32) { + let mut s = crate::Session::new(); + s.new_workbook(); + let (default, _) = col(&s, 0); + (s, default) + } + + /// Whole columns as tall as the sheet with two numbers: the cells are looked at, not the area. + #[test] + fn a_sparse_target_widens_for_the_numbers_it_holds() { + let (mut s, default) = book(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "E1000000", "input": "1234567.891"})).unwrap(); + s.execute("home.comma", json!({"range": "A:E"})).unwrap(); + assert!(col(&s, 4).0 > default, "E widens for 1,234,567.89 a million rows down"); + } + + /// A spilled number counts as the grid shows it: G1's formula spills 1,234,567.891 into H1. + #[test] + fn a_spilled_number_widens_its_column() { + let (mut s, default) = book(); + s.execute("cell.set", json!({"cell": "G1", "input": "=SEQUENCE(1,2,1,1234566.891)"})).unwrap(); + s.execute("home.numberFormat", json!({"range": "H1", "code": "#,##0.000"})).unwrap(); + assert!(col(&s, 7).0 > default, "H widens for the value it shows"); + } + + /// A merged area keeps its columns; the cell beside it widens. + #[test] + fn a_merged_area_keeps_its_columns() { + let (mut s, default) = book(); + s.execute("range.setValues", json!({"range": "J1", "values": [[1234567.891, null, 1234567.891]]})).unwrap(); + s.execute("home.mergeCells", json!({"range": "J1:K1"})).unwrap(); + s.execute("home.comma", json!({"range": "J1:L1"})).unwrap(); + assert_eq!((col(&s, 9).0, col(&s, 10).0), (default, default), "the merged J1:K1 doesn't widen J or K"); + assert!(col(&s, 11).0 > default, "L does"); + } + #[test] fn format_cells_widens_for_a_number_format_only() { let mut s = crate::Session::new(); 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 09/71] 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 a6bedd5153a3b2787eee35b5769e58cab2ab8efc Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:41:30 -0500 Subject: [PATCH 10/71] Docs: keep the UI parity revision table well-formed --- 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 75b7903dd9..d51d556b82 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -174,8 +174,8 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. ## Revision history -| Date | Change | Summary | | 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | +| Date | Change | Summary | |---|---|---| | 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 a4309846b2f7d44b08385027c47dbdd0e9788eb0 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:58:55 -0500 Subject: [PATCH 11/71] Keyboard: Add-mode header drags keep earlier areas; Shift-click ends a pending area --- crates/ui-egui/src/grid.rs | 23 +++++++++++++++++++---- docs/ui-parity.md | 2 +- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 415bb40805..ab478b5875 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -185,6 +185,8 @@ pub struct GridState { /// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next /// arrow moves it again instead of keeping it. pub add_pending: bool, + /// Add mode header drag: the areas kept from before the drag, which the dragged range joins. + pub header_drag_base: Vec, } /// Excel's keyboard selection modes, shown in the status bar. In Extend mode (F8) arrow keys and @@ -2369,6 +2371,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } let range = if sel_mods.shift { RangeRef::cols(sel.anchor.col.min(c), sel.anchor.col.max(c)) } else { RangeRef::cols(c, c) }; + app.grid.header_drag_base = add_mode_base(app); select_ranges(app, range, sel_mods.command, CellRef::new(geo.row_at(sh, geo.cells.top() + 1.0), c)); app.grid.drag = Drag::Cols(if sel_mods.shift { sel.anchor.col } else { c }); return; @@ -2383,6 +2386,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & return; } let range = if sel_mods.shift { RangeRef::rows(sel.anchor.row.min(r), sel.anchor.row.max(r)) } else { RangeRef::rows(r, r) }; + app.grid.header_drag_base = add_mode_base(app); select_ranges(app, range, sel_mods.command, CellRef::new(r, geo.col_at(sh, geo.cells.left() + 1.0))); app.grid.drag = Drag::Rows(if sel_mods.shift { sel.anchor.row } else { r }); return; @@ -2475,6 +2479,7 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & } app.grid.last_click = Some((c, now)); if sel_mods.shift { + app.grid.add_pending = false; let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { d.selection.anchor = sel.anchor; @@ -2549,14 +2554,16 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & } Drag::Rows(anchor) => { let r = geo.row_at(sh, p.y); - let _ = - app.session.run("selection.set", json!({"range": RangeRef::rows(anchor.min(r), anchor.max(r)).a1(), "active": sel.active.a1()})); + let range = RangeRef::rows(anchor.min(r), anchor.max(r)).a1(); + let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::>().join(","); + let _ = app.session.run("selection.set", json!({"range": ranges, "active": sel.active.a1()})); scroll_by(app, vec2(0.0, auto.y)); } Drag::Cols(anchor) => { let c = geo.col_at(sh, p.x); - let _ = - app.session.run("selection.set", json!({"range": RangeRef::cols(anchor.min(c), anchor.max(c)).a1(), "active": sel.active.a1()})); + let range = RangeRef::cols(anchor.min(c), anchor.max(c)).a1(); + let ranges = app.grid.header_drag_base.iter().map(String::as_str).chain([range.as_str()]).collect::>().join(","); + let _ = app.session.run("selection.set", json!({"range": ranges, "active": sel.active.a1()})); scroll_by(app, vec2(auto.x, 0.0)); } Drag::MoveCols { source, .. } => { @@ -3047,6 +3054,14 @@ fn add_mode_move(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, jump: bool) app.grid.add_pending = !kept; } +/// The active sheet's areas in Add mode, as `selection.set` takes them; empty in other modes. +fn add_mode_base(app: &SheetApp) -> Vec { + if app.grid.selection_mode != SelectionMode::Add { + return Vec::new(); + } + app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() +} + fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { // A clicked area is kept: the next Add mode arrow starts a new one. app.grid.add_pending = false; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d51d556b82..f62a30d5be 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -174,9 +174,9 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. ## Revision history -| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | | 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 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 12/71] 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 13/71] 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 41a1a3f8bc8611be25f853e70350fecb97e87a35 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:21:08 -0500 Subject: [PATCH 14/71] Keyboard: Add-mode Shift-click keeps earlier areas; Dutch status labels --- crates/ui-egui/src/grid.rs | 8 +++++++- crates/ui-egui/src/i18n/nl.rs | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 81d3b19298..4d13eee49b 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -2492,8 +2492,14 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & } app.grid.last_click = Some((c, now)); if sel_mods.shift { + // Add mode keeps the areas already selected and drops only the provisional area it made itself. + let mut ranges = add_mode_base(app); + if app.grid.add_pending { + ranges.pop(); + } app.grid.add_pending = false; - let _ = app.session.run("selection.set", json!({"range": RangeRef::new(sel.anchor, c).a1(), "active": sel.active.a1()})); + ranges.push(RangeRef::new(sel.anchor, c).a1()); + let _ = app.session.run("selection.set", json!({"range": ranges.join(","), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { d.selection.anchor = sel.anchor; } diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index c1f952357f..1f35904ddb 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -278,6 +278,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Point" => "Aanwijzen", "Calculate" => "Berekenen", "Select destination and press Enter or choose Paste" => "Selecteer de bestemming en druk op Enter of kies Plakken", + "Extend Selection" => "Selectie uitbreiden", + "Add or Remove Selection" => "Selectie toevoegen of verwijderen", "General" => "Algemeen", "Number" => "Getal", "Currency" => "Valuta", From bf9531954df1cbbe55c5a61f7af1ddd2ab8bed11 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:25:47 -0500 Subject: [PATCH 15/71] Keyboard: test that an Add-mode header drag keeps the earlier areas --- crates/ui-egui/tests/it/keyboard_shortcuts.rs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/ui-egui/tests/it/keyboard_shortcuts.rs b/crates/ui-egui/tests/it/keyboard_shortcuts.rs index 2c8a863fee..6a75c5f5ac 100644 --- a/crates/ui-egui/tests/it/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/it/keyboard_shortcuts.rs @@ -218,6 +218,38 @@ fn clicks_extend_or_add_in_the_selection_modes() { assert_eq!(selection_a1(&h), "B2:D4,H8,H9"); } +/// A point in the column header band, above `col`'s cells. +fn column_header_point(h: &Harness, col: &str) -> egui::Pos2 { + let app = h.state(); + let sheet = app.session.active().unwrap().wb.active().unwrap(); + let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll); + let x = geo.cell_rect(sheet, CellRef::parse(&format!("{col}1")).unwrap()).center().x; + egui::pos2(x, geo.head_top() + 4.0) +} + +fn drag(h: &mut Harness, from: egui::Pos2, to: egui::Pos2) { + h.input_mut().events.push(Event::PointerMoved(from)); + h.run_steps(1); + h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.input_mut().events.push(Event::PointerMoved(to)); + h.run_steps(2); + h.input_mut().events.push(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +#[test] +fn add_mode_header_drag_keeps_the_earlier_areas() { + let mut h = harness(book("B2")); + key(&mut h, Key::F8, Modifiers::SHIFT); + click(&mut h, "F6"); + assert_eq!(selection_a1(&h), "B2,F6"); + h.state_mut().grid.last_click = None; + let (from, to) = (column_header_point(&h, "H"), column_header_point(&h, "J")); + drag(&mut h, from, to); + assert_eq!(selection_a1(&h), "B2,F6,H:J", "a header drag in Add mode adds its columns and keeps the areas already selected"); +} + #[test] fn selection_mode_command_sets_and_reports_without_a_dialog() { let mut h = harness(book("A1")); From 8471ccace5a2a05b6a312b13021cbe0589ed248e Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:33:04 -0500 Subject: [PATCH 16/71] Keyboard: Add mode keeps areas for Home and End; a click inside a larger area removes it --- crates/ui-egui/src/grid.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 4d13eee49b..fc4fb8176d 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -3089,10 +3089,15 @@ fn add_mode_base(app: &SheetApp) -> Vec { fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { // A clicked area is kept: the next Add mode arrow starts a new one. app.grid.add_pending = false; - let current: Vec = - if add { app.session.active().map(|d| d.selection.ranges.iter().map(|x| x.a1()).collect()).unwrap_or_default() } else { vec![] }; + let current: Vec = if add { app.session.active().map(|d| d.selection.ranges.clone()).unwrap_or_default() } else { vec![] }; let clicked = r.a1(); - let ranges = toggled_ranges(current, clicked.clone(), add); + // A click on a cell inside a larger kept area removes that area, as a click on a single-cell area does. + let inside = + (add && current.len() > 1 && r.start == r.end).then(|| current.iter().position(|x| x.a1() != clicked && x.contains(r.start))).flatten(); + let ranges: Vec = match inside { + Some(i) => current.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, x)| x.a1()).collect(), + None => toggled_ranges(current.iter().map(|x| x.a1()).collect(), clicked.clone(), add), + }; // A removed area takes the active cell with it; `selection.set` then puts it at the start of the last area. let params = if ranges.contains(&clicked) { json!({"range": ranges.join(","), "active": active.a1()}) } else { json!({"range": ranges.join(",")}) }; @@ -3191,6 +3196,16 @@ fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: Key::PageUp if !cmd => mv(app, -page, 0), Key::PageDown => app.run_or_alert("sheet.next", json!({})), Key::PageUp => app.run_or_alert("sheet.previous", json!({})), + // Add mode: Home and End move the active cell as arrows do, keeping the selected areas. + Key::Home | Key::End if app.grid.selection_mode == SelectionMode::Add && (cmd || key == Key::Home) => { + let a = app.session.active().map(|d| d.selection.active).unwrap_or_default(); + let to = match key { + Key::Home if cmd => CellRef::new(sh.freeze.map(|f| f.0).unwrap_or(0), sh.freeze.map(|f| f.1).unwrap_or(0)), + Key::End => sh.used_range().map(|u| u.end).unwrap_or_default(), + _ => CellRef::new(a.row, 0), + }; + add_mode_move(app, i64::from(to.row) - i64::from(a.row), i64::from(to.col) - i64::from(a.col), false, false); + } Key::Home if cmd => { let r = sh.freeze.map(|f| f.0).unwrap_or(0); let c = sh.freeze.map(|f| f.1).unwrap_or(0); From 9b7c5ca1f604d7162c44700670686d4096a38572 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:41:13 -0500 Subject: [PATCH 17/71] Keyboard: Add mode drops only its own provisional area; selection commands go through app.run --- crates/ui-egui/src/grid.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index fc4fb8176d..6aff68e5fa 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -184,7 +184,7 @@ pub struct GridState { pub selection_mode: SelectionMode, /// Add mode: the last area is the cell an arrow key moved to, not yet extended, so the next /// arrow moves it again instead of keeping it. - pub add_pending: bool, + pub add_pending: Option, /// Add mode header drag: the areas kept from before the drag, which the dragged range joins. pub header_drag_base: Vec, } @@ -239,7 +239,7 @@ impl GridState { pub fn set_selection_mode(&mut self, mode: SelectionMode) { self.selection_mode = mode; - self.add_pending = false; + self.add_pending = None; } } @@ -2494,10 +2494,11 @@ fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: & if sel_mods.shift { // Add mode keeps the areas already selected and drops only the provisional area it made itself. let mut ranges = add_mode_base(app); - if app.grid.add_pending { + if let Some(p) = app.grid.add_pending.take() + && ranges.last() == Some(&p.a1()) + { ranges.pop(); } - app.grid.add_pending = false; ranges.push(RangeRef::new(sel.anchor, c).a1()); let _ = app.session.run("selection.set", json!({"range": ranges.join(","), "active": sel.active.a1()})); if let Some(d) = app.session.active_mut() { @@ -3058,24 +3059,27 @@ fn add_mode_move(app: &mut SheetApp, dr: i64, dc: i64, shift: bool, jump: bool) app.grid.ensure_visible = true; app.grid.reveal_moving_end = shift; if shift { - let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": jump})); - app.grid.add_pending = false; + let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": true, "jump": jump})); + app.grid.add_pending = None; return; } let Some(mut keep) = app.session.active().map(|d| d.selection.ranges.clone()) else { return }; - if app.grid.add_pending { + // Only the provisional area this mode made is dropped, and only while it is still the last area. + if let Some(p) = app.grid.add_pending.take() + && keep.last() == Some(&p) + { keep.pop(); } // The engine works out where the cell lands (hidden rows, merged cells, Ctrl+arrow jumps). - let _ = app.session.run("selection.move", json!({"dr": dr, "dc": dc, "extend": false, "jump": jump})); + let _ = app.run("selection.move", json!({"dr": dr, "dc": dc, "extend": false, "jump": jump})); let Some((area, active)) = app.session.active().map(|d| (d.selection.current(), d.selection.active)) else { return }; // Landing on an area already kept leaves it kept: the next arrow doesn't drop it. let kept = keep.contains(&area); keep.retain(|r| *r != area); keep.push(area); let range = keep.iter().map(|r| r.a1()).collect::>().join(","); - let _ = app.session.run("selection.set", json!({"range": range, "active": active.a1()})); - app.grid.add_pending = !kept; + let _ = app.run("selection.set", json!({"range": range, "active": active.a1()})); + app.grid.add_pending = (!kept).then_some(area); } /// The active sheet's areas in Add mode, as `selection.set` takes them; empty in other modes. @@ -3088,7 +3092,7 @@ fn add_mode_base(app: &SheetApp) -> Vec { fn select_ranges(app: &mut SheetApp, r: RangeRef, add: bool, active: CellRef) { // A clicked area is kept: the next Add mode arrow starts a new one. - app.grid.add_pending = false; + app.grid.add_pending = None; let current: Vec = if add { app.session.active().map(|d| d.selection.ranges.clone()).unwrap_or_default() } else { vec![] }; let clicked = r.a1(); // A click on a cell inside a larger kept area removes that area, as a click on a single-cell area does. From d2506c03d98f3fa04d4f6339ab75bc8888a1eb99 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:56:45 -0500 Subject: [PATCH 18/71] Resize Table: a normalized header keeps the settings of its own column With a header row, a resized column found its settings by name. A blank header that took a generated name could pick up the settings of another column with that name. A header that was normalized now keeps the column at its address. --- crates/engine/src/cmd/extra.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 77dd21db67..ccdf087704 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -903,7 +903,14 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { // A column that stays keeps its settings (totals, calculated formula): with a header // row it's found by name, without one by position. let existing = if header_row { - old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name)) + // A header that was normalized into a generated name keeps the settings of the + // column at its address, not of whichever column already has that name. + let raw = texts.get((c - r.start.col) as usize).and_then(|x| x.as_deref()); + if c >= old.start.col && c <= old.end.col && raw != Some(name.as_str()) { + old_cols.get((c - old.start.col) as usize) + } else { + old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name)) + } } else if c >= old.start.col && c <= old.end.col { old_cols.get((c - old.start.col) as usize) } else { From 79324b6c171f114bd7015d096124ec9f08db7da5 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:03:49 -0500 Subject: [PATCH 19/71] Resize Table test: the PivotTable fixture anchors outside the resize range The filter report starts above its anchor and overlaps the resize range, so the test checks the report's extent rather than only the anchor cell. --- crates/engine/tests/it/table_resize_overlap.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/table_resize_overlap.rs b/crates/engine/tests/it/table_resize_overlap.rs index 58d52444c2..a80282aa46 100644 --- a/crates/engine/tests/it/table_resize_overlap.rs +++ b/crates/engine/tests/it/table_resize_overlap.rs @@ -116,7 +116,7 @@ fn resize_onto_merged_cells_pivot_or_array_is_rejected() { let mut s = table(); s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap(); - s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D1", "rows": ["k"], "values": ["v"]})).unwrap(); + s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D3", "filters": ["k"], "values": ["v"]})).unwrap(); assert!(!sheet(&s).pivots.is_empty()); let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string(); assert!(e.contains("PivotTable"), "{e}"); From 707ce9e14cb85f34ead23b3d43ad556be58c56bc Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:26:54 -0500 Subject: [PATCH 20/71] Resize Table: name formula headers by value and clear pictures under normalized headers A formula header with formulas shown was named by its source text, so the header became constant text like "=1+1". Use the value text instead. Header normalization wrote through cells.set, which left a picture at that address in place. Use Sheet::set_cell so the picture is removed with it. --- crates/engine/src/cmd/extra.rs | 4 +-- .../engine/tests/it/table_resize_overlap.rs | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index ccdf087704..6a4551210e 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -889,7 +889,7 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { let v = sheet.value(at); let text = match v.as_text() { Some(x) => x.to_string(), - None => crate::display::cell_text(wb, sheet, at), + None => crate::display::value_text(wb, sheet, at), }; (!text.trim().is_empty()).then_some(text) }) @@ -930,7 +930,7 @@ fn table_resize(s: &mut Session, p: &Json) -> Result { let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none()); if !constant_text { let style = sheet.style_id(at); - sheet.cells.set(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() }); + sheet.set_cell(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() }); } } } diff --git a/crates/engine/tests/it/table_resize_overlap.rs b/crates/engine/tests/it/table_resize_overlap.rs index a80282aa46..7bdae2ebbc 100644 --- a/crates/engine/tests/it/table_resize_overlap.rs +++ b/crates/engine/tests/it/table_resize_overlap.rs @@ -193,3 +193,29 @@ fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() { assert_eq!(names(&s, 0), ["a", "b", "Column1"]); assert_eq!(sheet(&s).value(r.start).display(), first); } + +#[test] +fn resized_formula_header_is_named_by_its_value_when_formulas_show() { + let mut s = with_headers("A1:B3", &["x", "y"]); + s.execute("cell.set", json!({"cell": "C1", "input": "=1+1"})).unwrap(); + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + std::sync::Arc::make_mut(&mut wb.sheets[0]).show_formulas = true; + } + s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap(); + assert_eq!(names(&s, 0), ["x", "y", "2"]); + assert_eq!(headers(&s, 0), names(&s, 0)); +} + +#[test] +fn resized_picture_header_is_replaced_and_its_picture_removed() { + let mut s = with_headers("A1:B3", &["x", "y"]); + { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + let picture = gridcraft_engine::model::CellPicture { data: vec![1, 2, 3], mime: "image/png".into(), alt: String::new() }; + std::sync::Arc::make_mut(&mut wb.sheets[0]).set_picture(gridcraft_core::CellRef::new(0, 2), std::sync::Arc::new(picture)); + } + s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap(); + assert!(!sheet(&s).cell_pictures.contains_key(&gridcraft_core::CellRef::new(0, 2))); + assert_eq!(headers(&s, 0), names(&s, 0)); +} From c693db2b9fa3539bab7ec2f84e7269ba98b0802e Mon Sep 17 00:00:00 2001 From: alosslessdev Date: Fri, 23 Oct 2026 01:09:08 -0500 Subject: [PATCH 21/71] Conditional formatting: colour-scale editor and New Rule list (part of #1165) New Formatting Rule offers Excel's six rule types. The colour-scale branch edits per-stop type, value and colour, and Manage Rules edits a rule in place. Formula rules refuse an empty or unparseable formula: the dialog keeps OK disabled until a formula is typed, and the command rejects both an empty rule and a formula that does not parse (#1999), so neither a rule that never applies nor a workbook Excel cannot open is written. Percent and percentile stops are clamped to 0-100, and an edit past the last rule names home.manageRules and leaves no undo step. --- ROADMAP.md | 1 + crates/engine/src/cmd/insert.rs | 423 ++++++++++++++++++----- crates/ui-egui/src/dialogs.rs | 319 ++++++++++++++++- crates/ui-egui/src/i18n/cs.rs | 25 ++ crates/ui-egui/src/i18n/de.rs | 24 ++ crates/ui-egui/src/i18n/es.rs | 24 ++ crates/ui-egui/src/i18n/fr.rs | 24 ++ crates/ui-egui/src/i18n/ja.rs | 21 ++ crates/ui-egui/src/i18n/ko.rs | 24 ++ crates/ui-egui/src/i18n/pt.rs | 22 ++ crates/ui-egui/src/i18n/ru.rs | 24 ++ crates/ui-egui/src/i18n/sr.rs | 24 ++ crates/ui-egui/src/i18n/zh.rs | 24 ++ crates/ui-egui/src/ribbon.rs | 34 +- crates/ui-egui/tests/color_scale_rule.rs | 249 +++++++++++++ docs/gaps.md | 1 + docs/target-app-parity.md | 3 +- docs/ui-parity.md | 2 + 18 files changed, 1179 insertions(+), 89 deletions(-) create mode 100644 crates/ui-egui/tests/color_scale_rule.rs diff --git a/ROADMAP.md b/ROADMAP.md index 48b3cf9bc7..8f7cf001b0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -245,6 +245,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row | | 2026-10-19 | minor | Progress log: long flat operator chains (#916) | | 2026-10-19 | trivial | Progress log: desktop theme portal read timeout | +| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) | | 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes | | 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook | | 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) | diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 9719bf451b..1634cf32b0 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Conditional Formatting", ["Home", "Styles"], None, - "{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}", + "{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], stops?: [{type: min|max|num|percent|percentile|formula, value?, color}], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}", has_doc, add_cf ), @@ -200,7 +200,7 @@ pub fn specs() -> Vec { "Manage Rules…", ["Home", "Styles", "Conditional Formatting"], None, - "{delete?: index, moveUp?: index, moveDown?: index}", + "{delete?: index, moveUp?: index, moveDown?: index, edit?: index, rule?: {...} (with edit)}", has_doc, manage_cf ), @@ -1493,36 +1493,40 @@ fn cf_style_json(st: &Json) -> Result { fn check_cf_formula(cmd: &str, what: &str, formula: &str) -> Result<()> { // Strip exactly one leading '=', the way the XLSX writer does: a value like '===A1' // only parses after several strips and would still be saved unparseable. (#1999 review) - if gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).is_err() { + let parsed = formula.strip_prefix('=').unwrap_or(formula); + // A rule with no formula never applies; the dialog also keeps OK disabled for it. + if parsed.trim().is_empty() { + return Err(bad(cmd, format!("the {what} formula is empty"))); + } + if gridcraft_formula::parse(parsed).is_err() { return Err(bad(cmd, format!("invalid {what} formula `{formula}` — it does not parse; Excel would reject the saved file"))); } Ok(()) } -fn check_cf_value(what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> { +fn check_cf_value(cmd: &str, what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> { if let gridcraft_model::features::CfValueKind::Formula(f) = v { - check_cf_formula("home.conditionalFormat", what, f)?; + check_cf_formula(cmd, what, f)?; } Ok(()) } -fn check_cf_rule(rule: &CfRule) -> Result<()> { - const CMD: &str = "home.conditionalFormat"; +fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> { match rule { CfRule::CellIs { a, b, .. } => { - check_cf_formula(CMD, "comparison value", a)?; + check_cf_formula(cmd, "comparison value", a)?; if let Some(b) = b { - check_cf_formula(CMD, "second comparison value", b)?; + check_cf_formula(cmd, "second comparison value", b)?; } } - CfRule::Expression { formula, .. } => check_cf_formula(CMD, "rule", formula)?, + CfRule::Expression { formula, .. } => check_cf_formula(cmd, "rule", formula)?, CfRule::DataBar { min, max, .. } => { - check_cf_value("data bar minimum", min)?; - check_cf_value("data bar maximum", max)?; + check_cf_value(cmd, "data bar minimum", min)?; + check_cf_value(cmd, "data bar maximum", max)?; } CfRule::ColorScale { stops } => { for (kind, _) in stops { - check_cf_value("color scale threshold", kind)?; + check_cf_value(cmd, "color scale threshold", kind)?; } } _ => {} @@ -1530,41 +1534,50 @@ fn check_cf_rule(rule: &CfRule) -> Result<()> { Ok(()) } -fn add_cf(s: &mut Session, p: &Json) -> Result { - let ranges = target_ranges(s, p)?; - let sheet = target_sheet(s, p)?; - let Some(rule) = p.get("rule") else { - s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({}))); - return ok(); - }; +fn cf_style(rule: &Json, cmd: &str) -> Result