diff --git a/Cargo.lock b/Cargo.lock index a3a797038a..88181d25b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2987,6 +2987,7 @@ dependencies = [ "gridcraft-math", "serde", "serde_json", + "sha1 0.11.0", "sha2 0.11.1", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 6a2f966372..39f86f8c8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,8 @@ regex = { version = "1", default-features = false, features = ["std", "unicode", quick-xml = "0.41" zip = { version = "9.8.2", default-features = false, features = ["deflate"] } sha2 = { version = "0.11", default-features = false } +# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`). +sha1 = { version = "0.11", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } # equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is diff --git a/ROADMAP.md b/ROADMAP.md index 9d537eb3f5..a06032292a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,9 +2,10 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **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-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: 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,7 +152,9 @@ 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-25 | Charts: 100% Stacked Line and 100% Stacked Line with Markers (`insert.chart` `{type: "line", subtype: "stacked100"}` and `"stacked100Markers"`), drawn as each value's share of its category's total; XLSX `percentStacked` line charts open as 100% stacked instead of stacked | | 2026-10-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 | | 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority | @@ -168,6 +171,8 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does | | 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share | | 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked | +| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) | +| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel | | 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text | | 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row | | 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) | @@ -187,10 +192,13 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change | | 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS | | 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) | +| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root), with known differences in some `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) | | 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 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it | | 2026-10-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 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it | | 2026-10-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 | @@ -288,6 +296,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| | 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) | +| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; the roadmap qualifies XIRR's known `#NUM!` differences | | 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) | | 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update | | 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row | @@ -303,6 +312,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 | @@ -311,6 +321,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column | | 2026-10-24 | minor | Macro interface on the Automate tab; progress log row | | 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row | +| 2026-10-24 | minor | Progress log: password to modify (#921) | | 2026-10-23 | minor | Progress log: accounting negatives in number text | | 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! | | 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) | @@ -328,10 +339,13 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 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 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save | | 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 | trivial | Progress log: XLSX PivotTables on another workbook kept on save | | 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 | diff --git a/apps/gridcraft-cli/src/check/fidelity.rs b/apps/gridcraft-cli/src/check/fidelity.rs index d8def2747e..13c43a5e08 100644 --- a/apps/gridcraft-cli/src/check/fidelity.rs +++ b/apps/gridcraft-cli/src/check/fidelity.rs @@ -65,6 +65,13 @@ fn cond_format_list(s: &Sheet) -> Vec { cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect() } +/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is +/// in another workbook, a data connection or the Data Model). +fn pivot_count(s: &Sheet) -> usize { + let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count()); + s.pivots.len() + kept +} + fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) { if a != b { d.push(|| format!("{sheet}: {a} → {b}")); @@ -154,7 +161,7 @@ pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec BTreeSet { diff --git a/crates/calc/src/eval/array.rs b/crates/calc/src/eval/array.rs index 39a6e0f534..31fdeb8ab1 100644 --- a/crates/calc/src/eval/array.rs +++ b/crates/calc/src/eval/array.rs @@ -216,13 +216,7 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste } }), BinOp::Concat => match (a.to_text(), b.to_text()) { - (Ok(x), Ok(y)) => { - if x.len() + y.len() > 32767 * 4 { - Value::Error(CellError::Value) - } else { - Value::text(x + &y) - } - } + (Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)), (Err(e), _) | (_, Err(e)) => Value::Error(e), }, BinOp::Eq => Value::Bool(compare(a, b) == Equal), diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index a269f3a036..2048ce822c 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -2762,6 +2762,19 @@ fn loan_schedule_residue_keeps_excels_sign() { assert_eq!(t.get("P7"), Value::Text("".into())); } +#[test] +fn concat_operator_cuts_at_the_cell_limit() { + // Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767. + let mut t = T::new(); + t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))"); + t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")"); + t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))"); + t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")"); + t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))"); + assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0)); + assert_eq!(t.get("A5"), Value::Error(CellError::Value)); +} + #[test] fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() { let mut t = T::new(); diff --git a/crates/chart/src/render/cartesian.rs b/crates/chart/src/render/cartesian.rs index fd4c442248..98849447f3 100644 --- a/crates/chart/src/render/cartesian.rs +++ b/crates/chart/src/render/cartesian.rs @@ -16,6 +16,7 @@ enum Fam { Col100, Line, LineStack, + Line100, Area, AreaStack, Area100, @@ -31,6 +32,7 @@ fn family(k: ChartKind) -> Fam { ColumnStacked100 | BarStacked100 => Fam::Col100, Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line, LineStacked => Fam::LineStack, + LineStacked100 | LineStacked100Markers => Fam::Line100, Area => Fam::Area, AreaStacked => Fam::AreaStack, AreaStacked100 => Fam::Area100, @@ -40,7 +42,7 @@ fn family(k: ChartKind) -> Fam { /// Families stacked to 100%: each category's values are shares of its total. fn is_100(f: Fam) -> bool { - matches!(f, Fam::Col100 | Fam::Area100) + matches!(f, Fam::Col100 | Fam::Line100 | Fam::Area100) } fn is_col(f: Fam) -> bool { @@ -48,7 +50,12 @@ fn is_col(f: Fam) -> bool { } fn is_line(f: Fam) -> bool { - matches!(f, Fam::Line | Fam::LineStack) + matches!(f, Fam::Line | Fam::LineStack | Fam::Line100) +} + +/// Line kinds that draw a marker at each point. +fn has_markers(k: ChartKind) -> bool { + matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers) } /// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the @@ -156,7 +163,7 @@ impl BarSink { } fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec>> { - // Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart). + // Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart). let mut totals: Vec<((bool, Fam), Vec)> = Vec::new(); for (i, s) in data.series.iter().enumerate() { let fam = fams.get(i).copied().unwrap_or(Fam::Col); @@ -187,7 +194,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve for (i, s) in data.series.iter().enumerate() { let fam = fams.get(i).copied().unwrap_or(Fam::Col); let a = sec.get(i).copied().unwrap_or(false); - let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100); + let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::Line100 | Fam::AreaStack | Fam::Area100); let key = (a, fam); let si = if stacked { match stacks.iter().position(|(k, _, _)| *k == key) { @@ -216,7 +223,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve }), (Some((_, pos, _)), _) => { let v = v.unwrap_or(0.0); - let v = if fam == Fam::Area100 { share(key, j, v) } else { v }; + let v = if is_100(fam) { share(key, j, v) } else { v }; pos.get_mut(j).map(|acc| { let base = *acc; *acc = clean(*acc + v); @@ -424,7 +431,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx let pts: Vec> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect(); draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot)); let k = kinds.get(i).copied().unwrap_or(ChartKind::Line); - if k == ChartKind::LineMarkers && cw >= 3.0 { + if has_markers(k) && cw >= 3.0 { draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color); } if labels_on { diff --git a/crates/chart/src/render/legend.rs b/crates/chart/src/render/legend.rs index d2456ef135..38521ab0e8 100644 --- a/crates/chart/src/render/legend.rs +++ b/crates/chart/src/render/legend.rs @@ -57,8 +57,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa .clone() .map(|s| { let sw = match s.kind { - ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line, - ChartKind::LineMarkers => Swatch::LineMarker, + ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => { + Swatch::Line + } + ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker, ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker, _ => Swatch::Box, }; diff --git a/crates/chart/src/render/table.rs b/crates/chart/src/render/table.rs index 9047e0c31e..f356108ce1 100644 --- a/crates/chart/src/render/table.rs +++ b/crates/chart/src/render/table.rs @@ -71,8 +71,8 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 }; if settings.show_keys { let swatch = match series.kind { - ChartKind::Line | ChartKind::LineStacked => Swatch::Line, - ChartKind::LineMarkers => Swatch::LineMarker, + ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 => Swatch::Line, + ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker, _ => Swatch::Box, }; draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color); diff --git a/crates/chart/src/tests.rs b/crates/chart/src/tests.rs index aa261ab36e..7c41699653 100644 --- a/crates/chart/src/tests.rs +++ b/crates/chart/src/tests.rs @@ -8,7 +8,7 @@ use crate::*; mod budget; mod data_table; -const ALL_KINDS: [ChartKind; 26] = [ +const ALL_KINDS: [ChartKind; 28] = [ ChartKind::ColumnClustered, ChartKind::ColumnStacked, ChartKind::ColumnStacked100, @@ -18,6 +18,8 @@ const ALL_KINDS: [ChartKind; 26] = [ ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked, + ChartKind::LineStacked100, + ChartKind::LineStacked100Markers, ChartKind::Pie, ChartKind::Doughnut, ChartKind::Area, @@ -1491,6 +1493,62 @@ fn hundred_percent_stacked_areas_fill_each_category_to_its_total() { assert!(frac(top(south, 2)).abs() < 1e-3, "Q3: South reaches {}", frac(top(south, 2))); } +#[test] +fn hundred_percent_stacked_lines_end_each_category_at_its_total() { + let (north_color, south_color) = ([20, 96, 130, 255], [25, 107, 36, 255]); + for kind in [ChartKind::LineStacked100, ChartKind::LineStacked100Markers] { + let d = ChartData { + category_levels: vec![], + palette: vec![], + categories: ["Q1", "Q2", "Q3", "Q4"].iter().map(|s| s.to_string()).collect(), + series: vec![series("North", &[10.0, 30.0, 0.0, 5.0], north_color, kind), series("South", &[30.0, 10.0, 0.0, 15.0], south_color, kind)], + }; + let mut c = chart(kind); + c.data_labels = false; + let p = render(&c, &d, 640.0, 400.0, &ApproxMeasure); + let t = texts(&p); + assert!(t.contains(&"100%") && t.contains(&"0%"), "{kind:?}: {t:?}"); + assert!(!t.contains(&"40"), "{kind:?}: {t:?}"); + // The value axis labels sit on their gridlines. + let label_y = |s: &str| { + p.iter() + .find_map(|p| match p { + Prim::Text { text, y, .. } if text == s => Some(*y), + _ => None, + }) + .unwrap_or(f32::NAN) + }; + let (y0, y100) = (label_y("0%"), label_y("100%")); + assert!(y0 > y100, "{kind:?}: {y0} {y100}"); + let frac = |y: f32| (y0 - y) / (y0 - y100); + let line = |color: Rgba| { + p.iter() + .find_map(|p| match p { + // The series line is 2.25 wide; its legend swatch is 2.0. + Prim::Line { pts, color: c, width, .. } if *c == color && *width > 2.1 => { + Some(pts.iter().map(|q| frac(q[1])).collect::>()) + } + _ => None, + }) + .unwrap_or_default() + }; + let (north, south) = (line(north_color), line(south_color)); + assert_eq!((north.len(), south.len()), (4, 4), "{kind:?}: {north:?} {south:?}"); + // A category whose total is zero stays on the baseline. + for (j, (n, s)) in [(0.25, 1.0), (0.75, 1.0), (0.0, 0.0), (0.25, 1.0)].into_iter().enumerate() { + assert!((north[j] - n).abs() < 1e-3 && (south[j] - s).abs() < 1e-3, "{kind:?} Q{}: {} {}", j + 1, north[j], south[j]); + } + // Point markers have a white outline; the legend's marker swatches have none. + let circles = |outlined: bool| { + p.iter() + .filter(|p| matches!(p, Prim::Circle { fill: Some(f), stroke, .. } if (*f == north_color || *f == south_color) && stroke.is_some() == outlined)) + .count() + }; + let with_markers = kind == ChartKind::LineStacked100Markers; + assert_eq!((circles(true), circles(false)), if with_markers { (8, 2) } else { (0, 0) }, "{kind:?}"); + } +} + #[test] fn two_level_categories_resolve_and_draw() { let years = ["2023", "", "", "2024", "", ""]; diff --git a/crates/chart/src/tests/data_table.rs b/crates/chart/src/tests/data_table.rs index ddeee07bc6..c6f5105b52 100644 --- a/crates/chart/src/tests/data_table.rs +++ b/crates/chart/src/tests/data_table.rs @@ -148,3 +148,32 @@ fn dense_and_tiny_tables_are_bounded_and_explicit() { assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h); } } + +#[test] +fn table_keys_for_100_percent_stacked_lines_use_line_swatches() { + for (kind, marker) in [(ChartKind::LineStacked100, false), (ChartKind::LineStacked100Markers, true)] { + let mut c = chart(kind); + c.title = Some(String::new()); + c.legend = LegendPos::None; + c.data_labels = false; + c.data_table = Some(ChartDataTable::default()); + let color = [1, 2, 3, 255]; + let d = ChartData { + categories: ["Jan", "Feb"].map(String::from).to_vec(), + series: vec![series("Rate", &[1.0, 3.0], color, kind)], + ..Default::default() + }; + let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure); + let header_y = p + .iter() + .find_map(|p| match p { + Prim::Text { text, y, .. } if text == "Jan" => Some(*y), + _ => None, + }) + .unwrap(); + let key_circles = p.iter().filter(|p| matches!(p, Prim::Circle { cy, fill: Some(f), .. } if *f == color && *cy > header_y)).count(); + assert_eq!(key_circles, usize::from(marker), "{kind:?}"); + let key_box = p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y)); + assert!(!key_box, "{kind:?} key is a line swatch"); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 52b313b253..eebf010f50 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -16,4 +16,4 @@ pub use addr::{ }; pub use date::DateSystem; pub use region::Region; -pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare}; +pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare}; diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index a194f022b1..36b69e67ec 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -501,6 +501,31 @@ pub fn sci_text(n: f64, sig: usize) -> String { format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) } +/// Longest text a cell can hold, in UTF-16 code units. +pub const MAX_TEXT_CHARS: usize = 32_767; + +/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value. +pub fn cap_text(mut s: String) -> String { + if s.len() > MAX_TEXT_CHARS { + let mut units = 0; + if let Some((i, _)) = s.char_indices().find(|(_, c)| { + units += c.len_utf16(); + units > MAX_TEXT_CHARS + }) { + s.truncate(i); + } + } + s +} + +/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through. +pub fn cap_value(v: Value) -> Value { + match v { + Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())), + v => v, + } +} + #[cfg(test)] mod tests { use super::*; @@ -584,6 +609,16 @@ mod tests { assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater); } + #[test] + fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() { + let face = "😀"; + assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS)); + assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS)); + assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)); + assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1)); + assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383)); + } + #[test] fn arabic_diacritics_sort_with_their_base_letter() { assert_eq!(compare_text("بَاب", "بيت"), Ordering::Less); diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 2c786bf0a8..b4e0772ac0 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -23,9 +23,9 @@ mod sort; mod tools; mod validation; -pub use filter::filter_values; pub(crate) use filter::{apply_filter, grow_autofilter}; use filter::{clear_filter, filter_by, reapply, toggle_filter}; +pub use filter::{filter_selection, filter_values}; use grouping::{detail, group, outline_settings, show_levels, subtotal}; pub use sort::sort_context; use sort::{quick_sort, sort}; diff --git a/crates/engine/src/cmd/data/filter.rs b/crates/engine/src/cmd/data/filter.rs index 274c0879bc..f3163ea756 100644 --- a/crates/engine/src/cmd/data/filter.rs +++ b/crates/engine/src/cmd/data/filter.rs @@ -1,8 +1,9 @@ use super::sort::sort_key; use super::{ AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param, - current_region, data_target, edit, json, + data_target, edit, json, }; +use std::collections::{HashMap, HashSet}; // ---------------------------------------------------------------- filter @@ -14,14 +15,63 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { let has = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.autofilter.is_some()); let in_table = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.table_at(at).map(|t| t.name.clone())); if let Some(name) = in_table { + // An explicit range over part of the table is refused, as when installing a filter on it. + if p.get("range").is_some() + && let Some(sh) = s.doc()?.wb.sheet(sheet) + && let Some(t) = sh.tables.iter().find(|t| t.name == name) + && t.range.intersects(&r) + && !(t.header_row + && t.range.start.row == r.start.row + && t.range.contains(r.start) + && t.range.contains(r.end) + && r.start.col == t.range.start.col + && r.end.col == t.range.end.col + && t.data_range().is_none_or(|data| r.end.row >= data.end.row)) + { + return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); + } return edit(s, |cx| { let sh = cx.sheet_mut(sheet)?; + let filtered: Vec = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect(); + let mut cleared = false; if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) { t.filter_button = !t.filter_button; if !t.filter_button { t.filter.clear(); + // The sheet AutoFilter hosted on this table's header row is the table's filter too. + cleared = sh.autofilter.as_ref().is_some_and(|af| af.range.start.row == t.range.start.row && af.range.intersects(&t.range)); } } + if cleared { + sh.autofilter = None; + for r in filtered { + if let Some(info) = sh.rows.get_mut(&r) { + info.hidden = false; + } + } + // Rows another table's criteria hide stay hidden: evaluate each such table's saved + // criteria through the live filter, then hide the union once (a later table would + // unhide what an earlier one excluded) and take the filter off again. + let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> = + sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect(); + let mut excluded: std::collections::HashSet = std::collections::HashSet::new(); + for (range, criteria) in others { + if let Some(sh) = cx.wb.sheet_mut(sheet) { + sh.autofilter = Some(AutoFilter { range, criteria }); + } + apply_filter(&mut cx.wb, sheet); + if let Some(sh) = cx.wb.sheet(sheet) { + excluded.extend((range.start.row.saturating_add(1)..=range.end.row).filter(|r| sh.is_row_hidden(*r))); + } + } + if let Some(sh) = cx.wb.sheet_mut(sheet) { + sh.autofilter = None; + for r in excluded { + sh.rows.entry(r).or_default().hidden = true; + } + } + cx.structural = true; + } Ok(Json::Null) }); } @@ -44,19 +94,58 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result { } /// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection. +/// +/// A sheet AutoFilter never overlaps a table, because a file can't hold one (Excel refuses +/// `Range("A1:C8").AutoFilter` over part of a table, and from a cell outside a table it leaves the +/// table's cells out of the region). Inside a table the filter covers the table from its header +/// row, which is saved as the table's own filter, and takes over the criteria the table already +/// had so there is one filter to save. fn install_filter(s: &mut Session, p: &Json) -> Result { let (sheet, mut r) = data_target(s, p, "data.filter")?; - // A selected header row filters the data below it (#201). - if p.get("range").is_none() && r.height() == 1 { + { let d = s.doc()?; let sh = d.wb.active().ok_or(EngineError::NoDocument)?; - let below = current_region(sh, r.start).end.row; - if below > r.end.row { - r = RangeRef::new(r.start, CellRef::new(below, r.end.col)); + if p.get("range").is_none() && sh.table_at(d.selection.active).is_none() && d.selection.current().is_single() { + r = crate::selection::current_region_outside_tables(sh, d.selection.active); + } + // A selected header row filters the data below it (#201). + if p.get("range").is_none() && r.height() == 1 { + let region = match sh.table_at(r.start) { + Some(t) => t.data_range().map(|dr| RangeRef::new(t.range.start, dr.end)).unwrap_or(t.range), + None => crate::selection::current_region_outside_tables(sh, r.start), + }; + if region.end.row > r.end.row { + r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col)); + } + } + } + let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) }; + // The table whose header row the filter starts on, when it lies inside that table. + let host = + sh.tables.iter().position(|t| t.header_row && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end)); + if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) { + return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead")); + } + // A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them. + if let Some(t) = host.and_then(|i| sh.tables.get(i)) { + if t.data_range().is_some_and(|data| r.end.row < data.end.row) { + return Err(bad("data.filter", "filter the table's full data range")); + } + let shift = r.start.col.saturating_sub(t.range.start.col); + if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) { + return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width")); } } edit(s, |cx| { - cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] }); + let sh = cx.sheet_mut(sheet)?; + let mut criteria = vec![]; + if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) { + // The criteria are saved with the table only while its filter buttons are on. + t.filter_button = true; + let shift = r.start.col.saturating_sub(t.range.start.col); + criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect(); + } + sh.autofilter = Some(AutoFilter { range: r, criteria }); Ok(json!({"filter": true, "range": r.a1()})) }) } @@ -181,19 +270,18 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) { } } -/// Hides rows of the autofilter range that fail any criterion. -pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { - let Some(sh) = wb.sheet(sheet) else { return }; - let Some(af) = sh.autofilter.clone() else { return }; - // An imported range can name rows past the grid; none of those exist to hide. - let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col)); - let mut hide = Vec::new(); +/// Statistics use the original range within the grid, regardless of the other active criteria. +fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap, f64)> { + let r = af.range; // Precompute per-criterion top10 threshold and average once, not per row. - let mut col_stats: std::collections::HashMap, f64)> = std::collections::HashMap::new(); + let mut col_stats = HashMap::new(); for (i, (off, c)) in af.criteria.iter().enumerate() { if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) { - let col = r.start.col + off; - let mut nums: Vec = (r.start.row + 1..=r.end.row).filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()).collect(); + let Some(col) = r.start.col.checked_add(*off) else { continue }; + // Keep main's imported-range bound after extracting statistics from apply_filter. + let mut nums: Vec = (r.start.row.saturating_add(1)..=r.end.row.min(gridcraft_core::MAX_ROWS - 1)) + .filter_map(|row| sh.value(CellRef::new(row, col)).as_f64()) + .collect(); let avg = if nums.is_empty() { 0.0 } else { nums.iter().sum::() / nums.len() as f64 }; let thr = match c { FilterCriterion::Top10 { bottom, percent, count } => { @@ -207,59 +295,97 @@ pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { col_stats.insert(i, (thr, avg)); } } - for row in r.start.row + 1..=r.end.row { - let mut visible = true; - for (i, (off, crit)) in af.criteria.iter().enumerate() { - let c = CellRef::new(row, r.start.col + off); - let v = sh.value(c); - let text = crate::display::cell_text(wb, sh, c); - let ok = match crit { - FilterCriterion::Values { values, blanks } => { - if filter_blank(&v) { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display())) - } - } - FilterCriterion::Custom { a, b, and } => { - let x = custom_ok(&v, &text, &a.0, &a.1); - match b { - Some(b) => { - let y = custom_ok(&v, &text, &b.0, &b.1); - if *and { x && y } else { x || y } - } - None => x, - } - } - FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((thr, _))) => { - let thr = thr.unwrap_or(n); - if *bottom { n <= thr } else { n >= thr } - } - _ => false, - }, - FilterCriterion::AboveAverage(above) => match (v.as_f64(), col_stats.get(&i)) { - (Some(n), Some((_, avg))) => { - if *above { - n > *avg - } else { - n < *avg - } - } - _ => false, - }, - FilterCriterion::FillColor(col) => wb.styles.get(sh.style_id(c)).fill.fg == *col, - FilterCriterion::FontColor(col) => wb.styles.get(sh.style_id(c)).font.color == *col, - // Icons are not evaluated here: the row keeps its current visibility. - FilterCriterion::Icon { .. } => !sh.is_row_hidden(row), - }; - if !ok { - visible = false; - break; - } - } - hide.push((row, !visible)); + col_stats +} + +/// Shared row and checkbox matching, with thresholds and Values lookups prepared once per query. +struct FilterMatcher<'a> { + wb: &'a Workbook, + sh: &'a Sheet, + af: &'a AutoFilter, + stats: HashMap, f64)>, + values: HashMap>, +} + +impl<'a> FilterMatcher<'a> { + fn new(wb: &'a Workbook, sh: &'a Sheet, af: &'a AutoFilter) -> Self { + let values = af + .criteria + .iter() + .enumerate() + .filter_map(|(i, (_, crit))| match crit { + FilterCriterion::Values { values, .. } => Some((i, values.iter().map(|v| v.to_ascii_lowercase()).collect())), + _ => None, + }) + .collect(); + Self { wb, sh, af, stats: filter_stats(sh, af), values } } + + fn row_matches(&self, row: u32, excluded_offset: Option) -> bool { + self.af.criteria.iter().enumerate().all(|(i, (off, crit))| Some(*off) == excluded_offset || self.criterion_matches(row, i, *off, crit)) + } + + fn criterion_matches(&self, row: u32, i: usize, off: u32, crit: &FilterCriterion) -> bool { + let Some(col) = self.af.range.start.col.checked_add(off) else { return true }; + let c = CellRef::new(row, col); + let v = self.sh.value(c); + let text = crate::display::cell_text(self.wb, self.sh, c); + match crit { + FilterCriterion::Values { blanks, .. } => { + if filter_blank(&v) { + *blanks + } else { + self.values + .get(&i) + .is_some_and(|values| values.contains(&text.to_ascii_lowercase()) || values.contains(&v.display().to_ascii_lowercase())) + } + } + FilterCriterion::Custom { a, b, and } => { + let x = custom_ok(&v, &text, &a.0, &a.1); + match b { + Some(b) => { + let y = custom_ok(&v, &text, &b.0, &b.1); + if *and { x && y } else { x || y } + } + None => x, + } + } + FilterCriterion::Top10 { bottom, .. } => match (v.as_f64(), self.stats.get(&i)) { + (Some(n), Some((thr, _))) => { + let thr = thr.unwrap_or(n); + if *bottom { n <= thr } else { n >= thr } + } + _ => false, + }, + FilterCriterion::AboveAverage(above) => match (v.as_f64(), self.stats.get(&i)) { + (Some(n), Some((_, avg))) => { + if *above { + n > *avg + } else { + n < *avg + } + } + _ => false, + }, + FilterCriterion::FillColor(col) => self.wb.styles.get(self.sh.style_id(c)).fill.fg == *col, + FilterCriterion::FontColor(col) => self.wb.styles.get(self.sh.style_id(c)).font.color == *col, + // Icon criteria are retained from files but cannot be evaluated yet. + FilterCriterion::Icon { .. } => true, + } + } +} + +/// Hides rows of the autofilter range that fail any criterion. +pub(crate) fn apply_filter(wb: &mut Workbook, sheet: usize) { + let Some(sh) = wb.sheet(sheet) else { return }; + let Some(af) = sh.autofilter.clone() else { return }; + // An imported range can name rows past the grid; none of those exist to hide. + let r = RangeRef::new(af.range.start, CellRef::new(af.range.end.row.min(gridcraft_core::MAX_ROWS - 1), af.range.end.col)); + let matcher = FilterMatcher::new(wb, sh, &af); + // Reapplying a retained icon filter preserves visibility until icons can be evaluated. + let has_icon = af.criteria.iter().any(|(_, c)| matches!(c, FilterCriterion::Icon { .. })); + let hide: Vec<_> = + (r.start.row + 1..=r.end.row).map(|row| (row, !matcher.row_matches(row, None) || (has_icon && sh.is_row_hidden(row)))).collect(); let Some(shm) = wb.sheet_mut(sheet) else { return }; for (row, h) in hide { if h { @@ -294,30 +420,52 @@ pub(super) fn reapply(s: &mut Session, _: &Json) -> Result { }) } -/// Distinct display values of a filter column (for the dropdown list). +/// Distinct display values from rows matching the other columns' criteria. +/// The current criterion only determines checkboxes, so its unchecked alternatives stay available. pub fn filter_values(wb: &Workbook, sheet: usize, col: u32) -> Vec<(String, bool)> { + column_filter_values(wb, sheet, col, true) +} + +/// Applies edited eligible choices to the whole column's checkbox state, retaining choices hidden by other filters. +pub fn filter_selection(wb: &Workbook, sheet: usize, col: u32, choices: &[(String, bool)]) -> Vec<(String, bool)> { + let mut edited = std::collections::BTreeMap::new(); + for (value, on) in choices { + *edited.entry(value.to_ascii_lowercase()).or_insert(false) |= *on; + } + let mut selection = column_filter_values(wb, sheet, col, false); + for (value, on) in &mut selection { + if let Some(checked) = edited.get(&value.to_ascii_lowercase()) { + *on = *checked; + } + } + selection +} + +fn column_filter_values(wb: &Workbook, sheet: usize, col: u32, eligible_only: bool) -> Vec<(String, bool)> { let Some(sh) = wb.sheet(sheet) else { return vec![] }; let Some(af) = &sh.autofilter else { return vec![] }; - let off = col.saturating_sub(af.range.start.col); - let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c); + if col < af.range.start.col || col > af.range.end.col { + return vec![]; + } + let off = col - af.range.start.col; + let selected = af.criteria.iter().enumerate().find(|(_, (o, _))| *o == off); + let matcher = FilterMatcher::new(wb, sh, af); let mut seen = std::collections::BTreeMap::new(); - for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) { + // Imported end rows cannot add choices beyond the grid either. + for row in + af.range.start.row.saturating_add(1)..=af.range.end.row.min(af.range.start.row.saturating_add(1_000_000)).min(gridcraft_core::MAX_ROWS - 1) + { + if eligible_only && !matcher.row_matches(row, Some(off)) { + continue; + } let c = CellRef::new(row, col); let v = sh.value(c); let blank = filter_blank(&v); let t = if blank { "(Blanks)".to_string() } else { crate::display::cell_text(wb, sh, c) }; - let on = match selected { - Some(FilterCriterion::Values { values, blanks }) => { - if blank { - *blanks - } else { - values.iter().any(|x| x.eq_ignore_ascii_case(&t)) - } - } - _ => true, - }; + let on = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit)); let key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) }; - seen.entry((key, t)).or_insert(on); + // One choice can represent rows with different colors; keep any matching row checked. + *seen.entry((key, t)).or_insert(false) |= on; } let mut values: Vec<_> = seen.into_iter().collect(); values.sort_by(|((a, ta), _), ((b, tb), _)| { diff --git a/crates/engine/src/cmd/edit/cell.rs b/crates/engine/src/cmd/edit/cell.rs index 232c1152ce..b27955a1c4 100644 --- a/crates/engine/src/cmd/edit/cell.rs +++ b/crates/engine/src/cmd/edit/cell.rs @@ -27,7 +27,7 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri } let fmt_is_text = wb.styles.get(style).num_fmt.as_str() == "@"; if fmt_is_text { - return Ok(Some(Cell { value: Value::text(input), formula: None, style, py: None })); + return Ok(Some(Cell { value: gridcraft_core::cap_value(Value::text(input)), formula: None, style, py: None })); } let is_formula = is_formula_input(input); if is_formula && gridcraft_model::python::is_py_formula(input) { @@ -71,6 +71,8 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri return Ok(Some(cell)); } let mut parsed = gridcraft_core::parse::parse_input(input, wb.date_system); + // Excel cuts typed text to 32,767 characters (after any leading apostrophe is dropped). + parsed.value = gridcraft_core::cap_value(parsed.value); // Like Excel's automatic percent entry: a bare number of 1 or more typed into a cell already // formatted as a percentage is a percent (3 -> 3%); smaller numbers are taken as fractions. if parsed.format.is_none() @@ -317,7 +319,7 @@ pub(super) fn range_set_values(s: &mut Session, p: &Json) -> Result { if text.contains('\n') && !cx.wb.styles.get(style).align.wrap { style = cx.wb.styles.derive(style, |s| s.align.wrap = true); } - Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style, py: None }) + Some(Cell { value: gridcraft_core::cap_value(Value::Text(text.as_str().into())), formula: None, style, py: None }) } } _ => input_to_cell(&input, sheet, at, &mut cx.wb)?, diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 5fffeffa18..50441537d9 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -148,6 +148,27 @@ fn go_to_keeps_the_references_entered_newest_first() { assert_eq!(list["recent"][0], format!("Sheet1!A{}", GO_TO_RECENT + 2), "{list}"); } +#[test] +fn cell_set_cuts_text_to_32767_characters() { + // Excel cuts a 40,000-character entry to 32,767; a formula is left alone. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "é".repeat(40_000)})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=LEN(A1)"})).unwrap(); + // An apostrophe prefix isn't text, and a text-formatted cell takes `=` as text. + s.execute("cell.set", json!({"cell": "B1", "input": format!("'{}", "x".repeat(40_000))})).unwrap(); + s.execute("home.numberFormat", json!({"range": "C1", "code": "@"})).unwrap(); + s.execute("cell.set", json!({"cell": "C1", "input": format!("={}", "x".repeat(40_000))})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["value"].clone(); + for at in ["B1", "C1"] { + assert_eq!(get(&mut s, at).as_str().map(|t| t.chars().count()), Some(32_767), "{at}"); + } + assert_eq!(get(&mut s, "A1").as_str().map(|t| t.chars().count()), Some(32_767)); + assert_eq!(get(&mut s, "A2"), json!(32767.0)); + s.execute("cell.set", json!({"cell": "D1", "input": "😀".repeat(16_384)})).unwrap(); + assert_eq!(get(&mut s, "D1").as_str().map(|t| t.encode_utf16().count()), Some(32_766)); +} + #[test] fn cell_set_takes_numbers_for_input_and_value() { // #697: a JSON number for `input` used to clear the cell instead of entering it. @@ -208,6 +229,15 @@ fn set_values_can_store_strings_as_the_text_they_are() { assert!(s.execute("range.setValues", json!({"range": "A8", "parse": 0, "values": [["x"]]})).is_err()); // A line break still turns on Wrap Text. s.execute("range.setValues", json!({"range": "A9", "parse": false, "values": [["one\ntwo"]]})).unwrap(); + // Text stored as given still stops at Excel's 32,767-character cell limit. + let long = "x".repeat(40_000); + s.execute("range.setValues", json!({"range": "A10", "parse": false, "values": [[long]]})).unwrap(); + let len = s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("A10").unwrap()).map(|c| c.value.as_text().map(|t| t.chars().count())); + assert_eq!(len.flatten(), Some(32_767)); + s.execute("range.setValues", json!({"range": "B10", "parse": false, "values": [["😀".repeat(16_384)]]})).unwrap(); + let emoji_len = + s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse("B10").unwrap()).map(|c| c.value.as_text().map(|t| t.encode_utf16().count())); + assert_eq!(emoji_len.flatten(), Some(32_766)); assert_eq!(get(&mut s, "A9")["value"], json!("one\ntwo")); let d = s.doc().unwrap(); let sh = d.wb.active().unwrap(); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 5479b438e0..1887b06a89 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -3,12 +3,12 @@ use serde_json::{Value as Json, json}; use super::{CommandSpec, Result, Session, always, bad, bool_param, cmd, edit, has_doc, ok, str_param, target_sheet, u32_param}; -use crate::DocState; +use crate::{DocState, EngineError}; pub fn specs() -> Vec { vec![ cmd!(noundo "file.new", "New Workbook", ["File"], Some("Cmd+N"), "{sample?: \"budget\"|\"sales\"|\"grades\"}", always, new_workbook), - cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open), + cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"), "{path} | {name, base64}, plus {password} for a password-protected workbook, {modifyPassword} for one with a password to modify (or {readOnly: true} to open it without; Save then asks for a new file), and {csvAsText?: bool} to keep every csv/tsv/txt field as text, with no number or date conversion (xlsx, xlsm, xls import, xlsb and ods data import, csv, tsv, txt, json)", always, open), cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} (xlsx by default; .csv/.tsv/.json/.html/.pdf by extension)", has_doc, save), cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} (.xlsx, .csv, .tsv, .json, .html, or .pdf: a PDF of the active sheet)", has_doc, save_as), cmd!(query "file.saveBytes", "Encode Workbook", [], None, "{format?: xlsx|csv|tsv|json|html} → {base64}", has_doc, save_bytes), @@ -59,6 +59,19 @@ fn open(s: &mut Session, p: &Json) -> Result { }; let encrypted = gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Encrypted; let (mut wb, warnings) = crate::io::open_bytes_with(&name, &bytes, str_param(p, "password"), bool_param(p, "csvAsText").unwrap_or(false))?; + // A password to modify: the right one or a read-only open, or the workbook doesn't open. + let mut read_only = false; + if let Some(hash) = wb.write_reservation.as_ref().and_then(|r| r.password.as_ref()) { + read_only = bool_param(p, "readOnly").unwrap_or(false); + match str_param(p, "modifyPassword") { + _ if read_only => {} + None => return Err(EngineError::Other(format!("'{name}' {}", crate::io::MODIFY_PASSWORD_REQUIRED))), + Some(pw) if !hash.verify(pw).map_err(|e| bad("file.open", e))? => { + return Err(EngineError::Other(crate::io::WRONG_PASSWORD.into())); + } + Some(_) => {} + } + } wb.source_dir = str_param(p, "path").and_then(crate::io::source_dir); // What `CELL("filename")` reports (#1489). A workbook opened from bytes knows its name but // never a folder, so it reports `[name]Sheet` with none; an import reports the file it came @@ -78,7 +91,7 @@ fn open(s: &mut Session, p: &Json) -> Result { // An import has no save target: ordinary Save must ask for a new destination. Neither does a // workbook decrypted with its password, so Save never replaces the encrypted original with // an unprotected copy. - let path = str_param(p, "path").filter(|_| !imported && !encrypted).map(str::to_string); + let path = str_param(p, "path").filter(|_| !imported && !encrypted && !read_only).map(str::to_string); // Replace an untouched blank Book1 like Excel does. if s.documents().len() == 1 && s.active().is_some_and(|d| d.path.is_none() && !d.is_dirty() && d.undo.is_empty() && d.wb.sheets.iter().all(|sh| sh.cells.is_empty())) @@ -87,6 +100,9 @@ fn open(s: &mut Session, p: &Json) -> Result { } // Someone else may have made the file: its active content asks before it runs. let mut doc = DocState::new(wb, path, title, crate::Trust::FromFile); + if read_only { + doc.read_only_source = str_param(p, "path").map(str::to_string); + } if crate::io::FileKind::from_path(&name).is_none() && gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Xlsx { doc.content_kind = Some(crate::io::FileKind::Xlsx); } @@ -106,6 +122,14 @@ fn open(s: &mut Session, p: &Json) -> Result { ) } +/// Whether two paths name one file, whatever their spelling (`./book.xlsx`, a symlink). +fn same_file(a: &str, b: &str) -> bool { + match (std::fs::canonicalize(a), std::fs::canonicalize(b)) { + (Ok(x), Ok(y)) => x == y, + _ => a == b, + } +} + fn save(s: &mut Session, p: &Json) -> Result { let path = match str_param(p, "path").map(str::to_string).or_else(|| s.active().and_then(|d| d.path.clone())) { Some(p) => p, @@ -114,6 +138,9 @@ fn save(s: &mut Session, p: &Json) -> Result { return ok(); } }; + if s.active().and_then(|d| d.read_only_source.as_deref()).is_some_and(|src| same_file(src, &path)) { + return Err(bad("file.save", "is reserved by its author and open read-only. Save As to another file.")); + } // A PDF is a print of the sheet (Page Setup applies), not a copy of the workbook: the // document keeps its file and its unsaved changes. if std::path::Path::new(&path).extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) { diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index aeaf7866df..a3f0b03b32 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -1067,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 cfbb548cbc..446cfd7043 100644 --- a/crates/engine/src/cmd/format/sizes.rs +++ b/crates/engine/src/cmd/format/sizes.rs @@ -195,7 +195,8 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result { 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). @@ -229,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); diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 7aa1f6927b..cb39a2029c 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Insert Chart", ["Insert", "Charts"], None, - "{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers, title?, at?: \"H2\", width?, height?}", + "{range?, type?: column|bar|line|pie|doughnut|area|scatter|bubble|radar|combo|histogram|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}", has_doc, insert_chart ), diff --git a/crates/engine/src/cmd/insert/chart.rs b/crates/engine/src/cmd/insert/chart.rs index 66c99414f8..b45e545787 100644 --- a/crates/engine/src/cmd/insert/chart.rs +++ b/crates/engine/src/cmd/insert/chart.rs @@ -46,6 +46,8 @@ pub fn chart_kind(t: &str, sub: &str) -> ChartKind { ("bar", _) => ChartKind::BarClustered, ("line", "markers") => ChartKind::LineMarkers, ("line", "stacked") => ChartKind::LineStacked, + ("line", "stacked100") => ChartKind::LineStacked100, + ("line", "stacked100Markers") => ChartKind::LineStacked100Markers, ("line", _) => ChartKind::Line, ("pie", _) => ChartKind::Pie, ("doughnut", _) => ChartKind::Doughnut, diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index decd9d4ba6..615215bbb9 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -57,7 +57,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000; use layout::bands; pub(crate) use layout::split_bands; pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range}; -use layout::{known_paper, seg_size, segments}; +use layout::{seg_size, segments}; use objects::{PicCache, draw_objects}; #[cfg(test)] use text::{center_across_width, wrap_lines}; @@ -69,7 +69,7 @@ pub fn specs() -> Vec { "Export as PDF", ["File", "Export"], None, - "{path?, sheets?: active|all, range?: \"A1:F40\" (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.", + "{path?, sheets?: active|all, range?: \"A1:F40\" or several areas \"A1:B5,D1:E5\", one run of pages each (active sheet), fitToPage?: bool} → {pages, bytes, path} or {pages, bytes, base64} when no path. Honours each sheet's Page Setup.", has_doc, export_pdf ), @@ -96,7 +96,7 @@ pub fn specs() -> Vec { "Page Setup…", ["Page Layout", "Page Setup"], None, - "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings", + "{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown} → the sheet's print settings", has_doc, page_setup ), @@ -309,8 +309,9 @@ fn page_setup(s: &mut Session, p: &Json) -> Result { let paper = match str_param(p, "paper") { None => None, Some(name) => { - known_paper(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?; - Some(name.trim().to_string()) + // Stored under its table name, which every file format knows. + let paper = gridcraft_model::paper::canonical(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?; + Some(paper.to_string()) } }; let margin_src = p.get("margins").filter(|m| m.is_object()).unwrap_or(p); diff --git a/crates/engine/src/cmd/print/layout.rs b/crates/engine/src/cmd/print/layout.rs index 0d86de5158..30bf5842ba 100644 --- a/crates/engine/src/cmd/print/layout.rs +++ b/crates/engine/src/cmd/print/layout.rs @@ -9,43 +9,10 @@ pub(super) const DENSE_BLOCK: u64 = 60_000; // ---------------------------------------------------------------- paper -/// Paper size in points (portrait) for a paper name; unknown names fall back to Letter. +/// Paper size in points, as named (see `gridcraft_model::paper`); unknown names, and the empty +/// name of a file that stated no paper, fall back to Letter. pub fn paper_size(name: &str) -> (f32, f32) { - known_paper(name).unwrap_or((612.0, 792.0)) -} - -/// Paper sizes in points, portrait. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel and its -/// e-mail attachments use (257×364, 182×257 and 128×182 mm); the ISO B series stays reachable as -/// `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and envelopes are the JIS ones too. -pub(super) fn known_paper(name: &str) -> Option<(f32, f32)> { - // Spaces, hyphens, underscores and parentheses don't matter: `B5 (JIS)`, `b5-jis` and `b5` - // are one name. - let n = name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], ""); - Some(match n.as_str() { - "letter" | "usletter" => (612.0, 792.0), - "legal" | "uslegal" => (612.0, 1008.0), - "a4" => (595.28, 841.89), - "a3" => (841.89, 1190.55), - "a5" => (419.53, 595.28), - "a6" => (297.64, 419.53), - "tabloid" | "11x17" => (792.0, 1224.0), - "ledger" => (1224.0, 792.0), - "executive" => (522.0, 756.0), - "b4" | "b4jis" => (728.50, 1031.81), - "b5" | "b5jis" => (515.91, 728.50), - "b6" | "b6jis" => (362.83, 515.91), - "b4iso" => (708.66, 1000.63), - "b5iso" => (498.90, 708.66), - "b6iso" => (354.33, 498.90), - "japanesepostcard" | "postcard" => (283.46, 419.53), - "japanesedoublepostcard" | "doublepostcard" => (419.53, 566.93), - "japaneseenvelope#3" | "chou#3" => (340.16, 666.14), - // 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out. - "japaneseenvelope#4" | "chou#4" => (255.12, 581.10), - "japaneseenvelopekaku#2" | "kaku#2" => (680.31, 941.10), - "japaneseenvelopekaku#3" | "kaku#3" => (612.28, 785.20), - _ => return None, - }) + gridcraft_model::paper::size_pt(name).unwrap_or((612.0, 792.0)) } // ---------------------------------------------------------------- layout @@ -103,7 +70,8 @@ impl SheetLayout { #[derive(Clone, Debug, Default)] pub struct PrintOptions { pub all_sheets: bool, - pub range: Option, + /// Areas of the active sheet to print instead of its print area, in order (Print Selection). + pub ranges: Vec, pub fit_to_page: Option, } @@ -114,14 +82,35 @@ impl PrintOptions { Some("all") | Some("workbook") => true, Some(other) => return Err(bad(cmd, format!("`sheets` must be active or all, not `{other}`"))), }; - let range = match str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { - Some(r) => Some(RangeRef::parse(split_sheet(r).1).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?), - None => None, - }; - Ok(PrintOptions { all_sheets, range, fit_to_page: bool_param(p, "fitToPage") }) + let mut ranges = Vec::new(); + if let Some(r) = str_param(p, "range").map(str::trim).filter(|r| !r.is_empty()) { + for part in split_areas(r) { + ranges.push(RangeRef::parse(split_sheet(part.trim()).1.trim()).ok_or_else(|| bad(cmd, format!("not a range: `{r}`")))?); + } + } + Ok(PrintOptions { all_sheets, ranges, fit_to_page: bool_param(p, "fitToPage") }) } } +/// Splits a multi-area reference at the commas outside quoted sheet names, so each area keeps +/// its own optional `Sheet!` prefix. +fn split_areas(r: &str) -> Vec<&str> { + let mut parts = Vec::new(); + let (mut start, mut quoted) = (0, false); + for (i, c) in r.char_indices() { + match c { + '\'' => quoted = !quoted, + ',' if !quoted => { + parts.push(&r[start..i]); + start = i + 1; + } + _ => {} + } + } + parts.push(&r[start..]); + parts +} + /// The range a sheet prints: its print area, else the used range grown to cover drawing /// objects. `None` when there is nothing to print. pub fn print_range(sh: &Sheet) -> Option { @@ -354,14 +343,20 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec { if pages >= MAX_PAGES { break; } - let ovr = if si == wb.active_sheet() { opts.range } else { None }; - if opts.all_sheets && ovr.is_none() && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) { + let areas: Vec> = + if si == wb.active_sheet() && !opts.ranges.is_empty() { opts.ranges.iter().copied().map(Some).collect() } else { vec![None] }; + if opts.all_sheets && areas == [None] && wb.sheet(si).is_some_and(|s| print_range(s).is_none()) { continue; } - if let Some(mut l) = layout_sheet(wb, si, opts, ovr) { - l.pages.truncate(MAX_PAGES - pages); - pages += l.pages.len(); - out.push(l); + for ovr in areas { + if pages >= MAX_PAGES { + break; + } + if let Some(mut l) = layout_sheet(wb, si, opts, ovr) { + l.pages.truncate(MAX_PAGES - pages); + pages += l.pages.len(); + out.push(l); + } } } if out.is_empty() && opts.all_sheets { diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index 853e59937d..4fca8ce705 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -248,7 +248,7 @@ fn rtl_sheet_sparkline_reflects_with_cell_geometry() { color: Color::rgb(255, 0, 0), markers: false, }); - let options = PrintOptions { range: RangeRef::parse("A1:B2"), ..PrintOptions::default() }; + let options = PrintOptions { ranges: RangeRef::parse("A1:B2").into_iter().collect(), ..PrintOptions::default() }; let ltr = render_pdf(&wb, &layouts(&wb, &options), "", "").unwrap().bytes; wb.sheet_mut(0).unwrap().right_to_left = true; let rtl = render_pdf(&wb, &layouts(&wb, &options), "", "").unwrap().bytes; @@ -974,6 +974,48 @@ fn page_setup_paper_sizes_reach_the_pdf_page() { assert!(s.execute("pageLayout.pageSetup", json!({"paper": "Napkin"})).is_err()); } +/// An empty paper name means no paper is stated; it prints on Letter. +#[test] +fn an_unstated_paper_prints_on_letter() { + let mut wb = gridcraft_model::Workbook::new(); + std::sync::Arc::make_mut(&mut wb.sheets[0]).set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into())); + std::sync::Arc::make_mut(&mut wb.sheets[0]).print.paper = String::new(); + let layouts = super::layout::layouts(&wb, &super::layout::PrintOptions::default()); + let l = &layouts[0]; + assert_eq!((l.page_w, l.page_h), (612.0, 792.0)); + assert_eq!(paper_size(""), (612.0, 792.0)); +} + +/// Both commands that set the paper store a known one under its table name, so every file +/// format finds it. +#[test] +fn paper_size_commands_store_the_table_name() { + let mut s = s(); + s.execute("pageLayout.size", json!({"paper": "b5-jis"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "B5"); + s.execute("pageLayout.pageSetup", json!({"paper": "11x17"})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, "Tabloid"); + // Statement and the envelopes XLSX names are accepted by both commands (Page Setup refused + // them before), stored under their table name and printed on their own size. + s.execute("range.setValues", json!({"range": "A1", "values": [["x"]]})).unwrap(); + let close = |v: &Json, want: f64| (v.as_f64().unwrap() - want).abs() < 0.01; + for (cmd, given, stored, w, h) in [ + ("pageLayout.pageSetup", "statement", "Statement", 396.0, 612.0), + ("pageLayout.pageSetup", "envelope #10", "Envelope #10", 297.0, 684.0), + ("pageLayout.pageSetup", "Envelope-DL", "Envelope DL", 311.81, 623.62), + ("pageLayout.size", "Statement", "Statement", 396.0, 612.0), + ("pageLayout.size", "envelope dl", "Envelope DL", 311.81, 623.62), + ] { + s.execute(cmd, json!({"paper": given})).unwrap(); + assert_eq!(s.doc().unwrap().wb.sheets[0].print.paper, stored, "{cmd} {given}"); + let pv = s.execute("file.printPreview", json!({})).unwrap(); + let page = &pv["pageList"][0]; + assert!(close(&page["width"], w) && close(&page["height"], h), "{cmd} {given}: {page}"); + } + // A new workbook still prints on Letter. + assert_eq!(gridcraft_model::Workbook::new().sheets[0].print.paper, "Letter"); +} + #[test] fn hostile_settings_never_panic_and_cap_pages() { let mut s = s(); @@ -1344,3 +1386,71 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() { assert!(pics.chart((0, 1), || vec![line(1000)]).is_none()); assert!(pics.charts.is_empty() && pics.rejected_charts.contains(&(0, 1))); } + +fn preview_ranges(s: &mut Session, p: Json) -> Vec { + let r = s.execute("file.printPreview", p).unwrap(); + r["pageList"].as_array().unwrap().iter().map(|pg| pg["range"].as_str().unwrap().to_string()).collect() +} + +#[test] +fn a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages() { + let mut s = s(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("cell.set", json!({"cell": "H20", "input": "y"})).unwrap(); + s.execute("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap(); + assert_eq!(preview_ranges(&mut s, json!({})), ["F10:H20"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2"})), ["A1:B2"]); + // Several areas, like a multi-area selection: one run of pages each, in the order given. + assert_eq!(preview_ranges(&mut s, json!({"range": "D4:E5,A1:B2"})), ["D4:E5", "A1:B2"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2, D4:E5"})), ["A1:B2", "D4:E5"]); + let (_, pages) = pdf_of(&mut s, json!({"range": "A1:B2,D4:E5"})); + assert_eq!(pages, 2); + for bad in ["A1:B2,", "A1:B2,nope", ","] { + assert!(s.execute("file.printPreview", json!({"range": bad})).is_err(), "{bad}"); + } +} + +#[test] +fn a_sheet_qualifier_on_a_later_area_does_not_swallow_the_earlier_ones() { + let mut s = s(); + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]); + assert_eq!(preview_ranges(&mut s, json!({"range": "Sheet1!A1:B2,Sheet1!D4:E5"})), ["A1:B2", "D4:E5"]); + // A comma inside a quoted sheet name is not an area separator. + assert_eq!(preview_ranges(&mut s, json!({"range": "A1:B2,'a,b'!D4:E5"})), ["A1:B2", "D4:E5"]); +} + +/// XLSX id 34 is ISO B5 (176 × 250 mm), not the Letter fallback of the old name. +#[test] +fn imported_xlsx_b5_envelope_uses_iso_b5_print_dimensions() { + use std::io::{Cursor, Read, Write}; + let mut wb = gridcraft_model::Workbook::new(); + wb.sheet_mut(0).unwrap().set_value(CellRef::new(0, 0), gridcraft_core::Value::Text("x".into())); + wb.sheet_mut(0).unwrap().print.paper = "Legal".into(); + let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap(); + let mut input = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let mut output = zip::ZipWriter::new(Cursor::new(Vec::new())); + for i in 0..input.len() { + let mut part = input.by_index(i).unwrap(); + let mut data = Vec::new(); + part.read_to_end(&mut data).unwrap(); + let name = part.name().unwrap().to_string(); + if name == "xl/worksheets/sheet1.xml" { + let xml = String::from_utf8(data).unwrap(); + assert!(xml.contains(r#"paperSize="5""#)); + // Set the input id independently of the shared paper-name mapping under test. + data = xml.replace(r#"paperSize="5""#, r#"paperSize="34""#).into_bytes(); + } + output.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + output.write_all(&data).unwrap(); + } + let bytes = output.finish().unwrap().into_inner(); + let mut s = Session::new(); + s.execute("file.open", json!({"name": "iso-b5.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap(); + let preview = s.execute("file.printPreview", json!({})).unwrap(); + let page = &preview["pageList"][0]; + assert!((page["width"].as_f64().unwrap() - 498.90).abs() < 0.01, "{page}"); + assert!((page["height"].as_f64().unwrap() - 708.66).abs() < 0.01, "{page}"); + let (pdf, pages) = pdf_of(&mut s, json!({})); + assert_eq!(pages, 1); + assert!(contains(&pdf, "/MediaBox [0 0 498.9 708.66]")); +} diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 954ec95ad9..9df96f1c1e 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Size", ["Page Layout", "Page Setup"], None, - "{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3 (B4/B5/B6 are the JIS sizes)}", + "{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}", has_doc, paper ), @@ -324,7 +324,9 @@ fn orientation(s: &mut Session, p: &Json) -> Result { } fn paper(s: &mut Session, p: &Json) -> Result { - let paper = str_param(p, "paper").unwrap_or("Letter").to_string(); + // A known paper is stored under its table name; any other name is kept (it prints on Letter). + let name = str_param(p, "paper").unwrap_or("Letter"); + let paper = gridcraft_model::paper::canonical(name).unwrap_or(name).to_string(); edit(s, |cx| { let si = cx.sheet_index(); cx.sheet_mut(si)?.print.paper = paper.clone(); diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 0f2dd78287..31c183663c 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -53,6 +53,10 @@ impl FileKind { /// The error for an encrypted workbook opened without a password contains this. The interface /// asks for the password when it sees it; programmatic callers pass `password` instead. pub const PASSWORD_REQUIRED: &str = "is password-protected. Enter its password to open it."; +/// The error for a workbook with a password to modify, opened with neither that password +/// (`modifyPassword`) nor `readOnly`, contains this. The interface asks for the password or a +/// read-only open when it sees it. +pub const MODIFY_PASSWORD_REQUIRED: &str = "is reserved by its author. Enter the password to modify it, or open it read-only."; /// The error for a wrong password contains this. pub const WRONG_PASSWORD: &str = "The password is incorrect."; /// The first open warning of a workbook decrypted with its password. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1238be31dc..52a0c6482f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -206,6 +206,9 @@ pub struct DocState { /// The format `path`'s content was recognised as when its extension doesn't name one (an /// XLSX called `budget.dat`): Save writes it back in that format. pub content_kind: Option, + /// The file a read-only open came from (`readOnly` on a workbook with a password to modify). + /// Save never writes over it, so the reservation holds; Save As to another file still works. + pub read_only_source: Option, /// Whether the scripts stored in this workbook may run (`automate.runScript`). A workbook /// that arrives already carrying scripts (opened from a file) starts untrusted until the /// user trusts it in this session (`automate.trustScripts`); one with no scripts starts @@ -364,6 +367,7 @@ impl DocState { sheet_selections: vec![], unlocked_ranges: vec![], content_kind: None, + read_only_source: None, scripts_trusted, trust, touched: None, diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index c0c6959cdb..d96a846626 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -310,7 +310,40 @@ pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef { /// The contiguous data region around `c` (Ctrl+A / Ctrl+Shift+8, AutoSum, sort, tables). pub fn current_region(sheet: &Sheet, c: CellRef) -> RangeRef { - let filled = |c: CellRef| sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c); + region_where(sheet, c, |_| true) +} + +/// The data region a sheet AutoFilter takes from `c`, a cell outside any table: the current +/// region, kept off the tables it reaches. Observed in Windows Excel 16 (table B4:C8, text in +/// A1:A3, A5:A8 and B3; the current region of A1 is A1:C8): from A1 the filter covers A1:A3, from +/// A6 A5:A8, from B3 A1:B3. So the region is cut to the columns on the cell's side of the table +/// when the cell is left or right of it, else to the rows above or below, and grown again from +/// the cell inside that window. +pub fn current_region_outside_tables(sheet: &Sheet, c: CellRef) -> RangeRef { + let (mut c0, mut c1, mut r0, mut r1) = (0, MAX_COLS - 1, 0, MAX_ROWS - 1); + let mut region = current_region(sheet, c); + for _ in 0..=sheet.tables.len() { + let Some(t) = sheet.tables.iter().find(|t| t.range.intersects(®ion)) else { break }; + let t = t.range; + if c.col < t.start.col { + c1 = c1.min(t.start.col - 1); + } else if c.col > t.end.col { + c0 = c0.max(t.end.col + 1); + } else if c.row < t.start.row { + r1 = r1.min(t.start.row - 1); + } else if c.row > t.end.row { + r0 = r0.max(t.end.row + 1); + } else { + return RangeRef::cell(c); + } + region = region_where(sheet, c, |x| x.col >= c0 && x.col <= c1 && x.row >= r0 && x.row <= r1 && sheet.table_at(x).is_none()); + } + region +} + +/// The current region around `c`, counting only filled cells that `counts` accepts. +fn region_where(sheet: &Sheet, c: CellRef, counts: impl Fn(CellRef) -> bool) -> RangeRef { + let filled = |c: CellRef| (sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c)) && counts(c); // Whether a row (or column) has a filled cell between two columns (rows), inclusive. let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col))); let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col))); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ac3aad28f0..07cc1b9367 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -962,11 +962,13 @@ fn rich_clipboard_omits_html_for_large_ranges_without_truncating_text() { #[test] fn rich_clipboard_omits_html_when_escaping_exceeds_byte_budget() { let mut s = s(); - let text = "&".repeat(1_000_000); - s.execute("range.setValues", json!({"range": "A1", "values": [[text]]})).unwrap(); - let copied = s.execute("edit.copy", json!({"range": "A1", "html": true})).unwrap(); + // Cells hold at most 32,767 characters, so 30 full cells of `&` (5 bytes each once escaped) + // pass the 4 MiB HTML budget while the plain text stays far below it. + let cell = "&".repeat(32_767); + s.execute("range.setValues", json!({"range": "A1", "values": [vec![cell; 30]]})).unwrap(); + let copied = s.execute("edit.copy", json!({"range": "A1:AD1", "html": true})).unwrap(); assert!(copied.get("html").is_none(), "an oversized escaped value must not produce partial HTML"); - assert_eq!(copied["text"].as_str().unwrap().len(), 1_000_001); + assert_eq!(copied["text"].as_str().unwrap().len(), 30 * 32_767 + 30); assert!(copied["text"].as_str().unwrap().ends_with("&\n")); } @@ -2164,7 +2166,7 @@ fn filter_with_a_sheet_prefix_toggles_the_table_at_the_range() { wb.sheet(wb.sheet_index("Prices").unwrap()).unwrap().clone() }; assert!(prices(&s).tables[0].filter_button); - s.execute("data.filter", json!({"range": "Prices!A2:B3"})).unwrap(); + s.execute("data.filter", json!({"range": "Prices!A1:B3"})).unwrap(); assert!(!prices(&s).tables[0].filter_button); assert!(prices(&s).autofilter.is_none()); assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none()); @@ -5589,6 +5591,75 @@ fn encrypted_book(password: &str) -> Vec { gridcraft_xlsx::testing::encrypt_workbook(&xlsx, password) } +#[test] +fn a_password_to_modify_asks_for_it_or_a_read_only_open() { + const PW: &str = "synthetic-modify-pw"; + let mut src = s(); + src.execute("cell.set", json!({"cell": "A1", "input": "42"})).unwrap(); + std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation { + password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), + ..Default::default() + }); + let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap(); + let b64 = crate::io::base64_encode(&bytes); + let open = |s: &mut Session, extra: serde_json::Value| { + let mut p = json!({"name": "Reserved.xlsx", "base64": b64}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("file.open", p) + }; + let mut s = Session::new(); + let err = open(&mut s, json!({})).unwrap_err().to_string(); + assert!(err.contains(crate::io::MODIFY_PASSWORD_REQUIRED), "{err}"); + assert!(s.take_ui_requests().is_empty(), "programmatic calls never open dialogs"); + for wrong in ["not-it", ""] { + let err = open(&mut s, json!({"modifyPassword": wrong})).unwrap_err().to_string(); + assert!(err.contains(crate::io::WRONG_PASSWORD), "{err}"); + } + assert!(s.documents().is_empty()); + + // Read-only: opens, keeps the reservation, but has no file to save over. + open(&mut s, json!({"readOnly": true})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(42.0)); + assert!(s.doc().unwrap().wb.write_reservation.is_some()); + + // The password: opens, and the reservation survives a save. + let mut s = Session::new(); + open(&mut s, json!({"modifyPassword": PW})).unwrap(); + assert_eq!(v(&s, "A1"), Value::Number(42.0)); + let saved = crate::io::save_bytes(&s.doc().unwrap().wb, "book.xlsx").unwrap(); + let (back, _) = crate::io::open_bytes("book.xlsx", &saved).unwrap(); + assert!(back.write_reservation.and_then(|r| r.password).is_some_and(|h| h.verify(PW) == Ok(true))); +} + +#[test] +fn a_read_only_open_never_saves_over_its_reserved_file() { + const PW: &str = "synthetic-modify-pw"; + let dir = std::env::temp_dir().join(format!("gridcraft-read-only-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("reserved.xlsx").to_string_lossy().into_owned(); + let copy = dir.join("copy.xlsx").to_string_lossy().into_owned(); + let mut src = s(); + std::sync::Arc::make_mut(&mut src.doc_mut().unwrap().wb).write_reservation = Some(gridcraft_model::WriteReservation { + password: Some(gridcraft_model::PasswordHash::new_sha512(PW, b"0123456789abcdef")), + ..Default::default() + }); + let bytes = crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap(); + std::fs::write(&path, &bytes).unwrap(); + + let mut s = Session::new(); + s.execute("file.open", json!({"path": path, "readOnly": true})).unwrap(); + let err = s.execute("file.save", json!({"path": path})).unwrap_err().to_string(); + assert!(err.contains("read-only"), "{err}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); + let dotted = dir.join(".").join("reserved.xlsx").to_string_lossy().into_owned(); + let err = s.execute("file.save", json!({"path": dotted})).unwrap_err().to_string(); + assert!(err.contains("read-only"), "the same file under another spelling: {err}"); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the reserved file is untouched"); + s.execute("file.saveAs", json!({"path": copy})).unwrap(); + assert!(std::fs::metadata(©).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn encrypted_workbooks_open_with_their_password() { const PW: &str = "synthetic-pw-5521"; diff --git a/crates/engine/tests/it/autofit_filter_buttons.rs b/crates/engine/tests/it/autofit_filter_buttons.rs index dbf25eced0..2b27ad2b8a 100644 --- a/crates/engine/tests/it/autofit_filter_buttons.rs +++ b/crates/engine/tests/it/autofit_filter_buttons.rs @@ -7,6 +7,9 @@ fn table() -> Session { s.new_workbook(); s.execute("range.setValues", json!({"range":"A1", "values":[["Quarterly Revenue"], ["1"]]})).unwrap(); s.execute("insert.table", json!({"range":"A1:A2", "header":true})).unwrap(); + // Bold in its own style too, so the table style's bold header row changes nothing here and + // these tests compare only the filter button's room, with or without the table. + s.execute("home.bold", json!({"range":"A1", "on": true})).unwrap(); s } diff --git a/crates/engine/tests/it/cascading_filter_values.rs b/crates/engine/tests/it/cascading_filter_values.rs new file mode 100644 index 0000000000..0eb731522d --- /dev/null +++ b/crates/engine/tests/it/cascading_filter_values.rs @@ -0,0 +1,427 @@ +use std::sync::Arc; + +use gridcraft_engine::{ + Session, + cmd::data::{filter_selection, filter_values}, + core::{CellRef, Value}, + model::{Cell, Color, FilterCriterion, PyCode}, +}; +use serde_json::json; + +#[test] +fn python_cells_offer_cached_results_without_exposing_or_changing_code() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Company", "Result"], ["East", 7], ["East", null], ["West", 99]]})).unwrap(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + for (at, value) in [("B2", Value::Number(7.0)), ("B3", Value::Empty), ("B4", Value::Number(99.0))] { + // A loaded workbook can keep Python code alongside a cached or empty result. + sh.set_cell(CellRef::parse(at).unwrap(), Cell { value, py: Some(Arc::new(PyCode::new("secret_input * 2"))), ..Default::default() }); + } + s.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + let doc = s.doc().unwrap(); + let (before, revision, undo) = (doc.wb.clone(), doc.revision, doc.undo.len()); + assert_eq!(filter_values(&doc.wb, 0, 1), vec![("7".into(), true), ("(Blanks)".into(), true)]); + assert_eq!( + filter_selection(&doc.wb, 0, 1, &[("7".into(), false), ("(Blanks)".into(), false)]), + vec![("7".into(), false), ("99".into(), true), ("(Blanks)".into(), false)], + "eligible edits overlay the cached results; a hidden result keeps its checkbox" + ); + let doc = s.doc().unwrap(); + assert!(Arc::ptr_eq(&before, &doc.wb), "neither query mutates or evaluates the workbook"); + assert_eq!((doc.revision, doc.undo.len()), (revision, undo)); + assert_eq!(doc.wb.active().unwrap().cell(CellRef::parse("B3").unwrap()).unwrap().py.as_ref().unwrap().code, "secret_input * 2"); +} + +#[test] +fn slicer_criteria_outside_the_sheet_filters_columns_are_still_applied() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Name"], ["one"], ["two"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "F1", "values": [["Region"], ["East"], ["West"]]})).unwrap(); + s.execute("insert.table", json!({"range": "F1:F3", "name": "Other", "header": true})).unwrap(); + s.execute("selection.set", json!({"cell": "A1"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:A3"})).unwrap(); + let id = s.execute("insert.slicer", json!({"table": "Other", "column": "Region"})).unwrap()["slicer"].as_u64().unwrap(); + + s.execute("slicer.toggle", json!({"slicer": id, "value": "East"})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "A1:A3"); + assert!(!sh.is_row_hidden(1)); + assert!(sh.is_row_hidden(2)); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true)]); + + s.execute("data.reapply", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2)); + s.execute("slicer.clear", json!({"slicer": id})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(!sh.is_row_hidden(1)); + assert!(!sh.is_row_hidden(2)); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("one".into(), true), ("two".into(), true)]); +} + +#[test] +fn choices_use_the_same_custom_and_statistical_criteria_as_filtering() { + for (criterion, expected, mid_checked) in [ + (json!({"custom": {"op": ">=", "value": 20, "op2": "<", "value2": 100}}), vec!["mid", "upper"], true), + (json!({"custom": {"op": "=", "value": 10, "op2": "=", "value2": 100, "and": false}}), vec!["high", "low"], false), + (json!({"custom": {"op": "=", "value": "n?*"}}), vec!["text"], false), + (json!({"top": {"count": 2}}), vec!["high", "upper"], false), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["low", "mid"], true), + (json!({"aboveAverage": true}), vec!["high"], false), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"], true), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Amount"], ["low", 10], ["mid", 20], ["upper", 30], ["high", 100], ["blank", null], ["text", "n/a"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "A1:B7"})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}"); + // The current column's own criterion must not narrow its alternatives. + s.execute("data.filterBy", json!({"column": "A", "values": ["mid"]})).unwrap(); + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 0).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}, with the current column filtered"); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 1), + vec![("20".into(), mid_checked)], + "the numeric column's criterion sets checkboxes without excluding alternatives: {criterion}" + ); + } +} + +#[test] +fn statistical_thresholds_use_the_original_range_not_other_columns_subset() { + for (criterion, names, expected) in [ + (json!({"top": {"count": 2}}), vec!["low", "mid", "upper"], vec!["upper"]), + (json!({"top": {"count": 50, "percent": true}}), vec!["low", "mid", "upper"], vec!["upper"]), + (json!({"top": {"count": 2, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]), + (json!({"top": {"count": 50, "percent": true, "bottom": true}}), vec!["mid", "upper", "high"], vec!["mid"]), + (json!({"aboveAverage": true}), vec!["low", "mid", "upper"], vec![]), + (json!({"aboveAverage": false}), vec!["low", "mid", "upper"], vec!["low", "mid", "upper"]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Amount", "Job"], ["low", 10, "low"], ["mid", 20, "mid"], ["upper", 30, "upper"], ["high", 100, "high"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "A1:C5"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": names})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + // A and B both remain active when enumerating C. Subset statistics produce different jobs. + let actual: Vec<_> = filter_values(&s.doc().unwrap().wb, 0, 2).into_iter().map(|(v, _)| v).collect(); + assert_eq!(actual, expected, "{criterion}"); + } +} + +#[test] +fn choices_match_other_columns_but_keep_the_current_columns_unchecked_values() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "B3", "values": [ + ["Company", "Job", "Status"], + ["East", "Alpha", "Open"], + ["East", "Beta", "Open"], + ["East", "Closed job", "Closed"], + ["West", "Other company", "Open"], + ["East", null, "Open"], + ["East", "=\"\"", "Open"], + ["East", "Outside range", "Open"] + ]}), + ) + .unwrap(); + s.execute("data.filter", json!({"range": "B3:D9"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + s.execute("data.filterBy", json!({"column": "D", "values": ["Open"]})).unwrap(); + s.execute("data.filterBy", json!({"column": "C", "values": ["Alpha"]})).unwrap(); + + let choices = |s: &Session| filter_values(&s.doc().unwrap().wb, 0, 2); + let expected = + |beta: bool, blanks: bool| -> Vec<(String, bool)> { vec![("Alpha".into(), !beta), ("Beta".into(), beta), ("(Blanks)".into(), blanks)] }; + assert_eq!(choices(&s), expected(false, false)); + s.execute("data.filterBy", json!({"column": "C", "values": ["Beta"], "blanks": true})).unwrap(); + assert_eq!(choices(&s), expected(true, true)); + s.execute("data.filterBy", json!({"column": "C", "clear": true})).unwrap(); + assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]); + // Manual visibility is not a filter criterion, even when every eligible row is hidden. + s.execute("home.hideRows", json!({"rows": "4:10"})).unwrap(); + assert_eq!(choices(&s), vec![("Alpha".into(), true), ("Beta".into(), true), ("(Blanks)".into(), true)]); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); + assert!(filter_values(&s.doc().unwrap().wb, 0, 4).is_empty()); +} + +#[test] +fn a_header_only_table_has_no_data_values_or_blank_choice() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap(); + s.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap(); + s.execute("data.filter", json!({"range": "B3:C3"})).unwrap(); + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert!(sh.tables[0].header_row); + assert_eq!(sh.tables[0].range.height(), 1); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3"); + for col in [1, 2] { + assert!(filter_values(&d.wb, 0, col).is_empty(), "headers are not values or blank data rows"); + } +} + +#[test] +fn choices_respect_blank_and_formatted_value_criteria_on_other_columns() { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Name", "Value"], ["empty", null], ["formula", "=\"\""], ["spaces", " "], ["number", 12], ["other", 30] + ]}), + ) + .unwrap(); + s.execute("home.numberFormat", json!({"range": "B5:B6", "code": "0.00"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": [], "blanks": true})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("empty".into(), true), ("formula".into(), true)]); + for value in ["12", "12.00"] { + s.execute("data.filterBy", json!({"column": "B", "values": [value]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("number".into(), true)]); + } + s.execute("data.filterBy", json!({"column": "B", "values": ["absent"]})).unwrap(); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); +} + +#[test] +fn choices_match_color_criteria_and_do_not_infer_icon_matches_from_hidden_rows() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Name", "Color"], ["red", 1], ["plain", 2]]})).unwrap(); + s.execute("home.fillColor", json!({"range": "B2", "color": "#FF0000"})).unwrap(); + s.execute("home.fontColor", json!({"range": "B2", "color": "#FF0000"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B3"})).unwrap(); + for criterion in [FilterCriterion::FillColor(Color::Rgb(0xFF0000)), FilterCriterion::FontColor(Color::Rgb(0xFF0000))] { + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(1, criterion)]; + s.execute("data.reapply", json!({})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 0), vec![("red".into(), true)]); + assert_eq!(filter_selection(&s.doc().unwrap().wb, 0, 1, &[]), vec![("1".into(), true), ("2".into(), false)]); + } + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(1, FilterCriterion::Icon { set: "3Arrows".into(), id: Some(0) })]; + s.execute("data.reapply", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().is_row_hidden(2), "reapply preserves imported icon visibility"); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 0), + vec![("plain".into(), true), ("red".into(), true)], + "unsupported icon criteria cannot distinguish manual and current-column hiding" + ); +} + +#[test] +fn duplicate_color_choices_keep_any_eligible_match() { + for font in [false, true] { + for matching_cell in ["B2", "B3"] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["Company", "Color"], ["East", "Same"], ["East", "Same"], ["West", "Same"]]}), + ) + .unwrap(); + let command = if font { "home.fontColor" } else { "home.fillColor" }; + s.execute(command, json!({"range": "B4", "color": "#FF0000"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + let color = if font { FilterCriterion::FontColor(Color::Rgb(0xFF0000)) } else { FilterCriterion::FillColor(Color::Rgb(0xFF0000)) }; + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.autofilter.as_mut().unwrap().criteria = vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false }), (1, color)]; + s.execute("data.reapply", json!({})).unwrap(); + assert_eq!( + filter_values(&s.doc().unwrap().wb, 0, 1), + vec![("Same".into(), false)], + "an excluded red row cannot check an eligible choice" + ); + + s.execute(command, json!({"range": matching_cell, "color": "#FF0000"})).unwrap(); + s.execute("data.reapply", json!({})).unwrap(); + let choices = filter_values(&s.doc().unwrap().wb, 0, 1); + assert_eq!(choices, vec![("Same".into(), true)], "either eligible duplicate can supply the color match"); + let selected = filter_selection(&s.doc().unwrap().wb, 0, 1, &choices); + assert_eq!(selected, vec![("Same".into(), true)]); + let values: Vec<_> = selected.into_iter().filter_map(|(value, on)| on.then_some(value)).collect(); + s.execute("data.filterBy", json!({"column": "B", "values": values})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(!sh.is_row_hidden(CellRef::parse(matching_cell).unwrap().row), "unchanged Apply keeps the previously matching row"); + assert!(sh.is_row_hidden(3), "the other column still excludes West"); + } + } +} + +#[test] +fn querying_a_table_backed_sheet_filter_is_read_only_and_preserves_xlsx_criteria() { + for table in [false, true] { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + if table { + s.execute("insert.table", json!({"range": "B3:C6", "header": true})).unwrap(); + } + s.execute("selection.set", json!({"cell": "B3"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + let before = gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]); + assert_eq!(before, gridcraft_xlsx::write_xlsx(&s.doc().unwrap().wb).unwrap()); + let (reopened, _) = gridcraft_xlsx::read_xlsx(&before).unwrap(); + let sh = reopened.active().unwrap(); + let criteria = if table { &sh.tables[0].filter } else { &sh.autofilter.as_ref().unwrap().criteria }; + assert_eq!(criteria, &vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false })]); + assert!(!sh.is_row_hidden(3) && !sh.is_row_hidden(4) && sh.is_row_hidden(5)); + } +} + +#[test] +fn an_unrelated_tables_criteria_do_not_restrict_the_sheet_filter_choices() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + s.execute("range.setValues", json!({"range": "F3", "values": [["Company", "Job"], ["West", "Unrelated"], ["East", "Separate"]]})).unwrap(); + s.execute("insert.table", json!({"range": "F3:G5", "header": true})).unwrap(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + sh.tables[0].filter = vec![(0, FilterCriterion::Values { values: vec!["West".into()], blanks: false })]; + s.execute("selection.set", json!({"cell": "B3"})).unwrap(); + s.execute("data.filter", json!({"range": "B3:C6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Alpha".into(), true), ("Beta".into(), true)]); +} + +#[test] +fn choices_are_bounded_at_the_last_sheet_row_and_empty_for_missing_data() { + let mut s = Session::new(); + s.new_workbook(); + assert!(filter_values(&s.doc().unwrap().wb, 0, 0).is_empty()); + assert!(filter_values(&s.doc().unwrap().wb, 99, 0).is_empty()); + s.execute("range.setValues", json!({"range": "B1048574", "values": [["Company", "Job"], ["West", "Before last"], ["East", "Last East"]]})) + .unwrap(); + s.execute("data.filter", json!({"range": "B1048574:C1048576"})).unwrap(); + s.execute("data.filterBy", json!({"column": "B", "values": ["East"]})).unwrap(); + assert_eq!(filter_values(&s.doc().unwrap().wb, 0, 2), vec![("Last East".into(), true)]); +} + +#[test] +fn imported_filters_keep_choices_and_statistics_inside_the_grid() { + use gridcraft_engine::core::{MAX_ROWS, RangeRef}; + use gridcraft_engine::model::AutoFilter; + + for criterion in [FilterCriterion::Top10 { bottom: false, percent: false, count: 1 }, FilterCriterion::AboveAverage(true)] { + let mut s = Session::new(); + s.new_workbook(); + let range = RangeRef::new(CellRef::new(MAX_ROWS - 3, 0), CellRef::new(MAX_ROWS + 1, 0)); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + // Model data loaded from a malformed workbook can extend beyond the grid. + for (row, value) in [(MAX_ROWS - 2, 1.0), (MAX_ROWS - 1, 9.0), (MAX_ROWS, 100.0)] { + sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Number(value), ..Default::default() }); + } + sh.autofilter = Some(AutoFilter { range, criteria: vec![(0, criterion)] }); + let doc = s.doc().unwrap(); + let before = doc.wb.clone(); + let expected = vec![("1".into(), false), ("9".into(), true)]; + assert_eq!(filter_values(&doc.wb, 0, 0), expected, "out-of-grid data must not affect the choices or thresholds"); + assert_eq!(filter_selection(&doc.wb, 0, 0, &[]), expected); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().wb), "queries must not trim the stored workbook"); + + s.execute("data.reapply", json!({})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + assert!(sh.is_row_hidden(MAX_ROWS - 2)); + assert!(!sh.is_row_hidden(MAX_ROWS - 1), "the valid maximum still matches Top 1 and Above Average"); + assert!(sh.rows.keys().all(|row| *row < MAX_ROWS), "no hidden-row entries may be created beyond the grid"); + assert_eq!(sh.autofilter.as_ref().unwrap().range, range, "the scan bound does not rewrite imported metadata"); + assert_eq!(sh.value(CellRef::new(MAX_ROWS, 0)), Value::Number(100.0)); + } +} + +#[test] +fn merging_hidden_choices_preserves_the_active_criterion() { + for (criterion, checked) in [ + (json!({"values": ["7"], "blanks": true}), [false, true, false, false, true]), + (json!({"custom": {"op": ">=", "value": 7}}), [false, true, true, true, false]), + (json!({"top": {"count": 2}}), [false, false, true, true, false]), + (json!({"aboveAverage": true}), [false, false, false, true, false]), + (json!({"aboveAverage": false}), [true, true, true, false, false]), + ] { + let mut s = Session::new(); + s.new_workbook(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [["Region", "Amount"], ["East", 1], ["East", 9], ["West", 7], ["West", 20], ["West", null]]}), + ) + .unwrap(); + s.execute("home.numberFormat", json!({"range": "B2:B6", "code": "0.00"})).unwrap(); + s.execute("data.filter", json!({"range": "A1:B6"})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + let mut params = criterion.clone(); + params["column"] = json!("B"); + s.execute("data.filterBy", params).unwrap(); + let doc = s.doc().unwrap(); + let choices = filter_values(&doc.wb, 0, 1); + let selection = filter_selection(&doc.wb, 0, 1, &choices); + let expected: Vec<_> = + ["1.00", "7.00", "9.00", "20.00", "(Blanks)"].into_iter().zip(checked).map(|(label, on)| (label.to_string(), on)).collect(); + assert_eq!(selection, expected, "unchanged eligible choices must preserve hidden matches: {criterion}"); + let values: Vec<_> = selection.iter().filter(|(label, on)| *on && label != "(Blanks)").map(|(label, _)| label.clone()).collect(); + s.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": checked[4]})).unwrap(); + s.execute("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = s.doc().unwrap().wb.active().unwrap(); + for (row, on) in [checked[0], checked[2], checked[1], checked[3], checked[4]].into_iter().enumerate() { + assert_eq!(!sh.is_row_hidden(row as u32 + 1), on, "row after Apply and clearing the other filter: {criterion}"); + } + } +} + +#[test] +fn large_values_criteria_preserve_ascii_case_and_blank_matching() { + use gridcraft_engine::core::RangeRef; + use gridcraft_engine::model::AutoFilter; + let mut s = Session::new(); + s.new_workbook(); + let sh = Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap(); + let mut selected = Vec::new(); + for row in 1..=5_000 { + sh.set_cell(CellRef::new(row, 0), Cell { value: Value::Text(format!("item-{row}").into()), ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Number(f64::from(row)), ..Default::default() }); + selected.push(format!("ITEM-{row}")); + } + selected.extend(["ITEM-1".into(), "Ä".into()]); + for (row, value, label) in [ + (5_001, Value::Text("Ä".into()), "unicode selected"), + (5_002, Value::Text("ä".into()), "unicode excluded"), + (5_003, Value::Empty, "blank row"), + ] { + sh.set_cell(CellRef::new(row, 0), Cell { value, ..Default::default() }); + sh.set_cell(CellRef::new(row, 1), Cell { value: Value::Text(label.into()), ..Default::default() }); + } + sh.autofilter = Some(AutoFilter { + range: RangeRef::new(CellRef::new(0, 0), CellRef::new(5_003, 1)), + criteria: vec![(0, FilterCriterion::Values { values: selected, blanks: true })], + }); + let choices = filter_values(&s.doc().unwrap().wb, 0, 1); + let mut expected: Vec<_> = (1..=5_000).map(|n| (n.to_string(), true)).collect(); + expected.extend([("blank row".into(), true), ("unicode selected".into(), true)]); + assert_eq!(choices, expected); +} diff --git a/crates/engine/tests/it/chart_line_stacked100.rs b/crates/engine/tests/it/chart_line_stacked100.rs new file mode 100644 index 0000000000..68c6357c71 --- /dev/null +++ b/crates/engine/tests/it/chart_line_stacked100.rs @@ -0,0 +1,38 @@ +//! The 100% stacked line charts: `insert.chart` and `chart.set` take type `line` with subtype +//! `stacked100` or `stacked100Markers`. + +use gridcraft_engine::Session; +use gridcraft_model::ChartKind; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", "10", "30"], ["Q2", "30", "10"]]})).unwrap(); + s +} + +fn kinds(s: &Session) -> Vec { + s.doc().unwrap().wb.sheet(0).unwrap().charts.iter().map(|c| c.kind).collect() +} + +#[test] +fn insert_chart_makes_hundred_percent_stacked_lines() { + let mut s = session(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100"})).unwrap(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked100Markers"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100, ChartKind::LineStacked100Markers]); +} + +#[test] +fn chart_set_changes_a_chart_to_a_hundred_percent_stacked_line_and_back() { + let mut s = session(); + s.execute("insert.chart", json!({"range": "A1:C3", "type": "line", "subtype": "stacked"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked]); + s.execute("chart.set", json!({"type": "line", "subtype": "stacked100Markers"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]); + s.execute("chart.set", json!({"type": "line", "subtype": "stacked100"})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100]); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(kinds(&s), [ChartKind::LineStacked100Markers]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c099fa85c1..11df0e9d5e 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,8 +1,10 @@ //! The crate's integration tests, one module per file, built as one test binary. mod autofit_filter_buttons; +mod cascading_filter_values; mod cf_formula_validate; mod chart_area_stacked100; +mod chart_line_stacked100; mod chart_workbook_names; mod command_sequence_fuzz; mod cross_sheet_cut; @@ -31,6 +33,7 @@ mod sheet_name_quoting; mod sparse_clear_invalidation; mod stored_list_shape; mod structural_edit_rewrite; +mod subtotal_filter_roundtrip; mod table_resize_overlap; mod table_style_looks; mod table_total_row_last_row; diff --git a/crates/engine/tests/it/subtotal_filter_roundtrip.rs b/crates/engine/tests/it/subtotal_filter_roundtrip.rs new file mode 100644 index 0000000000..44e21e5a17 --- /dev/null +++ b/crates/engine/tests/it/subtotal_filter_roundtrip.rs @@ -0,0 +1,240 @@ +//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen. +//! +//! Excel (observed in Windows Excel 16 with synthetic workbooks) saves rows a filter hides as plain +//! `hidden="1"` rows; a hidden row counts as filtered when it lies in an AutoFilter (sheet or table) +//! that has criteria. Excel can't hold a sheet AutoFilter that overlaps a table, so GridCraft saves +//! a table's filter in the table part and never creates a sheet AutoFilter over part of a table. + +use gridcraft_core::{CellRef, Value}; +use gridcraft_engine::calc::Calc; +use gridcraft_engine::model::Workbook; +use gridcraft_engine::{Session, io}; +use serde_json::{Value as Json, json}; + +fn reopened(wb: &Workbook) -> Workbook { + let bytes = io::save_bytes(wb, "t.xlsx").unwrap(); + let (mut back, _) = io::open_bytes("t.xlsx", &bytes).unwrap(); + Calc::new().recalc_all(&mut back); + back +} + +/// Every formula value in memory against the same cell after a save and reopen. +fn assert_values_survive(wb: &Workbook) { + let back = reopened(wb); + for (a, b) in wb.sheets.iter().zip(&back.sheets) { + for (c, cell) in a.cells.iter() { + if cell.formula.is_some() { + assert_eq!(cell.value, b.value(c), "{}!{} ({:?})", a.name, c.a1(), cell.formula.as_ref().map(|f| &f.text)); + } + } + } +} + +fn session(sample: &str, steps: &[(&str, Json)]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"sample": sample})).unwrap(); + for (id, p) in steps { + // A refused step leaves the book as it was; the asserts check what survives. + let _ = s.execute(id, p.clone()); + } + s +} + +fn wb(s: &Session) -> &Workbook { + &s.doc().unwrap().wb +} + +#[test] +fn bead_repro_filter_then_replace_on_the_sales_sample() { + let s = + session("sales", &[("data.filterBy", json!({"column":"G","top":{"count":2}})), ("edit.replace", json!({"all":true,"what":"1","with":""}))]); + let sh = wb(&s).active().unwrap(); + assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range)))); + assert_values_survive(wb(&s)); +} + +#[test] +fn bead_repro_subtotal_then_filter_on_the_grades_sample() { + let s = session( + "grades", + &[ + ("home.insertColumns", json!({})), + ("data.subtotal", json!({"columns":["G"],"function":"sum","groupBy":"J"})), + ("data.filterBy", json!({"column":"B","values":["x"]})), + ], + ); + let sh = wb(&s).active().unwrap(); + assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range)))); + assert_values_survive(wb(&s)); +} + +/// A table A1:B7 (Name, Qty = 1, 10, 100...) with SUBTOTAL(9) and SUBTOTAL(109) beside it. +fn table_book() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["Name","Qty"],["a",1],["b",10],["c",100],["d",1000],["e",10000],["f",100000]]})) + .unwrap(); + s.execute("insert.table", json!({"range":"A1:B7","header":true})).unwrap(); + s.execute("cell.set", json!({"cell":"E1","input":"=SUBTOTAL(9,B2:B7)"})).unwrap(); + s.execute("cell.set", json!({"cell":"E2","input":"=SUBTOTAL(109,B2:B7)"})).unwrap(); + s.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s +} + +fn e1_e2(wb: &Workbook) -> (Value, Value) { + let sh = wb.active().unwrap(); + (sh.value(CellRef::new(0, 4)), sh.value(CellRef::new(1, 4))) +} + +#[test] +fn table_filter_keeps_subtotal_and_criteria_through_save() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); + // Like Excel, a row hidden by hand inside an active filter range is left out by SUBTOTAL 9 too. + s.execute("home.hideRows", json!({"rows":"6:6"})).unwrap(); + assert_eq!(e1_e2(wb(&s)), (Value::Number(100101.0), Value::Number(100101.0))); + assert_values_survive(wb(&s)); + let back = reopened(wb(&s)); + assert_eq!(e1_e2(&back), (Value::Number(100101.0), Value::Number(100101.0))); + let t = &back.active().unwrap().tables[0]; + assert_eq!(t.filter.len(), 1, "the criteria are saved with the table: {:?}", t.filter); +} + +#[test] +fn rows_hidden_by_hand_without_a_filter_still_count_for_subtotal_9() { + let mut s = table_book(); + s.execute("home.hideRows", json!({"rows":"3:3"})).unwrap(); + s.execute("home.hideRows", json!({"rows":"5:5"})).unwrap(); + assert_eq!(e1_e2(wb(&s)), (Value::Number(111111.0), Value::Number(110101.0))); + let back = reopened(wb(&s)); + assert_eq!(e1_e2(&back), (Value::Number(111111.0), Value::Number(110101.0))); +} + +#[test] +fn a_narrower_range_inside_a_filtered_table_is_refused_not_dropped() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + let back = reopened(wb(&s)); + let mut s = Session::new(); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile)); + s.execute("selection.set", json!({"cell":"D1"})).unwrap(); + assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err()); + assert_eq!(wb(&s).active().unwrap().tables[0].filter.len(), 1, "the table's criteria are kept"); +} + +#[test] +fn filtering_a_reopened_table_again_keeps_both_criteria() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap(); + let back = reopened(wb(&s)); + let mut s = Session::new(); + s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile)); + s.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"B","custom":{"op":">","value":"50"}})).unwrap(); + let sh = wb(&s).active().unwrap(); + assert!(sh.tables[0].filter.is_empty(), "the table's criteria moved into the live filter"); + assert_eq!(sh.autofilter.as_ref().map(|af| af.criteria.len()), Some(2)); + assert_eq!(e1_e2(wb(&s)), (Value::Number(110100.0), Value::Number(110100.0))); + assert_values_survive(wb(&s)); + assert_eq!(reopened(wb(&s)).active().unwrap().tables[0].filter.len(), 2); +} + +#[test] +fn a_sheet_filter_from_outside_a_table_leaves_the_table_out() { + // Excel: table B4:C8 with text in A1:A3, A5:A8 and B3. AutoFilter from A1 covers A1:A3, from + // A6 A5:A8, from B3 A1:B3; an explicit range over part of the table is refused. + let layout = || { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["Title"],["x"],["y"]]})).unwrap(); + s.execute("cell.set", json!({"cell":"B3","input":"z"})).unwrap(); + s.execute("range.setValues", json!({"range":"B4","values":[["Name","Qty"],["n5","v5"],["n6","v6"],["n7","v7"],["n8","v8"]]})).unwrap(); + s.execute("range.setValues", json!({"range":"A5","values":[["a5"],["a6"],["a7"],["a8"]]})).unwrap(); + s.execute("insert.table", json!({"range":"B4:C8","header":true})).unwrap(); + s + }; + for (cell, want) in [("A1", "A1:A3"), ("A6", "A5:A8"), ("B3", "A1:B3")] { + let mut s = layout(); + s.execute("selection.set", json!({"cell": cell})).unwrap(); + s.execute("data.filter", json!({})).unwrap(); + let af = wb(&s).active().unwrap().autofilter.clone(); + assert_eq!(af.map(|a| a.range.a1()), Some(want.to_string()), "from {cell}"); + } + let mut s = layout(); + assert!(s.execute("data.filter", json!({"range":"A1:C8"})).is_err()); + assert!(wb(&s).active().unwrap().autofilter.is_none()); +} + +#[test] +fn turning_a_table_filter_off_keeps_rows_another_table_still_hides() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range":"A1","values":[["K","V"],["k1",1],["k2",2],["k3",3],["k4",4],["k5",5]]})).unwrap(); + s.execute("range.setValues", json!({"range":"D1","values":[["X","Y"],["x1",1],["x2",2],["x3",3],["x4",4],["x5",5]]})).unwrap(); + s.execute("insert.table", json!({"range":"A1:B6","header":true})).unwrap(); + s.execute("insert.table", json!({"range":"D1:E6","header":true})).unwrap(); + // The second table's criteria are saved with it, so both tables hold a filter after reopening. + s.execute("selection.set", json!({"cell":"D2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap(); + let mut s2 = Session::new(); + s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s2.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s2.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap(); + s2.execute("data.filter", json!({})).unwrap(); + let sh = wb(&s2).active().unwrap(); + assert!(!sh.is_row_hidden(2), "only the first table hid row 3"); + for row in 3..6 { + assert!(sh.is_row_hidden(row), "row {} is still filtered out of the second table", row + 1); + } +} + +#[test] +fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() { + let mut s = Session::new(); + s.new_workbook(); + for (col, keys) in [("A", "k"), ("D", "x"), ("G", "z")] { + let mut values = vec![json!(["K", "V"])]; + values.extend((1..=5).map(|n| json!([format!("{keys}{n}"), n]))); + s.execute("range.setValues", json!({"range": format!("{col}1"), "values": values})).unwrap(); + } + for range in ["A1:B6", "D1:E6", "G1:H6"] { + s.execute("insert.table", json!({"range": range, "header": true})).unwrap(); + } + // Each filtered table's criteria are saved with it: reopening leaves both holding a filter. + s.execute("selection.set", json!({"cell":"D2"})).unwrap(); + s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap(); + let mut s2 = Session::new(); + s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s2.execute("selection.set", json!({"cell":"G2"})).unwrap(); + s2.execute("data.filterBy", json!({"column":"G","values":["z1","z3"]})).unwrap(); + let mut s3 = Session::new(); + s3.add_document(gridcraft_engine::DocState::new(reopened(wb(&s2)), None, "t".into(), gridcraft_engine::Trust::FromFile)); + s3.execute("selection.set", json!({"cell":"A2"})).unwrap(); + s3.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap(); + s3.execute("data.filter", json!({})).unwrap(); + let sh = wb(&s3).active().unwrap(); + assert!(!sh.is_row_hidden(1)); + for row in 2..6 { + assert!(sh.is_row_hidden(row), "row {} is excluded by one of the two other tables", row + 1); + } +} + +#[test] +fn filtering_a_table_whose_buttons_were_turned_off_turns_them_back_on() { + let mut s = table_book(); + s.execute("data.filter", json!({})).unwrap(); + assert!(!wb(&s).active().unwrap().tables[0].filter_button); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + assert!(wb(&s).active().unwrap().tables[0].filter_button); + let back = reopened(wb(&s)); + assert_eq!(back.active().unwrap().tables[0].filter.len(), 1, "the criteria are saved with the table"); +} + +#[test] +fn a_partial_range_inside_the_active_table_is_refused_not_a_toggle() { + let mut s = table_book(); + s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap(); + assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err()); + let sh = wb(&s).active().unwrap(); + assert!(sh.tables[0].filter_button && sh.autofilter.is_some(), "the filter is untouched"); +} diff --git a/crates/functions/src/financial/tests.rs b/crates/functions/src/financial/tests.rs index 54934eb7d1..1d0578d89a 100644 --- a/crates/functions/src/financial/tests.rs +++ b/crates/functions/src/financial/tests.rs @@ -33,6 +33,98 @@ fn tvm() { is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num); } +/// XIRR of `values` on `dates`, with an optional guess, as a number or an error. +fn xirr_of(values: &[f64], dates: &[f64], guess: Option) -> Value { + let mut args = vec![rf(col(values)), rf(col(dates))]; + args.extend(guess.map(n)); + ev("XIRR", args) +} + +#[track_caller] +fn xirr_is(values: &[f64], dates: &[f64], guess: Option, expected: f64) { + assert_eq!(xirr_of(values, dates, guess), Value::Number(expected), "XIRR{values:?} {dates:?} {guess:?}"); +} + +fn irr_of(values: &[f64], guess: Option) -> Value { + let mut args = vec![rf(col(values))]; + args.extend(guess.map(n)); + ev("IRR", args) +} + +/// Expected values observed in Excel 365 with these synthetic inputs. XIRR matches bit for +/// bit: its answer is a bisection midpoint, about 1e-8 from the exact root. +#[test] +fn xirr_follows_excel_bisection() { + let (b, y1, y2) = (43831.0, 44196.0, 44561.0); + // Root 10%: the bracket and so the answer depend on the guess, not on the flows. + xirr_is(&[-100.0, 110.0], &[b, y1], None, 0.099_999_994_039_535_52); + xirr_is(&[-100.0, 121.0], &[b, y2], None, 0.099_999_994_039_535_52); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.0), 0.099_999_995_117_187_5); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.25), 0.099_999_997_764_825_82); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(5.0), 0.100_000_002_421_438_7); + xirr_is(&[-100.0, 60.0, 60.0], &[b, y1, y2], None, 0.130_662_387_609_481_82); + xirr_is(&[-100.0, 150.0], &[b, y1], None, 0.499_999_994_039_535_54); + // Fractional dates are truncated. + xirr_is(&[-100.0, 60.0, 60.0], &[b, y1 + 0.9, y2 + 0.2], None, 0.130_662_387_609_481_82); + // Negative roots: minus the guess, then halfway to -100% each step. + xirr_is(&[-100.0, 73.0], &[b, y1], None, -0.269_999_996_572_733); + xirr_is(&[-100.0, 13.0], &[b, y1], None, -0.870_000_001_043_081_1); + xirr_is(&[-100.0, 1e-29], &[b, 45658.0], None, -0.999_999_359_104_708); + // A guess of 100% or more steps through rates below -100% (whole years only). + xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(2.0), -1.653_112_880_885_601); + xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(-0.3), -0.846_887_112_781_405_5); + is_err(xirr_of(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(1.0)), CellError::Num); + // One-day spans. + xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23); + xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34); + xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5); + // A leading zero cash flow scales the residual to 0: Excel halves the guess to a tiny + // number whatever the flows (observed), and a negative guess is #NUM!. + let z = [0.0, -100.0, 110.0]; + let zd = [b, y1, y2]; + xirr_is(&z, &zd, None, 2.980_232_238_769_531_4e-9); + xirr_is(&z, &zd, Some(0.2), 2.980_232_238_769_531_4e-9); + xirr_is(&z, &zd, Some(0.0), 4.882_812_5e-9); + xirr_is(&z, &zd, Some(5.0), 4.656_612_873_077_392_6e-9); + xirr_is(&[0.0, -100.0, 50.0], &zd, None, 2.980_232_238_769_531_4e-9); + is_err(xirr_of(&z, &zd, Some(-0.5)), CellError::Num); + // Dates before the first are allowed (time runs from the first date); in the second + // case the search finds no sign change. + xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b - 365.0, y2], None), CellError::Num); + // A negative guess never reaches a positive root; a guess at or below -1 is #NUM!. + is_err(xirr_of(&[-100.0, 110.0], &[b, y1], Some(-0.1)), CellError::Num); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, y1, y2], Some(-1.0)), CellError::Num); + // Two roots with the guess outside them; all dates the same. + is_err(xirr_of(&[-100.0, 300.0, -210.0], &[b, y1, y2], None), CellError::Num); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b, b], None), CellError::Num); +} + +/// IRR follows Excel's answers to about 1e-12 and its #NUM! cases. +#[test] +fn irr_follows_excel() { + assert_eq!(irr_of(&[-100.0, 110.0], None), Value::Number(0.100_000_000_000_000_09)); + close_tol(irr_of(&[-0.0001, 0.0, 0.0, 0.0, 100.0], None), 30.622_776_600_497_09, 1e-9); + let mut late = vec![-100.0]; + late.extend([0.0; 19]); + late.push(1e-5); + is_err(irr_of(&late, None), CellError::Num); + // ...but from a guess just above -100% Newton creeps down to the root. + let mut late18 = vec![-100.0]; + late18.extend([0.0; 18]); + late18.push(1e-5); + close_tol(irr_of(&late18, Some(-0.99)), -0.571_866_760_128_087_4, 1e-9); + close_tol(irr_of(&[-100.0, 300.0, -210.0], Some(0.9)), 0.887_298_334_620_741_5, 1e-12); + is_err(irr_of(&[-100.0, 60.0, 60.0], Some(-1.0)), CellError::Value); + close_tol(irr_of(&[-100.0, 60.0, 60.0], Some(-0.999_999)), 0.130_662_386_291_807_5, 1e-12); + // A small Newton step alone is not convergence when cancellation leaves a large scaled residual. + close_tol(irr_of(&[-1e-9, 1.0, -1e8], None), 112_701_664.379_258_29, 1e-8); + // An exact repeated root at the starting guess (zero slope) is the answer, as in Excel. + assert_eq!(irr_of(&[1.0, -2.0, 1.0], Some(0.0)), Value::Number(0.0)); + assert_eq!(irr_of(&[-1.0, 3.0, -3.0, 1.0], Some(0.0)), Value::Number(0.0)); + close_tol(irr_of(&[1.0, -2.0, 1.0], None), 1.09e-7, 1e-7); +} + /// RATE with the given arguments, as a number or an error. fn rate_of(args: &[f64]) -> Value { ev("RATE", args.iter().map(|x| n(*x)).collect()) @@ -145,6 +237,42 @@ fn pmt_edge_cases_follow_excel() { close_tol(ev("PMT", vec![n(0.05), n(10.0), n(100.0), n(50.0), n(1.0)]), -16.119701185541427, 1e-15); } +#[test] +fn blank_cash_flows_follow_excel_for_xirr_and_xnpv() { + // Each result below was observed in Excel on a synthetic workbook: five rows, the first + // four -10000, 2750, 4250, 3250 on 39448, 39508, 39751, 39859; the last row varies. + let dates = col(&[39448.0, 39508.0, 39751.0, 39859.0, 39904.0]); + let gap = arr([39448.0, 39508.0, 39751.0, 39859.0].iter().map(|x| vec![nv(*x)]).chain([vec![Value::Empty]]).collect()); + let flows = |last: Value| arr([-10000.0, 2750.0, 4250.0, 3250.0].iter().map(|x| vec![nv(*x)]).chain([vec![last]]).collect()); + let rate = 0.033791377645041754; + // XIRR: a blank value counts as 0 and a blank date is ignored when its value is blank or 0. The answer is a bisection midpoint, within about 1e-8 of the exact rate. + close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(dates.clone())]), rate, 1e-7); + close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(dates.clone())]), rate, 1e-7); + close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(gap.clone())]), rate, 1e-7); + close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(gap.clone())]), rate, 1e-7); + is_err(ev("XIRR", vec![rf(flows(nv(2750.0))), rf(gap.clone())]), CellError::Num); + is_err(ev("XIRR", vec![rf(flows(tv("-"))), rf(dates.clone())]), CellError::Value); + // XNPV is strict: a blank value is #NUM! where 0 is a number. + close_tol(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(dates.clone())]), -382.66, 1e-2); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates.clone())]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(tv("-"))), rf(dates.clone())]), CellError::Num); + // In the first row a blank value or date is #VALUE! for XNPV; XIRR reads a blank date there as day 0. + let first_row = |value: Value, date: Value| { + let cells = |x: Value, rest: [f64; 4]| arr(std::iter::once(vec![x]).chain(rest.iter().map(|y| vec![nv(*y)])).collect()); + (rf(cells(value, [2750.0, 4250.0, 3250.0, 500.0])), rf(cells(date, [39508.0, 39751.0, 39859.0, 39904.0]))) + }; + let (v0, d0) = first_row(Value::Empty, nv(39448.0)); + is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value); + let (v0, d0) = first_row(nv(0.0), Value::Empty); + is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value); + let (v0, d0) = first_row(nv(-10000.0), Value::Empty); + is_err(ev("XNPV", vec![n(0.09), v0.clone(), d0.clone()]), CellError::Value); + close_tol(ev("XIRR", vec![v0, d0]), 0.000_664_654_374_122_619_6, 1e-7); +} + #[test] fn cash_flows() { close_tol(ev("NPV", vec![n(0.1), n(-10000.0), n(3000.0), n(4200.0), n(6800.0)]), 1188.443412, 1e-9); diff --git a/crates/functions/src/financial/tvm.rs b/crates/functions/src/financial/tvm.rs index d8aa2f9977..16e1bd71db 100644 --- a/crates/functions/src/financial/tvm.rs +++ b/crates/functions/src/financial/tvm.rs @@ -152,72 +152,6 @@ pub(super) fn cumprinc(a: &[Arg], _c: &mut dyn Ctx) -> R { cumulative(a, true) } -/// Newton iteration with a numeric derivative, keeping the rate above -1. -fn newton(f: impl Fn(f64) -> f64, guess: f64) -> Option { - let mut x = guess; - for _ in 0..200 { - let y = f(x); - if !y.is_finite() { - return None; - } - let h = 1e-6 * x.abs().max(1e-3); - let d = (f(x + h) - f(x - h)) / (2.0 * h); - if d == 0.0 || !d.is_finite() { - return None; - } - let mut nx = x - y / d; - if nx <= -1.0 { - nx = (x - 1.0) / 2.0; - if nx <= -1.0 { - nx = -0.999_999_999; - } - } - if (nx - x).abs() < 1e-12 * nx.abs().max(1.0) { - return Some(nx); - } - x = nx; - } - None -} - -/// Tries Newton from the guess and a few fallback starting points; then bisection over a -/// bracket if one can be found. -fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R { - let check = |r: f64| f(r).is_finite() && f(r).abs() < 1e-7 * (1.0 + f(guess).abs().min(1e12)); - for g in [guess, 0.1, 0.01, 0.5, -0.5, 1.0, 0.001, 5.0, -0.9, 10.0] { - if let Some(r) = newton(&f, g) - && r > -1.0 - && check(r) - { - return Ok(r); - } - } - // Scan for a sign change and bisect. - let grid: Vec = [-0.999_999, -0.99, -0.9, -0.5, -0.2, 0.0, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0, 1000.0].to_vec(); - for w in grid.windows(2) { - let (mut lo, mut hi) = match w { - [a, b] => (*a, *b), - _ => continue, - }; - let (flo, fhi) = (f(lo), f(hi)); - if !(flo.is_finite() && fhi.is_finite()) || flo * fhi > 0.0 { - continue; - } - let lo_neg = flo < 0.0; - for _ in 0..200 { - let mid = 0.5 * (lo + hi); - let fm = f(mid); - if (fm < 0.0) == lo_neg { - lo = mid; - } else { - hi = mid; - } - } - return Ok(0.5 * (lo + hi)); - } - Err(CellError::Num) -} - /// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus /// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to /// judge how close to zero the first can get in floating point. @@ -314,8 +248,15 @@ pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { num_val(sum) } -/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. -fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { +/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. XNPV rejects a +/// date before the first; XIRR (`lenient`) takes it, as Excel does. +/// +/// Blank cells follow what Excel returns (observed on synthetic workbooks). With `lenient` (XIRR) +/// a blank value counts as 0 and a blank date is ignored when its value is blank or 0; a nonzero +/// value without a date is `#NUM!`, except in the first row, where the date is read as day 0. +/// XNPV is strict: a blank (or text) value or a blank date is `#NUM!`, except in the first row, +/// where it is `#VALUE!`. +fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec, Vec)> { let va = as_array(values); let da = as_array(dates); if va.data.len() != da.data.len() { @@ -323,21 +264,33 @@ fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { } let mut v = Vec::with_capacity(va.data.len()); let mut d = Vec::with_capacity(da.data.len()); - for (x, y) in va.data.iter().zip(da.data.iter()) { - match x { - Value::Number(n) => v.push(*n), + for (i, (x, y)) in va.data.iter().zip(da.data.iter()).enumerate() { + // Excel (XNPV): a blank or text value or a blank date is #NUM!, except in the first row, + // where it is #VALUE!. + let strict_err = if i == 0 { CellError::Value } else { CellError::Num }; + let value = match x { + Value::Number(n) => *n, + Value::Empty if lenient => 0.0, + Value::Empty => return Err(strict_err), Value::Error(e) => return Err(*e), - _ => return Err(CellError::Value), - } + _ if lenient => return Err(CellError::Value), + _ => return Err(strict_err), + }; match y { Value::Number(n) => d.push(n.trunc()), Value::Error(e) => return Err(*e), Value::Text(_) => d.push(y.to_number()?.trunc()), + Value::Empty if !lenient => return Err(strict_err), + // XIRR skips a blank date next to a 0 flow and reads one in the first row as day 0. + Value::Empty if value == 0.0 => continue, + Value::Empty if i == 0 => d.push(0.0), + Value::Empty => return Err(CellError::Num), _ => return Err(CellError::Value), } + v.push(value); } let d0 = *d.first().ok_or(CellError::Num)?; - if d.iter().any(|&x| x < d0 || x < 0.0) { + if d.iter().any(|&x| (x < d0 && !lenient) || x < 0.0) { return Err(CellError::Num); } Ok((v, d)) @@ -353,35 +306,219 @@ pub(super) fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R { if rate <= -1.0 { return Err(CellError::Num); } - let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value, false)?; num_val(xnpv_calc(rate, &v, &d)) } +/// Excel's XIRR solver, reconstructed by observing Excel with synthetic inputs (not from its +/// code; its documentation says only "iteration", 100 tries and 0.000001 percent). It looks +/// only at the sign of XNPV until the end, so its answer is the root to about 1e-8, not to the +/// last digit: +/// +/// - Bracket the root from the guess (0 counts as 1e-5): double the rate while XNPV keeps the +/// sign it has at the guess and that sign differs from the first nonzero value (the root is higher). +/// Otherwise the root is lower: bisect towards 0 if XNPV changes sign there; halve the rate +/// towards 0 if XNPV is larger in size at 0 than at the guess; otherwise try minus the guess +/// and then step halfway to -100% each time. A negative guess only moves towards 0 (root +/// higher) or towards -100% (root lower). +/// - Bisect the bracket, taking the midpoint from the upper end, until half the bracket is +/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first nonzero value|; return that +/// midpoint. A zero XNPV counts as the upper side. +/// - Halving towards 0 that gets within that tolerance of 0 without a sign change goes on with +/// the negative side; at most 100 XNPV evaluations in all; a rate of -100% or an XNPV that +/// can't be computed (a negative base for fractional years) is #NUM!. +struct XirrSolver<'a> { + values: &'a [f64], + /// First nonzero value: sets the search direction and the residual scale. + first: f64, + years: Vec, + evals: usize, + /// XNPV must be within this of 0 at the answer. + residual: f64, +} + +impl XirrSolver<'_> { + const MAX_EVALS: usize = 100; + + fn tol(rate: f64) -> f64 { + 1e-8 * (rate.abs() + 0.5) + } + + fn same_sign(a: f64, b: f64) -> bool { + a * b > 0.0 + } + + fn f(&mut self, rate: f64) -> R { + self.evals += 1; + if self.evals > Self::MAX_EVALS { + return Err(CellError::Num); + } + let base = 1.0 + rate; + if base == 0.0 { + return Err(CellError::Num); + } + let mut sum = 0.0; + for (x, t) in self.values.iter().zip(&self.years) { + sum += x / base.powf(*t); + } + if sum.is_finite() { Ok(sum) } else { Err(CellError::Num) } + } + + fn solve(&mut self, guess: f64) -> R { + let g = if guess == 0.0 { 1e-5 } else { guess }; + let fg = self.f(g)?; + let higher = fg * self.first < 0.0; + if g > 0.0 { + if higher { + return self.double(g, fg); + } + let f0 = self.f(0.0)?; + if !Self::same_sign(f0, fg) { + return self.bisect(g, fg, 0.0, f0); + } + if f0.abs() > fg.abs() { + return self.halve(g, fg, g, fg); + } + return self.negative_side(g, fg); + } + if higher { self.halve(g, fg, g, fg) } else { self.towards_minus_one(g, fg) } + } + + fn double(&mut self, mut x: f64, mut fx: f64) -> R { + loop { + let next = 2.0 * x; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + (x, fx) = (next, fnext); + } + } + + fn halve(&mut self, mut x: f64, mut fx: f64, g: f64, fg: f64) -> R { + loop { + let step = -x / 2.0; + let next = x + step; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + if step.abs() < Self::tol(next) { + if next < 0.0 { + return Err(CellError::Num); + } + return self.negative_side(g, fg); + } + (x, fx) = (next, fnext); + } + } + + fn negative_side(&mut self, g: f64, fg: f64) -> R { + let fm = self.f(-g)?; + if !Self::same_sign(fm, fg) { + return self.bisect(g, fg, -g, fm); + } + self.towards_minus_one(-g, fm) + } + + fn towards_minus_one(&mut self, mut x: f64, mut fx: f64) -> R { + loop { + let next = x + (-1.0 - x) / 2.0; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + (x, fx) = (next, fnext); + } + } + + fn bisect(&mut self, a: f64, fa: f64, b: f64, fb: f64) -> R { + let (mut lo, mut flo, mut hi) = if a < b { (a, fa, b) } else { (b, fb, a) }; + loop { + let mid = hi - (hi - lo) / 2.0; + let fm = self.f(mid)?; + if (hi - lo) / 2.0 < Self::tol(mid) && fm.abs() < self.residual { + return Ok(mid); + } + if Self::same_sign(fm, flo) { + (lo, flo) = (mid, fm); + } else { + hi = mid; + } + } + } +} + pub(super) fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { - let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?; let guess = opt_num(a, 2, 0.1)?; - if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { + if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } - num_val(solve_rate(|r| xnpv_calc(r, &v, &d), guess)?) + if v.first() == Some(&0.0) { + // Excel with a 0 (or blank) first flow: the residual scale is 0, so the search just + // halves the guess towards 0 until the step is under the tolerance; a negative guess is #NUM!. + if guess < 0.0 { + return Err(CellError::Num); + } + let mut x = if guess == 0.0 { 1e-5 } else { guess }; + // Bounded: a huge guess halves to the tolerance within about 1100 steps. + for _ in 0..1100 { + if x / 2.0 < XirrSolver::tol(x / 2.0) { + break; + } + x /= 2.0; + } + return num_val(x / 2.0); + } + let d0 = d.first().copied().unwrap_or(0.0); + let first = v.iter().copied().find(|x| *x != 0.0).unwrap_or(0.0); + let mut solver = XirrSolver { values: &v, first, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; + num_val(solver.solve(guess)?) +} + +/// Excel's IRR solver, approximated from observation (Excel's documentation says 20 tries and +/// 0.00001 percent): Newton's method on the discount factor 1/(1+rate), where the cash flows +/// are a polynomial, from 1/(1+guess) until a step moves less than 1e-8, for at most 100 steps. +/// Excel's answers agree with it to about 1e-12 on ordinary flows (the last digits differ) and +/// on which flows have no answer, apart from a few far from any guess. +fn irr_solve(v: &[f64], guess: f64) -> R { + let mut x = 1.0 / (1.0 + guess); + for _ in 0..100 { + let (mut s, mut ds, mut scale) = (0.0, 0.0, 0.0); + for c in v.iter().rev() { + ds = ds * x + s; + s = s * x + c; + scale = scale * x.abs() + c.abs(); + } + if ds == 0.0 { + // An exact root with a zero slope (a repeated root such as {1,-2,1} at guess 0) is + // still the answer: Excel returns 0 there. + return if s == 0.0 && x > 0.0 { Ok(1.0 / x - 1.0) } else { Err(CellError::Num) }; + } + let next = x - s / ds; + if !next.is_finite() { + return Err(CellError::Num); + } + if (next - x).abs() < 1e-8 && scale.is_finite() && s.abs() <= 1e-12 * scale { + return if next > 0.0 { Ok(1.0 / next - 1.0) } else { Err(CellError::Num) }; + } + x = next; + } + Err(CellError::Num) } pub(super) fn irr(a: &[Arg], _c: &mut dyn Ctx) -> R { let v = array_numbers(&a.first().ok_or(CellError::Value)?.value)?; let guess = opt_num(a, 1, 0.1)?; + // Excel: a guess at or below -100% is #VALUE! for IRR (#NUM! for XIRR). + if guess <= -1.0 { + return Err(CellError::Value); + } if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } - let f = |r: f64| { - let mut s = 0.0; - let mut d = 1.0; - for x in &v { - s += x / d; - d *= 1.0 + r; - } - s - }; - num_val(solve_rate(f, guess)?) + num_val(irr_solve(&v, guess)?) } pub(super) fn mirr(a: &[Arg], _c: &mut dyn Ctx) -> R { diff --git a/crates/functions/src/text.rs b/crates/functions/src/text.rs index 53186bb0e8..aca065c4d4 100644 --- a/crates/functions/src/text.rs +++ b/crates/functions/src/text.rs @@ -22,17 +22,17 @@ fn chars(s: &str) -> Vec { } fn check_len(s: String) -> R { - if s.len() > MAX_TEXT && s.chars().count() > MAX_TEXT { + if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT { return Err(CellError::Value); } text_val(s) } /// Pushes `piece` onto `out`, failing once the result exceeds the cell limit. -fn push_capped(out: &mut String, piece: &str) -> R<()> { +fn push_capped(out: &mut String, piece: &str, over: CellError) -> R<()> { // Checked before copying, so one oversized piece is refused without being appended. if out.len().saturating_add(piece.len()) > MAX_TEXT * 4 { - return Err(CellError::Value); + return Err(over); } out.push_str(piece); Ok(()) @@ -47,22 +47,35 @@ fn piece(v: &Value) -> R> { } } +/// CONCATENATE cuts at the cell limit like `&`; CONCAT and TEXTJOIN give `#CALC!` past it. fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { - push_capped(&mut out, &piece(&scalar(x))?)?; + // Past the budget, later arguments are still converted so their errors propagate. + let v = scalar(x); + let piece = piece(&v)?; + if out.len() <= MAX_TEXT * 4 { + out.push_str(&piece); + } } - check_len(out) + text_val(gridcraft_core::cap_text(out)) +} + +fn check_calc(s: String) -> R { + if s.len() > MAX_TEXT && s.encode_utf16().count() > MAX_TEXT { + return Err(CellError::Calc); + } + text_val(s) } fn concat(a: &[Arg], _c: &mut dyn Ctx) -> R { let mut out = String::new(); for x in a { for v in as_array(&x.value).iter() { - push_capped(&mut out, &piece(v)?)?; + push_capped(&mut out, &piece(v)?, CellError::Calc)?; } } - check_len(out) + check_calc(out) } /// The error `v.to_text()` would give, found without building any text. @@ -98,12 +111,12 @@ fn textjoin(a: &[Arg], _c: &mut dyn Ctx) -> R { && !delims.data.is_empty() && let Some(d) = delims.data.get((joined - 1) % delims.data.len()) { - push_capped(&mut out, &piece(d)?)?; + push_capped(&mut out, &piece(d)?, CellError::Calc)?; } - push_capped(&mut out, &s)?; + push_capped(&mut out, &s, CellError::Calc)?; joined += 1; } - check_len(out) + check_calc(out) } fn count_arg(a: &[Arg], i: usize, default: f64) -> R { @@ -252,7 +265,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R { return Err(CellError::Value); } let n = n.trunc(); - let total = s.chars().count() as f64 * n; + let total = s.encode_utf16().count() as f64 * n; if total > MAX_TEXT as f64 { return Err(CellError::Value); } @@ -772,7 +785,7 @@ fn arraytotext(a: &[Arg], _c: &mut dyn Ctx) -> R { } else if c > 0 { out.push_str(if strict { "," } else { ", " }); } - push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict))?; + push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict), CellError::Value)?; } } if strict { @@ -1207,20 +1220,37 @@ mod tests { is_text(ev("TEXTJOIN", vec![t("-"), b(false), av(arr(vec![vec![tv("a"), tv(""), tv("b")]]))]), "a--b"); is_text(ev("TEXTJOIN", vec![av(row_t(&[",", ";"])), b(true), t("a"), t("b"), t("c")]), "a,b;c"); is_err(ev("CONCAT", vec![t("a"), e(CellError::NA)]), CellError::NA); + // Past 32,767 characters: CONCAT and TEXTJOIN are #CALC!, CONCATENATE cuts like `&` + // (checked in Excel: LEN(...) is #CALC!, #CALC! and 32767). + let x = || t(&"x".repeat(20_000)); + is_err(ev("CONCAT", vec![x(), x()]), CellError::Calc); + is_err(ev("TEXTJOIN", vec![t(","), b(false), x(), x()]), CellError::Calc); + assert_eq!(ev("CONCATENATE", vec![x(), x()]), Value::text("x".repeat(32_767))); + assert_eq!(ev("CONCAT", vec![x()]), Value::text("x".repeat(20_000))); + // An error after the cut still propagates. + let big = || t(&"x".repeat(32_767)); + is_err(ev("CONCATENATE", vec![big(), big(), big(), big(), big(), e(CellError::NA)]), CellError::NA); + let emoji = "😀"; + is_err(ev("CONCAT", vec![t(&emoji.repeat(16_384))]), CellError::Calc); + is_err(ev("TEXTJOIN", vec![t(""), b(false), t(&emoji.repeat(16_384))]), CellError::Calc); + assert_eq!(ev("CONCATENATE", vec![t(&emoji.repeat(16_384))]), Value::text(emoji.repeat(16_383))); + is_err(ev("REPT", vec![t(emoji), n(16_384.0)]), CellError::Value); + assert_eq!(ev("REPT", vec![t(emoji), n(16_383.0)]), Value::text(emoji.repeat(16_383))); // Lifting: CONCATENATE over an array. assert_eq!(rows_of(&ev("CONCATENATE", vec![av(row_t(&["a", "b"])), t("x")])), vec![vec![tv("ax"), tv("bx")]]); } /// Security: TEXTJOIN builds its result piece by piece and stops at the text cap, rather /// than first copying every input (100,000 references to one 32,767-character text were - /// 3 GB of copies). Errors among the inputs still win, in argument order. + /// 3 GB of copies), giving `#CALC!` there as past the cell limit. Errors among the inputs still + /// win, in argument order. #[test] fn textjoin_stops_at_the_text_cap() { use gridcraft_core::Array; let long = tv(&"x".repeat(32_767)); let many = || av(Array::filled(100_000, 1, long.clone()).into()); - is_err(ev("TEXTJOIN", vec![t(","), b(true), many()]), CellError::Value); - is_err(ev("TEXTJOIN", vec![av(Array::filled(1, 100_000, long.clone()).into()), b(false), t("a"), t("b")]), CellError::Value); + is_err(ev("TEXTJOIN", vec![t(","), b(true), many()]), CellError::Calc); + is_err(ev("TEXTJOIN", vec![av(Array::filled(1, 100_000, long.clone()).into()), b(false), t("a"), t("b")]), CellError::Calc); is_err(ev("TEXTJOIN", vec![t(","), b(true), many(), e(CellError::Div0)]), CellError::Div0); is_err(ev("TEXTJOIN", vec![av(arr(vec![vec![tv(","), Value::Error(CellError::NA)]])), b(true), t("a")]), CellError::NA); // Delimiters cycle and are converted only where used. diff --git a/crates/functions/src/util.rs b/crates/functions/src/util.rs index 4e7853d2c1..d72cdf2fb5 100644 --- a/crates/functions/src/util.rs +++ b/crates/functions/src/util.rs @@ -11,7 +11,7 @@ pub(crate) type R = Result; /// Largest array a function may build. pub(crate) const MAX_CELLS: usize = 10_000_000; -/// Longest text a cell can hold. +/// Longest text a cell can hold, in UTF-16 code units. pub(crate) const MAX_TEXT: usize = 32_767; /// Scalar-position lifting tables. @@ -20,11 +20,11 @@ pub(crate) const S: &[bool] = &[true]; pub(crate) const A: &[bool] = &[false]; /// Turns an implementation result into a cell value: errors become error values, non-finite -/// numbers become `#NUM!`, text longer than 32,767 characters becomes `#VALUE!`. +/// numbers become `#NUM!`, text longer than 32,767 UTF-16 code units becomes `#VALUE!`. pub(crate) fn finish(r: R) -> Value { match r { Ok(Value::Number(n)) => Value::number(n), - Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.chars().count() > MAX_TEXT => Value::Error(CellError::Value), + Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.encode_utf16().count() > MAX_TEXT => Value::Error(CellError::Value), Ok(v) => v, Err(e) => Value::Error(e), } diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 87f7fea5d3..f61687524d 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -288,7 +288,7 @@ fn base_tool_definitions() -> Vec { json!({ "range": string("Source data range including headers, e.g. \"A1:C6\""), "type": enumeration("Chart type", CHART_TYPES), - "subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers"]), + "subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers", "stacked100Markers"]), "title": string("Chart title"), "at": string("Top-left anchor cell (default: right of the data)"), }), diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index d658ae739e..b3352fed70 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -15,6 +15,7 @@ test-support = [] [dependencies] gridcraft-core = { workspace = true } +sha1 = { workspace = true } sha2 = { workspace = true } gridcraft-formula = { workspace = true } gridcraft-math = { workspace = true } diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index 3cefcbe248..6de1ac50cf 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -501,6 +501,8 @@ pub enum ChartKind { Line, LineMarkers, LineStacked, + LineStacked100, + LineStacked100Markers, Pie, Doughnut, Area, @@ -683,10 +685,17 @@ pub struct Chart { } /// Whether a series of kind `b` can be drawn in a chart of kind `a` without making it a combo: -/// the same kind, or a line with or without markers, or a scatter with or without lines. +/// the same kind, or a line or 100% stacked line with or without markers, or a scatter with or +/// without lines. pub fn same_family(a: ChartKind, b: ChartKind) -> bool { use ChartKind::*; - a == b || matches!((a, b), (Line | LineMarkers, Line | LineMarkers) | (Scatter | ScatterLines, Scatter | ScatterLines)) + a == b + || matches!( + (a, b), + (Line | LineMarkers, Line | LineMarkers) + | (LineStacked100 | LineStacked100Markers, LineStacked100 | LineStacked100Markers) + | (Scatter | ScatterLines, Scatter | ScatterLines) + ) } /// The kind a combo chart's series `i` with its own kind `own` is drawn as. @@ -730,20 +739,34 @@ fn grouped(k: ChartKind) -> Option { use ChartKind::*; match k { ColumnClustered | ColumnStacked | ColumnStacked100 => Some(Grouped::Column), - Line | LineMarkers | LineStacked => Some(Grouped::Line), + Line | LineMarkers | LineStacked | LineStacked100 | LineStacked100Markers => Some(Grouped::Line), Area | AreaStacked | AreaStacked100 => Some(Grouped::Area), _ => None, } } /// Kind `k` drawn in the grouping of `first`, the first series of its type on its axes: columns -/// and areas take its kind; a line is stacked when it is, and unstacked (keeping its own -/// markers) when it isn't. +/// and areas take its kind; a line is stacked when it is, stacked to 100% (keeping its own +/// markers) when it is, and unstacked (keeping its own markers) when it isn't. fn regroup(k: ChartKind, first: ChartKind) -> ChartKind { + use ChartKind::*; + let marked = matches!(k, LineMarkers | LineStacked100Markers); match (grouped(k), first) { - (Some(Grouped::Line), ChartKind::LineStacked) => ChartKind::LineStacked, - (Some(Grouped::Line), _) if k == ChartKind::LineStacked => ChartKind::Line, - (Some(Grouped::Line), _) => k, + (Some(Grouped::Line), LineStacked) => LineStacked, + (Some(Grouped::Line), LineStacked100 | LineStacked100Markers) => { + if marked { + LineStacked100Markers + } else { + LineStacked100 + } + } + (Some(Grouped::Line), _) => { + if marked { + LineMarkers + } else { + Line + } + } _ => first, } } @@ -845,6 +868,8 @@ impl Chart { | ChartKind::Line | ChartKind::LineMarkers | ChartKind::LineStacked + | ChartKind::LineStacked100 + | ChartKind::LineStacked100Markers | ChartKind::Area | ChartKind::AreaStacked | ChartKind::AreaStacked100 @@ -1401,6 +1426,10 @@ mod series_kind_tests { assert_eq!(drawn(&chart(Line, &[None, Some(LineMarkers), Some(Area)])), vec![Line, LineMarkers, Line]); assert_eq!(drawn(&chart(ScatterLines, &[Some(Scatter), Some(Line)])), vec![Scatter, ScatterLines]); assert_eq!(drawn(&chart(ColumnClustered, &[Some(Line)])), vec![ColumnClustered]); + assert_eq!( + drawn(&chart(LineStacked100Markers, &[Some(LineStacked100), None, Some(LineMarkers)])), + vec![LineStacked100, LineStacked100Markers, LineStacked100Markers] + ); } #[test] @@ -1415,6 +1444,15 @@ mod series_kind_tests { // An unstacked line keeps its own markers; a stacked one after it is unstacked. let c = chart(Combo, &[Some(Line), Some(LineMarkers), Some(LineStacked)]); assert_eq!(drawn(&c), vec![Line, LineMarkers, Line]); + // Lines after a 100% stacked one are stacked to 100%, each keeping its own markers; a + // 100% stacked line after a stacked one is stacked, and after an unstacked one unstacked. + let c = chart(Combo, &[Some(LineStacked100), Some(LineMarkers), Some(LineStacked), Some(LineStacked100Markers)]); + assert_eq!(drawn(&c), vec![LineStacked100, LineStacked100Markers, LineStacked100, LineStacked100Markers]); + assert_eq!(c.series_kinds(), drawn(&c)); + let c = chart(Combo, &[Some(LineStacked), Some(LineStacked100Markers)]); + assert_eq!(drawn(&c), vec![LineStacked, LineStacked]); + let c = chart(Combo, &[Some(LineMarkers), Some(LineStacked100), Some(LineStacked100Markers)]); + assert_eq!(drawn(&c), vec![LineMarkers, Line, LineMarkers]); // Each pair of axes has its own first. let mut c = chart(Combo, &[Some(ColumnClustered), Some(ColumnStacked)]); c.series[1].secondary = true; diff --git a/crates/model/src/features/print.rs b/crates/model/src/features/print.rs index 755df94e96..e8758df131 100644 --- a/crates/model/src/features/print.rs +++ b/crates/model/src/features/print.rs @@ -11,7 +11,10 @@ pub enum Orientation { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrintSettings { pub orientation: Orientation, - /// Paper size name (`Letter`, `A4`, `Legal`…). + /// Paper size name (`Letter`, `A4`, `Legal`…; see [`crate::paper`]). Empty means no paper is + /// stated, so the printer's or locale's paper applies: a reader may leave it so for a file + /// that states none (none does yet). Print layout falls back to Letter and XLSX writes no + /// `paperSize`. New sheets default to Letter. pub paper: String, /// Margins in inches: left, right, top, bottom, header, footer. pub margins: [f32; 6], diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 9c3377665b..14bf4c7220 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -9,6 +9,7 @@ pub mod cell; mod cellmap; pub mod features; pub mod macros; +pub mod paper; pub mod password; pub mod preserved; pub mod python; @@ -31,7 +32,7 @@ pub use style::{ }; pub use workbook::{ CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString, - RefHost, ShowObjects, Workbook, WorkbookView, + RefHost, ShowObjects, Workbook, WorkbookView, WriteReservation, }; /// Font used for new workbooks. Only a name: renderers substitute an available open font diff --git a/crates/model/src/paper.rs b/crates/model/src/paper.rs new file mode 100644 index 0000000000..2db5c28e84 --- /dev/null +++ b/crates/model/src/paper.rs @@ -0,0 +1,137 @@ +//! Paper sizes by name: the names `PrintSettings::paper` holds, with their sizes. File formats +//! (paper ids or page sizes) and print layout all read this one table. + +/// Paper names and sizes in points, width then height, as the paper is named: Ledger is +/// Tabloid turned on its side. Each size has one name, so a size reads back as the name it was +/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and +/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and +/// envelopes are the JIS ones too. +pub const PAPERS: [(&str, f32, f32); 24] = [ + ("Letter", 612.0, 792.0), + ("Legal", 612.0, 1008.0), + ("A4", 595.28, 841.89), + ("A3", 841.89, 1190.55), + ("A5", 419.53, 595.28), + ("A6", 297.64, 419.53), + ("Tabloid", 792.0, 1224.0), + ("Ledger", 1224.0, 792.0), + ("Executive", 522.0, 756.0), + ("Statement", 396.0, 612.0), + ("B4", 728.50, 1031.81), + ("B5", 515.91, 728.50), + ("B6", 362.83, 515.91), + ("B4 (ISO)", 708.66, 1000.63), + ("B5 (ISO)", 498.90, 708.66), + ("B6 (ISO)", 354.33, 498.90), + ("Envelope #10", 297.0, 684.0), + ("Envelope DL", 311.81, 623.62), + ("Japanese Postcard", 283.46, 419.53), + ("Japanese Double Postcard", 419.53, 566.93), + ("Japanese Envelope #3", 340.16, 666.14), + // 長形4号 is 90×205 mm; 90×225 mm is 長形40号, a different envelope, so it stays out. + ("Japanese Envelope #4", 255.12, 581.10), + ("Japanese Envelope Kaku #2", 680.31, 941.10), + ("Japanese Envelope Kaku #3", 612.28, 785.20), +]; + +/// Other spellings of the names above, in [`key`] form. +const ALIASES: [(&str, &str); 13] = [ + // The B5 envelope is ISO B5 itself (176×250 mm): one size, one name. + ("envelopeb5", "B5 (ISO)"), + ("usletter", "Letter"), + ("uslegal", "Legal"), + ("11x17", "Tabloid"), + ("b4jis", "B4"), + ("b5jis", "B5"), + ("b6jis", "B6"), + ("postcard", "Japanese Postcard"), + ("doublepostcard", "Japanese Double Postcard"), + ("chou#3", "Japanese Envelope #3"), + ("chou#4", "Japanese Envelope #4"), + ("kaku#2", "Japanese Envelope Kaku #2"), + ("kaku#3", "Japanese Envelope Kaku #3"), +]; + +/// A name as compared: spaces, hyphens, underscores and parentheses don't matter, nor does case +/// (`B5 (JIS)`, `b5-jis` and `b5jis` are one name). +fn key(name: &str) -> String { + name.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], "") +} + +/// The paper `name` stands for, under its table name. +pub fn canonical(name: &str) -> Option<&'static str> { + // No paper name is long; a huge one (from a file or a command) is not worth folding. + if name.len() > 64 { + return None; + } + let k = key(name); + PAPERS.iter().map(|(n, _, _)| *n).find(|n| key(n) == k).or_else(|| ALIASES.iter().find(|(a, _)| *a == k).map(|(_, n)| *n)) +} + +/// The size of paper `name` in points (width, height). +pub fn size_pt(name: &str) -> Option<(f32, f32)> { + let n = canonical(name)?; + PAPERS.iter().find(|(p, _, _)| *p == n).map(|(_, w, h)| (*w, *h)) +} + +/// The paper of a page `width` × `height` points, within 2 mm on each side: the nearest one as it +/// stands, else the nearest one turned. Some papers are less than 4 mm apart (Letter and Japanese +/// Envelope Kaku #3), so the nearest wins, not the first in the table. +/// +/// The name is the paper as the page stands: a 17×11 in page is `Ledger`. A caller that also +/// records a landscape orientation should pass the size upright (narrow side first), since +/// print layout turns the named paper once more for landscape. +pub fn for_size(width: f32, height: f32) -> Option<&'static str> { + const TOLERANCE: f32 = 5.67; // 2 mm + let nearest = |w: f32, h: f32| { + PAPERS + .iter() + .filter_map(|(n, pw, ph)| { + let (dw, dh) = ((pw - w).abs(), (ph - h).abs()); + (dw < TOLERANCE && dh < TOLERANCE).then_some((dw + dh, *n)) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, n)| n) + }; + nearest(width, height).or_else(|| nearest(height, width)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_sizes() { + assert_eq!(size_pt("b5-jis"), Some((515.91, 728.50))); + assert_eq!(size_pt("US Letter"), Some((612.0, 792.0))); + assert_eq!(size_pt("nonsense"), None); + assert_eq!(for_size(1224.0, 792.0), Some("Ledger")); + assert_eq!(for_size(792.0, 1224.0), Some("Tabloid")); + assert_eq!(for_size(842.0, 595.0), Some("A4")); + assert_eq!(canonical("ledger"), Some("Ledger")); + assert_eq!(canonical(""), None); + assert_eq!(canonical(&"A4".repeat(1000)), None); + } + + #[test] + fn every_size_reads_back_as_its_name() { + for (name, w, h) in PAPERS { + assert_eq!(for_size(w, h), Some(name), "{name}"); + } + assert_eq!(canonical("Envelope B5"), Some("B5 (ISO)")); + } + + /// Letter (612×792) and Japanese Envelope Kaku #3 (612.28×785.2) are within 2 mm of some + /// of the same sizes: the nearer paper wins, whichever comes first in the table. + #[test] + fn for_size_picks_the_nearest_paper() { + assert_eq!(for_size(612.2, 788.0), Some("Japanese Envelope Kaku #3")); + assert_eq!(for_size(612.0, 790.0), Some("Letter")); + assert_eq!(for_size(788.0, 612.2), Some("Japanese Envelope Kaku #3")); + // A wide page that is a paper as it stands is not read as another paper turned. + assert_eq!(for_size(1224.0, 792.0), Some("Ledger")); + assert_eq!(for_size(1000.0, 10.0), None); + assert_eq!(for_size(f32::NAN, 792.0), None); + assert_eq!(for_size(f32::INFINITY, f32::INFINITY), None); + } +} diff --git a/crates/model/src/password.rs b/crates/model/src/password.rs index aa28ad97cc..16d5175ff0 100644 --- a/crates/model/src/password.rs +++ b/crates/model/src/password.rs @@ -160,6 +160,7 @@ impl PasswordHash { return Err("the stored password hash is damaged".into()); }; let got = match algorithm.to_ascii_uppercase().replace('_', "-").as_str() { + "SHA-1" => iterated::(password, &salt, *spin_count), "SHA-512" => iterated::(password, &salt, *spin_count), "SHA-384" => iterated::(password, &salt, *spin_count), "SHA-256" => iterated::(password, &salt, *spin_count), @@ -236,6 +237,19 @@ mod tests { Ok(()) } + #[test] + fn sha1_iterated_hash_verifies_the_correct_password() { + // Known answer for "s3cret", salt "0123456789abcdef", spin count 10, computed outside this code. + let h = PasswordHash::Iterated { + algorithm: "SHA-1".into(), + hash: "b2+ArdbduWEP3TNb+4NZg6qjkEk=".into(), + salt: crate::b64::encode(b"0123456789abcdef"), + spin_count: 10, + }; + assert!(h.verify("s3cret").unwrap()); + assert!(!h.verify("s3cret ").unwrap()); + } + #[test] fn iterated_hash_verifies_and_refuses_what_it_cannot_check() -> Result<(), Box> { let h = PasswordHash::new_sha512("s3cret", b"0123456789abcdef"); @@ -245,7 +259,7 @@ mod tests { let PasswordHash::Iterated { hash, salt, .. } = h else { return Err("not an iterated hash".into()) }; let other = |algorithm: &str, spin_count| PasswordHash::Iterated { algorithm: algorithm.into(), hash: hash.clone(), salt: salt.clone(), spin_count }; - assert!(other("SHA-1", 10).verify("s3cret").is_err()); + assert!(!other("SHA-1", 10).verify("s3cret").unwrap()); assert!(other("MD5", 10).verify("s3cret").is_err()); assert!(other("SHA-512", MAX_SPIN_COUNT + 1).verify("s3cret").is_err()); assert!(!other("SHA-256", 2).verify("s3cret")?); diff --git a/crates/model/src/preserved.rs b/crates/model/src/preserved.rs index 57007ae1de..227685f404 100644 --- a/crates/model/src/preserved.rs +++ b/crates/model/src/preserved.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use crate::sheet::Visibility; +use crate::style::Style; /// A relationship from an owning part (the package root, the workbook or a sheet, or a kept part) /// to a kept part or to an external target. @@ -32,6 +33,13 @@ pub struct PreservedPart { pub data: Arc<[u8]>, /// The part's own relationships, ids unchanged (the part's bytes refer to them). pub rels: Vec, + /// Differential formats its XML refers to by `dxfId`, by their id in the source file's styles + /// part. GridCraft rewrites the styles part, so the ids are renumbered on save (kept + /// PivotTables). + pub dxfs: Vec<(u32, Style)>, + /// Custom number formats its XML refers to by `numFmtId` (code by id in the source file), + /// renumbered on save like [`Self::dxfs`] (kept PivotTables and pivot caches). + pub num_fmts: Vec<(u32, String)>, } /// A raw XML element of an owning part that refers to kept parts, re-emitted on save with its diff --git a/crates/model/src/workbook.rs b/crates/model/src/workbook.rs index 7669f01252..2c6689ec54 100644 --- a/crates/model/src/workbook.rs +++ b/crates/model/src/workbook.rs @@ -224,6 +224,9 @@ pub struct Workbook { /// alone has none and is not written there. #[serde(default, skip_serializing_if = "Option::is_none")] pub structure_password: Option, + /// "Password to modify" (XLSX `fileSharing`): the file opens read-only unless it is given. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub write_reservation: Option, /// Custom fill lists (Options › Custom Lists) beyond the built-in ones. pub custom_lists: Vec>, /// Named cell styles (Cell Styles gallery): name → style. @@ -294,6 +297,15 @@ impl Default for Workbook { } } +/// The write-reservation of a file (XLSX `fileSharing`): who reserved it, whether it asks to open +/// read-only, and the hash of its password to modify, never the password. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct WriteReservation { + pub user_name: String, + pub read_only_recommended: bool, + pub password: Option, +} + /// The active sheet index of a [`Workbook`]. /// /// Every other part of a workbook value is immutable once shared (the engine keeps versions as @@ -564,6 +576,7 @@ impl Workbook { props: DocProps::default(), protected_structure: false, structure_password: None, + write_reservation: None, custom_lists: vec![], cell_styles: vec![], phonetics: vec![], diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 0cbde92a8f..74de61aade 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -6,6 +6,9 @@ impl SheetApp { Ok(r) => self.after_open(Some(path), &r), // A password-protected workbook: ask for the password; the dialog opens it. Err(e) if e.contains(gridcraft_engine::io::PASSWORD_REQUIRED) => self.open_dialog("openPassword", json!({"path": path})), + Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + self.open_dialog("openPassword", json!({"path": path, "modify": true})) + } Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))), } self.after_engine(); @@ -95,6 +98,10 @@ impl SheetApp { self.backstage = None; self.open_dialog("openPassword", json!({"name": name, "base64": b64})); } + Err(e) if e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) => { + self.backstage = None; + self.open_dialog("openPassword", json!({"name": name, "base64": b64, "modify": true})); + } Err(e) => self.message = Some(("GridCraft".into(), clean_error(&e))), } self.after_engine(); diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 453c9bee90..014844238a 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -98,6 +98,31 @@ impl Page { } } +/// What a print preview was built for: document, revision, scope, the selection when it is +/// the scope, and fit to page. +type PreviewKey = (u64, u64, PrintScope, String, bool); + +/// What File › Print › Settings prints. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PrintScope { + ActiveSheets, + EntireWorkbook, + /// The selected cells of the active sheet. + Selection, +} + +impl PrintScope { + const ALL: [PrintScope; 3] = [PrintScope::ActiveSheets, PrintScope::EntireWorkbook, PrintScope::Selection]; + + fn label(self) -> &'static str { + match self { + PrintScope::ActiveSheets => "Print Active Sheets", + PrintScope::EntireWorkbook => "Print Entire Workbook", + PrintScope::Selection => "Print Selection", + } + } +} + /// Document properties shown on the Info page: (`file.properties` key, label). const PROPERTIES: [(&str, &str); 6] = [ ("title", "Title"), @@ -116,14 +141,14 @@ pub struct Backstage { props: [String; 6], /// Focus at the end of the previous frame, before egui clears it on Esc. text_edit_focused: bool, - /// Print: the whole workbook rather than the active sheet. - pub print_all: bool, + /// Print: what to print (the Settings menu's first choice). + pub print_scope: PrintScope, /// Print: fit each sheet on one page. pub fit_to_page: bool, /// Print: the previewed page (0-based). preview_page: usize, - /// Print: the preview for (document, revision, whole workbook, fit to page). - preview: Option<((u64, u64, bool, bool), Json)>, + /// Print: the preview for (document, revision, scope, the selection when it is the scope, fit to page). + preview: Option<(PreviewKey, Json)>, /// Save As: the chosen file type (an extension from [`SAVE_TYPES`]). pub save_format: &'static str, /// Home and Open: when the recent workbooks were last changed. @@ -141,7 +166,7 @@ impl Backstage { page, props: Default::default(), text_edit_focused: false, - print_all: false, + print_scope: PrintScope::ActiveSheets, fit_to_page: false, preview_page: 0, preview: None, diff --git a/crates/ui-egui/src/backstage/print.rs b/crates/ui-egui/src/backstage/print.rs index 24178dba8a..a15c037064 100644 --- a/crates/ui-egui/src/backstage/print.rs +++ b/crates/ui-egui/src/backstage/print.rs @@ -1,5 +1,6 @@ use super::{ - Align2, Backstage, Icon, Json, Outcome, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme, vec2, + Align2, Backstage, Icon, Json, Outcome, PrintScope, Rect, Sense, SheetApp, Stroke, StrokeKind, Tokens, Ui, dim, json, pos2, square_button, theme, + vec2, }; /// Builds the print scope and fit-to-page parameters, caches `file.printPreview` per document revision/options, and draws page thumbnails with navigation plus the print settings and Print action. @@ -10,11 +11,19 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m dim(ui, lang.tr("No workbook is open.")); return; }; - let mut params = json!({"sheets": if bs.print_all { "all" } else { "active" }}); + let mut params = json!({"sheets": if bs.print_scope == PrintScope::EntireWorkbook { "all" } else { "active" }}); + // The selection is not part of the document revision, so it goes in the preview's key. + let mut selection = String::new(); + if bs.print_scope == PrintScope::Selection + && let Some(d) = app.session.active() + { + selection = d.selection.a1(); + params["range"] = json!(selection); + } if bs.fit_to_page { params["fitToPage"] = json!(true); } - let key = (uid, revision, bs.print_all, bs.fit_to_page); + let key = (uid, revision, bs.print_scope, selection, bs.fit_to_page); if bs.preview.as_ref().is_none_or(|(k, _)| *k != key) { let preview = app.session.run("file.printPreview", params.clone()).unwrap_or(Json::Null); bs.preview = Some((key, preview)); @@ -34,14 +43,13 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m out.close = app.services.print_native.is_none(); } ui.add_space(16.0); - let scope = if bs.print_all { "Print Entire Workbook" } else { "Print Active Sheets" }; egui::ComboBox::from_id_salt("backstage_print_scope") .width(230.0) - .selected_text(lang.tr(scope)) + .selected_text(lang.tr(bs.print_scope.label())) .show_ui(ui, |ui| { - for (all, label) in [(false, "Print Active Sheets"), (true, "Print Entire Workbook")] { - if ui.selectable_label(bs.print_all == all, lang.tr(label)).clicked() { - bs.print_all = all; + for scope in PrintScope::ALL { + if ui.selectable_label(bs.print_scope == scope, lang.tr(scope.label())).clicked() { + bs.print_scope = scope; bs.preview_page = 0; } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 09554cfac8..4621736d92 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -458,6 +458,22 @@ impl Dialog { // An empty password from the start, so OK on the untouched field says "incorrect" // rather than asking for the password again. let mut values = params.clone(); + // A workbook with a password to modify asks for that, or a read-only open. + if p("modify").as_bool().unwrap_or(false) { + values["modifyPassword"] = json!(""); + values["readOnly"] = json!(false); + return Some(Dialog::form( + "openPassword", + "Password", + "file.open", + vec![ + Note(format!("'{file}' is reserved by its author. Enter the password to modify it, or open it read-only.")), + Password { key: "modifyPassword", label: "Password:" }, + Check { key: "readOnly", label: "Read Only" }, + ], + values, + )); + } values["password"] = json!(""); Dialog::form( "openPassword", diff --git a/crates/ui-egui/src/dialogs/charts.rs b/crates/ui-egui/src/dialogs/charts.rs index 039b8b0f3a..35ce03cf53 100644 --- a/crates/ui-egui/src/dialogs/charts.rs +++ b/crates/ui-egui/src/dialogs/charts.rs @@ -2,7 +2,7 @@ use super::show::ok_cancel; use super::{Color32, Dialog, Icon, Json, Sense, SheetApp, Stroke, StrokeKind, icons, json, vec2}; /// Every chart type the All Charts tab offers: `(type, subtype, label)` for `insert.chart`. -const ALL_CHARTS: [(&str, &str, &str); 21] = [ +const ALL_CHARTS: [(&str, &str, &str); 23] = [ ("column", "", "Clustered Column"), ("column", "stacked", "Stacked Column"), ("column", "stacked100", "100% Stacked Column"), @@ -12,6 +12,8 @@ const ALL_CHARTS: [(&str, &str, &str); 21] = [ ("line", "", "Line"), ("line", "markers", "Line with Markers"), ("line", "stacked", "Stacked Line"), + ("line", "stacked100", "100% Stacked Line"), + ("line", "stacked100Markers", "100% Stacked Line with Markers"), ("pie", "", "Pie"), ("doughnut", "", "Doughnut"), ("area", "", "Area"), diff --git a/crates/ui-egui/src/dialogs/show.rs b/crates/ui-egui/src/dialogs/show.rs index 5672898601..64e0096fce 100644 --- a/crates/ui-egui/src/dialogs/show.rs +++ b/crates/ui-egui/src/dialogs/show.rs @@ -122,6 +122,27 @@ pub(crate) fn build_params(d: &Dialog) -> Json { v } +fn command_error(app: &mut SheetApp, d: &mut Dialog, e: String) { + if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) { + // Data Analysis asks before replacing data in its output range. + d.values.insert("askOverwrite".into(), json!(true)); + } else if d.name == "openPassword" && e.contains(gridcraft_engine::io::MODIFY_PASSWORD_REQUIRED) { + // The decryption password opened an encrypted, reserved workbook; ask for the modify password. + let mut params = Json::Object(d.values.clone()); + params["modify"] = json!(true); + if let Some(next) = Dialog::open(app, "openPassword", params) { + *d = Dialog { back: d.back.take(), ..next }; + } + } else if d.name == "openPassword" { + // A wrong password: say so, clear the field and stay open for another try. + let field = if d.values.contains_key("modifyPassword") { "modifyPassword" } else { "password" }; + d.values.insert(field.into(), json!("")); + app.message = Some((d.title.clone(), crate::clean_error(&e))); + } else { + app.message = Some((d.title.clone(), crate::clean_error(&e))); + } +} + /// Takes and draws the active dialog, dispatches its body by name, consumes picture-inbox results, runs OK/confirm commands, handles Esc/close and restores the back-dialog stack. pub fn show(app: &mut SheetApp, ctx: &egui::Context) { let Some(mut d) = app.dialog.take() else { return }; @@ -444,16 +465,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) { app.after_open(path.as_deref(), &r); } } - // Data Analysis asks before replacing data in its output range. - Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => { - d.values.insert("askOverwrite".into(), json!(true)); - } - // A wrong password: say so, clear the field and stay open for another try. - Err(e) if d.name == "openPassword" => { - d.values.insert("password".into(), json!("")); - app.message = Some((d.title.clone(), crate::clean_error(&e))); - } - Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))), + Err(e) => command_error(app, &mut d, e), } } else if confirm { open = false; diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index da7dd57ece..9c083bccfc 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -345,7 +345,10 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face let mut bound: Vec = Vec::new(); for (bold, italic) in [(false, false), (true, false), (false, true), (true, true)] { let Some(primary) = pick_face(faces, bold, italic) else { continue }; + let role = role_key(family, bold, italic); let mut chain: Vec = Vec::new(); + // The face the role's text is actually drawn in: the first one whose file could be read. + let mut drawn: Option<&Face> = None; for face in [Some(primary), pick_face(faces, false, false)] { let Some(face) = face else { continue }; let key = face_key(face); @@ -359,12 +362,15 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face fonts.font_data.insert(key.clone(), std::sync::Arc::new(fd)); } chain.push(key); + drawn.get_or_insert(face); } - if chain.is_empty() { - continue; - } + let Some(drawn) = drawn else { continue }; + // Imitate what the drawn face lacks: italic when it is upright; bold when it is the family's + // plain face (the family has no bold of its own, or the bold file couldn't be read). + let own_bold = pick_face(faces, false, italic).is_none_or(|plain| face_key(plain) != face_key(primary)); + set_synthetic(&role, SLANT, italic && !drawn.italic); + set_synthetic(&role, BOLD, bold && (face_key(drawn) != face_key(primary) || !own_bold)); chain.extend(base.iter().cloned()); - let role = role_key(family, bold, italic); fonts.families.insert(egui::FontFamily::Name(role.clone().into()), chain); bound.push(role); } @@ -389,6 +395,41 @@ pub fn is_bound(role: &str) -> bool { bound().read().unwrap_or_else(std::sync::PoisonError::into_inner).contains(role) } +/// Roles drawn with a face that lacks their slant or weight (Arial Black has one face only), as +/// `{role}|slant` and `{role}|bold`. Excel imitates the missing style (observed in its PDF: a cell in +/// Arial Black, bold italic, is slanted by 1/3 and outlined about 1/36 of its size thick). +static SYNTHETIC: OnceLock>> = OnceLock::new(); +const SLANT: &str = "slant"; +const BOLD: &str = "bold"; + +fn synthetic() -> &'static std::sync::RwLock> { + SYNTHETIC.get_or_init(|| std::sync::RwLock::new(HashSet::new())) +} + +fn set_synthetic(role: &str, style: &str, on: bool) { + let mut set = synthetic().write().unwrap_or_else(|e| e.into_inner()); + let key = format!("{role}|{style}"); + if on { + set.insert(key); + } else { + set.remove(&key); + } +} + +fn is_synthetic(role: &str, style: &str) -> bool { + is_bound(role) && synthetic().read().unwrap_or_else(|e| e.into_inner()).contains(&format!("{role}|{style}")) +} + +/// Does italic text in this installed family have to be slanted when drawn (no italic face)? +pub fn is_slanted(family: &str, bold: bool) -> bool { + is_synthetic(&role_key(family, bold, true), SLANT) +} + +/// Does bold text in this installed family have to be thickened when drawn (no face of its own)? +pub fn is_emboldened(family: &str, italic: bool) -> bool { + is_synthetic(&role_key(family, true, italic), BOLD) +} + /// Serializes tests that mutate the process-wide bound-family registry. #[cfg(test)] pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -490,6 +531,44 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn styles_a_family_has_no_face_for_are_imitated() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("gridcraft-fonts-synthetic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + // One font file stands in for every face; each face is its own (path, index) by its name. + let face = |family: &str, file: &str, weight: f32, italic: bool| { + let path = dir.join(file); + std::fs::write(&path, epaint_default_fonts::UBUNTU_LIGHT).expect("write"); + Face { family: family.into(), names: vec![family.into()], path, index: 0, weight, italic } + }; + let mut fonts = egui::FontDefinitions::default(); + // Like Arial Black: one face, whatever its weight. + let mut bound = bind_faces(&mut fonts, "One Face", &[face("One Face", "one.ttf", 900.0, false)]); + let full = [ + face("Full", "full.ttf", 400.0, false), + face("Full", "full-b.ttf", 700.0, false), + face("Full", "full-i.ttf", 400.0, true), + face("Full", "full-bi.ttf", 700.0, true), + ]; + bound.extend(bind_faces(&mut fonts, "Full", &full)); + // Bold and italic faces whose files can't be read: the regular face draws them, imitated. + let gone = |file: &str, weight: f32, italic: bool| Face { path: dir.join(file), ..face("Gone", "gone.ttf", weight, italic) }; + let broken = [face("Gone", "gone.ttf", 400.0, false), gone("missing-b.ttf", 700.0, false), gone("missing-i.ttf", 400.0, true)]; + bound.extend(bind_faces(&mut fonts, "Gone", &broken)); + set_bound(bound); + assert!(is_slanted("One Face", false) && is_slanted("One Face", true)); + assert!(is_emboldened("One Face", false) && is_emboldened("One Face", true)); + assert!(is_slanted("Gone", false) && is_emboldened("Gone", false), "the regular face stands in, imitated"); + assert!(!is_slanted("Full", false) && !is_slanted("Full", true), "its own italic faces are drawn as they are"); + assert!(!is_emboldened("Full", false) && !is_emboldened("Full", true), "its own bold faces are drawn as they are"); + assert!(!is_slanted("Not Bound", false) && !is_emboldened("Not Bound", false)); + set_bound([]); + assert!(!is_slanted("One Face", false) && !is_emboldened("One Face", false), "nothing is imitated once unbound"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A font that is just a table directory and a `name` table holding `records` as /// `(Windows language id, name id, text)`: all [`file_faces`] reads. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index ac10c049e1..26bd8cf92e 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -327,6 +327,10 @@ pub struct GridState { pub cells_rect: Option, /// Column and row of the clicked header cell, and where to open the menu. pub filter_menu: Option<(u32, u32, Pos2)>, + /// Pending popup edits travel with this window and are dropped when its menu or window closes. + pub filter_checks: Option>, + pub filter_search: String, + pub filter_buttons: Vec, pub context_menu: Option, /// The frame a right-click opened `context_menu` in: that click's own press doesn't close it. pub context_menu_frame: u64, diff --git a/crates/ui-egui/src/grid/cell_paint.rs b/crates/ui-egui/src/grid/cell_paint.rs index 73a3a1405d..2fc283df9a 100644 --- a/crates/ui-egui/src/grid/cell_paint.rs +++ b/crates/ui-egui/src/grid/cell_paint.rs @@ -230,6 +230,25 @@ pub(super) fn merged_edges(wb: &Workbook, si: usize, sh: &Sheet, geo: &Geo, area out } +/// One cell's text as a layout job, wrapped at `wrap` (`f32::INFINITY`: one line). `slant` draws it +/// oblique, for an italic cell whose font has no italic face (see [`crate::fonts::is_slanted`]). +pub(super) fn cell_job(text: String, font: FontId, color: Color32, wrap: f32, slant: bool) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::simple(text, font, color, wrap); + for section in &mut job.sections { + section.format.italics = slant; + } + job +} + +/// Paints one cell's text; `bold_dx` > 0 paints it again that far right, to thicken a bold cell +/// whose font has no bold face (see [`crate::fonts::is_emboldened`]). +pub(super) fn paint_cell_galley(p: &Painter, pos: Pos2, galley: std::sync::Arc, color: Color32, bold_dx: f32) { + if bold_dx > 0.0 { + p.galley(pos + egui::vec2(bold_dx, 0.0), galley.clone(), color); + } + p.galley(pos, galley, color); +} + /// The smaller font that makes `text` fit in `room` points of width (Shrink to fit), or `None` /// when it already fits at its own size. pub(super) fn shrink_font(p: &Painter, text: &str, font: &FontId, room: f32) -> Option { diff --git a/crates/ui-egui/src/grid/menus.rs b/crates/ui-egui/src/grid/menus.rs index b6546dacfa..c81a39ff6b 100644 --- a/crates/ui-egui/src/grid/menus.rs +++ b/crates/ui-egui/src/grid/menus.rs @@ -31,14 +31,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ } } let wb = app.session.active().map(|d| d.wb.clone()).unwrap_or(wb); - let values = gridcraft_engine::cmd::data::filter_values(&wb, si, col); - let key = egui::Id::unique(("filter_sel", col)); - let search_key = egui::Id::unique(("filter_search", col)); - let buttons_key = egui::Id::unique(("filter_buttons", col)); // Enter is the menu's OK, as in Excel: taken before the search box (which would only drop its // focus) and the value checkboxes (which would toggle) see it. A focused button keeps it as its click. - let buttons: Vec = ui.ctx().data_mut(|d| d.get_temp(buttons_key)).unwrap_or_default(); - let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| buttons.contains(&f)); + let on_button = ui.ctx().memory(|m| m.focused()).is_some_and(|f| app.grid.filter_buttons.contains(&f)); let enter = !on_button && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); let mut close = false; let area = egui::Area::new(egui::Id::unique("filter_menu")).fixed_pos(at + vec2(-180.0, 10.0)).order(egui::Order::Foreground); @@ -57,9 +52,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ } ui.separator(); ui.label(egui::RichText::new("Filter").strong()); - let mut checks: Vec<(String, bool)> = ui.ctx().data_mut(|d| d.get_temp::>(key)).unwrap_or(values.clone()); + let mut checks = app.grid.filter_checks.clone().unwrap_or_else(|| gridcraft_engine::cmd::data::filter_values(&wb, si, col)); // A search narrows the list; Select All and Apply then only cover the matches. - let mut search: String = ui.ctx().data_mut(|d| d.get_temp(search_key)).unwrap_or_default(); + let mut search = app.grid.filter_search.clone(); let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text("Search").desired_width(f32::INFINITY)); if !was_open { field.request_focus(); @@ -81,10 +76,8 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ ui.checkbox(on, v.as_str()); } }); - ui.ctx().data_mut(|d| { - d.insert_temp(key, checks.clone()); - d.insert_temp(search_key, search.clone()); - }); + app.grid.filter_checks = Some(checks.clone()); + app.grid.filter_search.clone_from(&search); let checks: Vec<(String, bool)> = checks.iter().map(|(v, on)| (v.clone(), *on && matches(v))).collect(); ui.separator(); ui.horizontal(|ui| { @@ -96,8 +89,12 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ // Nothing checked would hide every row, so Enter (unlike a click on Apply) does nothing then. let any = checks.iter().any(|(_, on)| *on); let apply = ui.button("Apply"); - ui.ctx().data_mut(|d| d.insert_temp(buttons_key, vec![ascending.id, descending.id, clear.id, apply.id])); + app.grid.filter_buttons = vec![ascending.id, descending.id, clear.id, apply.id]; if apply.clicked() || (enter && any) { + let mut checks = gridcraft_engine::cmd::data::filter_selection(&wb, si, col, &checks); + for (value, on) in &mut checks { + *on &= matches(value); + } let blanks = checks.iter().any(|(v, on)| v == "(Blanks)" && *on); let vals: Vec = checks.iter().filter(|(v, on)| *on && v != "(Blanks)").map(|(v, _)| v.clone()).collect(); let p = if checks.iter().all(|(_, b)| *b) { @@ -112,11 +109,9 @@ pub(super) fn filter_menu(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, was_ }); }); if close || popup_dismissed(&response.response, was_open) { - ui.ctx().data_mut(|d| { - d.remove::>(key); - d.remove::(search_key); - d.remove::>(buttons_key); - }); + app.grid.filter_checks = None; + app.grid.filter_search.clear(); + app.grid.filter_buttons.clear(); app.grid.filter_menu = None; } } diff --git a/crates/ui-egui/src/grid/quadrant.rs b/crates/ui-egui/src/grid/quadrant.rs index dedead69e8..a222222654 100644 --- a/crates/ui-egui/src/grid/quadrant.rs +++ b/crates/ui-egui/src/grid/quadrant.rs @@ -1,7 +1,7 @@ use super::active_row::paint_active_row; use super::cell_paint::{ - Look, MergedArea, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border, paint_cf_icon, - painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y, + Look, MergedArea, cell_job, cell_text_y, center_across_end, col32, display_text, galley_baseline_bounds, look, merged_edges, paint_border, + paint_cell_galley, paint_cf_icon, painted_halign, rotated_text_pos, shrink_font, wrapped_cell_text_y, }; use super::geo::Geo; use super::tables::{filter_button_rect, paint_filter_button}; @@ -352,6 +352,11 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option, painted: &(CellRef, Rect, Look, Option 0 first paints it that far along the text's own +/// direction, the second impression of imitated bold. +fn paint_rotated_galley(cp: &Painter, pos: Pos2, galley: std::sync::Arc, color: Color32, angle: f32, bold_dx: f32) { + if bold_dx > 0.0 { + let mut thick = egui::epaint::TextShape::new(pos + bold_dx * egui::vec2(angle.cos(), angle.sin()), galley.clone(), color); + thick.angle = angle; + cp.add(thick); + } + let mut shape = egui::epaint::TextShape::new(pos, galley, color); + shape.angle = angle; + cp.add(shape); +} + struct TextDecoration { x: f32, y: f32, diff --git a/crates/ui-egui/src/grid/show.rs b/crates/ui-egui/src/grid/show.rs index 8fe69acaa5..562e1d92ac 100644 --- a/crates/ui-egui/src/grid/show.rs +++ b/crates/ui-egui/src/grid/show.rs @@ -360,6 +360,7 @@ impl Geo> ActiveCellVisibility<'_, F> { } fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Response, geo: &Geo, sh: &Sheet, wb: &Workbook) { + let window = app.session.active_window(); let previous_popups = (app.grid.filter_menu, app.grid.list_picker, app.grid.header_menu, app.grid.fill_menu); // A pan the grid never saw end (it was hidden mid-drag) must not swallow the next press. if app.grid.touch_pan && !resp.dragged() && !resp.drag_stopped() { @@ -374,6 +375,15 @@ fn show_grid_interactions(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Re crate::paper_view::interact(app, ui, resp, geo, sh, wb); interact(app, ui, resp, geo, sh, wb); } + // A form button can switch windows and swap GridState; the old popup and geometry belong to the outgoing window. + if app.session.active_window() != window { + return; + } + if previous_popups.0 != app.grid.filter_menu && previous_popups.0.is_some() { + app.grid.filter_checks = None; + app.grid.filter_search.clear(); + app.grid.filter_buttons.clear(); + } update_cursor(app, ui, resp, geo, sh); crate::text_box::show(app, ui, geo, sh); if app.editor.as_ref().is_some_and(|e| !e.from_formula_bar) { diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index a573786782..0de9839cb2 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -337,6 +337,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Uloží sešit pod jiným názvem nebo do jiné složky.", "Print Active Sheets" => "Vytisknout aktivní listy", "Print Entire Workbook" => "Vytisknout celý sešit", + "Print Selection" => "Vytisknout výběr", "Fit Sheet on One Page" => "Přizpůsobit list na jednu stránku", "Page Setup…" => "Vzhled stránky…", "Page {page} of {pages}" => "Stránka {page} z {pages}", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 513b26e069..cf3fdbfb42 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -356,6 +356,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { } "Print Active Sheets" => "Aktive Blätter drucken", "Print Entire Workbook" => "Gesamte Arbeitsmappe drucken", + "Print Selection" => "Auswahl drucken", "Fit Sheet on One Page" => "Blatt auf einer Seite darstellen", "Page Setup…" => "Seite einrichten…", "Page {page} of {pages}" => "Seite {page} von {pages}", diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 95f35eb83f..573b6ba2d5 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -315,6 +315,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Αποθηκεύστε το βιβλίο εργασίας με άλλο όνομα ή σε άλλον φάκελο.", "Print Active Sheets" => "Εκτύπωση ενεργών φύλλων", "Print Entire Workbook" => "Εκτύπωση ολόκληρου βιβλίου εργασίας", + "Print Selection" => "Εκτύπωση επιλογής", "Fit Sheet on One Page" => "Προσαρμογή φύλλου σε μία σελίδα", "Page Setup…" => "Διαμόρφωση σελίδας…", "Page {page} of {pages}" => "Σελίδα {page} από {pages}", @@ -921,6 +922,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Γραμμή", "Line with Markers" => "Γραμμή με δείκτες", "Stacked Line" => "Σωρευμένες γραμμές", + "100% Stacked Line" => "Σωρευμένες γραμμές 100%", + "100% Stacked Line with Markers" => "Σωρευμένες γραμμές 100% με δείκτες", "Pie" => "Πίτα", "Doughnut" => "Δακτύλιος", "Area" => "Περιοχή", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 73c969a38d..5ce8fad5b8 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -343,6 +343,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Guarda el libro con otro nombre o en otra carpeta.", "Print Active Sheets" => "Imprimir hojas activas", "Print Entire Workbook" => "Imprimir todo el libro", + "Print Selection" => "Imprimir selección", "Fit Sheet on One Page" => "Ajustar hoja en una página", "Page Setup…" => "Configurar página…", "Page {page} of {pages}" => "Página {page} de {pages}", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 631adff8c1..473834399e 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -432,6 +432,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Enregistrer le classeur sous un autre nom ou dans un autre dossier.", "Print Active Sheets" => "Imprimer les feuilles actives", "Print Entire Workbook" => "Imprimer tout le classeur", + "Print Selection" => "Imprimer la sélection", "Fit Sheet on One Page" => "Ajuster la feuille sur une page", "Page Setup…" => "Mise en page…", "Page {page} of {pages}" => "Page {page} sur {pages}", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9bbeb0746c..dbd1a66da1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -417,6 +417,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salva la cartella di lavoro con un altro nome o in un'altra cartella.", "Print Active Sheets" => "Stampa fogli attivi", "Print Entire Workbook" => "Stampa intera cartella di lavoro", + "Print Selection" => "Stampa selezione", "Fit Sheet on One Page" => "Adatta foglio a una pagina", "Page Setup…" => "Imposta pagina…", "Page {page} of {pages}" => "Pagina {page} di {pages}", @@ -810,6 +811,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Linee", "Line with Markers" => "Linee con indicatori", "Stacked Line" => "Linee in pila", + "100% Stacked Line" => "Linee in pila 100%", + "100% Stacked Line with Markers" => "Linee in pila 100% con indicatori", "Pie" => "Torta", "Doughnut" => "Anello", "Area" => "Area", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 0b9177bd72..fd809f0658 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -420,6 +420,7 @@ pub(super) const CORE: &[(&str, &str)] = &[ ("Save the workbook under another name or in another folder.", "ブックを別の名前または別のフォルダーに保存します。"), ("Print Active Sheets", "作業中のシートを印刷"), ("Print Entire Workbook", "ブック全体を印刷"), + ("Print Selection", "選択した部分を印刷"), ("Fit Sheet on One Page", "シートを 1 ページに印刷"), ("Page Setup…", "ページ設定…"), ("Page {page} of {pages}", "{page} / {pages} ページ"), @@ -831,6 +832,8 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Line", "折れ線"), ("Line with Markers", "マーカー付き折れ線"), ("Stacked Line", "積み上げ折れ線"), + ("100% Stacked Line", "100% 積み上げ折れ線"), + ("100% Stacked Line with Markers", "マーカー付き 100% 積み上げ折れ線"), ("Pie", "円"), ("Doughnut", "ドーナツ"), ("Area", "面"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 116d95eac7..9490134eb5 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -432,6 +432,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "통합 문서를 다른 이름 또는 다른 폴더에 저장합니다.", "Print Active Sheets" => "활성 시트 인쇄", "Print Entire Workbook" => "전체 통합 문서 인쇄", + "Print Selection" => "선택 영역 인쇄", "Fit Sheet on One Page" => "한 페이지에 시트 맞추기", "Page Setup…" => "페이지 설정…", "Page {page} of {pages}" => "{page}/{pages} 페이지", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index d5ae1d4b6b..3840267385 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -419,6 +419,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "De werkmap onder een andere naam of in een andere map opslaan.", "Print Active Sheets" => "Actieve bladen afdrukken", "Print Entire Workbook" => "Hele werkmap afdrukken", + "Print Selection" => "Selectie afdrukken", "Fit Sheet on One Page" => "Blad op één pagina passen", "Page Setup…" => "Pagina-instelling…", "Page {page} of {pages}" => "Pagina {page} van {pages}", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 351e5a3838..0f12f8a87c 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -409,6 +409,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Zapisz skoroszyt pod inną nazwą lub w innym folderze.", "Print Active Sheets" => "Drukuj aktywne arkusze", "Print Entire Workbook" => "Drukuj cały skoroszyt", + "Print Selection" => "Drukuj zaznaczenie", "Fit Sheet on One Page" => "Dopasuj arkusz do jednej strony", "Page Setup…" => "Ustawienia strony…", "Page {page} of {pages}" => "Strona {page} z {pages}", @@ -798,6 +799,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Liniowy", "Line with Markers" => "Liniowy ze znacznikami", "Stacked Line" => "Liniowy skumulowany", + "100% Stacked Line" => "Liniowy 100% skumulowany", + "100% Stacked Line with Markers" => "Liniowy 100% skumulowany ze znacznikami", "Pie" => "Kołowy", "Doughnut" => "Pierścieniowy", "Area" => "Warstwowy", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index da11105e89..e8f5426344 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -426,6 +426,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salve a pasta de trabalho com outro nome ou em outra pasta.", "Print Active Sheets" => "Imprimir planilhas ativas", "Print Entire Workbook" => "Imprimir toda a pasta de trabalho", + "Print Selection" => "Imprimir seleção", "Fit Sheet on One Page" => "Ajustar planilha em uma página", "Page Setup…" => "Configurar página…", "Page {page} of {pages}" => "Página {page} de {pages}", @@ -837,6 +838,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Linhas", "Line with Markers" => "Linhas com Marcadores", "Stacked Line" => "Linhas Empilhadas", + "100% Stacked Line" => "Linhas 100% Empilhadas", + "100% Stacked Line with Markers" => "Linhas 100% Empilhadas com Marcadores", "Pie" => "Pizza", "Doughnut" => "Rosca", "Area" => "Área", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 5347487310..c427c0b6a3 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -416,6 +416,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Salvează registrul cu alt nume sau în alt folder.", "Print Active Sheets" => "Imprimare foi active", "Print Entire Workbook" => "Imprimare tot registrul", + "Print Selection" => "Imprimare selecție", "Fit Sheet on One Page" => "Încadrare foaie pe o pagină", "Page Setup…" => "Configurare pagină…", "Page {page} of {pages}" => "Pagina {page} din {pages}", @@ -804,6 +805,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Linie", "Line with Markers" => "Linii cu marcaje", "Stacked Line" => "Linii stivuite", + "100% Stacked Line" => "Linii 100% stivuite", + "100% Stacked Line with Markers" => "Linii 100% stivuite cu marcaje", "Pie" => "Radială", "Doughnut" => "Inel", "Area" => "Arie", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 6be38aaaf7..c729a0f60e 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -431,6 +431,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Сохранить книгу под другим именем или в другой папке.", "Print Active Sheets" => "Напечатать активные листы", "Print Entire Workbook" => "Напечатать всю книгу", + "Print Selection" => "Напечатать выделенный диапазон", "Fit Sheet on One Page" => "Вписать лист на одну страницу", "Page Setup…" => "Параметры страницы…", "Page {page} of {pages}" => "Страница {page} из {pages}", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index c5a60e89cd..dee5795c98 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -425,6 +425,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Sačuvaj radnu svesku pod drugim imenom ili u drugoj fascikli.", "Print Active Sheets" => "Štampaj aktivne listove", "Print Entire Workbook" => "Štampaj celu radnu svesku", + "Print Selection" => "Štampaj izbor", "Fit Sheet on One Page" => "Uklopi list na jednu stranicu", "Page Setup…" => "Podešavanje stranice…", "Page {page} of {pages}" => "Stranica {page} od {pages}", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index 8c175283fd..302bea1273 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -330,6 +330,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Çalışma kitabını başka bir adla veya başka bir klasöre kaydedin.", "Print Active Sheets" => "Etkin Sayfaları Yazdır", "Print Entire Workbook" => "Tüm Çalışma Kitabını Yazdır", + "Print Selection" => "Seçimi Yazdır", "Fit Sheet on One Page" => "Sayfayı Bir Sayfaya Sığdır", "Page Setup…" => "Sayfa Yapısı…", "Page {page} of {pages}" => "Sayfa {page} / {pages}", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 19f9ed161a..79b9db5db2 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -414,6 +414,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Зберегти книгу під іншим іменем або в іншій теці.", "Print Active Sheets" => "Надрукувати активні аркуші", "Print Entire Workbook" => "Надрукувати всю книгу", + "Print Selection" => "Надрукувати виділений діапазон", "Fit Sheet on One Page" => "Вмістити аркуш на одну сторінку", "Page Setup…" => "Параметри сторінки…", "Page {page} of {pages}" => "Сторінка {page} з {pages}", @@ -801,6 +802,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line" => "Line", "Line with Markers" => "Line with Markers", "Stacked Line" => "Stacked Line", + "100% Stacked Line" => "100% Stacked Line", + "100% Stacked Line with Markers" => "100% Stacked Line with Markers", "Pie" => "Pie", "Doughnut" => "Doughnut", "Area" => "Area", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index f7bb841da8..1891f3898c 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -420,6 +420,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "Lưu sổ làm việc với tên khác hoặc vào thư mục khác.", "Print Active Sheets" => "In các trang tính hiện hoạt", "Print Entire Workbook" => "In toàn bộ sổ làm việc", + "Print Selection" => "In vùng chọn", "Fit Sheet on One Page" => "Vừa trang tính trên một trang", "Page Setup…" => "Thiết lập trang…", "Page {page} of {pages}" => "Trang {page} / {pages}", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index ce0cfb3d48..738c19dbb1 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -424,6 +424,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Save the workbook under another name or in another folder." => "以其他名称或在其他文件夹中保存工作簿。", "Print Active Sheets" => "打印活动工作表", "Print Entire Workbook" => "打印整个工作簿", + "Print Selection" => "打印选定区域", "Fit Sheet on One Page" => "将工作表调整为一页", "Page Setup…" => "页面设置…", "Page {page} of {pages}" => "第 {page} 页,共 {pages} 页", diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index d3f35427a2..1e9544da54 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -196,6 +196,8 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) { ("100% Stacked Bar", "bar", "stacked100"), ("Line", "line", "markers"), ("Stacked Line", "line", "stacked"), + ("100% Stacked Line", "line", "stacked100"), + ("100% Stacked Line with Markers", "line", "stacked100Markers"), ("Area", "area", ""), ("Stacked Area", "area", "stacked"), ("100% Stacked Area", "area", "stacked100"), diff --git a/crates/ui-egui/src/ribbon/insert.rs b/crates/ui-egui/src/ribbon/insert.rs index b29257c769..d1f21af778 100644 --- a/crates/ui-egui/src/ribbon/insert.rs +++ b/crates/ui-egui/src/ribbon/insert.rs @@ -96,6 +96,8 @@ pub(super) fn insert(app: &mut SheetApp, ui: &mut Ui) { ("Line", "line", ""), ("Line with Markers", "line", "markers"), ("Stacked Line", "line", "stacked"), + ("100% Stacked Line", "line", "stacked100"), + ("100% Stacked Line with Markers", "line", "stacked100Markers"), ("Area", "area", ""), ("Stacked Area", "area", "stacked"), ("100% Stacked Area", "area", "stacked100"), diff --git a/crates/ui-egui/tests/it/cascading_filter_values.rs b/crates/ui-egui/tests/it/cascading_filter_values.rs new file mode 100644 index 0000000000..da6cc24d35 --- /dev/null +++ b/crates/ui-egui/tests/it/cascading_filter_values.rs @@ -0,0 +1,346 @@ +use crate::common; + +use egui::{Event, Key, Modifiers, PointerButton}; +use egui_kittest::kittest::{NodeT, Queryable}; +use gridcraft_engine::Session; +use gridcraft_engine::core::CellRef; +use gridcraft_engine::model::{ObjKind, ObjRef}; +use gridcraft_ui_egui::grid; +use serde_json::json; + +fn key(h: &mut common::Harness, key: Key, modifiers: Modifiers) { + for pressed in [true, false] { + h.input_mut().events.push(Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }); + } + h.run_steps(3); +} + +fn click_filter(h: &mut common::Harness, cell: &str) { + let app = h.state(); + let sh = app.session.active().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let at = grid::filter_button_rect(&geo, sh, CellRef::parse(cell).unwrap()).center(); + h.input_mut().events.push(Event::PointerMoved(at)); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.run_steps(3); +} + +#[test] +fn a_header_only_tables_popup_has_no_value_choices() { + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": "B3", "values": [["Company", "Job"]]})).unwrap(); + session.execute("insert.table", json!({"range": "B3:C3", "header": true})).unwrap(); + session.execute("selection.set", json!({"cell": "B3"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + click_filter(&mut h, "B3"); + assert_eq!(h.state().grid.filter_menu.map(|(col, row, _)| (col, row)), Some((1, 2))); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + assert_eq!(sh.tables[0].range.height(), 1); + assert_eq!(sh.autofilter.as_ref().unwrap().range.a1(), "B3:C3"); + assert_eq!(h.state().grid.filter_checks, Some(vec![])); + assert!(h.query_by_label("(Blanks)").is_none()); + key(&mut h, Key::Escape, Modifiers::NONE); + assert!(h.state().grid.filter_menu.is_none()); +} + +#[test] +fn switching_filter_columns_discards_old_edits_and_recomputes_eligible_choices() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"] + ]}), + ) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.get_by_label("Other").click(); + h.run_steps(2); + assert!(h.state().grid.filter_search.is_empty()); + + click_filter(&mut h, "A1"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + assert!(h.state().grid.filter_search.is_empty(), "the new column starts without the old search"); + assert!(h.query_by_label("East").is_some(), "the new column's choices must remain available"); + click_filter(&mut h, "B1"); + assert_eq!(h.get_by_label("Other").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "old checkbox edits are discarded"); + click_filter(&mut h, "A1"); + h.get_by_label("West").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(3); + click_filter(&mut h, "B1"); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_some(), "eligible alternatives must remain available"); + assert!(h.query_by_label("Other").is_none(), "the other column's new criterion must narrow the reopened list"); +} + +#[test] +fn switching_filter_columns_keeps_another_windows_pending_choices() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"] + ]}), + ) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let image = std::env::var("GRIDCRAFT_FILTER_WINDOW_SNAPSHOT").ok(); + let builder = common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)); + let builder = if image.is_some() { builder.wgpu() } else { builder }; + let mut h = common::harness_with(builder, common::app(session), 4); + let first = h.state().session.active_window().unwrap(); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.state_mut().run("view.newWindow", json!({})).unwrap(); + h.run_steps(3); + let second = h.state().session.active_window().unwrap(); + assert_ne!(first, second); + assert_eq!(h.state().session.documents().len(), 1, "two windows on the same workbook"); + click_filter(&mut h, "B1"); + h.input_mut().events.push(Event::Text("Bet".into())); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + assert!(h.query_by_label("Alpha").is_none()); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = &image { + h.render().unwrap().save(std::path::Path::new(path).with_extension("before.png")).unwrap(); + } + + h.state_mut().enter_window(first); + h.run_steps(2); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1)); + click_filter(&mut h, "A1"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + h.state_mut().enter_window(second); + h.run_steps(3); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1)); + assert!(h.query_by_label("Alpha").is_none(), "switching the other window's column must keep this search"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False), "its unsaved checkbox stays unchecked"); + if let Some(path) = image { + h.render().unwrap().save(path).unwrap(); + } + assert!(h.state().session.active().unwrap().wb.active().unwrap().autofilter.as_ref().unwrap().criteria.is_empty(), "no filter was applied"); +} + +#[test] +fn a_form_button_window_switch_keeps_the_incoming_filter_edits() { + let mut session = Session::new(); + session.new_workbook(); + session + .execute("range.setValues", json!({"range": "A1", "values": [["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"]]})) + .unwrap(); + session.execute("data.filter", json!({"range": "A1:B4"})).unwrap(); + let button = session.execute("insert.button", json!({"at": "E12", "text": "Other window"})).unwrap()["control"].as_u64().unwrap() as u32; + let image = std::env::var("GRIDCRAFT_FILTER_BUTTON_WINDOW_SNAPSHOT").ok(); + let builder = common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)); + let builder = if image.is_some() { builder.wgpu() } else { builder }; + let mut h = common::harness_with(builder, common::app(session), 4); + let first = h.state().session.active_window().unwrap(); + click_filter(&mut h, "A1"); + h.state_mut().run("view.newWindow", json!({})).unwrap(); + h.run_steps(3); + let second = h.state().session.active_window().unwrap(); + h.state_mut().run("control.assign", json!({"id": button, "command": "view.switchWindows", "params": {"window": second}})).unwrap(); + click_filter(&mut h, "B1"); + h.input_mut().events.push(Event::Text("Bet".into())); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + let checks = h.state().grid.filter_checks.clone(); + assert_eq!(h.state().grid.filter_search, "Bet"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = &image { + h.render().unwrap().save(std::path::Path::new(path).with_extension("before.png")).unwrap(); + } + + h.state_mut().enter_window(first); + h.run_steps(2); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(0)); + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + let geo = grid::Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let at = gridcraft_ui_egui::chartview::object_rect(&geo, sh, ObjRef::new(ObjKind::Control, button)).unwrap().center(); + for pressed in [true, false] { + h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE)); + h.input_mut().events.push(Event::PointerMoved(at)); + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + assert_eq!(h.state().session.active_window(), Some(second), "the real button action switches windows during grid interaction"); + assert_eq!(h.state().grid.filter_menu.map(|(col, _, _)| col), Some(1)); + assert_eq!(h.state().grid.filter_search, "Bet", "the outgoing popup must not clear the incoming search"); + assert_eq!(h.state().grid.filter_checks, checks, "the incoming window keeps its unsaved checkbox edits"); + assert_eq!(h.get_by_label("Beta").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + if let Some(path) = image { + h.render().unwrap().save(path).unwrap(); + } +} + +#[test] +fn applying_eligible_choices_preserves_values_and_blanks_hidden_by_another_filter() { + for table in [false, true] { + for click in [false, true] { + for edit in [false, true] { + for (values, blanks, other_hidden, blank_hidden) in + [(vec!["Alpha", "Other"], false, false, true), (vec!["Alpha", "Beta"], false, true, true), (vec!["Alpha"], true, true, false)] + { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"], ["West", null] + ]}), + ) + .unwrap(); + if table { + session.execute("insert.table", json!({"range": "A1:B5", "header": true})).unwrap(); + } else { + session.execute("data.filter", json!({"range": "A1:B5"})).unwrap(); + } + session.execute("data.filterBy", json!({"column": "B", "values": values, "blanks": blanks})).unwrap(); + session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.query_by_label("Other").is_none()); + assert!(h.query_by_label("(Blanks)").is_none()); + if edit { + h.get_by_label("Beta").click(); + h.run_steps(2); + } + if click { + h.get_by_label("Apply").click(); + h.run_steps(3); + } else { + key(&mut h, Key::Enter, Modifiers::NONE); + } + assert!(h.state().grid.filter_menu.is_none()); + h.state_mut().run("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + let beta_hidden = values.contains(&"Beta") == edit; + assert_eq!( + (1..=4).map(|row| sh.is_row_hidden(row)).collect::>(), + [false, beta_hidden, other_hidden, blank_hidden], + "table={table}, click={click}, edit={edit}, values={values:?}" + ); + } + } + } + } +} + +#[test] +fn search_apply_excludes_hidden_nonmatches_and_keeps_hidden_matches() { + for click in [false, true] { + for beta in [false, true] { + let mut session = Session::new(); + session.new_workbook(); + let mut values = vec![json!(["Company", "Job"]), json!(["East", "Alpha"])]; + if beta { + values.push(json!(["East", "Beta"])); + } + values.extend([json!(["West", "Alphonse"]), json!(["West", "Other"]), json!(["West", null])]); + let last = values.len() - 1; + session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + session.execute("data.filter", json!({"range": format!("A1:B{}", last + 1)})).unwrap(); + session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let mut h = common::os_harness(session, egui::os::OperatingSystem::Windows); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.query_by_label("Other").is_none()); + assert!(h.query_by_label("Alphonse").is_none()); + h.input_mut().events.push(Event::Text("Alph".into())); + h.run_steps(2); + assert_eq!(h.state().grid.filter_search, "Alph"); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_none()); + if click { + h.get_by_label("Apply").click(); + h.run_steps(3); + } else { + key(&mut h, Key::Enter, Modifiers::NONE); + } + assert!(h.state().grid.filter_menu.is_none()); + h.state_mut().run("data.filterBy", json!({"column": "A", "clear": true})).unwrap(); + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + assert!(!sh.is_row_hidden(1), "Alpha must remain selected"); + assert!(!sh.is_row_hidden((last - 2) as u32), "hidden Alphonse must still match the search"); + assert!(sh.is_row_hidden((last - 1) as u32), "hidden Other must be excluded: click={click}, beta={beta}"); + assert!(sh.is_row_hidden(last as u32), "hidden blanks do not match the search"); + if beta { + assert!(sh.is_row_hidden(2), "eligible Beta does not match the search"); + } + } + } +} + +#[test] +fn dropdown_can_change_and_clear_a_column_while_another_filter_stays_active() { + for table in [false, true] { + let mut session = Session::new(); + session.new_workbook(); + session + .execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["Company", "Job"], ["East", "Alpha"], ["East", "Beta"], ["West", "Other"], ["East", null] + ]}), + ) + .unwrap(); + if table { + session.execute("insert.table", json!({"range": "A1:B5", "header": true})).unwrap(); + } + session.execute("data.filterBy", json!({"column": "A", "values": ["East"]})).unwrap(); + session.execute("data.filterBy", json!({"column": "B", "values": ["Alpha"]})).unwrap(); + session.execute("selection.set", json!({"cell": "B1"})).unwrap(); + let screenshot = std::env::var("GRIDCRAFT_CASCADING_SNAPSHOT").ok().filter(|_| !table); + let mut h = if screenshot.is_some() { + common::harness_with( + common::builder().with_os(egui::os::OperatingSystem::Windows).with_size(egui::vec2(1200.0, 800.0)).wgpu(), + common::app(session), + 4, + ) + } else { + common::os_harness(session, egui::os::OperatingSystem::Windows) + }; + key(&mut h, Key::ArrowDown, Modifiers::ALT); + assert!(h.query_by_label("Alpha").is_some()); + assert!(h.query_by_label("Beta").is_some(), "current-column filtering must not remove alternatives"); + assert!(h.query_by_label("(Blanks)").is_some()); + assert!(h.query_by_label("Other").is_none(), "the other company's job must not be listed"); + if let Some(path) = screenshot { + h.render().unwrap().save(path).unwrap(); + } + h.get_by_label("Alpha").click(); + h.run_steps(2); + h.get_by_label("Beta").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(3); + let hidden = |h: &common::Harness| { + let sh = h.state().session.active().unwrap().wb.active().unwrap(); + (1..=4).map(|row| sh.is_row_hidden(row)).collect::>() + }; + assert_eq!(hidden(&h), [true, false, true, true]); + key(&mut h, Key::ArrowDown, Modifiers::ALT); + h.get_by_label("Clear Filter").click(); + h.run_steps(3); + assert_eq!(hidden(&h), [false, false, true, false], "clearing Job keeps Company filtered"); + } +} diff --git a/crates/ui-egui/tests/it/format_chart_type.rs b/crates/ui-egui/tests/it/format_chart_type.rs index 8fe695b069..a445b6270d 100644 --- a/crates/ui-egui/tests/it/format_chart_type.rs +++ b/crates/ui-egui/tests/it/format_chart_type.rs @@ -89,3 +89,14 @@ fn chart_type_marks_the_chart_s_current_type() { } } } + +#[test] +fn chart_type_offers_and_marks_the_hundred_percent_stacked_line_types() { + let (mut h, id) = open_chart_type("line", "stacked100Markers"); + assert!(marked(&h, "100% Stacked Line with Markers")); + assert!(!marked(&h, "100% Stacked Line")); + click(&mut h, "100% Stacked Line"); + assert_eq!(kind(&h, id), ChartKind::LineStacked100); + click(&mut h, "100% Stacked Line with Markers"); + assert_eq!(kind(&h, id), ChartKind::LineStacked100Markers); +} diff --git a/crates/ui-egui/tests/it/header_autofit.rs b/crates/ui-egui/tests/it/header_autofit.rs index a6bce5bf17..7597b73798 100644 --- a/crates/ui-egui/tests/it/header_autofit.rs +++ b/crates/ui-egui/tests/it/header_autofit.rs @@ -286,13 +286,16 @@ fn table_filter_autofit_works_through_command_and_header_double_click() { let cell = gridcraft_engine::core::CellRef::new(0, 0); let rect = geo.cell_rect(sheet, cell); let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell); - let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell)); + // The heading as the grid draws it: in the table style's font, bold in the header row. // Measured as AutoFit measured it, with the app's fonts (they differ from machine to // machine). The app installs them before AutoFit runs; AutoFit without them, on the // engine's estimate, is `autofit_filter_buttons` in the engine's tests. + let wb = &app.session.active().unwrap().wb; + let table = sheet.table_at(cell).expect("A1 is the table's header"); + let font = gridcraft_engine::tables::table_cell_style(wb, wb.active_sheet(), table, cell).font; + assert!(font.bold, "the table style draws its header bold"); let measure = app.session.text_width.as_ref().expect("the app measures text with its fonts"); - let measured = measure("Quarterly Revenue", &style.font, true); - let text_width = measured * geo.z; + let text_width = measure("Quarterly Revenue", &font, true) * geo.z; assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}"); assert_eq!(app.session.active().unwrap().undo.len(), 1); h.state_mut().session.execute("edit.undo", json!({})).unwrap(); diff --git a/crates/ui-egui/tests/it/interaction.rs b/crates/ui-egui/tests/it/interaction.rs index 3bc51f888b..20f251f9ac 100644 --- a/crates/ui-egui/tests/it/interaction.rs +++ b/crates/ui-egui/tests/it/interaction.rs @@ -539,6 +539,29 @@ fn insert_column_or_bar_menu_inserts_a_hundred_percent_stacked_bar() { assert_eq!(kinds, [gridcraft_engine::model::ChartKind::BarStacked100]); } +#[test] +fn insert_line_or_area_menu_inserts_hundred_percent_stacked_lines() { + // Insert › Line or Area (keytip N, N1) lists both 100% stacked line types. + let mut s = blank(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", 10, 30], ["Q2", 30, 10]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:C3"})).unwrap(); + let mut h = harness(s); + for label in ["100% Stacked Line", "100% Stacked Line with Markers"] { + key(&mut h, Key::F10, Modifiers::NONE); + for (k, t) in [(Key::N, "n"), (Key::N, "n"), (Key::Num1, "1")] { + h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.input_mut().events.push(Event::Text(t.into())); + h.input_mut().events.push(Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + h.run_steps(2); + h.get_by_role_and_label(egui::accesskit::Role::Button, label).click(); + h.run_steps(2); + } + let kinds: Vec<_> = h.state().session.active().unwrap().wb.active().unwrap().charts.iter().map(|c| c.kind).collect(); + assert_eq!(kinds, [gridcraft_engine::model::ChartKind::LineStacked100, gridcraft_engine::model::ChartKind::LineStacked100Markers]); +} + #[test] /// Every main ribbon tab and dark mode render with accessibility checks. fn renders_every_ribbon_tab_without_panicking() { @@ -754,6 +777,24 @@ fn all_charts_inserts_a_hundred_percent_stacked_area() { assert_eq!(kinds, [gridcraft_engine::model::ChartKind::AreaStacked100]); } +#[test] +fn all_charts_inserts_a_hundred_percent_stacked_line_with_markers() { + let mut s = blank(); + s.execute("range.setValues", json!({"range": "A1", "values": [["Quarter", "North", "South"], ["Q1", 10, 30], ["Q2", 30, 10]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:C3"})).unwrap(); + let mut h = harness(s); + h.state_mut().open_dialog("recommendedCharts", json!({"tab": "All Charts"})); + h.run_steps(4); + assert!(h.query_by_label("100% Stacked Line").is_some(), "the list has 100% Stacked Line"); + h.get_by_label("100% Stacked Line with Markers").click(); + h.run_steps(2); + key(&mut h, Key::Enter, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().dialog.is_none()); + let kinds: Vec<_> = h.state().session.active().unwrap().wb.active().unwrap().charts.iter().map(|c| c.kind).collect(); + assert_eq!(kinds, [gridcraft_engine::model::ChartKind::LineStacked100Markers]); +} + #[test] fn recommended_charts_command_without_a_type_opens_the_dialog() { // #1399: the ribbon button and the NR keytip ran the command directly and inserted the first diff --git a/crates/ui-egui/tests/it/keyboard_shortcuts.rs b/crates/ui-egui/tests/it/keyboard_shortcuts.rs index 7c508ce6bf..87b8ab7108 100644 --- a/crates/ui-egui/tests/it/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/it/keyboard_shortcuts.rs @@ -375,7 +375,7 @@ fn alt_down_opens_autofilter_headers_without_changing_the_workbook() { // Opening focuses the existing search box; typing must not edit the header. h.input_mut().events.push(Event::Text("1".into())); h.run_steps(2); - assert_eq!(h.ctx.data(|data| data.get_temp::(egui::Id::unique(("filter_search", column)))).as_deref(), Some("1")); + assert_eq!(h.state().grid.filter_search, "1"); assert!(h.state().editor.is_none()); assert_eq!(h.state().session.active().unwrap().wb, before); key(&mut h, Key::Escape, Modifiers::NONE); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d014cbfdb7..b3d966b14b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -13,6 +13,7 @@ mod argument_names; mod autosave_persist; mod autosum_edit; mod borders; +mod cascading_filter_values; mod cell_editor_caret; mod cell_pictures; mod cf_rule_pick; diff --git a/crates/ui-egui/tests/print_selection.rs b/crates/ui-egui/tests/print_selection.rs new file mode 100644 index 0000000000..f715ea043f --- /dev/null +++ b/crates/ui-egui/tests/print_selection.rs @@ -0,0 +1,78 @@ +//! File › Print › Settings offers "Print Selection": only the selected cells are previewed and sent. +use std::{cell::RefCell, rc::Rc}; + +use egui_kittest::kittest::Queryable as _; +use gridcraft_engine::Session; +use gridcraft_ui_egui::{Services, SheetApp}; +use serde_json::json; + +fn contains(hay: &[u8], needle: &str) -> bool { + hay.windows(needle.len()).any(|w| w == needle.as_bytes()) +} + +/// A sheet whose print area (F10:H20, "Outside") is not where the selection (A1:B2, "Inside") is, +/// so printing the selection and printing the sheet give different pages. +fn harness(jobs: Rc>>>) -> egui_kittest::Harness<'static, SheetApp> { + let mut session = Session::new(); + session.new_workbook(); + let mut app = SheetApp::new(session, Services::default()); + app.run("cell.set", json!({"cell": "A1", "input": "Inside"})).unwrap(); + app.run("cell.set", json!({"cell": "D4", "input": "Second area"})).unwrap(); + app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap(); + app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap(); + app.run("selection.set", json!({"range": "A1:B2"})).unwrap(); + app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec()))); + app.run("ui.backstage", json!({"page": "print"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn choose_selection(h: &mut egui_kittest::Harness<'static, SheetApp>) { + h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("print scope combo").click(); + h.run_steps(3); + h.get_by_label("Print Selection").click(); + h.run_steps(4); +} + +#[test] +fn print_selection_previews_and_prints_only_the_selected_cells() { + let jobs = Rc::new(RefCell::new(Vec::new())); + let mut h = harness(jobs.clone()); + assert!(h.query_by_label("Sheet1 · F10:H20").is_some(), "the sheet prints its print area by default"); + choose_selection(&mut h); + assert!(h.query_by_label("Sheet1 · A1:B2").is_some(), "the preview shows the selection"); + assert!(h.query_by_label("Sheet1 · F10:H20").is_none()); + + h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click(); + h.run_steps(3); + let jobs = jobs.borrow(); + assert_eq!(jobs.len(), 1); + assert!(contains(&jobs[0], "(Inside) Tj"), "the selected cell is printed"); + assert!(!contains(&jobs[0], "(Outside) Tj"), "the print area is not"); +} + +#[test] +fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() { + let jobs = Rc::new(RefCell::new(Vec::new())); + let mut h = harness(jobs.clone()); + choose_selection(&mut h); + assert!(h.query_by_label("Sheet1 · A1:B2").is_some()); + + // Same document revision, other selection: the cached preview must not be reused. + h.state_mut().run("selection.set", json!({"range": "D4:E5"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label("Sheet1 · D4:E5").is_some(), "the preview is rebuilt for the new selection"); + assert!(h.query_by_label("Sheet1 · A1:B2").is_none()); + + // Two selected areas: Excel prints each area on its own page. + h.state_mut().run("selection.set", json!({"range": "A1:B2,D4:E5"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages"); +} diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index f8511d6232..4408de8646 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -54,7 +54,16 @@ pub(crate) fn map_dml_color(c: &DmlColor) -> Option { } } +/// Whether a line group draws markers: the group's `c:marker` is on (or missing) and not every +/// series hides its marker. +fn line_group_markers(g: &El) -> bool { + let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); + let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none")); + group_markers && !(all_none && g.kids("ser").next().is_some()) +} + fn map_chart_type(k: ChartType, plot: Option<&El>) -> ChartKind { + let line_groups = || plot.into_iter().flat_map(|p| p.kids("lineChart").chain(p.kids("line3DChart"))); match k { ChartType::Column => ChartKind::ColumnClustered, ChartType::StackedColumn => ChartKind::ColumnStacked, @@ -63,19 +72,22 @@ fn map_chart_type(k: ChartType, plot: Option<&El>) -> ChartKind { ChartType::StackedBar => ChartKind::BarStacked, ChartType::PercentBar => ChartKind::BarStacked100, ChartType::Line => { - let markers = plot - .into_iter() - .flat_map(|p| p.kids("lineChart").chain(p.kids("line3DChart"))) - .filter(|g| !matches!(g.child_val("grouping"), Some("stacked" | "percentStacked"))) - .any(|g| { - let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); - let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none")); - group_markers && !(all_none && g.kids("ser").next().is_some()) - }); + let markers = line_groups().filter(|g| !matches!(g.child_val("grouping"), Some("stacked" | "percentStacked"))).any(line_group_markers); if markers { ChartKind::LineMarkers } else { ChartKind::Line } } ChartType::LineMarkers => ChartKind::LineMarkers, - ChartType::StackedLine => ChartKind::LineStacked, + // `percentStacked` and `stacked` line groups both read as stacked lines; the grouping + // tells them apart. + ChartType::StackedLine => { + let pct: Vec<&El> = line_groups().filter(|g| g.child_val("grouping") == Some("percentStacked")).collect(); + if pct.is_empty() { + ChartKind::LineStacked + } else if pct.iter().any(|g| line_group_markers(g)) { + ChartKind::LineStacked100Markers + } else { + ChartKind::LineStacked100 + } + } ChartType::Area => ChartKind::Area, ChartType::StackedArea => { let pct = plot @@ -214,15 +226,17 @@ fn group_kind(g: &El) -> Option { } } "lineChart" | "line3DChart" => { - if stacked || pct { + if stacked { ChartKind::LineStacked } else { // The group's kind is its first series' (each series may differ; see // `series_kind_in`). + let (plain, marked) = + if pct { (ChartKind::LineStacked100, ChartKind::LineStacked100Markers) } else { (ChartKind::Line, ChartKind::LineMarkers) }; match g.kids("ser").next() { - Some(first) => series_kind_in(g, ChartKind::LineMarkers, first), - None if g.child_val("marker").is_some_and(|v| v == "0" || v == "false") => ChartKind::Line, - None => ChartKind::LineMarkers, + Some(first) => series_kind_in(g, marked, first), + None if g.child_val("marker").is_some_and(|v| v == "0" || v == "false") => plain, + None => marked, } } } @@ -249,15 +263,20 @@ fn group_kind(g: &El) -> Option { }) } -/// The kind series `s` of group `g` (of kind `k`) is drawn as: in a line group its own markers -/// (none when it says so), in a scatter group its own lines; otherwise the group's. +/// The kind series `s` of group `g` (of kind `k`) is drawn as: in a line or 100% stacked line +/// group its own markers (none when it says so), in a scatter group its own lines; otherwise +/// the group's. fn series_kind_in(g: &El, k: ChartKind, s: &El) -> ChartKind { + let marked = || { + let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); + let none = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); + group_markers && !none + }; match k { - ChartKind::Line | ChartKind::LineMarkers => { - let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); - let none = s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none"); - if group_markers && !none { ChartKind::LineMarkers } else { ChartKind::Line } - } + ChartKind::Line | ChartKind::LineMarkers if marked() => ChartKind::LineMarkers, + ChartKind::Line | ChartKind::LineMarkers => ChartKind::Line, + ChartKind::LineStacked100 | ChartKind::LineStacked100Markers if marked() => ChartKind::LineStacked100Markers, + ChartKind::LineStacked100 | ChartKind::LineStacked100Markers => ChartKind::LineStacked100, ChartKind::Scatter | ChartKind::ScatterLines if g.child_val("scatterStyle") != Some("marker") => { if s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some()) { ChartKind::Scatter } else { ChartKind::ScatterLines } } @@ -468,7 +487,7 @@ pub fn read_chart(root: &El) -> Option { #[derive(Clone, Copy, PartialEq)] enum G { Bar { bar: bool, grouping: &'static str }, - Line { stacked: bool, markers: bool }, + Line { grouping: &'static str, markers: bool }, Pie, Doughnut, Area { grouping: &'static str }, @@ -510,7 +529,7 @@ fn fit_axes(g: G, family: Axes) -> G { let line_like = matches!(g, G::Line { .. } | G::Area { .. } | G::Radar | G::Scatter { .. }); match family { Axes::None => g, - Axes::Category if line_like => G::Line { stacked: false, markers: false }, + Axes::Category if line_like => G::Line { grouping: "standard", markers: false }, Axes::Category => G::Bar { bar: false, grouping: "clustered" }, Axes::Horizontal => G::Bar { bar: true, grouping: "clustered" }, Axes::Values => G::Scatter { lines: true }, @@ -524,9 +543,11 @@ fn group_for(k: ChartKind) -> G { ChartKind::BarClustered => G::Bar { bar: true, grouping: "clustered" }, ChartKind::BarStacked => G::Bar { bar: true, grouping: "stacked" }, ChartKind::BarStacked100 => G::Bar { bar: true, grouping: "percentStacked" }, - ChartKind::Line => G::Line { stacked: false, markers: false }, - ChartKind::LineMarkers => G::Line { stacked: false, markers: true }, - ChartKind::LineStacked => G::Line { stacked: true, markers: false }, + ChartKind::Line => G::Line { grouping: "standard", markers: false }, + ChartKind::LineMarkers => G::Line { grouping: "standard", markers: true }, + ChartKind::LineStacked => G::Line { grouping: "stacked", markers: false }, + ChartKind::LineStacked100 => G::Line { grouping: "percentStacked", markers: false }, + ChartKind::LineStacked100Markers => G::Line { grouping: "percentStacked", markers: true }, ChartKind::Pie => G::Pie, ChartKind::Doughnut => G::Doughnut, ChartKind::Area => G::Area { grouping: "standard" }, @@ -752,7 +773,7 @@ fn multi_level_cat(f: &str, values: &str, wb: &Workbook, si: usize) -> Option String { let g = match (g, group_for(own)) { - (G::Line { stacked, .. }, G::Line { markers, .. }) => G::Line { stacked, markers }, + (G::Line { grouping, .. }, G::Line { markers, .. }) => G::Line { grouping, markers }, (G::Scatter { .. }, mine @ G::Scatter { .. }) => mine, _ => g, }; @@ -902,9 +923,8 @@ fn group_xml(g: G, series: &[(usize, &Series)], kinds: &[ChartKind], ch: &Chart, ) } // Each series states its own markers; an empty group's say whether the chart has them. - G::Line { stacked, markers } => format!( - "{sers}{dl}{ax}", - if stacked { "stacked" } else { "standard" }, + G::Line { grouping, markers } => format!( + "{sers}{dl}{ax}", u8::from(markers || !series.is_empty()) ), G::Pie => format!("{sers}{dl}", ch.first_slice_angle % 360), @@ -1010,7 +1030,7 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str let stock = ch.kind == ChartKind::Stock; let kinds = ch.series_kinds(); let group_of = |i: usize| match group_for(kinds.get(i).copied().unwrap_or(ChartKind::ColumnClustered)) { - G::Line { stacked, .. } => G::Line { stacked, markers: false }, + G::Line { grouping, .. } => G::Line { grouping, markers: false }, G::Scatter { .. } => G::Scatter { lines: true }, g => g, }; @@ -1037,7 +1057,7 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str // A stock group holds 3 or 4 series (high-low-close, open-high-low-close); others are // lines, which join a line group already there rather than setting its grouping. let (out, stock_lines): (Vec<_>, Vec<_>) = out.into_iter().partition(|(g, m)| *g != G::Stock || (3..=4).contains(&m.len())); - let stock_lines = stock_lines.into_iter().map(|(_, m)| (G::Line { stacked: false, markers: false }, m)); + let stock_lines = stock_lines.into_iter().map(|(_, m)| (G::Line { grouping: "standard", markers: false }, m)); // One group per type on a pair of axes (as Excel keeps them; `Chart::series_kind` gives // the series of one type one grouping). Groups that fit the axes come first, so a group // moved onto them joins one of its type there rather than setting its grouping. @@ -1065,7 +1085,7 @@ pub fn write_chart(wb: &Workbook, si: usize, ch: &Chart, book_name: &str) -> Str // stock group must hold series, so an empty stock chart has a line group). if primary.is_empty() { let g = match group_for(ch.kind) { - G::Stock => G::Line { stacked: false, markers: false }, + G::Stock => G::Line { grouping: "standard", markers: false }, g => g, }; primary.push((g, Vec::new())); diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index ce9ef5a658..87955432f5 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -300,9 +300,9 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook }, None => StyleId::DEFAULT, }; - Cell { value: p.value, formula: None, style, py: None } + Cell { value: gridcraft_core::cap_value(p.value), formula: None, style, py: None } } else { - Cell::value(Value::Text(Arc::from(f))) + Cell::value(Value::Text(Arc::from(gridcraft_core::cap_text(f)))) }; sheet.cells.set(pos, cell); } diff --git a/crates/xlsx/src/passthrough.rs b/crates/xlsx/src/passthrough.rs index 6ed3dd10a7..89d33af8f1 100644 --- a/crates/xlsx/src/passthrough.rs +++ b/crates/xlsx/src/passthrough.rs @@ -7,8 +7,14 @@ //! mapped to XML elements, form controls other than the buttons, scroll bars and spin buttons //! `controls.rs` models, ActiveX controls, OLE objects, the sheet background and printer settings, with the sheet's ``, `` and `` XML, the `r:id` //! of ``, the legacy VML shapes those controls need and the pictures of the headers and -//! footers, `&G`, with their ``). The workbook also keeps its -//! `` and the calcFeatures extension, which Excel needs to trust the saved values. +//! footers, `&G`, with their ``). The workbook's Data Model (`xl/model/item.data`) +//! is kept with its data connections. PivotTables whose source is in another workbook, a data +//! connection or the Data Model are kept too: the PivotTable parts with their sheet, the cache +//! definition and records parts (with the cache's link to the other workbook's path) with the +//! workbook and its `` entry, its `cacheId` unchanged; a cache on a connection only +//! when the connections are kept, and on the Data Model only when the model is kept. The workbook +//! also keeps its `` and the calcFeatures extension, which Excel needs to trust the +//! saved values. //! //! On write, kept parts get fresh part names where needed and new relationship ids; the `r:id`s in //! kept XML are rewritten to match. Kept content is conservative: @@ -19,6 +25,7 @@ //! opened, followed or refreshed. A relative path to a linked workbook is rewritten when the //! workbook is saved into another folder ([`rebase_links`]), so it still names the same file. //! - Sheet content lives on the sheet: deleting the sheet drops it, Copy Sheet doesn't copy it. +//! A kept pivot cache no kept PivotTable uses any more is dropped with it. //! Cell references inside kept parts (a control's linked cell, a query table's range, a cell //! mapped to an XML element) are kept as they were, not adjusted to inserted or deleted rows. //! - Strict Open XML files are not passed through (their namespaces differ from what we write). @@ -38,6 +45,7 @@ use quick_xml::{Reader, Writer}; use crate::IoError; use crate::package::{self, normalize}; +use crate::pivot::{CT_PIVOT_CACHE_DEF, CT_PIVOT_TABLE, ExternalPivot, KeptSource}; use crate::read::Ctx; use crate::write::{NS_REL, Out, Rels, XML_DECL}; use crate::xml::{self, esc_attr}; @@ -50,7 +58,7 @@ pub use read::KeptReader; pub use rebase::{SheetKept, rebase_links}; #[cfg(test)] pub(crate) use write::sheet_names_in; -pub use write::{KeptOut, SheetIds, WorkbookKept, workbook_elements, write_package_rels, write_workbook}; +pub use write::{KeptOut, SheetIds, WorkbookKept, finish_style_ids, workbook_elements, write_package_rels, write_workbook}; /// Most bytes kept for one workbook. pub const MAX_KEPT_TOTAL: usize = 256 * 1024 * 1024; @@ -101,6 +109,13 @@ const SHEET_ELEMENT_KINDS: &[&str] = &["oleObject", "ctrlProp", "control", "imag const FILE_VERSION_ATTRS: &[&str] = &["appName", "lastEdited", "lowestEdited", "rupBuild", "codeName"]; /// Kept sheet elements, in schema order (all after ``, before ``). const SHEET_SLOTS: &[&str] = &["legacyDrawingHF", "picture", "oleObjects", "controls"]; +/// Rewritten kinds a kept PivotTable (source in another workbook) reaches: the table, from the +/// sheet, and its cache, which the workbook keeps (several tables can share one cache). +const PIVOT_TABLE_GRAPH: &[&str] = &["pivotTable", "pivotCacheDefinition"]; +/// Rewritten kinds a kept pivot cache reaches. +const PIVOT_CACHE_GRAPH: &[&str] = &["pivotCacheDefinition", "pivotCacheRecords"]; +/// The workbook's Data Model part (Power Pivot), kept byte for byte when its connections are. +const DATA_MODEL_GRAPH: &[&str] = &["powerPivotData"]; /// Relationship kinds GridCraft reads and rewrites, or that depend on content it rewrites: /// kept content whose graph reaches one of them is dropped. @@ -166,6 +181,7 @@ const OWN_DIRS: &[&str] = &[ "xl/activex/", "xl/webextensions/", "xl/printersettings/", + "xl/model/", ]; fn kind(rel_type: &str) -> &str { diff --git a/crates/xlsx/src/passthrough/read.rs b/crates/xlsx/src/passthrough/read.rs index 1c95be10d0..a150de7f66 100644 --- a/crates/xlsx/src/passthrough/read.rs +++ b/crates/xlsx/src/passthrough/read.rs @@ -53,6 +53,9 @@ pub struct KeptReader { overrides: HashMap, budget: usize, parts_left: usize, + /// Cache definition parts of the PivotTables kept with their sheets (source in another + /// workbook, a data connection or the Data Model), kept with the workbook. + pivot_caches: Vec<(String, KeptSource)>, } impl KeptReader { @@ -69,6 +72,7 @@ impl KeptReader { overrides: HashMap::new(), budget: kept_total(), parts_left: MAX_KEPT_PARTS, + pivot_caches: vec![], }; if let Ok(root) = raw_rels(cx, "") && root.iter().any(|r| r.rel_type.starts_with("http://purl.oclc.org/")) @@ -146,7 +150,12 @@ impl KeptReader { } queue.push_back((r.target.clone(), depth + 1)); } - parts.push(PreservedPart { name, content_type, data: Arc::from(data), rels }); + let (dxfs, num_fmts) = if content_type == CT_PIVOT_TABLE || content_type == CT_PIVOT_CACHE_DEF { + style_refs(cx, &data).ok_or_else(|| format!("{name} is damaged"))? + } else { + (vec![], vec![]) + }; + parts.push(PreservedPart { name, content_type, data: Arc::from(data), rels, dxfs, num_fmts }); } self.budget = self.budget.saturating_sub(bytes); self.parts_left = self.parts_left.saturating_sub(parts.len()); @@ -217,6 +226,20 @@ impl KeptReader { cx.warn(format!("{} part {} was dropped: {why}", kind(&r.rel_type), r.target)); } } + // The Data Model: its tables are loaded through the workbook's connections, so it is kept + // only with them. + let connections = p.rels.iter().any(|r| is_kind(r, &["connections"])); + for r in wb_rels.iter().filter(|r| !r.external && is_kind(r, DATA_MODEL_GRAPH)).take(1) { + let kept = if connections { + self.keep_through(cx, &mut p, std::slice::from_ref(r), &mut seen, DATA_MODEL_GRAPH) + } else { + Err("the workbook's data connections were not kept".into()) + }; + match kept { + Ok(()) => cx.warn("the workbook's Data Model is kept for saving as it is; it can't be viewed, edited or refreshed here"), + Err(why) => cx.warn(format!("the workbook's Data Model was dropped: {why}")), + } + } // Chart sheets: the sheet entry (name, state, position) plus the chart sheet part and the // drawing, chart, style and colour parts behind it. for (worksheets, se) in chart_sheet_entries(wb_xml, &wb_rels, file_to_model) { @@ -261,6 +284,7 @@ impl KeptReader { Err(why) => cx.warn(format!("links to external workbooks were dropped: {why}")), } } + self.keep_pivot_caches(cx, wb_xml, &wb_rels, &mut p, &mut seen); // Excel trusts the saved cell values only when both are present; without them it // recalculates everything on open, and links into closed workbooks come back as errors. if let Some(v) = wb_xml.child("fileVersion") { @@ -278,11 +302,77 @@ impl KeptReader { (!p.is_empty()).then(|| Arc::new(p)) } - /// Sheet-level content of the sheet part `part`. `controls` says which form controls the + /// The caches of the kept PivotTables, each with its `` entry (original `cacheId` + /// and relationship id). + fn keep_pivot_caches(&mut self, cx: &mut Ctx<'_>, wb_xml: &xml::El, wb_rels: &[PreservedRel], p: &mut Preserved, seen: &mut HashSet) { + let caches = std::mem::take(&mut self.pivot_caches); + // A cache names its connection by id in the kept connections part, and a Data Model cache + // reads the kept model: without them Excel refuses the file or can't refresh it. + let connections = p.rels.iter().any(|r| is_kind(r, &["connections"])); + let model = p.rels.iter().any(|r| is_kind(r, DATA_MODEL_GRAPH)); + let (mut no_connections, mut no_model) = (0usize, 0usize); + for (cache, source) in &caches { + match source { + KeptSource::Connection | KeptSource::DataModel if !connections => { + no_connections += 1; + continue; + } + KeptSource::DataModel if !model => { + no_model += 1; + continue; + } + _ => {} + } + let entry = wb_xml.child("pivotCaches").into_iter().flat_map(|c| c.kids("pivotCache")).find_map(|c| { + let id = c.attr_u32("cacheId")?; + let r = wb_rels.iter().find(|r| Some(r.id.as_str()) == c.attr("id") && !r.external && is_kind(r, &["pivotCacheDefinition"]))?; + (normalize(&r.target) == normalize(cache)).then(|| (id, r.clone())) + }); + let Some((id, r)) = entry else { + cx.warn(format!( + "the cache {cache} of a PivotTable on {} is not in the workbook's list; the PivotTable was dropped", + source.describe() + )); + continue; + }; + match self.keep_through(cx, p, std::slice::from_ref(&r), seen, PIVOT_CACHE_GRAPH) { + Ok(()) => p.elements.push(PreservedXml { + slot: "pivotCache".into(), + xml: format!("", esc_attr(&r.id)), + }), + Err(why) => cx.warn(format!("the cache of a PivotTable on {} was dropped with its PivotTables: {why}", source.describe())), + } + } + if no_connections > 0 { + cx.warn(format!( + "{no_connections} PivotTable cache(s) on a data connection or the Data Model were dropped with their PivotTables (kept as plain cells): the workbook's data connections were not kept" + )); + } + if no_model > 0 { + cx.warn(format!( + "{no_model} PivotTable cache(s) on the workbook's Data Model were dropped with their PivotTables (kept as plain cells): the Data Model was not kept" + )); + } + } + + /// Sheet-level content of the sheet part `part`; `pivots` are its PivotTables whose source is + /// in another workbook. `controls` says which form controls the /// sheet reader modelled (their VML shapes are left out of the kept content) and whether the /// VML drawing holds others that only it lists. - pub fn sheet(&mut self, cx: &mut Ctx<'_>, part: &str, name: &str, controls: &crate::controls::ReadControls) -> Option> { + pub fn sheet( + &mut self, + cx: &mut Ctx<'_>, + part: &str, + name: &str, + pivots: &[ExternalPivot], + controls: &crate::controls::ReadControls, + ) -> Option> { if !self.on { + if !pivots.is_empty() { + cx.warn(format!( + "sheet \"{name}\": PivotTables on another workbook, a data connection or the Data Model are not kept on save in this file" + )); + } return None; } let rels = match raw_rels(cx, part) { @@ -305,6 +395,22 @@ impl KeptReader { if rels.iter().any(|r| is_kind(r, SHEET_ELEMENT_KINDS)) || vml_drawings > notes || controls.vml_only_unmodelled { self.sheet_elements(cx, part, name, &rels, &mut p, &mut seen, controls); } + for ep in pivots { + let Some(r) = rels.iter().find(|r| r.id == ep.rel_id && !r.external && is_kind(r, &["pivotTable"])) else { continue }; + // The cache is kept with the workbook, not followed from here. + let mut scoped = seen.clone(); + scoped.insert(normalize(&ep.cache_part)); + match self.keep_through(cx, &mut p, std::slice::from_ref(r), &mut scoped, PIVOT_TABLE_GRAPH) { + Ok(()) => { + scoped.remove(&normalize(&ep.cache_part)); + seen = scoped; + if !self.pivot_caches.iter().any(|(c, _)| normalize(c) == normalize(&ep.cache_part)) { + self.pivot_caches.push((ep.cache_part.clone(), ep.source)); + } + } + Err(why) => cx.warn(format!("sheet \"{name}\": a PivotTable on {} was dropped: {why}", ep.source.describe())), + } + } (!p.is_empty()).then(|| Arc::new(p)) } @@ -427,11 +533,68 @@ impl KeptReader { let mut q = Preserved::default(); let roots: Vec = vrels.iter().filter(|r| !r.external).cloned().collect(); self.keep(cx, &mut q, &roots, seen)?; - let vml = PreservedPart { name: rel.target.clone(), content_type: CT_VML.into(), data: Arc::from(text.into_bytes()), rels: vrels }; + let vml = PreservedPart { + name: rel.target.clone(), + content_type: CT_VML.into(), + data: Arc::from(text.into_bytes()), + rels: vrels, + ..Default::default() + }; Ok((vml, q.parts)) } } +/// Attribute values of `local` (any prefix) in an XML part, in document order. `None` when the +/// XML is damaged. +fn attr_values(data: &[u8], local: &[&[u8]], mut f: impl FnMut(&[u8], &str)) -> Option<()> { + let text = xml::to_utf8(data); + let mut reader = Reader::from_reader(text.as_ref()); + let mut buf = vec![]; + loop { + match reader.read_event_into(&mut buf).ok()? { + Event::Eof => return Some(()), + Event::Start(e) | Event::Empty(e) => { + for a in e.attributes().with_checks(false) { + let a = a.ok()?; + let k = a.key.local_name(); + if let Some(name) = local.iter().find(|n| **n == k.as_ref()) + && let Ok(v) = std::str::from_utf8(&a.value) + { + f(name, v); + } + } + } + _ => {} + } + buf.clear(); + } +} + +/// The differential formats (`dxfId`) and custom number formats (`numFmtId`) of the source +/// styles part a kept PivotTable or pivot cache refers to. `None` when its XML is damaged. +type StyleRefs = (Vec<(u32, gridcraft_model::Style)>, Vec<(u32, String)>); +fn style_refs(cx: &Ctx<'_>, data: &[u8]) -> Option { + let mut dxfs: Vec<(u32, gridcraft_model::Style)> = vec![]; + let mut fmts: Vec<(u32, String)> = vec![]; + // Membership sets: a crafted part can name many distinct ids, so scanning the vectors would be quadratic. + let (mut seen_dxfs, mut seen_fmts) = (HashSet::new(), HashSet::new()); + attr_values(data, &[b"dxfId", b"numFmtId"], |name, v| { + let Ok(id) = v.trim().parse::() else { return }; + if name == b"dxfId" { + if let Some(s) = cx.dxfs.get(id as usize) + && seen_dxfs.insert(id) + { + dxfs.push((id, s.clone())); + } + } else if let Some(code) = cx.num_fmts.get(&id) + && seen_fmts.insert(id) + { + fmts.push((id, code.clone())); + } + })?; + Some((dxfs, fmts)) +} + /// What a sheet part holds for pass-through. struct SheetScan { /// (slot, XML with the namespace declarations it needs). diff --git a/crates/xlsx/src/passthrough/rebase.rs b/crates/xlsx/src/passthrough/rebase.rs index e9232658dd..5535eb2b27 100644 --- a/crates/xlsx/src/passthrough/rebase.rs +++ b/crates/xlsx/src/passthrough/rebase.rs @@ -13,8 +13,33 @@ impl<'a> SheetKept<'a> { /// Writes the sheet's kept parts and adds their relationships to the sheet's. pub fn write(sheet: &'a Sheet, rels: &mut Rels, out: &mut Out) -> SheetKept<'a> { let Some(p) = sheet.preserved.as_deref() else { return SheetKept { p: None, names: NameMap::new(), ids: HashMap::new() } }; - let names = write_parts(out, &p.parts); - let ids = attach(rels, &p.rels, &names); + // A kept PivotTable whose cache wasn't kept with the workbook is left out. + let (wb_names, cache_ids) = (&out.kept.wb_names, &out.kept.cache_ids); + let orphan: HashSet = p + .parts + .iter() + .filter(|q| { + let direct = q.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"])); + // A table with no relationship to its cache names it by `cacheId` instead. + let by_id = || { + q.content_type == CT_PIVOT_TABLE + && crate::xml::parse(&q.data).ok().and_then(|x| x.attr_u32("cacheId")).is_some_and(|id| !cache_ids.contains(&id)) + }; + let direct_is_orphan = direct.into_iter().any(|r| !wb_names.contains_key(&normalize(&r.target))); + direct_is_orphan || by_id() + }) + .map(|q| normalize(&q.name)) + .collect(); + let (parts, sheet_rels): (Cow<'_, [PreservedPart]>, Cow<'_, [PreservedRel]>) = if orphan.is_empty() { + (Cow::Borrowed(&p.parts), Cow::Borrowed(&p.rels)) + } else { + ( + p.parts.iter().filter(|q| !orphan.contains(&normalize(&q.name))).cloned().collect(), + p.rels.iter().filter(|r| r.external || !orphan.contains(&normalize(&r.target))).cloned().collect(), + ) + }; + let names = write_parts(out, &parts); + let ids = attach(rels, &sheet_rels, &names); SheetKept { p: Some(p), names, ids } } diff --git a/crates/xlsx/src/passthrough/write.rs b/crates/xlsx/src/passthrough/write.rs index 1670c66bb5..2217cc8a41 100644 --- a/crates/xlsx/src/passthrough/write.rs +++ b/crates/xlsx/src/passthrough/write.rs @@ -12,6 +12,13 @@ pub struct KeptOut { vml_blocks: u32, /// Package-root relationships (type, target, external), added when `_rels/.rels` is written. root: Vec<(String, String, bool)>, + /// Names of the workbook's kept parts, which sheets' kept parts can refer to (the cache of a + /// kept PivotTable). + pub(super) wb_names: NameMap, + /// The `cacheId`s of the workbook's kept pivot caches: a kept PivotTable that names its cache + /// only by id is written only when its cache is among them. + pub(super) cache_ids: HashSet, + patches: StylePatches, } impl KeptOut { @@ -60,6 +67,79 @@ impl KeptOut { } } +/// Rewrites the values of `dxfId` and `numFmtId` attributes through the maps (ids not in a map +/// are kept). `None` when the XML is damaged. +fn map_style_ids(data: &[u8], dxfs: &HashMap, fmts: &HashMap) -> Option> { + let text = xml::to_utf8(data); + let mut reader = Reader::from_reader(text.as_ref()); + let mut writer = Writer::new(Vec::with_capacity(data.len())); + let mut buf = vec![]; + let map = |e: &BytesStart<'_>| -> Option> { + let name = String::from_utf8(e.name().as_ref().to_vec()).ok()?; + let mut out = BytesStart::new(name); + for a in e.attributes().with_checks(false) { + let a = a.ok()?; + let k = a.key.local_name(); + let table = match k.as_ref() { + b"dxfId" => Some(dxfs), + b"numFmtId" => Some(fmts), + _ => None, + }; + let new = table.and_then(|t| std::str::from_utf8(&a.value).ok()?.trim().parse::().ok().and_then(|id| t.get(&id))); + match new { + Some(n) => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(n.to_string().into_bytes()) }), + None => out.push_attribute(Attribute { key: a.key, value: Cow::Owned(a.value.to_vec()) }), + } + } + Some(out) + }; + loop { + match reader.read_event_into(&mut buf).ok()? { + Event::Eof => break, + Event::Start(e) => writer.write_event(Event::Start(map(&e)?)).ok()?, + Event::Empty(e) => writer.write_event(Event::Empty(map(&e)?)).ok()?, + ev => writer.write_event(ev).ok()?, + } + buf.clear(); + } + Some(writer.into_inner()) +} + +/// Kept parts whose style ids are renumbered once the styles part is written. +#[derive(Default)] +pub struct StylePatches { + /// (written part name, source bytes, dxf id map, source number format id → code). + pub(super) list: Vec, +} + +pub(super) type StylePatch = (String, Arc<[u8]>, HashMap, Vec<(u32, String)>); + +impl KeptOut { + /// Number format codes kept parts refer to (to be registered in the styles part). + pub fn num_fmt_codes(&self) -> Vec { + let mut v: Vec = vec![]; + for (_, _, _, fmts) in &self.patches.list { + for (_, code) in fmts { + if !v.contains(code) { + v.push(code.clone()); + } + } + } + v + } +} + +/// Renumbers the `dxfId` and `numFmtId` attributes of kept PivotTables and pivot caches to the +/// written styles part. `fmt_id` maps a number format code to its id there. +pub fn finish_style_ids(out: &mut Out, fmt_id: &dyn Fn(&str) -> Option) { + for (name, data, dxfs, fmts) in std::mem::take(&mut out.kept.patches.list) { + let fmts: HashMap = fmts.iter().filter_map(|(old, code)| Some((*old, fmt_id(code)?))).collect(); + if let Some(x) = map_style_ids(&data, &dxfs, &fmts) { + out.replace(&name, x); + } + } +} + /// Original part name (normalized) → written part name. pub(super) type NameMap = HashMap; @@ -90,13 +170,21 @@ pub(super) fn write_parts(out: &mut Out, parts: &[PreservedPart]) -> NameMap { for p in parts { names.entry(normalize(&p.name)).or_insert_with(|| out.kept.claim(&p.name)); } + let own: HashSet = names.values().cloned().collect(); + for (k, v) in &out.kept.wb_names { + names.entry(k.clone()).or_insert_with(|| v.clone()); + } let mut written = HashSet::new(); for p in parts { let Some(new) = names.get(&normalize(&p.name)).cloned() else { continue }; - if !written.insert(new.clone()) { + if !own.contains(&new) || !written.insert(new.clone()) { continue; } out.part(&new, Some(&p.content_type), p.data.to_vec()); + if !p.dxfs.is_empty() || !p.num_fmts.is_empty() { + let dxfs = p.dxfs.iter().map(|(old, s)| (*old, crate::styles::dxf_id(&mut out.dxfs, s))).collect(); + out.kept.patches.list.push((new.clone(), p.data.clone(), dxfs, p.num_fmts.clone())); + } if !p.rels.is_empty() { out.part(&rels_part_name(&new), None, part_rels_xml(&p.rels, &names).into_bytes()); } @@ -162,9 +250,25 @@ pub struct WorkbookKept { /// Workbook XML elements that go right after `` (``). pub elements: String, sheets: Vec, + /// Kept pivot caches: (`cacheId`, new relationship id). + pivot_caches: Vec<(u32, String)>, } impl WorkbookKept { + /// The `cacheId`s of the kept pivot caches (written PivotTables must not reuse them). + pub fn pivot_cache_ids(&self) -> Vec { + self.pivot_caches.iter().map(|(id, _)| *id).collect() + } + + /// The `` entries of the kept pivot caches. + pub fn pivot_cache_entries(&self) -> String { + let mut x = String::new(); + for (id, rid) in &self.pivot_caches { + let _ = write!(x, "", esc_attr(rid)); + } + x + } + /// Where the model's sheet `i` is in the file's sheet list: chart sheets come between worksheets. pub fn file_index(&self, i: usize) -> usize { i + self.sheets.iter().filter(|s| s.before <= i).count() @@ -292,9 +396,37 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb p.sheets.iter().partition(|s| chart_sheet_usable(wb, p, s, &mut refs)) }; let root_of = |s: &PreservedSheet| p.rels.iter().find(|r| r.id == s.rel_id); - let dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect(); - // Parts reached only by dropped chart sheets go with them. - let mut gone: HashSet = dropped.iter().filter_map(|s| root_of(s)).flat_map(|r| reachable(p, r)).collect(); + // Pivot caches no kept PivotTable of a sheet uses any more (their sheets were deleted). + let sheet_parts = || wb.sheets.iter().filter_map(|s| s.preserved.as_deref()).flat_map(|q| q.parts.iter()); + let mut used_caches: HashSet = sheet_parts() + .flat_map(|part| part.rels.iter()) + .filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"])) + .map(|r| normalize(&r.target)) + .collect(); + // A PivotTable can name its cache only by the workbook's `cacheId`. + let cache_of_id: HashMap = p + .elements + .iter() + .filter(|e| e.slot == "pivotCache") + .filter_map(|e| { + let x = xml::parse(e.xml.as_bytes()).ok()?; + let rel = p.rels.iter().find(|r| Some(r.id.as_str()) == x.attr("id"))?; + Some((x.attr_u32("cacheId")?, normalize(&rel.target))) + }) + .collect(); + used_caches.extend( + sheet_parts() + .filter(|part| part.content_type == CT_PIVOT_TABLE) + .filter_map(|part| xml::parse(&part.data).ok()?.attr_u32("cacheId")) + .filter_map(|id| cache_of_id.get(&id).cloned()), + ); + let unused_caches: Vec<&PreservedRel> = + p.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]) && !used_caches.contains(&normalize(&r.target))).collect(); + let mut dropped_ids: HashSet<&str> = dropped.iter().map(|s| s.rel_id.as_str()).collect(); + dropped_ids.extend(unused_caches.iter().map(|r| r.id.as_str())); + // Parts reached only by dropped chart sheets and pivot caches go with them. + let mut gone: HashSet = + dropped.iter().filter_map(|s| root_of(s)).chain(unused_caches.iter().copied()).flat_map(|r| reachable(p, r)).collect(); if !gone.is_empty() { let others = p.rels.iter().filter(|r| !dropped_ids.contains(r.id.as_str())).flat_map(|r| reachable(p, r)); for n in others { @@ -310,7 +442,19 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb out.kept.root.push((r.rel_type.clone(), target, r.external)); } } + let pivot_caches: Vec<(u32, String)> = p + .elements + .iter() + .filter(|e| e.slot == "pivotCache") + .filter_map(|e| { + let x = xml::parse(e.xml.as_bytes()).ok()?; + Some((x.attr_u32("cacheId")?, ids.get(x.attr("id")?)?.clone())) + }) + .collect(); + out.kept.wb_names = names; + out.kept.cache_ids = pivot_caches.iter().map(|(id, _)| *id).collect(); WorkbookKept { + pivot_caches, elements: p.elements.iter().filter(|e| e.slot == "externalReferences").filter_map(|e| remap(&e.xml, &ids)).collect(), sheets: live .iter() diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 481c8a5599..c16252efc9 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -18,6 +18,14 @@ //! Reading: the cache's source and field names plus the table's areas, functions, show-values-as, //! layout flags, grand totals and style become a model [`PivotTable`]. Anything we don't model //! (OLAP sources, calculated fields, numeric grouping…) becomes a warning. +//! +//! A PivotTable whose source is a range or name in another workbook (its cache's +//! `worksheetSource` has an `r:id` to an `externalLinkPath` relationship), a data connection or +//! the workbook's Data Model (`cacheSource type="external"` with a `connectionId` in +//! `xl/connections.xml`) is not modelled: GridCraft never opens the other workbook, runs the +//! connection or loads the model, so it couldn't refresh it. [`read_pivots`] reports it instead, +//! and `passthrough` keeps its PivotTable, cache and records parts unchanged (with the Data Model +//! for a PivotTable on the model). use std::collections::HashMap; use std::fmt::Write as _; @@ -37,7 +45,7 @@ use crate::xml::{El, esc_attr}; mod read; mod write; -pub use read::{CachesIn, read_pivots}; +pub use read::{CachesIn, ExternalPivot, KeptSource, read_pivots}; pub use write::PivotWriter; pub const CT_PIVOT_TABLE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml"; diff --git a/crates/xlsx/src/pivot/read.rs b/crates/xlsx/src/pivot/read.rs index 61927e972e..e887602b52 100644 --- a/crates/xlsx/src/pivot/read.rs +++ b/crates/xlsx/src/pivot/read.rs @@ -32,6 +32,47 @@ impl FieldIn { struct CacheIn { source: String, fields: Vec, + /// Set when the PivotTables on this cache are kept as they are, not modelled. + kept: Option, +} + +/// Where the data of a PivotTable GridCraft keeps unchanged (doesn't model) comes from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeptSource { + /// A range or name in another workbook. + OtherWorkbook, + /// A data connection of the workbook (`xl/connections.xml`) other than its Data Model. + Connection, + /// The workbook's Data Model (Power Pivot), through its model connection. + DataModel, +} + +impl KeptSource { + pub(crate) fn describe(self) -> &'static str { + match self { + KeptSource::OtherWorkbook => "another workbook", + KeptSource::Connection => "a data connection", + KeptSource::DataModel => "the workbook's Data Model", + } + } +} + +/// A PivotTable GridCraft doesn't model (its data is in another workbook, a data connection or +/// the Data Model), kept unchanged for saving. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalPivot { + /// The id of the sheet's relationship to the PivotTable part. + pub rel_id: String, + /// The pivot cache definition part it uses. + pub cache_part: String, + pub source: KeptSource, +} + +/// The PivotTables of a sheet: those modelled, and those kept as they are. +#[derive(Debug, Default)] +pub struct SheetPivots { + pub tables: Vec, + pub external: Vec, } /// Workbook-level pivot cache lookup, filled from ``; caches are parsed once. @@ -40,6 +81,8 @@ pub struct CachesIn { by_id: HashMap, parsed: HashMap>, next_id: u32, + /// The workbook's data connections (`connectionId` → whether it is the Data Model's). + connections: HashMap, } impl CachesIn { @@ -54,10 +97,28 @@ impl CachesIn { } } } - CachesIn { by_id, parsed: HashMap::new(), next_id: 1 } + CachesIn { by_id, parsed: HashMap::new(), next_id: 1, connections: HashMap::new() } + } + + /// Reads the ids of the workbook's data connections (`xl/connections.xml`), which caches on a + /// connection or the Data Model name by `connectionId`. + pub fn read_connections(&mut self, cx: &mut Ctx<'_>, wb_rels: &[crate::package::Rel]) { + let Some(r) = wb_rels.iter().find(|r| r.kind == "connections" && !r.external) else { return }; + let Ok(Some(x)) = cx.optional_xml(&r.target) else { return }; + for c in x.kids("connection").take(MAX_CONNECTIONS) { + let Some(id) = c.attr_u32("id") else { continue }; + // The model connection: `` in its extension list (Excel + // also gives it ``). + let x15_model = c.child("extLst").is_some_and(|l| l.kids("ext").filter_map(|e| e.child("connection")).any(|x| x.flag("model", false))); + let dbpr_model = c.attr("type") == Some("5") && c.child("dbPr").and_then(|d| d.attr("command")) == Some("Model"); + self.connections.insert(id, x15_model || dbpr_model); + } } } +/// Most data connections read from `xl/connections.xml`. +const MAX_CONNECTIONS: usize = 100_000; + fn item_label_el(e: &El, sys: DateSystem) -> String { let v = e.attr("v").unwrap_or(""); match e.name.as_str() { @@ -69,7 +130,7 @@ fn item_label_el(e: &El, sys: DateSystem) -> String { } } -fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option { +fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str, connections: &HashMap) -> Option { // A cache that can't be read loses its PivotTable: say so instead of dropping it silently. // An oversized cache is refused before it inflates, so warning and opening the rest is safe. let x = match cx.optional_xml(part) { @@ -93,17 +154,34 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option } let src = x.child("cacheSource"); let ty = src.and_then(|s| s.attr("type")).unwrap_or("worksheet"); + // A data connection or the Data Model (OLAP): kept as it is when the workbook has that + // connection. + if ty == "external" { + let model = src.and_then(|s| s.attr_u32("connectionId")).and_then(|id| connections.get(&id).copied()); + let Some(model) = model else { + cx.warn("a PivotTable's data connection is not in the workbook; kept as plain cells"); + return None; + }; + let kept = if model { KeptSource::DataModel } else { KeptSource::Connection }; + return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(kept) }); + } if ty != "worksheet" { - cx.warn(format!("PivotTables with a {ty} data source are not supported; kept as plain cells")); + cx.warn(format!("PivotTables with a data source of type \"{ty}\" are not supported; kept as plain cells")); return None; } let ws = src.and_then(|s| s.child("worksheetSource")); + // A source in another workbook: `r:id` names the cache's link to that workbook's path. + if let Some(rid) = ws.and_then(|w| w.attr("id")) { + let linked = cx.pkg.rels(part).ok().is_some_and(|rels| rels.iter().any(|r| r.id == rid && r.external && r.kind == "externalLinkPath")); + if !linked { + cx.warn("a PivotTable's source is in another workbook that its cache doesn't name; kept as plain cells"); + return None; + } + return Some(CacheIn { source: String::new(), fields: vec![], kept: Some(KeptSource::OtherWorkbook) }); + } let source = match ws { Some(w) if w.attr("name").is_some_and(|n| !n.trim().is_empty()) => w.attr("name").unwrap_or("").trim().to_string(), Some(w) => { - if w.attr("id").is_some() { - cx.warn("a PivotTable's source is in another workbook; its source reference may not resolve"); - } let r = w.attr("ref").map(|r| r.replace('$', "")).and_then(|r| RangeRef::parse(&r)); let Some(r) = r else { cx.warn("a PivotTable's source reference is missing or invalid; kept as plain cells"); @@ -151,13 +229,15 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option cx.warn("a PivotTable's cache has no fields; kept as plain cells"); return None; } - Some(CacheIn { source, fields }) + Some(CacheIn { source, fields, kept: None }) } -/// Reads the PivotTables related to a worksheet part. -pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result, IoError> { +/// Reads the PivotTables related to a worksheet part. Those whose source is in another workbook, +/// a data connection or the Data Model are listed in [`SheetPivots::external`] (with a warning), +/// not modelled. +pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sheet_name: &str) -> Result { let rels = cx.pkg.rels(sheet_part)?; - let mut out = Vec::new(); + let mut out = SheetPivots::default(); for rel in rels.iter().filter(|r| r.kind == "pivotTable" && !r.external) { let Some(x) = cx.optional_xml(&rel.target)? else { continue }; if x.name != "pivotTableDefinition" { @@ -178,15 +258,24 @@ pub fn read_pivots(cx: &mut Ctx<'_>, caches: &mut CachesIn, sheet_part: &str, sh let cache = match caches.parsed.get(&cache_part) { Some(c) => c.clone(), None => { - let c = read_cache(cx, &cache_part, sheet_name); + let c = read_cache(cx, &cache_part, sheet_name, &caches.connections); caches.parsed.insert(cache_part.clone(), c.clone()); c } }; let Some(cache) = cache else { continue }; + if let Some(source) = cache.kept { + let name = x.attr("name").unwrap_or(""); + let from = source.describe(); + cx.warn(format!( + "PivotTable \"{name}\" on sheet \"{sheet_name}\" gets its data from {from}: it is kept for saving as it is, but can't be edited or refreshed here" + )); + out.external.push(ExternalPivot { rel_id: rel.id.clone(), cache_part, source }); + continue; + } if let Some(pt) = read_table(cx, &x, &cache, caches.next_id) { caches.next_id = caches.next_id.saturating_add(1); - out.push(pt); + out.tables.push(pt); } } Ok(out) diff --git a/crates/xlsx/src/pivot/write.rs b/crates/xlsx/src/pivot/write.rs index cea529999d..ab4a322225 100644 --- a/crates/xlsx/src/pivot/write.rs +++ b/crates/xlsx/src/pivot/write.rs @@ -104,6 +104,11 @@ pub struct PivotWriter { caches: Vec<(u32, String)>, pending: Vec, tables: u32, + /// Cache ids taken by kept pivot caches (PivotTables on another workbook). + reserved: Vec, + /// `` entries of the kept caches. + kept_entries: String, + next_id: u32, } struct Pending { @@ -115,6 +120,21 @@ struct Pending { } impl PivotWriter { + /// A writer whose caches don't reuse the kept caches' ids; `kept_entries` (their + /// `` elements) are listed with the written ones. + pub fn new(reserved: Vec, kept_entries: String) -> PivotWriter { + PivotWriter { reserved, kept_entries, ..PivotWriter::default() } + } + + fn next_cache_id(&mut self) -> u32 { + loop { + self.next_id = self.next_id.saturating_add(1); + if !self.reserved.contains(&self.next_id) || self.next_id == u32::MAX { + return self.next_id; + } + } + } + /// Writes the caches of a sheet's PivotTables and adds the sheet's relationships to its /// PivotTable parts. Pivots whose source can't be resolved are not written. pub fn add_sheet(&mut self, wb: &Workbook, si: usize, out: &mut Out, rels: &mut Rels) { @@ -122,6 +142,7 @@ impl PivotWriter { for (idx, pt) in sheet.pivots.iter().enumerate() { let Some(cache) = build_cache(wb, pt, si) else { continue }; let n = self.caches.len() as u32 + 1; + let cache_id = self.next_cache_id(); let cache_part = format!("xl/pivotCache/pivotCacheDefinition{n}.xml"); let rec_rid = if let Some((count, xml)) = &cache.records { let mut r = Rels::default(); @@ -138,24 +159,25 @@ impl PivotWriter { let refresh_on_load = !pt.values.iter().any(|v| v.func == PivotFunc::DistinctCount); let xml = cache_xml(&cache, rec_rid.as_deref(), wb.date_system, refresh_on_load); out.part(&cache_part, Some(CT_PIVOT_CACHE_DEF), xml.into_bytes()); - self.caches.push((n, format!("pivotCache/pivotCacheDefinition{n}.xml"))); + self.caches.push((cache_id, format!("pivotCache/pivotCacheDefinition{n}.xml"))); self.tables += 1; let t = self.tables; rels.add("pivotTable", &format!("../pivotTables/pivotTable{t}.xml")); let mut tr = Rels::default(); tr.add("pivotCacheDefinition", &format!("../pivotCache/pivotCacheDefinition{n}.xml")); out.part(&format!("xl/pivotTables/_rels/pivotTable{t}.xml.rels"), None, tr.xml().into_bytes()); - self.pending.push(Pending { part: format!("xl/pivotTables/pivotTable{t}.xml"), sheet: si, idx, cache_id: n, cache }); + self.pending.push(Pending { part: format!("xl/pivotTables/pivotTable{t}.xml"), sheet: si, idx, cache_id, cache }); } } /// Adds the workbook relationships to the caches; returns the `` element (empty /// when there are none). pub fn workbook_xml(&self, wb_rels: &mut Rels) -> String { - if self.caches.is_empty() { + if self.caches.is_empty() && self.kept_entries.is_empty() { return String::new(); } let mut s = String::from(""); + s.push_str(&self.kept_entries); for (id, target) in &self.caches { let rid = wb_rels.add("pivotCacheDefinition", target); let _ = write!(s, ""); diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index d28792618d..901ef885af 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -295,6 +295,14 @@ fn read_workbook_properties(cx: &mut Ctx<'_>, wb: &mut Workbook, xml: &El) { wb.protected_structure = p.flag("lockStructure", false); wb.structure_password = if wb.protected_structure { crate::sheet_read::read_password(p, "workbook") } else { None }; } + if let Some(f) = xml.child("fileSharing") { + // The iterated hash has bare attribute names; the legacy one is `reservationPassword`. + wb.write_reservation = Some(gridcraft_model::WriteReservation { + user_name: f.attr("userName").unwrap_or("").to_string(), + read_only_recommended: f.flag("readOnlyRecommended", false), + password: crate::sheet_read::read_password(f, "").or_else(|| crate::sheet_read::read_password(f, "reservation")), + }); + } } /// The single window modelled by GridCraft: prefer the first visible window, @@ -381,6 +389,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W // Legacy formula cells per model sheet, rewritten once names and tables are known. let mut legacy_formulas: Vec<(usize, Vec)> = vec![]; let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels); + pivot_caches.read_connections(&mut cx, &wb_rels); let sheet_els: Vec<&El> = wb_xml.child("sheets").map(|s| s.kids("sheet").collect()).unwrap_or_default(); if sheet_els.len() > MAX_SHEETS { return Err(IoError::TooLarge(format!("the workbook has more than {MAX_SHEETS} sheets"))); @@ -420,13 +429,17 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W (Sheet::new(name.clone()), Default::default()) } }; + let mut external_pivots = vec![]; legacy_formulas.push((wb.sheets.len(), std::mem::take(&mut cx.legacy_formulas))); match crate::pivot::read_pivots(&mut cx, &mut pivot_caches, &rel.target, &name) { - Ok(p) => sheet.pivots = p, + Ok(p) => { + sheet.pivots = p.tables; + external_pivots = p.external; + } Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)), Err(e) => cx.warn(format!("PivotTables on sheet \"{name}\" could not be read: {e}")), } - sheet.preserved = kept.sheet(&mut cx, &rel.target, &name, &read_controls); + sheet.preserved = kept.sheet(&mut cx, &rel.target, &name, &external_pivots, &read_controls); sheet.preserved = crate::extlist::keep_sheet(&mut cx, &name, sheet.preserved.take(), kept.keeps()); sheet.file_id = se.attr_u32("sheetId").unwrap_or(0); sheet.visibility = match se.attr("state") { diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index c21b703763..c7208e7945 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -33,7 +33,9 @@ mod parts; mod rules; pub(crate) use parts::password_attrs; -use parts::{autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_name, table_xml, thread_ids, threaded_xml, vml_xml}; +use parts::{ + autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_filter, table_name, table_xml, thread_ids, threaded_xml, vml_xml, +}; use rules::{cf_rule_xml, solid_bar_x14, validation_xml, x14_cf_rule_xml}; fn sqref(ranges: &[RangeRef]) -> String { @@ -203,7 +205,8 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( out.table_id += 1; let n = out.tables; let name = table_name(&t.name, &mut used_names, out.table_id); - let xml = table_xml(t, cols, &name, out.table_id, out); + let filter = table_filter(sheet, t); + let xml = table_xml(t, cols, &name, out.table_id, &filter, out); out.part(&format!("xl/tables/table{n}.xml"), Some(CT_TABLE), xml.into_bytes()); part.features.table_parts.push(rels.add("table", &format!("../tables/table{n}.xml"))); } diff --git a/crates/xlsx/src/sheet_write/parts.rs b/crates/xlsx/src/sheet_write/parts.rs index a5a06b31df..bc5d551d9b 100644 --- a/crates/xlsx/src/sheet_write/parts.rs +++ b/crates/xlsx/src/sheet_write/parts.rs @@ -110,7 +110,34 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion) s } -pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, out: &mut Out) -> String { +/// The criteria saved in a table's ``: its own, plus those of a sheet AutoFilter +/// that starts on the table's header row. GridCraft filters a table through the sheet +/// AutoFilter, but a file can't hold a sheet AutoFilter that overlaps a table (the sheet element +/// is left out), so without this the criteria would be lost and the rows they hide would reopen +/// as rows hidden by hand, which SUBTOTAL 1-11 counts. +pub(super) fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterion)> { + let mut criteria = t.filter.clone(); + let Some(af) = sheet.autofilter.as_ref().filter(|af| { + t.header_row + && t.filter_button + && af.range.start.row == t.range.start.row + && af.range.intersects(&t.range) + && t.data_range().is_some_and(|d| af.range.end.row >= d.end.row) + }) else { + return criteria; + }; + for (off, c) in &af.criteria { + let Some(col) = af.range.start.col.checked_add(*off).and_then(|abs| abs.checked_sub(t.range.start.col)) else { continue }; + if col < t.range.width() { + criteria.retain(|(o, _)| *o != col); + criteria.push((col, c.clone())); + } + } + criteria.sort_by_key(|(o, _)| *o); + criteria +} + +pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter: &[(u32, FilterCriterion)], out: &mut Out) -> String { let mut s = format!("{XML_DECL}", cols.len()); for (i, name) in cols.iter().enumerate() { diff --git a/crates/xlsx/src/tables.rs b/crates/xlsx/src/tables.rs index cf89dbcf12..a1d4eb82d6 100644 --- a/crates/xlsx/src/tables.rs +++ b/crates/xlsx/src/tables.rs @@ -57,7 +57,8 @@ pub use gridcraft_core::color::INDEXED; /// Paper sizes (`pageSetup paperSize`) we name. ID 12/13 are the JIS B4/B5 that /// `pageLayout.pageSetup` calls `B4`/`B5`; 42 is ISO B4, and 43–88 are the Japanese postcards, -/// envelopes and B6. The engine's `known_paper` uses the same names and sizes. +/// envelopes and B6. Their sizes are in `gridcraft_model::paper`, under the same names. 34 is +/// ECMA-376's "B5 envelope (176 mm by 250 mm)": the ISO B5 size, so it reads as `B5 (ISO)`. const PAPERS: [(u32, &str); 23] = [ (1, "Letter"), (3, "Tabloid"), @@ -72,7 +73,7 @@ const PAPERS: [(u32, &str); 23] = [ (13, "B5"), (20, "Envelope #10"), (27, "Envelope DL"), - (34, "Envelope B5"), + (34, "B5 (ISO)"), (42, "B4 (ISO)"), (43, "Japanese Postcard"), (69, "Japanese Double Postcard"), @@ -88,25 +89,10 @@ pub fn paper_name(id: u32) -> Option<&'static str> { PAPERS.iter().find(|(i, _)| *i == id).map(|(_, n)| *n) } -/// The file ID for a paper name. Spelling is loose like `known_paper`'s — spaces, hyphens, -/// underscores and parentheses don't matter, and the JIS/ISO and Japanese-envelope spellings the -/// page-setup commands take are folded onto the name in [`PAPERS`]. +/// The file ID for a paper name, spelled any way [`gridcraft_model::paper::canonical`] takes. pub fn paper_id(name: &str) -> Option { - let norm = |s: &str| s.trim().to_ascii_lowercase().replace([' ', '-', '_', '(', ')'], ""); - let normalized = norm(name); - let alias = match normalized.as_str() { - "b4jis" => "b4", - "b5jis" => "b5", - "b6jis" => "b6", - "postcard" => "japanesepostcard", - "doublepostcard" => "japanesedoublepostcard", - "chou#3" => "japaneseenvelope#3", - "chou#4" => "japaneseenvelope#4", - "kaku#2" => "japaneseenvelopekaku#2", - "kaku#3" => "japaneseenvelopekaku#3", - other => other, - }; - PAPERS.iter().find(|(_, n)| norm(n) == alias).map(|(i, _)| *i) + let name = gridcraft_model::paper::canonical(name)?; + PAPERS.iter().find(|(_, n)| *n == name).map(|(i, _)| *i) } /// Functions introduced after Excel 2007 that files store with the `_xlfn.` prefix. Entries with @@ -336,6 +322,20 @@ pub const EMU_PER_PX: f64 = 9525.0; mod tests { use super::*; + /// Every paper in the shared table saves with an XLSX id, so it reopens as itself. ECMA-376 + /// has no upright ISO B6 id (35 is the B6 envelope stated wide), so `B6 (ISO)` alone has none. + #[test] + fn every_shared_paper_has_an_xlsx_id() { + for (name, _, _) in gridcraft_model::paper::PAPERS { + let id = paper_id(name); + if name == "B6 (ISO)" { + assert_eq!(id, None); + } else { + assert_eq!(id.and_then(paper_name), Some(name), "{name}"); + } + } + } + #[test] fn widths() { assert_eq!(col_width_to_px(9.140625), 64.0); diff --git a/crates/xlsx/src/tests.rs b/crates/xlsx/src/tests.rs index f044a3fb82..9749d3f811 100644 --- a/crates/xlsx/src/tests.rs +++ b/crates/xlsx/src/tests.rs @@ -6,6 +6,7 @@ mod chart_book_names; mod chart_bool_default; mod chart_combo_kinds; mod chart_data_table; +mod chart_line_percent_stacked; mod chart_ref_offsets; mod controls_tests; mod csv_tests; @@ -32,6 +33,7 @@ mod shared_media; mod sheet_data_pin; mod sheet_names; mod smooth_roundtrip; +mod tablefilter; mod trendline_roundtrip; mod xls_dv_tests; mod xls_style_tests; diff --git a/crates/xlsx/src/tests/chart_combo_kinds.rs b/crates/xlsx/src/tests/chart_combo_kinds.rs index 04890de537..7b14c38251 100644 --- a/crates/xlsx/src/tests/chart_combo_kinds.rs +++ b/crates/xlsx/src/tests/chart_combo_kinds.rs @@ -338,6 +338,8 @@ fn a_chart_without_series_survives_a_round_trip() { Line, LineMarkers, LineStacked, + LineStacked100, + LineStacked100Markers, Pie, Doughnut, Area, diff --git a/crates/xlsx/src/tests/chart_line_percent_stacked.rs b/crates/xlsx/src/tests/chart_line_percent_stacked.rs new file mode 100644 index 0000000000..2b0f46c9d6 --- /dev/null +++ b/crates/xlsx/src/tests/chart_line_percent_stacked.rs @@ -0,0 +1,181 @@ +//! Line chart groups by `grouping` and markers: `percentStacked` opens as a 100% stacked line. + +use gridcraft_model::{ChartKind, Workbook}; + +use crate::chart::{read_chart, write_chart}; +use crate::xml::parse; + +/// Reads a line chart whose one group has `grouping` and whose one series holds `marker`. +fn kind(grouping: &str, marker: &str) -> ChartKind { + let xml = format!( + "\ + {marker}\ + Data!$A$1:$A$5\ + \ + " + ); + let root = parse(xml.as_bytes()).unwrap(); + read_chart(&root).unwrap().kind +} + +const NO_MARKER: &str = ""; + +#[test] +fn percent_stacked_lines_open_as_hundred_percent_stacked() { + assert_eq!(kind("percentStacked", NO_MARKER), ChartKind::LineStacked100); + assert_eq!(kind("percentStacked", ""), ChartKind::LineStacked100Markers); +} + +#[test] +fn standard_and_stacked_lines_keep_their_kinds() { + assert_eq!(kind("standard", NO_MARKER), ChartKind::Line); + assert_eq!(kind("standard", ""), ChartKind::LineMarkers); + assert_eq!(kind("stacked", NO_MARKER), ChartKind::LineStacked); + assert_eq!(kind("stacked", ""), ChartKind::LineStacked); +} + +#[test] +fn a_hundred_percent_stacked_line_series_in_a_combo_chart_keeps_its_kind_when_saved() { + let ser = + |i: usize| format!("Data!$A$1:$A$5"); + let xml = format!( + "\ + {}\ + {}\ + ", + ser(0), + ser(1) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.kind, ChartKind::Combo); + assert_eq!(ch.series.iter().map(|s| s.kind).collect::>(), [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers)]); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + let kinds: Vec> = again.series.iter().map(|s| s.kind).collect(); + assert_eq!(kinds.first(), Some(&Some(ChartKind::ColumnClustered)), "{saved}"); + assert_eq!(kinds, [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers)], "{saved}"); +} + +/// The lines on one pair of axes share the first one's grouping: a standard line after a 100% +/// stacked one is stacked to 100% too, keeping its own markers. +#[test] +fn combo_line_series_keep_their_order_and_share_one_percent_stack_when_saved() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + {}{}\ + ", + ser(0, ""), + ser(2, NO_MARKER), + ser(1, ""), + ser(3, NO_MARKER) + ); + let want = + [Some(ChartKind::ColumnClustered), Some(ChartKind::LineStacked100Markers), Some(ChartKind::LineStacked100), Some(ChartKind::LineStacked100)]; + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.series.iter().map(|s| s.kind).collect::>(), want); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + assert_eq!(saved.matches("percentStacked").count(), 1, "both 100% stacked series share one stack: {saved}"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); +} + +#[test] +fn a_hundred_percent_stacked_line_on_the_secondary_axis_keeps_its_kind_when_saved() { + let ser = + |i: usize| format!("Data!$A$1:$A$5"); + let xml = format!( + "\ + {}\ + {}\ + ", + ser(0), + ser(1) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert!(ch.series.get(1).is_some_and(|s| s.secondary && s.kind == Some(ChartKind::LineStacked100Markers))); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + let got: Vec<(Option, bool)> = again.series.iter().map(|s| (s.kind, s.secondary)).collect(); + assert_eq!(got, [(Some(ChartKind::ColumnClustered), false), (Some(ChartKind::LineStacked100Markers), true)], "{saved}"); +} + +/// On the secondary axes too, a standard line after a 100% stacked one is stacked to 100%. +#[test] +fn secondary_columns_and_hundred_percent_stacked_lines_keep_their_kinds_when_saved() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + {}\ + {}\ + ", + ser(0, ""), + ser(1, ""), + ser(2, ""), + ser(3, NO_MARKER) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + let want = [ + (Some(ChartKind::ColumnClustered), false), + (Some(ChartKind::ColumnClustered), true), + (Some(ChartKind::LineStacked100Markers), true), + (Some(ChartKind::LineStacked100), true), + ]; + assert_eq!(ch.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), want); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.series.iter().map(|s| (s.kind, s.secondary)).collect::>(), want, "{saved}"); +} + +#[test] +fn a_hundred_percent_stacked_line_group_with_mixed_markers_keeps_each_series_markers() { + let ser = |i: usize, marker: &str| { + format!("{marker}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}{}\ + ", + ser(0, ""), + ser(1, NO_MARKER) + ); + // A 100% stacked line chart with markers; the second series keeps its own lack of them. + let want = [None, Some(ChartKind::LineStacked100)]; + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.kind, ChartKind::LineStacked100Markers); + assert_eq!(ch.series.iter().map(|s| s.kind).collect::>(), want); + assert_eq!(ch.series_kinds(), [ChartKind::LineStacked100Markers, ChartKind::LineStacked100]); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + let again = read_chart(&parse(saved.as_bytes()).unwrap()).unwrap(); + assert_eq!(again.kind, ChartKind::LineStacked100Markers, "{saved}"); + assert_eq!(again.series.iter().map(|s| s.kind).collect::>(), want, "{saved}"); +} + +/// The lines on one pair of axes share the first one's grouping: a 100% stacked line group after +/// a stacked one is drawn stacked. +#[test] +fn a_hundred_percent_stacked_line_group_after_a_stacked_one_on_the_same_axes_is_stacked() { + let ser = |i: usize| { + format!("{NO_MARKER}Data!$A$1:$A$5") + }; + let xml = format!( + "\ + {}\ + {}\ + ", + ser(0), + ser(1) + ); + let ch = read_chart(&parse(xml.as_bytes()).unwrap()).unwrap(); + assert_eq!(ch.series_kinds(), [ChartKind::LineStacked, ChartKind::LineStacked]); + let saved = write_chart(&Workbook::default(), 0, &ch, "Book1"); + assert!(!saved.contains("percentStacked"), "{saved}"); +} diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index b4fd000b41..da537c1047 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -418,6 +418,19 @@ fn parser_stops_collecting_fields_at_max_cols() { assert_eq!(lens, vec![MAX_COLS as usize]); } +#[test] +fn a_field_over_32767_characters_is_cut() { + let src = format!("{},{},'{}", "x".repeat(40_000), "y".repeat(32_768), "z".repeat(40_000)); + for parse_values in [true, false] { + let wb = read_csv(src.as_bytes(), &CsvOptions { parse_values, ..Default::default() }).unwrap(); + assert_eq!(v(&wb, 0, 0), Value::text("x".repeat(32_767))); + assert_eq!(v(&wb, 0, 1), Value::text("y".repeat(32_767))); + } + // The apostrophe is dropped before the cut when values are parsed. + let wb = read_csv(src.as_bytes(), &CsvOptions::default()).unwrap(); + assert_eq!(v(&wb, 0, 2), Value::text("z".repeat(32_767))); +} + #[test] fn csv_used_range_limit_is_enforced_while_reading() { let opts = |max| CsvOptions { max_used_cells: Some(max), ..Default::default() }; diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index 6923a37f4c..a47ed27f0f 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -584,6 +584,7 @@ fn rebased(target: &str, from: &str, to: &str) -> String { content_type: String::new(), data: Arc::from(&b""[..]), rels: vec![link("externalLinkPath"), link("hyperlink")], + ..Default::default() }; let mut wb = gridcraft_model::Workbook::new(); wb.preserved = Some(Arc::new(gridcraft_model::Preserved { parts: vec![part], ..Default::default() })); @@ -971,6 +972,548 @@ fn notes_take_shape_blocks_the_header_pictures_dont_use() { assert!(notes_ids.iter().all(|b| notes_map.contains(b)), "note ids outside their drawing's blocks"); } +// ---------------------------------------------------------------- PivotTables on another workbook + +const EXT_CACHE_RANGE: &str = r#""#; +const EXT_CACHE_NAME: &str = r#""#; +const EXT_LINK_TARGET: &str = "file:///C:/data/source.xlsx"; +const EXT_RECORDS: &str = r#""#; +/// Source styles: custom number format 170 and two differential formats (the second blue). +const EXT_STYLES: &str = r#""#; + +fn ext_cache(source: &str) -> String { + format!( + r#"{source}"# + ) +} + +fn ext_table(name: &str, cache_id: u32) -> String { + format!( + r#""# + ) +} + +/// Sheets "Report" and "More", each with a PivotTable on cache 1, whose source (a range, or a +/// name with `by_name`) is in another workbook; with `shared` both use one cache, otherwise only +/// "Report" has a PivotTable. `link_kind` is the type of the cache's relationship to the source. +fn ext_pivot_package(by_name: bool, shared: bool, link_kind: &str) -> Vec { + let workbook = format!( + r#""# + ); + let ct = |part: &str, ty: &str| format!(r#""#); + let content_types = format!( + r#"{}{}{}{}{}{}{}{}"#, + ct("xl/workbook.xml", "sheet.main"), + ct("xl/worksheets/sheet1.xml", "worksheet"), + ct("xl/worksheets/sheet2.xml", "worksheet"), + ct("xl/styles.xml", "styles"), + ct("xl/pivotTables/pivotTable1.xml", "pivotTable"), + ct("xl/pivotTables/pivotTable2.xml", "pivotTable"), + ct("xl/pivotCache/pivotCacheDefinition1.xml", "pivotCacheDefinition"), + ct("xl/pivotCache/pivotCacheRecords1.xml", "pivotCacheRecords"), + ); + let sheet = |v: &str| { + format!( + r#"x{v}"# + ) + }; + let (s1, s2) = (sheet("5"), sheet("6")); + let cache = ext_cache(if by_name { EXT_CACHE_NAME } else { EXT_CACHE_RANGE }); + let (t1, t2) = (ext_table("Ext1", 1), ext_table("Ext2", 1)); + let link = if link_kind.starts_with("http") { link_kind.to_string() } else { format!("{NS_R}/{link_kind}") }; + let cache_rels = rels(&[("rId1", "pivotCacheRecords", "pivotCacheRecords1.xml"), ("rId2", &link, EXT_LINK_TARGET)]); + let table_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition1.xml")]); + let wb_rels = rels(&[ + ("rId1", "worksheet", "worksheets/sheet1.xml"), + ("rId2", "worksheet", "worksheets/sheet2.xml"), + ("rId3", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition1.xml"), + ("rId4", "styles", "styles.xml"), + ]); + let s1_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable1.xml")]); + let s2_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable2.xml")]); + let mut parts: Vec<(&str, &[u8])> = vec![ + ("[Content_Types].xml", content_types.as_bytes()), + ("_rels/.rels", super::ROOT_RELS.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()), + ("xl/styles.xml", EXT_STYLES.as_bytes()), + ("xl/worksheets/sheet1.xml", s1.as_bytes()), + ("xl/worksheets/sheet2.xml", s2.as_bytes()), + ("xl/worksheets/_rels/sheet1.xml.rels", s1_rels.as_bytes()), + ("xl/pivotTables/pivotTable1.xml", t1.as_bytes()), + ("xl/pivotTables/_rels/pivotTable1.xml.rels", table_rels.as_bytes()), + ("xl/pivotCache/pivotCacheDefinition1.xml", cache.as_bytes()), + ("xl/pivotCache/_rels/pivotCacheDefinition1.xml.rels", cache_rels.as_bytes()), + ("xl/pivotCache/pivotCacheRecords1.xml", EXT_RECORDS.as_bytes()), + ]; + if shared { + parts.push(("xl/worksheets/_rels/sheet2.xml.rels", s2_rels.as_bytes())); + parts.push(("xl/pivotTables/pivotTable2.xml", t2.as_bytes())); + parts.push(("xl/pivotTables/_rels/pivotTable2.xml.rels", table_rels.as_bytes())); + } + make_zip(&parts) +} + +/// The written PivotTable parts of a sheet, through its relationships. +fn written_pivot_tables(u: &Unpacked, sheet: &str) -> Vec { + u.rels(&sheet_part(u, sheet)).into_iter().filter(|r| r.1.ends_with("/pivotTable")).map(|r| r.2).collect() +} + +/// `` entries of a written workbook: (cacheId, cache part). +fn written_pivot_caches(u: &Unpacked) -> Vec<(String, String)> { + let wb = xml::parse(u.parts.get("xl/workbook.xml").unwrap()).unwrap(); + wb.child("pivotCaches") + .map(|c| { + c.kids("pivotCache").map(|e| (e.attr("cacheId").unwrap().to_string(), u.target("xl/workbook.xml", e.attr("id").unwrap()).1)).collect() + }) + .unwrap_or_default() +} + +/// The font colour of `` number `dxf` and the code of number format `fmt` in written styles. +fn written_style(u: &Unpacked, dxf: &str, fmt: &str) -> (String, String) { + let st = xml::parse(u.parts.get("xl/styles.xml").unwrap()).unwrap(); + let d = st.child("dxfs").unwrap().kids("dxf").nth(dxf.parse().unwrap()).unwrap(); + let color = d.child("font").and_then(|f| f.child("color")).and_then(|c| c.attr("rgb")).unwrap_or("").to_string(); + let code = st.child("numFmts").unwrap().kids("numFmt").find(|n| n.attr("numFmtId") == Some(fmt)).unwrap().attr("formatCode").unwrap().to_string(); + (color, code) +} + +#[test] +fn pivot_tables_on_another_workbook_survive_a_save() { + for by_name in [false, true] { + let src = ext_pivot_package(by_name, false, "externalLinkPath"); + let (wb, rep) = read_xlsx(&src).unwrap(); + // Not modelled (GridCraft can't refresh it), but said so. + assert!(wb.sheets.iter().all(|s| s.pivots.is_empty())); + assert!(rep.warnings.iter().any(|w| w.contains("Ext1") && w.contains("another workbook")), "{:?}", rep.warnings); + assert!(!rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings); + let cache_src = ext_cache(if by_name { EXT_CACHE_NAME } else { EXT_CACHE_RANGE }); + // Twice: what the first save kept is read back and kept again. + let first = write_xlsx(&wb).unwrap(); + let (again, _) = read_xlsx(&first).unwrap(); + for saved in [first, write_xlsx(&again).unwrap()] { + let u = Unpacked::new(&saved); + u.assert_valid(); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 1, "{caches:?}"); + let (id, cache_part) = &caches[0]; + assert_eq!(id, "1", "the kept table refers to its cache by this id"); + assert_eq!(u.text(cache_part), cache_src); + let cache_rels = u.rels(cache_part); + let records = cache_rels.iter().find(|r| r.1.ends_with("/pivotCacheRecords")).unwrap(); + assert_eq!(u.text(&records.2), EXT_RECORDS); + assert!( + cache_rels.iter().any(|r| r.0 == "rId2" && r.1.ends_with("/externalLinkPath") && r.2 == EXT_LINK_TARGET && r.3), + "{cache_rels:?}" + ); + let tables = written_pivot_tables(&u, "Report"); + assert_eq!(tables.len(), 1); + assert!(written_pivot_tables(&u, "More").is_empty()); + let t = u.text(&tables[0]); + assert_eq!(u.rels(&tables[0]).iter().find(|r| r.1.ends_with("/pivotCacheDefinition")).unwrap().2, *cache_part); + // Style ids follow the rewritten styles part. + let (color, code) = written_style(&u, &attr_of(&t, "format", "dxfId"), &attr_of(&t, "dataField", "numFmtId")); + assert_eq!((color.as_str(), code.as_str()), ("FF0000FF", "0.0%"), "{t}"); + assert!(t.contains(r#"name="Ext1" cacheId="1""#), "{t}"); + // The report cells are plain cells and stay. + assert!(u.text(&sheet_part(&u, "Report")).contains("5")); + } + } +} + +#[test] +fn pivot_tables_sharing_a_cache_on_another_workbook_keep_one_cache() { + let (wb, _) = read_xlsx(&ext_pivot_package(false, true, "externalLinkPath")).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 1, "{caches:?}"); + assert_eq!(u.find(ext_cache(EXT_CACHE_RANGE).as_bytes()).len(), 1, "the cache is written once"); + for sheet in ["Report", "More"] { + let t = written_pivot_tables(&u, sheet); + assert_eq!(t.len(), 1, "{sheet}"); + assert_eq!(u.rels(&t[0])[0].2, caches[0].1, "{sheet}"); + } + + // Deleting one sheet keeps the cache for the other; when no kept table is left, it goes. + let mut one = wb.clone(); + one.sheets.remove(1); + let u = Unpacked::new(&write_xlsx(&one).unwrap()); + u.assert_valid(); + assert_eq!(written_pivot_caches(&u).len(), 1); + let mut none = wb.clone(); + none.sheets.iter_mut().for_each(|s| Arc::make_mut(s).preserved = None); + let u = Unpacked::new(&write_xlsx(&none).unwrap()); + u.assert_valid(); + assert!(written_pivot_caches(&u).is_empty()); + assert!(u.find(ext_cache(EXT_CACHE_RANGE).as_bytes()).is_empty() && u.find(EXT_RECORDS.as_bytes()).is_empty()); + assert!(!u.text("xl/workbook.xml").contains("pivotCaches")); +} + +#[test] +fn written_pivot_caches_do_not_reuse_kept_cache_ids() { + use gridcraft_core::{CellRef, Value}; + use gridcraft_model::{Cell, PivotField, PivotTable, PivotValue}; + let (mut wb, _) = read_xlsx(&ext_pivot_package(false, false, "externalLinkPath")).unwrap(); + // A PivotTable GridCraft models, on a list on "More". + { + let more = wb.sheet_mut(1).unwrap(); + for (a, v) in [("D1", Value::text("K")), ("E1", Value::text("V")), ("D2", Value::text("a")), ("E2", Value::number(2.0))] { + more.cells.set(CellRef::parse(a).unwrap(), Cell::value(v)); + } + more.pivots.push(PivotTable { + name: "Ours".into(), + source: "More!$D$1:$E$2".into(), + anchor: CellRef::parse("H3").unwrap(), + rows: vec![PivotField { source_col: "K".into(), ..Default::default() }], + values: vec![PivotValue { source_col: "V".into(), name: "Sum of V".into(), ..Default::default() }], + ..Default::default() + }); + } + let saved = write_xlsx(&wb).unwrap(); + let u = Unpacked::new(&saved); + u.assert_valid(); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 2, "{caches:?}"); + assert_ne!(caches[0].0, caches[1].0, "{caches:?}"); + let ours = written_pivot_tables(&u, "More"); + assert_eq!(ours.len(), 1); + let id = attr_of(&u.text(&ours[0]), "pivotTableDefinition", "cacheId"); + assert_ne!(id, "1"); + assert!(caches.iter().any(|(i, part)| *i == id && *part == u.rels(&ours[0])[0].2), "{caches:?}"); + let (back, _) = read_xlsx(&saved).unwrap(); + assert_eq!(back.sheet(1).unwrap().pivots.len(), 1); + assert_eq!(written_pivot_tables(&Unpacked::new(&write_xlsx(&back).unwrap()), "Report").len(), 1); +} + +#[test] +fn a_pivot_cache_naming_no_linked_workbook_is_not_kept() { + // The source `r:id` resolves to something other than a link to a workbook's path. + for kind in ["hyperlink", "http://example.com/unknown"] { + let (wb, rep) = read_xlsx(&ext_pivot_package(false, false, kind)).unwrap(); + assert!(wb.sheets.iter().all(|s| s.pivots.is_empty())); + assert!(rep.warnings.iter().any(|w| w.contains("another workbook") && w.contains("plain cells")), "{:?}", rep.warnings); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_caches(&u).is_empty() && written_pivot_tables(&u, "Report").is_empty()); + } +} + +#[test] +fn a_kept_pivot_table_whose_cache_is_not_listed_is_dropped() { + // The workbook doesn't list the cache: the table can't be written back without it. + let src = ext_pivot_package(false, false, "externalLinkPath"); + let mut parts = Unpacked::new(&src).parts; + let wbx = String::from_utf8(parts.remove("xl/workbook.xml").unwrap()).unwrap().replace(r#""#, ""); + parts.insert("xl/workbook.xml".into(), wbx.into_bytes()); + let list: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect(); + let (wb, rep) = read_xlsx(&make_zip(&list)).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("dropped")), "{:?}", rep.warnings); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_tables(&u, "Report").is_empty()); + assert!(written_pivot_caches(&u).is_empty()); +} + +#[test] +fn a_kept_pivot_table_with_an_unlisted_cache_id_is_dropped_even_with_a_cache_relationship() { + let src = ext_pivot_package(false, false, "externalLinkPath"); + let mut parts = Unpacked::new(&src).parts; + let table = String::from_utf8(parts.remove("xl/pivotTables/pivotTable1.xml").unwrap()).unwrap().replace(r#"cacheId="1""#, r#"cacheId="99""#); + parts.insert("xl/pivotTables/pivotTable1.xml".into(), table.into_bytes()); + let list: Vec<(&str, &[u8])> = parts.iter().map(|(n, d)| (n.as_str(), d.as_slice())).collect(); + let (wb, _) = read_xlsx(&make_zip(&list)).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_tables(&u, "Report").is_empty()); +} + +// ---------------------------------------------------------------- PivotTables on a data connection or the Data Model + +/// Bytes standing in for the Data Model (Excel's `xl/model/item.data`). +const MODEL_DATA: &[u8] = b"\x00\x01model bytes, not really a model\xFE\xFF"; +/// A larger stand-in, for running out of room to keep it. +static BIG_MODEL: [u8; 64 * 1024] = [7; 64 * 1024]; +const CT_MODEL: &str = "application/vnd.openxmlformats-officedocument.model+data"; +/// The model connection (id 1, as Excel writes it), a plain OLE DB connection (id 2) and a +/// worksheet connection loading a range into the model (id 3). +const MODEL_CONNECTIONS: &str = r#""#; +const CONN_RECORDS: &str = r#""#; + +/// An OLAP cache on the Data Model (no records: `saveData="0"`), on connection `id`. +fn model_cache(id: u32) -> String { + format!( + r#""# + ) +} + +/// A relational cache on connection `id`, with records. +fn conn_cache(id: u32) -> String { + format!( + r#""# + ) +} + +/// What a data-connection test package holds. +#[derive(Clone, Copy)] +struct ConnPkg { + /// The Data Model part and its workbook relationship. + model_part: bool, + /// The larger model stand-in. + big_model: bool, + /// `xl/connections.xml` and its workbook relationship. + connections: bool, + /// The connections part has a relationship to content GridCraft rewrites (so it can't be kept). + connections_blocked: bool, + /// The connection the Data Model cache names. + model_connection: u32, + /// The PivotTables have relationships to their caches (otherwise they name them by `cacheId`). + table_rels: bool, +} + +const CONN_PKG: ConnPkg = + ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1, table_rels: true }; + +/// Sheet "Report" with a PivotTable on the Data Model (cache 3) and sheet "More" with one on the +/// plain connection (cache 4, with records), plus the hidden name a worksheet connection uses. +fn conn_pivot_package(o: ConnPkg) -> Vec { + let workbook = format!( + r#""# + ); + let ct = |part: &str, ty: &str| format!(r#""#); + let content_types = format!( + r#"{}{}{}{}{}{}{}{}{}{}"#, + ct("xl/workbook.xml", "sheet.main"), + ct("xl/worksheets/sheet1.xml", "worksheet"), + ct("xl/worksheets/sheet2.xml", "worksheet"), + ct("xl/styles.xml", "styles"), + ct("xl/connections.xml", "connections"), + ct("xl/pivotTables/pivotTable1.xml", "pivotTable"), + ct("xl/pivotTables/pivotTable2.xml", "pivotTable"), + ct("xl/pivotCache/pivotCacheDefinition1.xml", "pivotCacheDefinition"), + ct("xl/pivotCache/pivotCacheDefinition2.xml", "pivotCacheDefinition"), + ct("xl/pivotCache/pivotCacheRecords2.xml", "pivotCacheRecords"), + ); + let sheet = |v: &str| { + format!( + r#"x{v}"# + ) + }; + let (s1, s2) = (sheet("5"), sheet("6")); + let (c1, c2) = (model_cache(o.model_connection), conn_cache(2)); + let (t1, t2) = (ext_table("OnModel", 3), ext_table("OnConnection", 4)); + let mut wb_rels = vec![ + ("rId1", "worksheet", "worksheets/sheet1.xml"), + ("rId2", "worksheet", "worksheets/sheet2.xml"), + ("rId3", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition1.xml"), + ("rId4", "styles", "styles.xml"), + ("rId7", "pivotCacheDefinition", "pivotCache/pivotCacheDefinition2.xml"), + ]; + if o.connections { + wb_rels.push(("rId5", "connections", "connections.xml")); + } + if o.model_part { + wb_rels.push(("rId6", "powerPivotData", "model/item.data")); + } + let wb_rels = rels(&wb_rels); + let t1_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition1.xml")]); + let t2_rels = rels(&[("rId1", "pivotCacheDefinition", "../pivotCache/pivotCacheDefinition2.xml")]); + let c2_rels = rels(&[("rId1", "pivotCacheRecords", "pivotCacheRecords2.xml")]); + let s1_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable1.xml")]); + let s2_rels = rels(&[("rId1", "pivotTable", "../pivotTables/pivotTable2.xml")]); + let conn_rels = rels(&[("rId1", "worksheet", "worksheets/sheet1.xml")]); + let mut parts: Vec<(&str, &[u8])> = vec![ + ("[Content_Types].xml", content_types.as_bytes()), + ("_rels/.rels", super::ROOT_RELS.as_bytes()), + ("xl/workbook.xml", workbook.as_bytes()), + ("xl/_rels/workbook.xml.rels", wb_rels.as_bytes()), + ("xl/styles.xml", EXT_STYLES.as_bytes()), + ("xl/worksheets/sheet1.xml", s1.as_bytes()), + ("xl/worksheets/sheet2.xml", s2.as_bytes()), + ("xl/worksheets/_rels/sheet1.xml.rels", s1_rels.as_bytes()), + ("xl/worksheets/_rels/sheet2.xml.rels", s2_rels.as_bytes()), + ("xl/pivotTables/pivotTable1.xml", t1.as_bytes()), + ("xl/pivotTables/_rels/pivotTable1.xml.rels", t1_rels.as_bytes()), + ("xl/pivotTables/pivotTable2.xml", t2.as_bytes()), + ("xl/pivotTables/_rels/pivotTable2.xml.rels", t2_rels.as_bytes()), + ("xl/pivotCache/pivotCacheDefinition1.xml", c1.as_bytes()), + ("xl/pivotCache/pivotCacheDefinition2.xml", c2.as_bytes()), + ("xl/pivotCache/_rels/pivotCacheDefinition2.xml.rels", c2_rels.as_bytes()), + ("xl/pivotCache/pivotCacheRecords2.xml", CONN_RECORDS.as_bytes()), + ]; + if !o.table_rels { + parts.retain(|(name, _)| !name.starts_with("xl/pivotTables/_rels/")); + } + if o.connections { + parts.push(("xl/connections.xml", MODEL_CONNECTIONS.as_bytes())); + } + if o.connections_blocked { + parts.push(("xl/_rels/connections.xml.rels", conn_rels.as_bytes())); + } + if o.model_part { + parts.push(("xl/model/item.data", if o.big_model { &BIG_MODEL[..] } else { MODEL_DATA })); + } + make_zip(&parts) +} + +/// The content type a written package gives a part. +fn content_type_of(u: &Unpacked, part: &str) -> String { + let types = xml::parse(u.parts.get("[Content_Types].xml").unwrap()).unwrap(); + if let Some(o) = types.kids("Override").find(|o| normalize(o.attr("PartName").unwrap()) == normalize(part)) { + return o.attr("ContentType").unwrap().to_string(); + } + let ext = part.rsplit('.').next().unwrap().to_ascii_lowercase(); + types.kids("Default").find(|d| d.attr("Extension").unwrap().eq_ignore_ascii_case(&ext)).unwrap().attr("ContentType").unwrap().to_string() +} + +/// Bytes kept by a read workbook. +fn kept_bytes(wb: &gridcraft_model::Workbook) -> usize { + wb.preserved.as_ref().map_or(0, |p| p.byte_len()) + wb.sheets.iter().filter_map(|s| s.preserved.as_ref()).map(|p| p.byte_len()).sum::() +} + +#[test] +fn pivot_tables_on_the_data_model_and_a_connection_survive_a_save() { + let (wb, rep) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap(); + assert!(wb.sheets.iter().all(|s| s.pivots.is_empty()), "not modelled: GridCraft can't refresh them"); + assert!(rep.warnings.iter().any(|w| w.contains("OnModel") && w.contains("Data Model")), "{:?}", rep.warnings); + assert!(rep.warnings.iter().any(|w| w.contains("OnConnection") && w.contains("a data connection")), "{:?}", rep.warnings); + assert!(rep.warnings.iter().any(|w| w.contains("Data Model is kept")), "{:?}", rep.warnings); + assert!(!rep.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep.warnings); + // Twice: what the first save kept is read back and kept again. + let first = write_xlsx(&wb).unwrap(); + let (again, rep2) = read_xlsx(&first).unwrap(); + assert!(!rep2.warnings.iter().any(|w| w.contains("dropped") || w.contains("plain cells")), "{:?}", rep2.warnings); + for saved in [first, write_xlsx(&again).unwrap()] { + let u = Unpacked::new(&saved); + u.assert_valid(); + // The Data Model: same bytes, name and content type, related from the workbook. + assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA)); + assert_eq!(content_type_of(&u, "xl/model/item.data"), CT_MODEL); + let wb_rels = u.rels("xl/workbook.xml"); + assert!(wb_rels.iter().any(|r| r.1.ends_with("/powerPivotData") && r.2 == "xl/model/item.data"), "{wb_rels:?}"); + // The connections the caches name by id, and the hidden name a worksheet connection uses. + let conn = wb_rels.iter().find(|r| r.1.ends_with("/connections")).unwrap(); + assert_eq!(u.text(&conn.2), MODEL_CONNECTIONS); + assert!(u.text("xl/workbook.xml").contains("_xlcn.WorksheetConnection_T")); + let caches = written_pivot_caches(&u); + assert_eq!(caches.len(), 2, "{caches:?}"); + let cache = |id: &str| caches.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{caches:?}")).1.clone(); + assert_eq!(u.text(&cache("3")), model_cache(1)); + assert!(u.rels(&cache("3")).is_empty()); + assert_eq!(u.text(&cache("4")), conn_cache(2)); + let records = u.rels(&cache("4")).into_iter().find(|r| r.1.ends_with("/pivotCacheRecords")).unwrap(); + assert_eq!(u.text(&records.2), CONN_RECORDS); + for (sheet, name, id) in [("Report", "OnModel", "3"), ("More", "OnConnection", "4")] { + let t = written_pivot_tables(&u, sheet); + assert_eq!(t.len(), 1, "{sheet}"); + assert_eq!(u.rels(&t[0])[0].2, cache(id), "{sheet}"); + let x = u.text(&t[0]); + assert!(x.contains(&format!(r#"name="{name}" cacheId="{id}""#)), "{x}"); + let (color, code) = written_style(&u, &attr_of(&x, "format", "dxfId"), &attr_of(&x, "dataField", "numFmtId")); + assert_eq!((color.as_str(), code.as_str()), ("FF0000FF", "0.0%"), "{x}"); + } + } +} + +#[test] +fn the_data_model_is_kept_without_pivot_tables() { + let (mut wb, _) = read_xlsx(&conn_pivot_package(CONN_PKG)).unwrap(); + wb.sheets.iter_mut().for_each(|s| Arc::make_mut(s).preserved = None); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert_eq!(u.parts.get("xl/model/item.data").map(Vec::as_slice), Some(MODEL_DATA)); + // No kept table uses the caches any more: they go. + assert!(written_pivot_caches(&u).is_empty()); + assert!(u.find(model_cache(1).as_bytes()).is_empty() && u.find(CONN_RECORDS.as_bytes()).is_empty()); +} + +#[test] +fn data_model_pivot_tables_without_the_model_are_kept_as_plain_cells() { + // No model part, or no room left to keep it: the PivotTable on the model couldn't be + // refreshed and is dropped (its cells stay); the one on a plain connection is kept. + for too_large in [false, true] { + let pkg = ConnPkg { model_part: too_large, big_model: too_large, ..CONN_PKG }; + let src = conn_pivot_package(pkg); + let (wb, rep) = if too_large { + // Room for everything but the model: the caches are kept after it. + let all = kept_bytes(&read_xlsx(&src).unwrap().0); + crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(all - BIG_MODEL.len())); + let read = read_xlsx(&src); + crate::passthrough::KEPT_TOTAL_FOR_TEST.with(|c| c.set(crate::passthrough::MAX_KEPT_TOTAL)); + let r = read.unwrap(); + assert!(r.1.warnings.iter().any(|w| w.contains("Data Model was dropped") && w.contains("too large")), "{:?}", r.1.warnings); + r + } else { + read_xlsx(&src).unwrap() + }; + let w = &rep.warnings; + assert!( + w.iter().any(|w| w.contains("1 PivotTable cache(s) on the workbook's Data Model were dropped") && w.contains("plain cells")), + "{w:?}" + ); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(!u.parts.contains_key("xl/model/item.data")); + assert!(written_pivot_tables(&u, "Report").is_empty()); + assert!(u.find(model_cache(1).as_bytes()).is_empty()); + assert!(u.text(&sheet_part(&u, "Report")).contains("5"), "the report cells stay"); + let caches = written_pivot_caches(&u); + assert_eq!(caches.iter().map(|c| c.0.as_str()).collect::>(), ["4"], "{caches:?}"); + assert_eq!(written_pivot_tables(&u, "More").len(), 1); + } +} + +#[test] +fn pivot_tables_naming_their_cache_by_id_go_with_a_dropped_cache() { + // No connections part: both caches are dropped, and the tables that name them only by + // `cacheId` must not stay behind with an id the workbook no longer lists. + let (wb, _) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, table_rels: false, ..CONN_PKG })).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + for sheet in ["Report", "More"] { + assert!(written_pivot_tables(&u, sheet).is_empty(), "{sheet}"); + } + assert!(written_pivot_caches(&u).is_empty()); +} + +#[test] +fn pivot_tables_naming_their_cache_by_id_keep_it() { + let (wb, _) = read_xlsx(&conn_pivot_package(ConnPkg { table_rels: false, ..CONN_PKG })).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + for sheet in ["Report", "More"] { + assert_eq!(written_pivot_tables(&u, sheet).len(), 1, "{sheet}"); + } + let caches = written_pivot_caches(&u); + assert_eq!(caches.iter().map(|c| c.0.as_str()).collect::>(), ["3", "4"], "{caches:?}"); +} + +#[test] +fn connection_pivot_tables_need_their_connections() { + // No connections part: the caches name connections that aren't there. + let (none, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, ..CONN_PKG })).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings); + // A cache naming a connection id the part doesn't have; the other cache is unaffected. + let (missing, rep) = read_xlsx(&conn_pivot_package(ConnPkg { model_connection: 9, ..CONN_PKG })).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("data connection is not in the workbook")), "{:?}", rep.warnings); + // A connections part that can't be kept: the model and every connection cache go with it. + let (blocked, rep) = read_xlsx(&conn_pivot_package(ConnPkg { connections_blocked: true, ..CONN_PKG })).unwrap(); + assert!(rep.warnings.iter().any(|w| w.contains("Data Model was dropped")), "{:?}", rep.warnings); + assert!(rep.warnings.iter().any(|w| w.contains("2 PivotTable cache(s)") && w.contains("connections were not kept")), "{:?}", rep.warnings); + for (wb, all_gone) in [(none, true), (blocked, true), (missing, false)] { + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + assert!(written_pivot_tables(&u, "Report").is_empty()); + assert!(u.text(&sheet_part(&u, "Report")).contains("5")); + if all_gone { + assert!(written_pivot_tables(&u, "More").is_empty()); + assert!(written_pivot_caches(&u).is_empty()); + assert!(!u.parts.contains_key("xl/model/item.data")); + } else { + assert_eq!(written_pivot_tables(&u, "More").len(), 1); + } + } +} #[test] fn modelled_form_controls_join_kept_ones_in_one_controls_element() { use gridcraft_model::{Anchor, ControlKind, FormControl}; diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index ca6b7093e1..d810f3b64c 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -23,6 +23,11 @@ fn sample() -> Workbook { wb.calc = CalcSettings { mode: CalcMode::Manual, iterative: true, max_iterations: 42, max_change: 0.5, precision_as_displayed: true, r1c1: true }; wb.protected_structure = true; wb.structure_password = Some(gridcraft_model::PasswordHash::new_sha512("s3cret", b"0123456789abcdef")); + wb.write_reservation = Some(gridcraft_model::WriteReservation { + user_name: "Ann & ".into(), + read_only_recommended: true, + password: Some(gridcraft_model::PasswordHash::new_sha512("modify-me", b"fedcba9876543210")), + }); wb.props = DocProps { title: "T & ".into(), subject: "S".into(), @@ -447,6 +452,8 @@ fn sample() -> Workbook { ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked, + ChartKind::LineStacked100, + ChartKind::LineStacked100Markers, ChartKind::Pie, ChartKind::Doughnut, ChartKind::Area, @@ -530,6 +537,8 @@ fn assert_workbook_metadata_roundtrip(wb: &Workbook, back: &Workbook) { assert!(back.protected_structure); assert_eq!(back.structure_password, wb.structure_password); assert!(back.structure_password.as_ref().unwrap().verify("s3cret").unwrap()); + assert_eq!(back.write_reservation, wb.write_reservation); + assert!(back.write_reservation.as_ref().and_then(|r| r.password.as_ref()).unwrap().verify("modify-me").unwrap()); assert_eq!(back.props, wb.props); assert_eq!(back.theme, wb.theme); assert_eq!(back.names, wb.names); @@ -1922,6 +1931,25 @@ fn japanese_paper_sizes_round_trip() { assert_eq!(back.sheet(0).unwrap().print.paper, "B5"); } +/// The paper names every spelling folds onto keep their file id: `11x17` is Tabloid (3), and +/// ISO B5 is id 34 (ECMA-376's 176×250 mm "B5 envelope"), read back as `B5 (ISO)`. An empty +/// paper (none stated) writes no `paperSize`, so the reader's own paper applies. +#[test] +fn paper_names_keep_their_xlsx_id_and_an_unstated_paper_writes_none() { + for (paper, id, back_as) in [("11x17", 3, "Tabloid"), ("US Legal", 5, "Legal"), ("B5 (ISO)", 34, "B5 (ISO)"), ("Envelope B5", 34, "B5 (ISO)")] { + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().print.paper = paper.into(); + let bytes = write_xlsx(&wb).unwrap(); + assert!(sheet1_xml(&bytes).0.contains(&format!("paperSize=\"{id}\"")), "{paper}"); + let (back, _) = read_xlsx(&bytes).unwrap(); + assert_eq!(back.sheet(0).unwrap().print.paper, back_as); + } + let mut wb = Workbook::new(); + wb.sheet_mut(0).unwrap().print.paper = String::new(); + let (xml, _) = sheet1_xml(&write_xlsx(&wb).unwrap()); + assert!(!xml.contains("paperSize"), "{xml}"); +} + /// A table's dropdown filter lives in `sheet.autofilter` (the engine's only live filter state), /// not in `Table::filter`. Writing used to suppress the sheet `` because a table /// intersects it and write the table part from `Table::filter`, which was empty: the criteria @@ -1966,9 +1994,9 @@ fn a_table_filter_criteria_survive_a_round_trip() { assert!(b.autofilter.is_none(), "a table's filter belongs to the table part, not the sheet"); } -/// Stored `colId` offsets are relative to the filter range's first column, so criteria of a filter -/// that starts right of the table's first column must not be folded into the table part, where -/// they would apply to the wrong column. +/// Stored `colId` offsets are relative to the table's first column, so criteria of a sheet filter +/// that starts right of the table's first column are moved to the column they filter (Region), not +/// kept at the filter's own offset (which would be Id). #[test] fn a_partial_sheet_filter_is_not_folded_into_a_table() { let mut wb = Workbook::new(); @@ -2002,10 +2030,28 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() { assert!(rep.warnings.is_empty(), "{:?}", rep.warnings); let b = back.sheet(0).unwrap(); let t = b.tables.first().expect("the table survived"); - assert!(t.filter.is_empty(), "the criteria landed on the wrong table column: {:?}", t.filter); + assert!( + matches!(t.filter.as_slice(), [(1, FilterCriterion::Values { values, .. })] if values == &["East".to_string()]), + "the criteria landed on the wrong table column: {:?}", + t.filter + ); assert!(b.autofilter.is_none(), "a sheet filter inside a table would be invalid"); } +#[test] +fn legacy_reservation_password_is_written_with_a_user_name() { + let mut wb = sample(); + wb.write_reservation = + Some(WriteReservation { user_name: String::new(), read_only_recommended: false, password: Some(PasswordHash::Legacy(0x83AF)) }); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let r = back.write_reservation.expect("the reservation survived"); + assert_eq!(r.password, Some(PasswordHash::Legacy(0x83AF)), "a nameless legacy password is kept, under a placeholder name"); + assert!(!r.user_name.is_empty()); + wb.write_reservation.as_mut().unwrap().user_name = "Ann".into(); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert_eq!(back.write_reservation.and_then(|r| r.password), Some(PasswordHash::Legacy(0x83AF))); +} + #[test] fn workbook_view_settings_survive_a_round_trip() { // #3057: a workbook Excel saved with the sheet tabs and both scroll bars hidden diff --git a/crates/xlsx/src/tests/tablefilter.rs b/crates/xlsx/src/tests/tablefilter.rs new file mode 100644 index 0000000000..e8e9ff906d --- /dev/null +++ b/crates/xlsx/src/tests/tablefilter.rs @@ -0,0 +1,114 @@ +//! A sheet AutoFilter that filters a table is saved as the table's own filter (a file can't hold +//! a sheet AutoFilter that overlaps a table), so the rows it hides reopen as filtered rows. + +use gridcraft_core::{CellRef, RangeRef, Value}; +use gridcraft_model::*; + +use crate::{read_xlsx, write_xlsx}; + +fn rr(a: &str) -> RangeRef { + RangeRef::parse(a).unwrap() +} + +fn table(range: &str, cols: &[&str]) -> Table { + Table { + id: 1, + name: "T".into(), + range: rr(range), + header_row: true, + totals_row: false, + columns: cols + .iter() + .map(|n| TableColumn { name: (*n).into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None }) + .collect(), + style: String::new(), + banded_rows: true, + banded_cols: false, + first_col: false, + last_col: false, + filter_button: true, + filter: vec![], + table_type: None, + connection_id: None, + } +} + +/// Table B2:C6 (Name, Qty) with rows 4 and 6 hidden by a filter on Name. +fn filtered(af_range: &str, af_col: u32) -> Workbook { + let mut wb = Workbook::new(); + let s = wb.sheet_mut(0).unwrap(); + s.set_value(CellRef::new(1, 1), Value::text("Name")); + s.set_value(CellRef::new(1, 2), Value::text("Qty")); + for (i, n) in ["a", "b", "c", "d"].iter().enumerate() { + let row = 2 + i as u32; + s.set_value(CellRef::new(row, 1), Value::text(*n)); + s.set_value(CellRef::new(row, 2), Value::Number(10f64.powi(i as i32))); + } + let mut t = table("B2:C6", &["Name", "Qty"]); + // A criterion the table already had (from the file it was opened from) on the Qty column. + t.filter = vec![(1, FilterCriterion::Custom { a: (">".into(), "0".into()), b: None, and: true })]; + s.tables.push(t); + s.autofilter = Some(AutoFilter { + range: rr(af_range), + criteria: vec![(af_col, FilterCriterion::Values { values: vec!["a".into(), "c".into()], blanks: false })], + }); + for row in [3, 5] { + s.rows.entry(row).or_default().hidden = true; + } + wb +} + +#[test] +fn table_filter_through_the_sheet_autofilter_is_saved_with_the_table() { + let wb = filtered("B2:C6", 0); + assert!(wb.sheets[0].is_row_filtered(3)); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = back.sheet(0).unwrap(); + assert!(s.autofilter.is_none(), "no sheet AutoFilter over a table"); + let t = &s.tables[0]; + assert_eq!(t.filter.len(), 2, "{:?}", t.filter); + assert_eq!(t.filter[0].0, 0); + assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()])); + assert!(matches!(&t.filter[1].1, FilterCriterion::Custom { .. }), "the table's own criterion is kept"); + for row in [3, 5] { + assert!(s.is_row_filtered(row), "row {} reopens as filtered", row + 1); + } + assert!(!s.is_row_hidden(2) && !s.is_row_hidden(4)); +} + +#[test] +fn sheet_autofilter_starting_left_of_the_table_maps_its_columns() { + // The filter starts one column left of the table on its header row: Name is column 1 of the + // filter and column 0 of the table; a criterion on the column outside the table is dropped. + let mut wb = filtered("A2:C6", 1); + if let Some(af) = wb.sheet_mut(0).unwrap().autofilter.as_mut() { + af.criteria.push((0, FilterCriterion::Values { values: vec!["zz".into()], blanks: true })); + } + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let t = &back.sheet(0).unwrap().tables[0]; + let cols: Vec = t.filter.iter().map(|(c, _)| *c).collect(); + assert_eq!(cols, [0, 1]); + assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()])); +} + +#[test] +fn sheet_autofilter_not_on_the_header_row_is_not_folded() { + let wb = filtered("B1:C6", 0); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let s = back.sheet(0).unwrap(); + assert!(s.autofilter.is_none()); + let cols: Vec = s.tables[0].filter.iter().map(|(c, _)| *c).collect(); + assert_eq!(cols, [1], "only the table's own criterion"); +} + +#[test] +fn disabled_table_filter_saves_no_autofilter_criteria() { + let mut wb = filtered("B2:C6", 0); + if let Some(t) = wb.sheet_mut(0).unwrap().tables.first_mut() { + t.filter_button = false; + t.filter.clear(); + } + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + let t = &back.sheet(0).unwrap().tables[0]; + assert!(!t.filter_button && t.filter.is_empty(), "{:?}", t.filter); +} diff --git a/crates/xlsx/src/write.rs b/crates/xlsx/src/write.rs index acca0f9386..8845f1b8ff 100644 --- a/crates/xlsx/src/write.rs +++ b/crates/xlsx/src/write.rs @@ -174,6 +174,12 @@ impl Out { self.media.insert(key, file.clone()); file } + /// Replaces the bytes of a part already added. + pub fn replace(&mut self, name: &str, data: Vec) { + if let Some(p) = self.parts.iter_mut().find(|(n, _)| n == name) { + p.1 = data; + } + } pub fn default_type(&mut self, ext: &str, ct: &str) { self.defaults.entry(ext.to_string()).or_insert_with(|| ct.to_string()); } @@ -233,6 +239,29 @@ fn check_sheet_names(wb: &Workbook) -> Result<(), IoError> { /// Workbook name written in a PivotChart's link when the file name isn't known. const DEFAULT_BOOK_NAME: &str = "Workbook.xlsx"; +fn append_file_sharing(w: &mut String, wb: &Workbook) { + let Some(r) = &wb.write_reservation else { return }; + w.push_str(" { + let _ = write!(w, " reservationPassword=\"{h:04X}\""); + } + Some(h) => w.push_str(&crate::sheet_write::password_attrs(h, "")), + None => {} + } + w.push_str("/>"); +} + pub fn write_xlsx(wb: &Workbook, kind: XlsxKind, functions: FunctionInfo) -> Result, IoError> { write_xlsx_named_with(wb, kind, None, functions) } @@ -261,14 +290,18 @@ fn workbook_view_attrs(wb: &Workbook) -> String { /// Writes the workbook for the file `book_name` (a bare file name). A PivotChart is bound to its /// PivotTable in Excel only when its link starts with the workbook in brackets. -pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>, functions: FunctionInfo) -> Result, IoError> { +fn validate_xlsx_workbook(wb: &Workbook) -> Result<(), IoError> { if wb.sheets.is_empty() { return Err(IoError::Format("a workbook needs at least one sheet".into())); } if wb.sheets.iter().any(|sheet| sheet.cell_pictures.keys().any(|c| sheet.cell(*c).is_some_and(|cell| cell.formula.is_some()))) { return Err(IoError::Format("a static cell picture cannot also contain a formula".into())); } - check_sheet_names(wb)?; + check_sheet_names(wb) +} + +pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&str>, functions: FunctionInfo) -> Result, IoError> { + validate_xlsx_workbook(wb)?; let mut out = Out { parts: vec![], overrides: vec![], @@ -310,77 +343,23 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s }; let mut wb_rels = Rels::default(); - let (sheets_xml, kept, pivots) = write_sheets(wb, &mut out, active, &mut wb_rels); + let (sheets_xml, kept, mut pivots) = write_sheets(wb, &mut out, active, &mut wb_rels); let names = write_defined_names(wb, &kept, &out.chart_names); - let mut w = format!("{XML_DECL}"); - // A workbook read from a file keeps its as it was: Excel trusts the saved values - // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. - let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); - w.push_str(if file_version.is_empty() { "" } else { &file_version }); - w.push_str(" {} - ShowObjects::Placeholders => w.push_str(" showObjects=\"placeholders\""), - ShowObjects::None => w.push_str(" showObjects=\"none\""), - } - if wb.date_system == gridcraft_core::DateSystem::D1904 { - w.push_str(" date1904=\"1\""); - } - if wb.remove_personal_info { - w.push_str(" filterPrivacy=\"1\""); - } - w.push_str("/>"); - if wb.protected_structure { - let pw = wb.structure_password.as_ref().map(|h| crate::sheet_write::password_attrs(h, "workbook")).unwrap_or_default(); - let _ = write!(w, ""); - } - let _ = write!(w, "{sheets_xml}"); - w.push_str(&kept.elements); - if !names.is_empty() { - let _ = write!(w, "{names}"); - } - w.push_str(" {} - CalcMode::Manual => w.push_str(" calcMode=\"manual\""), - CalcMode::AutomaticExceptTables => w.push_str(" calcMode=\"autoNoTable\""), - } - // CT_CalcPr defaults: iterate off, 100 iterations, 0.001 maximum change. The limits are kept - // while iteration is off, as Options keeps them. - let calc = &wb.calc; - if calc.iterative { - w.push_str(" iterate=\"1\""); - } - if calc.iterative || calc.max_iterations != CalcSettings::DEFAULT_ITERATIONS { - let _ = write!(w, " iterateCount=\"{}\"", calc.max_iterations); - } - if calc.iterative || calc.max_change != CalcSettings::DEFAULT_CHANGE { - let _ = write!(w, " iterateDelta=\"{}\"", crate::xml::num(calc.max_change)); - } - if wb.calc.precision_as_displayed { - w.push_str(" fullPrecision=\"0\""); - } - if wb.calc.r1c1 { - w.push_str(" refMode=\"R1C1\""); - } - if out.needs_calc { - w.push_str(" fullCalcOnLoad=\"1\""); - } - w.push_str("/>"); - w.push_str(&pivots.workbook_xml(&mut wb_rels)); - let exts = crate::passthrough::workbook_elements(wb, "ext"); - if !exts.is_empty() { - let _ = write!(w, "{exts}"); - } - w.push_str(""); + let w = write_workbook_xml(WorkbookHeader { wb, active }, &sheets_xml, &names, &kept, &mut pivots, &mut wb_rels, out.needs_calc); // Workbook-level parts. - let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &pivots.number_formats(wb), std::mem::take(&mut out.num_fmts)); - pivots.finish(wb, &mut out, &|code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied())); + let mut extra_fmts = pivots.number_formats(wb); + for code in out.kept.num_fmt_codes() { + if !extra_fmts.contains(&code) { + extra_fmts.push(code); + } + } + let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &extra_fmts, std::mem::take(&mut out.num_fmts)); + let fmt_id = |code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied()); + pivots.finish(wb, &mut out, &fmt_id); + crate::passthrough::finish_style_ids(&mut out, &fmt_id); out.part("xl/styles.xml", Some("application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"), styles.into_bytes()); wb_rels.add("styles", "styles.xml"); if !out.python_scripts.is_empty() { @@ -503,6 +482,88 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s zip.finish() } +struct WorkbookHeader<'a> { + wb: &'a Workbook, + active: usize, +} + +fn write_workbook_xml( + header: WorkbookHeader<'_>, + sheets_xml: &str, + names: &str, + kept: &crate::passthrough::WorkbookKept, + pivots: &mut crate::pivot::PivotWriter, + wb_rels: &mut Rels, + needs_calc: bool, +) -> String { + let WorkbookHeader { wb, active } = header; + let mut w = format!("{XML_DECL}"); + // A workbook read from a file keeps its as it was: Excel trusts the saved values + // only when appName is "xl" (#799). One without names GridCraft (#1699), and Excel recalculates it. + let file_version = crate::passthrough::workbook_elements(wb, "fileVersion"); + w.push_str(if file_version.is_empty() { "" } else { &file_version }); + append_file_sharing(&mut w, wb); + w.push_str(" {} + ShowObjects::Placeholders => w.push_str(" showObjects=\"placeholders\""), + ShowObjects::None => w.push_str(" showObjects=\"none\""), + } + if wb.date_system == gridcraft_core::DateSystem::D1904 { + w.push_str(" date1904=\"1\""); + } + if wb.remove_personal_info { + w.push_str(" filterPrivacy=\"1\""); + } + w.push_str("/>"); + if wb.protected_structure { + let pw = wb.structure_password.as_ref().map(|h| crate::sheet_write::password_attrs(h, "workbook")).unwrap_or_default(); + let _ = write!(w, ""); + } + let _ = write!(w, "{sheets_xml}"); + w.push_str(&kept.elements); + if !names.is_empty() { + let _ = write!(w, "{names}"); + } + w.push_str(" {} + CalcMode::Manual => w.push_str(" calcMode=\"manual\""), + CalcMode::AutomaticExceptTables => w.push_str(" calcMode=\"autoNoTable\""), + } + // CT_CalcPr defaults: iterate off, 100 iterations, 0.001 maximum change. The limits are kept + // while iteration is off, as Options keeps them. + let calc = &wb.calc; + if calc.iterative { + w.push_str(" iterate=\"1\""); + } + if calc.iterative || calc.max_iterations != CalcSettings::DEFAULT_ITERATIONS { + let _ = write!(w, " iterateCount=\"{}\"", calc.max_iterations); + } + if calc.iterative || calc.max_change != CalcSettings::DEFAULT_CHANGE { + let _ = write!(w, " iterateDelta=\"{}\"", crate::xml::num(calc.max_change)); + } + if wb.calc.precision_as_displayed { + w.push_str(" fullPrecision=\"0\""); + } + if wb.calc.r1c1 { + w.push_str(" refMode=\"R1C1\""); + } + if needs_calc { + w.push_str(" fullCalcOnLoad=\"1\""); + } + w.push_str("/>"); + w.push_str(&pivots.workbook_xml(wb_rels)); + let exts = crate::passthrough::workbook_elements(wb, "ext"); + if !exts.is_empty() { + let _ = write!(w, "{exts}"); + } + w.push_str(""); + w +} + fn write_sheets( wb: &Workbook, out: &mut Out, @@ -511,7 +572,7 @@ fn write_sheets( ) -> (String, crate::passthrough::WorkbookKept, crate::pivot::PivotWriter) { // Kept content first: the chart sheets among the worksheets need their relationship ids. let kept = crate::passthrough::write_workbook(wb, wb_rels, out); - let mut pivots = crate::pivot::PivotWriter::default(); + let mut pivots = crate::pivot::PivotWriter::new(kept.pivot_cache_ids(), kept.pivot_cache_entries()); let mut sheets_xml = String::new(); let any_visible = wb.sheets.iter().any(|s| s.visibility == Visibility::Visible); let mut ids = crate::passthrough::SheetIds::new(wb, &kept); diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index 9ce69909d7..357617bc7d 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -244,7 +244,7 @@ fn preserve_external_links( let part_name = format!("xl/externalLinks/externalLink{next_ordinal}.xml"); let (xml, rels) = external_link_part_xml(book); p.rels.push(PreservedRel { id: rid.clone(), rel_type: format!("{NS_REL}/externalLink"), target: part_name.clone(), external: false }); - p.parts.push(PreservedPart { name: part_name, content_type: CT_EXT_LINK.into(), data: xml.into_bytes().into(), rels }); + p.parts.push(PreservedPart { name: part_name, content_type: CT_EXT_LINK.into(), data: xml.into_bytes().into(), rels, ..Default::default() }); let _ = write!(refs_xml, ""); } if had_unpreserved { diff --git a/docs/architecture.md b/docs/architecture.md index 051f15f21f..4fc0e31397 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (paper names and sizes in one table, `model::paper`; earlier: one workbook-wide reference rewrite; earlier: shared CJK fallback baselines; earlier: Python mode in the formula bar; earlier: Python cells as data; earlier: equations: the `math` crate and the layout cache; earlier: recently used functions kept in the preferences; Function Library module; accent icons; earlier: the hidden names that hold macros) · **Target:** Microsoft Excel (Microsoft 365) How GridCraft is built today. Rules for contributors are in [`AGENTS.md`](../AGENTS.md). @@ -17,7 +17,7 @@ including tests, 2026-10-10. | L1 | `formula` | ~1.7k | Tokenizer, parser, AST, printer (A1 and R1C1), reference adjustment for copy, fill and structural edits | | L1 | `functions` | ~13.4k | The function library: `FnSpec` registry (name, arity, category, scalar args, signature, description) and pure implementations; automatic array lifting | | L1 | `math` | ~1.1k | Equations: LaTeX laid out by RaTeX (MIT, pinned) into plain glyph, rule and path data, and LaTeX to Office Math; every entry point capped and panic-guarded | -| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings, protection | +| L2 | `model` | ~2.2k | Workbook, sheets, copy-on-write cell store (64-row bands behind `Arc`), interned styles, names, tables, CF, validation, comments, charts, shapes, images, sparklines, print settings (paper names and sizes in `paper`, the one table file formats and print layout read), protection | | L2 | `calc` | ~2.9k | Evaluator (references, names, tables, LET/LAMBDA, special forms like OFFSET/INDIRECT/SUBTOTAL) and dependency-graph recalculation with dynamic arrays, spills and cycle detection; single-threaded | | L2 | `xlsx` | ~10.7k | XLSX read/write (transitional and strict read), CSV/TSV, XLSB and ODS data import, PivotTable caches, DrawingML charts and drawings; byte slices only (WASM-safe); lenient reader that reports warnings | | L2 | `pdf` | ~1k | Small PDF 1.7 writer (14 standard fonts, vectors, images) for print and export | @@ -272,6 +272,7 @@ rpm, tarball), FreeBSD, and web (WASM; WebGPU or WebGL2). Release workflows in | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Paper sizes: `model::paper` (`canonical`, `size_pt`, `for_size`) replaces the engine's `known_paper` and the XLSX alias list; an empty `PrintSettings::paper` means no paper is stated (no reader sets it yet); `for_size` picks the nearest paper; Statement, Envelope #10 and Envelope DL are accepted by Page Setup and Size | | 2026-11-13 | minor | Reference rewriting: `Workbook::rewrite_references` as the one walker for every reference-moving edit; rule formulas re-hosted by how their ranges moved and moved with a cut | | 2026-11-02 | minor | Python mode in the formula bar: Python mode on the shared editor, `code_field` and its stop keys; drafts follow their sheet by `model::SheetUid` | | 2026-11-02 | minor | Python cells as data: `model::PyCode`, the file forms, calc laying out kept results, the limits on open, and what copying, filling and sorting do to `xl()` references; edits that would push code past the limit are refused | diff --git a/docs/chart-parity.md b/docs/chart-parity.md index 37f482eeb0..dc8c468c07 100644 --- a/docs/chart-parity.md +++ b/docs/chart-parity.md @@ -17,7 +17,7 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate |---|---|---|---| | Column | clustered, stacked, 100% stacked, 3-D clustered/stacked/100%, 3-D column | 3 of 7 | no 3-D | | Bar | clustered, stacked, 100%, 3-D ×3 | 3 of 6 | no 3-D | -| Line | line, stacked, 100% stacked, with markers ×3, 3-D line | 3 of 7 (line, with markers, stacked) | no 100% stacked; smoothed lines landed (#62) | +| Line | line, stacked, 100% stacked, with markers ×3, 3-D line | 5 of 7 (line, with markers, stacked, 100% stacked, 100% stacked with markers) | no stacked with markers, no 3-D; 100% stacked drawn as shares of each category's total and kept as `percentStacked` in XLSX; smoothed lines landed (#62) | | Pie | pie, 3-D pie, pie of pie, bar of pie, doughnut | 2 of 5 (pie, doughnut) | no exploded, pie of pie, bar of pie; doughnut draws every series as a concentric ring, first series innermost; its legend names categories, matching Excel's default vary-by-category colours | | Area | area, stacked, 100%, 3-D ×3 | 3 of 6 | no 3-D; 100% stacked drawn as shares of each category's total and kept as `percentStacked` in XLSX | | X Y (scatter) | markers, smooth lines (±markers), straight lines (±markers) | 2 of 5 | no smooth lines | @@ -32,8 +32,8 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate | Box & Whisker | 1 | 1 of 1 | | | Waterfall, Funnel | 2 | 2 of 2 | | | Filled map | 1 | 0 | needs geographic boundary data (licensing decision) | -| Combo | custom combinations, secondary axis | yes: each series drawn as its own kind (column, stacked column, line, line with markers, area; bars stand upright as columns, pies, doughnuts, bubbles and chartex kinds are clustered columns, scatter series lines with markers, scatter-with-lines and radar series lines), secondary axis | | -| **Total** | ~60 subtypes | **26 (~43%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | +| Combo | custom combinations, secondary axis | yes: each series drawn as its own kind (column, stacked column, line, line with markers, 100% stacked line with or without markers, area; bars stand upright as columns, pies, doughnuts, bubbles and chartex kinds are clustered columns, scatter series lines with markers, scatter-with-lines and radar series lines), secondary axis | | +| **Total** | ~60 subtypes | **28 (~47%)** | usage-weighted breadth higher (~65%): column, bar, line, pie and scatter dominate | ## Chart elements and formatting @@ -145,6 +145,7 @@ column chart draws and saves its forecast series as columns, not lines. | 2026-11-02 | minor | Charts move and resize from eight handles, each moving only its own edges (#190); resizing leaves the work list (1–2 h, within the 40–60 h rounding) | | 2026-11-01 | minor | Chart data tables for column, bar, line, area and compatible combo charts: command/UI controls, formatted source values, blanks, grouped category headers, legend keys, independent borders, shared print/PDF rendering and native c:dTable import/export. Dense tables show a space notice; no readiness score change. | | 2026-10-29 | minor | Selected charts highlight their source cells beneath floating objects, so the blue outline no longer crosses the chart; uncovered source cells remain highlighted (#2861) | +| 2026-10-25 | minor | 100% Stacked Line and 100% Stacked Line with Markers: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` | | 2026-10-24 | minor | 100% Stacked Area: inserted from the ribbon and All Charts, drawn as shares of each category's total, read and written as `percentStacked` | | 2026-10-18 | trivial | Stale notes: stock/combo, treemap/sunburst, box and waterfall kinds survive XLSX round-trip (PRs #158, #161) | | 2026-10-18 | minor | Doughnut charts: every series is a ring (first series innermost), hole size and first slice angle modelled, editable and round-tripped; rotated slices split at 12 o'clock without overlap; legend names categories like Excel's default (#1823) | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 253fe1d739..1f7757e81e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-14 · **Change:** minor (XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-23 · **Change:** minor (form controls: buttons, scroll bars and spin buttons read and written; web pages open their first table as a sheet; external-source PivotTables and the Data Model are kept on save when their connections are kept; earlier: one paper table, `model::paper`, for XLSX paper ids and print layout: `11x17`, `US Legal` and the other spellings keep their `paperSize`, XLSX id 34 (ECMA-376's 176×250 mm B5 envelope) reads as `B5 (ISO)` and prints at 176×250 mm instead of the old Letter fallback, and an empty paper name (no paper stated) writes no `paperSize`; Page Setup and Size take Statement, Envelope #10 and Envelope DL; earlier: XLSX and `.xls` column widths keep whether they were set by hand, so automatic ones still widen for wider number formats, #1077; earlier: a protection password set in GridCraft keeps both its XLSX form and the SHA-256 digest OpenDocument stores; earlier: the style model keeps a cell's padding, for OpenDocument; XLSX and XLS have none, so they read none and the XLSX writer leaves it out; not drawn yet; earlier: XLSX fonts keep outlined letters, ``, through open and save; GridCraft draws them solid; earlier: PDF honours cell reading direction and mirrors right-to-left sheets; earlier: Arabic PDF export no longer fails when a character or the Arabic font is missing; earlier: Arabic PDF text is shaped with embedded Noto Arabic glyphs beside the non-embedded standard, Symbol and CID fonts; earlier: .xls data validation is read; earlier: .xls is read by the shared craft-xls crate: the workbook opens on the sheet it was saved on, and rich-text (RString) cells are read; earlier: form controls: buttons, scroll bars and spin buttons read and written; earlier: a web page's first table opens as a sheet, also when the page is named `.xls`; earlier: `workbookPr filterPrivacy` kept, and honoured on save; earlier: a workbook's R1C1 reference style, `calcPr refMode`, is kept through open and save; earlier: XLSX page margins are written as their decimals, `0.3` rather than `0.30000001192092896`; earlier: Python cells in `.xlsx` as [MS-XLSX] specifies, `_xlfn._xlws.PY(…)` naming code in the Python part, with cached values, and in GridCraft JSON, with limits on open; earlier: equations in xlsx as Office Math with a marker in `descr` so an edit made in Excel reads back, read back only up to the equation source cap, and a brace with a label and a script on its other side keeps both; Symbol font in PDF; earlier: XLSX reads and writes Page Setup's page order, `pageSetup pageOrder`, and PDF export follows it; earlier: chart data tables: native c:dTable import/export; earlier: XLSX workbook-view selection, normalized tab ratios and sheet-edit regressions; fidelity estimates unchanged; earlier: formulas from Google Sheets' XLSX export open as the original formula instead of `IFERROR(__xludf.DUMMYFUNCTION(…),…)` when GridCraft calculates every function in it, and save as it; `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; earlier: `file.exportCsv {values: true}` writes raw values for automation; .xls dialog sheets are skipped instead of read as worksheets; `.xls` import reads each sheet's display options from WINDOW2: right-to-left, gridlines, headings, zeros, formulas; XLSX text boxes and shapes keep their paragraphs' right-to-left direction on save; CSV/TSV/TXT can open with every field kept as text via `file.open {csvAsText}`; formulas over Excel's 8,192 characters, and `%` or call chains past the nesting limit, are parse errors instead of stack overflows when a file is opened; XLSX PivotTables read and write `rowGrandTotals`/`colGrandTotals` the way Excel does, so a table saved with only one grand total opens with the right one; HTML export keeps right-to-left; CSV and text import detects likely Windows-1256 Arabic when invalid UTF-8 has Arabic byte runs; other invalid UTF-8 remains Windows-1252; HTML export places pictures and charts, as inline SVG, at their anchors; CSV and text open detects each column's date order from values that read only one way, warns when every date is ambiguous, and keeps a column with both kinds as text (#2765)) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -80,7 +80,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real | Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests | |---|---|---|---|---|---| -| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF (including the Excel 2010 `x14:conditionalFormattings` extension, MS-XLSX 2.4.6: `cellIs`, `expression`, `containsBlanks`/`notContainsBlanks`, `containsErrors`/`notContainsErrors`, `duplicateValues`/`uniqueValues`, `top10`, `aboveAverage` and `timePeriod` rules are read, with `xm:f` formulas and an inline `x14:dxf`; x14 data bars (beyond the solid fill a main-section data bar links to), icon sets, colour scales and the text rules `containsText`, `notContainsText`, `beginsWith` and `endsWith` are skipped with a warning and lost on save. Cell-value and formula rules referring to another sheet are written in the extension using `{78C0D931-6437-407d-A8EE-F0AAD7539E65}`; in the tested synthetic files, Excel for Mac 16.114 also wrote cross-sheet `expression` rules there and opened them without a repair prompt. Excel for Mac 16.114 stores cross-sheet `cfvo` rules for colour scales, data bars and icon sets only in x14; GridCraft writes those rules in the main section, and drops x14-only rules of those kinds on read with a warning. A rule with a 3-D span stays in the main section, since MS-XLSX 2.6.27 forbids `sheet-range-reference` in `xm:f`. Colour scale, data bar and icon set rules (whose cfvo formulas can also refer to other sheets) are always written in the main section), validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (the first five dropped URIs are named in an open warning, with a count for the rest), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | +| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF (including the Excel 2010 `x14:conditionalFormattings` extension, MS-XLSX 2.4.6: `cellIs`, `expression`, `containsBlanks`/`notContainsBlanks`, `containsErrors`/`notContainsErrors`, `duplicateValues`/`uniqueValues`, `top10`, `aboveAverage` and `timePeriod` rules are read, with `xm:f` formulas and an inline `x14:dxf`; x14 data bars (beyond the solid fill a main-section data bar links to), icon sets, colour scales and the text rules `containsText`, `notContainsText`, `beginsWith` and `endsWith` are skipped with a warning and lost on save. Cell-value and formula rules referring to another sheet are written in the extension using `{78C0D931-6437-407d-A8EE-F0AAD7539E65}`; in the tested synthetic files, Excel for Mac 16.114 also wrote cross-sheet `expression` rules there and opened them without a repair prompt. Excel for Mac 16.114 stores cross-sheet `cfvo` rules for colour scales, data bars and icon sets only in x14; GridCraft writes those rules in the main section, and drops x14-only rules of those kinds on read with a warning. A rule with a 3-D span stays in the main section, since MS-XLSX 2.6.27 forbids `sheet-range-reference` in `xm:f`. Colour scale, data bar and icon set rules (whose cfvo formulas can also refer to other sheets) are always written in the main section), validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. Self-contained `extLst` entries (`extlist.rs`, an allowlist of single attribute-only elements, rebuilt in source order): the workbook's calcFeatures, x15 and x14 `workbookPr`, `xlwcv:version` and Excel for Mac `mx:ArchID`, and the sheet's Excel for Mac `mx:PLV`. **Kept unchanged on save:** the Data Model when its workbook connections are kept, with the PivotTables on it or on a data connection. **Not preserved:** slicers and slicer caches, timelines, query tables attached to tables, other sheet and workbook `extLst` entries we don't model (the first five dropped URIs are named in an open warning, with a count for the rest), chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Legacy formula behavior | R/W | yes | yes | Formulas without dynamic-array metadata (`cm`) open with Excel's implicit `@`; implied operators are removed on save without `cm`, while explicit single-value `@` is kept as `_xlfn.SINGLE`; formulas the analyzer cannot finish are saved as read. | `roundtrip.rs`, `fixtures.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | | `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `` offsets and readings and `` are written back next to the same string; the table holds each text once, so duplicate `` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection (a sheet or workbook password set in GridCraft is kept as its salted SHA-512 hash, which XLSX stores, and as the SHA-256 digest OpenDocument stores; a digest alone has no XLSX form, so saving keeps that protection without its password, and without a warning yet: the XLSX save path has no warning channel), Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` | @@ -100,6 +100,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real | `.xml` XML Spreadsheet 2003 | R/W | no | no | Simple to support | — | | `.ods` OpenDocument Spreadsheet | R/W | **values only** (#100) | no | Sheets, values, dates, merges, repeated cells, cached formula results; no formulas, formatting, charts; encrypted ODS refused | `ods_tests.rs` | | Password-encrypted workbooks (Agile/Standard encryption) | R | **yes** (#11): asks for the password on open; Agile (AES-128/192/256, SHA-1/256/384/512) and Standard (AES, SHA-1) | no (opens with no save path; Save As writes it without the password) | Clean-room from [MS-OFFCRYPTO] on the CFB reader. RC4, Extensible and certificate-only encryption refused with a message. Data-integrity HMAC not checked | `crypto/tests.rs`, `encrypted_tests.rs` | +| Password to modify (XLSX `fileSharing`) | R/W | **yes** (#921): asks for the password, or opens read-only; a read-only open never saves over its file | yes (hash, user name and read-only-recommended kept) | Legacy `reservationPassword` and iterated SHA-1/256/384/512 hashes. Never checked against Excel: its prompt wording and read-only behaviour are unobserved; `readOnlyRecommended` alone does not prompt | `roundtrip.rs`, `engine/src/tests.rs` | | `.xlw` Excel 4.0 workbook, `.wk*`, `.dbf` | open only (some) | no | no | Rare | — | ## Text and data formats @@ -161,9 +162,11 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-11-23 | minor | Clarify that imported XLSX paper id 34 changes printed output from the old Letter fallback to ISO B5 (176×250 mm); add import-to-preview/PDF regression coverage | | 2026-11-14 | minor | A sheet or workbook protection password set in GridCraft is kept both as Excel's salted SHA-512 hash and as a SHA-256 digest (the form OpenDocument stores); XLSX writes the SHA-512 form, and a digest-only password keeps its protection without the password; one shared base64 implementation. GridCraft JSON (`.json`) workbooks keep such a password in the shape earlier GridCraft versions read (the SHA-512 hash, with the digest in an extra `odf` field they ignore), so they still open there | | 2026-11-14 | minor | Style model: `Alignment::padding` (left, right, top, bottom, hundredths of a point; none where a file states none) keeps an OpenDocument cell's padding; styles differing only by padding stay apart. XLSX and XLS read none and the XLSX writer leaves it out; GridCraft does not draw it yet | | 2026-11-14 | minor | XLSX fonts' outlined (hollow) letters, ``, are read and written back after `` as Excel writes them, in cell fonts and differential formats (a differential format that turns it off, ``, keeps that too); they were dropped before. Two fonts differing only in it are different styles. Set by `home.formatCells {style: {font: {outline: true}}}`; GridCraft does not draw outlined text yet (it shows solid) | +| 2026-11-13 | minor | One paper table (`model::paper`) behind XLSX `paperSize` and print layout; id 34 reads as `B5 (ISO)`, the ISO B5 size; `B5 (ISO)` and every alias save with their id; an empty paper writes no `paperSize`; Page Setup and Size now take Statement, Envelope #10 and Envelope DL (Page Setup refused them before) and print them on their own size | | 2026-11-13 | minor | PDF of a right-to-left sheet keeps explicit Left and Right alignment on the side the grid shows them | | 2026-11-12 | minor | `.xls` files open with their data validation (drop-down lists, input messages, error alerts and the rules), read by craft-xls and mapped as the `.xlsx` reader maps the same rules. A rule Excel would refuse, or one past 65,536 in a workbook, is skipped with a warning (#3634, from #3636) | | 2026-11-12 | minor | .xls import reads the file with craft-xls (storytold/craft-libs), the reader that moved there from this repository; GridCraft keeps the mapping onto its model. The workbook now opens on the sheet it was saved on (WINDOW1 `itabCur`), falling back to the first visible sheet as before (from #3551), and cells saved as RString records (text with formatting runs) are read as text instead of skipped | @@ -194,6 +197,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-26 | minor | PDF honors cell Context/LTR/RTL, preserves paragraph direction across wrapping, and mirrors RTL sheet geometry without reversing glyphs | | 2026-10-26 | minor | Arabic PDF export embeds licensed glyph outlines, joins letters and marks, preserves logical text and reports unsupported glyphs before writing; Arabic runs take the embedded faces ahead of the CJK CID font, and CJK inside Arabic text is set in the CID font instead of failing the export | | 2026-10-26 | minor | Alignment readingOrder 0/1/2 survives cell, named-style and differential-style round-trips; Format Cells exposes reading direction and CF priority preserves unspecified inheritance | +| 2026-10-24 | minor | XLSX: a password to modify (`fileSharing`) is read and written, and opening such a file asks for it or opens read-only (#921); a read-only open refuses Save to its own file; SHA-1 modify hashes verify; an encrypted and reserved file asks for the modify password after its decryption password | | 2026-10-22 | minor | XLSX column widths: `customWidth` without `bestFit` is a width set by hand, others (AutoFit, widened by a number format) are automatic, as Excel 16.0 reads them; written the same way (`bestFit="1" customWidth="1"` for automatic widths). `.xls` reads COLINFO's fUserSet as set by hand (the shared craft-xls reader does not report fBestFit) (#1077) | | 2026-10-21 | minor | HTML (Save as Web Page) writes pictures (`data:` URI ``) and charts (inline SVG from the chart crate's drawing primitives, text included) at their anchors; the table uses the sheet's column widths and row heights when the sheet has either, and output for sheets without pictures or charts is unchanged | | 2026-10-20 | trivial | XLSX shared strings: Japanese phonetic runs (ふりがな, `` with ``) are read into the workbook and written back next to the string with the same text, so an open + save no longer deletes them; bad offsets and readings are dropped with a warning, a `` without runs is kept on its own, and when duplicate `` items share a text but not a reading only the first reading is written (reported on open) (`phonetic_tests.rs`) | @@ -207,6 +211,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-19 | trivial | XLSX text boxes and shapes keep right-to-left paragraph direction (`a:pPr rtl`, ECMA-376 Part 1 §21.1.2.2.7): read from the first paragraph and written on every paragraph; output without it is unchanged | | 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` | | 2026-10-18 | trivial | `file.open {csvAsText: true}` keeps every CSV/TSV/TXT field as the text the file holds, so identifiers (GTINs, SKUs, ZIP codes) keep their digits and leading zeros (#1808; a preference and a CLI flag are separate work) | +| 2026-11-03 | minor | XLSX Data Model: kept on save when its workbook connections are kept; it is not an editable or refreshable data source in GridCraft | | 2026-10-18 | trivial | XLSX PivotTables: `rowGrandTotals` is the Grand Total row and `colGrandTotals` the Grand Total column. Both were read and written the other way round, which a GridCraft round trip hid, so an Excel file with only one grand total opened showing the other | | 2026-10-16 | trivial | XLSX charts: `[0]!Name` (a workbook-scoped defined name) in series references is read as the name, so the series resolve instead of showing `#NAME?`. Names in chart references are written qualified (`[0]!Name`, or `Sheet!Name` for a sheet-scoped name): Excel draws a chart with a bare name blank (#1686) | | 2026-10-16 | trivial | XLSX reads and writes the workbook's show-objects setting (`workbookPr showObjects`: all, placeholders, none), which Ctrl+6 switches; a file without it is saved without it | @@ -218,6 +223,9 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-15 | minor | XLSX: formulas and PivotTable sources quote sheet names like Excel (a leading `.`, R1C1-like and cell-like names), so `'.x'!A1` no longer saves as `.x!A1`, which Excel could not open (#1458) | | 2026-10-15 | minor | XLSX text preserves CR and CRLF across save/reopen; shared strings use `_x000D_` and other XML text uses ` ` (#1488) | | 2026-10-15 | minor | XLSX save keeps legacy `INDEX`/`MATCH` formulas scalar instead of marking them as dynamic arrays (#1505) | +| 2026-10-15 | minor | XLSX PivotTables on a data connection or the Data Model are kept on save with their caches and connections; unsupported sources fall back to plain cells with a warning | +| 2026-10-15 | minor | XLSX PivotTables whose source is in another workbook are kept on save, with style references adjusted to rewritten styles | +| 2026-10-14 | minor | `.xls` import reads cell formatting from Font, XF, Palette and Style records | | 2026-10-14 | minor | `.xls` import reads cell formatting from the Font, XF, Palette and Style records: fonts, fills, borders, alignment, protection, the custom palette, the Normal font and user cell styles | | 2026-10-14 | minor | CSV/text export writes General numbers with the 15 significant digits `&` gives (`0.3`, not `0.30000000000000004`) but never an exponent (integers below 1e16 keep every digit; 1E+15 and up as the shortest round-trip digits; small numbers written out), also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display. The underlying `&` conversion changed too (see [function-parity.md](function-parity.md)) | | 2026-10-14 | trivial | Formula parser: text longer than Excel's 8,192 characters, and postfix chains (`1%%%…`, `f(1)(1)…`) past the 256-level nesting limit, are parse errors (the cell keeps its formula text and cached value) instead of trees deep enough to overflow the stack when a hostile file is opened, saved or dropped | diff --git a/docs/function-parity.md b/docs/function-parity.md index cb19ffd551..2fcc7366dc 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -114,7 +114,7 @@ reports keep finding edge cases: MIN() with no arguments (#138), COUNTBLANK past XIRR, YIELD) are the highest-risk for last-digit differences. RATE follows Excel's own iteration, reconstructed from observation (secant from the guess and the guess ± 0.001, at most 200 steps, stop within 1e-7 by step and value, a looser 1e-4 check after 200 steps), so it returns the same iterate as Excel where convergence is slow (about -100% for `RATE(n,0,-pv,0)`) and `#NUM!` where -Excel's solver gives up (very large rates); roots at 0% differ only by rounding noise (under 1e-7). +Excel's solver gives up (very large rates); roots at 0% differ only by rounding noise (under 1e-7). XIRR follows Excel's own solver, reconstructed from observation: a sign-only search that brackets the root from the guess (doubling, halving towards 0, or stepping halfway to -100%) and bisects until half the bracket is under 1e-8 x (|rate| + 0.5) and XNPV is under 2e-8 x the first value, so its answer is the same midpoint as Excel's, about 1e-8 from the exact root, bit for bit in 888 of 910 synthetic cases with an answer (97.7% agreement on 1,283 cases including `#NUM!`). A 0 or blank first flow gives the tiny value Excel gives (the guess halved until the step is under the tolerance: about 2.98e-9 for the default guess, `#NUM!` for a negative guess). Known differences: flows with several sign changes where Excel returns about 3e-9 (a halving that reached 0), or `#NUM!` for two roots close to the guess. IRR uses Newton on the discount factor 1/(1+rate), at most 100 steps, stopping at a step under 1e-8; Excel's last digits differ by about 1e-12 (its exact iteration is not reconstructed) and a few far-from-guess cases differ in `#NUM!` (93.5% agreement on 708 cases, from 88%). TEXT() and cell display share `crates/numfmt`; checked against Excel-cached results in number- and text-format test workbooks (352 TEXT cells), all match: @@ -141,6 +141,7 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere | Date | Change | Summary | |---|---|---| | 2026-11-04 | minor | GCD and LCM reject negative fractional arguments before truncation; scalar and range regressions in the extracted math tests preserve positive truncation and signed-zero behavior; estimates unchanged | +| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; a tiny step with a large residual continues iterating | | 2026-11-03 | minor | GROUPBY: a total depth of 2 or more adds a subtotal line for each group of the leading key columns (after the group, or before it for a negative depth) and labels the last line Grand Total; a depth past the key columns, or above 1 with `field_relationship` 1, is `#VALUE!`, as in Excel (#1456 item 1) | | 2026-11-01 | minor | Python in cells row: Python mode in the formula bar | | 2026-11-01 | minor | Python in cells (stored, not run): `#PYTHON!`, `#BUSY!`, `#TIMEOUT!` and `#BLOCKED!` done, with their `ERROR.TYPE` numbers; `PY` still counted as missing | @@ -172,6 +173,8 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere | 2026-10-19 | minor | Long flat operator chains (#916): 4,096 operands (Excel's 8,192-character limit) no longer overflow the stack when entered, filled, adjusted or saved; chains past 64 operands are no longer saved as dynamic-array formulas; Spanish entry no longer refuses chains past 256 operands | | 2026-10-17 | minor | 15-significant-digit comparison moved from missing to done (#57), and the resolved caveats on the 3-D reference, dynamic-array and legacy-array rows cleared (#140, #133, #139, #156) | | 2026-10-16 | minor | FORECAST.ETS gap interpolation uses a forward-only known-point scan instead of rescanning each gap for every missing value; numerical behavior and missing-point limits are preserved (#1042) | +| 2026-10-15 | minor | XIRR follows Excel's bisection (answers bit for bit, about 1e-8 from the exact root; dates before the first allowed; guess <= -1 is `#NUM!`); IRR uses Newton on the discount factor (`IRR` of -100, 19 zeros, 1E-5 is `#NUM!` like Excel; guess <= -1 is `#VALUE!`) | +| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` Excel gives for a blank or text value or a blank date after the first row, and `#VALUE!` for a blank value or date in the first row (observed on synthetic workbooks); XIRR with a 0 or blank first flow returns Excel's tiny value (about 2.98e-9), and a first nonzero flow with a blank date reads the date as day 0 | | 2026-10-15 | minor | Iterative calculation: Maximum Iterations and Maximum Change are set in File › Options › Formulas (dropped "no Options dialog yet") | | 2026-10-15 | minor | MEDIAN and AGGREGATE median use an overflow-safe midpoint (#1579); regressions cover finite extremes, tiny values and dependent recalculation | | 2026-10-15 | minor | ADDRESS quotes a sheet name the way Excel does: names that read as an A1 cell (`A1`) or an R1C1 reference (`R1C1`, `RC`) and names starting with `.` get quotes; `TRUE` / `FALSE` stay bare (#1458) | diff --git a/docs/gaps.md b/docs/gaps.md index 089101dedb..9502ed64d7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,7 @@ # Gaps -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** minor (`cargo xtask bench`: measured recalc baselines; earlier: §5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry; earlier: §17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-13 · **Change:** minor (`cargo xtask bench`: measured recalc baselines; earlier: File › Print › Settings: Print Selection; earlier: §5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry; earlier: §17: equations; earlier: §13: Solver Sensitivity report; earlier: §4: chart resizing is no longer a gap; earlier: §13: Analysis ToolPak has all 19 tools; earlier: §4: chart data tables implemented with XLSX round-trip and print/PDF; earlier: §13: Solver Options; earlier: §13: Solver Load/Save Model and Reset All) · **Target:** Microsoft Excel (Microsoft 365) + Every known shortfall against Excel, one entry each, ranked by user impact (what blocks someone using GridCraft for real work first). This is the work list: pick from the top, check the open @@ -22,6 +23,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- - **Evidence:** round-trip tests cover our own files only (`crates/xlsx/src/tests/`); PivotTable round-trip noted as "unverified in real Excel" since 10-07; #64 (dynamic-array flag) shows the class of bug. +- **Check:** `packaging/windows/excel-open-check/check.ps1` saves workbooks with `gridcraft-cli` and opens each result in real Excel through COM with `CorruptLoad` = normal load, so a repair is a failure. The 0.12.1 run (18 public synthetic fixtures + 7 feature scenarios: charts, pivots with pivot chart and slicer, CF, validation, tables and names, shapes and pictures, sheets and protection) gave 24 of 25 saved files opening cleanly; the 25th (`gc_legacy_to_array`) is not a repair but Excel taking over 200 s on legacy formulas saved as whole-column array formulas (#410, open PRs #417, #1367, #1660). Still open: a run over a large real-world corpus. - **Impact:** the main format; a repair prompt or silent loss destroys trust. - **Estimate:** 15–25 h, plus owner time in Excel. [file-format-parity.md](file-format-parity.md) @@ -147,7 +149,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- ### 14. Page Layout view and print polish (U, F) - Page Layout view landed (#329): paper view with rulers and in-place header/footer editing. - Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print ranges and driver tray/options UI remain. **Estimate:** 5–10 h. + Margins are dragged on the rulers (#792). Remaining: pictures in headers/footers, Different First Page / Odd & Even pages. Desktop now submits directly through craft-print with printer choice, copies, duplex and grayscale; browser printing stays available. Print Selection landed (File › Print › Settings); Set Print Area is in Page Layout. Driver tray/options UI remains. **Estimate:** 5–10 h. ### 15. Remaining functions and an oracle suite (F) - 9 missing, 9 stubs; no Excel-computed oracle corpus; #137, #138. **Estimate:** 15–25 h. @@ -205,11 +207,13 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | 2026-11-01 | minor | §4: chart data tables implemented for column, bar, line, area and compatible combo charts, with legend keys and border settings, live source values, XLSX round-trip and print/PDF; other chart gaps remain. | | 2026-10-31 | minor | §13: Solver Options (Max Evaluations, Integer Optimality and the Evolutionary options), saved with the model | | 2026-10-31 | minor | §13: Solver Load/Save Model (`data.solverSaveModel`, `data.solverLoadModel`) and Reset All (`data.solverReset`), with buttons in the Solver Parameters dialog | +| 2026-10-26 | minor | §1: `packaging/windows/excel-open-check` opens saved workbooks in real Excel and records pass or the exact failure; first run: 24 of 25 open cleanly | | 2026-10-26 | minor | §5: Arabic PDF output preserves cell direction, joined glyphs and RTL sheet geometry. Other script and UI gaps remain. | | 2026-10-26 | minor | Arabic shared bidi display/editing and persisted cell reading direction; other script and PDF work remain separate | | 2026-10-26 | minor | §5: Arabic text renders in cells and the interface: a system Arabic face (Tahoma, Arial or Segoe UI on Windows, Geeza Pro on macOS, Noto Sans or Naskh Arabic on Linux) joins the script fallbacks, fontconfig's Arabic choice, when it has Arabic letters, leads the Arabic fallbacks and draws Arabic wherever the UI or cell font has none, such as the default cell fonts (part of #229; a UI font with Arabic of its own, such as DejaVu Sans in the Flatpak, still draws interface Arabic, left for a follow-up), and craft-fonts' Noto Sans Arabic is a required face allowed on the web. Workbook fonts without Arabic keep every script fallback. Shaping and bidirectional layout remain separate work | | 2026-10-26 | minor | #2: measured with `cargo xtask bench`; 100k-dependent edit around 100 ms, whole-column SUMIFS/XLOOKUP added | | 2026-10-24 | minor | §8: PivotTable Enable show details: `pivot.options` `enableShowDetails` turns Show Details off for a PivotTable, read and written in XLSX as `enableDrill` | +| 2026-10-23 | minor | §14: Print Selection landed in File › Print › Settings (several selected areas print one after the other); "print ranges" removed from the remainder | | 2026-10-23 | minor | §8: PivotTable Show Details: double-clicking a value cell lists its source records on a new sheet (#2364) | | 2026-10-22 | minor | §20: a native window per workbook window, New Window on the same workbook and Arrange All on the desktop; left: Arrange All across monitors, the web's one window, pen pressure (estimate 10–14 h → 5–8 h) | | 2026-10-20 | minor | §11: the Japanese catalog covers the dialogs, messages and menus — 943 keys (~43%), matching the pt-BR coverage; a test keeps the two catalogs in step | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f48ca2a54b..eef256a03d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (File › Print › Settings: Print Selection; earlier: preserve imported filter row bounds in shared statistics and choices; earlier: italic and bold in a font with one face, such as Arial Black, are slanted and thickened as Excel does; earlier: AutoFit Column Width measures a table's header in the table style's bold font; earlier: ribbon number formats widen columns nobody sized by hand, #1077; earlier: a leading + or - starts a formula, #2023; earlier: AutoSum on one cell proposes its range in the editor, #1834; earlier: Quick Analysis, Ctrl+Q (#791); earlier: validation list rows keep to their slot height whatever the font, and the "More entries not shown" note is translated; earlier: the searched validation list shows its eight rows, keeps the highlight in view and opens above a cell near the bottom of the window; earlier: the dropdown arrow's full list reads its source once within the same budget, draws only its visible rows and shows eight of them; earlier: a searched validation list reads at most 200,000 cells of its source; earlier: Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292; earlier: typing into a cell with a list validation searches its dropdown; Enter/Tab take the highlighted entry) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -35,7 +35,7 @@ Sources: `crates/ui-egui/src` (ribbon, grid, editor, formula bar, dialogs, panes | Task panes (Format Chart, Comments, Watch, Selection, PivotTable fields) | yes | yes; PivotTable source-field list scrollbar sits at the right edge of its pane | element-level Format pane for shapes and pictures missing | | Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | partial | template gallery missing | | Dark mode, system appearance | yes | yes | done (10-09); follows the system on first run, title-bar switch and File › Display theme (#194, #239); icons, reference colours, primary buttons and the comments pane follow the theme, and a unit test holds every token pair to WCAG 2 contrast in both themes | -| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet or workbook, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has | +| Backstage (File) view: Info, New with templates, Open recent, Export, Options | yes | yes (#174, 10-11): the File tab opens a full-window view (Esc or the back arrow return; Esc in a text field first cancels editing and leaves the field, #3035) with Home, New (blank + the three samples), Open (recent + Browse; the recent list tells when each workbook was last changed, 10-12), Info (location, properties, Protect Workbook), Save, Save As, Print (page preview, active sheet, workbook or selection, fit to page, Page Setup), Export (PDF, CSV, web page), Close and Options (`file.options`: theme, language, formula bar, AutoSave, calculation mode and iterative calculation with Maximum Iterations and Maximum Change, 10-15) | no Account, Share or template gallery beyond the samples; Options applies at once (no OK/Cancel dialog) and holds only the settings GridCraft has | | Dark mode, system appearance | yes | yes | done (10-09) | | Page Layout view (paper view with rulers and header editing) | yes | yes (#329, 10-11): per-sheet view saved in XLSX, pages with margins and gaps on the print pagination, "Click to add data" pages, rulers (inches or centimetres), headers and footers drawn and edited in place with a Header & Footer tab, whose Different First Page and Different Odd & Even Pages give the first page and the even pages their own header and footer (#344), and whose Scale with Document and Align with Page Margins set whether header and footer text follows the print scale and the side margins, on paper and in the view | margins drag on the rulers (#792, with header and footer margins); header/footer pictures missing (1–3 h). Unverified: with Align with Page Margins off, header and footer text sits 0.7 in from the paper edge, a value not yet measured in the target app | | Multiple windows per workbook | yes | yes (10-22, desktop): each workbook window is a native window of its own (New, Open and New Window open one; titles "Book1", or "Book1:1" / "Book1:2" for a workbook's second window, with " — Edited" while unsaved). Each window keeps its own cell draft, dialog, Backstage view, message and grid state, and its ribbon acts on it; on macOS the menu bar acts on the window focused last. Leaving a window enters its draft as Enter would. A window's close button closes that window: one of several on a workbook closes without asking, a workbook's last asks Save / Don't Save / Cancel when unsaved. Quit asks about each unsaved workbook in its window, and Cancel stops it. The last window closed quits on Windows and Linux; macOS keeps running with the menu bar until New or Open. View › Arrange All (dialog: Tiled, Horizontal, Vertical, Cascade, Windows of active workbook; `view.arrangeAll` tiles by default) lays the visible windows out over the main window's monitor, the active one first. Web: one window | Arrange All uses one monitor; a hidden window (View › Hide) has no native window; every window repaints when one does; see [hardware-parity.md](hardware-parity.md) | @@ -65,6 +65,7 @@ this logic, with one undo step. | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | | Searchable data validation dropdown (typing filters the in-cell list) | done (10-21): entries with a word starting with the typed text, ignoring case and the accents of Latin letters (é, ç, ß, ł, ș, ǎ, Vietnamese ộ: Latin-1, Latin Extended-A and -B, Latin Extended Additional; other scripts keep their marks), in list order; Up/Down highlight, Enter/Tab/Ctrl+Enter/click commit the highlighted entry as the list spells it (other commits, such as clicking another cell, keep the typed text), Escape hides the list then cancels; `data.validationList {cell, search?}` gives agents the same search. The search reads at most 200,000 cells of the list's source and keeps at most 10,000 matches; past either, `truncated` is set and the popup says more entries aren't shown (validation itself still checks the whole list). Fuzzy matching isn't offered (Excel doesn't either); behaviour follows the documented Excel 365 feature, not yet measured against the app | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | +| AutoFilter value dropdowns | Choices come from rows satisfying the other columns' active criteria; the current column only determines checkbox state, including (Blanks), so its filter can be changed or cleared (#2641). Without a search, Apply preserves selected and excluded values and blanks absent from the narrowed list. With a search, Apply excludes nonmatches throughout the column, including values hidden by another filter. Clear Filter clears the whole column. Custom comparisons, Top 10, average and color criteria use the same evaluator as row filtering. Top 10 / average thresholds still use the original range. Manual hidden rows do not restrict choices; imported icon criteria remain unevaluated. | | Data › Advanced Filter | dialog offers in-place or copy-to filtering, list and optional criteria ranges, and unique records; Alt+A,Q opens it (#1622). The engine's copy-to path clears only the result footprint and rejects worksheet overflow (#1031). | | Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; Data › Outline › Settings (`data.outlineSettings`) puts summary rows above and summary columns left of their detail, saved as `outlinePr` (the dialog's Automatic styles check box and Apply Styles button are missing), View › Show Outline Symbols (Ctrl+8) hides the bands and is saved with the sheet, and a block of cells still groups rows without the Rows / Columns dialog | | Reorder selected whole columns by dragging their headers | done (10-11) | @@ -79,6 +80,30 @@ this logic, with one undo step. | Smooth scrolling, scrollbars | done; vertical scrollbar added 10-09 (#73); horizontal scrollbar in the tab bar (60/40 split, drag, track click pages) 10-13 (#176, #840); dragging the handle at the scrollbar's left edge gives the tabs more or less of the bar; each workbook keeps its share while it is open (not saved in the file) | | Text overflow into empty neighbours, wrap, rotation, shrink to fit | done | +## AutoFilter population and pending integrations + +[Microsoft's filtering guide](https://support.microsoft.com/en-us/excel/get-started/filter-data-in-a-range-or-table-in-excel) +describes additive column filters and restricting other dropdowns to the filtered range. The +current column is excluded from enumeration so its unchecked alternatives remain available. +The existing one-million-data-row enumeration limit and value sorting remain unchanged. +Imported end rows stop at the last worksheet row in choices, statistics and visibility scans. +Checkbox state uses the row matcher for the active criterion, including raw and formatted +Values matches, custom comparisons, numeric thresholds and colors. A duplicate choice is +checked when any eligible row matches, including when those rows have different colors. +Hidden choices retain that state when Apply merges the eligible edits. Values criteria prepare ASCII-insensitive +lookup sets once per query rather than scanning every selected value for each row. + +This changes the population behind the pending row-count work (#1737, and its stacked Only +button #1741): a future count beside a choice should count eligible rows satisfying the other +columns, including rows rejected by the current column. It must not count the whole original +range or just currently visible rows. Search narrows the displayed choices, not that population; +Apply with a search excludes nonmatching values even when another filter hides them. +These PRs are not incorporated here. Date grouping (#1509) should group this same eligible +population. Table filter activation / roundtrip ownership changes remain in #2506. Enumeration +reads the active sheet AutoFilter without changing criteria, row visibility or the XLSX +representation. A separate table dropdown outside that AutoFilter's columns remains empty; +it does not receive choices from its own eligible-row population. + ## Keyboard | Area | Excel | GridCraft | @@ -277,10 +302,13 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-11-14 | minor | The searched validation list measures its rows at their real height, like the dropdown arrow's list: it shows eight rows instead of six, the highlighted row stays in view and the last entries of a long list can be reached. It opens above the cell when it would run past the bottom of the window, measures its width once per search instead of every frame, and its "More entries not shown" note goes through the interface translations. Typing over the open dropdown drops the entries the dropdown had read | | 2026-11-13 | minor | The full list the dropdown arrow (or Alt+Down) opens reads its source once while it stays open, within the same 200,000-cell budget, and draws only the rows in view, so a list over a huge column no longer rereads and redraws every entry each frame; it says when entries aren't shown, and its rows are measured at their real height so eight show, as intended | | 2026-11-13 | minor | A searched validation list reads at most 200,000 cells of its source (`LIST_SOURCE_BUDGET`), walking a range source within the used range instead of evaluating it whole, so a list over a huge or whole column can't stall the edit; `data.validationList` reports `truncated` and the popup says when entries aren't shown | +| 2026-11-11 | minor | Carry the imported AutoFilter end-row bound through shared statistics and dropdown choices as well as row visibility; retain duplicate-color and per-window pending-choice fixes (#2641) | +| 2026-11-10 | minor | Keep duplicate choices checked when any eligible row matches a color filter; a form-button window switch preserves the incoming window's pending filter search and checkbox edits (#2641) | | 2026-11-05 | minor | Reconcile upstream form-control coverage with the CJK baseline and cell-alignment updates | | 2026-11-04 | minor | Keep centered emoji and symbol fallback placement when a row starts with a fallback or contains only fallbacks; use primary or baseline-aligned glyphs to anchor cell alignment | | 2026-11-04 | minor | Preserve leading and trailing blank lines in wrapped cells when calculating vertical alignment; regression covers single, multiple and all-empty lines | | 2026-11-04 | minor | Align wrapped and unwrapped cells with the same vertical margins; regressions compare numbers with mixed CJK/Latin text, including explicit line breaks | +| 2026-11-04 | minor | AutoFilter checkboxes and hidden-choice merging use the active row criterion, including raw/formatted Values, custom comparisons, Top 10, averages and colors; Values criteria use one prepared ASCII-insensitive lookup per query (#2641) | | 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 | | 2026-11-03 | minor | Find and Replace: workbook Undo/Redo works with a keyboard-focused button; focused text fields keep text-editing Undo, and a modal message blocks workbook shortcuts. Regression covers Replace All, both Redo shortcuts, actual text undo, and an error message | | 2026-11-03 | minor | Highlight the active cell's row: a global preference that tints the whole row, off by default | @@ -295,12 +323,14 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-11-03 | minor | Draw tab: the stroke drawn under the pointer while dragging a pen is the ink that will be committed, in the pen's colour and thickness (translucent for a highlighter), instead of always blue at 2 pt (#1786) | | 2026-11-03 | minor | Copy puts a cell that holds a quote on the clipboard as it is (`say "hi"`), quoting only text with a tab or line break, as Excel does; pasting text reads a field as quoted only when its closing quote ends it, so `"hi" there` pastes with its quotes (#2225) | | 2026-11-03 | minor | Ctrl+. (Control+. on a Mac): Next Corner of Selection, `selection.nextCorner`: the active cell moves clockwise to the next corner of the selected area, which stays selected, and becomes the anchor, as in Excel (#1442) | +| 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 | | 2026-11-02 | minor | Dragging the selection's border onto cells that hold data asks "There's already data here. Do you want to replace it?" (OK replaces, Cancel leaves the sheet and clipboard as they were) through the new `range.move` command (#3136); the row no longer claims Ctrl/Option copy and Shift insert for the border drag, which are not wired yet | | 2026-11-02 | minor | RefEdit reference boxes in dialogs: pick a range on the grid, collapse the dialog while selecting; Goal Seek, Solver (with the Model Range of Load/Save) and Data Analysis use them; while collapsed the arrow keys move the selection and Shift+arrow extends it, F4 cycles a reference's anchors, a click elsewhere keeps the box picking, a dialog opened over a picking one puts the selection back, OK stays on the sheet its command showed, and scripted cancel and confirm end a pick like the buttons; the dialog's sheet is followed through the recorded undo steps, so a sheet deleted and recreated under its name is not taken for it and an undo of the deletion brings it back; a box the dialog stops showing is no longer picked into; the dialog's sheet is recorded when it opens, not at its first pick | | 2026-11-02 | minor | Python mode edits a cell's code in the formula bar's code editor (Ctrl+Alt+Shift+P, `=PY` then Tab, editing a Python cell), with the PY badge beside fx; its keys apply in input order, also several in one frame, and Ctrl+Enter commits through `python.set` (empty code clears the cell), keeping the code and showing the command's message when the code is refused | | 2026-11-02 | minor | Insert › Symbols: Equation split button (access keys N E), a gallery of examples, and an equation editor with quick-insert buttons, the error underlined at its position and a live preview; double-clicking an equation edits it | | 2026-11-02 | minor | Floating objects: one selection for charts, pictures, shapes and slicers, eight resize handles with matching cursors (right-to-left sheets included), Escape drops the selection | | 2026-11-02 | minor | Record macOS mixed CJK/Latin rendering validation, the actual fallback fonts and the unverified Calibri 10 case | +| 2026-11-01 | minor | Filter popup checkbox edits, search and button state belong to their document window; switching columns in another window no longer discards an open popup's pending choices (#2641); the separate AutoFilter section documents the empty dropdown outside the active sheet filter columns (#2506) | | 2026-11-01 | minor | Chart Design › Add Chart Element offers Data Table with/no legend keys and None; Format Chart Area has a Data Table section with visibility, legend keys, horizontal/vertical borders and outline. Both use engine commands. | | 2026-11-01 | minor | Page Setup has a Page order choice (Down, then over, the default, or Over, then down) with a small picture of the order, also when Print Titles opens it on its Sheet tab; OK sets it with the margins in one undo step. Printing, PDF export, the print preview, Page Break Preview's page numbers and Page Layout view's headers and footers follow the order. The dialog is in German now too | | 2026-11-01 | minor | Formulas › Error Checking › Trace Error (`formulas.traceError`): red arrows from the cell an error starts in to the selected cell, through the first reference showing the same error at each step, and blue arrows from that cell's own references, as measured in Excel; the command returns the source and the arrows | @@ -310,6 +340,8 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-31 | minor | Recently Used lists the functions most recently entered in a formula from any source, kept with the preferences; the Insert Function dialog is titled as in Excel, its category list (Most Recently Used, All, each category) works, and its category column follows the widest name shown | | 2026-10-31 | minor | Formulas › Function Library: Insert Function, the AutoSum split button and three columns of labelled small buttons with category colours; category menus end with Insert Function…; More Functions cascades; Home › Editing shares the AutoSum menu; MR key tip for Recently Used | | 2026-10-31 | minor | CJK fallback text shares the Latin baseline in cells, editors and window titles; fixed row heights and clipping remain workbook-controlled | +| 2026-10-30 | minor | AutoFilter choices cascade across other columns while retaining current-column alternatives and blanks (#2641); Apply without search preserves selected and excluded values and blanks hidden by other filters; searched Apply excludes hidden nonmatches while retaining hidden matches; documents pending counts, date grouping and table roundtrip integration; retains slicer row filtering when its criterion is outside the sheet filter columns | +| 2026-10-30 | minor | Italic and bold in an installed font that has no face for them (Arial Black has a single face) are imitated on the grid, as Excel does: the text is slanted and drawn a second time a little to the right (about 1/36 of the size, at least one pixel). Observed in Excel's PDF of a cell in Arial Black, bold italic: oblique by 1/3 and outlined 0.23 pt thick at 9 pt. egui's slant is fixed at about 1/4. Print and PDF still use the standard PDF fonts (`fonts.rs` test) | | 2026-10-30 | minor | Checkbox cells print and export to PDF as boxes, as on screen: unchecked white with a grey outline, checked green with a white tick (#2972). They printed their value as TRUE or FALSE; other values in a checkbox cell still print as text | | 2026-10-29 | minor | Formula pointing from the keyboard: Ctrl+arrow (⌘arrow) moves the pointed cell to the edge of its data and Ctrl+Shift+arrow (⌘⇧arrow) extends the pointed range there, as the same keys move and extend the selection, so typing `=COUNTIF(`, clicking the top of a column and pressing ⌘⇧↓ points at the whole column of data; the keys used to move or extend by one cell. A range reaching the sheet edge is written as whole columns or rows (`A:B`). The editor reads the modifiers of the arrow's own key event, so a keystroke pressed and released within one frame (a control client's `ui.key`, an automation tool) keeps its Shift and Ctrl | | 2026-10-29 | minor | Insert Hyperlink opens with an existing link's address, display text and ScreenTip (#2876). An address-only edit preserves the cell's content and formula; Cancel leaves the link unchanged, and Undo restores the edit | @@ -326,6 +358,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-24 | minor | Right-clicking a PivotTable's value, subtotal or grand total cell offers Show Details in the cell menu, as in Excel ("Right-click a field in the values area of the PivotTable, and then click Show Details"): it lists the cell's source records on a new sheet, as double-clicking the cell does (`pivot.showDetails`). Labels and headers of a current report don't offer it; in a report that is out of date every cell offers it, and choosing it asks for a refresh | | 2026-10-24 | minor | Sheet tabs: the handle at the horizontal scrollbar's left edge shows the resize cursor, and dragging it moves the boundary, as in Excel ("Hover the mouse pointer at the edge of the scrollbar until you see the double-headed arrow"). Dragging it right gives the tabs more of the bar, until the scrollbar is 100 px wide (the scrollbar stays 100 px wide after the window is narrowed); dragging it left gives the scrollbar more, down to the New sheet button. Room the tabs don't fill stays empty, with New sheet after the last tab. Each open workbook keeps its own share; a workbook starts at the default (tabs up to 60%) | | 2026-10-24 | minor | Outline Settings (Data ▸ Outline ▸ Settings, `data.outlineSettings`): clearing Summary rows below detail or Summary columns to right of detail puts the − / + buttons on the line above or left of each group, and Hide Detail, Show Detail and the level buttons mark that line collapsed. Changing a direction moves the marks of collapsed groups. Read and written as `outlinePr summaryBelow` / `summaryRight` | +| 2026-10-23 | minor | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook: the preview and the printed PDF cover the selected cells, and a selection of several areas prints each area on its own pages, as in Excel (`file.print`, `file.exportPdf` and `file.printPreview` accept `range: "A1:B5,D1:E5"`). A single selected cell prints that cell | | 2026-10-23 | minor | F3, Formulas › Use in Formula › Paste Names… and Alt+M, S, P open the Paste Name dialog (F3 only when the workbook has names). It lists the workbook's names and the active sheet's own in alphabetical order, hidden names left out; OK or a double-click puts the selected name at the caret of the formula being edited, in place of selected text, or starts `=Name` in the active cell (`formulas.pasteName` `{name}`), and Paste List writes each name and the text of what it refers to in two columns from the active cell (`{list: true}`). While a dialog is open over the edit, the cell editor takes no keys, and Cancel leaves the selected text selected. The Use in Formula menu lists the same names and inserts at the caret too (`formulas.useInFormula`); it used to list hidden names and other sheets' names, the menu added the name at the end of the text, and the command replaced the text being edited | | 2026-10-23 | minor | Conditional Formatting ▸ New Rule, formula: clicking a cell on the grid writes its absolute reference at the formula box's caret (`=$B$2`, an empty box starts with `=`), a drag writes a range (`$B$2:$C$4`) and a second click replaces the reference just written, as in Excel ("Selecting cells on the worksheet inserts absolute cell references"). The selection the rule applies to doesn't move, and the box keeps the keyboard. After an operand (`=A1>5`) the click does nothing (#2348) | | 2026-10-15 | minor | F8 Extend Selection and Shift+F8 Add or Remove Selection modes, shown in the status bar (`ui.selectionMode`) | @@ -338,6 +371,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 2026-10-22 | minor | One native window per workbook window on the desktop: per-window drafts, dialogs and ribbons; menu bar commands go to the focused window; closing one of several windows on a workbook doesn't ask; Quit asks in each unsaved workbook's window; the last window closed quits (Windows, Linux) or leaves macOS running | | 2026-10-22 | minor | New Window opens a second window on the same workbook instead of a copy that saved over the original; windows keep their own selection, sheet and scroll; titles Name:1 / Name:2; Switch Windows, Hide and Unhide work by window; File › Close closes one window of several without asking | | 2026-10-22 | minor | New workbook no longer loses the first one: the cell being typed is entered into its own workbook before any File or window command (an entry the workbook refuses stays open and the command doesn't run; an untouched F2 draft changes nothing), the editor is tied to its workbook, View › Switch Windows and the macOS Window menu list the open workbooks, and the macOS Quit item asks about unsaved workbooks like the close button | +| 2026-10-22 | minor | AutoFit Column Width measures a table's cells in the font the table style draws them in, so a bold header row is fitted bold; it measured the cell's own, plain font and could leave a bold heading too narrow | | 2026-10-22 | minor | Increase/Decrease Decimal, the ribbon's other number formats (Number Format list, Accounting, Percent, Comma) and Format Cells' number formats widen a column nobody sized by hand so the numbers fit, instead of showing #### (#1077). As observed in Excel 16.0: AutoFit counts as automatic, Column Width or dragging the border as by hand; hidden columns, text, General numbers, merged and shrink-to-fit cells don't widen, and columns never narrow | | 2026-10-21 | minor | Typing into a cell with an in-cell list validation shows the list filtered to entries with a word starting with the typed text (case and Latin accents ignored, Vietnamese included, list order kept, only visible rows drawn); Up/Down move the highlight, Enter/Tab/click commit it with the list's spelling, Escape hides the list before cancelling. Column AutoComplete is off for those cells. New query command `data.validationList` | | 2026-10-21 | minor | Background error checking, first part (#1994): a constant whose text would be a number if typed (signs, thousands, currency, percent, exponent, parenthesised negative) gets Excel's green corner triangle; the active cell then shows a warning button whose menu names the problem and offers Convert to Number for the selection (`formulas.convertToNumber`). Dates, times and fractions kept as text and formula results are not flagged, as in Excel | diff --git a/packaging/windows/excel-open-check/README.md b/packaging/windows/excel-open-check/README.md new file mode 100644 index 0000000000..a927997bb1 --- /dev/null +++ b/packaging/windows/excel-open-check/README.md @@ -0,0 +1,13 @@ +# Excel open check + +Saves workbooks with `gridcraft-cli` and opens each result in real Excel (COM), recording per file `PASS` or the +exact failure. Windows with Excel only. See `check.ps1` for the options. + +```powershell +.\check.ps1 -Cli C:\gridcraft\gridcraft-cli.exe -Inputs C:\workbooks -Csv result.csv +``` + +Inputs are any `.xlsx`/`.xlsm` (the synthetic `gridcraft/` fixtures in a public fixtures repo are a good start); each +`*.jsonl` here is a feature scenario run on the Sales sample. Add a scenario by dropping in another `.jsonl` +(`gridcraft-cli run --script` format). Results: `Original` is the input opened in Excel (so a file Excel itself +rejects or loads slowly isn't blamed on GridCraft), `Saved` is the GridCraft-saved copy. diff --git a/packaging/windows/excel-open-check/charts.jsonl b/packaging/windows/excel-open-check/charts.jsonl new file mode 100644 index 0000000000..3746a83e9c --- /dev/null +++ b/packaging/windows/excel-open-check/charts.jsonl @@ -0,0 +1,12 @@ +# One chart of each common kind over the sales table +insert.chart={"range":"B4:F8","type":"bar","at":"K36"} +insert.chart={"range":"B4:F8","type":"line","subtype":"markers","at":"S3"} +insert.chart={"range":"B4:F8","type":"area","subtype":"stacked","at":"S19"} +insert.chart={"range":"C5:D8","type":"scatter","at":"S36"} +insert.chart={"range":"B4:F8","type":"radar","at":"AA3"} +insert.chart={"range":"B4:C8","type":"doughnut","at":"AA19"} +insert.chart={"range":"B4:C8","type":"waterfall","at":"AA36"} +insert.chart={"range":"B4:C8","type":"treemap","at":"AI3"} +insert.chart={"range":"B4:C8","type":"histogram","at":"AI19"} +insert.sparkline={"range":"C5:F5","location":"J5","type":"line"} +insert.sparkline={"range":"C6:F6","location":"J6","type":"column"} diff --git a/packaging/windows/excel-open-check/check.ps1 b/packaging/windows/excel-open-check/check.ps1 new file mode 100644 index 0000000000..1e82a48633 --- /dev/null +++ b/packaging/windows/excel-open-check/check.ps1 @@ -0,0 +1,125 @@ +<# +Excel open check: saves workbooks with GridCraft, opens each result in real Excel (COM) and records per +file whether Excel loads it as it is or has to repair it (docs/file-format-parity.md, "Excel open check"). + + check.ps1 -Cli C:\gridcraft\gridcraft-cli.exe [-Inputs C:\workbooks] [-Out C:\out] [-Csv result.csv] + [-TimeoutSec 120] + +Files saved: + - every .xlsx / .xlsm in -Inputs, opened and saved with `gridcraft-cli run --in --out` (the original + is opened in Excel too, so a file Excel itself dislikes or loads slowly is told apart from a + GridCraft regression); + - every *.jsonl scenario next to this script (one feature each), run on the Sales sample. + +Each file is opened read-only with CorruptLoad = xlNormalLoad (0), so a part Excel would repair is a +failure instead of a silent fix, with DisplayAlerts off and VBA macros disabled so nothing waits on a prompt. +AutomationSecurity does not cover Excel 4.0 (XLM) macros, which would still prompt, so a workbook that +holds XLM macro sheets is never opened: it is reported as SKIP-XLM and the run does not pass. +Excel is a fresh instance per file; a file that hangs or kills Excel is recorded as TIMEOUT or CRASH and +that instance (found by its window's process id) is stopped. Nothing is written next to the inputs; any other +Excel, such as one the person starts meanwhile, is never touched. Exit code 1 when any saved file is not PASS. +#> +param( + [Parameter(Mandatory = $true)][string]$Cli, + [string]$Inputs, + [string]$Out = (Join-Path ([IO.Path]::GetTempPath()) 'gridcraft-excel-open-check'), + [string]$Csv, + [int]$TimeoutSec = 120 +) +$ErrorActionPreference = 'Stop' + +# Runs in a child PowerShell so a hang can be killed after $TimeoutSec without taking this script with it. +$probe = { + param($path) + $x = $null + try { + # Compiled before Excel starts, so nothing between the start and the PID line can fail or stall on it. + Add-Type -Namespace Win -Name U -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);' + $x = New-Object -ComObject Excel.Application + # Report this instance's process id so the caller can stop exactly it and nothing else. + $xlPid = [uint32]0 + [void][Win.U]::GetWindowThreadProcessId([IntPtr]$x.Hwnd, [ref]$xlPid) + "PID`t$xlPid" + $x.Visible = $false + $x.DisplayAlerts = $false + $x.AutomationSecurity = 3 # msoAutomationSecurityForceDisable: no VBA macros (XLM is screened by Test-HasXlm) + # Named arguments: PowerShell can't skip the optional ones in between positionally. + $wb = [System.__ComObject].InvokeMember('Open', [Reflection.BindingFlags]::InvokeMethod, $null, $x.Workbooks, + @($path, 0, $true, 0), $null, $null, @('Filename', 'UpdateLinks', 'ReadOnly', 'CorruptLoad')) + $sheets = $wb.Worksheets.Count + $wb.Chartsheets.Count + $wb.Close($false) + "PASS`t$sheets sheets" + } catch { + "FAIL`t" + ($_.Exception.Message -replace '\s+', ' ') + } finally { + # Also covers a failure before the PID line: this process's own instance is quit, no other is touched. + if ($x) { try { $x.Quit() } catch {} } + } +} + +# True when the package holds Excel 4.0 macro sheets, which ForceDisable does not stop and Excel would prompt for. +function Test-HasXlm([string]$path) { + Add-Type -AssemblyName System.IO.Compression.FileSystem + # Not a zip at all: nothing to screen, Excel gets to report it. + try { $zip = [IO.Compression.ZipFile]::OpenRead($path) } catch { return $false } + try { return [bool]($zip.Entries | Where-Object { $_.FullName -like 'xl/macrosheets/*' }) } finally { $zip.Dispose() } +} + +function Test-InExcel([string]$path) { + if (Test-HasXlm $path) { return [pscustomobject]@{ State = 'SKIP-XLM'; Seconds = 0; Detail = 'Excel 4.0 macro sheets; not opened' } } + $clock = [Diagnostics.Stopwatch]::StartNew() + $job = Start-Job -ScriptBlock $probe -ArgumentList $path + $done = Wait-Job $job -Timeout $TimeoutSec + $lines = @(Receive-Job $job -Keep -ErrorAction SilentlyContinue) + $failed = $job.State -eq 'Failed' + if (-not $done) { Stop-Job $job } + Remove-Job $job -Force + $xlPid = ($lines | Where-Object { $_ -like "PID`t*" } | Select-Object -First 1) -replace '^PID\t', '' + $out = $lines | Where-Object { $_ -notlike "PID`t*" } | Select-Object -Last 1 + if (-not $done) { $out = "TIMEOUT`tno answer in $TimeoutSec s" } elseif ($failed -or -not $out) { $out = "CRASH`tno result (Excel died)" } + if ($xlPid) { + # A clean Quit lets Excel exit by itself; give it a moment, then stop only this instance. + Wait-Process -Id ([int]$xlPid) -Timeout 15 -ErrorAction SilentlyContinue + Stop-Process -Id ([int]$xlPid) -Force -ErrorAction SilentlyContinue + } + $state, $detail = $out -split "`t", 2 + [pscustomobject]@{ State = $state; Seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); Detail = $detail } +} + +$saved = Join-Path $Out 'saved' +Remove-Item -LiteralPath $saved -Recurse -Force -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Path $saved -Force | Out-Null + +# (name, original or $null, saved) per file +$work = @() +if ($Inputs) { + foreach ($f in Get-ChildItem -LiteralPath $Inputs -File | Where-Object { $_.Extension -in '.xlsx', '.xlsm' } | Sort-Object Name) { + $work += , @($f.Name, $f.FullName, (Join-Path $saved $f.Name), @('run', '--in', $f.FullName, '--quiet')) + } +} +foreach ($s in Get-ChildItem -Path $PSScriptRoot -Filter *.jsonl | Sort-Object Name) { + $work += , @("scenario:$($s.BaseName)", $null, (Join-Path $saved "$($s.BaseName).xlsx"), @('run', '--sample', 'sales', '--script', $s.FullName, '--quiet')) +} + +$rows = @() +foreach ($w in $work) { + $name, $orig, $dest, $cliArgs = $w + # The CLI reports on stderr, which Stop would turn into an exception. + Remove-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue + $ErrorActionPreference = 'Continue' + & $Cli @cliArgs --out $dest *> $null + $code = $LASTEXITCODE + $ErrorActionPreference = 'Stop' + $base = if ($orig) { (Test-InExcel $orig) } else { $null } + $r = if ($code -eq 0 -and (Test-Path -LiteralPath $dest)) { Test-InExcel $dest } else { [pscustomobject]@{ State = 'SAVE-FAIL'; Seconds = 0; Detail = "gridcraft-cli exit code $code" } } + $rows += [pscustomobject]@{ + File = $name; Original = if ($base) { $base.State } else { '-' }; Saved = $r.State + Seconds = $r.Seconds; Detail = $r.Detail + } +} +$rows | Format-Table -AutoSize -Wrap | Out-String -Width 220 | Write-Output +if ($Csv) { $rows | Export-Csv -NoTypeInformation -Path $Csv } +$bad = @($rows | Where-Object { $_.Saved -ne 'PASS' -or $_.Original -eq 'SKIP-XLM' }).Count +$savedBad = @($rows | Where-Object Saved -ne 'PASS').Count +"{0} of {1} saved files pass" -f ($rows.Count - $savedBad), $rows.Count +if ($bad) { exit 1 } diff --git a/packaging/windows/excel-open-check/conditional-formats.jsonl b/packaging/windows/excel-open-check/conditional-formats.jsonl new file mode 100644 index 0000000000..ebfb544fa9 --- /dev/null +++ b/packaging/windows/excel-open-check/conditional-formats.jsonl @@ -0,0 +1,8 @@ +# Colour scale, data bar, icon set, top 10, formula and text rules +home.conditionalFormat={"range":"C5:F8","rule":{"type":"colorScale"}} +home.conditionalFormat={"range":"C5:C8","rule":{"type":"dataBar"}} +home.conditionalFormat={"range":"D5:D8","rule":{"type":"iconSet"}} +home.conditionalFormat={"range":"E5:E8","rule":{"type":"top10","rank":2}} +home.conditionalFormat={"range":"F5:F8","rule":{"type":"cellIs","operator":"greaterThan","value":"60000","preset":"lightRedFill"}} +home.conditionalFormat={"range":"B5:B8","rule":{"type":"containsText","text":"th","preset":"yellowFill"}} +home.conditionalFormat={"range":"C5:F8","rule":{"type":"expression","formula":"=C5>AVERAGE($C$5:$F$8)","preset":"greenFill"}} diff --git a/packaging/windows/excel-open-check/pivots.jsonl b/packaging/windows/excel-open-check/pivots.jsonl new file mode 100644 index 0000000000..23315f9e8b --- /dev/null +++ b/packaging/windows/excel-open-check/pivots.jsonl @@ -0,0 +1,4 @@ +# PivotTable on the sales table, a pivot chart, a table slicer +insert.pivotTable={"source":"Sales","destination":"Sales!K40","rows":["Region"],"values":[{"field":"Q1","func":"sum"}]} +insert.pivotChart={"pivot":"Sales!K42","type":"column","at":"S50"} +insert.slicer={"table":"Sales","column":"Region","at":"AA50"} diff --git a/packaging/windows/excel-open-check/protection-sheets.jsonl b/packaging/windows/excel-open-check/protection-sheets.jsonl new file mode 100644 index 0000000000..f05bd57ce4 --- /dev/null +++ b/packaging/windows/excel-open-check/protection-sheets.jsonl @@ -0,0 +1,9 @@ +# Extra sheets (renamed, coloured, hidden), grouping and a protected sheet +home.insertSheet={} +sheet.rename={"name":"Second"} +sheet.tabColor={"color":"#FF0000"} +cell.set={"cell":"A1","input":"=Sales!B5&\" \"&Sales!C5"} +home.insertSheet={} +sheet.hide={} +sheet.activate={"sheet":"Sales"} +review.protectSheet={"formatCells":true} diff --git a/packaging/windows/excel-open-check/shapes-pictures.jsonl b/packaging/windows/excel-open-check/shapes-pictures.jsonl new file mode 100644 index 0000000000..ecfcfbbaef --- /dev/null +++ b/packaging/windows/excel-open-check/shapes-pictures.jsonl @@ -0,0 +1,5 @@ +# Shapes with text and a picture from base64 (a 1x1 PNG) +insert.shape={"kind":"rectangle","at":"K30","width":120,"height":40,"text":"Box","fill":"#FFC000"} +insert.shape={"kind":"ellipse","at":"O30","width":80,"height":40} +insert.shape={"kind":"arrow","at":"K33","width":80,"height":30} +insert.picture={"base64":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==","mime":"image/png","at":"B20","width":60,"height":60,"alt":"dot"} diff --git a/packaging/windows/excel-open-check/tables-names.jsonl b/packaging/windows/excel-open-check/tables-names.jsonl new file mode 100644 index 0000000000..98f07d0949 --- /dev/null +++ b/packaging/windows/excel-open-check/tables-names.jsonl @@ -0,0 +1,13 @@ +# Table style and total row, defined names, merged cells, frozen panes, hyperlink-free cell notes +selection.set={"cell":"C5"} +table.totalRow={} +table.style={"style":"TableStyleLight9"} +formulas.defineName={"name":"NorthQ1","refersTo":"=Sales!$C$5"} +formulas.defineName={"name":"AllRegions","refersTo":"=Sales!$B$5:$B$8"} +formulas.defineName={"name":"Rate","refersTo":"=0.2","comment":"tax rate"} +cell.set={"cell":"K14","input":"=SUM(AllRegions)"} +cell.set={"cell":"K15","input":"=NorthQ1*Rate"} +home.mergeCells={"range":"K16:M16"} +view.freezePanes={"cell":"C5"} +review.newNote={"cell":"C5","text":"checked"} +review.newComment={"cell":"D5","text":"threaded"} diff --git a/packaging/windows/excel-open-check/validation.jsonl b/packaging/windows/excel-open-check/validation.jsonl new file mode 100644 index 0000000000..cd7e2efa09 --- /dev/null +++ b/packaging/windows/excel-open-check/validation.jsonl @@ -0,0 +1,8 @@ +# One rule of each kind +data.validation={"range":"K2:K5","type":"list","formula1":"North,South,East,West"} +data.validation={"range":"K6:K8","type":"whole","operator":"between","formula1":"1","formula2":"100","inputTitle":"Count","inputMessage":"1 to 100","errorStyle":"warning"} +data.validation={"range":"L2:L5","type":"decimal","operator":"greaterThan","formula1":"0"} +data.validation={"range":"L6:L8","type":"date","operator":"greaterOrEqual","formula1":"2026-01-01"} +data.validation={"range":"M2:M5","type":"textLength","operator":"lessOrEqual","formula1":"10"} +data.validation={"range":"M6:M8","type":"custom","formula1":"=ISNUMBER(M6)"} +data.validation={"range":"N2:N5","type":"list","formula1":"=$B$5:$B$8"}