diff --git a/ROADMAP.md b/ROADMAP.md index 8a1c6e7d01..864f53cbb7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -190,6 +190,7 @@ 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 | @@ -322,11 +323,13 @@ 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 | trivial | Progress log: XIRR and IRR follow Excel's solvers | +| 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 | diff --git a/contributors/people.toml b/contributors/people.toml index 703df2ecda..289680d99c 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -121,3 +121,6 @@ sync_github_name = true [people.gmrmad1] real_name = "Madhav Agarwal" + +[people.alosslessdev] +real_name = "Francisco Herrera" 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