Merge main into the bench branch

This commit is contained in:
FredApps committed 2026-11-26 21:15:32 +01:00
commit 04720627bd
124 files changed
+4812 -532

No files matched your search

Generated
+1
View File
@@ -2987,6 +2987,7 @@ dependencies = [
"gridcraft-math",
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
]
+2
View File
@@ -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
+15 -1
View File
@@ -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 |
+8 -1
View File
@@ -65,6 +65,13 @@ fn cond_format_list(s: &Sheet) -> Vec<String> {
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<Categor
}
diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len());
diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len());
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
diff_count(&mut pivots, &name, pivot_count(sa), pivot_count(sb));
}
let mut names = Diffs::new("names", m);
let name_list = |wb: &Workbook| -> BTreeSet<String> {
+1 -7
View File
@@ -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),
+13
View File
@@ -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();
+13 -6
View File
@@ -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<Vec<Option<(f64, f64)>>> {
// 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<f64>)> = 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<Option<[f32; 2]>> = 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 {
+4 -2
View File
@@ -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,
};
+2 -2
View File
@@ -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);
+59 -1
View File
@@ -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::<Vec<f32>>())
}
_ => 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", "", ""];
+29
View File
@@ -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");
}
}
+1 -1
View File
@@ -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};
+35
View File
@@ -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);
+1 -1
View File
@@ -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};
+232 -84
View File
@@ -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<Json> {
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<u32> = 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<u32> = 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<Json> {
}
/// 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<Json> {
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<usize, (Option<f64>, f64)> {
let r = af.range;
// Precompute per-criterion top10 threshold and average once, not per row.
let mut col_stats: std::collections::HashMap<usize, (Option<f64>, 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<f64> = (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<f64> = (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::<f64>() / 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<usize, (Option<f64>, f64)>,
values: HashMap<usize, HashSet<String>>,
}
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<u32>) -> 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<Json> {
})
}
/// 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), _)| {
+4 -2
View File
@@ -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<Json> {
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)?,
+30
View File
@@ -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();
+30 -3
View File
@@ -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<CommandSpec> {
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<Json> {
};
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<Json> {
// 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<Json> {
}
// 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<Json> {
)
}
/// 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<Json> {
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<Json> {
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")) {
+14
View File
@@ -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() {
+9 -4
View File
@@ -195,7 +195,8 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
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<StyleId, std::collections::HashMap<String, f32>> = 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<String, f32>> = 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<Json> {
}
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);
+1 -1
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+2
View File
@@ -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,
+6 -5
View File
@@ -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<CommandSpec> {
"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<CommandSpec> {
"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<Json> {
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);
+43 -48
View File
@@ -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<RangeRef>,
/// Areas of the active sheet to print instead of its print area, in order (Print Selection).
pub ranges: Vec<RangeRef>,
pub fit_to_page: Option<bool>,
}
@@ -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<RangeRef> {
@@ -354,14 +343,20 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
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<Option<RangeRef>> =
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 {
+111 -1
View File
@@ -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<String> {
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]"));
}
+4 -2
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Json> {
}
fn paper(s: &mut Session, p: &Json) -> Result<Json> {
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();
+4
View File
@@ -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.
+4
View File
@@ -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<io::FileKind>,
/// 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<String>,
/// 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,
+34 -1
View File
@@ -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(&region)) 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)));
+76 -5
View File
@@ -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<u8> {
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(&copy).is_ok());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn encrypted_workbooks_open_with_their_password() {
const PW: &str = "synthetic-pw-5521";
@@ -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
}
@@ -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);
}
@@ -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<ChartKind> {
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]);
}
+3
View File
@@ -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;
@@ -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");
}
+128
View File
@@ -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<f64>) -> 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<f64>, expected: f64) {
assert_eq!(xirr_of(values, dates, guess), Value::Number(expected), "XIRR{values:?} {dates:?} {guess:?}");
}
fn irr_of(values: &[f64], guess: Option<f64>) -> 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);
+225 -88
View File
@@ -152,72 +152,6 @@ pub(super) fn cumprinc(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
cumulative(a, true)
}
/// Newton iteration with a numeric derivative, keeping the rate above -1.
fn newton(f: impl Fn(f64) -> f64, guess: f64) -> Option<f64> {
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<f64> {
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<f64> = [-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<Value> {
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<f64>, Vec<f64>)> {
/// 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<f64>, Vec<f64>)> {
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<f64>, Vec<f64>)> {
}
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<Value> {
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<f64>,
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<f64> {
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<f64> {
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<f64> {
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<f64> {
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<f64> {
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<f64> {
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<f64> {
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<Value> {
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<f64> {
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<Value> {
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<Value> {
+45 -15
View File
@@ -22,17 +22,17 @@ fn chars(s: &str) -> Vec<char> {
}
fn check_len(s: String) -> R<Value> {
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<std::borrow::Cow<'_, str>> {
}
}
/// CONCATENATE cuts at the cell limit like `&`; CONCAT and TEXTJOIN give `#CALC!` past it.
fn concatenate(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
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<Value> {
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<Value> {
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<Value> {
&& !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<usize> {
@@ -252,7 +265,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
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<Value> {
} 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.
+3 -3
View File
@@ -11,7 +11,7 @@ pub(crate) type R<T> = Result<T, CellError>;
/// 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>) -> 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),
}
+1 -1
View File
@@ -288,7 +288,7 @@ fn base_tool_definitions() -> Vec<Value> {
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)"),
}),
+1
View File
@@ -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 }
+46 -8
View File
@@ -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<Grouped> {
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;
+4 -1
View File
@@ -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],
+2 -1
View File
@@ -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
+137
View File
@@ -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);
}
}
+15 -1
View File
@@ -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::<sha1::Sha1>(password, &salt, *spin_count),
"SHA-512" => iterated::<sha2::Sha512>(password, &salt, *spin_count),
"SHA-384" => iterated::<sha2::Sha384>(password, &salt, *spin_count),
"SHA-256" => iterated::<sha2::Sha256>(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<dyn std::error::Error>> {
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")?);
+8
View File
@@ -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<PreservedRel>,
/// 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
+13
View File
@@ -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<crate::PasswordHash>,
/// "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<WriteReservation>,
/// Custom fill lists (Options › Custom Lists) beyond the built-in ones.
pub custom_lists: Vec<Vec<String>>,
/// 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<crate::PasswordHash>,
}
/// 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![],
+7
View File
@@ -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();
+30 -5
View File
@@ -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,
+16 -8
View File
@@ -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;
}
}
+16
View File
@@ -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",
+3 -1
View File
@@ -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"),
+22 -10
View File
@@ -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;
+83 -4
View File
@@ -345,7 +345,10 @@ pub fn bind_faces(fonts: &mut egui::FontDefinitions, family: &str, faces: &[Face
let mut bound: Vec<String> = 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<String> = 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<std::sync::RwLock<HashSet<String>>> = OnceLock::new();
const SLANT: &str = "slant";
const BOLD: &str = "bold";
fn synthetic() -> &'static std::sync::RwLock<HashSet<String>> {
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"))]
+4
View File
@@ -327,6 +327,10 @@ pub struct GridState {
pub cells_rect: Option<Rect>,
/// 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<Vec<(String, bool)>>,
pub filter_search: String,
pub filter_buttons: Vec<egui::Id>,
pub context_menu: Option<Pos2>,
/// The frame a right-click opened `context_menu` in: that click's own press doesn't close it.
pub context_menu_frame: u64,
+19
View File
@@ -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<egui::Galley>, 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<FontId> {
+13 -18
View File
@@ -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<egui::Id> = 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::<Vec<(String, bool)>>(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<String> = 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::<Vec<(String, bool)>>(key);
d.remove::<String>(search_key);
d.remove::<Vec<egui::Id>>(buttons_key);
});
app.grid.filter_checks = None;
app.grid.filter_search.clear();
app.grid.filter_buttons.clear();
app.grid.filter_menu = None;
}
}
+26 -10
View File
@@ -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<CfLo
let size = st.font.size * 96.0 / 72.0 * z;
let fam = theme::cell_family(&st.font.name, st.font.bold, st.font.italic);
let font = FontId::new(size, fam);
let slant = st.font.italic && crate::fonts::is_slanted(&st.font.name, st.font.bold);
let embolden = st.font.bold && crate::fonts::is_emboldened(&st.font.name, st.font.italic);
// How far the second impression of imitated bold sits from the first, by the size painted.
let ppp = p.ctx().pixels_per_point();
let bold_dx = |size: f32| if embolden { (size / 36.0).max(1.0 / ppp) } else { 0.0 };
// Digits fit by the cell's own font and size, not the default 11pt (9pt marks in narrow columns).
let char_w = p.layout_no_wrap("0".to_string(), font.clone(), Color32::PLACEHOLDER).size().x.max(1.0);
let avail_w = rect.right() - text_left;
@@ -380,7 +385,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
// Rotated text wraps along its own direction (below), not across the column width.
if !rotated && (st.align.wrap || st.align.h == HAlign::Justify) {
let wrap_w = (rect.width() - 2.0 * pad - indent).max(4.0);
let mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, wrap_w);
let mut job = cell_job(text.clone(), font.clone(), color, wrap_w, slant);
job.direction = direction;
job.halign_min_is_start = false;
job.halign = match painted_halign(halign, geo.rtl) {
@@ -397,7 +402,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
let (text_top, text_bottom) = galley_baseline_bounds(&galley);
let y = wrapped_cell_text_y(st.align.v, *rect, text_bottom - text_top, z) - text_top;
let text_clip = wrapped_text_clip(p, *rect, &galley, y, st.align.v);
p.with_clip_rect(text_clip).galley(pos2(x, y), galley, color);
paint_cell_galley(&p.with_clip_rect(text_clip), pos2(x, y), galley, color, bold_dx(size));
return;
}
// Wrap Text off: Excel ignores the line breaks and draws the whole string on one line.
@@ -412,7 +417,7 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
let shrunk = small.is_some();
let font = small.unwrap_or(font);
let layout = |text: String| {
let mut job = egui::text::LayoutJob::simple(text, font.clone(), color, f32::INFINITY);
let mut job = cell_job(text, font.clone(), color, f32::INFINITY, slant);
job.direction = direction;
job.halign_min_is_start = false;
p.layout_job(job)
@@ -507,18 +512,16 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
let angle = -(st.align.rotation as f32).to_radians();
// Upright (±90°) wrapped text wraps to the row height: lines then stack across the column.
let galley = if st.align.wrap && st.align.rotation.abs() == 90 {
let mut job = egui::text::LayoutJob::simple(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0));
let mut job = cell_job(text.clone(), font.clone(), color, (rect.height() - 2.0 * pad).max(4.0), slant);
job.direction = direction;
p.layout_job(job)
} else {
galley.clone()
};
let pos = rotated_text_pos(*rect, galley.size(), angle, halign, st.align.v, pad, indent);
let mut shape = egui::epaint::TextShape::new(pos, galley, color);
shape.angle = angle;
cp.add(shape);
paint_rotated_galley(&cp, pos, galley, color, angle, bold_dx(font.size));
} else {
cp.galley(pos2(x, y), galley.clone(), color);
paint_cell_galley(&cp, pos2(x, y), galley.clone(), color, bold_dx(font.size));
}
paint_text_decorations(
&cp,
@@ -526,6 +529,19 @@ fn paint_cell(q: &QuadrantPaint<'_>, painted: &(CellRef, Rect, Look, Option<CfLo
);
}
/// Paints rotated cell text; `bold_dx` > 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<egui::Galley>, 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,
+10
View File
@@ -360,6 +360,7 @@ impl<F: Fn(&mut SheetApp, egui::Vec2) -> 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) {
+1
View File
@@ -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}",
+1
View File
@@ -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}",
+3
View File
@@ -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" => "Περιοχή",
+1
View File
@@ -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}",
+1
View File
@@ -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}",
+3
View File
@@ -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",
+3
View File
@@ -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", "面"),
+1
View File
@@ -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} 페이지",
+1
View File
@@ -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}",
+3
View File
@@ -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",
+3
View File
@@ -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",
+3
View File
@@ -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",
+1
View File
@@ -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}",
+1
View File
@@ -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}",
+1
View File
@@ -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}",
+3
View File
@@ -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",
+1
View File
@@ -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}",
+1
View File
@@ -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} 页",
+2
View File
@@ -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"),
+2
View File
@@ -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"),
@@ -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::<Vec<_>>(),
[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::<Vec<_>>()
};
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");
}
}
@@ -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);
}
+6 -3
View File
@@ -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();
+41
View File
@@ -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
@@ -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::<String>(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);
+1
View File
@@ -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;
+78
View File
@@ -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<RefCell<Vec<Vec<u8>>>>) -> 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");
}
+53 -33
View File
@@ -54,7 +54,16 @@ pub(crate) fn map_dml_color(c: &DmlColor) -> Option<Color> {
}
}
/// 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<ChartKind> {
}
}
"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<ChartKind> {
})
}
/// 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<Chart> {
#[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<St
/// or lines within its group.
fn series_xml(s: &Series, idx: usize, g: G, own: ChartKind, wb: &Workbook, si: usize) -> 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!(
"<c:lineChart><c:grouping val=\"{}\"/><c:varyColors val=\"0\"/>{sers}{dl}<c:marker val=\"{}\"/>{ax}</c:lineChart>",
if stacked { "stacked" } else { "standard" },
G::Line { grouping, markers } => format!(
"<c:lineChart><c:grouping val=\"{grouping}\"/><c:varyColors val=\"0\"/>{sers}{dl}<c:marker val=\"{}\"/>{ax}</c:lineChart>",
u8::from(markers || !series.is_empty())
),
G::Pie => format!("<c:pieChart><c:varyColors val=\"1\"/>{sers}{dl}<c:firstSliceAng val=\"{}\"/></c:pieChart>", 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()));
+2 -2
View File
@@ -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);
}
+19 -3
View File
@@ -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 `<picture>`, `<oleObjects>` and `<controls>` XML, the `r:id`
//! of `<pageSetup>`, the legacy VML shapes those controls need and the pictures of the headers and
//! footers, `&G`, with their `<legacyDrawingHF>`). The workbook also keeps its
//! `<fileVersion>` and the calcFeatures extension, which Excel needs to trust the saved values.
//! footers, `&G`, with their `<legacyDrawingHF>`). 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 `<pivotCache>` 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 `<fileVersion>` 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 `<legacyDrawing>`, before `<tableParts>`).
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 {
+167 -4
View File
@@ -53,6 +53,9 @@ pub struct KeptReader {
overrides: HashMap<String, String>,
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 `<pivotCache>` 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<String>) {
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!("<pivotCache xmlns:r=\"{NS_REL}\" cacheId=\"{id}\" r:id=\"{}\"/>", 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<Arc<Preserved>> {
pub fn sheet(
&mut self,
cx: &mut Ctx<'_>,
part: &str,
name: &str,
pivots: &[ExternalPivot],
controls: &crate::controls::ReadControls,
) -> Option<Arc<Preserved>> {
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<PreservedRel> = 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<StyleRefs> {
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::<u32>() 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).
+27 -2
View File
@@ -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<String> = 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 }
}
+148 -4
View File
@@ -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<u32>,
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<u32, u32>, fmts: &HashMap<u32, u32>) -> Option<Vec<u8>> {
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<BytesStart<'static>> {
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::<u32>().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<StylePatch>,
}
pub(super) type StylePatch = (String, Arc<[u8]>, HashMap<u32, u32>, 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<String> {
let mut v: Vec<String> = 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<u32>) {
for (name, data, dxfs, fmts) in std::mem::take(&mut out.kept.patches.list) {
let fmts: HashMap<u32, u32> = 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<String, String>;
@@ -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<String> = 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 `<sheets>` (`<externalReferences>`).
pub elements: String,
sheets: Vec<KeptSheet>,
/// 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<u32> {
self.pivot_caches.iter().map(|(id, _)| *id).collect()
}
/// The `<pivotCache>` 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, "<pivotCache cacheId=\"{id}\" r:id=\"{}\"/>", 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<String> = 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<String> = 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<u32, String> = 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<String> =
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()
+9 -1
View File
@@ -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";
+101 -12
View File
@@ -32,6 +32,47 @@ impl FieldIn {
struct CacheIn {
source: String,
fields: Vec<FieldIn>,
/// Set when the PivotTables on this cache are kept as they are, not modelled.
kept: Option<KeptSource>,
}
/// 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<PivotTable>,
pub external: Vec<ExternalPivot>,
}
/// Workbook-level pivot cache lookup, filled from `<pivotCaches>`; caches are parsed once.
@@ -40,6 +81,8 @@ pub struct CachesIn {
by_id: HashMap<u32, String>,
parsed: HashMap<String, Option<CacheIn>>,
next_id: u32,
/// The workbook's data connections (`connectionId` → whether it is the Data Model's).
connections: HashMap<u32, bool>,
}
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: `<x15:connection model="1">` in its extension list (Excel
// also gives it `<dbPr command="Model">`).
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<CacheIn> {
fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str, connections: &HashMap<u32, bool>) -> Option<CacheIn> {
// 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<CacheIn>
}
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<CacheIn>
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<Vec<PivotTable>, 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<SheetPivots, IoError> {
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)
+25 -3
View File
@@ -104,6 +104,11 @@ pub struct PivotWriter {
caches: Vec<(u32, String)>,
pending: Vec<Pending>,
tables: u32,
/// Cache ids taken by kept pivot caches (PivotTables on another workbook).
reserved: Vec<u32>,
/// `<pivotCache>` 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
/// `<pivotCache>` elements) are listed with the written ones.
pub fn new(reserved: Vec<u32>, 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 `<pivotCaches>` 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("<pivotCaches>");
s.push_str(&self.kept_entries);
for (id, target) in &self.caches {
let rid = wb_rels.add("pivotCacheDefinition", target);
let _ = write!(s, "<pivotCache cacheId=\"{id}\" r:id=\"{rid}\"/>");
+15 -2
View File
@@ -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<gridcraft_core::CellRef>)> = 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") {
+5 -2
View File
@@ -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")));
}
+29 -2
View File
@@ -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 `<autoFilter>`: 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}<table xmlns=\"{NS_MAIN}\" id=\"{id}\" name=\"{0}\" displayName=\"{0}\" ref=\"{1}\"", esc_attr(name), t.range.a1());
if !t.header_row {
@@ -131,7 +158,7 @@ pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, out: &m
if t.header_row && t.filter_button {
let end_row = if t.totals_row { t.range.end.row.saturating_sub(1).max(t.range.start.row) } else { t.range.end.row };
let r = RangeRef::new(t.range.start, CellRef::new(end_row, t.range.end.col));
s.push_str(&autofilter_xml(r, &t.filter, out));
s.push_str(&autofilter_xml(r, filter, out));
}
let _ = write!(s, "<tableColumns count=\"{}\">", cols.len());
for (i, name) in cols.iter().enumerate() {
+20 -20
View File
@@ -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<u32> {
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);
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more