Compare commits

..
Author SHA1 Message Date
skylartaylor 7a685125d0 nightly: re-pin the callers and policy to craft-common-actions 6bde9f8b
Nightly 994 / App Leads 432 routine repin: seven literal pin substitutions across three files, no other change. Verified before applying — the patch SHA256 matched, the public head was 05c5463e, and gridcraft main was still 59f6b6c1, the commit the shared merge was built on.
2026-11-26 22:12:43 +01:00
skylartaylor 05c5463efb nightly: forward the thirteen signing secrets the sign steps actually read
The caller forwarded fifteen: the thirteen environment names plus the optional Windows PFX pair. The PFX
pair is optional at runtime (the signer accepts the six AZURE_* values when it is absent), and no app's
release environment holds it, so forwarding it does nothing. It also puts the caller outside the
reviewed set: the settings closure derives its allowlist from the app's targets, which is thirteen for a
Linux/macOS/Windows app, and refuses an extra name.

This forwards exactly the thirteen and trims the app's own SIGNER_SECRETS allowlist to match. The callee
keeps declaring all fifteen, since extra declarations are harmless and it only checks for missing ones.
2026-11-26 16:57:42 +01:00
219 changed files with 2175 additions and 15494 deletions
Generated
-144
View File
@@ -199,56 +199,12 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]]
name = "anyhow"
version = "1.0.104"
@@ -840,65 +796,6 @@ dependencies = [
"libloading",
]
[[package]]
name = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_complete"
version = "4.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "clap_mangen"
version = "0.2.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78"
dependencies = [
"clap",
"roff",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -976,12 +873,6 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "colored"
version = "2.2.0"
@@ -3004,16 +2895,12 @@ dependencies = [
name = "gridcraft-cli"
version = "0.19.1"
dependencies = [
"clap",
"clap_complete",
"clap_mangen",
"gridcraft-engine",
"gridcraft-mcp",
"gridcraft-sandbox",
"log",
"quick-xml 0.41.0",
"serde_json",
"thiserror 2.0.21",
"zip",
]
@@ -3100,7 +2987,6 @@ dependencies = [
"gridcraft-math",
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
]
@@ -3829,12 +3715,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.13.0"
@@ -4896,12 +4776,6 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "open"
version = "5.4.4"
@@ -5837,12 +5711,6 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "roff"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
[[package]]
name = "roxmltree"
version = "0.21.2"
@@ -6613,12 +6481,6 @@ dependencies = [
"float-cmp",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.28.0"
@@ -7325,12 +7187,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.27.0"
-6
View File
@@ -56,10 +56,6 @@ craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa
# foundation
thiserror = "2"
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
clap = { version = "4", features = ["derive"] }
clap_complete = "4"
clap_mangen = "0.2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
@@ -71,8 +67,6 @@ 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
+1 -24
View File
@@ -2,10 +2,9 @@
**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 (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-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
This page is the summary. The detail is in:
@@ -152,14 +151,11 @@ 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 |
| 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks |
| 2026-10-26 | `cargo xtask bench`: ten fixed in-code workbooks (100k rows) time edits, formula entry, Calculate Now, sort and XLSX save/open, check their results and compare with a saved baseline. On an M2 Pro a 100k-dependent edit recalculates in 90–106 ms and 300k formulas in 395–455 ms |
| 2026-10-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) |
| 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before |
| 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step |
@@ -171,9 +167,6 @@ 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 charts keep what GridCraft doesn't model on save: an embedded chart that was not edited (moving or resizing aside) is written back from its original chart part, with its style, colour and user-shape parts, while every sheet its formulas name still exists; an edited chart is written from the model as before (#1668) |
| 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) |
@@ -193,20 +186,15 @@ 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 |
| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate |
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning |
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
| 2026-10-14 | XLSX: formulas opened with dynamic-array metadata (`cm`) keep it on save, with `xl/metadata.xml`. Before, a formula returning one value lost it (11 of 40 corpus files that have the part lost it entirely), and Excel recalculated some of them with implicit intersection (`SUMPRODUCT(IFERROR(...))` changed value) |
| 2026-10-14 | Recalculation: a dynamic array's anchor given a new formula that reads its old spill area (`A1` was `=SEQUENCE(3)`, becomes `=SUM(A2:A3)+1` or `=SEQUENCE(1,A2+1)`) sees that area empty instead of the old values |
@@ -297,7 +285,6 @@ 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 |
@@ -313,17 +300,13 @@ 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 |
| 2026-10-26 | minor | Progress log: Arabic font fallback |
| 2026-10-26 | minor | Progress log: `cargo xtask bench` |
| 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 | trivial | Progress log: unedited embedded charts keep their XML on save (#1668) |
| 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) |
@@ -336,21 +319,15 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
| 2026-10-19 | trivial | Progress log: desktop theme portal read timeout |
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) |
| 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes |
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers |
| 2026-10-15 | 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 |
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
| 2026-10-14 | minor | Progress log: spill anchor reading its old spill area |
| 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict |
-11
View File
@@ -9,10 +9,6 @@ publish = false
[lints]
workspace = true
[lib]
name = "gridcraft_cli"
path = "src/lib.rs"
[[bin]]
name = "gridcraft-cli"
path = "src/main.rs"
@@ -26,10 +22,3 @@ log = { workspace = true }
# `check`: validating the packages GridCraft writes (content types, relationships).
zip = { workspace = true }
quick-xml = { workspace = true }
thiserror = { workspace = true }
clap = { workspace = true }
[dev-dependencies]
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
clap_complete = { workspace = true }
clap_mangen = { workspace = true }
@@ -1,42 +0,0 @@
//! Writes gridcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
//! PowerShell) and man pages ([`clap_mangen`]: `gridcraft-cli.1` and one per subcommand, such as
//! `gridcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
//! (see `packaging/`):
//!
//! ```sh
//! cargo run -p gridcraft-cli --example man-and-completions -- <out-dir>
//! ```
use std::path::Path;
use std::process::ExitCode;
use clap::ValueEnum;
use clap_complete::Shell;
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let (Some(dir), None) = (args.next(), args.next()) else {
eprintln!("usage: man-and-completions <out-dir>");
return ExitCode::from(2);
};
let dir = Path::new(&dir);
match generate(dir) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {}: {e}", dir.display());
ExitCode::FAILURE
}
}
}
/// Also run by the tests.
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let mut cmd = gridcraft_cli::command();
for &shell in Shell::value_variants() {
clap_complete::generate_to(shell, &mut cmd, "gridcraft-cli", dir)?;
}
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
// which `clap_mangen` would otherwise give pages of its own (`gridcraft-cli-help-convert.1`).
clap_mangen::generate_to(gridcraft_cli::command(), dir)
}
-316
View File
@@ -1,316 +0,0 @@
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string;
//! what clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
//!
//! `run` is ordered: its `--cmd` and `--script` steps run in the order they were given, so the repeatable options are
//! kept with their positions and read back in order ([`RunArgs::steps`]).
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use serde_json::Value;
use crate::script::{ScriptError, Step, parse_command};
/// The end of every subcommand's `--help`.
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// The top-level `--help` ends with the environment and the exit status.
const TOP_NOTES: &str = "Environment:\n none: the CLI reads no environment variables of its own\n\nExit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// What a script line looks like (the `run` help ends with it).
const SCRIPT_LINES: &str = "A script line is `id={json}`, `id {json}`, `id`, or {\"command\": \"id\", \"params\": {…}}; blank lines and lines starting with # or // are skipped.";
/// Headless GridCraft: inspect, convert, evaluate, script and serve MCP without a window
#[derive(Parser, Debug)]
#[command(name = "gridcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
}
#[derive(Subcommand, Debug)]
pub(crate) enum Command {
/// Sheets, used ranges, tables, charts and names of a workbook
#[command(after_help = EXIT_STATUS)]
Info(InfoArgs),
/// Convert a workbook: xlsx, csv, tsv, json, html or pdf, by the extension of OUT
#[command(after_help = EXIT_STATUS)]
Convert(ConvertArgs),
/// Evaluate one formula, optionally against a workbook
#[command(after_help = EXIT_STATUS)]
Eval(EvalArgs),
/// Print a range as an aligned table or CSV
#[command(after_help = EXIT_STATUS)]
Cat(CatArgs),
/// Cached-value calc oracle and XLSX round-trip fidelity of files or folders (exit 1 on any difference)
#[command(after_help = EXIT_STATUS)]
Check(CheckArgs),
/// Run commands and scripts on a workbook, then save or print it
#[command(after_help = format!("{SCRIPT_LINES}\n\n{EXIT_STATUS}"))]
Run(RunArgs),
/// List the commands
#[command(after_help = EXIT_STATUS)]
Commands(ListArgs),
/// List the formula functions
#[command(after_help = EXIT_STATUS)]
Functions(FunctionsArgs),
/// Serve MCP on stdio, headless or driving the running app
#[command(after_help = EXIT_STATUS)]
Mcp(McpArgs),
/// Send one control-channel request to the running app
#[command(after_help = EXIT_STATUS)]
Send(SendArgs),
/// Whether this system confines programs (no program: a confined self-test)
///
/// With a program it runs that program confined, with the given read and executable paths and the system's shared
/// libraries, passing its output and exit status through; its own lines then go to standard error. Every path is
/// absolute. Exit status: 0 when every attempt is as required (or the program succeeded), 1 otherwise (a refused
/// launch included), 2 when GridCraft has no sandbox for this kind of system.
#[command(name = "sandbox-check", after_help = EXIT_STATUS)]
SandboxCheck(SandboxCheckArgs),
}
#[derive(Args, Debug)]
pub(crate) struct InfoArgs {
/// The workbook
pub(crate) file: PathBuf,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct ConvertArgs {
/// The workbook to read
pub(crate) input: PathBuf,
/// The file to write (.xlsx, .csv, .tsv, .json, .html or .pdf)
pub(crate) output: PathBuf,
/// The sheet to write, by name or index
#[arg(long, value_name = "NAME")]
pub(crate) sheet: Option<String>,
}
#[derive(Args, Debug)]
pub(crate) struct EvalArgs {
/// The formula; a leading `=` is optional
#[arg(allow_hyphen_values = true, value_parser = formula)]
pub(crate) formula: String,
/// Evaluate against this workbook
#[arg(long = "in", value_name = "FILE")]
pub(crate) input: Option<PathBuf>,
/// The sheet to evaluate on, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// The cell the formula sits in
#[arg(long, value_name = "A1")]
pub(crate) cell: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CatArgs {
/// The workbook
pub(crate) file: PathBuf,
/// The range to print (default: the used range)
#[arg(long, value_name = "A1:D20")]
pub(crate) range: Option<String>,
/// The sheet to print, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// Show formulas instead of values
#[arg(long)]
pub(crate) formulas: bool,
/// Print CSV instead of an aligned table
#[arg(long)]
pub(crate) csv: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CheckArgs {
/// Files to check, or folders to scan for .xlsx and .xlsm files
#[arg(required = true, value_name = "FILE_OR_DIR")]
pub(crate) inputs: Vec<PathBuf>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
/// How far a cached number may differ from the recalculated one
#[arg(long, value_name = "T", allow_negative_numbers = true, value_parser = tolerance)]
pub(crate) tolerance: Option<f64>,
/// How many mismatches to list per file
#[arg(long = "max-report", value_name = "N")]
pub(crate) max_report: Option<usize>,
}
/// A formula may start with one dash (`-1+3`), but `--word` is a mistyped option, not a formula (`=--1` is one).
fn formula(text: &str) -> Result<String, UsageError> {
if text.starts_with("--") { Err(UsageError::Formula(text.to_owned())) } else { Ok(text.to_owned()) }
}
fn tolerance(text: &str) -> Result<f64, UsageError> {
text.parse().ok().filter(|t: &f64| t.is_finite() && *t >= 0.0).ok_or_else(|| UsageError::Tolerance(text.to_owned()))
}
/// The command or the script file of a `run` step.
#[derive(Clone, Debug)]
pub(crate) enum RunStep {
/// `--cmd`; a blank or comment line is `None`.
Cmd(Option<Step>),
/// `--script`
Script(PathBuf),
}
#[derive(Args, Debug)]
pub(crate) struct RunArgs {
/// Start from this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Start from a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
/// Run one command, `ID={json}`; repeatable, in order with `--script`
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = command_step)]
cmds: Vec<Option<Step>>,
/// Run a script file of command lines (.jsonl); repeatable, in order with `--cmd`
#[arg(long = "script", value_name = "FILE")]
scripts: Vec<PathBuf>,
/// Save the workbook here when the steps are done (by extension)
#[arg(long, value_name = "FILE")]
pub(crate) out: Option<PathBuf>,
/// Print a range when the steps are done (`used` or empty: the used range); repeatable
#[arg(long, value_name = "RANGE")]
pub(crate) print: Vec<String>,
/// The sheet `--print` shows, by name or index
#[arg(long, value_name = "S", requires = "print")]
pub(crate) sheet: Option<String>,
/// `--print` shows formulas instead of values
#[arg(long, requires = "print")]
pub(crate) formulas: bool,
/// `--print` writes CSV instead of an aligned table
#[arg(long, requires = "print")]
pub(crate) csv: bool,
/// Don't print each command's result
#[arg(long)]
pub(crate) quiet: bool,
/// The steps in the order they were given.
#[arg(skip)]
pub(crate) steps: Vec<RunStep>,
}
/// The values of a repeatable option with the position each was given at.
fn at<T: Clone>(sub: &ArgMatches, id: &str, values: &[T]) -> Vec<(usize, T)> {
sub.indices_of(id).into_iter().flatten().zip(values.iter().cloned()).collect()
}
impl RunArgs {
fn check(&mut self, sub: &ArgMatches) {
let mut steps: Vec<(usize, RunStep)> = at(sub, "cmds", &self.cmds).into_iter().map(|(i, c)| (i, RunStep::Cmd(c))).collect();
steps.extend(at(sub, "scripts", &self.scripts).into_iter().map(|(i, p)| (i, RunStep::Script(p))));
steps.sort_by_key(|(i, _)| *i);
self.steps = steps.into_iter().map(|(_, s)| s).collect();
}
}
fn command_step(text: &str) -> Result<Option<Step>, UsageError> {
parse_command(text).map_err(UsageError::Cmd)
}
#[derive(Args, Debug)]
pub(crate) struct ListArgs {
/// Only those whose id, label or menu contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct FunctionsArgs {
/// Only those whose name or description contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// Only this category
#[arg(long, value_name = "C")]
pub(crate) category: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct McpArgs {
/// Drive the running app (started with `gridcraft --control PORT`) instead of a headless workbook
#[arg(long, value_name = "PORT", conflicts_with_all = ["input", "sample"])]
pub(crate) connect: Option<String>,
/// Serve this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Serve a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
}
#[derive(Args, Debug)]
pub(crate) struct SendArgs {
/// The control port of the running app
pub(crate) port: String,
/// The control-channel method
pub(crate) method: String,
/// Its parameters, as JSON
#[arg(value_name = "JSON", value_parser = json_value)]
pub(crate) params: Option<Value>,
}
fn json_value(text: &str) -> Result<Value, UsageError> {
serde_json::from_str(text).map_err(|e| UsageError::Json(e.to_string()))
}
#[derive(Args, Debug)]
pub(crate) struct SandboxCheckArgs {
/// Let the program read this path; repeatable
#[arg(long, value_name = "PATH")]
pub(crate) read: Vec<PathBuf>,
/// Let the program execute this path; repeatable
#[arg(long = "exec", value_name = "PATH")]
pub(crate) exec: Vec<PathBuf>,
/// After `--`: the program to run confined, and its arguments
#[arg(last = true, value_name = "PROGRAM")]
pub(crate) program: Vec<OsString>,
}
/// A mistake in the command line that clap can't see by itself.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum UsageError {
#[error("--tolerance: expected a number ≥ 0, not `{0}`")]
Tolerance(String),
#[error("unexpected argument '{0}' found (start a formula that begins with `--` with `=`, as in `=--1`)")]
Formula(String),
#[error("--cmd: {0}")]
Cmd(ScriptError),
#[error("bad JSON params: {0}")]
Json(String),
}
/// The clap definition of the whole command line (completions and man pages are generated from it).
pub fn command() -> clap::Command {
Cli::command()
}
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("gridcraft-cli")).chain(args.iter().cloned()))?;
let mut cli = Cli::from_arg_matches(&matches)?;
if let (Command::Run(run), Some(("run", sub))) = (&mut cli.command, matches.subcommand()) {
run.check(sub);
}
Ok(cli)
}
+29 -15
View File
@@ -15,6 +15,7 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::{Cursor, Read as _};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use gridcraft_engine::calc::{Calc, Key};
use gridcraft_engine::cmd::inspect::value_json;
@@ -23,10 +24,7 @@ use gridcraft_engine::formula::{Expr, quote_sheet};
use gridcraft_engine::model::{Cell, Sheet, Workbook};
use serde_json::{Value as Json, json};
use crate::args::CheckArgs;
use crate::commands::{number_text, pretty};
use crate::error::CliError;
use crate::{Io, outln};
use super::{Args, USAGE, number_text, pretty};
mod calc;
mod fidelity;
@@ -191,16 +189,32 @@ impl Diffs {
/// `check <file-or-dir>... [--json] [--tolerance X] [--max-report N]`. Exit 0 when every file opens,
/// every checked formula matches and every round trip is clean; 1 otherwise; 2 on a usage error.
pub(crate) fn run(a: &CheckArgs, io: &mut Io) -> Result<i32, CliError> {
pub fn main(args: &[String]) -> ExitCode {
let usage = |e: String| {
eprintln!("gridcraft-cli: {e}\n{USAGE}");
ExitCode::from(2)
};
let a = match Args::parse(args, &["tolerance", "max-report"], &["json"]) {
Ok(a) => a,
Err(e) => return usage(e),
};
if a.positional.is_empty() {
return usage("missing <file-or-dir>".into());
}
let mut opts = Options::default();
if let Some(t) = a.tolerance {
opts.tolerance = t;
if let Some(t) = a.opt("tolerance") {
match t.parse::<f64>() {
Ok(t) if t.is_finite() && t >= 0.0 => opts.tolerance = t,
_ => return usage(format!("--tolerance needs a number ≥ 0, not `{t}`")),
}
}
if let Some(n) = a.max_report {
opts.max_report = n;
if let Some(n) = a.opt("max-report") {
match n.parse::<usize>() {
Ok(n) => opts.max_report = n,
Err(_) => return usage(format!("--max-report needs a whole number, not `{n}`")),
}
}
let inputs: Vec<String> = a.inputs.iter().map(|p| p.to_string_lossy().into_owned()).collect();
let Discovery { files, failures: mut reports, .. } = collect_inputs(&inputs);
let Discovery { files, failures: mut reports, .. } = collect_inputs(&a.positional);
reports.extend(files.iter().map(|p| {
let path = p.to_string_lossy().into_owned();
match gridcraft_engine::io::read_file(&path) {
@@ -208,12 +222,12 @@ pub(crate) fn run(a: &CheckArgs, io: &mut Io) -> Result<i32, CliError> {
Err(e) => FileReport { path, error: Some(e.to_string()), ..Default::default() },
}
}));
if a.json {
outln!(io, "{}", pretty(&report_json(&reports, &opts)));
if a.has("json") {
outln!("{}", pretty(&report_json(&reports, &opts)));
} else {
print_human(io, &reports, &opts)?;
print_human(&reports, &opts);
}
Ok(if !files.is_empty() && reports.iter().all(FileReport::is_clean) { 0 } else { 1 })
if !files.is_empty() && reports.iter().all(FileReport::is_clean) { ExitCode::SUCCESS } else { ExitCode::FAILURE }
}
#[derive(Default)]
+1 -8
View File
@@ -65,13 +65,6 @@ 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}"));
@@ -161,7 +154,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, pivot_count(sa), pivot_count(sb));
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
}
let mut names = Diffs::new("names", m);
let name_list = |wb: &Workbook| -> BTreeSet<String> {
+31 -41
View File
@@ -131,16 +131,15 @@ fn fit(s: &str, w: usize) -> String {
if n <= w { s.to_string() } else { format!("…{}", s.chars().skip(n + 1 - w).collect::<String>()) }
}
fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
fn print_file_reports(reports: &[FileReport]) {
for r in reports {
outln!(io, "== {}", r.path);
outln!("== {}", r.path);
if let Some(e) = &r.error {
outln!(io, " can't open: {e}");
outln!(" can't open: {e}");
continue;
}
let c = &r.calc;
outln!(
io,
" formulas {}: {} checked, {} matched, {} mismatched, {} no oracle, {} volatile",
c.formula_cells,
c.checked,
@@ -150,15 +149,14 @@ fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliErro
c.volatile
);
if c.stale_cache {
outln!(io, " (the producer asked for a full recalculation on load: its cached values aren't results)");
outln!(" (the producer asked for a full recalculation on load: its cached values aren't results)");
}
if c.bool_as_number > 0 {
outln!(io, " ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
outln!(" ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
}
for m in &c.mismatches {
let tag = if m.primary { "mismatch" } else { " (downstream)" };
outln!(
io,
" {tag} {} {} expected {} got {} [{}]",
m.cell,
one_line(&m.formula),
@@ -168,33 +166,31 @@ fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliErro
);
}
if c.mismatched > c.mismatches.len() {
outln!(io, " … {} more mismatches", c.mismatched - c.mismatches.len());
outln!(" … {} more mismatches", c.mismatched - c.mismatches.len());
}
let rt = &r.round_trip;
if let Some(e) = &rt.error {
outln!(io, " round trip: {e}");
outln!(" round trip: {e}");
}
let differing: Vec<&Category> = rt.categories.iter().filter(|c| c.diffs > 0).collect();
if differing.is_empty() && rt.error.is_none() {
outln!(io, " round trip: all equal");
outln!(" round trip: all equal");
}
for cat in differing {
outln!(io, " round trip {}: {} difference(s)", cat.name, cat.diffs);
outln!(" round trip {}: {} difference(s)", cat.name, cat.diffs);
for e in &cat.examples {
outln!(io, " {}", one_line(e));
outln!(" {}", one_line(e));
}
if cat.diffs > cat.examples.len() {
outln!(io, " … {} more", cat.diffs - cat.examples.len());
outln!(" … {} more", cat.diffs - cat.examples.len());
}
}
}
Ok(())
}
fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
fn print_file_table(reports: &[FileReport]) {
let w = reports.iter().map(|r| r.path.chars().count()).max().unwrap_or(4).clamp(4, 50);
outln!(
io,
"{:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} round trip",
"file",
"formulas",
@@ -207,7 +203,7 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
for r in reports {
let label = fit(&r.path, w);
if let Some(e) = &r.error {
outln!(io, "{label:<w$} can't open: {}", one_line(&fit(e, 100)));
outln!("{label:<w$} can't open: {}", one_line(&fit(e, 100)));
continue;
}
let c = &r.calc;
@@ -217,7 +213,6 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
(None, d) => d.join(","),
};
outln!(
io,
"{label:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} {rt}",
c.formula_cells,
c.checked,
@@ -227,36 +222,33 @@ fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError>
c.volatile
);
}
Ok(())
}
fn print_rankings(io: &mut Io, t: &Totals, opts: &Options) -> Result<(), CliError> {
fn print_rankings(t: &Totals, opts: &Options) {
let top = ranked(&t.functions);
if !top.is_empty() {
outln!(io, "");
outln!(io, "top mismatching functions (primary = no mismatching precedent):");
outln!(io, " {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
outln!("");
outln!("top mismatching functions (primary = no mismatching precedent):");
outln!(" {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
for (n, s) in top.iter().take(opts.max_report.max(1)) {
outln!(io, " {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
outln!(" {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
}
}
let mut sigs: Vec<(&String, &usize)> = t.signatures.iter().collect();
sigs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
if !sigs.is_empty() {
outln!(io, "");
outln!(io, "mismatch signatures (expected → GridCraft):");
outln!("");
outln!("mismatch signatures (expected → GridCraft):");
for (sig, n) in sigs.iter().take(opts.max_report.max(1)) {
outln!(io, " {n:>8} {sig}");
outln!(" {n:>8} {sig}");
}
}
Ok(())
}
fn print_totals(io: &mut Io, t: &Totals) -> Result<(), CliError> {
outln!(io, "");
outln!(io, "files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
fn print_totals(t: &Totals) {
outln!("");
outln!("files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
outln!(
io,
"formula cells: {} ({} checked: {} matched, {} mismatched; {} no oracle; {} volatile)",
t.formula_cells,
t.checked,
@@ -266,25 +258,23 @@ fn print_totals(io: &mut Io, t: &Totals) -> Result<(), CliError> {
t.volatile
);
if t.bool_as_number > 0 {
outln!(io, "booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
outln!("booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
}
let cats: Vec<String> = t.categories.iter().map(|(c, n)| format!("{c} {n}")).collect();
outln!(
io,
"round trip: {} of {} files differ{}{}",
t.round_trip_differing,
t.opened,
if t.round_trip_failed > 0 { format!(" ({} failed)", t.round_trip_failed) } else { String::new() },
if cats.is_empty() { String::new() } else { format!("; categories (files): {}", cats.join(", ")) }
);
Ok(())
}
pub(super) fn print_human(io: &mut Io, reports: &[FileReport], opts: &Options) -> Result<(), CliError> {
print_file_reports(io, reports)?;
outln!(io, "");
print_file_table(io, reports)?;
pub(super) fn print_human(reports: &[FileReport], opts: &Options) {
print_file_reports(reports);
outln!("");
print_file_table(reports);
let t = totals(reports);
print_rankings(io, &t, opts)?;
print_totals(io, &t)
print_rankings(&t, opts);
print_totals(&t);
}
-438
View File
@@ -1,438 +0,0 @@
//! The subcommands: each takes its typed arguments and the streams, and returns what to exit with.
use gridcraft_engine::Session;
use serde_json::{Value, json};
use crate::args::{CatArgs, Command, ConvertArgs, EvalArgs, FunctionsArgs, InfoArgs, ListArgs, McpArgs, RunArgs, RunStep, SendArgs};
use crate::error::{CliError, unicode};
use crate::script::parse_command;
use crate::{Io, check, errln, outln, sandbox_check};
/// Run a parsed command line; gives the exit code (0, or 1 when `check` found a difference and said so itself).
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<i32, CliError> {
match command {
Command::Info(a) => info(&a, io),
Command::Convert(a) => convert(&a, io),
Command::Eval(a) => eval(&a, io),
Command::Cat(a) => cat(&a, io),
Command::Run(a) => run(&a, io),
Command::Commands(a) => commands(&a, io),
Command::Functions(a) => functions(&a, io),
Command::Mcp(a) => mcp(&a, io),
Command::Send(a) => send(&a, io),
Command::Check(a) => return check::run(&a, io),
Command::SandboxCheck(a) => return sandbox_check::run(&a, io),
}
.map(|()| 0)
}
// ---------------------------------------------------------------- helpers
fn exec(io: &mut Io, s: &mut Session, id: &str, params: Value) -> Result<Value, CliError> {
let r = s.execute_headless(id, params).map_err(CliError::engine);
if id == "file.open"
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
for warning in warnings.iter().filter_map(Value::as_str) {
errln!(io, "Warning: {warning}");
}
}
r
}
fn open(io: &mut Io, path: &std::path::Path) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.open", json!({"path": unicode(path)?}))?;
Ok(s)
}
fn sample(io: &mut Io, name: &str) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.new", json!({"sample": name}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(io: &mut Io, s: &mut Session, sheet: Option<&str>) -> Result<(), CliError> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(io, s, "sheet.activate", p)?;
}
Ok(())
}
pub(crate) fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
pub(crate) fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(a: &InfoArgs, io: &mut Io) -> Result<(), CliError> {
let path = unicode(&a.file)?;
let mut s = open(io, &a.file)?;
let v = exec(io, &mut s, "document.inspect", json!({}))?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
outln!(io, "{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
io,
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(
io,
" table {} {} ({})",
t["name"].as_str().unwrap_or("?"),
t["range"].as_str().unwrap_or("?"),
t["style"].as_str().unwrap_or("")
);
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(io, " chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(io, " filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!(io, "names:");
for n in names {
outln!(io, " {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
fn convert(a: &ConvertArgs, io: &mut Io) -> Result<(), CliError> {
let out = unicode(&a.output)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(CliError::OutputFormat { out: out.to_owned() });
}
let mut s = open(io, &a.input)?;
activate_sheet(io, &mut s, a.sheet.as_deref())?;
if pdf {
let result = exec(io, &mut s, "file.exportPdf", json!({"path": out}))?;
errln!(io, "wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
return Ok(());
}
let d = s.doc().map_err(CliError::engine)?;
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(CliError::engine)?;
gridcraft_engine::io::write_file(out, &bytes).map_err(CliError::engine)?;
errln!(io, "wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(a: &EvalArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = match &a.input {
Some(p) => open(io, p)?,
None => blank(),
};
activate_sheet(io, &mut s, a.sheet.as_deref())?;
let formula = if a.formula.starts_with('=') { a.formula.clone() } else { format!("={}", a.formula) };
let mut p = json!({"formula": formula});
if let Some(c) = &a.cell {
p["cell"] = json!(c);
}
let v = exec(io, &mut s, "formulas.evaluate", p)?;
if a.json {
outln!(io, "{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!(io, "{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(io: &mut Io, s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), CliError> {
activate_sheet(io, s, sheet)?;
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
if let Some(sh) = sheet {
p["sheet"] = json!(sh);
}
let raw = exec(io, s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(io, s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!(io, "{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!(io, "{}", line.trim_end());
}
Ok(())
}
fn cat(a: &CatArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = open(io, &a.file)?;
print_range(io, &mut s, a.range.as_deref(), a.sheet.as_deref(), a.formulas, a.csv)
}
fn run(a: &RunArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
let mut step = 0usize;
for item in &a.steps {
let cmds: Vec<(String, Value, String)> = match item {
RunStep::Cmd(c) => c.iter().map(|(id, p)| (id.clone(), p.clone(), "--cmd".to_string())).collect(),
RunStep::Script(path) => {
let value = path.display().to_string();
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
let origin = format!("{value}:{}", i + 1);
if let Some((id, p)) = parse_command(line).map_err(|source| CliError::Script { origin: origin.clone(), source })? {
v.push((id, p, origin));
}
}
v
}
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(io, &mut s, &id, p).map_err(|e| CliError::Step { step, origin, id: id.clone(), message: e.to_string() })?;
if !a.quiet && !r.is_null() {
outln!(io, "{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = &a.out {
let out = unicode(out)?;
let r = exec(io, &mut s, "file.save", json!({"path": out}))?;
errln!(io, "wrote {out} ({} bytes)", r["bytes"]);
}
for range in &a.print {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(io, &mut s, range, a.sheet.as_deref(), a.formulas, a.csv)?;
}
Ok(())
}
fn commands(a: &ListArgs, io: &mut Io) -> Result<(), CliError> {
let q = a.search.as_ref().or(a.word.as_ref()).map(|q| q.to_ascii_lowercase());
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.json {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!(io, "{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!(io, "{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!(io, "{:<w$} {}", "", c.params);
}
errln!(io, "{} commands", list.len());
Ok(())
}
fn functions(a: &FunctionsArgs, io: &mut Io) -> Result<(), CliError> {
let mut p = json!({});
if let Some(q) = a.search.as_ref().or(a.word.as_ref()) {
p["search"] = json!(q);
}
if let Some(c) = &a.category {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(io, &mut s, "formulas.functions", p)?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!(io, "{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(io, " {cat}: {desc}");
}
errln!(io, "{} functions", list.len());
Ok(())
}
fn connect(port: &str) -> Result<gridcraft_mcp::Remote, CliError> {
use gridcraft_mcp::control_addr;
let addr = control_addr(port);
gridcraft_mcp::Remote::connect(&addr).map_err(|e| CliError::Connect { addr, port: port.to_owned(), message: e.to_string() })
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app started with
/// `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(a: &McpArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::{Backend, Headless, Server};
let backend: Box<dyn Backend> = match &a.connect {
Some(c) => Box::new(connect(c)?),
None => {
let session = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
errln!(io, "gridcraft-cli: MCP server on stdio ({})", backend.describe());
// The server speaks on the process's own stdin and stdout: that is the protocol, not this program's output.
let stdin = std::io::stdin();
let stdout = std::io::stdout();
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(CliError::engine)
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(a: &SendArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::Backend;
let params = a.params.clone().unwrap_or_else(|| json!({}));
let mut r = connect(&a.port)?;
let v = r.call(&a.method, params).map_err(CliError::engine)?;
outln!(io, "{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = crate::run(["convert", input.to_str().unwrap(), output.to_str().unwrap()], &mut out, &mut err);
assert_eq!(code, 0, "{}", String::from_utf8_lossy(&err));
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
}
-39
View File
@@ -1,39 +0,0 @@
use std::path::{Path, PathBuf};
/// Why a command failed: printed as `error: {e}`, exit 1. The engine, the MCP backends and the sandbox report their
/// failures as text; [`CliError::Engine`] carries it.
#[derive(Debug, thiserror::Error)]
pub(crate) enum CliError {
/// What the engine, a backend or a library reported.
#[error("{0}")]
Engine(String),
/// The engine's commands take paths as JSON, which holds only text.
#[error("{}: the path is not valid Unicode", .0.display())]
NotUnicode(PathBuf),
#[error("{}: {source}", path.display())]
File { path: PathBuf, source: std::io::Error },
#[error("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)")]
OutputFormat { out: String },
#[error("cannot connect to the GridCraft app at {addr}: {message} (start it with `gridcraft --control {port}`)")]
Connect { addr: String, port: String, message: String },
#[error("step {step} ({origin}, {id}): {message}")]
Step { step: usize, origin: String, id: String, message: String },
#[error("{origin}: {source}")]
Script { origin: String, source: crate::script::ScriptError },
#[error("sandbox-check: {0}")]
Sandbox(String),
/// Standard output went away.
#[error("can't write to stdout: {0}")]
Stdout(std::io::Error),
}
impl CliError {
pub(crate) fn engine(e: impl ToString) -> Self {
Self::Engine(e.to_string())
}
}
/// A path as the text the engine's commands take.
pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> {
path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned()))
}
-120
View File
@@ -1,120 +0,0 @@
//! Headless GridCraft (`gridcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
//! through the binary; `gridcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod args;
mod check;
mod commands;
mod error;
mod sandbox_check;
mod script;
use std::ffi::OsString;
use std::io::Write;
use error::CliError;
pub use args::command;
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
pub(crate) struct Io<'a> {
pub(crate) out: &'a mut dyn Write,
pub(crate) err: &'a mut dyn Write,
}
/// Writes a line of results; fails with [`CliError::Stdout`], which `run` turns into a quiet end for a closed pipe
/// (`gridcraft-cli commands | head`) and a message for any other error.
macro_rules! outln {
($io:expr, $($arg:tt)*) => {
writeln!($io.out, $($arg)*).map_err($crate::error::CliError::Stdout)?
};
}
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
macro_rules! errln {
($io:expr, $($arg:tt)*) => {
drop(writeln!($io.err, $($arg)*))
};
}
pub(crate) use {errln, outln};
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the tokens a shell would see
/// before `--` count: after it they are file names.
fn launch_profile_argument(args: &[OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
/// to `out`, exit 0.
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
where
I: IntoIterator<Item = T>,
T: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
// A confined launcher run (and its probes) comes first, before anything else starts.
if let Some(code) = gridcraft_sandbox::handle_args(&args) {
return code;
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a CLI option, and a CLI
// that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&args) {
let _ = writeln!(err, "error: {flag} belongs to the GridCraft desktop app, not this CLI");
return 2;
}
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
let cli = match args::parse(&args) {
Ok(cli) => cli,
Err(e) => {
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
let _ = write!(to, "{}", e.render());
return e.exit_code();
}
};
let mut io = Io { out, err };
match commands::dispatch(cli.command, &mut io) {
Ok(code) => code,
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
Err(CliError::Stdout(e)) if e.kind() == std::io::ErrorKind::BrokenPipe => 0,
Err(e) => {
errln!(io, "error: {e}");
1
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2 rather than acting on
/// whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
}
+702 -4
View File
@@ -1,9 +1,707 @@
//! `gridcraft-cli`: headless GridCraft. Thin wiring over [`gridcraft_cli::run`].
//! Headless GridCraft.
//!
//! ```text
//! gridcraft-cli info <file> [--json]
//! gridcraft-cli convert <in> <out> [--sheet NAME]
//! gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
//! gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
//! gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
//! gridcraft-cli commands [--json] [--search X]
//! gridcraft-cli functions [--json] [--search X] [--category C]
//! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
//! gridcraft-cli send <port> <method> [json]
//! gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
//! gridcraft-cli version | --version
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
use std::process::ExitCode;
/// `println!` that ends the program quietly when stdout is closed (`gridcraft-cli commands |
/// head`) instead of panicking on a broken pipe.
macro_rules! outln {
($($arg:tt)*) => {{
use std::io::Write as _;
if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
$crate::stdout_failed(e);
}
}};
}
mod check;
mod sandbox_check;
use gridcraft_engine::Session;
use serde_json::{Value, json};
const USAGE: &str = "usage:
gridcraft-cli info <file> [--json] sheets, used ranges, tables, charts, names
gridcraft-cli convert <in> <out> [--sheet NAME] xlsx/csv/tsv/json/html/pdf by extension
gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
cached-value calc oracle + XLSX round-trip fidelity (exit 1 on any difference)
gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl]
[--out FILE] [--print RANGE] [--quiet]
a script line is id={json} or {\"command\": \"id\", \"params\": {…}};
blank lines and lines starting with # or // are skipped
gridcraft-cli commands [--json] [--search X]
gridcraft-cli functions [--json] [--search X] [--category C]
gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
gridcraft-cli send <port> <method> [json]
gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
whether this system confines programs (no program: a confined self-test)
gridcraft-cli version";
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly; any
/// other write error is reported.
fn stdout_failed(e: std::io::Error) -> ! {
if e.kind() == std::io::ErrorKind::BrokenPipe {
std::process::exit(0);
}
eprintln!("gridcraft-cli: can't write to stdout: {e}");
std::process::exit(1);
}
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the
/// tokens a shell would see before `--` count: after it they are file names.
fn launch_profile_argument(args: &[std::ffi::OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
fn main() -> ExitCode {
let (mut out, mut err) = (std::io::stdout().lock(), std::io::stderr().lock());
// An exit code is 0 to 2 here; 128 + signal is the shell's, for a process a signal ended.
ExitCode::from(u8::try_from(gridcraft_cli::run(std::env::args_os().skip(1), &mut out, &mut err)).unwrap_or(1))
// A confined launcher run (and its probes) comes first, before anything else starts.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
return ExitCode::from(u8::try_from(code).unwrap_or(1));
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a
// CLI option, and a CLI that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&raw) {
eprintln!("gridcraft-cli: {flag} belongs to the GridCraft desktop app, not this CLI");
return ExitCode::from(2);
}
let args: Vec<String> = std::env::args().skip(1).collect();
let rest = args.get(1..).unwrap_or_default();
let r = match args.first().map(String::as_str) {
Some("--version" | "-V" | "version") => {
outln!("gridcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some("--help" | "-h" | "help") => {
outln!("{USAGE}");
Ok(())
}
Some("info") => info(rest),
Some("convert") => convert(rest),
Some("eval") => eval(rest),
Some("cat") => cat(rest),
Some("run") => run(rest),
Some("check") => return check::main(rest),
Some("sandbox-check") => return sandbox_check::main(rest),
Some("commands") => commands(rest),
Some("functions") => functions(rest),
Some("mcp") => mcp(rest),
Some("send") => send(rest),
Some(other) => Err(format!("unknown subcommand `{other}`\n{USAGE}")),
None => Err(USAGE.to_string()),
};
match r {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("gridcraft-cli: {e}");
ExitCode::FAILURE
}
}
}
// ---------------------------------------------------------------- argument parsing
/// Parsed arguments: positionals, `--flag value` options and boolean `--switch`es.
struct Args {
positional: Vec<String>,
opts: Vec<(String, String)>,
switches: Vec<String>,
}
impl Args {
/// `with_value` lists the options that take a value; `switches` the boolean ones. Anything
/// else starting with `--` is an error.
fn parse(args: &[String], with_value: &[&str], switches: &[&str]) -> Result<Args, String> {
let mut out = Args { positional: vec![], opts: vec![], switches: vec![] };
let mut it = args.iter();
while let Some(a) = it.next() {
if let Some(name) = a.strip_prefix("--").filter(|n| !n.is_empty()) {
let (name, inline) = match name.split_once('=') {
Some((n, v)) => (n, Some(v.to_string())),
None => (name, None),
};
if with_value.contains(&name) {
let v = match inline {
Some(v) => v,
None => it.next().cloned().ok_or_else(|| format!("--{name} needs a value"))?,
};
out.opts.push((name.to_string(), v));
} else if switches.contains(&name) && inline.is_none() {
out.switches.push(name.to_string());
} else {
return Err(format!("unknown option --{name}"));
}
} else {
out.positional.push(a.clone());
}
}
Ok(out)
}
fn opt(&self, name: &str) -> Option<&str> {
self.opts.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.as_str())
}
fn has(&self, name: &str) -> bool {
self.switches.iter().any(|s| s == name)
}
fn pos(&self, i: usize, what: &str) -> Result<&str, String> {
self.positional.get(i).map(String::as_str).ok_or_else(|| format!("missing {what}\n{USAGE}"))
}
fn no_extra(&self, n: usize) -> Result<(), String> {
match self.positional.get(n) {
Some(x) => Err(format!("unexpected argument `{x}`")),
None => Ok(()),
}
}
}
// ---------------------------------------------------------------- helpers
fn exec(s: &mut Session, id: &str, params: Value) -> Result<Value, String> {
let r = s.execute_headless(id, params).map_err(|e| e.to_string());
if id == "file.open"
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
for warning in warnings.iter().filter_map(Value::as_str) {
eprintln!("Warning: {warning}");
}
}
r
}
fn open(path: &str) -> Result<Session, String> {
let mut s = Session::new();
exec(&mut s, "file.open", json!({"path": path}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(s: &mut Session, sheet: Option<&str>) -> Result<(), String> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(s, "sheet.activate", p)?;
}
Ok(())
}
fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &[], &["json"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
let v = exec(&mut s, "document.inspect", json!({}))?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
outln!("{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(" table {} {} ({})", t["name"].as_str().unwrap_or("?"), t["range"].as_str().unwrap_or("?"), t["style"].as_str().unwrap_or(""));
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(" chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(" filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!("names:");
for n in names {
outln!(" {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
fn convert(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["sheet"], &[])?;
let input = a.pos(0, "<in>")?;
let out = a.pos(1, "<out>")?;
a.no_extra(2)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(format!("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)"));
}
let mut s = open(input)?;
activate_sheet(&mut s, a.opt("sheet"))?;
if pdf {
let result = exec(&mut s, "file.exportPdf", json!({"path": out}))?;
eprintln!("wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
return Ok(());
}
let d = s.doc().map_err(|e| e.to_string())?;
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(|e| e.to_string())?;
gridcraft_engine::io::write_file(out, &bytes).map_err(|e| e.to_string())?;
eprintln!("wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sheet", "cell"], &["json"])?;
let formula = a.pos(0, "<formula>")?;
a.no_extra(1)?;
let mut s = match a.opt("in") {
Some(p) => open(p)?,
None => blank(),
};
activate_sheet(&mut s, a.opt("sheet"))?;
let formula = if formula.starts_with('=') { formula.to_string() } else { format!("={formula}") };
let mut p = json!({"formula": formula});
if let Some(c) = a.opt("cell") {
p["cell"] = json!(c);
}
let v = exec(&mut s, "formulas.evaluate", p)?;
if a.has("json") {
outln!("{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!("{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), String> {
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
if let Some(sh) = sheet {
p["sheet"] = json!(sh);
}
let raw = exec(s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!("{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!("{}", line.trim_end());
}
Ok(())
}
fn cat(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["range", "sheet"], &["formulas", "csv"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
print_range(&mut s, a.opt("range"), a.opt("sheet"), a.has("formulas"), a.has("csv"))
}
/// One command from `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
fn parse_command(text: &str) -> Result<Option<(String, Value)>, String> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| format!("bad JSON: {e}"))?;
// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the
// script still exited 0, so a typo made a valid, wrong workbook (#2256).
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let (plural, list) = (if unknown.len() == 1 { "key" } else { "keys" }, unknown.join("`, `"));
return Err(format!("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}"));
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or("JSON command needs a `command` field")?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() { json!({}) } else { serde_json::from_str(rest).map_err(|e| format!("{id}: bad JSON params: {e}"))? };
Ok(Some((id.to_string(), params)))
}
fn run(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sample", "cmd", "script", "out", "print", "sheet"], &["quiet", "csv", "formulas"])?;
a.no_extra(0)?;
let mut s = match (a.opt("in"), a.opt("sample")) {
(Some(_), Some(_)) => return Err("give --in or --sample, not both".into()),
(Some(p), None) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
let quiet = a.has("quiet");
let mut step = 0usize;
for (name, value) in &a.opts {
let cmds: Vec<(String, Value, String)> = match name.as_str() {
"cmd" => parse_command(value)?.map(|(id, p)| vec![(id, p, "--cmd".to_string())]).unwrap_or_default(),
"script" => {
let text = std::fs::read_to_string(value).map_err(|e| format!("{value}: {e}"))?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
if let Some((id, p)) = parse_command(line).map_err(|e| format!("{value}:{}: {e}", i + 1))? {
v.push((id, p, format!("{value}:{}", i + 1)));
}
}
v
}
_ => continue,
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(&mut s, &id, p).map_err(|e| format!("step {step} ({origin}, {id}): {e}"))?;
if !quiet && !r.is_null() {
outln!("{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = a.opt("out") {
let r = exec(&mut s, "file.save", json!({"path": out}))?;
eprintln!("wrote {out} ({} bytes)", r["bytes"]);
}
for (name, range) in &a.opts {
if name == "print" {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(&mut s, range, a.opt("sheet"), a.has("formulas"), a.has("csv"))?;
}
}
Ok(())
}
fn commands(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search"], &["json"])?;
let q = a.opt("search").or(a.positional.first().map(String::as_str)).map(str::to_ascii_lowercase);
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.has("json") {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!("{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!("{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!("{:<w$} {}", "", c.params);
}
eprintln!("{} commands", list.len());
Ok(())
}
fn functions(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search", "category"], &["json"])?;
let mut p = json!({});
if let Some(q) = a.opt("search").or(a.positional.first().map(String::as_str)) {
p["search"] = json!(q);
}
if let Some(c) = a.opt("category") {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(&mut s, "formulas.functions", p)?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!("{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(" {cat}: {desc}");
}
eprintln!("{} functions", list.len());
Ok(())
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
/// started with `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
let a = Args::parse(args, &["connect", "in", "sample"], &[])?;
a.no_extra(0)?;
let backend: Box<dyn Backend> = match a.opt("connect") {
Some(c) => {
let addr = control_addr(c);
Box::new(
Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control PORT`)"))?,
)
}
None => {
let session = match (a.opt("in"), a.opt("sample")) {
(Some(p), _) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
eprintln!("gridcraft-cli: MCP server on stdio ({})", backend.describe());
let stdin = std::io::stdin();
let stdout = std::io::stdout();
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Remote, control_addr};
let port = args.first().ok_or_else(|| format!("missing <port>\n{USAGE}"))?;
let method = args.get(1).ok_or_else(|| format!("missing <method>\n{USAGE}"))?;
let params: Value = match args.get(2) {
Some(t) => serde_json::from_str(t).map_err(|e| format!("bad JSON params: {e}"))?,
None => json!({}),
};
if let Some(x) = args.get(3) {
return Err(format!("unexpected argument `{x}`"));
}
let addr = control_addr(port);
let mut r = Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control {port}`)"))?;
let v = r.call(method, params)?;
outln!("{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2
/// rather than acting on whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused");
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused");
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn args_parsing() {
let v: Vec<String> = ["a", "--range", "A1", "--csv", "--sheet=S"].iter().map(|s| s.to_string()).collect();
let a = Args::parse(&v, &["range", "sheet"], &["csv"]).unwrap();
assert_eq!(a.positional, ["a"]);
assert_eq!(a.opt("range"), Some("A1"));
assert_eq!(a.opt("sheet"), Some("S"));
assert!(a.has("csv"));
assert!(Args::parse(&["--nope".to_string()], &[], &[]).is_err());
assert!(Args::parse(&["--range".to_string()], &["range"], &[]).is_err());
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
convert(&[input.to_string_lossy().into_owned(), output.to_string_lossy().into_owned()]).unwrap();
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
}
+46 -42
View File
@@ -12,41 +12,54 @@
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;
use crate::args::SandboxCheckArgs;
use crate::error::CliError;
use crate::{Io, errln, outln};
use gridcraft_sandbox::{Canary, Policy, REFUSED_EXIT_CODE, REPORT_FLAG, Support};
pub(crate) fn run(a: &SandboxCheckArgs, io: &mut Io) -> Result<i32, CliError> {
pub fn main(args: &[String]) -> ExitCode {
match run(args) {
Ok(code) => code,
Err(e) => {
eprintln!("gridcraft-cli: sandbox-check: {e}");
ExitCode::FAILURE
}
}
}
fn run(args: &[String]) -> Result<ExitCode, String> {
let mut policy = Policy::new().with_system_libraries();
for path in &a.read {
policy = policy.read(path);
let mut it = args.iter();
let mut program: Option<(PathBuf, Vec<OsString>)> = None;
while let Some(a) = it.next() {
match a.as_str() {
"--read" => policy = policy.read(it.next().ok_or("--read needs a path")?),
"--exec" => policy = policy.exec(it.next().ok_or("--exec needs a path")?),
"--" => {
let p = it.next().ok_or("a program follows `--`")?;
program = Some((PathBuf::from(p), it.by_ref().map(OsString::from).collect()));
}
other => return Err(format!("unknown option `{other}`")),
}
}
for path in &a.exec {
policy = policy.exec(path);
}
let program: Option<(PathBuf, Vec<OsString>)> = a.program.split_first().map(|(p, rest)| (PathBuf::from(p), rest.to_vec()));
// With a program, its standard output is passed through untouched, so this command's own
// lines go to standard error; the self-test's report is the output, on standard output.
let report = program.is_none();
let say = |io: &mut Io, line: String| -> Result<(), CliError> {
let say = |line: String| {
if report {
outln!(io, "{line}");
outln!("{line}");
} else {
errln!(io, "{line}");
eprintln!("{line}");
}
Ok(())
};
match gridcraft_sandbox::support() {
Support::Available(how) => say(io, format!("sandbox: available ({how})"))?,
Support::Available(how) => say(format!("sandbox: available ({how})")),
Support::Unsupported(why) => {
say(io, format!("sandbox: unsupported ({why})"))?;
return Ok(2);
say(format!("sandbox: unsupported ({why})"));
return Ok(ExitCode::from(2));
}
}
let canary = Canary::create().map_err(|e| CliError::Sandbox(e.to_string()))?;
let exe = std::env::current_exe().map_err(|e| CliError::Sandbox(e.to_string()))?;
let canary = Canary::create().map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let (program, program_args) = match program {
Some((p, a)) => (p, a),
// A confined copy of this program, reporting each attempt; it reads its own executable as
@@ -57,38 +70,29 @@ pub(crate) fn run(a: &SandboxCheckArgs, io: &mut Io) -> Result<i32, CliError> {
}
};
let policy = policy.exec(program.clone());
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| CliError::Sandbox(e.to_string()))?;
let status = cmd.status().map_err(|e| CliError::Sandbox(format!("couldn't start the launcher: {e}")))?;
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| e.to_string())?;
let status = cmd.status().map_err(|e| format!("couldn't start the launcher: {e}"))?;
drop(canary);
match status.code() {
Some(0) => {
say(
io,
if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into(),
)?;
Ok(0)
say(if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into());
Ok(ExitCode::SUCCESS)
}
Some(REFUSED_EXIT_CODE) => {
// The launcher's refusal and a program's own exit share the code; the launcher's reason,
// when it refused, is the `gridcraft-sandbox: refused:` line above.
say(
io,
format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
),
)?;
Ok(1)
say(format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
));
Ok(ExitCode::FAILURE)
}
other => {
say(
io,
format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
),
)?;
Ok(1)
say(format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
));
Ok(ExitCode::FAILURE)
}
}
}
-92
View File
@@ -1,92 +0,0 @@
//! One command of a script: `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
use serde_json::{Value, json};
/// A command line that cannot be read.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum ScriptError {
#[error("bad JSON: {0}")]
BadJson(String),
/// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
/// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the script still exited 0, so a
/// typo made a valid, wrong workbook (#2256).
#[error("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}")]
UnknownKeys { plural: &'static str, list: String },
#[error("JSON command needs a `command` field")]
NoCommand,
#[error("{id}: bad JSON params: {why}")]
BadParams { id: String, why: String },
}
/// A command and its parameters.
pub(crate) type Step = (String, Value);
/// The command in `text`, or `None` for a blank line, a `#` comment or a `//` comment.
pub(crate) fn parse_command(text: &str) -> Result<Option<Step>, ScriptError> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| ScriptError::BadJson(e.to_string()))?;
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let plural = if unknown.len() == 1 { "key" } else { "keys" };
return Err(ScriptError::UnknownKeys { plural, list: unknown.join("`, `") });
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or(ScriptError::NoCommand)?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() {
json!({})
} else {
serde_json::from_str(rest).map_err(|e| ScriptError::BadParams { id: id.to_string(), why: e.to_string() })?
};
Ok(Some((id.to_string(), params)))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused").to_string();
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused").to_string();
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
}
-142
View File
@@ -1,142 +0,0 @@
//! What the command line does with its arguments: RFC-0018's contract, through the binary. A usage error exits 2 on
//! stderr; help and the version go to stdout with exit 0; an unknown or repeated flag after a subcommand is refused.
use std::process::Command;
struct Ran {
code: Option<i32>,
out: String,
err: String,
}
fn run(args: &[&str]) -> Ran {
let o = Command::new(env!("CARGO_BIN_EXE_gridcraft-cli")).args(args).output().unwrap();
Ran { code: o.status.code(), out: String::from_utf8_lossy(&o.stdout).into_owned(), err: String::from_utf8_lossy(&o.stderr).into_owned() }
}
const SUBCOMMANDS: [&str; 11] = ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"];
/// A usage error: exit 2, nothing on stdout, `error:` and the offending argument on stderr.
fn usage_error(args: &[&str], names: &str) {
let r = run(args);
assert_eq!(r.code, Some(2), "{args:?}: {:?} / {:?}", r.out, r.err);
assert_eq!(r.out, "", "{args:?}");
assert!(r.err.starts_with("error:") && r.err.contains(names), "{args:?}: {:?}", r.err);
}
#[test]
fn every_subcommand_answers_help_and_version_on_stdout() {
for sub in SUBCOMMANDS {
for flag in ["--help", "-h"] {
let r = run(&[sub, flag]);
assert_eq!((r.code, r.err.as_str()), (Some(0), ""), "{sub} {flag}");
assert!(r.out.contains(&format!("Usage: gridcraft-cli {sub}")), "{sub} {flag}: {:?}", r.out);
assert!(r.out.contains("Exit status:"), "{sub} {flag}: {:?}", r.out);
}
let r = run(&[sub, "--version"]);
assert!(r.out.starts_with(&format!("gridcraft-cli-{sub} ")), "{sub}: {:?}", r.out);
}
let r = run(&["help", "run"]);
assert_eq!(r.code, Some(0));
}
#[test]
fn an_unknown_option_is_refused_by_name_in_every_subcommand() {
for sub in ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"] {
usage_error(&[sub, "--no-such-option"], "--no-such-option");
}
// An option of another subcommand is not this one's.
usage_error(&["commands", "--sample", "x"], "--sample");
usage_error(&["info", "a.xlsx", "--csv"], "--csv");
usage_error(&["cat", "a.xlsx", "--json"], "--json");
}
#[test]
fn a_missing_or_extra_argument_is_a_usage_error() {
usage_error(&["info"], "FILE");
usage_error(&["info", "a", "b"], "b");
usage_error(&["convert", "a.xlsx"], "OUTPUT");
usage_error(&["eval"], "FORMULA");
usage_error(&["check"], "FILE_OR_DIR");
usage_error(&["send", "7979"], "METHOD");
usage_error(&["run", "--in"], "--in");
usage_error(&["run", "--cmd"], "--cmd");
usage_error(&["commands", "a", "b"], "b");
}
#[test]
fn a_repeated_single_value_flag_is_refused() {
usage_error(&["convert", "a.xlsx", "b.csv", "--sheet", "1", "--sheet", "2"], "--sheet");
usage_error(&["run", "--in", "a.xlsx", "--in", "b.xlsx"], "--in");
usage_error(&["run", "--out", "a.xlsx", "--out", "b.xlsx"], "--out");
usage_error(&["check", "x.xlsx", "--tolerance", "1", "--tolerance", "2"], "--tolerance");
}
#[test]
fn conflicting_flags_are_refused_before_anything_starts() {
usage_error(&["run", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["mcp", "--connect", "7979", "--in", "a.xlsx"], "--connect");
usage_error(&["mcp", "--connect", "7979", "--sample", "sales"], "--connect");
usage_error(&["mcp", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["commands", "x", "--search", "y"], "--search");
// `--print` carries the options that shape it.
usage_error(&["run", "--csv"], "--print");
usage_error(&["run", "--sheet", "1"], "--print");
}
#[test]
fn a_value_that_cannot_mean_anything_is_a_usage_error() {
usage_error(&["check", "x.xlsx", "--tolerance", "-1"], "--tolerance");
usage_error(&["check", "x.xlsx", "--tolerance", "nan"], "--tolerance");
usage_error(&["check", "x.xlsx", "--max-report", "many"], "--max-report");
usage_error(&["run", "--cmd", "x={bad"], "--cmd");
usage_error(&["send", "7979", "m", "{bad"], "JSON");
}
/// `eval` takes its formula as the first thing, even one that starts with a dash; `--` ends the options.
#[test]
fn a_formula_may_start_with_a_dash() {
let r = run(&["eval", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2"), "{:?}", r.err);
let r = run(&["eval", "--json", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2.0"), "{:?}", r.err);
// A mistyped option is not a formula; `=` makes it one.
usage_error(&["eval", "--no-such-option"], "--no-such-option");
assert_eq!(run(&["eval", "=--1"]).code, Some(0));
}
/// A word after the options (or after `--`) is a filter; `--search` is the same filter as an option.
#[test]
fn commands_and_functions_filter_by_a_word_or_search() {
let a = run(&["commands", "--json", "home.bold"]);
let b = run(&["commands", "--json", "--search", "home.bold"]);
assert_eq!((a.code, b.code), (Some(0), Some(0)));
assert_eq!(a.out, b.out);
assert!(a.out.contains("home.bold"));
let r = run(&["functions", "--json", "--category", "Math and trigonometry", "SUM"]);
assert_eq!(r.code, Some(0), "{}", r.err);
}
/// A failed command is exit 1 with `error:`; connection failures are command failures, not usage errors.
#[test]
fn a_failed_command_exits_1_with_an_error_line() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port().to_string();
drop(listener);
for args in [&["send", &port, "x"][..], &["mcp", "--connect", &port], &["info", "/no/such/file.xlsx"], &["convert", "/no/such.xlsx", "o.csv"]] {
let r = run(args);
assert_eq!(r.code, Some(1), "{args:?}: {:?}", r.err);
assert_eq!(r.out, "");
assert!(r.err.starts_with("error:"), "{args:?}: {:?}", r.err);
}
}
/// The nightly profile protocol belongs to the desktop app: exit 2 before any subcommand parses it.
#[test]
fn the_launcher_profile_arguments_are_refused() {
for args in [&["--launch-profile", "nightly-v1", "info", "a.xlsx"][..], &["info", "--profile-root=/tmp/x", "a.xlsx"]] {
let r = run(args);
assert_eq!((r.code, r.out.as_str()), (Some(2), ""), "{args:?}");
assert!(r.err.contains("desktop app"), "{:?}", r.err);
}
}
+6 -12
View File
@@ -25,18 +25,12 @@ fn tmpdir(name: &str) -> PathBuf {
#[test]
fn version_and_usage() {
assert_eq!(ok(&["--version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
assert_eq!(ok(&["-V"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
// `--version` reaches the subcommands, and there is no `version` subcommand.
assert!(ok(&["run", "--version"]).starts_with("gridcraft-cli-run "));
for unknown in ["frobnicate", "version"] {
let o = run(&[unknown]);
assert_eq!(o.status.code(), Some(2), "{unknown}");
assert!(String::from_utf8_lossy(&o.stderr).contains("unrecognized subcommand"));
}
// No arguments: the usage on stderr, a usage error.
assert_eq!(ok(&["version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
let o = run(&["frobnicate"]);
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown subcommand"));
let o = run(&[]);
assert_eq!(o.status.code(), Some(2));
assert!(o.stdout.is_empty() && String::from_utf8_lossy(&o.stderr).contains("Usage: gridcraft-cli"));
assert!(!o.status.success());
}
#[test]
@@ -281,7 +275,7 @@ fn a_script_line_with_an_unknown_key_stops_the_run() {
assert!(!info.contains("Sheet2"), "and no sheet was added with a default name: {info}");
// The usage text says what a line looks like, which is how this was found.
let usage = ok(&["run", "--help"]);
let usage = String::from_utf8_lossy(&run(&[]).stderr).into_owned() + &String::from_utf8_lossy(&run(&["--help"]).stdout);
assert!(usage.contains(r#"{"command": "id", "params": {…}}"#), "{usage}");
let _ = std::fs::remove_dir_all(&dir);
-143
View File
@@ -1,143 +0,0 @@
//! `gridcraft_cli::run` called in-process: the same program the binary is, with its streams captured, so the whole of
//! RFC-0018's surface is covered without a subprocess per case.
fn run(args: &[&str]) -> (i32, String, String) {
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = gridcraft_cli::run(args.iter().copied(), &mut out, &mut err);
(code, String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap())
}
struct Dir(std::path::PathBuf);
impl Dir {
fn new(name: &str) -> Dir {
let dir = std::env::temp_dir().join(format!("gc-inproc-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Dir(dir)
}
fn file(&self, name: &str) -> String {
self.0.join(name).to_str().unwrap().to_owned()
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn help_and_version_exit_0_on_stdout_and_usage_errors_exit_2_on_stderr() {
for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"], &["run", "-V"], &["check", "--help"]] {
let (code, out, err) = run(args);
assert_eq!((code, err.as_str()), (0, ""), "{args:?}");
assert!(!out.is_empty(), "{args:?}");
}
for args in [&[][..], &["bogus"], &["info"], &["run", "--nope"], &["info", "--bogus"]] {
let (code, out, err) = run(args);
assert_eq!((code, out.as_str()), (2, ""), "{args:?}");
assert!(err.contains("Usage: gridcraft-cli"), "{args:?}: {err}");
}
}
#[test]
fn eval_info_cat_and_commands_write_results_to_stdout_and_progress_to_stderr() {
let dir = Dir::new("flow");
let book = dir.file("b.xlsx");
let (code, out, err) = run(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("cell.set") && err.contains("wrote"), "{out} / {err}");
let (code, out, _) = run(&["eval", "=SUM(1,2,3)"]);
assert_eq!((code, out.trim()), (0, "6"));
let (code, out, err) = run(&["info", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("Sheet1"), "{out}");
let (code, out, _) = run(&["info", "--json", &book]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, out, _) = run(&["cat", &book, "--csv"]);
assert_eq!((code, out.trim()), (0, "2"));
let (code, out, _) = run(&["cat", &book, "--formulas"]);
assert_eq!((code, out.trim()), (0, "=1+1"));
let csv = dir.file("b.csv");
let (code, _, err) = run(&["convert", &book, &csv]);
assert_eq!(code, 0, "{err}");
assert_eq!(std::fs::read_to_string(&csv).unwrap().trim(), "2");
let (code, _, err) = run(&["convert", &book, &dir.file("b.nope")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:") && err.contains("unknown output format"), "{err}");
}
#[test]
fn run_keeps_cmd_and_script_in_the_order_given() {
let dir = Dir::new("order");
let script = dir.file("s.jsonl");
std::fs::write(&script, "cell.set={\"cell\":\"A1\",\"input\":\"2\"}\n").unwrap();
// The script writes A1 = 2 after the first --cmd wrote 1 and before the last wrote 3: the last one wins.
let (code, out, err) = run(&[
"run",
"--quiet",
"--cmd",
r#"cell.set={"cell":"A1","input":"1"}"#,
"--script",
&script,
"--cmd",
r#"cell.set={"cell":"B1","input":"=A1*10"}"#,
"--print",
"A1:B1",
"--csv",
]);
assert_eq!(code, 0, "{err}");
assert_eq!(out.trim(), "2,20", "{out}");
let (code, _, err) = run(&["run", "--script", &dir.file("missing.jsonl")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:"), "{err}");
let (code, _, err) = run(&["run", "--cmd", "no.such.command"]);
assert_eq!(code, 1);
assert!(err.contains("step 1 (--cmd, no.such.command)"), "{err}");
}
#[test]
fn check_reports_and_exits_with_the_verdict() {
let dir = Dir::new("check");
let book = dir.file("b.xlsx");
assert_eq!(run(&["run", "--quiet", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]).0, 0);
let (code, out, _) = run(&["check", &book]);
assert_eq!(code, 0, "{out}");
assert!(out.contains("files: 1"), "{out}");
let (code, out, _) = run(&["check", "--json", &book, "--tolerance", "1e-6", "--max-report", "3"]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, _, _) = run(&["check", &dir.file("missing.xlsx")]);
assert_eq!(code, 1);
}
#[test]
fn sandbox_check_without_a_program_reports_on_stdout() {
let (code, out, _) = run(&["sandbox-check"]);
assert!(out.starts_with("sandbox:"), "{out}");
assert!(code == 0 || code == 1 || code == 2, "{code}");
}
/// A closed stdout (`gridcraft-cli commands | head`) ends the program quietly; any other write error is reported.
#[test]
fn a_closed_pipe_ends_quietly_and_another_write_error_is_an_error() {
struct Failing(std::io::ErrorKind);
impl std::io::Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut err = Vec::new();
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::BrokenPipe), &mut err), 0);
assert!(err.is_empty());
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8(err).unwrap().starts_with("error:"));
}
-3
View File
@@ -1,7 +1,4 @@
//! The crate's integration tests, one module per file, built as one test binary.
mod args;
mod cli;
mod in_process;
mod man_and_completions;
mod sandbox;
mod text_to_columns_quotes;
@@ -1,55 +0,0 @@
//! The clap definition is consistent, and every shell's completions and every man page
//! (`examples/man-and-completions.rs`) can be generated from it.
use clap::ValueEnum;
use clap_complete::Shell;
// The example itself, so the test writes the files exactly as the packages get them.
#[allow(dead_code)]
#[path = "../../examples/man-and-completions.rs"]
mod example;
#[test]
fn command_is_consistent() {
gridcraft_cli::command().debug_assert();
}
#[test]
fn completions_generate_for_every_shell() {
for &shell in Shell::value_variants() {
let mut out = Vec::new();
clap_complete::generate(shell, &mut gridcraft_cli::command(), "gridcraft-cli", &mut out);
assert!(!out.is_empty(), "{shell}");
}
}
#[test]
fn man_pages_render_for_the_command_and_every_subcommand() {
let cmd = gridcraft_cli::command();
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
let mut out = Vec::new();
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
assert!(!out.is_empty(), "{}", page.get_name());
}
}
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
/// `packaging/freebsd/package.sh` install, `gridcraft-cli.1` and a page per subcommand, and no
/// pages for the `help` subcommand.
#[test]
fn the_example_writes_the_files_the_packages_install() {
let dir = std::env::temp_dir().join(format!("gc-cli-{}-man-and-completions", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
example::generate(&dir).unwrap();
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
written.sort();
let completions = ["gridcraft-cli.bash", "_gridcraft-cli", "gridcraft-cli.fish", "gridcraft-cli.elv", "_gridcraft-cli.ps1"];
let subcommands = ["cat", "check", "commands", "convert", "eval", "functions", "info", "mcp", "run", "sandbox-check", "send"];
let mut expected: Vec<String> = completions.map(String::from).into();
expected.push("gridcraft-cli.1".into());
expected.extend(subcommands.iter().map(|s| format!("gridcraft-cli-{s}.1")));
expected.sort();
assert_eq!(written, expected);
std::fs::remove_dir_all(&dir).unwrap();
}
-6
View File
@@ -118,9 +118,3 @@ sync_github_name = true
[people.RockerHX]
sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
[people.alosslessdev]
real_name = "Francisco Herrera"
+7 -1
View File
@@ -216,7 +216,13 @@ 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)) => Value::text(gridcraft_core::cap_text(x + &y)),
(Ok(x), Ok(y)) => {
if x.len() + y.len() > 32767 * 4 {
Value::Error(CellError::Value)
} else {
Value::text(x + &y)
}
}
(Err(e), _) | (_, Err(e)) => Value::Error(e),
},
BinOp::Eq => Value::Bool(compare(a, b) == Equal),
+1 -1
View File
@@ -12,7 +12,7 @@ mod trimrange;
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
pub use precision::DisplayedPrecision;
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, evaluate_expr, now_serial};
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial};
#[cfg(test)]
mod tests;
-13
View File
@@ -2762,19 +2762,6 @@ 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();
+6 -13
View File
@@ -16,7 +16,6 @@ enum Fam {
Col100,
Line,
LineStack,
Line100,
Area,
AreaStack,
Area100,
@@ -32,7 +31,6 @@ 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,
@@ -42,7 +40,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::Line100 | Fam::Area100)
matches!(f, Fam::Col100 | Fam::Area100)
}
fn is_col(f: Fam) -> bool {
@@ -50,12 +48,7 @@ fn is_col(f: Fam) -> bool {
}
fn is_line(f: Fam) -> bool {
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)
matches!(f, Fam::Line | Fam::LineStack)
}
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
@@ -163,7 +156,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, lines and areas stack apart).
// Totals for 100% stacking, per axis and family (100% columns and 100% 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);
@@ -194,7 +187,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::Line100 | Fam::AreaStack | Fam::Area100);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100);
let key = (a, fam);
let si = if stacked {
match stacks.iter().position(|(k, _, _)| *k == key) {
@@ -223,7 +216,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 is_100(fam) { share(key, j, v) } else { v };
let v = if fam == Fam::Area100 { share(key, j, v) } else { v };
pos.get_mut(j).map(|acc| {
let base = *acc;
*acc = clean(*acc + v);
@@ -431,7 +424,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 has_markers(k) && cw >= 3.0 {
if k == ChartKind::LineMarkers && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
}
if labels_on {
+2 -4
View File
@@ -57,10 +57,8 @@ 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::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => {
Swatch::Line
}
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
ChartKind::LineMarkers => 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 | ChartKind::LineStacked100 => Swatch::Line,
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
_ => Swatch::Box,
};
draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color);
+8 -20
View File
@@ -360,7 +360,7 @@ fn category_label(wb: &Workbook, src: Option<(&gridcraft_model::Sheet, RangeRef)
/// the outer levels of a multi-level axis: a category range wider than a column of values (or
/// taller than a row of values) groups its innermost labels, year beside month. Each outer level
/// has one entry per category, non-empty where a group starts, as the cells are.
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize, innermost: bool) -> (Vec<String>, Vec<Vec<String>>) {
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize) -> (Vec<String>, Vec<Vec<String>>) {
let cells: Option<(usize, RangeRef)> = parse_ref(wb, sheet, formula);
let value_range = parse_ref(wb, sheet, values).map(|(_, r)| r);
// Bound the category dimension by `limit` and read only the cells the levels use (the
@@ -419,21 +419,12 @@ fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limi
let at = |row: usize, col: usize| texts.get(row * w + col).cloned().unwrap_or_default();
let column = |c: usize| (0..h).map(|row| at(row, c)).collect::<Vec<String>>();
let row = |rr: usize| (0..w).map(|c| at(rr, c)).collect::<Vec<String>>();
let value_count = eval_list_in(wb, sheet, values, limit, 0).len();
let by_columns = if value_count == h && w > 1 && h != w {
true
} else if value_count == w && h > 1 && h != w {
false
} else {
levels.by_columns
};
let outer = if by_columns { w.saturating_sub(1).min(3) } else { h.saturating_sub(1).min(3) };
let result = if by_columns {
let outer = levels.outer as usize;
if levels.by_columns {
(column(w - 1), (1..=outer).filter_map(|k| (w - 1).checked_sub(k)).map(column).collect())
} else {
(row(h - 1), (1..=outer).filter_map(|k| (h - 1).checked_sub(k)).map(row).collect())
};
if innermost { (result.0, vec![]) } else { result }
}
}
/// Whether `t` names a defined name seen from `sheet` (`Name`, or `Sheet1!Name` looked up on
@@ -483,7 +474,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
if categories.is_none()
&& let Some(f) = &s.categories
{
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit, s.innermost_categories);
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit);
c.truncate(limit);
if !c.is_empty() {
categories = Some(c);
@@ -511,10 +502,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
secondary: s.secondary,
smooth: s.smooth,
trendlines,
number_format: match &s.number_format {
Some(code) if s.values.trim_start().starts_with('{') => code.clone(),
_ => ref_format(wb, sheet, &s.values),
},
number_format: ref_format(wb, sheet, &s.values),
});
}
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
@@ -533,7 +521,7 @@ mod label_budget_tests {
#[test]
fn category_labels_share_one_byte_budget() {
let wb = Workbook::new();
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS, false);
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS);
assert_eq!(texts.len(), 100_000);
assert_eq!(texts.first().map(String::len), Some(super::MAX_LABEL_CHARS));
assert!(texts.iter().map(String::len).sum::<usize>() <= super::MAX_CATEGORY_BYTES);
@@ -556,7 +544,7 @@ mod label_budget_tests {
}
}
// Five columns: column A is a fourth outer level and is discarded.
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS, false);
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS);
assert_eq!(outer.len(), 3);
assert_eq!(inner.last().map(String::len), Some(super::MAX_LABEL_CHARS));
assert_eq!(outer.first().and_then(|l| l.last()).map(String::len), Some(super::MAX_LABEL_CHARS));
+1 -140
View File
@@ -8,7 +8,7 @@ use crate::*;
mod budget;
mod data_table;
const ALL_KINDS: [ChartKind; 28] = [
const ALL_KINDS: [ChartKind; 26] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -18,8 +18,6 @@ const ALL_KINDS: [ChartKind; 28] = [
ChartKind::Line,
ChartKind::LineMarkers,
ChartKind::LineStacked,
ChartKind::LineStacked100,
ChartKind::LineStacked100Markers,
ChartKind::Pie,
ChartKind::Doughnut,
ChartKind::Area,
@@ -551,9 +549,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
// References use their cells' format, whatever the series says.
number_format: Some("0%".into()),
innermost_categories: false,
},
Series {
name: None,
@@ -566,8 +561,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: Some("Literal".into()),
@@ -580,8 +573,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: Some("0.0%".into()),
innermost_categories: false,
},
];
let d = resolve(&wb, 0, &c);
@@ -601,7 +592,6 @@ fn resolve_from_workbook() {
assert!(s1.secondary);
assert_eq!(d.series[2].name, "Literal");
assert_eq!(d.series[2].values.len(), 4);
assert_eq!(d.series[2].number_format, "0.0%");
// Default categories.
c.series.remove(0);
@@ -622,8 +612,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: None,
@@ -636,8 +624,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
];
let d = resolve(&wb, 0, &c);
@@ -655,8 +641,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
@@ -675,8 +659,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 7, &c);
assert_eq!(d.series.len(), 1);
@@ -1382,8 +1364,6 @@ fn pie_points_follow_workbook_theme() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 0, &c);
let expected = vec![series_color(&wb.theme, 0), series_color(&wb.theme, 1)];
@@ -1439,47 +1419,6 @@ fn area_charts_draw_source_value_labels_only_when_enabled() {
}
}
#[test]
fn a_multi_level_category_block_draws_its_innermost_level() {
// A PivotChart's two levels of row labels in A1:B4, the outer one (country) on the left:
// one label per point, from the innermost column.
let mut wb = Workbook::new();
{
let s = wb.sheet_mut(0).unwrap();
s.name = "Graph".into();
for (r, (outer, inner)) in [("Canada", "Ottawa"), ("", "Toronto"), ("USA", "Boston"), ("", "NYC")].iter().enumerate() {
if !outer.is_empty() {
s.set_value(CellRef::new(r as u32, 0), Value::from(*outer));
}
s.set_value(CellRef::new(r as u32, 1), Value::from(*inner));
s.set_value(CellRef::new(r as u32, 2), Value::Number(r as f64 + 1.0));
s.set_value(CellRef::new(5, r as u32), Value::from(*inner));
s.set_value(CellRef::new(6, r as u32), Value::from(*outer));
}
}
let mut c = chart(ChartKind::ColumnClustered);
c.series = vec![Series {
categories: Some("Graph!$A$1:$B$4".into()),
values: "Graph!$C$1:$C$4".into(),
innermost_categories: true,
..Series::default()
}];
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
// A block with a column per point: its last row is the innermost level.
c.series[0].categories = Some("Graph!$A$6:$D$7".into());
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Canada", "", "USA", ""]);
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
// Without the flag, every cell is a label, as for any other chart.
c.series[0].categories = Some("Graph!$A$1:$B$4".into());
c.series[0].innermost_categories = false;
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
assert_eq!(data.category_levels, vec![vec!["Canada", "", "USA", ""]]);
}
#[test]
fn drawing_and_resolving_agree_on_the_combo_plot_kind() {
// Resolved series carry `Chart::series_kind`, the kind drawing uses: for every chart kind,
@@ -1552,62 +1491,6 @@ 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", "", ""];
@@ -1682,22 +1565,6 @@ fn two_level_categories_resolve_and_draw() {
assert!(d.category_levels.is_empty());
}
#[test]
fn square_category_blocks_keep_their_declared_orientation_on_ties() {
let mut wb = Workbook::new();
let s = wb.sheet_mut(0).unwrap();
s.name = "Data".into();
for (i, value) in ["A1", "B1", "A2", "B2", "A3", "B3"].iter().enumerate() {
s.set_value(CellRef::parse(value).unwrap(), Value::from(*value));
s.set_value(CellRef::new(3, i as u32), Value::Number(i as f64 + 1.0));
}
let mut c = chart(ChartKind::Line);
c.series = vec![Series { categories: Some("Data!$A$1:$B$2".into()), values: "Data!$A$3:$B$3".into(), ..Series::default() }];
let d = resolve(&wb, 0, &c);
assert_eq!(d.categories, vec!["A2", "B2"]);
assert_eq!(d.category_levels, vec![vec!["A1", "B1"]]);
}
#[test]
fn a_huge_trendline_forecast_does_not_collapse_the_columns() {
let m = ApproxMeasure;
@@ -1774,7 +1641,6 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
..Series::default()
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
@@ -1811,7 +1677,6 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
..Series::default()
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
@@ -1833,8 +1698,6 @@ fn volatile_series_formulas_are_detected() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
@@ -1864,8 +1727,6 @@ fn volatile_defined_names_are_followed() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
-29
View File
@@ -148,32 +148,3 @@ 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");
}
}
-65
View File
@@ -162,43 +162,6 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
Some(serial as f64)
}
/// The calendar date a pivot cache's ISO 8601 date items (`<d>`, `minDate`, `startDate`…) give
/// a date of a date system's calendar, as [`datetime_from_serial`] returns it. Those dates count
/// real days: from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to
/// February 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious
/// 1900-02-29, runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30,
/// serial 1 is 1899-12-31 and serial 60 is 1900-02-28. Excel writes its caches that way.
pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) {
if sys == DateSystem::D1900 && year == 1900 && month <= 2 {
let serial = if month <= 1 { day } else { 31 + day };
return civil_from_days(i64::from(serial) + UNIX_1899_12_30);
}
(year, month, day)
}
/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`]
/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid.
/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the
/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date,
/// or one before the epoch or after 9999-12-31.
pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option<f64> {
let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?);
match (sys, y, m, d) {
(DateSystem::D1900, 1900, 2, 29) => return Some(60.0),
(DateSystem::D1904, 1899, 12, 30) => return Some(0.0),
_ => {}
}
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) {
return None;
}
let base = match sys {
DateSystem::D1900 => UNIX_1899_12_30,
DateSystem::D1904 => UNIX_1904_01_01,
};
let serial = days_from_civil(y, m, d) - base;
(0..=max_serial(sys)).contains(&serial).then_some(serial as f64)
}
/// Date/time from a serial. `None` for negative or too-large serials.
pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option<DateTime> {
if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) {
@@ -421,32 +384,4 @@ mod tests {
assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar
Ok(())
}
#[test]
fn iso_dates_count_real_days() {
let s = DateSystem::D1900;
// Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31.
for (serial, ymd) in
[(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))]
{
let d = datetime_from_serial(s, serial as f64).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}");
assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}");
}
assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None);
assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0));
assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None);
assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None);
// The 1904 system has no offset; 1899-12-30 stands for a time's date part there too.
let s = DateSystem::D1904;
let d = datetime_from_serial(s, 0.5).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1));
assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None);
}
}
+1 -1
View File
@@ -16,4 +16,4 @@ pub use addr::{
};
pub use date::DateSystem;
pub use region::Region;
pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
-35
View File
@@ -501,31 +501,6 @@ 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::*;
@@ -609,16 +584,6 @@ 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);
-377
View File
@@ -1,377 +0,0 @@
//! Calculation benchmarks on fixed workbooks built in code (release build). Run through
//! `cargo xtask bench`, which builds this in release and compares against a saved baseline, or
//! directly: `cargo run --release -p gridcraft-engine --example bench -- [--quick] [--rows N]
//! [--reps N] [--filter NAME] [--json PATH]`.
//!
//! Every scenario builds its workbook untimed, runs one warm-up, then times `reps` runs of one
//! operation through `Session::execute` (so a timing includes what an edit costs the user: undo
//! history, graph update and recalculation). Results are checked so a scenario that silently
//! stopped recalculating fails instead of getting fast.
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
use std::time::{Duration, Instant};
use gridcraft_core::{CellRef, Value};
use gridcraft_engine::Session;
use serde_json::{Value as Json, json};
struct Cfg {
rows: usize,
reps: usize,
filter: Option<String>,
}
struct Outcome {
name: &'static str,
what: String,
times: Vec<Duration>,
cells: usize,
}
type R<T> = Result<T, String>;
/// A scenario: its name and the function that runs it.
type Scenario = (&'static str, fn(&Cfg) -> R<Outcome>);
fn main() -> std::process::ExitCode {
match run() {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
eprintln!("bench: {e}");
std::process::ExitCode::FAILURE
}
}
}
fn run() -> R<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
let quick = args.iter().any(|a| a == "--quick");
let cfg = Cfg {
rows: count(flag("--rows"), "--rows")?.unwrap_or(if quick { 10_000 } else { 100_000 }).max(200),
reps: count(flag("--reps"), "--reps")?.unwrap_or(if quick { 3 } else { 7 }).max(1),
filter: flag("--filter"),
};
let scenarios: [Scenario; 10] = [
("edit.chain", edit_chain),
("edit.fanout", edit_fanout),
("edit.sliding", edit_sliding),
("edit.sumifs", edit_sumifs),
("edit.lookup", edit_lookup),
("enter.formulas", enter_formulas),
("recalc.full", recalc_full),
("data.sort", data_sort),
("xlsx.save", xlsx_save),
("xlsx.open", xlsx_open),
];
println!("GridCraft calc bench: {} rows, {} reps (median / min)\n", cfg.rows, cfg.reps);
println!("{:<16} {:>10} {:>10} {:>9} workload", "scenario", "median", "min", "cells");
let mut results = Vec::new();
// A failed scenario is reported and the others still run, so one regression doesn't hide
// the numbers for everything else.
let mut failed = Vec::new();
let selected: Vec<_> = scenarios.into_iter().filter(|(name, _)| cfg.filter.as_deref().is_none_or(|p| name.contains(p))).collect();
if selected.is_empty() {
// An empty run would otherwise save as a baseline with nothing in it.
return Err(format!("--filter {} matches no scenario", cfg.filter.as_deref().unwrap_or("")));
}
for (name, f) in selected {
let o = match f(&cfg) {
Ok(o) => o,
Err(e) => {
println!("{name:<16} {:>10} {e}", "FAILED");
failed.push(name);
continue;
}
};
let (med, min) = stats(&o.times);
let cells = if o.cells == 0 { "-".to_string() } else { o.cells.to_string() };
println!("{:<16} {:>10} {:>10} {:>9} {}", o.name, ms(med), ms(min), cells, o.what);
results.push(json!({"name": o.name, "what": o.what, "median_ms": med, "min_ms": min, "cells": o.cells}));
}
if let Some(path) = flag("--json") {
let out = json!({"rows": cfg.rows, "reps": cfg.reps, "results": results, "failed": failed});
let text = serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?;
std::fs::write(&path, text).map_err(|e| format!("{path}: {e}"))?;
}
if failed.is_empty() { Ok(()) } else { Err(format!("{} scenario(s) failed: {}", failed.len(), failed.join(", "))) }
}
fn stats(times: &[Duration]) -> (f64, f64) {
let mut v: Vec<f64> = times.iter().map(|d| d.as_secs_f64() * 1000.0).collect();
v.sort_by(f64::total_cmp);
// An even count averages the two middle samples.
let mid = v.len() / 2;
let med = match (v.len() % 2, v.get(mid.wrapping_sub(1)), v.get(mid)) {
(0, Some(a), Some(b)) => (a + b) / 2.0,
(_, _, Some(m)) => *m,
_ => 0.0,
};
(med, v.first().copied().unwrap_or(0.0))
}
fn ms(v: f64) -> String {
if v >= 100.0 { format!("{v:.0} ms") } else { format!("{v:.2} ms") }
}
fn exec(s: &mut Session, cmd: &str, p: Json) -> R<Json> {
s.execute(cmd, p).map_err(|e| format!("{cmd}: {e}"))
}
/// A count flag's value; one that isn't a number is an error, not the default.
fn count(v: Option<String>, name: &str) -> R<Option<usize>> {
v.map(|s| s.parse().map_err(|_| format!("{name}: `{s}` is not a count"))).transpose()
}
fn session() -> R<Session> {
let mut s = Session::new();
s.new_workbook();
Ok(s)
}
/// Writes `rows` rows starting at `col` row 1, `make(i)` giving row i (0-based), in chunks.
fn fill(s: &mut Session, col: &str, rows: usize, make: impl Fn(usize) -> Json) -> R<()> {
let chunk = 10_000;
let mut r = 0;
while r < rows {
let n = chunk.min(rows - r);
let vals: Vec<Json> = (r..r + n).map(&make).collect();
exec(s, "range.setValues", json!({"range": format!("{col}{}", r + 1), "values": vals}))?;
r += n;
}
Ok(())
}
fn num(s: &Session, at: &str) -> R<f64> {
let c = CellRef::parse(at).ok_or_else(|| format!("bad ref {at}"))?;
let d = s.doc().map_err(|e| e.to_string())?;
match d.wb.sheet(0).map(|sh| sh.value(c)) {
Some(Value::Number(n)) => Ok(n),
other => Err(format!("{at} = {other:?}, expected a number")),
}
}
fn expect(s: &Session, at: &str, want: f64) -> R<()> {
let got = num(s, at)?;
if (got - want).abs() <= 1e-6 * want.abs().max(1.0) { Ok(()) } else { Err(format!("{at} = {got}, expected {want}")) }
}
fn recalc_cells(s: &Session) -> usize {
s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0)
}
/// Runs a warm-up then `reps` timed calls of `op(rep)`, then `check(rep)` (untimed) after each.
fn time(
cfg: &Cfg,
s: &mut Session,
op: impl FnMut(&mut Session, usize) -> R<()>,
check: impl Fn(&Session, usize) -> R<()>,
) -> R<(Vec<Duration>, usize)> {
time_prepared(cfg, s, |_| Ok(()), op, check)
}
/// [`time`] with `prep` run (untimed) before each call, to put back the state `op` starts from.
fn time_prepared(
cfg: &Cfg,
s: &mut Session,
mut prep: impl FnMut(&mut Session) -> R<()>,
mut op: impl FnMut(&mut Session, usize) -> R<()>,
check: impl Fn(&Session, usize) -> R<()>,
) -> R<(Vec<Duration>, usize)> {
let mut times = Vec::with_capacity(cfg.reps);
let mut cells = 0;
for rep in 0..=cfg.reps {
prep(s)?;
let t = Instant::now();
op(s, rep)?;
let dt = t.elapsed();
check(s, rep)?;
cells = recalc_cells(s);
if rep > 0 {
times.push(dt);
}
}
Ok((times, cells))
}
/// Value typed into A1 on rep `r`: alternates so every rep changes something.
fn a1(r: usize) -> f64 {
(r % 2 + 2) as f64
}
/// A running sum `B[n] = B[n-1] + A[n]`: one edit at the top recalculates a dependency chain
/// `rows` deep.
fn edit_chain(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |_| json!([1]))?;
fill(&mut s, "B", n, |i| json!([if i == 0 { "=A1".to_string() } else { format!("=B{i}+A{}", i + 1) }]))?;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, &format!("B{n}"), (n - 1) as f64 + a1(r)),
)?;
Ok(Outcome { name: "edit.chain", what: format!("edit A1 under a {n}-deep running sum"), times, cells })
}
/// `rows` formulas that each read `$A$1`: one edit, a wide and shallow dirty set.
fn edit_fanout(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
exec(&mut s, "cell.set", json!({"cell": "A1", "input": "1"}))?;
fill(&mut s, "B", n, |i| json!([format!("=$A$1*{}", i + 1)]))?;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, &format!("B{n}"), a1(r) * n as f64),
)?;
Ok(Outcome { name: "edit.fanout", what: format!("edit $A$1 read by {n} formulas"), times, cells })
}
/// `rows` overlapping 100-row window sums; an edit in the middle dirties ~100 of them, so this
/// measures the range index lookup, not evaluation.
fn edit_sliding(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n + 99, |_| json!([1]))?;
fill(&mut s, "B", n, |i| json!([format!("=SUM(A{}:A{})", i + 1, i + 100)]))?;
let mid = n / 2;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": format!("A{mid}"), "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, &format!("B{mid}"), 99.0 + a1(r)),
)?;
Ok(Outcome { name: "edit.sliding", what: format!("edit one cell under {n} 100-row SUM windows"), times, cells })
}
/// 100 whole-column SUMIFS over `rows` rows of data, all dirtied by one data edit.
fn edit_sumifs(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([1, (i % 100) as f64]))?;
fill(&mut s, "D", 100, |k| json!([format!("=SUMIFS(A:A,B:B,{k})")]))?;
// Rows whose category is 0 (i % 100 == 0), A1 among them.
let per = n.div_ceil(100) as f64;
let (times, cells) = time(
cfg,
&mut s,
|s, r| exec(s, "cell.set", json!({"cell": "A1", "input": a1(r).to_string()})).map(drop),
|s, r| expect(s, "D1", per - 1.0 + a1(r)),
)?;
Ok(Outcome { name: "edit.sumifs", what: format!("edit data under 100 SUMIFS(A:A,B:B,k) over {n} rows"), times, cells })
}
/// 100 exact-match XLOOKUPs over whole columns of `rows` keys, all dirtied by one key edit.
fn edit_lookup(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([(i + 1) as f64, (2 * (i + 1)) as f64]))?;
let step = n / 100;
fill(&mut s, "D", 100, |k| json!([format!("=XLOOKUP({},A:A,B:B,0)", (k + 1) * step)]))?;
let last = (2 * 100 * step) as f64;
let (times, cells) = time(
cfg,
&mut s,
// D1 looks up the key in A{step}: removing it (-step) makes D1 fall back to 0, putting it
// back finds it again. Every lookup reads A:A, so all 100 recalculate either way.
|s, r| {
let key = if r % 2 == 0 { format!("-{step}") } else { step.to_string() };
exec(s, "cell.set", json!({"cell": format!("A{step}"), "input": key})).map(drop)
},
|s, r| {
expect(s, "D1", if r % 2 == 0 { 0.0 } else { (2 * step) as f64 })?;
expect(s, "D100", last)
},
)?;
Ok(Outcome { name: "edit.lookup", what: format!("edit a key under 100 XLOOKUPs over {n} rows"), times, cells })
}
/// Entering `rows` formulas in one command: parse, graph insertion and first evaluation.
fn enter_formulas(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([(i % 97) as f64]))?;
let vals: Vec<Json> = (0..n).map(|i| json!([format!("=A{}*2+1", i + 1)])).collect();
let (times, cells) = time_prepared(
cfg,
&mut s,
// Each run enters the formulas into empty cells, not over the previous run's.
|s| exec(s, "edit.clearAll", json!({"range": format!("B1:B{n}")})).map(drop),
|s, _| exec(s, "range.setValues", json!({"range": "B1", "values": vals})).map(drop),
|s, _| expect(s, &format!("B{n}"), ((n - 1) % 97) as f64 * 2.0 + 1.0),
)?;
Ok(Outcome { name: "enter.formulas", what: format!("enter {n} formulas =An*2+1 in one paste"), times, cells })
}
/// A model with 3 formulas per row (arithmetic and a row SUM), recalculated in full.
fn model(n: usize) -> R<Session> {
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([(i % 97) as f64, format!("=A{}*2", i + 1), format!("=B{0}+A{0}", i + 1), format!("=SUM(A{0}:C{0})", i + 1)]))?;
Ok(s)
}
fn recalc_full(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = model(n)?;
// Manual calculation, and A[n] changed (untimed) before each run, so D[n] is stale until
// Calculate Now recalculates: a Calculate Now that did nothing fails the check.
exec(&mut s, "formulas.calculationOptions", json!({"mode": "manual"}))?;
let mut rep = 0;
let (times, cells) = time_prepared(
cfg,
&mut s,
|s| {
rep += 1;
exec(s, "cell.set", json!({"cell": format!("A{n}"), "input": (100 + rep).to_string()})).map(drop)
},
|s, _| exec(s, "formulas.calculateNow", json!({})).map(drop),
|s, r| expect(s, &format!("D{n}"), (101 + r) as f64 * 6.0),
)?;
Ok(Outcome { name: "recalc.full", what: format!("Calculate Now, {} formulas (3 per row)", 3 * n), times, cells })
}
fn data_sort(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = session()?;
fill(&mut s, "A", n, |i| json!([format!("Item {i}"), (i % 97) as f64, ((i * 7919) % 1000) as f64]))?;
let (times, _) = time(
cfg,
&mut s,
|s, r| {
let cmd = if r % 2 == 0 { "data.sortDescending" } else { "data.sortAscending" };
exec(s, cmd, json!({"range": format!("A1:C{n}"), "column": "B"})).map(drop)
},
|s, r| expect(s, "B1", if r % 2 == 0 { 96.0 } else { 0.0 }),
)?;
// A sort with no formulas recalculates nothing; 0 shows as "-".
Ok(Outcome { name: "data.sort", what: format!("sort {n} rows x 3 columns by a numeric key"), times, cells: 0 })
}
fn save_bytes(s: &mut Session) -> R<String> {
let r = exec(s, "file.saveBytes", json!({"format": "xlsx"}))?;
r.get("base64").and_then(Json::as_str).map(str::to_string).ok_or_else(|| "file.saveBytes: no base64".to_string())
}
fn xlsx_save(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = model(n)?;
let (times, _) = time(cfg, &mut s, |s, _| save_bytes(s).map(drop), |_, _| Ok(()))?;
Ok(Outcome { name: "xlsx.save", what: format!("save the {n}-row model as XLSX"), times, cells: 0 })
}
fn xlsx_open(cfg: &Cfg) -> R<Outcome> {
let n = cfg.rows;
let mut s = model(n)?;
let b64 = save_bytes(&mut s)?;
let last = ((n - 1) % 97) as f64 * 6.0;
let (times, cells) = time(
cfg,
&mut s,
|s, _| exec(s, "file.open", json!({"name": "bench.xlsx", "base64": b64})).map(drop),
|s, _| expect(s, &format!("D{n}"), last),
)?;
Ok(Outcome { name: "xlsx.open", what: format!("open the {n}-row model from XLSX (with full recalc)"), times, cells })
}
+60
View File
@@ -0,0 +1,60 @@
//! Performance scenarios on large workbooks (release build):
//! `cargo run --release -p gridcraft-engine --example perf -- [rows]`
#![allow(clippy::disallowed_methods)] // a native-only benchmark: wasm never runs it
use std::time::Instant;
use gridcraft_engine::Session;
use serde_json::json;
fn main() {
let rows: usize = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(100_000);
let mut s = Session::new();
s.new_workbook();
// Data: rows × 6 numeric columns, built through range.setValues in chunks.
let t = Instant::now();
let chunk = 10_000;
let mut r = 0;
while r < rows {
let n = chunk.min(rows - r);
let vals: Vec<serde_json::Value> = (0..n)
.map(|i| json!([format!("Item {}", r + i), (r + i) as f64, ((r + i) % 97) as f64, ((r + i) % 13) as f64 * 1.5, 1.0, 2.0]))
.collect();
s.execute("range.setValues", json!({"range": format!("A{}", r + 1), "values": vals})).expect("set");
r += n;
}
println!("fill {rows}x6 values: {:?}", t.elapsed());
// Formulas: G = B*C+D, H = running sum of G (chain).
let t = Instant::now();
s.execute("cell.set", json!({"cell": "G1", "input": "=B1*C1+D1"})).expect("g1");
s.execute("edit.autoFill", json!({"source": "G1", "target": format!("G1:G{rows}")})).expect("fill g");
println!("fill {rows} formulas G=B*C+D: {:?}", t.elapsed());
let t = Instant::now();
s.execute("cell.set", json!({"cell": "H1", "input": "=G1"})).expect("h1");
s.execute("cell.set", json!({"cell": "H2", "input": "=H1+G2"})).expect("h2");
s.execute("edit.autoFill", json!({"source": "H2", "target": format!("H2:H{rows}")})).expect("fill h");
println!("fill {rows} chained running-sum formulas: {:?}", t.elapsed());
let t = Instant::now();
s.execute("cell.set", json!({"cell": "J1", "input": format!("=SUM(G1:G{rows})")})).expect("sum");
s.execute("cell.set", json!({"cell": "J2", "input": "=SUMIFS(B:B,C:C,\">50\")"})).expect("sumifs");
s.execute("cell.set", json!({"cell": "J3", "input": "=XLOOKUP(\"Item 77777\",A:A,B:B)"})).expect("xlookup");
println!("aggregate formulas: {:?}", t.elapsed());
// Edit at the top: everything below recalculates.
let t = Instant::now();
s.execute("cell.set", json!({"cell": "B1", "input": "5"})).expect("edit");
println!("edit B1 → recalc {} cells: {:?}", s.doc().map(|d| d.calc.last_recalc_cells).unwrap_or(0), t.elapsed());
let t = Instant::now();
s.execute("data.sortDescending", json!({"range": format!("A1:F{rows}"), "column": "C"})).expect("sort");
println!("sort {rows} rows: {:?}", t.elapsed());
let t = Instant::now();
let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).expect("save");
let b64 = r["base64"].as_str().unwrap_or("").to_string();
println!("save xlsx ({} bytes): {:?}", r["bytes"], t.elapsed());
let t = Instant::now();
s.execute("file.open", json!({"name": "big.xlsx", "base64": b64})).expect("open");
println!("open xlsx + full recalc: {:?}", t.elapsed());
let t = Instant::now();
s.execute("edit.undo", json!({})).ok();
println!("undo: {:?}", t.elapsed());
}
+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};
+80 -228
View File
@@ -1,9 +1,8 @@
use super::sort::sort_key;
use super::{
AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param,
data_target, edit, json,
current_region, data_target, edit, json,
};
use std::collections::{HashMap, HashSet};
// ---------------------------------------------------------------- filter
@@ -15,63 +14,14 @@ 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)
});
}
@@ -94,58 +44,19 @@ 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)?;
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"));
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));
}
}
edit(s, |cx| {
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 });
cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] });
Ok(json!({"filter": true, "range": r.a1()}))
})
}
@@ -270,18 +181,19 @@ pub(crate) fn grow_autofilter(sh: &mut Sheet, at: CellRef) {
}
}
/// 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;
/// 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();
// Precompute per-criterion top10 threshold and average once, not per row.
let mut col_stats = HashMap::new();
let mut col_stats: std::collections::HashMap<usize, (Option<f64>, f64)> = std::collections::HashMap::new();
for (i, (off, c)) in af.criteria.iter().enumerate() {
if matches!(c, FilterCriterion::Top10 { .. } | FilterCriterion::AboveAverage(_)) {
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 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 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 } => {
@@ -295,97 +207,59 @@ fn filter_stats(sh: &Sheet, af: &AutoFilter) -> HashMap<usize, (Option<f64>, f64
col_stats.insert(i, (thr, avg));
}
}
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
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 {
n < *avg
values.iter().any(|x| x.eq_ignore_ascii_case(&text) || x.eq_ignore_ascii_case(&v.display()))
}
}
_ => 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,
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));
}
}
/// 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 {
@@ -420,52 +294,30 @@ pub(super) fn reapply(s: &mut Session, _: &Json) -> Result<Json> {
})
}
/// Distinct display values from rows matching the other columns' criteria.
/// The current criterion only determines checkboxes, so its unchecked alternatives stay available.
/// Distinct display values of a filter column (for the dropdown list).
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![] };
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 off = col.saturating_sub(af.range.start.col);
let selected: Option<&FilterCriterion> = af.criteria.iter().find(|(o, _)| *o == off).map(|(_, c)| c);
let mut seen = std::collections::BTreeMap::new();
// 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;
}
for row in af.range.start.row + 1..=af.range.end.row.min(af.range.start.row + 1_000_000) {
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 = selected.is_none_or(|(i, (off, crit))| matcher.criterion_matches(row, i, *off, crit));
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 key = if blank { sort_key(&Value::Empty) } else { sort_key(&v) };
// One choice can represent rows with different colors; keep any matching row checked.
*seen.entry((key, t)).or_insert(false) |= on;
seen.entry((key, t)).or_insert(on);
}
let mut values: Vec<_> = seen.into_iter().collect();
values.sort_by(|((a, ta), _), ((b, tb), _)| {
+2 -4
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: gridcraft_core::cap_value(Value::text(input)), formula: None, style, py: None }));
return Ok(Some(Cell { 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,8 +71,6 @@ 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()
@@ -319,7 +317,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: gridcraft_core::cap_value(Value::Text(text.as_str().into())), formula: None, style, py: None })
Some(Cell { value: Value::Text(text.as_str().into()), formula: None, style, py: None })
}
}
_ => input_to_cell(&input, sheet, at, &mut cx.wb)?,
@@ -421,11 +421,6 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
if let (Some(a), Some(b)) = (m.start.offset(dr, dc), m.end.offset(dr, dc)) {
let nm = RangeRef::new(a, b);
let sh = cx.sheet_mut(dest_sheet)?;
// A table can't hold merged cells (Excel removes the table on open): the
// cells are pasted there unmerged.
if sh.tables.iter().any(|t| t.range.intersects(&nm)) {
continue;
}
sh.merges.retain(|x| !x.intersects(&nm));
sh.merges.push(nm);
}
-30
View File
@@ -148,27 +148,6 @@ 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.
@@ -229,15 +208,6 @@ 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();
+18 -124
View File
@@ -1,5 +1,4 @@
use super::{CellRef, EngineError, Json, RangeRef, Result, Session, TableColumn, TotalsFn, Value, bad, edit, json, ok, str_param, target_range};
use gridcraft_model::Cell;
pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
let r = str_param(p, "range").and_then(RangeRef::parse).ok_or_else(|| bad("table.resize", "missing `range`"))?;
@@ -12,85 +11,30 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
}
.ok_or_else(|| bad("table.resize", "select a cell in a table"))?;
edit(s, |cx| {
let wb = &cx.wb;
let sheet = wb.sheet(si).ok_or(EngineError::NoDocument)?;
let t = sheet.tables.get(ti).ok_or_else(|| bad("table", "gone"))?;
let sheet = cx.sheet_mut(si)?;
let headers: Vec<String> = (r.start.col..=r.end.col).map(|c| sheet.value(CellRef::new(r.start.row, c)).display()).collect();
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap another table.".into()));
}
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
if r.start.row != t.range.start.row || !r.intersects(&t.range) {
return Err(EngineError::Other(
"The headers must remain in the same row, and the resulting table range must overlap the original table range.".into(),
));
}
// Like Excel, the new range can't take in another table, a merged area, a PivotTable or a
// multi-cell array formula (a spill is fine: it shows #SPILL! inside the table).
if sheet.tables.iter().enumerate().any(|(i, o)| i != ti && o.range.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap another table.".into()));
let mut cols = Vec::new();
for (i, h) in headers.iter().enumerate() {
let name = if h.is_empty() { format!("Column{}", i + 1) } else { h.clone() };
let existing = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&name)).cloned();
cols.push(existing.unwrap_or(TableColumn {
name,
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
xml: None,
}));
}
if sheet.merges.iter().any(|m| m.intersects(&r)) {
return Err(EngineError::Other("A table can't overlap merged cells.".into()));
}
if sheet.pivots.iter().any(|pt| pt.last_range.unwrap_or_else(|| RangeRef::new(pt.anchor, pt.anchor)).intersects(&r)) {
return Err(EngineError::Other("A table can't overlap a PivotTable report.".into()));
}
if sheet.cells.iter().any(|(_, x)| x.formula.as_ref().and_then(|f| f.array).is_some_and(|a| !a.is_single() && a.intersects(&r))) {
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
}
// Header text per new column (`None`: empty). Without a header row, a column that stays
// keeps its name.
let texts: Vec<Option<String>> = (r.start.col..=r.end.col)
.map(|c| {
if !t.header_row {
return c.checked_sub(t.range.start.col).and_then(|i| t.columns.get(i as usize)).map(|x| x.name.clone());
}
let at = CellRef::new(r.start.row, c);
let v = sheet.value(at);
let text = match v.as_text() {
Some(x) => x.to_string(),
None => crate::display::value_text(wb, sheet, at),
};
(!text.trim().is_empty()).then_some(text)
})
.collect();
let names = resized_column_names(&texts);
let old = t.range;
let old_cols = t.columns.clone();
let header_row = t.header_row;
let mut cols = Vec::with_capacity(names.len());
for (c, name) in (r.start.col..=r.end.col).zip(&names) {
// A column that stays keeps its settings (totals, calculated formula): with a header
// row it's found by name, without one by position.
let existing = if header_row {
// A header that was normalized into a generated name keeps the settings of the
// column at its address, not of whichever column already has that name.
let raw = texts.get((c - r.start.col) as usize).and_then(|x| x.as_deref());
if c >= old.start.col && c <= old.end.col && raw != Some(name.as_str()) {
old_cols.get((c - old.start.col) as usize)
} else {
old_cols.iter().find(|x| x.name.eq_ignore_ascii_case(name))
}
} else if c >= old.start.col && c <= old.end.col {
old_cols.get((c - old.start.col) as usize)
} else {
None
};
cols.push(match existing {
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
});
}
let sheet = cx.sheet_mut(si)?;
if header_row {
// Headers hold constant text: a generated or de-duplicated name is written into its
// cell, so the header row and the column names never disagree.
for (c, col) in (r.start.col..=r.end.col).zip(&cols) {
let at = CellRef::new(r.start.row, c);
let constant_text = sheet.value(at).as_text() == Some(col.name.as_str()) && sheet.cell(at).is_some_and(|x| x.formula.is_none());
if !constant_text {
let style = sheet.style_id(at);
sheet.set_cell(at, Cell { value: Value::text(col.name.as_str()), style, ..Default::default() });
}
}
}
let t = sheet.tables.get_mut(ti).ok_or_else(|| bad("table", "gone"))?;
t.columns = cols;
t.range = r;
cx.structural = true;
@@ -98,56 +42,6 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// Unique column names for a resized table, from each column's header text (`None` = empty), the
/// way Excel names them: a repeated header gets the lowest free suffix (`Qty`, `Qty2`, `Qty3`,
/// compared without case), and an empty header continues a `ColumnN` neighbour on its left
/// (`Column3` → `Column4`, or `Column32` when `Column4` is taken) or else takes the lowest free
/// `ColumnN`.
fn resized_column_names(texts: &[Option<String>]) -> Vec<String> {
use std::collections::{HashMap, HashSet};
let mut taken: HashSet<String> = HashSet::new();
let mut next_suffix: HashMap<String, u64> = HashMap::new();
// The lowest `ColumnN` not yet tried, so many empty headers stay linear.
let mut lowest = 1u64;
let mut names: Vec<String> = Vec::with_capacity(texts.len());
let dedupe = |base: &str, taken: &HashSet<String>, next_suffix: &mut HashMap<String, u64>| {
let k = next_suffix.entry(base.to_lowercase()).or_insert(2);
let mut n = base.to_string();
while taken.contains(&n.to_lowercase()) {
n = format!("{base}{k}");
*k = k.saturating_add(1);
}
n
};
for text in texts {
let name = match text {
Some(t) => dedupe(t, &taken, &mut next_suffix),
None => {
let left = names.last().and_then(|l| {
l.strip_prefix("Column")
.filter(|d| !d.starts_with('0') && !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
.and_then(|d| d.parse::<u64>().ok())
});
match left {
Some(n) => {
let cand = format!("Column{}", n.saturating_add(1));
if taken.contains(&cand.to_lowercase()) { dedupe(&format!("Column{n}"), &taken, &mut next_suffix) } else { cand }
}
None => {
while taken.contains(&format!("column{lowest}")) {
lowest = lowest.saturating_add(1);
}
format!("Column{lowest}")
}
}
}
};
taken.insert(name.to_lowercase());
names.push(name);
}
names
}
/// Most cells (rows × columns, blanks included) Get Data imports. The rows are built densely
/// before they are written, so a few sparse records or one far-away CSV cell must not expand
/// into a rectangle of billions of slots.
+3 -30
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, EngineError};
use crate::DocState;
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, {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.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.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,19 +59,6 @@ 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
@@ -91,7 +78,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 && !read_only).map(str::to_string);
let path = str_param(p, "path").filter(|_| !imported && !encrypted).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()))
@@ -100,9 +87,6 @@ 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);
}
@@ -122,14 +106,6 @@ 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,
@@ -138,9 +114,6 @@ 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")) {
-2
View File
@@ -439,8 +439,6 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
})
.collect();
sheet.charts.push(Chart {
+3 -219
View File
@@ -553,12 +553,7 @@ fn format_cells(s: &mut Session, p: &Json) -> Result<Json> {
{
*st = new;
}
})?;
// A number format set here widens columns as the ribbon's do (observed: Excel 16.0).
if patch.get("num_fmt").is_some() {
widen_for_numbers(s, p)?;
}
ok()
})
}
/// The style patch with camelCase keys (`numFmt`, `diagDown`, as documented) renamed to the
@@ -642,11 +637,6 @@ fn merge(s: &mut Session, p: &Json, how: &str) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let how =
if how == "center" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| ranges.iter().all(|r| sh.merges.contains(r))) { "unmerge" } else { how };
// Excel has no merged cells in a table (a file with one loses the table when Excel opens it):
// merging there is refused, unmerging is still allowed.
if how != "unmerge" && s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| ranges.iter().any(|r| t.range.intersects(r)))) {
return Err(EngineError::Other("You can't merge cells in a table.".into()));
}
edit(s, |cx| {
let mut touched = Vec::new();
// Areas whose merging changes: a merged cell blocks a dynamic array's spill.
@@ -742,95 +732,9 @@ fn number_format(s: &mut Session, p: &Json) -> Result<Json> {
set_fmt(s, p, &code)
}
/// How many stored cells [`widen_for_numbers`] looks at in one command.
const MAX_WIDEN_CELLS: usize = 1_000_000;
fn set_fmt(s: &mut Session, p: &Json, code: &str) -> Result<Json> {
let nf = NumFmt::new(code);
apply_style(s, p, |st| st.num_fmt = nf.clone())?;
widen_for_numbers(s, p)
}
/// After a number format from the ribbon (Increase Decimal, Comma Style, the Number Format list…) or
/// Format Cells, a column nobody sized by hand widens so the formatted numbers in the target fit,
/// instead of showing ####. Observed in Excel 16.0 (build 17932): a column at the default width, AutoFitted, or
/// widened this way before widens to the widest number in the range, also with Wrap Text and a large
/// font. A width set with Column Width (or by dragging) stays, even when it equals the default. Hidden
/// columns, text, General numbers (they round to fit), shrink-to-fit and merged cells don't widen,
/// and columns never narrow.
fn widen_for_numbers(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
let ranges = target_ranges(s, p)?;
let measure = s.text_width.clone();
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(Json::Null) };
let Some(used) = sh.used_range() else { return Ok(Json::Null) };
if sh.show_formulas {
return Ok(Json::Null);
}
let targets: Vec<RangeRef> = ranges.iter().filter_map(|r| r.intersection(&used)).collect();
// Merged areas over the targets as sorted row intervals per column, so each cell is checked
// with a binary search rather than a scan of every merge.
let mut merged: std::collections::HashMap<u32, Vec<(u32, u32)>> = Default::default();
for m in sh.merges.iter().filter(|m| !m.is_single()) {
for x in targets.iter().filter_map(|r| m.intersection(r)) {
for col in x.start.col..=x.end.col {
merged.entry(col).or_default().push((m.start.row, m.end.row));
}
}
}
for v in merged.values_mut() {
v.sort_unstable();
v.dedup();
}
let in_merge = |c: CellRef| {
merged.get(&c.col).is_some_and(|v| {
let i = v.partition_point(|&(r0, _)| r0 <= c.row);
i > 0 && v.get(i - 1).is_some_and(|&(_, r1)| c.row <= r1)
})
};
let mut need: std::collections::BTreeMap<u32, f32> = std::collections::BTreeMap::new();
// Measured as AutoFit Column Width measures (the UI's font when it supplies one).
let mut measured: std::collections::HashMap<(StyleId, String), f32> = Default::default();
// The stored cells looked at are capped, not the area: a sparse target as tall as the sheet
// still widens for the numbers it holds. Spilled values count as the grid shows them.
let mut budget = MAX_WIDEN_CELLS;
for r in &targets {
let spilled = sh.spill.range(r.start..=r.end).map(|(c, _)| *c).filter(|c| r.contains(*c));
for c in sh.cells.iter_range(*r).map(|(c, _)| c).chain(spilled) {
if budget == 0 {
break;
}
budget -= 1;
if !matches!(sh.value_ref(c), Some(gridcraft_core::Value::Number(_)))
|| sh.cols.get(&c.col).is_some_and(|i| i.custom || i.hidden)
|| in_merge(c)
{
continue;
}
let id = sh.style_id(c);
let st = cx.wb.styles.get(id);
if st.num_fmt.as_str() == "General" || st.align.shrink || st.align.h == HAlign::Fill {
continue;
}
let text = crate::display::cell_text(&cx.wb, sh, c);
let exact = measured.len() < EXACT_TEXT_WIDTHS;
let w = *measured.entry((id, text)).or_insert_with_key(|(_, t)| match &measure {
Some(m) => m(t, &st.font, exact),
None => approx_text_width(t, st.font.size, st.font.bold),
});
let w = w + 6.0 + st.align.indent as f32 * 9.0;
let e = need.entry(c.col).or_insert(0.0);
*e = e.max(w);
}
}
let widen: Vec<(u32, f32)> = need.into_iter().filter(|&(c, w)| w > sh.col_width(c)).collect();
let sh = cx.sheet_mut(sheet)?;
for (c, w) in widen {
sh.cols.entry(c).or_default().size = Some(w.ceil().min(1785.0));
}
Ok(Json::Null)
})
apply_style(s, p, |st| st.num_fmt = nf.clone())
}
/// Adds or removes one decimal place in the number format (Increase/Decrease Decimal).
@@ -915,8 +819,8 @@ mod sizes;
use cell_styles::cell_style;
pub use cell_styles::{CELL_STYLE_NAMES, builtin_cell_style};
use sizes::{EXACT_TEXT_WIDTHS, autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
pub use sizes::{approx_text_width, chars_to_points};
use sizes::{autofit_cols, autofit_rows, col_width, default_width, hide, row_height};
#[cfg(test)]
mod tests {
@@ -952,112 +856,6 @@ mod tests {
assert_eq!(adjust_decimals("0%", &v, 1), "0.0%");
}
fn col(s: &crate::Session, c: u32) -> (f32, bool) {
let sh = s.active().unwrap().wb.active().unwrap();
(sh.col_width(c), sh.cols.get(&c).is_some_and(|i| i.custom))
}
/// #1077: Increase Decimal widened the format but not the column, so the number turned into ####.
#[test]
fn increase_decimal_widens_a_column_nobody_sized() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "3.14159265"})).unwrap();
let (default, _) = col(&s, 0);
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
let (w, custom) = col(&s, 0);
let text = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["text"].as_str().unwrap().to_string();
assert_eq!(text, "3.141592650");
assert!(w > default, "the column widens for {text}: {w} vs {default}");
assert!(w >= approx_text_width(&text, gridcraft_model::DEFAULT_FONT_SIZE, false), "and fits it");
assert!(!custom, "it isn't a width set by hand, so it can widen again");
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > w, "one more decimal, a little wider again");
let wide = col(&s, 0).0;
s.execute("home.decreaseDecimal", json!({"range": "A1"})).unwrap();
assert_eq!(col(&s, 0).0, wide, "fewer decimals don't narrow it");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(col(&s, 0).0, w, "Undo takes back the format and the width in one step");
}
#[test]
fn number_formats_keep_a_width_set_by_hand_and_general_numbers_round_instead() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891, 1234567.891, 1234567.891]]})).unwrap();
s.execute("home.columnWidth", json!({"cols": "A:A", "width": 40})).unwrap();
assert_eq!(col(&s, 0), (40.0, true), "Column Width (and dragging the border) is a width set by hand");
s.execute("home.hideColumns", json!({"cols": "D:D"})).unwrap();
for a in ["A1", "B1", "D1"] {
s.execute("home.comma", json!({"range": a})).unwrap();
}
s.execute("home.numberFormat", json!({"range": "C1", "format": "General"})).unwrap();
let (default, _) = col(&s, 4);
assert_eq!(col(&s, 0), (40.0, true), "a width set by hand stays: the cell shows ####, as in Excel");
assert!(col(&s, 1).0 > default, "B widens for 1,234,567.89");
assert_eq!(col(&s, 2).0, default, "General rounds to fit instead");
assert_eq!(col(&s, 3).0, 0.0, "a hidden column stays hidden");
// AutoFit makes a width set by hand automatic again; Wrap Text doesn't stop the widening.
s.execute("home.autofitColumnWidth", json!({"cols": "A:A"})).unwrap();
assert!(!col(&s, 0).1);
s.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
let fitted = col(&s, 0).0;
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
s.execute("home.increaseDecimal", json!({"range": "A1"})).unwrap();
assert!(col(&s, 0).0 > fitted, "after AutoFit, with Wrap Text, A widens again");
}
fn book() -> (crate::Session, f32) {
let mut s = crate::Session::new();
s.new_workbook();
let (default, _) = col(&s, 0);
(s, default)
}
/// Whole columns as tall as the sheet with two numbers: the cells are looked at, not the area.
#[test]
fn a_sparse_target_widens_for_the_numbers_it_holds() {
let (mut s, default) = book();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "E1000000", "input": "1234567.891"})).unwrap();
s.execute("home.comma", json!({"range": "A:E"})).unwrap();
assert!(col(&s, 4).0 > default, "E widens for 1,234,567.89 a million rows down");
}
/// A spilled number counts as the grid shows it: G1's formula spills 1,234,567.891 into H1.
#[test]
fn a_spilled_number_widens_its_column() {
let (mut s, default) = book();
s.execute("cell.set", json!({"cell": "G1", "input": "=SEQUENCE(1,2,1,1234566.891)"})).unwrap();
s.execute("home.numberFormat", json!({"range": "H1", "code": "#,##0.000"})).unwrap();
assert!(col(&s, 7).0 > default, "H widens for the value it shows");
}
/// A merged area keeps its columns; the cell beside it widens.
#[test]
fn a_merged_area_keeps_its_columns() {
let (mut s, default) = book();
s.execute("range.setValues", json!({"range": "J1", "values": [[1234567.891, null, 1234567.891]]})).unwrap();
s.execute("home.mergeCells", json!({"range": "J1:K1"})).unwrap();
s.execute("home.comma", json!({"range": "J1:L1"})).unwrap();
assert_eq!((col(&s, 9).0, col(&s, 10).0), (default, default), "the merged J1:K1 doesn't widen J or K");
assert!(col(&s, 11).0 > default, "L does");
}
#[test]
fn format_cells_widens_for_a_number_format_only() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[1234567.891, 1234567.891]]})).unwrap();
let (default, _) = col(&s, 0);
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"bold": true}}})).unwrap();
assert_eq!(col(&s, 1).0, default, "no number format, no widening");
s.execute("home.formatCells", json!({"range": "A1", "style": {"numFmt": "#,##0.000000"}})).unwrap();
assert!(col(&s, 0).0 > default, "A widens for 1,234,567.891000, as Excel's Format Cells does");
assert!(!col(&s, 0).1);
}
#[test]
fn format_cells_takes_the_documented_keys() {
let mut s = crate::Session::new();
@@ -1072,20 +870,6 @@ 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() {
+5 -12
View File
@@ -107,7 +107,6 @@ pub(super) fn col_width(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w as f32);
e.hidden = w == 0.0;
e.custom = true;
}
}
Ok(Json::Null)
@@ -188,15 +187,14 @@ fn arabic_em(c: char) -> Option<f32> {
/// Distinct texts AutoFit measures exactly; past this many, `Session::text_width` is asked for a
/// quick measure so a huge column doesn't lay out every value.
pub(super) const EXACT_TEXT_WIDTHS: usize = 2_000;
const EXACT_TEXT_WIDTHS: usize = 2_000;
pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let (si, lines) = line_targets(s, p, false)?;
let measure = s.text_width.clone();
edit(s, |cx| {
let Some(sh) = cx.wb.sheet(si) else { return Ok(Json::Null) };
// 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 measured: std::collections::HashMap<StyleId, 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).
@@ -230,26 +228,22 @@ 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, font.bold)).or_default();
let known = measured.entry(id).or_default();
match known.get(line) {
Some(w) => *w,
None => {
let w = m(line, font, distinct < EXACT_TEXT_WIDTHS);
let w = m(line, &st.font, distinct < EXACT_TEXT_WIDTHS);
known.insert(line.to_owned(), w);
distinct += 1;
w
}
}
}
None => approx_text_width(line, font.size, font.bold),
None => approx_text_width(line, st.font.size, st.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);
@@ -264,7 +258,6 @@ pub(super) fn autofit_cols(s: &mut Session, p: &Json) -> Result<Json> {
let e = sh.cols.entry(c).or_default();
e.size = Some(w.ceil());
e.hidden = false;
e.custom = false; // AutoFit makes a width set by hand automatic again (Excel).
}
Ok(Json::Null)
})
+3 -301
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|stacked100Markers, 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, title?, at?: \"H2\", width?, height?}",
has_doc,
insert_chart
),
@@ -217,7 +217,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Conditional Formatting",
["Home", "Styles"],
None,
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], stops?: [{type: min|max|num|percent|percentile|formula, value?, color}], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
"{range?, rule: {type: cellIs|expression|containsText|beginsWith|endsWith|blanks|noBlanks|errors|noErrors|duplicate|unique|top10|aboveAverage|timePeriod|colorScale|dataBar|iconSet, operator?, value?, value2?, formula?, text?, rank?, bottom?, percent?, below?, period?, colors?: [..], color?, set?, style?: {font?: {bold?, italic?, color?}, fill?: \"#FFC7CE\" | {pattern?, fg?, bg?}, borders?, num_fmt?} (colours \"#RRGGBB\") | preset?: lightRedFill|redText|yellowFill|greenFill|redBorder|lightRedFillDarkRedText…}; a text `value` is matched as text, or kept when already a quoted literal}",
has_doc,
add_cf
),
@@ -227,7 +227,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Manage Rules…",
["Home", "Styles", "Conditional Formatting"],
None,
"{delete?: index, moveUp?: index, moveDown?: index, edit?: index, rule?: {...} (with edit)}",
"{delete?: index, moveUp?: index, moveDown?: index}",
has_doc,
manage_cf
),
@@ -496,302 +496,4 @@ mod tests {
s.execute("table.rename", json!({"table": "Table1", "name": "Table1"})).unwrap();
s.execute("table.rename", json!({"table": "Table1", "name": "Rates"})).unwrap();
}
#[test]
fn colour_scale_thresholds_are_clamped_to_the_percent_range() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "percent", "value": -5, "color": "#112233"},
{"type": "percentile", "value": 150, "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(
stops,
vec![
(CfValueKind::Percent(0.0), Color::Rgb(0x112233)),
(CfValueKind::Percentile(100.0), Color::Rgb(0x445566)),
(CfValueKind::Max, Color::Rgb(0x778899)),
]
);
}
#[test]
fn colour_scale_stops_reject_empty_formulas_and_unknown_types() {
let mut s = Session::new();
s.new_workbook();
let with_stops = |stops: Json| json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}});
let err = s
.execute(
"home.conditionalFormat",
with_stops(json!([
{"type": "min", "color": "#112233"},
{"type": "formula", "value": " ", "color": "#445566"},
{"type": "max", "color": "#778899"},
])),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
assert!(err.contains("formula"), "{err}");
let err = s
.execute(
"home.conditionalFormat",
with_stops(json!([
{"type": "min", "color": "#112233"},
{"type": "median", "value": 50, "color": "#445566"},
{"type": "max", "color": "#778899"},
])),
)
.unwrap_err()
.to_string();
assert!(err.contains("unknown stop type `median`"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
}
#[test]
fn colour_scale_rejects_a_stops_value_that_is_not_an_array() {
let mut s = Session::new();
s.new_workbook();
// `stops` present but misshapen used to fall back to the default scale instead of erroring.
for stops in [json!({}), json!(null), json!("min")] {
let err = s
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": stops}}))
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
assert!(err.contains("`stops` must be an array"), "{err}");
}
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "an invalid `stops` creates no rule");
}
#[test]
fn colour_scale_formulas_are_stored_verbatim() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "formula", "value": "=$Z$1", "color": "#445566"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(stops[1].0, CfValueKind::Formula("=$Z$1".into()));
}
#[test]
fn manage_rules_rejects_a_non_index_edit() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
for bad in [json!("0"), json!(1.5), json!(-1), json!(true)] {
let err = s
.execute("home.manageRules", json!({"edit": bad, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
.unwrap_err()
.to_string();
assert!(err.contains("`edit` must be a rule index"), "{err}");
}
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1));
}
#[test]
fn manage_rules_rejects_an_edit_past_the_last_rule() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
let err = s
.execute("home.manageRules", json!({"edit": 1, "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}}))
.unwrap_err()
.to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(err.contains("index 1"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(1), "the failed edit leaves the rule alone");
}
#[test]
fn manage_rules_rejects_an_edit_index_that_does_not_fit_a_usize() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
// On a 32-bit target this used to cast to zero and replace the rule at index 0.
let err =
s.execute("home.manageRules", json!({"edit": 4294967296u64, "rule": {"type": "expression", "formula": "A1>3"}})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(err.contains("index 4294967296"), "{err}");
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
assert_eq!(formula, "A1>2", "the failed edit leaves the rule alone");
}
#[test]
fn manage_rules_names_itself_in_a_style_error() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "colorScale", "colors": ["#112233", "#778899"]}})).unwrap();
// A style shared by both commands must name the one that was called.
let rule = json!({"type": "cellIs", "operator": "greater", "value": 1, "style": {"nope": 1}});
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": rule.clone()})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
assert!(!err.contains("home.conditionalFormat"), "{err}");
let err = s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": rule})).unwrap_err().to_string();
assert!(err.contains("home.conditionalFormat"), "{err}");
}
#[test]
fn manage_rules_names_itself_in_a_stop_count_error() {
let mut s = Session::new();
s.new_workbook();
let err = s
.execute(
"home.manageRules",
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
]}}),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.manageRules"), "{err}");
}
#[test]
fn a_formula_rule_needs_a_formula_that_parses() {
let mut s = Session::new();
s.new_workbook();
// An empty box used to create a rule that never applies.
let err =
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": ""}})).unwrap_err().to_string();
assert!(err.contains("formula is empty"), "{err}");
// `=C1>` used to be written as `<formula>C1&gt;</formula>`, which Excel refuses to open.
let err = s
.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "=C1>"}}))
.unwrap_err()
.to_string();
assert!(err.contains("invalid"), "{err}");
assert!(err.contains("does not parse"), "{err}");
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0), "a refused rule is not stored");
}
#[test]
fn an_invalid_formula_on_edit_leaves_the_rule_alone() {
let mut s = Session::new();
s.new_workbook();
s.execute("home.conditionalFormat", json!({"range": "A1:A3", "rule": {"type": "expression", "formula": "A1>2"}})).unwrap();
let err = s.execute("home.manageRules", json!({"edit": 0, "rule": {"type": "expression", "formula": "=C1>"}})).unwrap_err().to_string();
assert!(err.contains("home.manageRules"), "{err}");
let rule: CfRule = serde_json::from_value(s.execute("home.manageRules", json!({})).unwrap()["rules"][0]["rule"].clone()).unwrap();
let CfRule::Expression { formula, .. } = rule else { panic!("expected a formula rule, got {rule:?}") };
assert_eq!(formula, "A1>2");
}
#[test]
fn a_given_stop_value_must_be_a_number() {
let mut s = Session::new();
s.new_workbook();
for ty in ["num", "percent", "percentile"] {
let err = s
.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": ty, "value": "5", "color": "#112233"},
{"type": "max", "color": "#778899"},
]}}),
)
.unwrap_err()
.to_string();
assert!(err.contains("home.conditionalFormat"), "{ty}: {err}");
assert!(err.contains(&format!("`{ty}` stop's `value` must be a number")), "{ty}: {err}");
}
// A refused scale stores nothing.
let rules = s.execute("home.manageRules", json!({})).unwrap();
assert_eq!(rules["rules"].as_array().map(Vec::len), Some(0));
}
#[test]
fn an_omitted_stop_value_is_zero() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "num", "color": "#112233"},
{"type": "percent", "color": "#445566"},
{"type": "percentile", "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let CfRule::ColorScale { stops } = rule else { panic!("expected a colour scale") };
assert_eq!(
stops,
vec![
(CfValueKind::Number(0.0), Color::Rgb(0x112233)),
(CfValueKind::Percent(0.0), Color::Rgb(0x445566)),
(CfValueKind::Percentile(0.0), Color::Rgb(0x778899)),
]
);
}
#[test]
fn colour_scale_stops_keep_their_thresholds_and_can_be_edited() {
let mut s = Session::new();
s.new_workbook();
s.execute(
"home.conditionalFormat",
json!({"range": "A1:A3", "rule": {"type": "colorScale", "stops": [
{"type": "min", "color": "#112233"},
{"type": "num", "value": 5, "color": "#445566"},
{"type": "percentile", "value": 90, "color": "#778899"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let stops = match rule {
CfRule::ColorScale { stops } => stops,
_ => Vec::new(),
};
assert_eq!(
stops,
vec![
(CfValueKind::Min, Color::Rgb(0x112233)),
(CfValueKind::Number(5.0), Color::Rgb(0x445566)),
(CfValueKind::Percentile(90.0), Color::Rgb(0x778899)),
]
);
s.execute(
"home.manageRules",
json!({"edit": 0, "rule": {"type": "colorScale", "stops": [
{"type": "formula", "value": "$B$1", "color": "#ABCABC"},
{"type": "max", "color": "#DEFDEF"},
]}}),
)
.unwrap();
let list = s.execute("home.manageRules", json!({})).unwrap();
let rule: CfRule = serde_json::from_value(list["rules"][0]["rule"].clone()).unwrap();
let stops = match rule {
CfRule::ColorScale { stops } => stops,
_ => Vec::new(),
};
assert_eq!(stops, vec![(CfValueKind::Formula("$B$1".into()), Color::Rgb(0xABCABC)), (CfValueKind::Max, Color::Rgb(0xDEFDEF))]);
}
}
-6
View File
@@ -46,8 +46,6 @@ 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,
@@ -108,8 +106,6 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
});
}
} else {
@@ -126,8 +122,6 @@ pub fn series_from_range(sh: &Sheet, r: RangeRef, by_rows: bool) -> Vec<Series>
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
});
}
}
+82 -144
View File
@@ -46,9 +46,9 @@ fn is_string_literal(v: &str) -> bool {
/// written as `format_range` takes it (`"#RRGGBB"`, `{theme, tint}`, `"auto"`) and `fill` may be a
/// colour alone (a solid fill) or `"none"` (no fill). An unknown key is an error rather than
/// dropped: dropped, it left a rule with an empty format that matches and shows nothing.
fn cf_style_json(st: &Json, cmd: &str) -> Result<Json> {
fn cf_style_json(st: &Json) -> Result<Json> {
const KEYS: [&str; 6] = ["font", "fill", "borders", "align", "num_fmt", "protection"];
let err = |m: String| bad(cmd, m);
let err = |m: String| bad("home.conditionalFormat", m);
let Some(obj) = st.as_object() else { return Err(err("`style` must be an object, e.g. {\"fill\": \"#FFC7CE\"}".into())) };
let mut st = obj.clone();
if let Some(k) = st.keys().find(|k| !KEYS.contains(&k.as_str())) {
@@ -103,40 +103,36 @@ fn cf_style_json(st: &Json, cmd: &str) -> Result<Json> {
fn check_cf_formula(cmd: &str, what: &str, formula: &str) -> Result<()> {
// Strip exactly one leading '=', the way the XLSX writer does: a value like '===A1'
// only parses after several strips and would still be saved unparseable. (#1999 review)
let parsed = formula.strip_prefix('=').unwrap_or(formula);
// A rule with no formula never applies; the dialog also keeps OK disabled for it.
if parsed.trim().is_empty() {
return Err(bad(cmd, format!("the {what} formula is empty")));
}
if gridcraft_formula::parse(parsed).is_err() {
if gridcraft_formula::parse(formula.strip_prefix('=').unwrap_or(formula)).is_err() {
return Err(bad(cmd, format!("invalid {what} formula `{formula}` — it does not parse; Excel would reject the saved file")));
}
Ok(())
}
fn check_cf_value(cmd: &str, what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
fn check_cf_value(what: &str, v: &gridcraft_model::features::CfValueKind) -> Result<()> {
if let gridcraft_model::features::CfValueKind::Formula(f) = v {
check_cf_formula(cmd, what, f)?;
check_cf_formula("home.conditionalFormat", what, f)?;
}
Ok(())
}
fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> {
fn check_cf_rule(rule: &CfRule) -> Result<()> {
const CMD: &str = "home.conditionalFormat";
match rule {
CfRule::CellIs { a, b, .. } => {
check_cf_formula(cmd, "comparison value", a)?;
check_cf_formula(CMD, "comparison value", a)?;
if let Some(b) = b {
check_cf_formula(cmd, "second comparison value", b)?;
check_cf_formula(CMD, "second comparison value", b)?;
}
}
CfRule::Expression { formula, .. } => check_cf_formula(cmd, "rule", formula)?,
CfRule::Expression { formula, .. } => check_cf_formula(CMD, "rule", formula)?,
CfRule::DataBar { min, max, .. } => {
check_cf_value(cmd, "data bar minimum", min)?;
check_cf_value(cmd, "data bar maximum", max)?;
check_cf_value("data bar minimum", min)?;
check_cf_value("data bar maximum", max)?;
}
CfRule::ColorScale { stops } => {
for (kind, _) in stops {
check_cf_value(cmd, "color scale threshold", kind)?;
check_cf_value("color scale threshold", kind)?;
}
}
_ => {}
@@ -144,53 +140,41 @@ fn check_cf_rule(cmd: &str, rule: &CfRule) -> Result<()> {
Ok(())
}
fn cf_style(rule: &Json, cmd: &str) -> Result<Style> {
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let sheet = target_sheet(s, p)?;
let Some(rule) = p.get("rule") else {
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
return ok();
};
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
match rule.get("style") {
let style = Box::new(match rule.get("style") {
Some(st) if !st.is_null() => {
let st = cf_style_json(st, cmd)?;
let st = cf_style_json(st)?;
let base = serde_json::to_value(Style::default()).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad(cmd, e.to_string()))?)
serde_json::from_value(crate::cmd::format::merge_json(base, &st)).map_err(|e| bad("home.conditionalFormat", e.to_string()))?
}
_ => Ok(preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText"))),
}
}
fn cf_value_kind(v: Option<&Json>, default: CfValueKind, cmd: &str) -> Result<CfValueKind> {
let Some(Json::Object(o)) = v else { return Ok(default) };
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
// A value that is given must be a number: a string used to be read as 0 without a word.
// Only an omitted `value` defaults to zero.
let number = || -> Result<f64> {
match o.get("value") {
None => Ok(0.0),
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("the `{t}` stop's `value` must be a number, not {v}"))),
_ => preset_style(g("preset").as_deref().unwrap_or("lightRedFillDarkRedText")),
});
let kind = g("type").unwrap_or_else(|| "cellIs".into());
let value_kind = |v: Option<&Json>, default: CfValueKind| -> CfValueKind {
match v {
Some(Json::Object(o)) => {
let t = o.get("type").and_then(Json::as_str).unwrap_or("num");
let val = o.get("value").and_then(Json::as_f64).unwrap_or(0.0);
match t {
"min" => CfValueKind::Min,
"max" => CfValueKind::Max,
"percent" => CfValueKind::Percent(val),
"percentile" => CfValueKind::Percentile(val),
"formula" => CfValueKind::Formula(o.get("value").and_then(Json::as_str).unwrap_or("").into()),
_ => CfValueKind::Number(val),
}
}
_ => default,
}
};
Ok(match t {
"min" => CfValueKind::Min,
"max" => CfValueKind::Max,
// The dialog clamps these to 0-100; engine callers get the same range.
"percent" => CfValueKind::Percent(number()?.clamp(0.0, 100.0)),
"percentile" => CfValueKind::Percentile(number()?.clamp(0.0, 100.0)),
"formula" => {
let f = o.get("value").and_then(Json::as_str).unwrap_or("");
if f.trim().is_empty() {
return Err(bad(cmd, "a formula stop needs a formula"));
}
// Stored exactly: the evaluator takes the formula as written.
CfValueKind::Formula(f.into())
}
"num" => CfValueKind::Number(number()?),
other => return Err(bad(cmd, format!("unknown stop type `{other}`"))),
})
}
fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
let g = |k: &str| rule.get(k).and_then(Json::as_str).map(str::to_string);
let style = Box::new(cf_style(rule, cmd)?);
let kind = g("type").unwrap_or_else(|| "cellIs".into());
match kind.as_str() {
let rule = match kind.as_str() {
"cellIs" => {
// Excel's file and VBA names (`lessThan`, …) are accepted too.
let op = match g("operator").as_deref().unwrap_or("greater") {
@@ -202,7 +186,7 @@ fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
"greaterOrEqual" | "greaterThanOrEqual" => CfOperator::GreaterOrEqual,
"lessOrEqual" | "lessThanOrEqual" => CfOperator::LessOrEqual,
"greater" | "greaterThan" => CfOperator::Greater,
other => return Err(bad(cmd, format!("unknown operator `{other}`"))),
other => return Err(bad("home.conditionalFormat", format!("unknown operator `{other}`"))),
};
let a = rule.get("value").map(crate::cmd::edit::json_to_input).unwrap_or_default();
let b = rule.get("value2").map(crate::cmd::edit::json_to_input);
@@ -217,85 +201,59 @@ fn cf_rule(rule: &Json, cmd: &str) -> Result<CfRule> {
format!("\"{}\"", v.replace('"', "\"\""))
}
};
Ok(CfRule::CellIs { op, a: quote(a), b: b.map(quote), style })
CfRule::CellIs { op, a: quote(a), b: b.map(quote), style }
}
"expression" => Ok(CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style }),
"containsText" => Ok(CfRule::ContainsText { text: g("text").unwrap_or_default(), style }),
"notContainsText" => Ok(CfRule::NotContainsText { text: g("text").unwrap_or_default(), style }),
"beginsWith" => Ok(CfRule::BeginsWith { text: g("text").unwrap_or_default(), style }),
"endsWith" => Ok(CfRule::EndsWith { text: g("text").unwrap_or_default(), style }),
"blanks" => Ok(CfRule::Blanks { style }),
"noBlanks" => Ok(CfRule::NoBlanks { style }),
"errors" => Ok(CfRule::Errors { style }),
"noErrors" => Ok(CfRule::NoErrors { style }),
"duplicate" => Ok(CfRule::Duplicate { style }),
"unique" => Ok(CfRule::Unique { style }),
"top10" => Ok(CfRule::Top10 {
"expression" => CfRule::Expression { formula: g("formula").unwrap_or_default().trim_start_matches('=').to_string(), style },
"containsText" => CfRule::ContainsText { text: g("text").unwrap_or_default(), style },
"notContainsText" => CfRule::NotContainsText { text: g("text").unwrap_or_default(), style },
"beginsWith" => CfRule::BeginsWith { text: g("text").unwrap_or_default(), style },
"endsWith" => CfRule::EndsWith { text: g("text").unwrap_or_default(), style },
"blanks" => CfRule::Blanks { style },
"noBlanks" => CfRule::NoBlanks { style },
"errors" => CfRule::Errors { style },
"noErrors" => CfRule::NoErrors { style },
"duplicate" => CfRule::Duplicate { style },
"unique" => CfRule::Unique { style },
"top10" => CfRule::Top10 {
bottom: rule.get("bottom").and_then(Json::as_bool).unwrap_or(false),
percent: rule.get("percent").and_then(Json::as_bool).unwrap_or(false),
rank: rule.get("rank").and_then(Json::as_u64).unwrap_or(10) as u32,
style,
}),
"aboveAverage" => {
Ok(CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style })
}
"timePeriod" => Ok(CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style }),
},
"aboveAverage" => CfRule::AboveAverage { below: rule.get("below").and_then(Json::as_bool).unwrap_or(false), equal: false, std_dev: 0, style },
"timePeriod" => CfRule::TimePeriod { period: g("period").unwrap_or_else(|| "today".into()), style },
"colorScale" => {
let stops = if let Some(stops) = rule.get("stops") {
// A present but misshapen `stops` is a mistake, not a request for `colors`.
let list = stops.as_array().ok_or_else(|| bad(cmd, "`stops` must be an array"))?;
let mut out = Vec::with_capacity(list.len().min(3));
for stop in list {
let color = crate::cmd::format::color_param(stop.get("color")).ok_or_else(|| bad(cmd, "a colour-scale stop needs a colour"))?;
out.push((cf_value_kind(Some(stop), CfValueKind::Min, cmd)?, color));
}
if !(2..=3).contains(&out.len()) {
return Err(bad(cmd, "a colour scale needs two or three stops"));
}
out
} else {
let cols: Vec<Color> = rule
.get("colors")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
match cols.len() {
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
_ => vec![
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
],
}
let cols: Vec<Color> = rule
.get("colors")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(|c| crate::cmd::format::color_param(Some(c))).collect())
.unwrap_or_else(|| vec![Color::rgb(0xF8, 0x69, 0x6B), Color::rgb(0xFF, 0xEB, 0x84), Color::rgb(0x63, 0xBE, 0x7B)]);
let stops = match cols.len() {
2 => vec![(CfValueKind::Min, cols[0]), (CfValueKind::Max, cols[1])],
_ => vec![
(CfValueKind::Min, cols.first().copied().unwrap_or_default()),
(CfValueKind::Percentile(50.0), cols.get(1).copied().unwrap_or_default()),
(CfValueKind::Max, cols.get(2).copied().unwrap_or_default()),
],
};
Ok(CfRule::ColorScale { stops })
CfRule::ColorScale { stops }
}
"dataBar" => Ok(CfRule::DataBar {
min: cf_value_kind(rule.get("min"), CfValueKind::Min, cmd)?,
max: cf_value_kind(rule.get("max"), CfValueKind::Max, cmd)?,
"dataBar" => CfRule::DataBar {
min: value_kind(rule.get("min"), CfValueKind::Min),
max: value_kind(rule.get("max"), CfValueKind::Max),
color: crate::cmd::format::color_param(rule.get("color")).unwrap_or(Color::rgb(0x63, 0x8E, 0xC6)),
gradient: rule.get("gradient").and_then(Json::as_bool).unwrap_or(true),
show_value: true,
}),
"iconSet" => Ok(CfRule::IconSet {
},
"iconSet" => CfRule::IconSet {
set: g("set").unwrap_or_else(|| "3TrafficLights1".into()),
thresholds: vec![],
reverse: rule.get("reverse").and_then(Json::as_bool).unwrap_or(false),
show_value: true,
}),
other => Err(bad(cmd, format!("unknown rule type `{other}`"))),
}
}
pub(super) fn add_cf(s: &mut Session, p: &Json) -> Result<Json> {
let ranges = target_ranges(s, p)?;
let sheet = target_sheet(s, p)?;
let Some(rule) = p.get("rule") else {
s.ui_requests.push(crate::UiRequest::Dialog("newFormattingRule".into(), json!({})));
return ok();
},
other => return Err(bad("home.conditionalFormat", format!("unknown rule type `{other}`"))),
};
let rule = cf_rule(rule, "home.conditionalFormat")?;
check_cf_rule("home.conditionalFormat", &rule)?;
check_cf_rule(&rule)?;
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
let priority = sh.cond_formats.iter().map(|c| c.priority).max().unwrap_or(0) + 1;
@@ -337,33 +295,17 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
let sheet = target_sheet(s, p)?;
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() && p.get("edit").is_none() {
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
let list: Vec<Json> = s
.doc()?
.wb
.sheet(sheet)
.map(|sh| {
sh.cond_formats
.iter()
.map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule, "priority": c.priority}))
.collect()
sh.cond_formats.iter().map(|c| json!({"ranges": c.ranges.iter().map(|r| r.a1()).collect::<Vec<_>>(), "rule": c.rule})).collect()
})
.unwrap_or_default();
return Ok(json!({"rules": list}));
}
let edited = match (p.get("edit"), p.get("rule")) {
(None, _) => None,
(Some(_), None) => return Err(bad("home.manageRules", "missing `rule` for an edit")),
(Some(e), Some(rule)) => {
let i = e.as_u64().ok_or_else(|| bad("home.manageRules", "`edit` must be a rule index"))?;
// A number too large for `usize` on this target names no rule: casting it would
// wrap to a real index and replace that rule instead of reporting out of range.
let i = usize::try_from(i).map_err(|_| bad("home.manageRules", format!("no conditional format at index {i}")))?;
let rule = cf_rule(rule, "home.manageRules")?;
check_cf_rule("home.manageRules", &rule)?;
Some((i, rule))
}
};
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
// The count is taken again after each step: a delete shortens the list.
@@ -372,10 +314,6 @@ pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
{
sh.cond_formats.remove(i);
}
if let Some((i, rule)) = edited {
let cf = sh.cond_formats.get_mut(i).ok_or_else(|| bad("home.manageRules", format!("no conditional format at index {i}")))?;
cf.rule = rule;
}
if let Some(i) = u32_param(p, "moveUp").map(|v| v as usize)
&& i > 0
&& i < sh.cond_formats.len()
+2 -2
View File
@@ -56,10 +56,10 @@ pub(super) fn open_link(s: &mut Session, p: &Json) -> Result<Json> {
None => {
let sheet = target_sheet(s, p)?;
let at = cell_param_on(s, p, "cell", sheet)?.unwrap_or(s.doc()?.selection.active);
let Some(h) = crate::links::cell_link(&s.doc()?.wb, sheet, at) else {
let Some(h) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.hyperlinks.get(&at)) else {
return Err(EngineError::Other("There's no hyperlink in this cell.".into()));
};
h.target
h.target.clone()
}
};
match crate::links::classify(&target) {
-7
View File
@@ -74,13 +74,6 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
RangeRef::new(r.start, CellRef::new((r.end.row + 1).min(MAX_ROWS - 1), r.end.col))
};
let sh = cx.sheet_mut(sheet)?;
// As in Excel, the table unmerges the merged cells it covers: a table can't hold them.
let merged = sh.merges.len();
sh.merges.retain(|m| !m.intersects(&r));
if sh.merges.len() != merged {
cx.structural = true;
}
let sh = cx.sheet_mut(sheet)?;
let mut names: Vec<String> = Vec::new();
// Lower-case names taken, and the next suffix for each header, so that thousands of equal
// headers don't take cubic time.
+1 -1
View File
@@ -136,7 +136,7 @@ fn cell_get(s: &mut Session, p: &Json) -> Result<Json> {
"style": style,
"merge": sh.merge_at(c).map(|m| m.a1()),
"comment": sh.comments.get(&c),
"hyperlink": crate::links::cell_link(&d.wb, sheet, c),
"hyperlink": sh.hyperlinks.get(&c),
"python": cell.and_then(|x| x.py.as_deref()).map(|py| json!({
"code": py.code,
"output": if py.object { "object" } else { "value" },
+1 -9
View File
@@ -118,15 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
value_settings
),
cmd!("pivot.filter", "Filter Items", [], None, "{pivot?, field, selected: [\"East\", ..] | null (all), replace?}", has_doc, filter),
cmd!(
"pivot.sort",
"Sort Field",
[],
None,
"{pivot?, field, order: asc|desc|none, by?: \"Sum of Sales\" (sort by a value field), replace?}",
has_doc,
sort
),
cmd!("pivot.sort", "Sort Field", [], None, "{pivot?, field, order: asc|desc|none, replace?}", has_doc, sort),
cmd!(
"pivot.group",
"Group Field",
+4 -16
View File
@@ -1,8 +1,8 @@
use super::fields::{AreaPlacement, add_to_area, in_axes};
use super::params::{func_name, func_param, group_name, group_param, layout_name, show_as_name, sort_name};
use super::{
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotField, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook,
bad, bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook, bad,
bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with,
};
// ---------------------------------------------------------------- insert
@@ -327,18 +327,6 @@ pub(super) fn summarize_table(s: &mut Session, p: &Json) -> Result<Json> {
// ---------------------------------------------------------------- queries
fn field_json(f: &PivotField) -> Json {
json!({
"field": f.source_col,
"caption": f.caption,
"sort": sort_name(f.sort),
"sortBy": f.sort_by,
"group": group_name(f.date_group),
"numberFormat": f.number_format,
"collapsed": f.collapsed_items,
})
}
pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
json!({
"id": pt.id,
@@ -347,8 +335,8 @@ pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json {
"anchor": pt.anchor.a1(),
"range": pt.last_range.map(|r| r.a1()),
"source": pt.source,
"rows": pt.rows.iter().map(field_json).collect::<Vec<_>>(),
"columns": pt.columns.iter().map(field_json).collect::<Vec<_>>(),
"rows": pt.rows.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::<Vec<_>>(),
"columns": pt.columns.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::<Vec<_>>(),
"values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": func_name(v.func), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::<Vec<_>>(),
"filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::<Vec<_>>(),
"layout": layout_name(pt.layout),
-6
View File
@@ -551,12 +551,6 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result<Json> {
None => {}
}
let name = v.name.clone();
// Fields sorted by this value field follow its new caption.
for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) {
if f.sort_by.as_deref().is_some_and(|b| b.eq_ignore_ascii_case(&cur.name)) {
f.sort_by = Some(name.clone());
}
}
if let Some(slot) = pt.values.get_mut(i) {
*slot = v;
}
+1 -21
View File
@@ -71,24 +71,8 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result<Json> {
"none" | "manual" | "source" => PivotSort::None,
o => return Err(bad(C, format!("unknown order `{o}` (asc|desc|none)"))),
};
// Sort by a value field (its caption or source field) instead of by the item labels.
let by = str_param(p, "by").map(str::to_string);
update(s, p, |pt, _, _| {
let by = match by {
Some(b) => Some(
pt.values
.iter()
.find(|v| v.name.eq_ignore_ascii_case(&b))
.or_else(|| pt.values.iter().find(|v| v.source_col.eq_ignore_ascii_case(&b)))
.map(|v| v.name.clone())
.ok_or_else(|| bad(C, format!("`{b}` isn't in the values area")))?,
),
None => None,
};
let f = axis_field(C, pt, &field)?;
f.sort = order;
f.sort_by = by;
f.sort_scope.clear();
axis_field(C, pt, &field)?.sort = order;
Ok(json!({}))
})
}
@@ -180,11 +164,7 @@ pub(super) fn layout(s: &mut Session, p: &Json) -> Result<Json> {
}
}
if let Some((on, top)) = subtotals {
// Design › Subtotals applies to every field, replacing per-field settings.
pt.subtotals = on;
for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) {
f.subtotal = None;
}
if let Some(t) = top {
pt.subtotals_top = t;
}
+4 -508
View File
@@ -1,5 +1,4 @@
use gridcraft_core::{CellError, CellRef, Value};
use gridcraft_model::{PivotLayout, PivotSort};
use serde_json::{Value as Json, json};
use crate::Session;
@@ -318,10 +317,6 @@ fn assert_values_on_rows_tabular(s: &mut Session) {
assert_eq!(text(s, "A3"), "Region");
assert_eq!(text(s, "B3"), "Values");
assert_eq!(text(s, "C3"), "Total");
// The Values field's caption heads its column, as in Excel's saved reports.
edit_pt(s, |p| p.data_caption = Some("Data".into()));
assert_eq!(text(s, "B3"), "Data");
edit_pt(s, |p| p.data_caption = None);
}
fn assert_values_on_rows_position(s: &mut Session) {
@@ -506,231 +501,6 @@ fn refresh_after_source_edits() {
s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap();
}
/// Edits the active sheet's last PivotTable in the model (settings only a file sets) and
/// refreshes it.
fn edit_pt(s: &mut Session, f: impl FnOnce(&mut gridcraft_model::PivotTable)) {
let d = s.doc_mut().unwrap();
let wb = std::sync::Arc::make_mut(&mut d.wb);
let si = wb.active_sheet();
f(wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap());
s.execute("pivot.refresh", json!({})).unwrap();
}
#[test]
fn sort_by_value_within_each_parent() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap();
// East 415, West 285, North 135.
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Sum of Sales"));
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["East", "West", "North"]);
s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Sales"})).unwrap();
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["North", "West", "East"]);
assert!(s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Nope"})).is_err());
// The sort follows a renamed value field; sorting without `by` sorts by label again.
s.execute("pivot.valueSettings", json!({"field": "Sum of Sales", "name": "Revenue"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Revenue"));
assert_eq!(text(&s, "A4"), "North");
s.execute("pivot.sort", json!({"field": "Region", "order": "desc"})).unwrap();
assert_eq!(pt(&s).rows[0].sort_by, None);
assert_eq!(text(&s, "A4"), "West");
// Inner items sort within their parent; subtotals stay with their group.
s.execute("pivot.addField", json!({"field": "Product", "area": "rows"})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Revenue"})).unwrap();
s.execute("pivot.sort", json!({"field": "Product", "order": "desc", "by": "Revenue"})).unwrap();
// East: Pears 195, Apples 160, Plums 60.
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "B5"), text(&s, "B6"), text(&s, "A7")], ["East", "Pears", "Apples", "Plums", "East Total"]);
assert_eq!(val(&s, "C4"), Value::Number(195.0));
// West: Apples 170, Plums 70, Pears 45.
assert_eq!([text(&s, "A8"), text(&s, "B8"), text(&s, "B9"), text(&s, "B10")], ["West", "Apples", "Plums", "Pears"]);
// Columns sort by their row totals.
s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap();
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4")], ["East", "West", "North"]);
}
#[test]
fn captions_renamed_items_and_manual_order() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
p.row_header_caption = Some("Area".into());
p.col_header_caption = Some("Fruit".into());
p.grand_total_caption = Some("Everything".into());
p.rows[0].item_captions = vec![("East".into(), "Eastern".into())];
p.columns[0].sort = PivotSort::None;
p.columns[0].item_order = vec!["Plums".into(), "Pears".into()];
});
assert_eq!(text(&s, "A4"), "Area");
assert_eq!(text(&s, "B3"), "Fruit");
// Listed items first, the rest after.
assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4"), text(&s, "E4")], ["Plums", "Pears", "Apples", "Everything"]);
assert_eq!(text(&s, "A5"), "Eastern");
assert_eq!(text(&s, "A8"), "Everything");
// A renamed item sorts by its label still, and a filter still names it by its label.
s.execute("pivot.filter", json!({"field": "Region", "selected": ["East"]})).unwrap();
assert_eq!(text(&s, "A5"), "Eastern");
assert_eq!(val(&s, "E5"), Value::Number(415.0));
// Outline layout: the field's custom name heads its column.
edit_pt(&mut s, |p| {
p.layout = PivotLayout::Outline;
p.rows[0].caption = Some("Sales area".into());
p.columns[0].caption = Some("Kind".into());
});
assert_eq!(text(&s, "A4"), "Sales area");
assert_eq!(text(&s, "B3"), "Kind");
}
#[test]
fn field_subtotals_repeat_labels_and_values_row() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
assert_eq!(text(&s, "A7"), "East Total");
// Region without subtotals although the table has them; labels repeated on every row.
edit_pt(&mut s, |p| {
p.rows[0].subtotal = Some(false);
p.rows[0].repeat_labels = true;
});
assert_eq!(pt(&s).last_range.unwrap().height(), 1 + 9 + 1);
assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6"), text(&s, "A7")], ["East", "East", "East", "North"]);
assert_eq!(text(&s, "B7"), "Apples");
// Outline repeats the labels too.
s.execute("pivot.layout", json!({"layout": "outline"})).unwrap();
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "A5"), text(&s, "B5")], ["East", "", "East", "Apples"]);
// Two values without a column field: the Values row (Outline/Tabular) holds the caption.
s.execute("pivot.removeField", json!({"field": "Product"})).unwrap();
s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap();
assert_eq!(text(&s, "B3"), "Values");
assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "C4")], ["Region", "Sum of Sales", "Sum of Units"]);
edit_pt(&mut s, |p| p.data_caption = Some("Data".into()));
assert_eq!(text(&s, "B3"), "Data");
edit_pt(&mut s, |p| p.show_values_row = false);
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Region", "Sum of Sales"]);
// Compact layout never shows it.
edit_pt(&mut s, |p| {
p.show_values_row = true;
p.layout = PivotLayout::Compact;
});
assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Row Labels", "Sum of Sales"]);
}
#[test]
fn empty_cell_caption_classic_layout_and_date_order() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Units"], "values": ["Sales"]})).unwrap();
// East has no record with 1 unit: blank, or the "For empty cells show" caption.
assert_eq!([text(&s, "A5"), text(&s, "B4"), text(&s, "B5")], ["East", "1", ""]);
edit_pt(&mut s, |p| p.empty_caption = Some("0".into()));
assert_eq!(text(&s, "B5"), "0");
// Classic layout, one value and no column field: the value caption above the row
// headers and a "Total" column.
s.execute("pivot.removeField", json!({"field": "Units"})).unwrap();
edit_pt(&mut s, |p| {
p.layout = PivotLayout::Tabular;
p.classic_layout = true;
});
assert_eq!([text(&s, "A3"), text(&s, "A4"), text(&s, "B4"), text(&s, "A5")], ["Sum of Sales", "Region", "Total", "East"]);
assert_eq!(pt(&s).last_range.unwrap().height(), 2 + 3 + 1);
// A field number format applies to the item labels; date items sort after text, as in
// Excel.
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
s.execute("pivot.removeField", json!({"field": "Region"})).unwrap();
s.execute("pivot.addField", json!({"field": "Date", "area": "rows"})).unwrap();
edit_pt(&mut s, |p| p.rows[0].number_format = Some("m/d/yyyy".into()));
assert_eq!(text(&s, "A5"), "NA");
}
#[test]
fn only_date_formatted_cells_sort_as_dates() {
// The two mixed columns of ClosedXML's VariousDataTypesInTableColumns, in source order.
// Excel caches each date-formatted cell as `<d>` and each General one as `<n>`, and its
// saved items list numbers first and dates after errors, whatever the first cell is.
let mixed = ["", "TRUE", "14.5", "10", "ABC", "=1/0", "8/10/2020", "16:30"];
// 1 and 1.52… are 12/31/1899 and 12/31/1899 12:30, which typed input reads as text.
let with_num = ["1", "1.5208333333333333", "12/24/2020", "16:30", "0.1", "45000", ""];
let order = |inputs: &[&str], dates: Option<&str>| -> Vec<String> {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "K"})).unwrap();
s.execute("cell.set", json!({"cell": "B1", "input": "V"})).unwrap();
for (i, input) in inputs.iter().enumerate() {
s.execute("cell.set", json!({"cell": format!("A{}", i + 2), "input": input})).unwrap();
s.execute("cell.set", json!({"cell": format!("B{}", i + 2), "input": "1"})).unwrap();
}
if let Some(range) = dates {
s.execute("home.formatCells", json!({"range": range, "style": {"num_fmt": "m/d/yyyy h:mm"}})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"]})).unwrap();
edit_pt(&mut s, |p| p.rows[0].sort = PivotSort::Asc);
let wb = &s.doc().unwrap().wb;
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().skip(1).filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l != "Grand Total").collect()
};
// Excel's saved <items> order for each field.
let excel_mixed = ["10", "14.5", "ABC", "TRUE", "#DIV/0!", "0.6875", "44053", "(blank)"];
let excel_with_num = ["0.1", "45000", "0.6875", "1", "1.52083333333333", "44189", "(blank)"];
assert_eq!(order(&mixed, None), excel_mixed);
assert_eq!(order(&with_num, Some("A2:A3")), excel_with_num);
// One number in a date cell and in a General cell is one item, which sorts as a number
// whichever cell comes first.
let number = ["5", "44053", "ABC"];
assert_eq!(order(&["5", "8/10/2020", "44053", "ABC"], None), number);
assert_eq!(order(&["5", "44053", "8/10/2020", "ABC"], None), number);
}
#[test]
fn a_general_cell_filtered_out_still_makes_its_number_sort_as_a_number() {
// 3/15/2023 is 45000: the General 45000 in row 3 makes that item a number, as in Excel's
// cache, even when the report filter leaves only the date cell.
let order = |filter: bool| -> Vec<String> {
let mut s = Session::new();
s.new_workbook();
for (cell, input) in [("A1", "K"), ("B1", "V"), ("C1", "R"), ("A2", "3/15/2023"), ("A3", "45000"), ("A4", "ABC")] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
for (row, r) in [(2, "a"), (3, "b"), (4, "a")] {
s.execute("cell.set", json!({"cell": format!("B{row}"), "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": format!("C{row}"), "input": r})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"], "filters": ["R"]})).unwrap();
s.execute("pivot.sort", json!({"field": "K", "order": "asc"})).unwrap();
if filter {
s.execute("pivot.filter", json!({"field": "R", "selected": ["a"]})).unwrap();
}
let wb = &s.doc().unwrap().wb;
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l == "45000" || l == "ABC").collect()
};
assert_eq!(order(false), ["45000", "ABC"]);
assert_eq!(order(true), ["45000", "ABC"]);
}
#[test]
fn dates_sort_after_logicals_and_errors() {
// Excel's ascending item order: numbers, text, logicals, errors, dates, blanks.
let mut s = sales();
s.execute("cell.set", json!({"cell": "C11", "input": "TRUE"})).unwrap();
s.execute("cell.set", json!({"cell": "C12", "input": "=1/0"})).unwrap();
s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
p.rows[0].number_format = None;
p.rows[0].sort = PivotSort::Asc;
});
let p = pt(&s);
let r = p.last_range.unwrap();
let labels: Vec<String> = (r.start.row + 1..=r.end.row).map(|row| text(&s, &CellRef::new(row, r.start.col).a1())).collect();
// 46037 is 1/15/2026, the first date.
assert_eq!(labels[..4], ["NA", "TRUE", "#DIV/0!", "46037"]);
}
fn pivot_chart(s: &Session) -> gridcraft_model::Chart {
s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone()
}
@@ -1383,289 +1153,12 @@ fn collapsed_column_items_count_as_one_column_group() {
s.execute("pivot.addField", json!({"field": "Sub", "area": "columns"})).unwrap();
}
#[test]
fn design_subtotals_replace_field_settings() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// A file's field can override the table default (`defaultSubtotal`).
edit_pt(&mut s, |p| {
p.subtotals = false;
p.rows[0].subtotal = Some(true);
});
assert!(find_row(&s, "East Total").is_some());
// Design › Subtotals › Do Not Show Subtotals applies to every field.
s.execute("pivot.subtotals", json!({"mode": "none"})).unwrap();
assert!(pt(&s).rows.iter().all(|f| f.subtotal.is_none()));
assert_eq!(find_row(&s, "East Total"), None);
edit_pt(&mut s, |p| p.rows[0].subtotal = Some(false));
s.execute("pivot.subtotals", json!({"mode": "bottom"})).unwrap();
assert!(find_row(&s, "East Total").is_some());
}
#[test]
fn numeric_empty_cell_caption_is_a_number() {
let mut s = sales();
s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
// South has no Apples: the cell shows the caption, a number as Excel stores it.
edit_pt(&mut s, |p| p.empty_caption = Some("0".into()));
let south = find_row(&s, "South").unwrap();
let apples = CellRef::new(south, 1);
assert_eq!(text(&s, &CellRef::new(south - 3, 1).a1()), "Apples");
assert_eq!(val(&s, &apples.a1()), Value::Number(0.0));
edit_pt(&mut s, |p| p.empty_caption = Some("n/a".into()));
assert_eq!(val(&s, &apples.a1()), Value::text("n/a"));
}
/// Saves the active workbook, applies `patch` to the first PivotTable part and reopens it.
fn reopen_patched(s: &Session, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec<String>) {
reopen_patched_part(s, "xl/pivotTables/pivotTable1.xml", patch)
}
/// Saves the active workbook, applies `patch` to `part` and reopens it.
fn reopen_patched_part(s: &Session, part: &str, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec<String>) {
use std::io::{Read, Write};
let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for i in 0..z.len() {
let mut f = z.by_index(i).unwrap();
let name = f.name().unwrap().to_string();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
if name == part {
b = patch(&String::from_utf8(b).unwrap()).into_bytes();
}
out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
out.write_all(&b).unwrap();
}
let bytes = out.finish().unwrap().into_inner();
crate::io::open_bytes("t.xlsx", &bytes).unwrap()
}
#[test]
fn sort_by_value_in_a_column_keeps_its_scope() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Excel's "sort by the values in the Apples column": the scope also names Product's
// item 0 (Apples). Apples: East 160, West 170, North 90; totals East 415, West 285.
let one = "<references count=\"1\"><reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
let values_ref = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
let two = format!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>");
let (wb, _) = reopen_patched(&s, |x| {
assert!(x.contains(one), "{x}");
x.replace(one, &two)
});
let si = wb.active_sheet();
let p = wb.sheet(si).unwrap().pivots.last().unwrap();
let apples = gridcraft_model::PivotScopeItem { source_col: "Product".into(), item: "Apples".into(), ..Default::default() };
assert_eq!(p.rows[0].sort_scope, vec![apples]);
let out = crate::pivot::compute(&wb, p, si).unwrap();
let labels: Vec<String> = out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).collect();
let order: Vec<&str> = labels.iter().map(String::as_str).filter(|l| ["East", "West", "North"].contains(l)).collect();
assert_eq!(order, ["West", "East", "North"]);
// Saving writes the scope back.
let again = crate::io::save_bytes(&wb, "t.xlsx").unwrap();
let (back, _) = crate::io::open_bytes("t.xlsx", &again).unwrap();
assert_eq!(back.sheet(si).unwrap().pivots.last().unwrap().rows[0].sort_scope, p.rows[0].sort_scope);
// A scope GridCraft can't represent (two Product items) loads as a sort by label, with
// a warning, instead of as a sort by the grand total.
let bad = format!("<references count=\"2\">{values_ref}<reference field=\"1\" count=\"2\" selected=\"0\"><x v=\"0\"/><x v=\"1\"/></reference>");
let (wb2, warnings) = reopen_patched(&s, |x| x.replace(one, &bad));
let p2 = wb2.sheet(wb2.active_sheet()).unwrap().pivots.last().unwrap();
assert_eq!(p2.rows[0].sort_by, None);
assert!(p2.rows[0].sort_scope.is_empty());
assert!(warnings.iter().any(|w| w.contains("scope")), "{warnings:?}");
}
/// Saves and reopens a workbook.
fn reopen_wb(wb: &gridcraft_model::Workbook) -> gridcraft_model::Workbook {
let bytes = crate::io::save_bytes(wb, "t.xlsx").unwrap();
crate::io::open_bytes("t.xlsx", &bytes).unwrap().0
}
/// The labels in the report's first column, as computed from `wb`, keeping only `keep`.
fn first_col(wb: &gridcraft_model::Workbook, keep: &[&str]) -> Vec<String> {
let si = wb.active_sheet();
let p = wb.sheet(si).unwrap().pivots.last().unwrap();
let out = crate::pivot::compute(wb, p, si).unwrap();
out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).filter(|l| keep.contains(&l.as_str())).collect()
}
const VALUES_REF: &str = "<reference field=\"4294967294\" count=\"1\" selected=\"0\"><x v=\"0\"/></reference>";
/// The Values-only sort scope the writer emits, as a `<references>` opening.
fn values_only() -> String {
format!("<references count=\"1\">{VALUES_REF}")
}
#[test]
fn sort_scope_tells_date_levels_of_one_column_apart() {
use gridcraft_model::{PivotDateGroup, PivotField};
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Date"], "values": ["Sales"]})).unwrap();
edit_pt(&mut s, |p| {
let date = p.columns[0].clone();
p.columns =
vec![PivotField { date_group: PivotDateGroup::Years, ..date.clone() }, PivotField { date_group: PivotDateGroup::Quarters, ..date }];
});
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Sort by the values in the 2026 › Qtr2 column: Years is cache field 5 (item 1 = 2026,
// after "<1/15/2026"), Quarters the Date field 2 (item 2 = Qtr2). Qtr2 holds West 70,
// East 60, North 30; the totals are East 415, West 285, North 135.
let refs = format!(
"<references count=\"3\">{VALUES_REF}<reference field=\"5\" count=\"1\" selected=\"0\"><x v=\"1\"/></reference><reference field=\"2\" count=\"1\" selected=\"0\"><x v=\"2\"/></reference>"
);
let (wb, _) = reopen_patched(&s, |x| {
assert!(x.contains(&values_only()), "{x}");
x.replace(&values_only(), &refs)
});
let regions = ["East", "West", "North"];
assert_eq!(first_col(&wb, &regions), ["West", "East", "North"]);
// Saving writes both references back.
let back = reopen_wb(&wb);
let scope = |wb: &gridcraft_model::Workbook| wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.clone();
assert_eq!(scope(&back).len(), 2);
assert_eq!(scope(&back), scope(&wb));
assert_eq!(first_col(&back, &regions), ["West", "East", "North"]);
}
#[test]
fn custom_subtotal_functions_keep_the_subtotal_rows() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// Field Settings › Subtotals › Custom (Sum and Count) on Product, as Excel stores it.
let (wb, warnings) = reopen_patched(&s, |x| {
let start = x.match_indices("<pivotField ").nth(1).unwrap().0;
let end = start + x[start..].find("</pivotField>").unwrap();
let field = x[start..end]
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" countSubtotal=\"1\" ", 1)
.replace("<item t=\"default\"/>", "<item t=\"sum\"/><item t=\"count\"/>");
assert!(field.contains("t=\"sum\""), "{field}");
format!("{}{field}{}", &x[..start], &x[end..])
});
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
assert_ne!(p.rows[1].subtotal, Some(false));
// Shown with the automatic subtotal, with a warning.
let plain = reopen_wb(&s.doc().unwrap().wb);
let all = |wb: &gridcraft_model::Workbook| {
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid.iter().map(|r| r.iter().map(|c| c.value.display()).collect::<Vec<_>>()).collect::<Vec<_>>()
};
assert_eq!(all(&wb), all(&plain));
assert!(warnings.iter().any(|w| w.contains("subtotal")), "{warnings:?}");
}
#[test]
fn custom_subtotals_on_the_first_field_keep_the_table_default() {
use std::io::Read;
let mut s = sales();
s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap();
s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap();
// Custom Sum subtotal on Region (cache field 0, the first axis field), no xpdl extension.
let (wb, _) = reopen_patched(&s, |x| {
assert!(!x.contains("pivotTableDefinition16"), "{x}");
let start = x.find("<pivotField ").unwrap();
let end = start + x[start..].find("</pivotField>").unwrap();
let field = x[start..end]
.replacen("<pivotField ", "<pivotField defaultSubtotal=\"0\" sumSubtotal=\"1\" ", 1)
.replace("<item t=\"default\"/>", "<item t=\"sum\"/>");
assert!(field.contains("t=\"sum\""), "{field}");
format!("{}{field}{}", &x[..start], &x[end..])
});
let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap();
assert!(p.subtotals);
assert_eq!([p.rows[0].subtotal, p.rows[1].subtotal], [None, None]);
// Saving doesn't add a table default of "off" the file never had.
let bytes = crate::io::save_bytes(&wb, "t.xlsx").unwrap();
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
z.by_name("xl/pivotTables/pivotTable1.xml").unwrap().read_to_string(&mut xml).unwrap();
assert!(!xml.contains("EnabledSubtotalsDefault=\"0\""), "{xml}");
}
#[test]
fn sort_scope_on_a_vanished_item_sorts_as_after_saving() {
let mut s = sales();
s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap();
s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap();
// Sorted by the values in the Kiwis column (Product item 3)…
let refs = format!("<references count=\"2\">{VALUES_REF}<reference field=\"1\" count=\"1\" selected=\"0\"><x v=\"3\"/></reference>");
let (mut wb, _) = reopen_patched(&s, |x| x.replace(&values_only(), &refs));
assert_eq!(wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.len(), 1);
// …then Kiwis leaves the source: the rows sort by the grand total, before and after saving.
let src = wb.sheets.iter().position(|sh| sh.name == "Sheet1").unwrap();
wb.sheet_mut(src).unwrap().set_value(CellRef::parse("B14").unwrap(), Value::text("Apples"));
let regions = ["East", "West", "North", "South"];
let total_order = ["East", "West", "North", "South"];
assert_eq!(first_col(&wb, &regions), total_order);
assert_eq!(first_col(&reopen_wb(&wb), &regions), total_order);
}
#[test]
fn date_groups_not_sorted_are_in_date_order() {
let mut s = sales();
// The first record is in Qtr4.
s.execute("cell.set", json!({"cell": "C2", "input": "12/1/2026"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap();
s.execute("pivot.group", json!({"field": "Date", "by": "quarters"})).unwrap();
s.execute("pivot.sort", json!({"field": "Date", "order": "none"})).unwrap();
let quarters = ["Qtr1", "Qtr2", "Qtr3", "Qtr4"];
assert_eq!(first_col(&s.doc().unwrap().wb, &quarters), quarters);
let back = reopen_wb(&s.doc().unwrap().wb);
assert_eq!(first_col(&back, &quarters), quarters);
// A reordered list still wins; items it doesn't name follow in date order.
let mut wb = back;
let si = wb.active_sheet();
wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap().rows[0].item_order = vec!["Qtr3".into()];
assert_eq!(first_col(&wb, &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
assert_eq!(first_col(&reopen_wb(&wb), &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]);
}
#[test]
fn manual_order_of_time_items_from_an_excel_cache() {
// Excel caches times as `<d v="1899-12-30T08:00:00"/>`: those items must name the
// report's 8:00 and 9:30, or a refresh puts the blank ahead of them.
let mut s = Session::new();
s.new_workbook();
for (cell, input) in [("A1", "Shift"), ("B1", "Sales"), ("A2", "8:00"), ("B2", "10"), ("A3", "9:30"), ("B3", "20"), ("B4", "5")] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("insert.pivotTable", json!({"rows": ["Shift"], "values": ["Sales"]})).unwrap();
s.execute("pivot.sort", json!({"field": "Shift", "order": "none"})).unwrap();
// The report's first column: times as minutes, and the blank item.
let shifts = |wb: &gridcraft_model::Workbook| -> Vec<String> {
let si = wb.active_sheet();
let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap();
out.grid
.iter()
.filter_map(|r| match &r.first()?.value {
Value::Number(n) => Some(format!("{}", (n * 1440.0).round())),
v if v.display() == "(blank)" => Some(v.display()),
_ => None,
})
.collect()
};
let order = ["480", "570", "(blank)"];
assert_eq!(shifts(&s.doc().unwrap().wb), order);
let excel_items = "<d v=\"1899-12-30T08:00:00\"/><d v=\"1899-12-30T09:30:00\"/><m/>";
let (back, _) = reopen_patched_part(&s, "xl/pivotCache/pivotCacheDefinition1.xml", |x| {
let ours = "<n v=\"0.3333333333333333\"/><n v=\"0.3958333333333333\"/><m/>";
assert!(x.contains(ours), "{x}");
x.replace(ours, excel_items)
});
assert_eq!(shifts(&back), order);
// Saving writes that order back.
assert_eq!(shifts(&reopen_wb(&back)), order);
}
#[test]
fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
let mut s = sales();
s.execute("insert.pivotTable", json!({"source": "Sheet1!A1:E13", "destination": "Sheet1!H10", "rows": ["Region"], "values": ["Sales"]})).unwrap();
assert_eq!(pt(&s).last_range.unwrap().a1(), "H10:I14");
// Rows above the report (and below the source) move the report only.
s.execute("home.insertRows", json!({"rows": "16:17"})).unwrap();
s.execute("home.insertRows", json!({"rows": "6:7"})).unwrap();
assert_eq!(text(&s, "H12"), "Row Labels");
@@ -1673,6 +1166,7 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
assert_eq!(l[0]["anchor"], "H12");
assert_eq!(l[0]["range"], "H12:I16");
assert_eq!(l[0]["source"], "Sheet1!A1:E15");
// A row above the source moves both.
s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap();
let p = pt(&s);
assert_eq!(p.source, "Sheet1!A2:E16");
@@ -1681,10 +1175,12 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() {
assert_eq!(pt(&s).last_range.unwrap().a1(), "H13:I17");
assert_eq!(text(&s, "H13"), "Row Labels");
assert_eq!(val(&s, "I17"), Value::Number(TOTAL));
// Deleting a column left of the report moves it left.
s.execute("home.deleteColumns", json!({"cols": "F:F"})).unwrap();
let p = pt(&s);
assert_eq!(p.anchor.a1(), "G13");
assert_eq!(p.last_range.unwrap().a1(), "G13:H17");
// Deleting rows above moves it up.
s.execute("home.deleteRows", json!({"rows": "1:1"})).unwrap();
assert_eq!(pt(&s).source, "Sheet1!A1:E15");
assert_eq!(pt(&s).anchor.a1(), "G12");
+54 -18
View File
@@ -11,7 +11,7 @@
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value};
#[cfg(test)]
use gridcraft_model::{Alignment, CellPicture, Image, SheetViewMode};
use gridcraft_model::{Alignment, Image, SheetViewMode};
use gridcraft_model::{
Anchor, BorderLine, BorderStyle, Borders, Color, HAlign, Orientation, PageOrder, PatternType, PrintSettings, ReadingOrder, ShapeKind, Sheet,
Style, StyleId, StyleTable, Underline, VAlign, Visibility, Workbook,
@@ -34,6 +34,49 @@ use header_footer::draw_header_footer;
pub use header_footer::{
HF_FIELDS, HfContext, HfSection, codes_to_fields, expand_header_footer, fields_to_codes, hf_date_time, join_header_footer, split_header_footer,
};
type DecodedPicture = (Vec<u8>, u32, u32);
/// What one PDF render shares across the pages an object spans.
#[derive(Default)]
struct PicCache {
/// Decoded pictures (bytes, width, height) keyed by (sheet, picture); `None` = undecodable.
decoded: std::collections::HashMap<(usize, usize), Option<DecodedPicture>>,
/// Laid-out charts (with their [`chart_cost`]) keyed by (sheet, chart), rendered once however
/// many pages they touch. Only charts that can still be drawn are kept.
charts: std::collections::HashMap<(usize, usize), (Vec<gridcraft_chart::Prim>, usize)>,
/// Charts too big for what was left of the budget: never drawn, so not rendered again.
rejected_charts: std::collections::HashSet<(usize, usize)>,
/// Bytes of picture pixels embedded so far, and chart cost units emitted so far. Each page an
/// object touches gets its own copy in the PDF, so a workbook-controlled anchor over thousands
/// of pages would multiply them without bound.
image_bytes: usize,
chart_prims: usize,
}
impl PicCache {
/// The chart's primitives for one more page, or `None` once they no longer fit
/// [`MAX_CHART_PRIMS`]. `render` runs at most once per chart; a chart that doesn't fit is
/// dropped at once and remembered, so its vectors are never retained.
fn chart(&mut self, key: (usize, usize), render: impl FnOnce() -> Vec<gridcraft_chart::Prim>) -> Option<&[gridcraft_chart::Prim]> {
if self.rejected_charts.contains(&key) {
return None;
}
let (prims, cost) = match self.charts.remove(&key) {
Some(cached) => cached,
None => {
let prims = render();
let cost = chart_cost(&prims);
(prims, cost)
}
};
if self.chart_prims.saturating_add(cost) > MAX_CHART_PRIMS {
self.rejected_charts.insert(key);
return None;
}
self.chart_prims += cost;
Some(&self.charts.entry(key).or_insert((prims, cost)).0)
}
}
/// What a chart's drawing costs in the PDF: one unit per primitive plus one per path point (a
/// smoothed line holds thousands of points, each written out) and per point of a wedge's outline.
@@ -50,6 +93,8 @@ fn chart_cost(prims: &[gridcraft_chart::Prim]) -> usize {
.fold(0, usize::saturating_add)
}
/// Most picture pixel bytes (RGBA, before PDF packing) one render embeds across all pages.
const MAX_EMBEDDED_IMAGE_BYTES: usize = 512 * 1024 * 1024;
/// Most chart cost units (primitives and path points, see [`chart_cost`]) one render draws across all pages.
const MAX_CHART_PRIMS: usize = 4_000_000;
@@ -57,8 +102,8 @@ 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::{seg_size, segments};
use objects::{PicCache, draw_objects};
use layout::{known_paper, seg_size, segments};
use objects::draw_objects;
#[cfg(test)]
use text::{center_across_width, wrap_lines};
@@ -69,7 +114,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export as PDF",
["File", "Export"],
None,
"{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.",
"{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.",
has_doc,
export_pdf
),
@@ -96,7 +141,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|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",
"{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",
has_doc,
page_setup
),
@@ -119,14 +164,7 @@ const MISSING_ARABIC_FONT: &str = "Some Arabic text could not be drawn in this P
/// Renders laid-out sheets to a PDF.
pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str) -> Result<RenderedPdf> {
render_pdf_with_image_budget(wb, layouts, file, path, gridcraft_pdf::MAX_DOC_IMAGE_BYTES)
}
/// [`render_pdf`] keeping at most `image_bytes` of picture data in the document (tests lower it
/// to exercise the cap without building gigabytes of pictures).
fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str, image_bytes: u64) -> Result<RenderedPdf> {
let mut doc = PdfDoc::new();
doc.set_image_budget(image_bytes);
doc.info.title = if wb.props.title.is_empty() { file.to_string() } else { wb.props.title.clone() };
doc.info.author = wb.props.author.clone();
let total: usize = layouts.iter().map(|l| l.pages.len()).sum();
@@ -135,8 +173,7 @@ fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &s
let mut pending_links = Vec::new();
let mut printed_blocks = Vec::new();
// Decoded pictures are reused across the pages their anchor covers: a floating picture
// spanning 40 pages was decoded 40 times (#2389). Each page still keeps its own copy in the
// PDF, within the document's image budget.
// spanning 40 pages was decoded (and pushed into the PDF) 40 times (#2389).
let mut pics = PicCache::default();
for lay in layouts {
let Some(sh) = wb.sheet(lay.sheet) else { continue };
@@ -160,7 +197,7 @@ fn render_pdf_with_image_budget(wb: &Workbook, layouts: &[SheetLayout], file: &s
let mut x = ox + lay.heading_w * k;
for (csi, cs) in csegs.iter().enumerate() {
let b = make_block(wb, lay.sheet, sh, *rs, *cs, (x, y), lay);
draw_block(pg, &b, lay.settings.gridlines, &mut cf, &mut pics);
draw_block(pg, &b, lay.settings.gridlines, &mut cf);
draw_block_links(pg, &b, page_index, &mut pending_links);
printed_blocks.push(PrintedBlock {
page: page_index,
@@ -309,9 +346,8 @@ fn page_setup(s: &mut Session, p: &Json) -> Result<Json> {
let paper = match str_param(p, "paper") {
None => None,
Some(name) => {
// 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())
known_paper(name).ok_or_else(|| bad(CMD, format!("unknown paper size `{name}`")))?;
Some(name.trim().to_string())
}
};
let margin_src = p.get("margins").filter(|m| m.is_object()).unwrap_or(p);
+3 -3
View File
@@ -1,5 +1,5 @@
use super::layout::{DENSE_BLOCK, SheetLayout};
use super::objects::{PicCache, draw_cell_picture};
use super::objects::draw_cell_picture;
use super::text::{TextPlacement, draw_text};
use super::{
BorderLine, BorderStyle, Borders, CellRef, Color, Font, Page, PatternType, Point, RangeRef, Rgb, Sheet, Style, StyleId, Underline, Value,
@@ -319,7 +319,7 @@ impl<'a> Covered<'a> {
}
/// Draws the cells of a block: fills, gridlines, data bars, borders and text.
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache, pics: &mut PicCache) {
pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) {
let (bx, by) = (b.xs.first().copied().unwrap_or(0.0), b.ys.first().copied().unwrap_or(0.0));
let (bw, bh) = (b.xs.last().copied().unwrap_or(bx) - bx, b.ys.last().copied().unwrap_or(by) - by);
if bw <= 0.0 || bh <= 0.0 {
@@ -434,7 +434,7 @@ pub(super) fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut cra
continue;
}
if let Some(picture) = sh.cell_pictures.get(c) {
draw_cell_picture(pg, pics, (b.si, *c), &picture.data, (b.text_x(x, w), y, w, h), b.k);
draw_cell_picture(pg, &picture.data, (b.text_x(x, w), y, w, h), b.k);
} else if let Some(on) = checkbox_state(l, &sh.value(*c)) {
draw_checkbox(pg, (b.text_x(x, w), y, w, h), b.k, on);
} else {
+48 -43
View File
@@ -9,10 +9,43 @@ pub(super) const DENSE_BLOCK: u64 = 60_000;
// ---------------------------------------------------------------- paper
/// 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.
/// Paper size in points (portrait) for a paper name; unknown names fall back to Letter.
pub fn paper_size(name: &str) -> (f32, f32) {
gridcraft_model::paper::size_pt(name).unwrap_or((612.0, 792.0))
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,
})
}
// ---------------------------------------------------------------- layout
@@ -70,8 +103,7 @@ impl SheetLayout {
#[derive(Clone, Debug, Default)]
pub struct PrintOptions {
pub all_sheets: bool,
/// Areas of the active sheet to print instead of its print area, in order (Print Selection).
pub ranges: Vec<RangeRef>,
pub range: Option<RangeRef>,
pub fit_to_page: Option<bool>,
}
@@ -82,35 +114,14 @@ impl PrintOptions {
Some("all") | Some("workbook") => true,
Some(other) => return Err(bad(cmd, format!("`sheets` must be active or all, not `{other}`"))),
};
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") })
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") })
}
}
/// 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> {
@@ -343,20 +354,14 @@ pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
if pages >= MAX_PAGES {
break;
}
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()) {
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()) {
continue;
}
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 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 {
+21 -115
View File
@@ -1,94 +1,9 @@
use super::draw::{Block, PdfMeasure, Xf, draw_prims, rgb_of};
use super::text::wrap_lines;
use super::{Anchor, Baseline, CellRef, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
use std::borrow::Cow;
use std::collections::hash_map::Entry;
/// A decoded picture: RGBA pixels, width, height.
type Decoded = (Vec<u8>, u32, u32);
/// Most bytes of decoded pictures one render memoizes; a picture decoded past it is used once
/// and dropped (and decoded again on the next page that prints it).
const MAX_PIC_CACHE_BYTES: u64 = 256 * 1024 * 1024;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum PicKey {
/// A floating picture: sheet index and position in `Sheet::images`.
Floating(usize, usize),
/// A cell picture: sheet index, cell and the thumbnail size it is decoded at.
Cell(usize, CellRef, u32, u32),
}
/// Decoded pictures reused across the pages (and repeated title rows) that print them, so a
/// picture is decoded once per render instead of once per page (#2389).
#[derive(Default)]
pub(super) struct PicCache {
map: std::collections::HashMap<PicKey, Option<Decoded>>,
/// Bytes of pixels in `map`.
bytes: u64,
/// Laid-out charts (with their [`chart_cost`](super::chart_cost)) keyed by (sheet, chart),
/// rendered once however many pages they touch. Only charts that can still be drawn are kept.
pub(super) charts: std::collections::HashMap<(usize, usize), (Vec<gridcraft_chart::Prim>, usize)>,
/// Charts too big for what was left of the budget: never drawn, so not rendered again.
pub(super) rejected_charts: std::collections::HashSet<(usize, usize)>,
/// Chart cost units emitted so far. Each page a chart touches gets its own copy in the PDF,
/// so a workbook-controlled anchor over thousands of pages would multiply them without bound.
pub(super) chart_prims: usize,
}
impl PicCache {
/// The decoded picture for `key`, running `decode` the first time. A failed decode is
/// remembered too; a decode that does not fit in the cache is returned without being kept.
fn get(&mut self, key: PicKey, decode: impl FnOnce() -> Option<Decoded>) -> Option<Cow<'_, Decoded>> {
let slot = match self.map.entry(key) {
Entry::Occupied(e) => e.into_mut(),
Entry::Vacant(e) => {
let decoded = decode();
let size = decoded.as_ref().map_or(0, |d| d.0.len() as u64);
if self.bytes.saturating_add(size) > MAX_PIC_CACHE_BYTES {
return decoded.map(Cow::Owned);
}
self.bytes = self.bytes.saturating_add(size);
e.insert(decoded)
}
};
slot.as_ref().map(Cow::Borrowed)
}
/// The chart's primitives for one more page, or `None` once they no longer fit
/// [`MAX_CHART_PRIMS`](super::MAX_CHART_PRIMS). `render` runs at most once per chart; a chart
/// that doesn't fit is dropped at once and remembered, so its vectors are never retained.
pub(super) fn chart(&mut self, key: (usize, usize), render: impl FnOnce() -> Vec<gridcraft_chart::Prim>) -> Option<&[gridcraft_chart::Prim]> {
if self.rejected_charts.contains(&key) {
return None;
}
let (prims, cost) = match self.charts.remove(&key) {
Some(cached) => cached,
None => {
let prims = render();
let cost = super::chart_cost(&prims);
(prims, cost)
}
};
if self.chart_prims.saturating_add(cost) > super::MAX_CHART_PRIMS {
self.rejected_charts.insert(key);
return None;
}
self.chart_prims += cost;
Some(&self.charts.entry(key).or_insert((prims, cost)).0)
}
}
/// Whether a picture decoded into at most `max_w`×`max_h` pixels can still be kept by the PDF.
/// The document's image room only shrinks while it is built, so a picture refused here would be
/// refused on every later page too and is not decoded at all.
fn fits(room: u64, max_w: u32, max_h: u32) -> bool {
u64::from(max_w).saturating_mul(u64::from(max_h)).saturating_mul(4) <= room
}
use super::{Anchor, Baseline, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
/// Cell pictures fit the current cell (or merged-cell) rectangle without changing aspect ratio.
/// `at` (sheet index and cell) keys the decode in `pics`.
pub(super) fn draw_cell_picture(pg: &mut Page, pics: &mut PicCache, at: (usize, CellRef), data: &[u8], rect: (f32, f32, f32, f32), k: f32) {
pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32, f32), k: f32) {
let (x, y, w, h) = rect;
let pad = 2.0 * k;
let (w, h) = ((w - 2.0 * pad).max(0.0), (h - 2.0 * pad).max(0.0));
@@ -99,30 +14,18 @@ pub(super) fn draw_cell_picture(pg: &mut Page, pics: &mut PicCache, at: (usize,
if iw == 0 || ih == 0 || iw > 8192 || ih > 8192 || u64::from(iw) * u64::from(ih) > 16_000_000 {
return;
}
let (tw, th) = (((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32);
let room = pg.image_room();
let Some(image) = pics.get(PicKey::Cell(at.0, at.1, tw, th), || decode_cell_picture(data, tw, th, room)) else { return };
let (px, px_w, px_h) = &*image;
let fit = (w / iw as f32).min(h / ih as f32);
let (pw, ph) = (iw as f32 * fit, ih as f32 * fit);
pg.image_rgba(Rect::new(x + pad + (w - pw) / 2.0, y + pad + (h - ph) / 2.0, pw, ph), px, [*px_w, *px_h]);
}
/// Decodes a cell picture to RGBA scaled to fit `tw`×`th` pixels, unless the PDF has no `room`
/// left for it.
fn decode_cell_picture(data: &[u8], tw: u32, th: u32, room: u64) -> Option<Decoded> {
if !fits(room, tw, th) {
return None;
}
let mut reader = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?;
let Ok(mut reader) = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format() else { return };
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(64 * 1024 * 1024);
reader.limits(limits);
let image = reader.decode().ok()?.thumbnail(tw, th).to_rgba8();
let (pw, ph) = (image.width(), image.height());
Some((image.into_raw(), pw, ph))
let Ok(image) = reader.decode() else { return };
let image =
image.thumbnail(((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32).to_rgba8();
let fit = (w / iw as f32).min(h / ih as f32);
let (pw, ph) = (iw as f32 * fit, ih as f32 * fit);
pg.image_rgba(Rect::new(x + pad + (w - pw) / 2.0, y + pad + (h - ph) / 2.0, pw, ph), image.as_raw(), [image.width(), image.height()]);
}
/// Sheet pixel rectangle of an anchor.
@@ -150,11 +53,10 @@ fn anchor_rect(sh: &Sheet, a: &Anchor) -> (f64, f64, f64, f64) {
(sh.col_left(a.cell.col) + a.dx as f64, sh.row_top(a.cell.row) + a.dy as f64, a.width.max(0.0) as f64, a.height.max(0.0) as f64)
}
/// Decodes an embedded picture to RGBA, downscaled to at most `max_w`×`max_h` pixels, unless the
/// PDF has no `room` left for it.
fn decode_image(data: &[u8], max_w: u32, max_h: u32, room: u64) -> Option<Decoded> {
/// Decodes an embedded picture to RGBA, downscaled to at most `max_w`×`max_h` pixels.
fn decode_image(data: &[u8], max_w: u32, max_h: u32) -> Option<(Vec<u8>, u32, u32)> {
let (w, h) = crate::io::image_size(data)?;
if w == 0 || h == 0 || w as u64 * h as u64 > 60_000_000 || !fits(room, w.min(max_w.max(1)), h.min(max_h.max(1))) {
if w == 0 || h == 0 || w as u64 * h as u64 > 60_000_000 {
return None;
}
let img = image::load_from_memory(data).ok()?;
@@ -167,7 +69,7 @@ fn decode_image(data: &[u8], max_w: u32, max_h: u32, room: u64) -> Option<Decode
/// Draws charts, pictures, shapes and sparklines overlapping the body block of a page.
/// `pics` memoizes decoded pictures for the whole render (one page at a time draws each
/// picture again, but the decode happens once).
pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block, pics: &mut PicCache) {
pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Block, pics: &mut super::PicCache) {
let block = b.range();
let (sx0, sy0) = (sh.col_left(block.start.col), sh.row_top(block.start.row));
let (sx1, sy1) = (sh.col_left(block.end.col.saturating_add(1)), sh.row_top(block.end.row.saturating_add(1)));
@@ -188,10 +90,14 @@ pub(super) fn draw_objects(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet,
let (x, y, w, h) = place(r);
// About 150 dpi is plenty for print.
let (mw, mh) = (((w / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32, ((h / 72.0) * 150.0).ceil().clamp(1.0, 4000.0) as u32);
let room = pg.image_room();
if let Some(decoded) = pics.get(PicKey::Floating(si, imi), || decode_image(&im.data, mw, mh, room)) {
let (px, pw, ph) = &*decoded;
pg.image_rgba(Rect::new(x, y, w, h), px, [*pw, *ph]);
let decoded = pics.decoded.entry((si, imi)).or_insert_with(|| decode_image(&im.data, mw, mh));
if let Some((px, pw, ph)) = decoded.as_ref() {
// Every page the picture touches embeds its own copy: past the budget it is left out.
let bytes = px.len();
if pics.image_bytes.saturating_add(bytes) <= super::MAX_EMBEDDED_IMAGE_BYTES {
pics.image_bytes += bytes;
pg.image_rgba(Rect::new(x, y, w, h), px, [*pw, *ph]);
}
}
}
for shp in &sh.shapes {
+3 -207
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 { ranges: RangeRef::parse("A1:B2").into_iter().collect(), ..PrintOptions::default() };
let options = PrintOptions { range: RangeRef::parse("A1:B2"), ..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;
@@ -779,98 +779,6 @@ fn charts_and_images_are_drawn() {
}
}
/// Bytes of pixel data the pages of a PDF hold: 3 per RGB pixel plus 1 per soft-mask pixel, for
/// every image each page references. The writer shares identical images across pages, but each
/// page kept its own copy while the document was built, so a shared image counts once per page.
fn image_bytes(pdf: &[u8]) -> u64 {
let text = String::from_utf8_lossy(pdf);
let num_after = |s: &str, key: &str| -> u64 {
let at = s.find(key).unwrap() + key.len();
s[at..].split_whitespace().next().unwrap().parse().unwrap()
};
// Object id → (pixel bytes, soft mask id).
let mut images = std::collections::HashMap::new();
let mut pages = vec![];
for obj in text.split("endobj").filter(|o| o.contains(" 0 obj")) {
let head = &obj[..obj.find(" 0 obj").unwrap()];
let id: u64 = head.split_whitespace().last().unwrap().parse().unwrap();
let dict = &obj[..obj.find(">>").unwrap_or(obj.len())];
if dict.contains("/Subtype /Image") {
let bytes = num_after(dict, "/Width ") * num_after(dict, "/Height ") * if dict.contains("/DeviceRGB") { 3 } else { 1 };
let smask = dict.contains("/SMask ").then(|| num_after(dict, "/SMask "));
images.insert(id, (bytes, smask));
} else if obj.contains("/Type /Page /Parent") {
pages.push(obj);
}
}
let with_mask = |id: u64| -> u64 {
let (bytes, smask) = images[&id];
bytes + smask.map_or(0, |m| images[&m].0)
};
pages
.iter()
.filter_map(|page| page.find("/XObject << ").map(|at| &page[at + "/XObject << ".len()..]))
.map(|refs| {
let refs = &refs[..refs.find(">>").unwrap()];
let tokens: Vec<&str> = refs.split_whitespace().collect();
tokens.chunks(4).map(|c| with_mask(c[1].parse().unwrap())).sum::<u64>()
})
.sum()
}
/// A picture anchored across many pages keeps no more copies in the PDF than the image budget
/// allows, and the export still succeeds.
#[test]
fn picture_copies_across_pages_stay_within_the_image_budget() {
// Each page a picture overlaps kept its own decoded copy in the PDF with no document-wide
// bound: a 3 KB workbook with one tall picture reached 2 GiB before running out of pages.
let mut s = s();
let mut png = Vec::new();
let img = image::RgbaImage::from_pixel(64, 64, image::Rgba([10, 120, 200, 255]));
image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "Title"})).unwrap();
s.execute("pageLayout.pageSetup", json!({"titleRows": "1:1"})).unwrap();
let d = s.doc_mut().unwrap();
let wb = std::sync::Arc::make_mut(&mut d.wb);
let id = wb.next_object_id();
let sh = wb.sheet_mut(0).unwrap();
// A floating picture over some 20 pages, and a cell picture in the title row on every page.
sh.images.push(Image {
id,
anchor: Anchor { cell: CellRef::new(1, 1), dx: 0.0, dy: 0.0, width: 200.0, height: 19_990.0, mode: gridcraft_model::AnchorMode::MoveAndSize },
data: std::sync::Arc::new(png.clone()),
mime: "image/png".into(),
alt: String::new(),
});
// `set_picture` gives C1 the cell value `draw_block` needs to reach the picture at all.
sh.set_picture(CellRef::new(0, 2), std::sync::Arc::new(CellPicture { data: png, mime: "image/png".into(), alt: String::new() }));
let d = s.doc().unwrap();
let lays = layouts(&d.wb, &PrintOptions::from_params(&json!({}), "file.exportPdf").unwrap());
let RenderedPdf { bytes: full, pages, .. } = render_pdf(&d.wb, &lays, "t", "").unwrap();
assert!(pages >= 15, "{pages} pages");
// Within the default budget every page draws (and holds while the PDF is built) its own copy.
// Identical copies are written to the file once, so the draws are what to count.
let draws = |pdf: &[u8]| String::from_utf8_lossy(pdf).matches(" Do Q").count();
let full_draws = draws(&full);
// The cell picture, on its own: the same render without it draws one picture fewer per page.
let mut floating_only = (*d.wb).clone();
floating_only.sheet_mut(0).unwrap().cell_pictures.clear();
let floating_draws = draws(&render_pdf(&floating_only, &lays, "t", "").unwrap().bytes);
assert!(floating_draws >= pages - 1, "{floating_draws} floating picture draws on {pages} pages");
assert_eq!(full_draws - floating_draws, pages, "the title-row cell picture draws once on each of {pages} pages");
// 64×64 RGB is 12,288 bytes: a 64 KiB budget holds a handful of page copies, not one per page.
let budget = 64 * 1024;
let RenderedPdf { bytes: capped, pages: capped_pages, .. } = render_pdf_with_image_budget(&d.wb, &lays, "t", "", budget).unwrap();
assert_eq!(capped_pages, pages, "pages past the budget still print, without the pictures");
let capped_draws = draws(&capped);
assert!((1..full_draws / 2).contains(&capped_draws), "{capped_draws} of {full_draws} picture draws kept with a {budget}-byte budget");
let kept = image_bytes(&capped);
assert!((1..=budget).contains(&kept), "{kept} bytes of images kept with a {budget}-byte budget");
assert!(contains(&capped, "%%EOF"));
}
#[test]
fn page_setup_edits_settings() {
let mut s = s();
@@ -974,48 +882,6 @@ 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();
@@ -1368,8 +1234,7 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
// A smoothed line is its points, not one unit.
assert_eq!(chart_cost(&[line(4000), Prim::Circle { cx: 0.0, cy: 0.0, r: 1.0, fill: None, stroke: None }]), 4002);
// Room for exactly two copies of a 1,000-point chart.
let mut pics = PicCache::default();
pics.chart_prims = MAX_CHART_PRIMS - 2002;
let mut pics = PicCache { chart_prims: MAX_CHART_PRIMS - 2002, ..Default::default() };
let mut renders = 0;
for expect in [true, true, false, false] {
let got = pics.chart((0, 0), || {
@@ -1381,76 +1246,7 @@ fn chart_budget_counts_path_points_and_drops_charts_that_do_not_fit() {
assert_eq!(renders, 1, "a rejected chart is not rendered again");
assert!(pics.charts.is_empty(), "and its primitives are not kept");
// A chart too big for what is left is dropped without being cached at all.
let mut pics = PicCache::default();
pics.chart_prims = MAX_CHART_PRIMS - 10;
let mut pics = PicCache { chart_prims: MAX_CHART_PRIMS - 10, ..Default::default() };
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]"));
}
+2 -4
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|Statement|Envelope #10|Envelope DL (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 (B4/B5/B6 are the JIS sizes)}",
has_doc,
paper
),
@@ -324,9 +324,7 @@ fn orientation(s: &mut Session, p: &Json) -> Result<Json> {
}
fn paper(s: &mut Session, p: &Json) -> Result<Json> {
// 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();
let paper = str_param(p, "paper").unwrap_or("Letter").to_string();
edit(s, |cx| {
let si = cx.sheet_index();
cx.sheet_mut(si)?.print.paper = paper.clone();
+4 -14
View File
@@ -53,10 +53,6 @@ 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.
@@ -532,8 +528,8 @@ pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result<Vec<u8
Err(EngineError::Other("SYLK (.slk) is supported for import only. Save as .xlsx or another supported export format.".into()))
}
// A workbook read from CSV keeps the separator it was read with (a `;` file stays `;`).
FileKind::Csv => wb.sheet(sheet).map(|sh| csv(wb, sh, Some(wb.csv_delimiter.unwrap_or(b',')))).transpose().map(Option::unwrap_or_default),
FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, None)).transpose().map(Option::unwrap_or_default),
FileKind::Csv => wb.sheet(sheet).map(|sh| csv(wb, sh, wb.csv_delimiter.unwrap_or(b','))).transpose().map(Option::unwrap_or_default),
FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, b'\t')).transpose().map(Option::unwrap_or_default),
FileKind::Json => crate::macros::json_bytes(wb),
FileKind::Html => to_html(wb, sheet).map(String::into_bytes),
}
@@ -567,14 +563,8 @@ pub fn source_path(path: &str) -> Option<std::path::PathBuf> {
/// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as
/// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers
/// that `&` writes in scientific notation as their 15 digits in full.
/// `delimiter` `None` writes a tab-separated file (`.tsv`, `.txt`).
fn csv(wb: &Workbook, sh: &Sheet, delimiter: Option<u8>) -> Result<Vec<u8>> {
let text = |c| crate::display::value_text(wb, sh, c);
match delimiter {
Some(d) => gridcraft_xlsx::write_csv(sh, d, text),
None => gridcraft_xlsx::write_tsv(sh, text),
}
.map_err(|e| EngineError::Other(e.to_string()))
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string()))
}
/// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and
-58
View File
@@ -518,64 +518,6 @@ fn csv_save_keeps_the_separator_it_was_opened_with() {
assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs);
}
/// #1446: File › Open honours Excel's `sep=` first line; saved again, the file opens in the same
/// columns. A `.txt` file is read with tabs, so its `sep=` line stays data.
#[test]
fn csv_open_honours_a_sep_line_and_saves_a_file_that_reopens_in_columns() {
let (wb, _) = open_bytes("parts.csv", b"sep=|\r\nPart|Note\r\n1|a,b\r\n").unwrap();
let sh = wb.sheet(0).unwrap();
let text = |a: &str| sh.value(CellRef::parse(a).unwrap()).as_text().map(str::to_string);
assert_eq!((text("A1"), text("B1"), text("B2")), (Some("Part".into()), Some("Note".into()), Some("a,b".into())));
let saved = save_bytes(&wb, "parts.csv").unwrap();
assert_eq!(String::from_utf8(saved.clone()).unwrap(), "Part,Note\r\n1,\"a,b\"\r\n");
let (again, _) = open_bytes("parts.csv", &saved).unwrap();
assert_eq!(again.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()).as_text(), Some("a,b"));
// `sep=;` keeps its semicolons, as a semicolon file does.
let (semi, _) = open_bytes("semi.csv", b"sep=;\r\na;b\r\n").unwrap();
assert_eq!(save_bytes(&semi, "semi.csv").unwrap(), b"a;b\r\n");
let (txt, _) = open_bytes("list.txt", b"sep=|\r\na\tb\r\n").unwrap();
assert_eq!(txt.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=|"));
}
/// A first cell that reads like a `sep=` line needs one of its own only in a CSV. A `.tsv` is read
/// with tabs given, so a `sep=` line there would come back as an extra row above the data.
#[test]
fn csv_save_names_its_delimiter_when_reopening_would_pick_another() {
let cells = |wb: &Workbook| {
let sh = wb.sheet(0).unwrap();
(0..2).map(|c| sh.value(CellRef::new(0, c)).as_text().map(str::to_string)).collect::<Vec<_>>()
};
// Read with `;`; saved, `a,b` loses its quotes and the line has one comma and one semicolon,
// which detection alone would read as comma-separated.
let (wb, _) = open_bytes("tie.csv", b"sep=;\r\n\"a,b\";x\r\n").unwrap();
let saved = save_bytes(&wb, "tie.csv").unwrap();
assert_eq!(saved, b"sep=;\r\na,b;x\r\n");
assert_eq!(cells(&open_bytes("tie.csv", &saved).unwrap().0), [Some("a,b".into()), Some("x".into())]);
// `|` is saved as commas; semicolons in the values would make detection pick `;`.
let (wb, _) = open_bytes("pipe.csv", b"sep=|\r\na;b;c|d;e;f\r\n").unwrap();
let saved = save_bytes(&wb, "pipe.csv").unwrap();
assert_eq!(saved, b"sep=,\r\na;b;c,d;e;f\r\n");
assert_eq!(cells(&open_bytes("pipe.csv", &saved).unwrap().0), [Some("a;b;c".into()), Some("d;e;f".into())]);
}
#[test]
fn tsv_save_writes_no_sep_line_and_reopens_in_place() {
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("sep=;"));
sh.set_value(CellRef::new(1, 0), gridcraft_core::Value::text("x"));
let saved = save_bytes(&wb, "list.tsv").unwrap();
assert_eq!(saved, b"sep=;\r\nx\r\n");
let (again, _) = open_bytes("list.tsv", &saved).unwrap();
let text = |r: u32| again.sheet(0).unwrap().value(CellRef::new(r, 0)).as_text().map(str::to_string);
assert_eq!((text(0), text(1)), (Some("sep=;".into()), Some("x".into())));
// Saved as CSV, the same sheet keeps its protective line, which reading drops again.
let csv = save_bytes(&wb, "list.csv").unwrap();
assert_eq!(csv, b"sep=,\r\nsep=;\r\nx\r\n");
let (again, _) = open_bytes("list.csv", &csv).unwrap();
assert_eq!(again.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=;"));
}
#[test]
fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() {
let mut wb = Workbook::new();
-4
View File
@@ -206,9 +206,6 @@ 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
@@ -367,7 +364,6 @@ impl DocState {
sheet_selections: vec![],
unlocked_ranges: vec![],
content_kind: None,
read_only_source: None,
scripts_trusted,
trust,
touched: None,
+1 -47
View File
@@ -9,9 +9,7 @@
//! external addresses; only the host, after showing the address and getting OK from the user,
//! opens one through [`crate::Session::open_confirmed_link`], which no command reaches.
use gridcraft_core::{CellRef, RangeRef};
use gridcraft_formula::Expr;
use gridcraft_model::{Hyperlink, Workbook};
use gridcraft_core::RangeRef;
use serde_json::{Value as Json, json};
use crate::{EngineError, Result, Session, UiRequest};
@@ -88,50 +86,6 @@ pub fn classify(target: &str) -> LinkKind {
}
}
/// The link of a cell: the one stored with it, or, for a cell whose formula is `HYPERLINK(target, …)`,
/// the target that formula currently evaluates to. A scheme-less web address (`google.com`) is
/// opened over `https`, as Excel does.
pub fn cell_link(wb: &Workbook, sheet: usize, at: CellRef) -> Option<Hyperlink> {
let sh = wb.sheet(sheet)?;
if let Some(h) = sh.hyperlinks.get(&at) {
return Some(h.clone());
}
let expr = sh.cell(at)?.formula.as_ref()?.expr()?;
let Expr::Call(name, args) = &expr else { return None };
if name != "HYPERLINK" {
return None;
}
let value = gridcraft_calc::evaluate_expr(wb, sheet, at, args.first()?);
let target = value.display().trim().to_string();
if target.is_empty() || matches!(value, gridcraft_core::Value::Error(_)) {
return None;
}
// a defined name or a table of that spelling (`sales.data`) stays an internal target
let internal_name = wb.name(&target, sheet).is_some() || wb.table(&target).is_some();
let target = if looks_like_web_address(&target) && !internal_name { format!("https://{target}") } else { target };
let external = !matches!(classify(&target), LinkKind::Internal(_));
Some(Hyperlink { target, tooltip: None, external })
}
fn looks_like_web_address(t: &str) -> bool {
if t.contains(|c: char| c.is_whitespace() || matches!(c, '\\' | '!')) {
return false;
}
// the host ends at the path, query or fragment (`google.com/x`, `google.com?q=1`, `google.com#top`)
let host = t.split(['/', '?', '#']).next().unwrap_or(t);
// with an optional port (`example.com:8443`); any other colon is a scheme or a sheet reference
let host = match host.split_once(':') {
Some((h, port)) if !port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit()) => h,
Some(_) => return false,
None => host,
};
let Some((_, tld)) = host.rsplit_once('.') else { return false };
tld.len() >= 2
&& tld.chars().all(|c| c.is_ascii_alphabetic())
&& !["xlsx", "xlsm", "xlsb", "xls", "csv", "txt", "pdf", "doc", "docx"].contains(&tld.to_ascii_lowercase().as_str())
&& RangeRef::parse(t).is_none()
}
#[cfg(test)]
mod tests {
use super::*;
+3 -44
View File
@@ -10,7 +10,7 @@ use std::collections::{HashMap, HashSet};
use gridcraft_core::date::datetime_from_serial;
pub use gridcraft_core::quote_sheet;
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, number_to_text, split_sheet};
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, split_sheet};
use gridcraft_model::{
BorderLine, BorderStyle, Cell, Chart, Color, Fill, HAlign, NumFmt, PivotDataCell, PivotDateGroup, PivotField, PivotFilter, PivotFunc,
PivotItemRef, PivotLayout, PivotLookup, PivotShowAs, PivotSort, PivotTable, PivotValue, Series, Style, StyleId, Workbook,
@@ -32,6 +32,7 @@ pub use items::{distinct_labels, func_caption, item_label};
use output::data_cols_exceed_sheet;
pub use output::{CellKind, OutCell, Output, RowKind};
use output::{cell_style, look};
/// Largest source block read (cells).
pub const MAX_SOURCE_CELLS: u64 = 10_000_000;
/// Largest report written (cells).
@@ -60,52 +61,12 @@ pub struct Source {
/// Numeric with a date number format.
pub dates: Vec<bool>,
pub rows: Vec<Vec<Value>>,
/// The sheet row of each record (blank rows are skipped).
pub record_rows: Vec<u32>,
}
impl Source {
pub fn col(&self, name: &str) -> Option<usize> {
self.headers.iter().position(|h| h.eq_ignore_ascii_case(name))
}
/// Per record: the column's cell is a number whose own format is a date (Excel caches such
/// a number as `<d>` and sorts it after errors), and no cell of the column holds that number
/// with a non-date format: a number in any General cell is a number item, whatever the row
/// order or report filter. Looks up each distinct style once.
pub fn date_cells(&self, wb: &Workbook, col: usize) -> Vec<bool> {
let (Some(sh), Ok(off)) = (wb.sheet(self.sheet), u32::try_from(col)) else {
return vec![false; self.rows.len()];
};
let c = self.range.start.col + off;
let mut memo: HashMap<StyleId, bool> = HashMap::new();
let mut dates: Vec<bool> = self
.rows
.iter()
.zip(&self.record_rows)
.map(|(rec, &row)| {
rec.get(col).is_some_and(Value::is_number)
&& *memo
.entry(sh.style_id(CellRef::new(row, c)))
.or_insert_with_key(|id| crate::display::number_format(wb.styles.get(*id).num_fmt.as_str()).is_date())
})
.collect();
if !dates.contains(&true) {
return dates;
}
let number = |rec: &Vec<Value>| match rec.get(col) {
Some(Value::Number(n)) => Some(n.to_bits()),
_ => None,
};
let general: HashSet<u64> = dates.iter().zip(&self.rows).filter(|(d, _)| !**d).filter_map(|(_, rec)| number(rec)).collect();
if !general.is_empty() {
for (d, rec) in dates.iter_mut().zip(&self.rows) {
if *d && number(rec).is_some_and(|n| general.contains(&n)) {
*d = false;
}
}
}
dates
}
}
/// Absolute reference text for a range on a sheet: `Sheet1!$A$1:$E$20`.
@@ -198,7 +159,6 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
}
let w = headers.len();
let mut rows = Vec::new();
let mut record_rows = Vec::new();
let mut numeric = vec![true; w];
let mut any = vec![false; w];
if r.end.row > r.start.row {
@@ -219,7 +179,6 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
}
}
}
record_rows.push(row);
rows.push(rec);
}
}
@@ -227,7 +186,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result<So
*n = *n && *a;
}
let dates = numeric.iter().zip(formats.iter()).map(|(n, f)| *n && crate::display::parsed(f).is_date()).collect();
Ok(Source { sheet: si, range: r, headers, formats, numeric, dates, rows, record_rows })
Ok(Source { sheet: si, range: r, headers, formats, numeric, dates, rows })
}
/// Computes a PivotTable report from the workbook.
-2
View File
@@ -81,8 +81,6 @@ pub fn chart_series(sheet: &str, origin: CellRef, out: &Output) -> Vec<Series> {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
})
})
.collect()
+72 -228
View File
@@ -1,4 +1,4 @@
use super::items::{Acc, ByValue, FieldItems, build_tree, collect_siblings, date_flags, is_collapsed, item_label};
use super::items::{Acc, FieldItems, build_tree, collect_siblings, is_collapsed, item_label};
use super::output::{
AggMap, CellKind, ColKind, ColSpec, Ctx, Grid, Line, LineKind, Output, RowKind, ValSrc, caption, data_cols_exceed_sheet, flatten_cols,
};
@@ -83,8 +83,6 @@ struct AggregateInput<'a> {
filter_sets: &'a [Option<HashSet<String>>],
row_fmts: &'a [String],
col_fmts: &'a [String],
row_dates: &'a [Vec<bool>],
col_dates: &'a [Vec<bool>],
empty: bool,
}
@@ -121,14 +119,12 @@ fn aggregate_record(
return Ok(());
}
let mut row_path = Vec::with_capacity(input.rows.len());
for ((((column, field), items), fmt), dates) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts).zip(input.row_dates) {
let date = dates.get(ri).copied().unwrap_or(false);
row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri));
for (((column, field), items), fmt) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts) {
row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri));
}
let mut col_path = Vec::with_capacity(input.cols.len());
for ((((column, field), items), fmt), dates) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts).zip(input.col_dates) {
let date = dates.get(ri).copied().unwrap_or(false);
col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri));
for (((column, field), items), fmt) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts) {
col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri));
}
for row_depth in 0..=row_path.len() {
for col_depth in 0..=col_path.len() {
@@ -201,49 +197,23 @@ struct HeaderInput<'a> {
k: usize,
l: usize,
headers_on: bool,
row_caption: Option<&'a str>,
data_caption: Option<&'a str>,
col_caption: Option<&'a str>,
grand_caption: &'a str,
classic: bool,
show_values_row: bool,
}
fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
let HeaderInput {
vals,
row_fields,
col_fields,
col_items,
col_fmts,
vpos,
data_cols,
specs,
row_levels,
compact,
on_rows,
k,
l,
headers_on,
row_caption,
data_caption,
col_caption,
grand_caption,
classic,
show_values_row,
} = input;
let HeaderInput { vals, row_fields, col_fields, col_items, col_fmts, vpos, data_cols, specs, row_levels, compact, on_rows, k, l, headers_on } =
input;
let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default();
let row_header = |g: &mut Grid, r: usize| {
if row_levels == 0 || !headers_on {
return;
}
if compact {
g.set(r, 0, Value::text(row_caption.unwrap_or("Row Labels")), CellKind::Header, 0, None);
g.set(r, 0, Value::text("Row Labels"), CellKind::Header, 0, None);
} else {
// One column per row field, Σ Values (its caption, "Values" by default) at its place.
let mut names: Vec<&str> = row_fields.iter().map(|f| f.header()).collect();
// One column per row field, Σ Values ("Values") at its place.
let mut names: Vec<&str> = row_fields.iter().map(|f| f.source_col.as_str()).collect();
if let Some(p) = vpos {
names.insert(p.min(names.len()), data_caption.unwrap_or("Values"));
names.insert(p.min(names.len()), "Values");
}
for (i, name) in names.into_iter().enumerate() {
g.set(r, i, Value::text(name), CellKind::Header, 0, None);
@@ -253,23 +223,12 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
// ---- header rows
if col_fields.is_empty() {
let classic = classic && !compact && k == 1 && headers_on;
if classic {
let r = g.push_row(RowKind::Header)?;
g.set(r, 0, Value::text(val_name(0)), CellKind::Header, 0, None);
}
if !compact && k > 1 && !on_rows && show_values_row && headers_on {
let r = g.push_row(RowKind::Header)?;
g.set(r, l, Value::text(data_caption.unwrap_or("Values")), CellKind::Header, 0, None);
}
let r = g.push_row(RowKind::Header)?;
row_header(g, r);
for (j, (_, vi)) in data_cols.iter().enumerate() {
match vi {
Some(vi) => {
let caption = if classic { "Total".to_string() } else { val_name(*vi) };
g.set(r, l + j, Value::text(caption), CellKind::Header, 0, None);
}
Some(vi) => g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None),
// Values on rows, no column field: the one data column is the grand total.
None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None),
None => {}
}
@@ -280,11 +239,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None);
}
if headers_on {
let caption = if compact {
col_caption.unwrap_or("Column Labels").to_string()
} else {
col_fields.first().map(|f| f.header().to_string()).unwrap_or_default()
};
let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() };
g.set(cap, l, Value::text(caption), CellKind::Header, 0, None);
}
let levels = col_fields.len() + usize::from(k > 1 && !on_rows);
@@ -302,8 +257,8 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
let same = prev.is_some_and(|p| p.kind != ColKind::Grand && p.path.get(..=lv) == spec.path.get(..=lv));
if !same {
let Some(item) = col_items.get(lv).and_then(|fi| fi.get(it)) else { continue };
let fmt = if item.formatted && item.caption.is_none() { col_fmts.get(lv).cloned() } else { None };
g.set(first_level + lv, c, item.shown_value(), CellKind::ColLabel, 0, fmt);
let fmt = if item.formatted { col_fmts.get(lv).cloned() } else { None };
g.set(first_level + lv, c, item.value.clone(), CellKind::ColLabel, 0, fmt);
}
}
if k > 1
@@ -314,7 +269,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
}
ColKind::Subtotal => {
let lv = spec.path.len().saturating_sub(1);
let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.shown_label(*it))).unwrap_or_default();
let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.label(*it))).unwrap_or_default();
let text = match vi {
Some(vi) if k > 1 => caption(&label, &val_name(*vi)),
_ => caption(&label, "Total"),
@@ -324,7 +279,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
ColKind::Grand => {
let text = match vi {
Some(vi) if k > 1 => format!("Total {}", val_name(*vi)),
_ => grand_caption.to_string(),
_ => "Grand Total".to_string(),
};
g.set(first_level, c, Value::text(text), CellKind::ColLabel, 0, None);
}
@@ -337,6 +292,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> {
Ok(())
}
struct ValueLookup<'a> {
wb: &'a Workbook,
source: &'a Source,
@@ -583,11 +539,8 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
let filter_fmts: Vec<String> = filters.iter().map(|f| fmt_of(f.0)).collect();
let filter_sets: Vec<Option<HashSet<String>>> =
filters.iter().map(|(_, field, _, _)| field.selected.as_ref().map(|s| s.iter().map(|v| v.to_ascii_lowercase()).collect())).collect();
let field_fmt = |c: usize, f: &PivotField| f.number_format.clone().unwrap_or_else(|| fmt_of(c));
let row_fmts: Vec<String> = rows.iter().map(|(c, f)| field_fmt(*c, f)).collect();
let col_fmts: Vec<String> = cols.iter().map(|(c, f)| field_fmt(*c, f)).collect();
let row_dates: Vec<Vec<bool>> = rows.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect();
let col_dates: Vec<Vec<bool>> = cols.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect();
let row_fmts: Vec<String> = rows.iter().map(|(c, _)| fmt_of(*c)).collect();
let col_fmts: Vec<String> = cols.iter().map(|(c, _)| fmt_of(*c)).collect();
let aggregate = aggregate_source(
AggregateInput {
wb,
@@ -602,83 +555,33 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
filter_sets: &filter_sets,
row_fmts: &row_fmts,
col_fmts: &col_fmts,
row_dates: &row_dates,
col_dates: &col_dates,
empty,
},
&mut probe,
)?;
let AggregateData { mut row_items, mut col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate;
for (fi, (_, f)) in row_items.iter_mut().zip(rows.iter()) {
fi.apply(f);
}
for (fi, (_, f)) in col_items.iter_mut().zip(cols.iter()) {
fi.apply(f);
}
let get = |rp: &[u32], cp: &[u32], vi: usize| -> Option<Value> {
let (vs, v) = vals.get(vi)?;
let accs = aggs.get(&(rp.to_vec(), cp.to_vec()))?;
match vs {
ValSrc::Col(_) => accs.get(vi).map(|a| a.result(v.func)),
ValSrc::Calc(i) => {
let sum = |name: &str| -> Value {
src.col(name)
.and_then(|c| extra.iter().position(|x| *x == c))
.and_then(|j| accs.get(k + j))
.map(|a| a.result(PivotFunc::Sum))
.unwrap_or(Value::Number(0.0))
};
Some(calc.value(wb, *i, &sum))
}
}
};
let AggregateData { row_items, col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate;
// ---- axes
let row_fields: Vec<&PivotField> = rows.iter().map(|(_, f)| *f).collect();
let col_fields: Vec<&PivotField> = cols.iter().map(|(_, f)| *f).collect();
let row_paths: Vec<&[u32]> = row_set.iter().map(Vec::as_slice).collect();
let col_paths: Vec<&[u32]> = col_set.iter().map(Vec::as_slice).collect();
// The other-axis path a sort scope names: its items of the other axis's fields, outer first,
// up to the first field it doesn't name. A scope naming an item that isn't there sorts by the
// grand total, as the writer then drops it.
let scope_path = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| -> Vec<u32> {
let mut path = Vec::new();
for ((_, o), oi) in others.iter().zip(other_items) {
let Some(e) = f.sort_scope.iter().find(|e| e.is_of(o)) else { break };
match oi.find(&e.item) {
Some(i) => path.push(i),
None => return Vec::new(),
}
}
path
};
let sorting = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| {
let vi = f.sort_by.as_deref().and_then(|n| vals.iter().position(|(_, v)| v.name.eq_ignore_ascii_case(n)))?;
Some((vi, scope_path(f, others, other_items)))
};
let row_value = |p: &[u32], other: &[u32], vi: usize| get(p, other, vi).as_ref().and_then(Value::as_f64);
let col_value = |p: &[u32], other: &[u32], vi: usize| get(other, p, vi).as_ref().and_then(Value::as_f64);
let row_by = ByValue { fields: row_fields.iter().map(|f| sorting(f, &cols, &col_items)).collect(), value: &row_value };
let col_by = ByValue { fields: col_fields.iter().map(|f| sorting(f, &rows, &row_items)).collect(), value: &col_value };
let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items, &row_by);
let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items, &col_by);
let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items);
let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items);
let mut siblings: HashMap<Vec<u32>, Vec<u32>> = HashMap::new();
collect_siblings(&row_tree, &mut Vec::new(), &mut siblings);
let level0: Vec<u32> = row_tree.iter().map(|n| n.item).collect();
let val_names: Vec<String> = vals.iter().map(|(_, v)| v.name.clone()).collect();
let grand_caption = pt.grand_total_caption.as_deref().unwrap_or("Grand Total");
let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone(), vpos, val_names: val_names.clone() };
let mut lines: Vec<Line> = Vec::new();
if row_levels == 0 {
lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![], vi: None });
} else {
if pt.layout == PivotLayout::Tabular {
ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut Vec::new(), &mut lines);
ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines);
} else {
ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut Vec::new(), &mut lines);
ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut lines);
}
// With only Σ Values in Rows its items are the totals already.
if pt.grand_totals_cols && !rows.is_empty() {
@@ -693,7 +596,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
if on_rows {
lines.extend(val_names.iter().enumerate().map(|(vi, name)| grand(format!("Total {name}"), Some(vi))));
} else {
lines.push(grand(grand_caption.into(), None));
lines.push(grand("Grand Total".into(), None));
}
}
}
@@ -701,7 +604,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
if cols.is_empty() {
specs.push(ColSpec { kind: ColKind::Leaf, path: vec![] });
} else {
flatten_cols(&col_tree, 0, &col_fields, &col_items, pt, &mut Vec::new(), &mut specs);
flatten_cols(&col_tree, 0, &col_fields, &col_items, pt.subtotals, &mut Vec::new(), &mut specs);
if pt.grand_totals_rows {
specs.push(ColSpec { kind: ColKind::Grand, path: vec![] });
}
@@ -775,12 +678,6 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
k,
l,
headers_on: pt.show_headers,
row_caption: pt.row_header_caption.as_deref(),
data_caption: pt.data_caption.as_deref(),
col_caption: pt.col_header_caption.as_deref(),
grand_caption: pt.grand_total_caption.as_deref().unwrap_or("Grand Total"),
classic: pt.classic_layout,
show_values_row: pt.show_values_row,
},
)?;
let val_name = |vi: usize| vals.get(vi).map(|(_, value)| value.name.clone()).unwrap_or_default();
@@ -817,7 +714,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
return None;
}
let mut parts: Vec<String> =
spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.shown_label(*it)).unwrap_or_default()).collect();
spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.label(*it)).unwrap_or_default()).collect();
if let Some(vi) = vi
&& (k > 1 || parts.is_empty())
{
@@ -836,6 +733,15 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
} else {
Some(row_levels.saturating_sub(1) as u32)
};
let item_refs = |fields: &[&PivotField], items: &[FieldItems], path: &[u32]| -> Vec<PivotItemRef> {
path.iter()
.enumerate()
.filter_map(|(d, it)| {
let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?);
Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() })
})
.collect()
};
let mut data: Vec<PivotDataCell> = Vec::new();
for line in &lines {
let rk = match line.kind {
@@ -858,102 +764,40 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro
if !line.values {
continue;
}
fill_line_values(
&mut g,
r,
line,
&data_cols,
&specs,
&vals,
&data_fmt,
l,
ck.1,
pt,
&ctx,
&col_fields,
&col_items,
&lookup,
&level0,
&siblings,
&show_cache,
&mut probe,
&mut data,
)?;
let rp = line.path.as_slice();
for (j, (si, col_vi)) in data_cols.iter().enumerate() {
let line_vi = col_vi.or(line.vi);
let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue };
let Some((_, vdef)) = vals.get(*vi) else { continue };
let cp = spec.path.as_slice();
let Some(raw) = lookup.get(rp, cp, *vi) else { continue };
let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0: &level0, siblings: &siblings, cache: &show_cache };
let shown = show_value(vdef, raw, &lookup, &context);
// Every value cell of the report is indexed, so a report that needs more cells than
// the index cap is rejected outright — never written with a truncated index that
// would answer #REF! for the values the sheet shows.
if data.len() >= MAX_INDEXED_CELLS {
return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells."));
}
let mut items = item_refs(&ctx.rows, &ctx.row_items, rp);
items.extend(item_refs(&col_fields, &col_items, cp));
data.push(PivotDataCell {
data_field: vdef.name.clone(),
source_col: vdef.source_col.clone(),
items,
row: u32::try_from(r).unwrap_or(u32::MAX),
col: u32::try_from(l + j).unwrap_or(u32::MAX),
});
if let Some(pr) = probe.as_deref_mut() {
if pr.at == Some((r, l + j)) {
pr.hit = Some((rp.to_vec(), cp.to_vec()));
}
if let Some(cells) = pr.cells.as_mut() {
cells.insert((r, l + j));
}
}
g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten());
}
}
Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col, data })
}
#[allow(clippy::too_many_arguments)]
fn fill_line_values(
g: &mut Grid,
r: usize,
line: &Line,
data_cols: &[(usize, Option<usize>)],
specs: &[ColSpec],
vals: &[(ValSrc, &PivotValue)],
data_fmt: &[Option<String>],
l: usize,
ck: CellKind,
pt: &PivotTable,
ctx: &Ctx<'_>,
col_fields: &[&PivotField],
col_items: &[FieldItems],
lookup: &ValueLookup<'_>,
level0: &[u32],
siblings: &HashMap<Vec<u32>, Vec<u32>>,
show_cache: &ShowCache,
probe: &mut Option<&mut Probe>,
data: &mut Vec<PivotDataCell>,
) -> Result<(), String> {
let rp = line.path.as_slice();
for (j, (si, col_vi)) in data_cols.iter().enumerate() {
let line_vi = col_vi.or(line.vi);
let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue };
let Some((_, vdef)) = vals.get(*vi) else { continue };
let cp = spec.path.as_slice();
let Some(raw) = lookup.get(rp, cp, *vi) else {
// No records: blank, or the "For empty cells show" caption (a number when it
// reads as one, as Excel stores `missingCaption="0"`).
if let Some(c) = &pt.empty_caption {
let v = c.trim().parse::<f64>().ok().filter(|x| x.is_finite()).map(Value::number).unwrap_or_else(|| Value::text(c.as_str()));
let fmt = if matches!(v, Value::Number(_)) { data_fmt.get(*vi).cloned().flatten() } else { None };
g.set(r, l + j, v, ck, 0, fmt);
}
continue;
};
let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0, siblings, cache: show_cache };
let shown = show_value(vdef, raw, lookup, &context);
if data.len() >= MAX_INDEXED_CELLS {
return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells."));
}
let mut items = item_refs(&ctx.rows, &ctx.row_items, rp);
items.extend(item_refs(col_fields, col_items, cp));
data.push(PivotDataCell {
data_field: vdef.name.clone(),
source_col: vdef.source_col.clone(),
items,
row: u32::try_from(r).unwrap_or(u32::MAX),
col: u32::try_from(l + j).unwrap_or(u32::MAX),
});
if let Some(pr) = probe.as_deref_mut() {
if pr.at == Some((r, l + j)) {
pr.hit = Some((rp.to_vec(), cp.to_vec()));
}
if let Some(cells) = pr.cells.as_mut() {
cells.insert((r, l + j));
}
}
g.set(r, l + j, shown, ck, 0, data_fmt.get(*vi).cloned().flatten());
}
Ok(())
}
fn item_refs(fields: &[&PivotField], items: &[FieldItems], path: &[u32]) -> Vec<PivotItemRef> {
path.iter()
.enumerate()
.filter_map(|(d, it)| {
let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?);
Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() })
})
.collect()
}
+18 -99
View File
@@ -1,9 +1,6 @@
use std::collections::HashSet;
use super::{
CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial,
number_to_text,
};
use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial};
// ---------------------------------------------------------------- items
@@ -17,20 +14,6 @@ pub(super) struct Item {
first: usize,
/// The value is a number shown with the source format.
pub(super) formatted: bool,
/// The item's custom name (a renamed item).
pub(super) caption: Option<String>,
/// Position in the field's manual item order.
rank: Option<usize>,
}
impl Item {
/// The value shown: the custom name, else the item's value.
pub(super) fn shown_value(&self) -> Value {
self.caption.as_deref().map(Value::text).unwrap_or_else(|| self.value.clone())
}
pub(super) fn shown_label(&self) -> &str {
self.caption.as_deref().unwrap_or(&self.label)
}
}
#[derive(Default)]
@@ -39,15 +22,12 @@ pub(super) struct FieldItems {
index: HashMap<String, u32>,
}
/// Sort classes: numbers, text, logicals, errors, dates (a number whose own cell has a date
/// format, which Excel caches as `<d>` and sorts after errors), blanks.
fn cmp_items(a: &Item, b: &Item) -> Ordering {
a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| gridcraft_core::compare_text(&a.text, &b.text))
}
/// (identity key, item) for a source value under a field's date grouping; `date` marks a number
/// whose cell has a date format.
fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> (String, Item) {
/// (identity key, item) for a source value under a field's date grouping.
fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> (String, Item) {
let it = |value: Value, label: String, class: u8, num: f64, formatted: bool| Item {
text: label.to_lowercase(),
value,
@@ -56,11 +36,9 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: b
num,
first,
formatted,
caption: None,
rank: None,
};
match v {
Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 5, 0.0, false)),
Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)),
Value::Number(n) => {
if group != PivotDateGroup::None
&& let Some(dt) = datetime_from_serial(wb.date_system, *n)
@@ -77,9 +55,8 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: b
};
return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false));
}
let shown = crate::display::format(v, fmt, wb);
let class = if date { 4 } else { 0 };
(format!("n{}", n.to_bits()), it(v.clone(), shown.text, class, *n, true))
let label = crate::display::format(v, fmt, wb).text;
(format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true))
}
Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)),
Value::Bool(b) => {
@@ -87,13 +64,13 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: b
(format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false))
}
Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)),
Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, date, first),
Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first),
}
}
impl FieldItems {
pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> u32 {
let (key, item) = make_item(wb, v, group, fmt, date, first);
pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> u32 {
let (key, item) = make_item(wb, v, group, fmt, first);
if let Some(i) = self.index.get(&key) {
return *i;
}
@@ -108,50 +85,20 @@ impl FieldItems {
pub(super) fn label(&self, i: u32) -> String {
self.get(i).map(|x| x.label.clone()).unwrap_or_default()
}
pub(super) fn shown_label(&self, i: u32) -> String {
self.get(i).map(|x| x.shown_label().to_string()).unwrap_or_default()
}
/// The item a setting names by label (or, for a number item, its unformatted number text).
pub(super) fn find(&self, label: &str) -> Option<u32> {
let l = label.to_lowercase();
let i = self.items.iter().position(|it| it.text == l || (it.formatted && number_to_text(it.num).to_lowercase() == l))?;
u32::try_from(i).ok()
}
/// Applies a field's renamed items and manual item order. Settings name items by label; a
/// number item also matches its unformatted number text (how a file's cache names it).
pub(super) fn apply(&mut self, f: &PivotField) {
if f.item_captions.is_empty() && f.item_order.is_empty() {
return;
}
let mut order: HashMap<String, usize> = HashMap::new();
for (i, l) in f.item_order.iter().enumerate() {
order.entry(l.to_lowercase()).or_insert(i);
}
let mut captions: HashMap<String, &str> = HashMap::new();
for (l, c) in &f.item_captions {
captions.entry(l.to_lowercase()).or_insert(c.as_str());
}
for it in &mut self.items {
let raw = if it.formatted { Some(number_to_text(it.num).to_lowercase()) } else { None };
it.rank = order.get(&it.text).or_else(|| raw.as_ref().and_then(|r| order.get(r))).copied();
it.caption = captions.get(&it.text).or_else(|| raw.as_ref().and_then(|r| captions.get(r))).map(|c| c.to_string());
}
}
}
/// The label of a source value under a date grouping (for filters and field lists).
pub fn item_label(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str) -> String {
make_item(wb, v, group, fmt, false, 0).1.label
make_item(wb, v, group, fmt, 0).1.label
}
/// Distinct item labels of a source column, sorted like the field list shows them.
pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup, limit: usize) -> Vec<String> {
let mut fi = FieldItems::default();
let fmt = src.formats.get(col).map(String::as_str).unwrap_or("General");
let dates = date_flags(wb, src, col, group);
for (i, r) in src.rows.iter().enumerate() {
if let Some(v) = r.get(col) {
fi.intern(wb, v, group, fmt, dates.get(i).copied().unwrap_or(false), i);
fi.intern(wb, v, group, fmt, i);
}
if fi.items.len() > 100_000 {
break;
@@ -162,11 +109,6 @@ pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDate
items.into_iter().take(limit).map(|i| i.label).collect()
}
/// [`Source::date_cells`] for an ungrouped field; a date-grouped field doesn't use them.
pub(super) fn date_flags(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup) -> Vec<bool> {
if group == PivotDateGroup::None { src.date_cells(wb, col) } else { Vec::new() }
}
// ---------------------------------------------------------------- aggregation
#[derive(Clone, Debug, Default)]
@@ -310,17 +252,7 @@ pub(super) struct Node {
pub(super) children: Vec<Node>,
}
/// Sorting of an axis by value fields: per axis field, the value field it sorts by and the path
/// on the other axis whose values it uses (empty = the total); and the value of an axis path at
/// an other-axis path.
pub(super) type ValueLookup<'a> = &'a dyn Fn(&[u32], &[u32], usize) -> Option<f64>;
pub(super) struct ByValue<'a> {
pub(super) fields: Vec<Option<(usize, Vec<u32>)>>,
pub(super) value: ValueLookup<'a>,
}
pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems], by_value: &ByValue) -> Vec<Node> {
pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec<Node> {
let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] };
let mut order: Vec<u32> = Vec::new();
let mut groups: HashMap<u32, Vec<&[u32]>> = HashMap::new();
@@ -333,36 +265,23 @@ pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField],
g.push(p);
}
}
let vi = by_value.fields.get(depth).and_then(Option::as_ref).filter(|_| field.sort != PivotSort::None);
let mut nodes: Vec<(Option<f64>, Node)> = order
let mut nodes: Vec<Node> = order
.into_iter()
.map(|it| {
let ps = groups.remove(&it).unwrap_or_default();
let key = vi.and_then(|(vi, other)| ps.first().and_then(|p| p.get(..=depth)).and_then(|p| (by_value.value)(p, other, *vi)));
(key, Node { item: it, children: build_tree(&ps, depth + 1, fields, items, by_value) })
Node { item: it, children: build_tree(&ps, depth + 1, fields, items) }
})
.collect();
let by_label = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) {
let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) {
(Some(x), Some(y)) => match field.sort {
PivotSort::Asc => cmp_items(x, y),
PivotSort::Desc => cmp_items(y, x),
PivotSort::None => x.rank.unwrap_or(usize::MAX).cmp(&y.rank.unwrap_or(usize::MAX)).then_with(|| {
// Date groups are in date order, like the groups Excel's cache lists.
if field.date_group == PivotDateGroup::None { x.first.cmp(&y.first) } else { cmp_items(x, y) }
}),
PivotSort::None => x.first.cmp(&y.first),
},
_ => Ordering::Equal,
};
// By value: numbers in the sort direction, then items without a number; ties by label.
let by_key = |a: &Option<f64>, b: &Option<f64>| match (a, b) {
(Some(x), Some(y)) if field.sort == PivotSort::Desc => y.total_cmp(x),
(Some(x), Some(y)) => x.total_cmp(y),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
};
nodes.sort_by(|(ka, a), (kb, b)| by_key(ka, kb).then_with(|| by_label(a, b)));
nodes.into_iter().map(|(_, n)| n).collect()
nodes.sort_by(by);
nodes
}
pub(super) fn is_collapsed(field: &PivotField, label: &str) -> bool {
+71 -98
View File
@@ -151,22 +151,11 @@ pub(super) struct Ctx<'a> {
pub(super) val_names: Vec<String>,
}
/// A label cell of a report line: (column, value, indent, number format).
type Label = (usize, Value, u8, Option<String>);
/// Whether an axis field shows subtotals (its own setting, else the table's).
pub(super) fn shows_subtotals(pt: &PivotTable, f: Option<&&PivotField>) -> bool {
f.and_then(|f| f.subtotal).unwrap_or(pt.subtotals)
}
impl Ctx<'_> {
/// (shown value, number format, item label, shown label) of a row item.
fn label_cell(&self, depth: usize, item: u32) -> (Value, Option<String>, String, String) {
let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else {
return (Value::Empty, None, String::new(), String::new());
};
let fmt = if it.formatted && it.caption.is_none() { self.row_fmts.get(depth).cloned() } else { None };
(it.shown_value(), fmt, it.label.clone(), it.shown_label().to_string())
fn label_cell(&self, depth: usize, item: u32) -> (Value, Option<String>, String) {
let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) };
let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None };
(it.value.clone(), fmt, it.label.clone())
}
/// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form.
@@ -195,87 +184,86 @@ impl Ctx<'_> {
/// The Σ Values level at row field depth `depth`: one item per value field, each followed by
/// the row fields below it (`nodes`) or, innermost, holding that value.
fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec<u32>, repeat: &mut Vec<Label>, out: &mut Vec<Line>) {
fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
let (col, indent) = self.level_cell(depth);
for (vi, name) in self.val_names.iter().enumerate() {
let mut labels = repeat.clone();
labels.push((col, Value::text(name.as_str()), indent, None));
let labels = vec![(col, Value::text(name.as_str()), indent, None)];
let leaf = nodes.is_empty();
out.push(Line { kind: LineKind::Item(!leaf), leaf, path: prefix.clone(), values: leaf, labels, vi: Some(vi) });
if !leaf {
self.flatten(nodes, depth, Some(vi), prefix, repeat, out);
self.flatten(nodes, depth, Some(vi), prefix, out);
}
}
}
/// Compact and Outline rows. `repeat` holds the labels of enclosing items repeated on each
/// row (Outline, Repeat Item Labels).
pub(super) fn flatten(
&self,
nodes: &[Node],
depth: usize,
vi: Option<usize>,
prefix: &mut Vec<u32>,
repeat: &mut Vec<Label>,
out: &mut Vec<Line>,
) {
pub(super) fn flatten(&self, nodes: &[Node], depth: usize, vi: Option<usize>, prefix: &mut Vec<u32>, out: &mut Vec<Line>) {
if self.values_here(depth, vi) {
self.flatten_values(nodes, depth, prefix, repeat, out);
self.flatten_values(nodes, depth, prefix, out);
return;
}
let n = self.rows.len();
let outline = self.pt.layout == PivotLayout::Outline;
let field = self.rows.get(depth);
let subtotals = shows_subtotals(self.pt, field);
// Σ Values still to come below this level: totals need one line per value field.
let values_below = vi.is_none() && self.vpos.is_some();
let (col, indent) = self.level_cell(depth + usize::from(vi.is_some() && self.vpos.is_some()));
for node in nodes {
prefix.push(node.item);
let (v, fmt, label, shown) = self.label_cell(depth, node.item);
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
let (v, fmt, label) = self.label_cell(depth, node.item);
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
let leaf = depth + 1 >= n || collapsed || node.children.is_empty();
let mut labels = repeat.clone();
labels.push((col, v.clone(), indent, fmt.clone()));
let pushed = !leaf && outline && field.is_some_and(|f| f.repeat_labels);
if leaf && !values_below {
out.push(Line { kind: LineKind::Item(depth + 1 < n), leaf: true, path: prefix.clone(), values: true, labels, vi });
out.push(Line {
kind: LineKind::Item(depth + 1 < n),
leaf: true,
path: prefix.clone(),
values: true,
labels: vec![(col, v, indent, fmt)],
vi,
});
} else if leaf {
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: false, labels, vi });
out.push(Line {
kind: LineKind::Item(true),
leaf: false,
path: prefix.clone(),
values: false,
labels: vec![(col, v, indent, fmt)],
vi,
});
// Outline gives each level its own column, so the captions go in the Values
// column even when the levels between are collapsed away.
let level = if outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 };
self.flatten_values(&[], level, prefix, repeat, out);
let level = if self.pt.layout == PivotLayout::Outline { self.vpos.unwrap_or(depth + 1) } else { depth + 1 };
self.flatten_values(&[], level, prefix, out);
} else if values_below {
// Subtotals per value field, below the group (one line can't hold them all).
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: false, labels, vi });
if pushed {
repeat.push((col, v, indent, fmt));
}
self.flatten(&node.children, depth + 1, None, prefix, repeat, out);
if pushed {
repeat.pop();
}
if subtotals {
self.value_subtotals(col, indent, &shown, prefix, out);
out.push(Line {
kind: LineKind::Item(true),
leaf: false,
path: prefix.clone(),
values: false,
labels: vec![(col, v, indent, fmt)],
vi,
});
self.flatten(&node.children, depth + 1, None, prefix, out);
if self.pt.subtotals {
self.value_subtotals(col, indent, &label, prefix, out);
}
} else {
let top = subtotals && self.pt.subtotals_top;
out.push(Line { kind: LineKind::Item(true), leaf: false, path: prefix.clone(), values: top, labels, vi });
if pushed {
repeat.push((col, v, indent, fmt));
}
self.flatten(&node.children, depth + 1, vi, prefix, repeat, out);
if pushed {
repeat.pop();
}
if subtotals && !self.pt.subtotals_top {
let top = self.pt.subtotals && self.pt.subtotals_top;
out.push(Line {
kind: LineKind::Item(true),
leaf: false,
path: prefix.clone(),
values: top,
labels: vec![(col, v, indent, fmt)],
vi,
});
self.flatten(&node.children, depth + 1, vi, prefix, out);
if self.pt.subtotals && !self.pt.subtotals_top {
out.push(Line {
kind: LineKind::Subtotal,
leaf: false,
path: prefix.clone(),
values: true,
labels: vec![(col, Value::text(caption(&shown, "Total")), indent, None)],
labels: vec![(col, Value::text(caption(&label, "Total")), indent, None)],
vi,
});
}
@@ -290,73 +278,59 @@ impl Ctx<'_> {
nodes: &[Node],
depth: usize,
prefix: &mut Vec<u32>,
pending: &[Label],
repeat: &mut Vec<Label>,
pending: &[(usize, Value, u8, Option<String>)],
out: &mut Vec<Line>,
) {
for (vi, name) in self.val_names.iter().enumerate() {
let mut labels: Vec<Label> = if vi == 0 { pending.to_vec() } else { repeat.clone() };
let mut labels: Vec<(usize, Value, u8, Option<String>)> = if vi == 0 { pending.to_vec() } else { vec![] };
labels.push((depth, Value::text(name.as_str()), 0, None));
if nodes.is_empty() {
out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi: Some(vi) });
} else {
self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, repeat, out);
self.flatten_tabular(nodes, depth, Some(vi), prefix, &labels, out);
}
}
}
/// Tabular rows: an item's label sits on its first child's row (`pending`); `repeat` holds
/// the labels of enclosing items repeated on the other rows (Repeat Item Labels).
#[allow(clippy::too_many_arguments)]
pub(super) fn flatten_tabular(
&self,
nodes: &[Node],
depth: usize,
vi: Option<usize>,
prefix: &mut Vec<u32>,
pending: &[Label],
repeat: &mut Vec<Label>,
pending: &[(usize, Value, u8, Option<String>)],
out: &mut Vec<Line>,
) {
if self.values_here(depth, vi) {
self.flatten_tabular_values(nodes, depth, prefix, pending, repeat, out);
self.flatten_tabular_values(nodes, depth, prefix, pending, out);
return;
}
let n = self.rows.len();
let field = self.rows.get(depth);
let values_below = vi.is_none() && self.vpos.is_some();
let col = depth + usize::from(vi.is_some() && self.vpos.is_some());
for (i, node) in nodes.iter().enumerate() {
prefix.push(node.item);
let (v, fmt, label, shown) = self.label_cell(depth, node.item);
let mut labels: Vec<Label> = if i == 0 { pending.to_vec() } else { repeat.clone() };
labels.push((col, v.clone(), 0, fmt.clone()));
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
let (v, fmt, label) = self.label_cell(depth, node.item);
let mut labels: Vec<(usize, Value, u8, Option<String>)> = if i == 0 { pending.to_vec() } else { vec![] };
labels.push((col, v, 0, fmt));
let collapsed = depth + 1 < n && self.rows.get(depth).is_some_and(|f| is_collapsed(f, &label));
if depth + 1 >= n || collapsed || node.children.is_empty() {
if values_below {
self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, repeat, out);
self.flatten_tabular_values(&[], self.vpos.unwrap_or(depth + 1), prefix, &labels, out);
} else {
out.push(Line { kind: LineKind::Item(false), leaf: true, path: prefix.clone(), values: true, labels, vi });
}
} else {
let pushed = field.is_some_and(|f| f.repeat_labels);
if pushed {
repeat.push((col, v, 0, fmt));
}
self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, repeat, out);
if pushed {
repeat.pop();
}
let subtotals = shows_subtotals(self.pt, field);
if subtotals && values_below {
self.value_subtotals(col, 0, &shown, prefix, out);
} else if subtotals {
self.flatten_tabular(&node.children, depth + 1, vi, prefix, &labels, out);
if self.pt.subtotals && values_below {
self.value_subtotals(col, 0, &label, prefix, out);
} else if self.pt.subtotals {
out.push(Line {
kind: LineKind::Subtotal,
leaf: false,
path: prefix.clone(),
values: true,
labels: vec![(col, Value::text(caption(&shown, "Total")), 0, None)],
labels: vec![(col, Value::text(caption(&label, "Total")), 0, None)],
vi,
});
}
@@ -371,21 +345,20 @@ pub(super) fn flatten_cols(
depth: usize,
fields: &[&PivotField],
items: &[FieldItems],
pt: &PivotTable,
subtotals: bool,
prefix: &mut Vec<u32>,
out: &mut Vec<ColSpec>,
) {
let n = fields.len();
let field = fields.get(depth);
for node in nodes {
prefix.push(node.item);
let label = items.get(depth).map(|fi| fi.label(node.item)).unwrap_or_default();
let collapsed = depth + 1 < n && field.is_some_and(|f| is_collapsed(f, &label));
let collapsed = depth + 1 < n && fields.get(depth).is_some_and(|f| is_collapsed(f, &label));
if depth + 1 >= n || collapsed || node.children.is_empty() {
out.push(ColSpec { kind: ColKind::Leaf, path: prefix.clone() });
} else {
flatten_cols(&node.children, depth + 1, fields, items, pt, prefix, out);
if shows_subtotals(pt, field) {
flatten_cols(&node.children, depth + 1, fields, items, subtotals, prefix, out);
if subtotals {
out.push(ColSpec { kind: ColKind::Subtotal, path: prefix.clone() });
}
}
-2
View File
@@ -111,8 +111,6 @@ fn sales(s: &mut Session) -> bool {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
}
}
+1 -34
View File
@@ -310,40 +310,7 @@ 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 {
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);
let filled = |c: CellRef| sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&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)));
+6 -221
View File
@@ -962,13 +962,11 @@ 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();
// 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();
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();
assert!(copied.get("html").is_none(), "an oversized escaped value must not produce partial HTML");
assert_eq!(copied["text"].as_str().unwrap().len(), 30 * 32_767 + 30);
assert_eq!(copied["text"].as_str().unwrap().len(), 1_000_001);
assert!(copied["text"].as_str().unwrap().ends_with("&\n"));
}
@@ -2166,7 +2164,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!A1:B3"})).unwrap();
s.execute("data.filter", json!({"range": "Prices!A2: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());
@@ -5591,75 +5589,6 @@ 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";
@@ -6376,58 +6305,6 @@ fn filtered_copy_with_many_runs_moves_notes_and_merges_with_their_rows() {
assert_eq!(sh.merges.iter().filter(|m| m.start.col >= 7).count(), 1);
}
#[test]
fn a_multi_level_pivot_chart_draws_one_label_per_point_after_saves() {
use gridcraft_model::{Anchor, Chart, ChartKind, LegendPos, Series, Workbook};
// Two levels of row labels in A4:B7, the outer one (country) on the left, as a PivotChart
// opened from a file keeps them when the innermost column holds its cache.
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
sh.name = "Graph".into();
sh.set_value(CellRef::new(2, 2), Value::from("Total"));
for (i, (outer, inner)) in [("Canada", "Ottawa"), ("", "Toronto"), ("USA", "Boston"), ("", "NYC")].iter().enumerate() {
let r = 3 + i as u32;
if !outer.is_empty() {
sh.set_value(CellRef::new(r, 0), Value::from(*outer));
}
sh.set_value(CellRef::new(r, 1), Value::from(*inner));
sh.set_value(CellRef::new(r, 2), Value::Number(i as f64 + 1.0));
}
sh.charts.push(Chart {
id: 1,
kind: ChartKind::ColumnClustered,
anchor: Anchor { cell: CellRef::new(0, 5), width: 480.0, height: 300.0, ..Anchor::default() },
title: None,
series: vec![Series {
name: Some("Graph!$C$3".into()),
categories: Some("Graph!$A$4:$B$7".into()),
values: "Graph!$C$4:$C$7".into(),
innermost_categories: true,
..Series::default()
}],
legend: LegendPos::Bottom,
data_labels: false,
data_table: None,
gridlines: true,
style: 2,
x_title: None,
y_title: None,
source: None,
by_rows: false,
pivot: Some("Graph!PivotTable1".into()),
first_slice_angle: 0,
hole_size: 50,
});
let labels = ["Ottawa", "Toronto", "Boston", "NYC"];
for _ in 0..2 {
wb = gridcraft_xlsx::read_xlsx(&gridcraft_xlsx::write_xlsx(&wb).unwrap()).unwrap().0;
let ch = &wb.sheet(0).unwrap().charts[0];
let s = &ch.series[0];
assert_eq!((s.name.as_deref(), s.categories.as_deref(), s.innermost_categories), (Some("Graph!$C$3"), Some("Graph!$A$4:$B$7"), true));
assert_eq!(gridcraft_chart::resolve(&wb, 0, ch).categories, labels);
}
}
#[test]
fn object_move_refuses_to_rotate_ink() {
let mut s = s();
@@ -6500,6 +6377,7 @@ fn editing_quote_prefixed_text_keeps_it_text() {
let d = s.doc().unwrap();
assert_eq!(crate::display::edit_text(&d.wb, d.wb.active().unwrap(), CellRef::parse("B1").unwrap()), "hello");
}
#[test]
fn csv_as_text_keeps_identifier_columns_as_written() {
let csv = "gtin,zip,flag,day\n8435392892278,01234,TRUE,2026-03-04\n";
@@ -8223,99 +8101,6 @@ fn history_charges_the_storage_of_empty_comment_replies() {
assert!(crate::sheet_text_bytes(&sheet) >= 500 * std::mem::size_of::<(String, String)>());
}
#[test]
fn tables_never_hold_merged_cells() {
// Excel removes a table that contains a merged cell when it opens the file. Merging in a
// table is refused; making or resizing a table over merged cells unmerges them; pasting into
// a table skips the merges.
let base = || {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1:D4", "values": [["A", "B", "C", "D"], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]}))
.unwrap();
s
};
let merges = |s: &Session| s.doc().unwrap().wb.active().unwrap().merges.clone();
let mut s = base();
s.execute("insert.table", json!({"range": "A1:C4"})).unwrap();
for id in ["home.mergeCells", "home.mergeCenter", "home.mergeAcross"] {
for range in ["A2:B2", "A1:B1", "C3:D3"] {
let e = s.execute(id, json!({"range": range})).unwrap_err().to_string();
assert!(e.contains("can't merge cells in a table"), "{id} {range}: {e}");
}
}
assert!(merges(&s).is_empty());
s.execute("home.mergeCells", json!({"range": "E2:F2"})).unwrap();
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F2").unwrap()]);
// A table over merged cells unmerges them; undo brings them back.
let mut s = base();
s.execute("home.mergeCells", json!({"range": "A2:B2"})).unwrap();
s.execute("home.mergeCells", json!({"range": "C3:D4"})).unwrap();
s.execute("home.mergeCells", json!({"range": "F1:G1"})).unwrap();
s.execute("insert.table", json!({"range": "A1:C4"})).unwrap();
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("F1:G1").unwrap()]);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(merges(&s).len(), 3);
s.execute("edit.redo", json!({})).unwrap();
// Resizing a table over merged cells is refused, as in Excel; the merge stays.
let mut s = base();
s.execute("insert.table", json!({"range": "A1:B4", "name": "T"})).unwrap();
s.execute("home.mergeCells", json!({"range": "C2:D2"})).unwrap();
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap_err().to_string();
assert!(e.contains("can't overlap merged cells"), "{e}");
s.execute("home.unmergeCells", json!({"range": "C2:D2"})).unwrap();
s.execute("table.resize", json!({"table": "T", "range": "A1:C4"})).unwrap();
// Merged cells pasted into a table arrive unmerged; elsewhere they stay merged.
s.execute("home.mergeCells", json!({"range": "E2:F3"})).unwrap();
s.execute("edit.copy", json!({"range": "E2:F3"})).unwrap();
s.execute("edit.paste", json!({"at": "A2"})).unwrap();
s.execute("edit.paste", json!({"at": "H2"})).unwrap();
assert_eq!(merges(&s), vec![gridcraft_core::RangeRef::parse("E2:F3").unwrap(), gridcraft_core::RangeRef::parse("H2:I3").unwrap()]);
// The saved file has no merge inside the table.
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
let bytes = crate::io::base64_decode(saved["base64"].as_str().unwrap()).unwrap();
let (back, _) = crate::io::open_bytes("t.xlsx", &bytes).unwrap();
let sh = back.active().unwrap();
assert_eq!(sh.tables.len(), 1);
assert_eq!(sh.tables[0].range, gridcraft_core::RangeRef::parse("A1:C4").unwrap());
assert!(sh.merges.iter().all(|m| sh.tables.iter().all(|t| !t.range.intersects(m))));
}
#[test]
fn hyperlink_function_makes_a_cell_link() {
let mut s = s();
s.link_policy = crate::links::LinkPolicy::Allow;
s.execute("cell.set", json!({"cell": "A1", "input": "https://example.com/x"})).unwrap();
s.execute("cell.set", json!({"cell": "B2", "input": "=HYPERLINK(A1,\"Go\")"})).unwrap();
s.execute("cell.set", json!({"cell": "C3", "input": "=HYPERLINK(\"google.com\")"})).unwrap();
s.take_ui_requests();
s.execute("link.open", json!({"cell": "B2"})).unwrap();
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://example.com/x".into())]);
s.execute("link.open", json!({"cell": "C3"})).unwrap();
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl("https://google.com".into())]);
assert!(s.execute("link.open", json!({"cell": "A1"})).is_err());
// a scheme-less address with a query, fragment or port opens over https too
for (cell, input, url) in [
("D1", "=HYPERLINK(\"google.com?q=rust\")", "https://google.com?q=rust"),
("D2", "=HYPERLINK(\"google.com#results\")", "https://google.com#results"),
("D3", "=HYPERLINK(\"example.com:8443/x\")", "https://example.com:8443/x"),
] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
s.execute("link.open", json!({"cell": cell})).unwrap();
assert_eq!(s.take_ui_requests(), vec![crate::UiRequest::OpenUrl(url.into())], "{input}");
}
// a table named like an address stays an internal target
s.execute("range.setValues", json!({"range": "F1:G2", "values": [["a", "b"], [1, 2]]})).unwrap();
s.execute("insert.table", json!({"range": "F1:G2", "name": "sales.data"})).unwrap();
s.execute("cell.set", json!({"cell": "D4", "input": "=HYPERLINK(\"sales.data\")"})).unwrap();
let link = crate::links::cell_link(&s.doc().unwrap().wb, 0, gridcraft_core::CellRef::parse("D4").unwrap()).unwrap();
assert_eq!(link.target, "sales.data");
}
/// #1348: the selection a workbook opens with, and the one a sheet gets on its first visit, take
/// a merged active cell whole, as a click on it does: a merge at A1 and one elsewhere. A
/// selection the sheet remembers comes back as it was, even inside a merged cell.
@@ -7,9 +7,6 @@ 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
}
@@ -1,427 +0,0 @@
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);
}
@@ -1,38 +0,0 @@
//! 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]);
}
@@ -12,7 +12,7 @@
//! and saving, reloading or recalculating never panics either;
//! - a non-undoable command never changes cell content (it would be lost to undo);
//! - the structure stays valid: active sheet in range, sheet and table names valid and unique,
//! merges and tables on the sheet and not overlapping (nor a merge inside a table), legacy arrays anchored at their
//! merges and tables on the sheet and not overlapping, legacy arrays anchored at their
//! top-left cell, the selection on the sheet;
//! - a full recalculation from scratch gives the values the incremental recalculation left
//! (catches stale dependency graphs);
@@ -442,10 +442,6 @@ fn structure_problem(wb: &Workbook, sel: &gridcraft_engine::Selection) -> Option
if let Some(o) = sh.tables.iter().skip(k + 1).find(|o| overlaps(&t.range, &o.range)) {
return Some(format!("{}: tables `{}` ({}) and `{}` ({}) overlap", sh.name, t.name, t.range, o.name, o.range));
}
// Excel removes a table that holds a merged cell when it opens the file.
if let Some(m) = sh.merges.iter().find(|m| overlaps(&t.range, m)) {
return Some(format!("{}: table `{}` ({}) holds merged cells {m}", sh.name, t.name, t.range));
}
}
}
if sel.ranges.is_empty() || !sel.active.is_valid() || sel.ranges.iter().any(|r| !r.start.is_valid() || !r.end.is_valid()) {
-3
View File
@@ -1,10 +1,8 @@
//! 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;
@@ -33,7 +31,6 @@ 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;
+1 -1
View File
@@ -17,7 +17,7 @@ fn value(s: &Session, sheet: &str, cell: &str) -> Value {
fn copied_sheet_keeps_spill_values_through_full_recalc() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"sample": "grades"}));
run(&mut s, "home.mergeCells", json!({"range": "F15:H20"}));
run(&mut s, "home.mergeCells", json!({"range": "F:H"}));
run(&mut s, "cell.set", json!({"cell": "J54", "input": "=SEQUENCE(5)*C6"}));
run(&mut s, "selection.set", json!({"range": "15:15"}));
run(&mut s, "sheet.move", json!({"copy": true, "sheet": 0, "to": 1}));
@@ -1,240 +0,0 @@
//! 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");
}
@@ -54,168 +54,3 @@ fn resize_next_to_another_table_still_works() {
s.execute("table.resize", json!({"table":"T", "range":"A1:C3"})).unwrap();
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
}
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
s.doc().unwrap().wb.active().unwrap()
}
fn names(s: &Session, table: usize) -> Vec<String> {
sheet(s).tables[table].columns.iter().map(|c| c.name.clone()).collect()
}
fn headers(s: &Session, table: usize) -> Vec<String> {
let sh = sheet(s);
let r = sh.tables[table].range;
(r.start.col..=r.end.col).map(|c| sh.value(gridcraft_core::CellRef::new(r.start.row, c)).display()).collect()
}
fn with_headers(range: &str, row: &[&str]) -> Session {
let mut s = Session::new();
s.new_workbook();
let rows = vec![row.iter().map(|h| json!(h)).collect::<Vec<_>>(), row.iter().map(|_| json!(1)).collect(), row.iter().map(|_| json!(2)).collect()];
s.execute("range.setValues", json!({"range": range, "values": rows})).unwrap();
s.execute("insert.table", json!({"range": range, "header": true, "name": "T"})).unwrap();
s
}
#[test]
fn resize_onto_another_table_is_rejected() {
// From the sales sample, growing Table2 over Table1 used to leave two overlapping tables.
let mut s = Session::new();
s.execute("file.new", json!({"sample": "sales"})).unwrap();
s.execute("insert.table", json!({"header": true, "range": "M2:N5"})).unwrap();
s.execute("insert.table", json!({"header": true, "range": "P2:Q5"})).unwrap();
let e = s.execute("table.resize", json!({"range": "M2:Q5", "table": "Table2"})).unwrap_err().to_string();
assert!(e.contains("overlap another table"), "{e}");
let ranges: Vec<String> = sheet(&s).tables.iter().map(|t| t.range.a1()).collect();
assert!(ranges.contains(&"M2:N5".to_string()) && ranges.contains(&"P2:Q5".to_string()), "{ranges:?}");
// Down over a table below, or around a whole table, is refused too; next to it is fine.
let mut s = table();
s.execute("range.setValues", json!({"range": "A5", "values": [["c"], ["1"]]})).unwrap();
s.execute("insert.table", json!({"range": "A5:A6", "header": true, "name": "U"})).unwrap();
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:B5"})).is_err());
assert!(s.execute("table.resize", json!({"table": "T", "range": "A1:C9"})).is_err());
s.execute("table.resize", json!({"table": "T", "range": "A1:B4"})).unwrap();
assert_eq!(table_range(&s), "A1:B4");
}
#[test]
fn resize_onto_merged_cells_pivot_or_array_is_rejected() {
let mut s = table();
s.execute("home.mergeCenter", json!({"range": "D2:E2"})).unwrap();
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
assert!(e.contains("merged"), "{e}");
assert_eq!(table_range(&s), "A1:B2");
let mut s = table();
s.execute("selection.set", json!({"range": "D1:D2"})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "=ROW(1:2)", "array": true})).unwrap();
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap_err().to_string();
assert!(e.contains("array"), "{e}");
assert_eq!(table_range(&s), "A1:B2");
let mut s = table();
s.execute("range.setValues", json!({"range": "H1", "values": [["k", "v"], ["x", "1"], ["y", "2"]]})).unwrap();
s.execute("insert.pivotTable", json!({"source": "Sheet1!$H$1:$I$3", "destination": "Sheet1!D3", "filters": ["k"], "values": ["v"]})).unwrap();
assert!(!sheet(&s).pivots.is_empty());
let e = s.execute("table.resize", json!({"table": "T", "range": "A1:E2"})).unwrap_err().to_string();
assert!(e.contains("PivotTable"), "{e}");
assert_eq!(table_range(&s), "A1:B2");
}
#[test]
fn resize_onto_a_spill_is_allowed() {
// Excel lets a table take in a spilled formula (the spill then shows #SPILL!).
let mut s = table();
s.execute("cell.set", json!({"cell": "D2", "input": "=SEQUENCE(1,2)"})).unwrap();
s.execute("table.resize", json!({"table": "T", "range": "A1:D2"})).unwrap();
assert_eq!(table_range(&s), "A1:D2");
}
#[test]
fn resized_in_columns_get_excel_names_written_into_the_header_row() {
// A resize whose new columns repeated a name left the header row and the column
// names out of step ("Column3" in memory, "Column32" after reopening).
let mut s = Session::new();
s.execute("file.new", json!({"sample": "grades"})).unwrap();
s.execute("home.formatAsTable", json!({"header": "x", "range": "I3:K9", "style": false})).unwrap();
s.execute("table.resize", json!({"range": "K3:N7", "table": "Table1"})).unwrap();
let ti = sheet(&s).tables.iter().position(|t| t.name == "Table1").unwrap();
assert_eq!(names(&s, ti), headers(&s, ti));
let mut seen = std::collections::HashSet::new();
assert!(names(&s, ti).iter().all(|n| seen.insert(n.to_lowercase())), "{:?}", names(&s, ti));
let bytes = gridcraft_engine::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap();
let (back, _) = gridcraft_engine::io::open_bytes("t.xlsx", &bytes).unwrap();
let t = back.active().unwrap().tables.iter().find(|t| t.name == "Table1").unwrap();
assert_eq!(t.columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>(), names(&s, ti));
// Names Excel gives (observed): an empty header continues a ColumnN on its left, else takes
// the lowest free ColumnN; a repeated header gets the next free suffix.
let cases: [(&str, &[&str], &str, &[&str]); 5] = [
("A1:B3", &["a", "b"], "A1:E3", &["a", "b", "Column1", "Column2", "Column3"]),
("A1:C3", &["Column2", "b", "c"], "A1:F3", &["Column2", "b", "c", "Column1", "Column12", "Column13"]),
("A1:B3", &["Column3", "b"], "A1:E3", &["Column3", "b", "Column1", "Column2", "Column22"]),
("A1:B3", &["Column1", "b"], "A1:D3", &["Column1", "b", "Column2", "Column3"]),
("A1:C3", &["Column1", "Column2", "Column3"], "C1:F3", &["Column3", "Column4", "Column5", "Column6"]),
];
for (range, row, to, want) in cases {
let mut s = with_headers(range, row);
s.execute("table.resize", json!({"table": "T", "range": to})).unwrap();
assert_eq!(names(&s, 0), want.iter().map(|w| w.to_string()).collect::<Vec<_>>(), "{row:?} -> {to}");
assert_eq!(headers(&s, 0), names(&s, 0), "{row:?} -> {to}");
}
// Headers already in the new columns are kept, made unique and turned into text.
let mut s = with_headers("A1:B3", &["x", "y"]);
s.execute("range.setValues", json!({"range": "C1", "values": [["X", "x", 5]]})).unwrap();
s.execute("cell.set", json!({"cell": "F1", "input": "=1+1"})).unwrap();
s.execute("table.resize", json!({"table": "T", "range": "A1:F3"})).unwrap();
assert_eq!(names(&s, 0), ["x", "y", "X2", "x3", "5", "2"]);
assert_eq!(headers(&s, 0), names(&s, 0));
assert!(sheet(&s).cell(gridcraft_core::CellRef::new(0, 5)).is_some_and(|c| c.formula.is_none()));
}
#[test]
fn resizing_a_table_without_a_header_row_keeps_its_names_and_data() {
let mut s = with_headers("A1:B3", &["a", "b"]);
// As a file can have it: the table starts at its first data row (A2:B3), with no header row.
{
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
let t = &mut std::sync::Arc::make_mut(&mut wb.sheets[0]).tables[0];
t.header_row = false;
t.range.start.row = 1;
}
let r = sheet(&s).tables[0].range;
assert!(!sheet(&s).tables[0].header_row);
let to = gridcraft_core::RangeRef::new(r.start, gridcraft_core::CellRef::new(r.end.row, r.end.col + 1));
let first = sheet(&s).value(r.start).display();
s.execute("table.resize", json!({"table": "T", "range": to.a1()})).unwrap();
assert_eq!(names(&s, 0), ["a", "b", "Column1"]);
assert_eq!(sheet(&s).value(r.start).display(), first);
}
#[test]
fn resized_formula_header_is_named_by_its_value_when_formulas_show() {
let mut s = with_headers("A1:B3", &["x", "y"]);
s.execute("cell.set", json!({"cell": "C1", "input": "=1+1"})).unwrap();
{
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
std::sync::Arc::make_mut(&mut wb.sheets[0]).show_formulas = true;
}
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
assert_eq!(names(&s, 0), ["x", "y", "2"]);
assert_eq!(headers(&s, 0), names(&s, 0));
}
#[test]
fn resized_picture_header_is_replaced_and_its_picture_removed() {
let mut s = with_headers("A1:B3", &["x", "y"]);
{
let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb);
let picture = gridcraft_engine::model::CellPicture { data: vec![1, 2, 3], mime: "image/png".into(), alt: String::new() };
std::sync::Arc::make_mut(&mut wb.sheets[0]).set_picture(gridcraft_core::CellRef::new(0, 2), std::sync::Arc::new(picture));
}
s.execute("table.resize", json!({"table": "T", "range": "A1:C3"})).unwrap();
assert!(!sheet(&s).cell_pictures.contains_key(&gridcraft_core::CellRef::new(0, 2)));
assert_eq!(headers(&s, 0), names(&s, 0));
}
-128
View File
@@ -33,98 +33,6 @@ 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())
@@ -237,42 +145,6 @@ 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);
+88 -225
View File
@@ -152,6 +152,72 @@ 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.
@@ -248,15 +314,8 @@ 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. 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>)> {
/// 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>)> {
let va = as_array(values);
let da = as_array(dates);
if va.data.len() != da.data.len() {
@@ -264,33 +323,21 @@ fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec<f64>, Vec
}
let mut v = Vec::with_capacity(va.data.len());
let mut d = Vec::with_capacity(da.data.len());
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),
for (x, y) in va.data.iter().zip(da.data.iter()) {
match x {
Value::Number(n) => v.push(*n),
Value::Error(e) => return Err(*e),
_ if lenient => return Err(CellError::Value),
_ => return Err(strict_err),
};
_ => return Err(CellError::Value),
}
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 && !lenient) || x < 0.0) {
if d.iter().any(|&x| x < d0 || x < 0.0) {
return Err(CellError::Num);
}
Ok((v, d))
@@ -306,219 +353,35 @@ 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, false)?;
let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?;
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, true)?;
let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?;
let guess = opt_num(a, 2, 0.1)?;
if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
return Err(CellError::Num);
}
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)
num_val(solve_rate(|r| xnpv_calc(r, &v, &d), guess)?)
}
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);
}
num_val(irr_solve(&v, guess)?)
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)?)
}
pub(super) fn mirr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
+15 -45
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.encode_utf16().count() > MAX_TEXT {
if s.len() > MAX_TEXT && s.chars().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, over: CellError) -> R<()> {
fn push_capped(out: &mut String, piece: &str) -> 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(over);
return Err(CellError::Value);
}
out.push_str(piece);
Ok(())
@@ -47,35 +47,22 @@ 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 {
// 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);
}
push_capped(&mut out, &piece(&scalar(x))?)?;
}
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)
check_len(out)
}
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)?, CellError::Calc)?;
push_capped(&mut out, &piece(v)?)?;
}
}
check_calc(out)
check_len(out)
}
/// The error `v.to_text()` would give, found without building any text.
@@ -111,12 +98,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)?, CellError::Calc)?;
push_capped(&mut out, &piece(d)?)?;
}
push_capped(&mut out, &s, CellError::Calc)?;
push_capped(&mut out, &s)?;
joined += 1;
}
check_calc(out)
check_len(out)
}
fn count_arg(a: &[Arg], i: usize, default: f64) -> R<usize> {
@@ -265,7 +252,7 @@ fn rept(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
return Err(CellError::Value);
}
let n = n.trunc();
let total = s.encode_utf16().count() as f64 * n;
let total = s.chars().count() as f64 * n;
if total > MAX_TEXT as f64 {
return Err(CellError::Value);
}
@@ -785,7 +772,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), CellError::Value)?;
push_capped(&mut out, &value_text(arr.get(r, c).unwrap_or(&Value::Empty), strict))?;
}
}
if strict {
@@ -1220,37 +1207,20 @@ 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), giving `#CALC!` there as past the cell limit. Errors among the inputs still
/// win, in argument order.
/// 3 GB of copies). 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::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()]), 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(), 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, in UTF-16 code units.
/// Longest text a cell can hold.
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 UTF-16 code units becomes `#VALUE!`.
/// numbers become `#NUM!`, text longer than 32,767 characters 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.encode_utf16().count() > MAX_TEXT => Value::Error(CellError::Value),
Ok(Value::Text(t)) if t.len() > MAX_TEXT && t.chars().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", "stacked100Markers"]),
"subtype": enumeration("Variant (optional)", &["clustered", "stacked", "stacked100", "markers"]),
"title": string("Chart title"),
"at": string("Top-left anchor cell (default: right of the data)"),
}),
-1
View File
@@ -15,7 +15,6 @@ test-support = []
[dependencies]
gridcraft-core = { workspace = true }
sha1 = { workspace = true }
sha2 = { workspace = true }
gridcraft-formula = { workspace = true }
gridcraft-math = { workspace = true }
+9 -57
View File
@@ -11,7 +11,7 @@ mod print;
pub use pivot::{
PIVOT_INDEXER, PivotCalcField, PivotDataCell, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotIndexer, PivotItemRef, PivotLayout,
PivotLookup, PivotScopeItem, PivotShowAs, PivotSort, PivotTable, PivotValue, pivot_key,
PivotLookup, PivotShowAs, PivotSort, PivotTable, PivotValue, pivot_key,
};
pub use print::{EditRange, HfPage, LineInfo, Orientation, PageOrder, PrintSettings, SheetProtection, password_hash};
@@ -501,8 +501,6 @@ pub enum ChartKind {
Line,
LineMarkers,
LineStacked,
LineStacked100,
LineStacked100Markers,
Pie,
Doughnut,
Area,
@@ -561,16 +559,6 @@ pub struct Series {
/// Trendlines fitted to this series (Excel allows several per series).
#[serde(default)]
pub trendlines: Vec<Trendline>,
/// Number format of literal values (an array constant, such as a PivotChart's cached
/// points). Values that reference cells use the cells' format instead.
#[serde(default)]
pub number_format: Option<String>,
/// The categories are a multi-level block (a PivotChart's `multiLvlStrRef`): a column (or
/// row) of cells per level, the innermost last. Only the innermost level is drawn, one
/// label per point. The reference is kept, and XLSX saves it as a `multiLvlStrRef` with a
/// cache of every level; a PivotChart reads that back with this flag set again.
#[serde(default)]
pub innermost_categories: bool,
}
/// Regression a trendline fits (`c:trendlineType`).
@@ -695,17 +683,10 @@ 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 or 100% stacked line with or without markers, or a scatter with or
/// without lines.
/// the same kind, or a 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)
| (LineStacked100 | LineStacked100Markers, LineStacked100 | LineStacked100Markers)
| (Scatter | ScatterLines, Scatter | ScatterLines)
)
a == b || matches!((a, b), (Line | LineMarkers, Line | LineMarkers) | (Scatter | ScatterLines, Scatter | ScatterLines))
}
/// The kind a combo chart's series `i` with its own kind `own` is drawn as.
@@ -749,34 +730,20 @@ fn grouped(k: ChartKind) -> Option<Grouped> {
use ChartKind::*;
match k {
ColumnClustered | ColumnStacked | ColumnStacked100 => Some(Grouped::Column),
Line | LineMarkers | LineStacked | LineStacked100 | LineStacked100Markers => Some(Grouped::Line),
Line | LineMarkers | LineStacked => 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, stacked to 100% (keeping its own
/// markers) 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, 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), LineStacked) => LineStacked,
(Some(Grouped::Line), LineStacked100 | LineStacked100Markers) => {
if marked {
LineStacked100Markers
} else {
LineStacked100
}
}
(Some(Grouped::Line), _) => {
if marked {
LineMarkers
} else {
Line
}
}
(Some(Grouped::Line), ChartKind::LineStacked) => ChartKind::LineStacked,
(Some(Grouped::Line), _) if k == ChartKind::LineStacked => ChartKind::Line,
(Some(Grouped::Line), _) => k,
_ => first,
}
}
@@ -878,8 +845,6 @@ impl Chart {
| ChartKind::Line
| ChartKind::LineMarkers
| ChartKind::LineStacked
| ChartKind::LineStacked100
| ChartKind::LineStacked100Markers
| ChartKind::Area
| ChartKind::AreaStacked
| ChartKind::AreaStacked100
@@ -1436,10 +1401,6 @@ 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]
@@ -1454,15 +1415,6 @@ 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;
-71
View File
@@ -37,25 +37,6 @@ pub enum PivotDateGroup {
Days,
}
/// An item of a field on the other axis that a sort by value takes its values from (e.g. the
/// "Apples" column). The field is named by source column and date grouping, so two levels
/// grouped from one date column (Years and Quarters) stay apart.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PivotScopeItem {
pub source_col: String,
pub date_group: PivotDateGroup,
/// The item's label.
pub item: String,
}
impl PivotScopeItem {
/// Whether this names an item of `f`.
pub fn is_of(&self, f: &PivotField) -> bool {
self.date_group == f.date_group && self.source_col.eq_ignore_ascii_case(&f.source_col)
}
}
/// A field placed in the Rows or Columns area.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
@@ -66,35 +47,6 @@ pub struct PivotField {
pub date_group: PivotDateGroup,
/// Item labels whose detail is hidden (collapsed).
pub collapsed_items: Vec<String>,
/// Custom name shown in the field's header (Field Settings > Custom Name); `None` = the
/// source column name.
pub caption: Option<String>,
/// Sort the items by this value field (its caption) instead of by their labels, in the
/// `sort` direction (Sort > More Sort Options > by value). Ignored when `sort` is `None`.
pub sort_by: Option<String>,
/// Where `sort_by` takes its values: an item of each field on the other axis, outer field
/// first, up to the first field it doesn't name (e.g. sort the rows by the "Apples" column).
/// Empty, or naming an item that isn't there, = the grand total.
pub sort_scope: Vec<PivotScopeItem>,
/// Manual item order (item labels), used when `sort` is `None`; unlisted items follow in
/// source order (date groups in date order).
pub item_order: Vec<String>,
/// Renamed items: (item label, caption shown instead).
pub item_captions: Vec<(String, String)>,
/// Subtotals of this field; `None` = the table's `subtotals`.
pub subtotal: Option<bool>,
/// Repeat the item labels on every row (Outline/Tabular, Repeat Item Labels).
pub repeat_labels: bool,
/// Number format of the item labels (Field Settings > Number Format); `None` = the source
/// column's format.
pub number_format: Option<String>,
}
impl PivotField {
/// The header text: the custom name, else the source column name.
pub fn header(&self) -> &str {
self.caption.as_deref().unwrap_or(&self.source_col)
}
}
/// Summarize-values-by function.
@@ -182,22 +134,6 @@ pub struct PivotTable {
pub show_headers: bool,
/// Area written by the last refresh.
pub last_range: Option<RangeRef>,
/// Header of the row labels in Compact layout; `None` = "Row Labels".
pub row_header_caption: Option<String>,
/// Header of the column labels in Compact layout; `None` = "Column Labels".
pub col_header_caption: Option<String>,
/// Caption of the Values field; `None` = "Values".
pub data_caption: Option<String>,
/// Caption of the grand totals; `None` = "Grand Total".
pub grand_total_caption: Option<String>,
/// Shown in value cells that summarize no records (For empty cells show); `None` = blank.
pub empty_caption: Option<String>,
/// Show the Values row: a header row with `data_caption` above the value captions
/// (Outline/Tabular, several values and no column field). Excel's default is on.
pub show_values_row: bool,
/// Classic PivotTable layout (fields dragged in the grid): with one value field and no
/// column field, the value caption sits above the row headers and the column reads "Total".
pub classic_layout: bool,
/// Calculated fields, usable in the Values area by name.
pub calculated_fields: Vec<PivotCalcField>,
/// Where GETPIVOTDATA finds the report's value cells, as of the last refresh. Shared between
@@ -380,13 +316,6 @@ impl Default for PivotTable {
style: "PivotStyleLight16".into(),
show_headers: true,
last_range: None,
row_header_caption: None,
col_header_caption: None,
data_caption: None,
grand_total_caption: None,
empty_caption: None,
show_values_row: true,
classic_layout: false,
calculated_fields: vec![],
data_index: PivotLookup::default(),
values_on_rows: false,
+2 -6
View File
@@ -11,10 +11,7 @@ pub enum Orientation {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrintSettings {
pub orientation: Orientation,
/// 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.
/// Paper size name (`Letter`, `A4`, `Legal`…).
pub paper: String,
/// Margins in inches: left, right, top, bottom, header, footer.
pub margins: [f32; 6],
@@ -261,8 +258,7 @@ pub struct LineInfo {
pub outline: u8,
pub collapsed: bool,
pub style: Option<crate::style::StyleId>,
/// The size was set by the user. Rows without it follow their content's height; columns
/// without it widen when a number format makes their numbers wider (`home.increaseDecimal`…).
/// The size was set by the user (rows): automatic heights follow the content.
#[serde(default)]
pub custom: bool,
}
+2 -3
View File
@@ -9,7 +9,6 @@ pub mod cell;
mod cellmap;
pub mod features;
pub mod macros;
pub mod paper;
pub mod password;
pub mod preserved;
pub mod python;
@@ -22,7 +21,7 @@ pub use cell::{Cell, CellPicture, Formula};
pub use features::*;
pub use macros::*;
pub use password::PasswordHash;
pub use preserved::{Preserved, PreservedChart, PreservedPart, PreservedRel, PreservedSheet, PreservedXml};
pub use preserved::{Preserved, PreservedPart, PreservedRel, PreservedSheet, PreservedXml};
pub use python::{PyCode, PyOutput};
pub use sheet::{DEFAULT_COL_WIDTH, DEFAULT_ROW_HEIGHT, LineIndex, Sheet, SheetUid, SheetViewMode, Visibility, points_to_chars};
pub use store::CellStore;
@@ -32,7 +31,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, WriteReservation,
RefHost, ShowObjects, Workbook, WorkbookView,
};
/// Font used for new workbooks. Only a name: renderers substitute an available open font
-137
View File
@@ -1,137 +0,0 @@
//! 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);
}
}
+1 -15
View File
@@ -160,7 +160,6 @@ 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),
@@ -237,19 +236,6 @@ 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");
@@ -259,7 +245,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").unwrap());
assert!(other("SHA-1", 10).verify("s3cret").is_err());
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")?);
+3 -35
View File
@@ -1,15 +1,13 @@
//! File content GridCraft does not model, carried through unchanged so that saving a workbook
//! never silently drops it (XLSX pass-through: custom XML, external links, connections, query
//! tables, form controls, OLE objects, chart sheets, and the original XML of embedded charts).
//! tables, form controls, OLE objects…).
//!
//! The data is opaque to everything except the file-format crate: the model only holds it, so a
//! sheet's kept content disappears with the sheet. It is not part of the JSON format.
use std::sync::Arc;
use crate::features::Chart;
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.
@@ -34,13 +32,6 @@ 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
@@ -69,25 +60,9 @@ pub struct PreservedSheet {
pub sheet_id: u32,
}
/// An embedded chart (a chart in a sheet's drawing) kept as it was in the source file, so that
/// what the model doesn't hold (fonts, point colours, axis bounds, line dashes…) survives a save.
/// It is written in place of GridCraft's own chart part only while the model's chart still equals
/// [`Self::chart`], apart from its id and position.
#[derive(Clone, Debug, PartialEq)]
pub struct PreservedChart {
/// The id of the model chart read from it.
pub id: u32,
/// The chart as GridCraft read it from the kept part (id 0, default anchor).
pub chart: Chart,
/// Part name of the chart part in the source file (no leading `/`).
pub part: String,
/// The chart part and every part its relationships reach (style, colours, user shapes…).
pub parts: Vec<PreservedPart>,
}
/// Unmodelled content kept for one owner (the workbook, which also holds package-root content,
/// or one sheet).
#[derive(Clone, Debug, Default, PartialEq)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Preserved {
/// Relationships of the package root (`_rels/.rels`) to kept parts (workbook owner only).
pub package_rels: Vec<PreservedRel>,
@@ -102,8 +77,6 @@ pub struct Preserved {
pub vml: Option<PreservedPart>,
/// Chart sheets, in file order (workbook owner only).
pub sheets: Vec<PreservedSheet>,
/// The original parts of the sheet's embedded charts (sheet owner only).
pub charts: Vec<PreservedChart>,
}
impl Preserved {
@@ -114,14 +87,9 @@ impl Preserved {
&& self.elements.is_empty()
&& self.vml.is_none()
&& self.sheets.is_empty()
&& self.charts.is_empty()
}
/// Total bytes held.
pub fn byte_len(&self) -> usize {
self.parts
.iter()
.chain(self.vml.iter())
.chain(self.charts.iter().flat_map(|c| c.parts.iter()))
.fold(0usize, |n, p| n.saturating_add(p.data.len()))
self.parts.iter().chain(self.vml.iter()).fold(0usize, |n, p| n.saturating_add(p.data.len()))
}
}
-13
View File
@@ -224,9 +224,6 @@ 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.
@@ -297,15 +294,6 @@ 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
@@ -576,7 +564,6 @@ impl Workbook {
props: DocProps::default(),
protected_structure: false,
structure_password: None,
write_reservation: None,
custom_lists: vec![],
cell_styles: vec![],
phonetics: vec![],
+7 -42
View File
@@ -10,7 +10,7 @@ use skrifa::{
};
use unicode_bidi::BidiInfo;
use crate::{CID_FONT, EXT_FONT, Error, FONT_COUNT, Font, Run, TextDirection, n, pdf_ext_string, pdf_string, pdf_utf16_string, run_kind};
use crate::{CID_FONT, Error, Font, TextDirection, n, needs_cid, pdf_string, pdf_utf16_string};
include!(concat!(env!("OUT_DIR"), "/arabic_fonts.rs"));
@@ -197,25 +197,9 @@ fn has_weight_axis(bytes: &[u8]) -> bool {
#[derive(Debug)]
pub(crate) enum Item {
Glyph {
id: u32,
x: f32,
y: f32,
source: String,
},
Latin {
text: String,
x: f32,
},
/// Latin Extended-A letters WinAnsiEncoding lacks, set in the face's extended font.
Ext {
text: String,
x: f32,
},
Cid {
text: String,
x: f32,
},
Glyph { id: u32, x: f32, y: f32, source: String },
Latin { text: String, x: f32 },
Cid { text: String, x: f32 },
}
pub(crate) struct Layout {
@@ -266,14 +250,10 @@ pub(crate) fn layout(font: Font, text: &str, direction: TextDirection) -> Result
if !embedded {
let part = part.chars().map(|ch| if is_line_break(ch) { ' ' } else { ch });
let part: Vec<char> = if rtl { part.rev().map(mirror_ansi).collect() } else { part.collect() };
for run in part.chunk_by(|a, b| run_kind(*a) == run_kind(*b)) {
for run in part.chunk_by(|a, b| needs_cid(*a) == needs_cid(*b)) {
let (text, x) = (run.iter().collect(), layout.width);
layout.width += run.iter().map(|&ch| f32::from(font.char_width(ch))).sum::<f32>();
layout.items.push(match run.first().map(|&ch| run_kind(ch)) {
Some(Run::Cid) => Item::Cid { text, x },
Some(Run::Ext) => Item::Ext { text, x },
_ => Item::Latin { text, x },
});
layout.items.push(if run.first().is_some_and(|&ch| needs_cid(ch)) { Item::Cid { text, x } } else { Item::Latin { text, x } });
}
continue;
}
@@ -345,7 +325,7 @@ pub(crate) fn vertical_extents(font: Font, text: &str, direction: TextDirection)
ascent = ascent.max(y + top);
descent = descent.max(-y - bottom);
}
Item::Latin { .. } | Item::Ext { .. } | Item::Cid { .. } => {
Item::Latin { .. } | Item::Cid { .. } => {
ascent = ascent.max(800.0);
descent = descent.max(220.0);
}
@@ -430,8 +410,6 @@ pub(crate) struct Subset {
bytes: usize,
/// Some text on the page set a run in the CJK CID font, so the page must declare it.
pub(crate) uses_cid: bool,
/// The faces (by [`Font::index`]) whose Latin Extended-A font some text on the page used.
pub(crate) uses_ext: [bool; FONT_COUNT],
}
struct Glyph {
@@ -501,19 +479,6 @@ impl Subset {
Item::Latin { text, x } => {
let _ = writeln!(out, "/F{} {} Tf 1 0 0 1 {} 0 Tm {} Tj", font.index() + 1, n(size), n(x * size / 1000.0), pdf_string(&text));
}
Item::Ext { text, x } => {
if let Some(used) = self.uses_ext.get_mut(font.index()) {
*used = true;
}
let _ = writeln!(
out,
"/F{} {} Tf 1 0 0 1 {} 0 Tm {} Tj",
EXT_FONT + font.index() + 1,
n(size),
n(x * size / 1000.0),
pdf_ext_string(&text)
);
}
Item::Cid { text, x } => {
self.uses_cid = true;
let _ = writeln!(out, "/F{} {} Tf 1 0 0 1 {} 0 Tm {} Tj", CID_FONT + 1, n(size), n(x * size / 1000.0), pdf_utf16_string(&text));
+23 -227
View File
@@ -1,17 +1,13 @@
//! PDF 1.7 drawing for GridCraft print/export, with shared object and xref framing.
//!
//! - The 14 standard fonts (no embedding) with WinAnsiEncoding, plus approximate width tables
//! ([`text_width`]) so callers can measure, align and wrap text. Latin Extended-A letters
//! WinAnsiEncoding lacks (ő, ű, ł, č, …) are set in the same face through a second resource with
//! a `/Differences` encoding of standard glyph names. Other characters outside
//! ([`text_width`]) so callers can measure, align and wrap text. Characters outside
//! WinAnsiEncoding (CJK and other scripts) are set in a predefined, non-embedded Adobe-GB1 CID
//! font with the `UniGB-UTF16-H` CMap instead of being replaced by `?`. Symbol uses its own
//! built-in encoding ([`symbol_code`]), for Greek letters and mathematical operators.
//! - Arabic is shaped and set in embedded Type3 subsets, with exact shaped advances.
//! - Vector drawing: rectangles, lines (solid or dashed), polygons, circles (Bézier), clipping.
//! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded). The
//! decoded image bytes one document keeps across all its pages are capped
//! ([`MAX_DOC_IMAGE_BYTES`]); images past the cap are left out.
//! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded).
//! - Coordinates are points with a **top-left origin** (y grows down); text `y` is the baseline.
//!
//! Streams are written uncompressed (images use the RunLengthDecode filter).
@@ -328,73 +324,10 @@ pub fn win_ansi(c: char) -> u8 {
}
}
/// Objects a font resource takes: the CID font also has its descendant font and font descriptor,
/// a Latin Extended-A face its font descriptor.
fn font_objects(slot: usize) -> u32 {
if slot == CID_FONT {
3
} else if slot >= EXT_FONT {
2
} else {
1
}
}
/// Writes the Latin Extended-A resource of `face` as object `id`, with its font descriptor as
/// `id + 1`.
fn write_ext_font(out: &mut craft_pdf::classic::Writer, id: u32, face: Font) -> Result<(), Error> {
let names: Vec<&str> = metrics::LATIN_EXT_A.iter().map(|(name, _)| *name).collect();
// Not every glyph name here is in the standard fonts' metrics (Ccircumflex
// isn't), so the resource states each width: without one a reader can give
// the glyph no advance and set the next letter on top of it. The PDF reference
// asks for /FirstChar, /LastChar, /Widths and /FontDescriptor together.
let widths: Vec<String> = (0x100u32..0x180).map(|u| char::from_u32(u).map_or(0, |c| face.char_width(c)).to_string()).collect();
let last = 127 + widths.len();
let desc_id = id + 1;
out.object(
id,
&format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} /Encoding << /Type /Encoding /Differences [128 /{}] >> /FirstChar 128 /LastChar {last} /Widths [{}] /FontDescriptor {desc_id} 0 R >>",
face.base_name(),
names.join(" /"),
widths.join(" ")
),
)?;
out.object(desc_id, &font_descriptor(face))?;
Ok(())
}
/// The font descriptor of a standard face (values from its Adobe AFM), for a resource that states
/// its own widths.
fn font_descriptor(face: Font) -> String {
// (flags, bbox, italic angle, ascent, descent, cap height, StemV)
let (flags, bbox, italic, ascent, descent, cap, stem) = match face {
Font::Helvetica => (32, "-166 -225 1000 931", 0.0, 718, -207, 718, 88),
Font::HelveticaOblique => (96, "-170 -225 1116 931", -12.0, 718, -207, 718, 88),
Font::HelveticaBold => (32, "-170 -228 1003 962", 0.0, 718, -207, 718, 140),
Font::HelveticaBoldOblique => (96, "-174 -228 1114 962", -12.0, 718, -207, 718, 140),
Font::TimesRoman => (34, "-168 -218 1000 898", 0.0, 683, -217, 662, 84),
Font::TimesBold => (34, "-168 -218 1000 935", 0.0, 683, -217, 676, 139),
Font::TimesItalic => (98, "-169 -217 1010 883", -15.5, 683, -217, 653, 76),
Font::TimesBoldItalic => (98, "-200 -218 996 921", -15.0, 683, -217, 669, 121),
Font::Courier => (35, "-23 -250 715 805", 0.0, 629, -157, 562, 51),
Font::CourierBold => (35, "-113 -250 749 801", 0.0, 629, -157, 562, 106),
Font::CourierOblique => (99, "-27 -250 849 805", -12.0, 629, -157, 562, 51),
Font::CourierBoldOblique => (99, "-57 -250 869 801", -12.0, 629, -157, 562, 106),
Font::Symbol => (4, "-180 -293 1090 1010", 0.0, 1010, -293, 1010, 85),
};
format!(
"<< /Type /FontDescriptor /FontName /{} /Flags {flags} /FontBBox [{bbox}] /ItalicAngle {italic} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem} >>",
face.base_name()
)
}
/// Index of the CID font in a page's font flags (after the [`Font::ALL`] faces).
const CID_FONT: usize = Font::ALL.len();
/// Index of the first Latin Extended-A face (one per [`Font::ALL`] face, after the CID font).
const EXT_FONT: usize = CID_FONT + 1;
/// Number of font resources a page can use.
const FONT_SLOTS: usize = EXT_FONT + Font::ALL.len();
const FONT_SLOTS: usize = CID_FONT + 1;
/// Base font of the CID font used for characters WinAnsiEncoding lacks.
const CID_BASE_FONT: &str = "STSong-Light";
/// Default glyph width of the CID font (full-width), in 1/1000 em.
@@ -402,44 +335,7 @@ const CID_WIDTH: u16 = 1000;
/// True when `c` has no WinAnsiEncoding byte and is drawn with the CID font.
fn needs_cid(c: char) -> bool {
!c.is_control() && c != '?' && win_ansi(c) == b'?' && ext_code(c).is_none()
}
/// The byte of `c` in the Latin Extended-A encoding (U+0100..=U+017F at 0x80..=0xFF), for
/// characters WinAnsiEncoding lacks. These are set in the standard face with a `/Differences`
/// encoding of standard glyph names, not in the CID font.
fn ext_code(c: char) -> Option<u8> {
let u = c as u32;
((0x100..=0x17F).contains(&u) && win_ansi(c) == b'?').then(|| (u - 0x80) as u8)
}
/// How a character is encoded in a text run.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Run {
Ansi,
Ext,
Cid,
}
fn run_kind(c: char) -> Run {
if ext_code(c).is_some() {
Run::Ext
} else if needs_cid(c) {
Run::Cid
} else {
Run::Ansi
}
}
/// A PDF hex string `< … >` of `text` in the Latin Extended-A encoding of [`ext_code`].
fn pdf_ext_string(text: &str) -> String {
let mut s = String::with_capacity(text.len() * 2 + 2);
s.push('<');
for c in text.chars() {
let _ = write!(s, "{:02X}", ext_code(c).unwrap_or(b'?'));
}
s.push('>');
s
!c.is_control() && c != '?' && win_ansi(c) == b'?'
}
/// A PDF hex string `< … >` of `text` in UTF-16BE (the `UniGB-UTF16-H` encoding).
@@ -614,11 +510,6 @@ pub struct Page {
content: String,
fonts: [bool; FONT_SLOTS],
images: Vec<ImageData>,
/// Image bytes this page may still keep before the document's image budget is spent. Set by
/// [`PdfDoc::add_page`] and [`PdfDoc::page_mut`], which hand out one page at a time.
image_room: u64,
/// Bytes of image data this page keeps, counted as images are added.
image_kept: u64,
/// Indexes into `images`, by content hash; a hash match is confirmed with [`ImageData::same`].
image_index: HashMap<u64, Vec<usize>>,
/// Pixel comparisons made while looking up duplicate pictures (test instrumentation).
@@ -641,10 +532,6 @@ pub struct Page {
const MAX_PAGE_CONTENT: usize = 64 * 1024 * 1024;
/// Largest image (pixels) embedded.
const MAX_IMAGE_PIXELS: u64 = 40_000_000;
/// Most bytes of image data (RGB plus alpha planes) one document keeps across all its pages.
/// Each [`Page::image_rgba`] call keeps its own copy, so a picture repeated on every page of a
/// long export would otherwise grow without bound; images past the budget are left out.
pub const MAX_DOC_IMAGE_BYTES: u64 = 512 * 1024 * 1024;
/// Deepest `q` nesting a PDF consumer must support (the PDF specification's implementation limits).
const MAX_SAVE_DEPTH: usize = 28;
/// Line join styles, as the `j` operator takes them.
@@ -666,22 +553,6 @@ impl Page {
fn full(&self) -> bool {
self.content.len() > MAX_PAGE_CONTENT
}
/// Bytes of image data this page may still add before the document's image budget
/// ([`MAX_DOC_IMAGE_BYTES`]) is spent. An image of `pw`×`ph` pixels needs up to `pw * ph * 4`;
/// callers can skip decoding pictures that cannot fit (the room never grows back while a
/// document is built).
pub fn image_room(&self) -> u64 {
self.image_room
}
/// Bytes of image data kept by this page, summed from its images (tests check the running
/// [`Page::image_kept`] count against it).
#[cfg(test)]
fn image_bytes(&self) -> u64 {
self.images.iter().fold(0u64, |acc, i| acc.saturating_add(i.rgb.len() as u64).saturating_add(i.alpha.as_ref().map_or(0, |a| a.len() as u64)))
}
fn op(&mut self, s: &str) {
if !self.full() {
self.content.push_str(s);
@@ -981,8 +852,7 @@ impl Page {
return;
}
};
let ext = self.arabic.uses_ext.get(font.index()).copied().unwrap_or(false).then_some(EXT_FONT + font.index());
for slot in [Some(font.index()), self.arabic.uses_cid.then_some(CID_FONT), ext].into_iter().flatten() {
for slot in [Some(font.index()), self.arabic.uses_cid.then_some(CID_FONT)].into_iter().flatten() {
if let Some(f) = self.fonts.get_mut(slot) {
*f = true;
}
@@ -1010,17 +880,13 @@ impl Page {
// advances the text position, so the runs follow each other on the baseline.
// Symbol text is one run in Symbol's own encoding (the CID font has no maths symbols).
let symbol = font == Font::Symbol;
let kind_of = |c: char| if symbol { Run::Ansi } else { run_kind(c) };
let uses_cid = |c: char| !symbol && needs_cid(c);
let mut rest: &str = &visual;
while let Some(first) = rest.chars().next() {
let kind = kind_of(first);
let end = rest.char_indices().find(|(_, c)| kind_of(*c) != kind).map_or(rest.len(), |(i, _)| i);
let cid = uses_cid(first);
let end = rest.char_indices().find(|(_, c)| uses_cid(*c) != cid).map_or(rest.len(), |(i, _)| i);
let (run, tail) = rest.split_at(end);
let (slot, string) = match kind {
Run::Cid => (CID_FONT, pdf_utf16_string(run)),
Run::Ext => (EXT_FONT + fi, pdf_ext_string(run)),
Run::Ansi => (fi, pdf_string_in(run, symbol)),
};
let (slot, string) = if cid { (CID_FONT, pdf_utf16_string(run)) } else { (fi, pdf_string_in(run, symbol)) };
if let Some(f) = self.fonts.get_mut(slot) {
*f = true;
}
@@ -1048,8 +914,7 @@ impl Page {
}
/// Draws an RGBA image (`pw`×`ph` pixels, row-major, straight alpha) into the box
/// `(x, y, w, h)`. Malformed or oversized buffers are ignored, and so are images that do not
/// fit in what is left of the document's image budget ([`Page::image_room`]).
/// `(x, y, w, h)`. Malformed or oversized buffers are ignored.
pub fn image_rgba(&mut self, destination: Rect, rgba: &[u8], pixel_size: [u32; 2]) {
let Rect { x, y, width: w, height: h } = destination;
let [pw, ph] = pixel_size;
@@ -1061,16 +926,6 @@ impl Page {
if self.saved.len() >= MAX_SAVE_DEPTH {
return;
}
// Room for the worst case (RGB plus an alpha plane) is checked before anything is
// allocated, so the document's image bytes stay bounded however many pages it has. Past
// the budget, a picture this page already holds can still be drawn again: it is only
// built for the lookup when the page holds one of the same size, so the temporary copy
// made to compare is bounded by pixel dimensions the page already accepted (up to
// `px * 4` bytes) and is dropped when nothing matches.
let over_budget = px * 4 > self.image_room;
if over_budget && !self.images.iter().any(|o| o.width == pw && o.height == ph) {
return;
}
let px = px as usize;
let mut rgb = Vec::with_capacity(px * 3);
// The alpha plane is only allocated once a non-opaque pixel shows up.
@@ -1089,33 +944,23 @@ impl Page {
}
}
let img = ImageData::new(pw, ph, rgb, alpha);
// The same picture drawn again on this page shares one XObject. The lookup does not
// insert: only an accepted picture gets an index entry, so refused pictures past the
// budget don't grow the index.
// The same picture drawn again on this page shares one XObject.
let candidates = self.image_index.entry(img.hash).or_default();
#[cfg(test)]
let comparisons = &mut self.image_comparisons;
let images = &self.images;
let known = self.image_index.get(&img.hash).and_then(|candidates| {
candidates.iter().copied().find(|&i| {
#[cfg(test)]
{
*comparisons += 1;
}
images.get(i).is_some_and(|o| o.same(&img))
})
let known = candidates.iter().copied().find(|&i| {
#[cfg(test)]
{
*comparisons += 1;
}
self.images.get(i).is_some_and(|o| o.same(&img))
});
let idx = match known {
Some(i) => i,
None if over_budget => return,
None => {
// Only a picture this page doesn't hold yet spends the document's image budget.
let kept = (img.rgb.len() as u64).saturating_add(img.alpha.as_ref().map_or(0, |a| a.len() as u64));
self.image_room = self.image_room.saturating_sub(kept);
self.image_kept = self.image_kept.saturating_add(kept);
let idx = self.images.len();
self.image_index.entry(img.hash).or_default().push(idx);
candidates.push(self.images.len());
self.images.push(img);
idx
self.images.len() - 1
}
};
let s = format!("q {} 0 0 {} {} {} cm /Im{} Do Q", n(w), n(h), n(x), n(self.y(y + h)), idx + 1);
@@ -1136,14 +981,6 @@ pub struct Info {
pub struct PdfDoc {
pages: Vec<Page>,
pub info: Info,
/// Image budget lowered by [`PdfDoc::set_image_budget`]; `None` = [`MAX_DOC_IMAGE_BYTES`].
image_budget: Option<u64>,
/// Image bytes kept by every page except [`PdfDoc::open_page`], kept up to date as pages are
/// handed out so the remaining room is found without scanning every page.
image_used: u64,
/// The page last handed out by [`PdfDoc::add_page`] or [`PdfDoc::page_mut`], whose images
/// may have grown since; its bytes are folded into `image_used` when another page is handed out.
open_page: Option<usize>,
}
/// PackBits-style run-length encoding (PDF `RunLengthDecode`).
@@ -1179,17 +1016,12 @@ impl PdfDoc {
pub fn add_page(&mut self, width_pt: f32, height_pt: f32) -> &mut Page {
let width = if width_pt.is_finite() { width_pt.clamp(3.0, 14_400.0) } else { 612.0 };
let height = if height_pt.is_finite() { height_pt.clamp(3.0, 14_400.0) } else { 792.0 };
self.close_open_page();
let image_room = self.image_room(0);
self.open_page = Some(self.pages.len());
self.pages.push(Page {
width,
height,
content: String::new(),
fonts: [false; FONT_SLOTS],
images: Vec::new(),
image_room,
image_kept: 0,
image_index: HashMap::new(),
#[cfg(test)]
image_comparisons: 0,
@@ -1205,44 +1037,13 @@ impl PdfDoc {
&mut self.pages[i]
}
/// Lowers the bytes of image data the whole document keeps (never above
/// [`MAX_DOC_IMAGE_BYTES`], nor above a budget set before); images drawn past it are left out.
pub fn set_image_budget(&mut self, bytes: u64) {
let cap = self.image_budget.unwrap_or(MAX_DOC_IMAGE_BYTES);
self.image_budget = Some(bytes.min(cap));
}
/// Image bytes the document may still keep: its budget minus what every closed page holds
/// and the `open_kept` bytes of the page being handed out.
fn image_room(&self, open_kept: u64) -> u64 {
self.image_budget.unwrap_or(MAX_DOC_IMAGE_BYTES).saturating_sub(self.image_used.saturating_add(open_kept))
}
/// Folds the images the open page added since it was handed out into the document's count.
fn close_open_page(&mut self) {
if let Some(kept) = self.open_page.take().and_then(|i| self.pages.get(i)).map(|p| p.image_kept) {
self.image_used = self.image_used.saturating_add(kept);
}
}
pub fn page_count(&self) -> usize {
self.pages.len()
}
/// The page at `i`, to keep drawing on it.
pub fn page_mut(&mut self, i: usize) -> Option<&mut Page> {
if i >= self.pages.len() {
return None;
}
self.close_open_page();
let kept = self.pages.get(i)?.image_kept;
// Page `i` is open again: its bytes leave the closed count until the next hand-out.
self.image_used = self.image_used.saturating_sub(kept);
let room = self.image_room(kept);
self.open_page = Some(i);
let page = self.pages.get_mut(i)?;
page.image_room = room;
Some(page)
self.pages.get_mut(i)
}
/// Whether some Arabic text was set in the standard and CID fonts, which have no Arabic glyphs,
@@ -1286,9 +1087,8 @@ impl PdfDoc {
for (i, u) in used.iter().enumerate() {
if *u {
font_ids[i] = next;
// The CID font also needs its descendant font and font descriptor; a Latin
// Extended-A face its font descriptor.
next += font_objects(i);
// The CID font also needs its descendant font and font descriptor.
next += if i == CID_FONT { 3 } else { 1 };
}
}
// Page contents are moved out so each one is freed as soon as it is in the output.
@@ -1323,10 +1123,6 @@ impl PdfDoc {
)?;
continue;
}
if let Some(face) = i.checked_sub(EXT_FONT).and_then(|f| Font::ALL.get(f)) {
write_ext_font(&mut out, *id, *face)?;
continue;
}
let name = Font::ALL.get(i).copied().unwrap_or_default().base_name();
let enc = if name.starts_with("Symbol") { "" } else { " /Encoding /WinAnsiEncoding" };
out.object(*id, &format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name}{enc} >>"))?;
-141
View File
@@ -64,150 +64,9 @@ pub(crate) const TIMES_BOLD: [u16; 95] = [
394, 220, 394, 520, // '{'..'~'
];
/// Latin Extended-A (U+0100..=U+017F): the standard (Adobe Glyph List) glyph name of each
/// character and an ASCII character of similar width.
pub(crate) const LATIN_EXT_A: [(&str, char); 128] = [
("Amacron", 'A'),
("amacron", 'a'),
("Abreve", 'A'),
("abreve", 'a'),
("Aogonek", 'A'),
("aogonek", 'a'),
("Cacute", 'C'),
("cacute", 'c'),
("Ccircumflex", 'C'),
("ccircumflex", 'c'),
("Cdotaccent", 'C'),
("cdotaccent", 'c'),
("Ccaron", 'C'),
("ccaron", 'c'),
("Dcaron", 'D'),
("dcaron", 'd'),
("Dcroat", 'D'),
("dcroat", 'd'),
("Emacron", 'E'),
("emacron", 'e'),
("Ebreve", 'E'),
("ebreve", 'e'),
("Edotaccent", 'E'),
("edotaccent", 'e'),
("Eogonek", 'E'),
("eogonek", 'e'),
("Ecaron", 'E'),
("ecaron", 'e'),
("Gcircumflex", 'G'),
("gcircumflex", 'g'),
("Gbreve", 'G'),
("gbreve", 'g'),
("Gdotaccent", 'G'),
("gdotaccent", 'g'),
("Gcommaaccent", 'G'),
("gcommaaccent", 'g'),
("Hcircumflex", 'H'),
("hcircumflex", 'h'),
("Hbar", 'H'),
("hbar", 'h'),
("Itilde", 'I'),
("itilde", 'i'),
("Imacron", 'I'),
("imacron", 'i'),
("Ibreve", 'I'),
("ibreve", 'i'),
("Iogonek", 'I'),
("iogonek", 'i'),
("Idotaccent", 'I'),
("dotlessi", 'i'),
("IJ", 'N'),
("ij", 'x'),
("Jcircumflex", 'J'),
("jcircumflex", 'j'),
("Kcommaaccent", 'K'),
("kcommaaccent", 'k'),
("kgreenlandic", 'k'),
("Lacute", 'L'),
("lacute", 'l'),
("Lcommaaccent", 'L'),
("lcommaaccent", 'l'),
("Lcaron", 'L'),
("lcaron", 'l'),
("Ldot", 'L'),
("ldot", 'l'),
("Lslash", 'L'),
("lslash", 'l'),
("Nacute", 'N'),
("nacute", 'n'),
("Ncommaaccent", 'N'),
("ncommaaccent", 'n'),
("Ncaron", 'N'),
("ncaron", 'n'),
("napostrophe", 'n'),
("Eng", 'N'),
("eng", 'n'),
("Omacron", 'O'),
("omacron", 'o'),
("Obreve", 'O'),
("obreve", 'o'),
("Ohungarumlaut", 'O'),
("ohungarumlaut", 'o'),
("OE", 'W'),
("oe", 'm'),
("Racute", 'R'),
("racute", 'r'),
("Rcommaaccent", 'R'),
("rcommaaccent", 'r'),
("Rcaron", 'R'),
("rcaron", 'r'),
("Sacute", 'S'),
("sacute", 's'),
("Scircumflex", 'S'),
("scircumflex", 's'),
("Scedilla", 'S'),
("scedilla", 's'),
("Scaron", 'S'),
("scaron", 's'),
("Tcommaaccent", 'T'),
("tcommaaccent", 't'),
("Tcaron", 'T'),
("tcaron", 't'),
("Tbar", 'T'),
("tbar", 't'),
("Utilde", 'U'),
("utilde", 'u'),
("Umacron", 'U'),
("umacron", 'u'),
("Ubreve", 'U'),
("ubreve", 'u'),
("Uring", 'U'),
("uring", 'u'),
("Uhungarumlaut", 'U'),
("uhungarumlaut", 'u'),
("Uogonek", 'U'),
("uogonek", 'u'),
("Wcircumflex", 'W'),
("wcircumflex", 'w'),
("Ycircumflex", 'Y'),
("ycircumflex", 'y'),
("Ydieresis", 'Y'),
("Zacute", 'Z'),
("zacute", 'z'),
("Zdotaccent", 'Z'),
("zdotaccent", 'z'),
("Zcaron", 'Z'),
("zcaron", 'z'),
("longs", 'f'),
];
/// The [`LATIN_EXT_A`] entry of `c`, if it is in that block.
pub(crate) fn latin_ext_a(c: char) -> Option<(&'static str, char)> {
LATIN_EXT_A.get((c as u32).checked_sub(0x100)? as usize).copied()
}
/// Maps a non-ASCII character to an ASCII character of similar width, or `None` to use the
/// font's default width.
pub(crate) fn fold(c: char) -> Option<char> {
if let Some((_, base)) = latin_ext_a(c) {
return Some(base);
}
Some(match c {
'À'..='Å' => 'A',
'Æ' => 'W',
+2 -182
View File
@@ -923,81 +923,6 @@ fn cjk_text_is_not_replaced_by_question_marks() -> Result<(), Box<dyn Error>> {
Ok(())
}
/// A picture drawn on every page keeps only as many copies as the document-wide image budget
/// holds, and the running byte counts stay in step as pages are added and reopened.
#[test]
fn image_bytes_are_bounded_across_pages() -> Result<(), Box<dyn Error>> {
// Each page keeps its own copy of a picture it draws, so a picture repeated on every page of
// a long export grew without bound (a 3 KB workbook reached 2 GiB). The document-wide budget
// stops adding copies once it is spent.
let mut d = PdfDoc::new();
assert_eq!(d.add_page(100.0, 100.0).image_room(), MAX_DOC_IMAGE_BYTES);
d.set_image_budget(u64::MAX);
assert_eq!(d.add_page(100.0, 100.0).image_room(), MAX_DOC_IMAGE_BYTES, "the budget is never raised");
let mut d = PdfDoc::new();
d.set_image_budget(4);
d.set_image_budget(8);
assert_eq!(d.add_page(100.0, 100.0).image_room(), 4, "a later, higher budget doesn't raise a lower one");
let mut d = PdfDoc::new();
d.set_image_budget(10_000);
// Opaque 32×32: 4096 bytes of room needed, 3072 bytes (RGB, no mask) kept.
let px = [200u8, 200, 200, 255].repeat(32 * 32);
for _ in 0..50 {
let p = d.add_page(100.0, 100.0);
p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &px, [32, 32]);
}
let kept: u64 = d.pages.iter().map(Page::image_bytes).sum();
assert_eq!(kept, 2 * 3072);
assert_eq!(d.pages.iter().filter(|p| !p.images.is_empty()).count(), 2);
assert!(d.pages.iter().skip(2).all(|p| p.images.is_empty() && p.content.is_empty()));
// A page reopened later sees what the whole document already holds.
let p = d.page_mut(0).ok_or_else(|| io::Error::other("missing page"))?;
assert_eq!(p.image_room(), 10_000 - 2 * 3072);
// The copy page 0 already holds is drawn again past the budget; a new picture of the same
// size is refused; a small one still fits.
p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &px, [32, 32]);
p.image_rgba(Rect::new(0.0, 0.0, 50.0, 50.0), &[100u8, 100, 100, 255].repeat(32 * 32), [32, 32]);
p.image_rgba(Rect::new(0.0, 0.0, 10.0, 10.0), &[255; 4 * 4 * 4], [4, 4]);
assert_eq!(d.pages[0].images.len(), 2, "the new big picture is refused, the small one still fits");
assert_eq!(d.pages[0].content.matches(" Do Q").count(), 3, "the held copy is drawn twice, the small one once");
// The running per-page counts match the images each page holds, and a page handed out next
// sees what the reopened page added.
assert!(d.pages.iter().all(|p| p.image_kept == p.image_bytes()));
assert_eq!(d.add_page(100.0, 100.0).image_room(), 10_000 - 2 * 3072 - 4 * 4 * 3);
assert!(d.page_mut(10_000).is_none());
assert_eq!(d.page_mut(1).map(|p| p.image_room()), Some(10_000 - 2 * 3072 - 4 * 4 * 3));
let pdf = d.finish()?;
check_xref(&pdf)?;
// The identical 32×32 copies on pages 0 and 1 are written once; the 4×4 picture is the other.
assert_eq!(String::from_utf8_lossy(&pdf).matches("/Subtype /Image").count(), 2);
Ok(())
}
#[test]
fn a_picture_the_page_holds_is_drawn_again_after_the_budget_is_spent() -> Result<(), Box<dyn Error>> {
let mut d = PdfDoc::new();
// Room for exactly one translucent 1×1 picture (3 bytes of RGB plus 1 of alpha).
d.set_image_budget(4);
let p = d.add_page(100.0, 100.0);
let pixel = [10u8, 20, 30, 128];
p.image_rgba(Rect::new(0.0, 0.0, 10.0, 10.0), &pixel, [1, 1]);
assert_eq!(p.image_room(), 0);
p.image_rgba(Rect::new(20.0, 0.0, 10.0, 10.0), &pixel, [1, 1]);
p.image_rgba(Rect::new(40.0, 0.0, 10.0, 10.0), &[10u8, 20, 30, 64], [1, 1]);
assert_eq!(p.images.len(), 1, "a new picture past the budget is refused");
assert_eq!(p.content.matches("/Im1 Do Q").count(), 2, "the picture the page holds is drawn both times");
// Refused pictures leave no trace in the duplicate index, however many distinct ones come.
for v in 0..=255u8 {
p.image_rgba(Rect::new(60.0, 0.0, 10.0, 10.0), &[v, 0, 0, 64], [1, 1]);
}
assert_eq!(p.images.len(), 1);
assert_eq!(p.image_index.len(), 1, "a refused picture adds no index entry");
assert_eq!(p.image_index.values().map(Vec::len).sum::<usize>(), 1);
check_xref(&d.finish()?)?;
Ok(())
}
#[test]
fn arabic_is_shaped_and_preserved_or_falls_back_without_a_font() {
let text = "مَرْحَبًا 123 (ABC)";
@@ -1071,31 +996,6 @@ fn oversized_arabic_text_is_an_error_instead_of_partial_pdf() {
assert!(doc.finish().unwrap_err().to_string().contains("128 KiB"));
}
#[test]
fn arabic_fallback_sets_latin_extended_a_in_the_extended_font() {
if arabic::layout(Font::Helvetica, "مرحبا", TextDirection::Auto).is_err() && arabic::ARABIC_FONTS.is_empty() {
return;
}
// Noto Sans Arabic draws ő and Ş itself but lacks the Esperanto Ĉ and ĥ, which fall back to the standard face.
let text = "سلام ő Ĉu ĥ";
let items = arabic::layout(Font::Helvetica, text, TextDirection::Auto).unwrap().items;
// Drawn by the face itself or in the extended font, never in WinAnsi.
assert!(
items.iter().any(|item| matches!(item, arabic::Item::Glyph { source: text, .. } | arabic::Item::Ext { text, .. } if text.contains('Ĉ'))),
"{items:?}"
);
for item in items {
if let arabic::Item::Latin { text: drawn, .. } = &item {
assert!(!drawn.chars().any(|c| ext_code(c).is_some()), "{drawn:?} is set in WinAnsi, where it would print as ?");
}
}
let mut subset = arabic::Subset::default();
let body = subset.text(Font::Helvetica, text, 12.0, TextDirection::Auto).unwrap();
let ext = format!("/F{} ", EXT_FONT + Font::Helvetica.index() + 1);
assert_eq!(body.contains(&ext), subset.uses_ext[Font::Helvetica.index()], "the page declares the extended font it uses");
assert!(!body.contains("(?)") && !body.contains("?)"), "no letter falls back to ?: {body}");
}
#[test]
fn arabic_joining_marks_styles_and_rotation() {
if arabic::layout(Font::Helvetica, "مرحبا", TextDirection::Auto).is_err() && arabic::ARABIC_FONTS.is_empty() {
@@ -1171,7 +1071,7 @@ fn line_breaks_in_arabic_text_draw_as_spaces() {
{
let layout = arabic::layout(Font::Helvetica, text, direction).unwrap();
for item in &layout.items {
if let arabic::Item::Latin { text: drawn, .. } | arabic::Item::Ext { text: drawn, .. } = item {
if let arabic::Item::Latin { text: drawn, .. } = item {
assert!(!drawn.chars().any(|ch| matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')), "{drawn:?} from {text:?}");
}
}
@@ -1269,7 +1169,7 @@ fn arabic_explicit_base_changes_visual_order_and_preserves_logical_text() {
.into_iter()
.map(|item| match item {
arabic::Item::Glyph { source, .. } => source,
arabic::Item::Latin { text, .. } | arabic::Item::Ext { text, .. } | arabic::Item::Cid { text, .. } => text,
arabic::Item::Latin { text, .. } | arabic::Item::Cid { text, .. } => text,
})
.collect::<String>()
};
@@ -1360,83 +1260,3 @@ fn shared_run_length_preserves_pixels_at_packet_boundaries() {
// Two equal bytes may now terminate a literal packet. PDF pixel values stay exact.
assert_eq!(run_length(&[1, 2, 2, 3]), [0, 1, 255, 2, 0, 3, 128]);
}
#[test]
fn latin_extended_letters_use_the_latin_font() {
let mut doc = PdfDoc::new();
let p = doc.add_page(612.0, 792.0);
p.text(10.0, 20.0, 10.0, Font::Helvetica, [0, 0, 0], "tőrű ŐŰ");
let c = page_content(&doc).to_string();
assert!(!c.contains("<0151>") && !c.contains("<0171>"), "ő/ű set in the CJK font: {c}");
// ő, ű, Ő, Ű are bytes 0xD1, 0xF1, 0xD0, 0xF0 of the Helvetica Latin Extended-A resource.
// Resources: the faces, then the CID font, then their Latin Extended-A twins.
let ext = format!("/F{}", EXT_FONT + 1);
let expected = format!(
"/F1 10 Tf\n1 0 0 1 10 772 Tm\n(t) Tj\n{ext} 10 Tf\n<D1> Tj\n/F1 10 Tf\n(r) Tj\n{ext} 10 Tf\n<F1> Tj\n/F1 10 Tf\n( ) Tj\n{ext} 10 Tf\n<D0F0> Tj\n"
);
assert!(c.contains(&expected), "ő/ű not set through the Latin resource: {c}");
let pdf = doc.finish().unwrap();
check_xref(&pdf).unwrap();
assert!(find(&pdf, CID_BASE_FONT.as_bytes()).is_none(), "CJK font used for Latin letters");
for name in ["/ohungarumlaut", "/uhungarumlaut", "/Ohungarumlaut", "/Uhungarumlaut"] {
assert!(find(&pdf, name.as_bytes()).is_some(), "missing glyph name {name}");
}
assert_eq!(text_width(Font::Helvetica, 10.0, "ő"), text_width(Font::Helvetica, 10.0, "o"));
assert_eq!(text_width(Font::TimesBold, 10.0, "Ű"), text_width(Font::TimesBold, 10.0, "U"));
assert_eq!(text_width(Font::Courier, 10.0, "ł"), 6.0);
}
#[test]
fn latin_extended_resources_give_every_glyph_a_width() {
// Ccircumflex and other Extended-A names aren't in every standard font's metrics: the resource
// states each width, so no glyph gets a zero advance and overlaps the next letter.
for face in Font::ALL {
if face == Font::Symbol {
continue;
}
let mut doc = PdfDoc::new();
let p = doc.add_page(612.0, 792.0);
p.text(10.0, 20.0, 10.0, face, [0, 0, 0], "Ĉu ő");
let pdf = doc.finish().unwrap();
check_xref(&pdf).unwrap();
let text = String::from_utf8_lossy(&pdf);
let name = face.base_name();
let dict = text
.split("<< /Type /Font /Subtype /Type1 /BaseFont /")
.find(|d| d.starts_with(&format!("{name} /Encoding << /Type /Encoding /Differences")))
.unwrap();
assert!(dict.contains("/FirstChar 128 /LastChar 255 /Widths ["), "{name}: {dict}");
let widths = dict.split("/Widths [").nth(1).and_then(|w| w.split(']').next()).unwrap();
let widths: Vec<u16> = widths.split_whitespace().map(|w| w.parse().unwrap()).collect();
assert_eq!(widths.len(), 128, "{name}");
assert!(widths.iter().all(|&w| w > 0), "{name}: {widths:?}");
// Ĉ (U+0108) is set at its base letter's width.
assert_eq!(widths[8], face.char_width('C'), "{name}");
let desc = dict.split("/FontDescriptor ").nth(1).and_then(|d| d.split(' ').next()).unwrap();
assert!(text.contains(&format!("{desc} 0 obj\n<< /Type /FontDescriptor /FontName /{name} ")), "{name}: descriptor {desc}");
}
}
#[test]
fn latin_extended_letters_use_each_faces_own_resource() {
// Every face routed to a `/Differences` resource has the Latin glyphs; the symbolic standard
// fonts (Symbol, ZapfDingbats) lack them and are never routed there.
for face in Font::ALL {
let name = face.base_name();
if name.starts_with("Symbol") || name.starts_with("ZapfDingbats") {
continue;
}
let mut doc = PdfDoc::new();
let p = doc.add_page(612.0, 792.0);
p.text(10.0, 20.0, 10.0, face, [0, 0, 0], "ő");
let ext = Font::ALL.len() + 2 + face.index();
let c = page_content(&doc).to_string();
assert!(c.contains(&format!("/F{ext} 10 Tf\n")) && c.contains("<D1> Tj\n"), "{name}: {c}");
let pdf = doc.finish().unwrap();
check_xref(&pdf).unwrap();
let dict = format!("/BaseFont /{name} /Encoding << /Type /Encoding /Differences [128 /Amacron");
assert!(find(&pdf, dict.as_bytes()).is_some(), "{name}: no Latin Extended-A encoding");
assert!(find(&pdf, format!("/F{ext} ").as_bytes()).is_some(), "{name}: resource missing");
assert!(find(&pdf, CID_BASE_FONT.as_bytes()).is_none(), "{name}: CJK font used");
}
}

Some files were not shown because too many files have changed in this diff Show More