diff --git a/ROADMAP.md b/ROADMAP.md index e1e5d1ed39..c3fd7b234e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -5,6 +5,7 @@ > **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365) > **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **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. This page is the summary. The detail is in: @@ -151,6 +152,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) | | 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used | | 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged | +| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 | | 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) | | 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently | | 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export | @@ -190,12 +192,14 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) | | 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format | | 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) | +| 2026-10-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-14 | SORT, SORTBY and Data > Sort order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison | | 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) | | 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison | | 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate | | 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift | | 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) | +| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning | | 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles | | 2026-10-14 | XLSX: formulas opened with dynamic-array metadata (`cm`) keep it on save, with `xl/metadata.xml`. Before, a formula returning one value lost it (11 of 40 corpus files that have the part lost it entirely), and Excel recalculated some of them with implicit intersection (`SUMPRODUCT(IFERROR(...))` changed value) | | 2026-10-14 | Recalculation: a dynamic array's anchor given a new formula that reads its old spill area (`A1` was `=SEQUENCE(3)`, becomes `=SUM(A2:A3)+1` or `=SEQUENCE(1,A2+1)`) sees that area empty instead of the old values | @@ -301,6 +305,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories | | 2026-10-31 | minor | Progress log: Function Library | | 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles | +| 2026-10-26 | minor | Progress log: Excel open check | | 2026-10-26 | minor | Progress log: PDF reading direction and RTL sheets | | 2026-10-26 | minor | Progress log: Arabic PDF text | | 2026-10-26 | minor | Progress log: Arabic bidi display and editing | @@ -321,15 +326,18 @@ 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) | | 2026-10-16 | minor | Progress log: interface fonts held once instead of twice | +| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes | | 2026-10-14 | minor | Progress log: sorts order numbers exactly | | 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) | | 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting | | 2026-10-14 | minor | Progress log: lookups compare numbers exactly | | 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references | +| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save | | 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row | | 2026-10-14 | minor | Progress log: spill anchor reading its old spill area | | 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict | diff --git a/contributors/people.toml b/contributors/people.toml index 442780af74..289680d99c 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -118,3 +118,9 @@ sync_github_name = true [people.RockerHX] sync_github_name = true + +[people.gmrmad1] +real_name = "Madhav Agarwal" + +[people.alosslessdev] +real_name = "Francisco Herrera" diff --git a/crates/calc/src/eval.rs b/crates/calc/src/eval.rs index d10de1240b..a70a23402e 100644 --- a/crates/calc/src/eval.rs +++ b/crates/calc/src/eval.rs @@ -62,6 +62,28 @@ pub struct Lambda { pub env: Vec<(String, Ev)>, } +/// What the tail of a LAMBDA body came to. +enum Tail { + Done(Ev), + /// A call to make in place of the current one, its arguments evaluated. + Call(Arc, Vec<(String, Ev)>), +} + +/// A tail call can pass a closure that captures the previous one, thousands deep. Releasing the +/// chain is a loop, not a recursion, so it cannot overflow the native stack. +impl Drop for Lambda { + fn drop(&mut self) { + let mut pending = std::mem::take(&mut self.env); + while let Some((_, ev)) = pending.pop() { + if let Ev::L(l) = ev + && let Ok(mut inner) = Arc::try_unwrap(l) + { + pending.append(&mut inner.env); + } + } + } +} + #[derive(Clone, Debug)] pub enum Ev { V(Value), @@ -84,6 +106,11 @@ fn err(e: CellError) -> Ev { /// calls in progress, so it still runs. const MAX_LAMBDA_CALLS: usize = 140; +/// Tail calls one LAMBDA call may chain. They run in a loop on one native frame, so this only keeps +/// an endless tail recursion finite. Excel computes a tail countdown to 5,459 and answers `#NUM!` +/// for 5,460, which is 5,460 invocations in the chain. +const MAX_TAIL_CALLS: usize = 5460; + /// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it, /// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames /// above the formula. A cell that another cell's formula computes on demand shares the budget of the diff --git a/crates/calc/src/eval/call.rs b/crates/calc/src/eval/call.rs index 25c1947588..a174d4e960 100644 --- a/crates/calc/src/eval/call.rs +++ b/crates/calc/src/eval/call.rs @@ -5,6 +5,17 @@ use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, Lambda, Pip use std::sync::Arc; impl<'h> Evaluator<'h> { + /// `IF` with an array condition: element-wise. + pub(super) fn if_elementwise(&mut self, arr: &Array, args: &[Expr]) -> Ev { + let t = self.arg_val(args, 1).unwrap_or(Value::Bool(true)); + let f = if args.len() > 2 { self.arg_val(args, 2).unwrap_or(Value::Bool(false)) } else { Value::Bool(false) }; + Ev::V(zip3(arr, &t, &f, |c, t, f| match c.to_bool() { + Ok(true) => t.clone(), + Ok(false) => f.clone(), + Err(e) => Value::Error(e), + })) + } + pub(super) fn call(&mut self, name: &str, args: &[Expr]) -> Ev { match name { "IF" => self.if_call(args), diff --git a/crates/calc/src/eval/lambda.rs b/crates/calc/src/eval/lambda.rs index dfb30029ac..9c98f9f040 100644 --- a/crates/calc/src/eval/lambda.rs +++ b/crates/calc/src/eval/lambda.rs @@ -1,17 +1,26 @@ use super::MAX_LAMBDA_CALLS; use super::array::{broadcast_len, single}; -use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, Value, err}; +use super::special::is_special; +use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err}; use std::sync::Arc; impl<'h> Evaluator<'h> { pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev { + match self.bind_args(l, args) { + Ok(bound) => self.call_lambda_values(l, bound), + Err(e) => e, + } + } + + /// The arguments of a call to `l`, evaluated in the current scope. + fn bind_args(&mut self, l: &Lambda, args: &[Expr]) -> Result, Ev> { // Too many or too few argument positions is #VALUE!. An explicitly empty position, as in // `(1,)`, is `Expr::Missing` and still counts as a position (it binds as omitted). `f()` // parses to no arguments, which for a one-parameter lambda can also be read as one empty // position, so that call still binds the parameter as omitted. let positions_ok = args.len() == l.params.len() || (args.is_empty() && l.params.len() == 1); if !positions_ok { - return err(CellError::Value); + return Err(err(CellError::Value)); } let mut bound = Vec::with_capacity(l.params.len()); for (i, p) in l.params.iter().enumerate() { @@ -21,7 +30,56 @@ impl<'h> Evaluator<'h> { }; bound.push((p.clone(), v)); } - self.call_lambda_values(l, bound) + Ok(bound) + } + + /// Follows `e` through the positions whose value is the value of a LAMBDA call (`IF` branches, + /// parentheses), and returns the call with its arguments evaluated instead of making it, so + /// that `call_lambda_values` can loop. Anything else is evaluated here. + fn tail_step(&mut self, e: &Expr) -> Tail { + match e { + Expr::Paren(x) => self.tail_step(x), + Expr::Call(name, args) if name == "IF" && (2..=3).contains(&args.len()) => { + let c = self.arg_val(args, 0).unwrap_or_default(); + if let Value::Array(arr) = &c { + return Tail::Done(self.if_elementwise(arr, args)); + } + match c.to_bool() { + Ok(true) => self.tail_step_branch(args.get(1)), + Ok(false) => match args.get(2) { + Some(_) => self.tail_step_branch(args.get(2)), + None => Tail::Done(Ev::V(Value::Bool(false))), + }, + Err(x) => Tail::Done(err(x)), + } + } + Expr::Call(name, args) if gridcraft_functions::lookup(name).is_none() && !is_special(name) => match self.name(name) { + Ev::L(l) => self.tail_call(l, args), + Ev::V(Value::Error(x)) => Tail::Done(err(x)), + _ => Tail::Done(err(CellError::Name)), + }, + Expr::Invoke(callee, args) => match self.eval(callee) { + Ev::L(l) => self.tail_call(l, args), + Ev::V(Value::Error(x)) => Tail::Done(err(x)), + _ => Tail::Done(err(CellError::Value)), + }, + _ => Tail::Done(self.eval(e)), + } + } + + /// An `IF` branch; an omitted one (`IF(c,,1)`) is 0. + fn tail_step_branch(&mut self, branch: Option<&Expr>) -> Tail { + match branch { + Some(Expr::Missing) | None => Tail::Done(Ev::V(Value::Number(0.0))), + Some(b) => self.tail_step(b), + } + } + + fn tail_call(&mut self, l: Arc, args: &[Expr]) -> Tail { + match self.bind_args(&l, args) { + Ok(bound) => Tail::Call(l, bound), + Err(e) => Tail::Done(e), + } } pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev { @@ -38,7 +96,29 @@ impl<'h> Evaluator<'h> { self.calls += 1; let saved = std::mem::replace(&mut self.env, l.env.clone()); self.env.extend(bound); - let r = self.eval(&l.body); + // A call in tail position replaces this one instead of nesting under it, so a tail recursion + // uses no more native stack at 5,000 deep than at 5. Each link still spends fuel. + let mut tails = 0; + let mut step = self.tail_step(&l.body); + let r = loop { + match step { + Tail::Done(v) => break v, + Tail::Call(next, bound) => { + tails += 1; + if tails >= MAX_TAIL_CALLS { + break err(CellError::Num); + } + self.fuel = match self.fuel.checked_sub(1) { + Some(f) => f, + None => break err(CellError::Calc), + }; + self.env.clear(); + self.env.extend(next.env.iter().cloned()); + self.env.extend(bound); + step = self.tail_step(&next.body); + } + } + }; self.env = saved; self.calls -= 1; r diff --git a/crates/calc/src/eval/special.rs b/crates/calc/src/eval/special.rs index c75d489d80..72adb5ee11 100644 --- a/crates/calc/src/eval/special.rs +++ b/crates/calc/src/eval/special.rs @@ -195,7 +195,7 @@ impl Precedents<'_> { } } -fn is_special(n: &str) -> bool { +pub(super) fn is_special(n: &str) -> bool { matches!( n, "IF" | "IFS" diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 8dbc4a09a2..a269f3a036 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -1217,17 +1217,67 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() { comment: String::new(), hidden: false, }); - // F(F,n) has n + 1 calls in progress at its deepest; W adds one more call per step. + // W's call to `f` is a tail call, so a wrapped call level costs one call in progress, not two. A tail call reuses its frame, so the tail chain is bounded by `MAX_TAIL_CALLS`, as in Excel + // (5,459 ok, 5,460 #NUM!). F(F,n) otherwise has n + 1 calls in progress at its deepest; W adds + // one more call per step. let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))"); let wrapped = |n: u32| format!("=LET(W,LAMBDA(f,k,f(f,k)),F,LAMBDA(me,n,IF(n<=0,0,1+W(me,n-1))),F(F,{n}))"); - [tail(139), tail(140), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f)) + [tail(5459), tail(5460), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f)) }) .expect("spawn") .join() .expect("recursion must not overflow the stack") }; let small = run(1 << 20); - assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]); + assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Number(70.0), Value::Number(131.0)]); + assert_eq!(run(64 << 20), small); +} + +#[test] +fn a_tail_recursive_lambda_reaches_excels_depth_on_a_small_stack() { + // Excel (measured): a tail countdown is 0 at 5,000 and 5,459 and #NUM! at 5,460 and 10,000. + let run = |stack: usize| { + std::thread::Builder::new() + .stack_size(stack) + .spawn(|| { + let mut wb = Workbook::new(); + wb.names.push(gridcraft_model::DefinedName { + name: "TAILN".into(), + scope: None, + formula: "LAMBDA(n,IF(n=0,0,TAILN(n-1)))".into(), + comment: String::new(), + hidden: false, + }); + let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))"); + // The same chain through parentheses and an applied lambda, and one that returns the base case's value. + let paren = "=LET(F,LAMBDA(me,n,IF(n=0,7,(me(me,n-1)))),F(F,5000))".to_string(); + let invoke = "=LET(F,LAMBDA(me,n,IF(n=0,7,LAMBDA(a,b,me(me,a))(n-1,0))),F(F,2000))".to_string(); + let endless = "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))".to_string(); + // Each call passes a closure that captures the last, 5,000 deep: releasing them must not recurse. + let closures = "=LET(F,LAMBDA(me,n,acc,IF(n=0,0,me(me,n-1,LAMBDA(x,acc)))),F(F,5000,0))".to_string(); + [tail(5000), tail(5459), tail(5460), tail(10000), paren, invoke, endless, "=TAILN(5000)".to_string(), closures] + .map(|f| crate::evaluate(&wb, 0, c("B1"), &f)) + }) + .expect("spawn") + .join() + .expect("tail recursion must not overflow the stack") + }; + let num = Value::Error(CellError::Num); + let small = run(1 << 20); + assert_eq!( + small, + [ + Value::Number(0.0), + Value::Number(0.0), + num.clone(), + num.clone(), + Value::Number(7.0), + Value::Number(7.0), + num, + Value::Number(0.0), + Value::Number(0.0) + ] + ); assert_eq!(run(64 << 20), small); } diff --git a/crates/engine/src/cmd/extra/data.rs b/crates/engine/src/cmd/extra/data.rs index 5af7df0a86..cc4490e7f9 100644 --- a/crates/engine/src/cmd/extra/data.rs +++ b/crates/engine/src/cmd/extra/data.rs @@ -1,4 +1,5 @@ use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range}; +use gridcraft_model::Cell; pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result { let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?; @@ -11,30 +12,85 @@ pub(super) 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(); - 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())); - } - 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::value_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 { + // 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 { + 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.set_cell(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; @@ -42,6 +98,56 @@ pub(super) 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 +} + /// Most cells (rows × columns, blanks included) Get Data imports. The rows are built densely /// before they are written, so a few sparse records or one far-away CSV cell must not expand /// into a rectangle of billions of slots. diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index a5c79bbf91..a3f0b03b32 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -553,7 +553,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 @@ -732,9 +737,95 @@ fn number_format(s: &mut Session, p: &Json) -> Result { set_fmt(s, p, &code) } +/// How many stored cells [`widen_for_numbers`] looks at in one command. +const MAX_WIDEN_CELLS: usize = 1_000_000; + 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…) 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, +/// 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 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(); + // 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) + || in_merge(c) + { + 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). @@ -819,8 +910,8 @@ mod sizes; use cell_styles::cell_style; pub use cell_styles::{CELL_STYLE_NAMES, builtin_cell_style}; +use sizes::{EXACT_TEXT_WIDTHS, autofit_cols, autofit_rows, col_width, default_width, hide, row_height}; pub use sizes::{approx_text_width, chars_to_points}; -use sizes::{autofit_cols, autofit_rows, col_width, default_width, hide, row_height}; #[cfg(test)] mod tests { @@ -856,6 +947,112 @@ 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"); + } + + 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(); + 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(); @@ -870,6 +1067,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}"); + } + /// Outlined letters have no Font-group command; Format Cells' style JSON sets and clears them. #[test] fn format_cells_sets_outlined_letters() { diff --git a/crates/engine/src/cmd/format/sizes.rs b/crates/engine/src/cmd/format/sizes.rs index 5a4ba863ab..446cfd7043 100644 --- a/crates/engine/src/cmd/format/sizes.rs +++ b/crates/engine/src/cmd/format/sizes.rs @@ -107,6 +107,7 @@ pub(super) 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) @@ -187,14 +188,15 @@ fn arabic_em(c: char) -> Option { /// Distinct texts AutoFit measures exactly; past this many, `Session::text_width` is asked for a /// quick measure so a huge column doesn't lay out every value. -const EXACT_TEXT_WIDTHS: usize = 2_000; +pub(super) const EXACT_TEXT_WIDTHS: usize = 2_000; pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result { let (si, lines) = line_targets(s, p, false)?; let measure = s.text_width.clone(); edit(s, |cx| { let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) }; - 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; // Selected columns, then one pass over the populated cells (the store is row-oriented, so a // scan per column would revisit every row for each selected column, empty or not). @@ -228,22 +230,26 @@ pub(super) 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), }; let w = w + 6.0 + st.align.indent as f32 * 9.0 + sh.filter_button_space(cell); let max = maxes.entry(cell.col).or_insert(0.0); @@ -258,6 +264,7 @@ pub(super) 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) }) diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 41310782cb..7aa1f6927b 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -217,7 +217,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 ), @@ -227,7 +227,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 ), @@ -496,4 +496,302 @@ mod tests { s.execute("table.rename", json!({"table": "Table1", "name": "Table1"})).unwrap(); s.execute("table.rename", json!({"table": "Table1", "name": "Rates"})).unwrap(); } + + #[test] + fn colour_scale_thresholds_are_clamped_to_the_percent_range() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "home.conditionalFormat", + json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [ + {"type": "percent", "value": -5, "color": "#112233"}, + {"type": "percentile", "value": 150, "color": "#445566"}, + {"type": "max", "color": "#778899"}, + ]}}), + ) + .unwrap(); + let list = s.execute("home.manageRules", json!({})).unwrap(); + let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap(); + let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") }; + assert_eq!( + stops, + vec![ + (CfValueKind::Percent(0.0), Color::Rgb(0x112233)), + (CfValueKind::Percentile(100.0), Color::Rgb(0x445566)), + (CfValueKind::Max, Color::Rgb(0x778899)), + ] + ); + } + + #[test] + fn colour_scale_stops_reject_empty_formulas_and_unknown_types() { + let mut s = Session::new(); + s.new_workbook(); + let with_stops = |stops: Json| json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}}); + let err = s + .execute( + "home.conditionalFormat", + with_stops(json!([ + {"type": "min", "color": "#112233"}, + {"type": "formula", "value": " ", "color": "#445566"}, + {"type": "max", "color": "#778899"}, + ])), + ) + .unwrap_err() + .to_string(); + assert!(err.contains("home.conditionalFormat"), "{err}"); + assert!(err.contains("formula"), "{err}"); + + let err = s + .execute( + "home.conditionalFormat", + with_stops(json!([ + {"type": "min", "color": "#112233"}, + {"type": "median", "value": 50, "color": "#445566"}, + {"type": "max", "color": "#778899"}, + ])), + ) + .unwrap_err() + .to_string(); + assert!(err.contains("unknown stop type `median`"), "{err}"); + let rules = s.execute("home.manageRules", json!({})).unwrap(); + assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0)); + } + + #[test] + fn colour_scale_rejects_a_stops_value_that_is_not_an_array() { + let mut s = Session::new(); + s.new_workbook(); + // `stops` present but misshapen used to fall back to the default scale instead of erroring. + for stops in [json!({}), json!(null), json!("min")] { + let err = s + .execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}})) + .unwrap_err() + .to_string(); + assert!(err.contains("home.conditionalFormat"), "{err}"); + assert!(err.contains("`stops` must be an array"), "{err}"); + } + let rules = s.execute("home.manageRules", json!({})).unwrap(); + assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "an invalid `stops` creates no rule"); + } + + #[test] + fn colour_scale_formulas_are_stored_verbatim() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "home.conditionalFormat", + json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [ + {"type": "min", "color": "#112233"}, + {"type": "formula", "value": "=$Z$1", "color": "#445566"}, + {"type": "max", "color": "#778899"}, + ]}}), + ) + .unwrap(); + let list = s.execute("home.manageRules", json!({})).unwrap(); + let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap(); + let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") }; + assert_eq!(stops[1].0, CfValueKind::Formula("=$Z$1".into())); + } + + #[test] + fn manage_rules_rejects_a_non_index_edit() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap(); + for bad in [json!("0"), json!(1.5), json!(-1), json!(true)] { + let err = s + .execute("home.manageRules", json!({"edit": bad, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})) + .unwrap_err() + .to_string(); + assert!(err.contains("`edit` must be a rule index"), "{err}"); + } + let rules = s.execute("home.manageRules", json!({})).unwrap(); + assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1)); + } + + #[test] + fn manage_rules_rejects_an_edit_past_the_last_rule() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap(); + let err = s + .execute("home.manageRules", json!({"edit": 1, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})) + .unwrap_err() + .to_string(); + assert!(err.contains("home.manageRules"), "{err}"); + assert!(err.contains("index 1"), "{err}"); + let rules = s.execute("home.manageRules", json!({})).unwrap(); + assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1), "the failed edit leaves the rule alone"); + } + + #[test] + fn manage_rules_rejects_an_edit_index_that_does_not_fit_a_usize() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap(); + // On a 32-bit target this used to cast to zero and replace the rule at index 0. + let err = + s.execute("home.manageRules", json!({"edit": 4294967296u64, "rule": {"type": "expression", "formula": "A1>3"}})).unwrap_err().to_string(); + assert!(err.contains("home.manageRules"), "{err}"); + assert!(err.contains("index 4294967296"), "{err}"); + let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap(); + let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") }; + assert_eq!(formula, "A1>2", "the failed edit leaves the rule alone"); + } + + #[test] + fn manage_rules_names_itself_in_a_style_error() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap(); + // A style shared by both commands must name the one that was called. + let rule = json!({"type": "cellIs", "operator": "greater", "value": 1, "style": {"nope": 1}}); + let err = s.execute("home.manageRules", json!({"edit": 0, "rule": rule.clone()})).unwrap_err().to_string(); + assert!(err.contains("home.manageRules"), "{err}"); + assert!(!err.contains("home.conditionalFormat"), "{err}"); + let err = s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": rule})).unwrap_err().to_string(); + assert!(err.contains("home.conditionalFormat"), "{err}"); + } + + #[test] + fn manage_rules_names_itself_in_a_stop_count_error() { + let mut s = Session::new(); + s.new_workbook(); + let err = s + .execute( + "home.manageRules", + json!({"edit": 0, "rule": {"type": "colorScale", "stops": [ + {"type": "min", "color": "#112233"}, + ]}}), + ) + .unwrap_err() + .to_string(); + assert!(err.contains("home.manageRules"), "{err}"); + } + + #[test] + fn a_formula_rule_needs_a_formula_that_parses() { + let mut s = Session::new(); + s.new_workbook(); + // An empty box used to create a rule that never applies. + let err = + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": ""}})).unwrap_err().to_string(); + assert!(err.contains("formula is empty"), "{err}"); + // `=C1>` used to be written as `C1>`, which Excel refuses to open. + let err = s + .execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=C1>"}})) + .unwrap_err() + .to_string(); + assert!(err.contains("invalid"), "{err}"); + assert!(err.contains("does not parse"), "{err}"); + let rules = s.execute("home.manageRules", json!({})).unwrap(); + assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "a refused rule is not stored"); + } + + #[test] + fn an_invalid_formula_on_edit_leaves_the_rule_alone() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap(); + let err = s.execute("home.manageRules", json!({"edit": 0, "rule": {"type": "expression", "formula": "=C1>"}})).unwrap_err().to_string(); + assert!(err.contains("home.manageRules"), "{err}"); + let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap(); + let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") }; + assert_eq!(formula, "A1>2"); + } + + #[test] + fn a_given_stop_value_must_be_a_number() { + let mut s = Session::new(); + s.new_workbook(); + for ty in ["num", "percent", "percentile"] { + let err = s + .execute( + "home.conditionalFormat", + json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [ + {"type": ty, "value": "5", "color": "#112233"}, + {"type": "max", "color": "#778899"}, + ]}}), + ) + .unwrap_err() + .to_string(); + assert!(err.contains("home.conditionalFormat"), "{ty}: {err}"); + assert!(err.contains(&format!("`{ty}` stop's `value` must be a number")), "{ty}: {err}"); + } + // A refused scale stores nothing. + let rules = s.execute("home.manageRules", json!({})).unwrap(); + assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0)); + } + + #[test] + fn an_omitted_stop_value_is_zero() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "home.conditionalFormat", + json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [ + {"type": "num", "color": "#112233"}, + {"type": "percent", "color": "#445566"}, + {"type": "percentile", "color": "#778899"}, + ]}}), + ) + .unwrap(); + let list = s.execute("home.manageRules", json!({})).unwrap(); + let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap(); + let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") }; + assert_eq!( + stops, + vec![ + (CfValueKind::Number(0.0), Color::Rgb(0x112233)), + (CfValueKind::Percent(0.0), Color::Rgb(0x445566)), + (CfValueKind::Percentile(0.0), Color::Rgb(0x778899)), + ] + ); + } + + #[test] + fn colour_scale_stops_keep_their_thresholds_and_can_be_edited() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "home.conditionalFormat", + json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [ + {"type": "min", "color": "#112233"}, + {"type": "num", "value": 5, "color": "#445566"}, + {"type": "percentile", "value": 90, "color": "#778899"}, + ]}}), + ) + .unwrap(); + let list = s.execute("home.manageRules", json!({})).unwrap(); + let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap(); + let stops = match rule { + CfRule::ColorScale { stops } => stops, + _ => Vec::new(), + }; + assert_eq!( + stops, + vec![ + (CfValueKind::Min, Color::Rgb(0x112233)), + (CfValueKind::Number(5.0), Color::Rgb(0x445566)), + (CfValueKind::Percentile(90.0), Color::Rgb(0x778899)), + ] + ); + + s.execute( + "home.manageRules", + json!({"edit": 0, "rule": {"type": "colorScale", "stops": [ + {"type": "formula", "value": "$B$1", "color": "#ABCABC"}, + {"type": "max", "color": "#DEFDEF"}, + ]}}), + ) + .unwrap(); + let list = s.execute("home.manageRules", json!({})).unwrap(); + let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap(); + let stops = match rule { + CfRule::ColorScale { stops } => stops, + _ => Vec::new(), + }; + assert_eq!(stops, vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]); + } } diff --git a/crates/engine/src/cmd/insert/cond_format.rs b/crates/engine/src/cmd/insert/cond_format.rs index 6f0928ab55..02418698d3 100644 --- a/crates/engine/src/cmd/insert/cond_format.rs +++ b/crates/engine/src/cmd/insert/cond_format.rs @@ -46,9 +46,9 @@ fn is_string_literal(v: &str) -> bool { /// written as `format_range` takes it (`"#RRGGBB"`, `{theme, tint}`, `"auto"`) and `fill` may be a /// colour alone (a solid fill) or `"none"` (no fill). An unknown key is an error rather than /// dropped: dropped, it left a rule with an empty format that matches and shows nothing. -fn cf_style_json(st: &Json) -> Result { +fn cf_style_json(st: &Json, cmd: &str) -> Result { const KEYS: [&str; 6] = ["font", "fill", "borders", "align", "num_fmt", "protection"]; - let err = |m: String| bad("home.conditionalFormat", m); + let err = |m: String| bad(cmd, m); let Some(obj) = st.as_object() else { return Err(err("`style` must be an object, e.g. {\"fill\": \"#FFC7CE\"}".into())) }; let mut st = obj.clone(); if let Some(k) = st.keys().find(|k| !KEYS.contains(&k.as_str())) { @@ -103,36 +103,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)?; } } _ => {} @@ -140,41 +144,53 @@ fn check_cf_rule(rule: &CfRule) -> Result<()> { Ok(()) } -pub(super) 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