Compare commits

..
Author SHA1 Message Date
skylartaylor dd3f8a7138 nightly-tests: rustfmt the launcher fixture 2026-11-26 12:13:44 +01:00
skylartaylor 88e6bf0fba nightly-tests: give the launcher fixture the platform's absolute profile root
`launcher_argv` started a nightly with `/nightly-data/profiles/gridcraft`. Rust needs a prefix and a
root for an absolute path on Windows, so that spelling is relative there, `launch_profile::parse`
refuses it, and every test that builds argv with it fails on windows-latest - which runs this suite.

`launcher_root()` now returns the platform's spelling (`C:\NightlyData\profiles\gridcraft` on Windows,
`/nightly-data/profiles/gridcraft` elsewhere), and a new case refuses the other platform's spelling so
the fixture cannot drift back to a POSIX-only literal.
2026-11-26 11:05:59 +01:00
skylartaylor 1cf61ebf48 nightly: only options before -- name the control channel
The nightly control guard scanned the whole argv, so a document named `--control` after the
separator was read as the flag and the launch was refused with exit 2: a nightly handed
`-- --control` could not open that file.

`nightly_control_refused` now looks only at the tokens before `--`; everything after it stays a file,
as `desktop_args` already treats it. Three cases in `launch_separator_tests` cover `-- --control`
(the file opens, no port), `--control 7979 -- a.file` and `--control 7979` (the port is set and the
file still opens), plus the stable app keeping its channel.

cargo clippy -p gridcraft --all-targets -- -D warnings is clean; cargo test -p gridcraft --bin
gridcraft launch_separator_tests passes all five.
2026-11-26 09:57:16 +01:00
skylartaylor 1178a3594e nightly: drop the redundant control_port rebinding the gate refuses
`main` froze the mutable control-port binding with `let control_port = control_port;` after the
argument scan. The scan now lives in `desktop_args` and the value is bound immutably from the
environment and destructured from `DesktopArgs`, so that line rebinds an immutable binding to
itself - `clippy::redundant_locals`, which the gate's `-D warnings` turns into an error:

  error: redundant redefinition of a binding `control_port`
  --> apps/gridcraft/src/main.rs

Removing it changes nothing else: the value used further down is the one from the destructure.
2026-11-26 08:40:26 +01:00
skylartaylor bc65aa048c Merge main into the dashdash-launcher branch
gridcraft main de4e878a carries the fix for the redundant control_port binding that the
gate was failing on, plus the craft-common-actions 8389cad8 nightly re-pin.
2026-11-26 08:38:39 +01:00
skylartaylor fe148ab826 nightly: open the Launcher's files, not its -- separator
The Launcher starts a nightly as `--launch-profile nightly-v1 --profile-root
<dir> --` and `launch_profile::parse` hands the window `--` followed by the
file names. The argument scan in `main` had no arm for the separator, so it
was opened as a file: every nightly launch showed the alert `--: No such file
or directory (os error 2)` (Mac smoke of run 45749038918).

The scan moves into `desktop_args`, where `--` ends the options and
everything after it is a file. `main` keeps its `--control`,
`--control-token` and `--sample` handling unchanged.

The same smoke showed a refused launch hanging on macOS with no window: the
refusal opened rfd's message box before eframe's event loop, and that alert
needs the AppKit run loop this start never reaches. `refusal_dialog` now adds
the box only where one renders on its own (Windows, X11/Wayland); macOS gets
the reason on standard error and the caller's exit status 2.

Unit tests cover both argvs the Launcher sends, a file named like a flag after
the separator, and the dialog rule.
2026-11-26 05:32:08 +01:00
235 changed files with 1292 additions and 14574 deletions
+3 -3
View File
@@ -4,10 +4,10 @@
"repository_id": 1408285582,
"producer_workflow_id": 429713469,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "3dee18226ed28134896f69fb8b280fff9247ec7f",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@3dee18226ed28134896f69fb8b280fff9247ec7f",
"producer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "3dee18226ed28134896f69fb8b280fff9247ec7f",
"signer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
+5 -21
View File
@@ -34,28 +34,12 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@3dee18226ed28134896f69fb8b280fff9247ec7f
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a
with:
tooling-revision: 3dee18226ed28134896f69fb8b280fff9247ec7f
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
app-name: gridcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# Forward exactly the secrets the signer's sign steps read, named explicitly (never `inherit`),
# as the stable Release caller does. The callee must declare them; it does since the shared
# change that added them, and `uses:` is pinned to that revision.
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@3dee18226ed28134896f69fb8b280fff9247ec7f
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a
with:
tooling-revision: 3dee18226ed28134896f69fb8b280fff9247ec7f
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
app-name: gridcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
Generated
+50 -30
View File
@@ -211,6 +211,15 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "arboard"
version = "3.7.0"
@@ -227,7 +236,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -914,15 +923,6 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "constant_time_eq"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"
dependencies = [
"rustversion",
]
[[package]]
name = "cookie-factory"
version = "0.3.3"
@@ -1601,7 +1601,7 @@ dependencies = [
"verifysign",
"winreg",
"winsafe",
"zip",
"zip 9.1.0",
]
[[package]]
@@ -1709,7 +1709,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259e
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip",
"zip 9.1.0",
]
[[package]]
@@ -1843,6 +1843,17 @@ version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "dify"
version = "0.8.0"
@@ -1896,7 +1907,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -2303,7 +2314,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -2901,7 +2912,7 @@ dependencies = [
"log",
"quick-xml 0.41.0",
"serde_json",
"zip",
"zip 3.0.0",
]
[[package]]
@@ -2938,7 +2949,7 @@ dependencies = [
"thiserror 2.0.21",
"unicode-segmentation",
"web-time",
"zip",
"zip 3.0.0",
]
[[package]]
@@ -2987,7 +2998,6 @@ dependencies = [
"gridcraft-math",
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.1",
"thiserror 2.0.21",
]
@@ -3095,7 +3105,7 @@ dependencies = [
"quick-xml 0.41.0",
"sha2 0.11.1",
"thiserror 2.0.21",
"zip",
"zip 3.0.0",
]
[[package]]
@@ -4835,7 +4845,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5324,7 +5334,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5765,7 +5775,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5824,7 +5834,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6644,7 +6654,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -7739,7 +7749,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -8484,22 +8494,32 @@ dependencies = [
[[package]]
name = "zip"
version = "9.8.2"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
dependencies = [
"arbitrary",
"crc32fast",
"flate2",
"indexmap",
"memchr",
"zopfli",
]
[[package]]
name = "zip"
version = "9.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704"
dependencies = [
"constant_time_eq",
"crc32fast",
"flate2",
"getrandom 0.4.3",
"indexmap",
"libc",
"memchr",
"nix",
"typed-path",
"windows-sys 0.61.2",
"zeroize",
"zopfli",
]
[[package]]
+1 -3
View File
@@ -65,10 +65,8 @@ web-time = "1.1.0"
rayon = "1"
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
quick-xml = "0.41"
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
zip = { version = "3", 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 -27
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,15 +151,10 @@ 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 |
| 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) |
@@ -171,8 +165,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: 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) |
@@ -192,20 +184,14 @@ 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 |
@@ -223,7 +209,6 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) |
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
| 2026-10-12 | PDF writer: objects are written straight to the output, identical pictures are stored once, style operators are emitted only when they change, `q` nesting is limited to 28 and polyline joins no longer leak into later strokes (#816) |
| 2026-10-12 | Insert › Text › WordArt (`insert.wordArt`, `wordArt.set`): floating decorative text with 10 original styles, outline and shadow, in-place editing, XLSX and print (#784) |
@@ -296,7 +281,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 |
@@ -312,16 +296,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 | 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) |
@@ -334,21 +315,14 @@ 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 |
+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> {
+33 -92
View File
@@ -110,20 +110,12 @@ fn resolve_target(source_dir: &str, target: &str) -> String {
type Zip<'a> = zip::ZipArchive<Cursor<&'a [u8]>>;
/// `(index, name)` of every file entry. Parts are read by index: two entries can decode to the
/// same name, and looking up a CP437 name scans the whole archive.
fn zip_names(zip: &mut Zip<'_>) -> Vec<(usize, String)> {
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| (i, entry_name(&f)))).collect()
fn zip_names(zip: &mut Zip<'_>) -> Vec<String> {
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| f.name().to_string())).collect()
}
/// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode
/// is listed with its raw bytes made lossy, so the entry is still checked and reported.
fn entry_name<R: std::io::Read>(f: &zip::read::ZipFile<'_, R>) -> String {
f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned())
}
fn read_zip_part(zip: &mut Zip<'_>, index: usize, name: &str) -> Result<Vec<u8>, String> {
let f = zip.by_index(index).map_err(|e| format!("{name}: {e}"))?;
fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
let mut buf = Vec::new();
f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?;
Ok(buf)
@@ -136,8 +128,8 @@ enum PartError {
}
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_index(index).map_err(|_| PartError::Unreadable)?;
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
// One byte past what is left shows that the part doesn't fit.
let limit = MAX_XML_PART.min(budget.saturating_add(1));
let mut buf = Vec::new();
@@ -158,10 +150,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Re
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
let Ok(mut zip) = zip::ZipArchive::new(Cursor::new(bytes)) else { return false };
let names = zip_names(&mut zip);
let find = |key: &str| names.iter().find(|(_, n)| part_key(n) == key).cloned();
let find = |key: &str| names.iter().find(|n| part_key(n) == key).cloned();
let mut workbook = "xl/workbook.xml".to_string();
if let Some((i, rels)) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, i, &rels)
if let Some(rels) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, &rels)
&& let Ok(els) = xml_elements(&xml)
&& let Some(target) = els
.iter()
@@ -170,8 +162,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
{
workbook = resolve_target("", target);
}
let Some((i, name)) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false };
let Some(name) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, &name) else { return false };
xml_elements(&xml)
.ok()
.into_iter()
@@ -185,15 +177,15 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let parts: HashSet<String> = names.iter().map(|(_, n)| part_key(n)).collect();
let mut read_part = |index: usize, name: &str| read_zip_part(&mut zip, index, name);
let parts: HashSet<String> = names.iter().map(|n| part_key(n)).collect();
let mut read_part = |name: &str| read_zip_part(&mut zip, name);
let mut issues = Vec::new();
let ct_name = names.iter().find(|(_, n)| part_key(n) == "[content_types].xml").cloned();
let ct_name = names.iter().find(|n| part_key(n) == "[content_types].xml").cloned();
let (mut defaults, mut overrides) = (HashSet::new(), HashSet::new());
match ct_name {
None => issues.push("no [Content_Types].xml".to_string()),
Some((i, n)) => {
for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
Some(n) => {
for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
match el.as_str() {
"Default" => {
if let Some(x) = attr(&attrs, "Extension") {
@@ -210,9 +202,9 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
}
}
}
let mut sorted: Vec<&(usize, String)> = names.iter().collect();
sorted.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
for (_, n) in &sorted {
let mut sorted: Vec<&String> = names.iter().collect();
sorted.sort();
for n in &sorted {
let key = part_key(n);
if key == "[content_types].xml" {
continue;
@@ -227,7 +219,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
for p in missing_overrides {
issues.push(format!("content type override for missing part /{p}"));
}
for (i, n) in sorted {
for n in sorted {
let key = part_key(n);
let Some(rels_file) = key.strip_suffix(".rels") else { continue };
// `dir/_rels/name.rels` describes `dir/name`; `_rels/.rels` the package itself.
@@ -241,7 +233,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
issues.push(format!("{n} describes missing part {source}"));
}
let mut ids = HashSet::new();
for (el, attrs) in xml_elements(&read_part(*i, n)?).map_err(|e| format!("{n}: {e}"))? {
for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? {
if el != "Relationship" {
continue;
}
@@ -276,17 +268,17 @@ pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let by_key: HashMap<String, &(usize, String)> = names.iter().map(|e| (part_key(&e.1), e)).collect();
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
// Several relationships name the same part; each fresh check decompressed it again, so
// repeated references to one highly compressible part multiplied the work. The verdict is
// remembered per (part, named content) and the decompression the package can cause is
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
// would otherwise each spend a full per-part allowance.
let mut verdicts: HashMap<(usize, &'static str), bool> = HashMap::new();
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
let mut kinds = BTreeMap::new();
for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) {
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
let xml = match read_zip_part_within(&mut zip, *i, &mut budget) {
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
Ok(xml) => xml,
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
Err(PartError::Unreadable) => continue,
@@ -300,8 +292,8 @@ fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<S
}
let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External"));
if !external
&& let Some((index, _)) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, *index, kind, &mut verdicts, &mut budget)
&& let Some(part) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, part, kind, &mut verdicts, &mut budget)
{
continue;
}
@@ -322,7 +314,7 @@ fn rels_source_dir(key: &str) -> Option<String> {
/// comes first) a comment, for VML a shape. Read only as far as needed; an unreadable part counts.
/// `verdicts` remembers the answer per (part, named content); `budget` is the decompression this
/// package's remaining checks may cause, and once it is spent the part counts as having content.
fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool {
fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'static str), bool>, budget: &mut u64) -> bool {
let wanted: Option<&'static [u8]> = match kind.to_ascii_lowercase().as_str() {
"comments" => Some(b"comment"),
"vmldrawing" => Some(b"shape"),
@@ -333,17 +325,17 @@ fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut H
Some(_) => "shape",
None => "any",
};
if let Some(v) = verdicts.get(&(index, marker)) {
if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) {
return *v;
}
let v = holds_something_uncached(zip, index, marker, budget);
verdicts.insert((index, marker), v);
let v = holds_something_uncached(zip, name, marker, budget);
verdicts.insert((name.to_ascii_lowercase(), marker), v);
v
}
fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool {
fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool {
use quick_xml::events::Event;
let Ok(f) = zip.by_index(index) else { return true };
let Ok(f) = zip.by_name(name) else { return true };
if *budget == 0 {
return true;
}
@@ -400,57 +392,6 @@ mod tests {
z.finish().unwrap().into_inner()
}
/// A package with two relationship parts whose names both read `xl/_rels/é.xml.rels`: the first
/// stored as UTF-8 holding `first`, the second stored as CP437 (byte 0x82) holding `second`.
fn same_name_rels(first: &str, second: &str) -> Vec<u8> {
const PLACEHOLDER: &[u8] = b"xl/_rels/Q.xml.rels";
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
z.start_file("xl/_rels/\u{e9}.xml.rels", opts).unwrap();
z.write_all(first.as_bytes()).unwrap();
z.start_file(String::from_utf8(PLACEHOLDER.to_vec()).unwrap(), opts).unwrap();
z.write_all(second.as_bytes()).unwrap();
let mut bytes = z.finish().unwrap().into_inner();
// The name sits in the local header and in the central directory; both get the CP437 byte.
let mut at = 0;
let mut patched = 0;
while let Some(i) = bytes.get(at..).and_then(|rest| rest.windows(PLACEHOLDER.len()).position(|w| w == PLACEHOLDER)) {
bytes[at + i + 9] = 0x82;
at += i + PLACEHOLDER.len();
patched += 1;
}
assert_eq!(patched, 2);
bytes
}
fn rels_xml(rels: &[(&str, &str)]) -> String {
let body: String = rels
.iter()
.map(|(id, kind)| {
format!(
r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}" Target="https://example.com" TargetMode="External"/>"#
)
})
.collect();
format!(r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{body}</Relationships>"#)
}
#[test]
fn parts_with_the_same_decoded_name_are_each_validated() {
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "custom"), ("rId1", "custom")]));
let issues = validate_package(&bytes).unwrap();
let duplicates = issues.iter().filter(|i| i.ends_with("duplicate relationship id rId1")).count();
assert_eq!(duplicates, 1, "{issues:?}");
}
#[test]
fn relationship_kinds_read_parts_with_the_same_decoded_name() {
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "audio")]));
let kinds = relationship_kinds(&bytes).unwrap();
assert!(kinds.contains_key("custom"), "{kinds:?}");
assert!(kinds.contains_key("audio"), "{kinds:?}");
}
#[test]
fn relationship_parts_count_against_the_decompression_budget() {
// Each part fits the per-part allowance, but together they need more than the budget.
+1 -1
View File
@@ -344,7 +344,7 @@ fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec
let mut pending: Vec<(&str, &str)> = rels.to_vec();
for i in 0..src.len() {
let mut f = src.by_index(i).unwrap();
let name = f.name().unwrap().to_string();
let name = f.name().to_string();
let mut body = String::new();
f.read_to_string(&mut body).unwrap();
if let Some(at) = pending.iter().position(|(r, _)| *r == name) {
-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"
-27
View File
@@ -62,28 +62,6 @@ pub struct Lambda {
pub env: Vec<(String, Ev)>,
}
/// What the tail of a LAMBDA body came to.
enum Tail {
Done(Ev),
/// A call to make in place of the current one, its arguments evaluated.
Call(Arc<Lambda>, Vec<(String, Ev)>),
}
/// A tail call can pass a closure that captures the previous one, thousands deep. Releasing the
/// chain is a loop, not a recursion, so it cannot overflow the native stack.
impl Drop for Lambda {
fn drop(&mut self) {
let mut pending = std::mem::take(&mut self.env);
while let Some((_, ev)) = pending.pop() {
if let Ev::L(l) = ev
&& let Ok(mut inner) = Arc::try_unwrap(l)
{
pending.append(&mut inner.env);
}
}
}
}
#[derive(Clone, Debug)]
pub enum Ev {
V(Value),
@@ -106,11 +84,6 @@ fn err(e: CellError) -> Ev {
/// calls in progress, so it still runs.
const MAX_LAMBDA_CALLS: usize = 140;
/// Tail calls one LAMBDA call may chain. They run in a loop on one native frame, so this only keeps
/// an endless tail recursion finite. Excel computes a tail countdown to 5,459 and answers `#NUM!`
/// for 5,460, which is 5,460 invocations in the chain.
const MAX_TAIL_CALLS: usize = 5460;
/// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it,
/// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames
/// above the formula. A cell that another cell's formula computes on demand shares the budget of the
+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),
-11
View File
@@ -5,17 +5,6 @@ use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, Lambda, Pip
use std::sync::Arc;
impl<'h> Evaluator<'h> {
/// `IF` with an array condition: element-wise.
pub(super) fn if_elementwise(&mut self, arr: &Array, args: &[Expr]) -> Ev {
let t = self.arg_val(args, 1).unwrap_or(Value::Bool(true));
let f = if args.len() > 2 { self.arg_val(args, 2).unwrap_or(Value::Bool(false)) } else { Value::Bool(false) };
Ev::V(zip3(arr, &t, &f, |c, t, f| match c.to_bool() {
Ok(true) => t.clone(),
Ok(false) => f.clone(),
Err(e) => Value::Error(e),
}))
}
pub(super) fn call(&mut self, name: &str, args: &[Expr]) -> Ev {
match name {
"IF" => self.if_call(args),
+4 -84
View File
@@ -1,26 +1,17 @@
use super::MAX_LAMBDA_CALLS;
use super::array::{broadcast_len, single};
use super::special::is_special;
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, Value, err};
use std::sync::Arc;
impl<'h> Evaluator<'h> {
pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev {
match self.bind_args(l, args) {
Ok(bound) => self.call_lambda_values(l, bound),
Err(e) => e,
}
}
/// The arguments of a call to `l`, evaluated in the current scope.
fn bind_args(&mut self, l: &Lambda, args: &[Expr]) -> Result<Vec<(String, Ev)>, Ev> {
// Too many or too few argument positions is #VALUE!. An explicitly empty position, as in
// `(1,)`, is `Expr::Missing` and still counts as a position (it binds as omitted). `f()`
// parses to no arguments, which for a one-parameter lambda can also be read as one empty
// position, so that call still binds the parameter as omitted.
let positions_ok = args.len() == l.params.len() || (args.is_empty() && l.params.len() == 1);
if !positions_ok {
return Err(err(CellError::Value));
return err(CellError::Value);
}
let mut bound = Vec::with_capacity(l.params.len());
for (i, p) in l.params.iter().enumerate() {
@@ -30,56 +21,7 @@ impl<'h> Evaluator<'h> {
};
bound.push((p.clone(), v));
}
Ok(bound)
}
/// Follows `e` through the positions whose value is the value of a LAMBDA call (`IF` branches,
/// parentheses), and returns the call with its arguments evaluated instead of making it, so
/// that `call_lambda_values` can loop. Anything else is evaluated here.
fn tail_step(&mut self, e: &Expr) -> Tail {
match e {
Expr::Paren(x) => self.tail_step(x),
Expr::Call(name, args) if name == "IF" && (2..=3).contains(&args.len()) => {
let c = self.arg_val(args, 0).unwrap_or_default();
if let Value::Array(arr) = &c {
return Tail::Done(self.if_elementwise(arr, args));
}
match c.to_bool() {
Ok(true) => self.tail_step_branch(args.get(1)),
Ok(false) => match args.get(2) {
Some(_) => self.tail_step_branch(args.get(2)),
None => Tail::Done(Ev::V(Value::Bool(false))),
},
Err(x) => Tail::Done(err(x)),
}
}
Expr::Call(name, args) if gridcraft_functions::lookup(name).is_none() && !is_special(name) => match self.name(name) {
Ev::L(l) => self.tail_call(l, args),
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
_ => Tail::Done(err(CellError::Name)),
},
Expr::Invoke(callee, args) => match self.eval(callee) {
Ev::L(l) => self.tail_call(l, args),
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
_ => Tail::Done(err(CellError::Value)),
},
_ => Tail::Done(self.eval(e)),
}
}
/// An `IF` branch; an omitted one (`IF(c,,1)`) is 0.
fn tail_step_branch(&mut self, branch: Option<&Expr>) -> Tail {
match branch {
Some(Expr::Missing) | None => Tail::Done(Ev::V(Value::Number(0.0))),
Some(b) => self.tail_step(b),
}
}
fn tail_call(&mut self, l: Arc<Lambda>, args: &[Expr]) -> Tail {
match self.bind_args(&l, args) {
Ok(bound) => Tail::Call(l, bound),
Err(e) => Tail::Done(e),
}
self.call_lambda_values(l, bound)
}
pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev {
@@ -96,29 +38,7 @@ impl<'h> Evaluator<'h> {
self.calls += 1;
let saved = std::mem::replace(&mut self.env, l.env.clone());
self.env.extend(bound);
// A call in tail position replaces this one instead of nesting under it, so a tail recursion
// uses no more native stack at 5,000 deep than at 5. Each link still spends fuel.
let mut tails = 0;
let mut step = self.tail_step(&l.body);
let r = loop {
match step {
Tail::Done(v) => break v,
Tail::Call(next, bound) => {
tails += 1;
if tails >= MAX_TAIL_CALLS {
break err(CellError::Num);
}
self.fuel = match self.fuel.checked_sub(1) {
Some(f) => f,
None => break err(CellError::Calc),
};
self.env.clear();
self.env.extend(next.env.iter().cloned());
self.env.extend(bound);
step = self.tail_step(&next.body);
}
}
};
let r = self.eval(&l.body);
self.env = saved;
self.calls -= 1;
r
+1 -1
View File
@@ -195,7 +195,7 @@ impl Precedents<'_> {
}
}
pub(super) fn is_special(n: &str) -> bool {
fn is_special(n: &str) -> bool {
matches!(
n,
"IF" | "IFS"
+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;
+2 -3
View File
@@ -718,7 +718,7 @@ impl Calc {
} else {
Vec::new()
};
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing, array.data.len());
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
if !blocked {
for (o, r) in outranked {
for c in r.iter() {
@@ -785,7 +785,6 @@ fn spill_is_blocked(
range: RangeRef,
end: CellRef,
standing: &Standing,
array_len: usize,
) -> bool {
let outranked = |cell: CellRef| {
sheet
@@ -797,7 +796,7 @@ fn spill_is_blocked(
|| end.col >= gridcraft_core::MAX_COLS
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
|| sheet.merges.iter().any(|merge| merge.intersects(&range))
|| (array_len > 1 && sheet.tables.iter().any(|table| table.range.contains(anchor.1)))
|| sheet.tables.iter().any(|table| table.range.contains(anchor.1))
}
fn fill_spill(sheet: &mut gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, array: &Array) {
+3 -4
View File
@@ -162,8 +162,7 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
})
}
/// Whether an array result at `k` can't spill: it is in a table (a one-value result is shown
/// there, as in Excel), or its area runs off the sheet,
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
@@ -189,7 +188,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
end.row >= gridcraft_core::MAX_ROWS
|| end.col >= gridcraft_core::MAX_COLS
|| sh.merges.iter().any(|m| m.intersects(&range))
|| (a.data.len() > 1 && sh.tables.iter().any(|t| t.range.contains(anchor)))
|| sh.tables.iter().any(|t| t.range.contains(anchor))
|| sh.cells.iter_range(range).any(|(c, cell)| c != anchor && (!cell.value.is_empty() || cell.formula.is_some()))
|| sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c) && spilled_over(*c))
}
@@ -201,7 +200,7 @@ pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef,
CellRef::new(anchor.row.saturating_add((arr.rows as u32).saturating_sub(1)), anchor.col.saturating_add((arr.cols as u32).saturating_sub(1)));
RangeRef::new(anchor, end) == range
&& !sheet.merges.iter().any(|m| m.intersects(&range))
&& (arr.data.len() <= 1 || !sheet.tables.iter().any(|t| t.range.contains(anchor)))
&& !sheet.tables.iter().any(|t| t.range.contains(anchor))
&& range
.iter()
.enumerate()
+3 -161
View File
@@ -820,42 +820,6 @@ fn arrays_do_not_spill_in_tables() {
assert_eq!(t.num("E4"), 4.0);
}
#[test]
fn one_value_array_in_a_table_is_not_a_spill() {
// Excel shows a one-value dynamic-array result in a table column; two or more is #SPILL! (#2335).
let table = |range: &str| gridcraft_model::Table {
id: 1,
name: "Table1".into(),
range: gridcraft_core::RangeRef::parse(range).unwrap(),
header_row: true,
totals_row: false,
columns: vec![],
style: String::new(),
banded_rows: false,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: false,
filter: vec![],
table_type: None,
connection_id: None,
};
let mut t = T::new();
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
t.set("A1", "7");
t.set("A2", "8");
t.set("C4", "=FILTER(A1:A2,A1:A2>7)");
t.set("C5", "=FILTER(A1:A2,A1:A2>0)");
t.set("H4", "=FILTER(A1:A2,A1:A2>7)");
t.set("D4", "=ROWS(C4#)");
assert_eq!((t.num("C4"), t.num("H4"), t.num("D4")), (8.0, 8.0, 1.0));
assert_eq!(t.get("C5"), Value::Error(CellError::Spill));
// Recalculating again keeps the one-value result.
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.num("C4"), 8.0);
assert_eq!(t.num("D4"), 1.0);
}
#[test]
fn ifs_and_lazy() {
let mut t = T::new();
@@ -1217,67 +1181,17 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() {
comment: String::new(),
hidden: false,
});
// W's call to `f` is a tail call, so a wrapped call level costs one call in progress, not two. A tail call reuses its frame, so the tail chain is bounded by `MAX_TAIL_CALLS`, as in Excel
// (5,459 ok, 5,460 #NUM!). F(F,n) otherwise has n + 1 calls in progress at its deepest; W adds
// one more call per step.
// F(F,n) has n + 1 calls in progress at its deepest; W adds one more call per step.
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
let wrapped = |n: u32| format!("=LET(W,LAMBDA(f,k,f(f,k)),F,LAMBDA(me,n,IF(n<=0,0,1+W(me,n-1))),F(F,{n}))");
[tail(5459), tail(5460), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
[tail(139), tail(140), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
})
.expect("spawn")
.join()
.expect("recursion must not overflow the stack")
};
let small = run(1 << 20);
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Number(70.0), Value::Number(131.0)]);
assert_eq!(run(64 << 20), small);
}
#[test]
fn a_tail_recursive_lambda_reaches_excels_depth_on_a_small_stack() {
// Excel (measured): a tail countdown is 0 at 5,000 and 5,459 and #NUM! at 5,460 and 10,000.
let run = |stack: usize| {
std::thread::Builder::new()
.stack_size(stack)
.spawn(|| {
let mut wb = Workbook::new();
wb.names.push(gridcraft_model::DefinedName {
name: "TAILN".into(),
scope: None,
formula: "LAMBDA(n,IF(n=0,0,TAILN(n-1)))".into(),
comment: String::new(),
hidden: false,
});
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
// The same chain through parentheses and an applied lambda, and one that returns the base case's value.
let paren = "=LET(F,LAMBDA(me,n,IF(n=0,7,(me(me,n-1)))),F(F,5000))".to_string();
let invoke = "=LET(F,LAMBDA(me,n,IF(n=0,7,LAMBDA(a,b,me(me,a))(n-1,0))),F(F,2000))".to_string();
let endless = "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))".to_string();
// Each call passes a closure that captures the last, 5,000 deep: releasing them must not recurse.
let closures = "=LET(F,LAMBDA(me,n,acc,IF(n=0,0,me(me,n-1,LAMBDA(x,acc)))),F(F,5000,0))".to_string();
[tail(5000), tail(5459), tail(5460), tail(10000), paren, invoke, endless, "=TAILN(5000)".to_string(), closures]
.map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
})
.expect("spawn")
.join()
.expect("tail recursion must not overflow the stack")
};
let num = Value::Error(CellError::Num);
let small = run(1 << 20);
assert_eq!(
small,
[
Value::Number(0.0),
Value::Number(0.0),
num.clone(),
num.clone(),
Value::Number(7.0),
Value::Number(7.0),
num,
Value::Number(0.0),
Value::Number(0.0)
]
);
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]);
assert_eq!(run(64 << 20), small);
}
@@ -2121,65 +2035,6 @@ fn offset_extreme_arguments_return_ref() {
}
}
/// Sorting and ranking compare numbers exactly while `=` and COUNTIF compare them at 15
/// significant digits. Every expectation was observed in Excel 365 with these fixtures
/// (`=0.1+0.2` is 0.30000000000000004): 0.3 sorts first whatever the input order.
#[test]
fn sorts_and_ranks_compare_numbers_exactly() {
let mut t = T::new();
for (at, input) in [
// The noisy value first, then the exact one first.
("A1", "=0.1+0.2"),
("B1", "e"),
("A2", "0.3"),
("B2", "t"),
("D1", "0.3"),
("E1", "t"),
("D2", "=0.1+0.2"),
("E2", "e"),
("G1", "=100+1E-14"),
("H1", "e"),
("G2", "100"),
("H2", "t"),
] {
t.set(at, input);
}
let e = 0.1 + 0.2;
let n = Value::Number;
let s = |x: &str| Value::from(x);
let cases: Vec<(&str, Value)> = vec![
("=A1=A2", Value::Bool(true)),
("=COUNTIF(A1:A2,0.3)", n(2.0)),
("=INDEX(SORT(A1:B2),1,2)", s("t")),
("=INDEX(SORT(D1:E2),1,2)", s("t")),
("=INDEX(SORT(A1:B2,1,-1),1,2)", s("e")),
("=INDEX(SORT(D1:E2,1,-1),1,2)", s("e")),
("=INDEX(SORT(G1:H2),1,2)", s("t")),
("=INDEX(SORT(G1:H2,1,-1),1,2)", s("e")),
("=INDEX(SORTBY(B1:B2,A1:A2),1,1)", s("t")),
("=INDEX(SORTBY(E1:E2,D1:D2),1,1)", s("t")),
("=INDEX(SORTBY(B1:B2,A1:A2,-1),1,1)", s("e")),
("=INDEX(SORTBY(E1:E2,D1:D2,-1),1,1)", s("e")),
// Already exact: UNIQUE, RANK, LARGE/SMALL, MODE.
("=ROWS(UNIQUE(A1:A2))", n(2.0)),
("=RANK.EQ(0.3,A1:A2)", n(2.0)),
("=RANK.EQ(0.3,A1:A2,1)", n(1.0)),
("=RANK.AVG(0.3,A1:A2)", n(2.0)),
("=RANK.EQ(0.3,A1)", Value::Error(CellError::NA)),
("=LARGE(A1:A2,1)", n(e)),
("=SMALL(A1:A2,1)", n(0.3)),
("=MODE.SNGL(A1:A2,5)", Value::Error(CellError::NA)),
];
let mut wrong = Vec::new();
for (formula, expected) in cases {
let got = crate::evaluate(&t.wb, 0, c("Z1"), formula);
if got != expected {
wrong.push(format!("{formula}: got {got:?}, Excel {expected:?}"));
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// `@` intersects a reference with the formula's row (a column range) or column (a row range);
/// a 2D range both (circular when it includes the formula's cell); a range the formula does not
/// line up with gives #VALUE!. An array gives its top-left value. Legacy formulas read from files use it where Excel intersects implicitly.
@@ -2762,19 +2617,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);
+1 -59
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,
@@ -1493,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", "", ""];
-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");
}
}
+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};
-26
View File
@@ -49,19 +49,6 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option<f64> {
parse_numeric(s.trim(), sys).map(|(n, _)| n)
}
/// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users
/// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5,
/// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse
/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. So does `+`
/// before a time (`+1:30`), while `-1:30` is a formula (rows 1 to 30), as Excel for the web does.
pub fn starts_formula(input: &str) -> bool {
input.starts_with('=')
|| (input.len() > 1
&& input.starts_with(['+', '-'])
&& parse_number_text(input).is_none()
&& !input.strip_prefix('+').is_some_and(|time| time.contains(':') && parse_number_text(time).is_some()))
}
/// Text that Excel's "Number Stored as Text" check flags: it would be a number if typed (signs,
/// thousands separators, currency, percent, exponent, a parenthesised negative). Dates, times and
/// fractions kept as text are not flagged, as in Excel.
@@ -590,19 +577,6 @@ mod tests {
assert_eq!(p("1.2.3.4").value, Value::text("1.2.3.4"));
}
#[test]
fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() {
// #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did.
for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--", "-1:30", "+1/30", "-1/30"] {
assert!(starts_formula(s), "{s}");
}
// Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or
// apostrophe, `+` before a time and other text stay text.
for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b", "+1:30", "+0:30:15"] {
assert!(!starts_formula(s), "{s}");
}
}
#[test]
fn dates_and_times() {
assert_eq!(p("10/7/2026").value, Value::Number(46302.0));
-52
View File
@@ -434,16 +434,12 @@ fn secondary_weights(s: &str) -> impl Iterator<Item = u16> + '_ {
}
/// Sorting order used by Sort (ascending): numbers, text, booleans, errors, then blanks last.
/// Numbers compare exactly, not at the 15 digits of [`compare`]. Observed in Excel 365: SORT,
/// SORTBY, Data > Sort, the AutoFilter sort and table sort all put 0.3 before `=0.1+0.2`
/// (0.30000000000000004) ascending and after it descending, whatever the input order.
pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
match (a, b) {
(Value::Empty, Value::Empty) => Ordering::Equal,
(Value::Empty, _) => Ordering::Greater,
(_, Value::Empty) => Ordering::Less,
(Value::Error(_), Value::Error(_)) => Ordering::Equal,
(Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
_ => compare(a, b),
}
}
@@ -501,31 +497,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 +580,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);
@@ -814,19 +775,6 @@ mod tests {
assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less);
}
#[test]
fn sort_orders_numbers_exactly() {
let num = Value::Number;
let e = 0.1 + 0.2;
assert_eq!(sort_compare(&num(0.3), &num(e)), Ordering::Less);
assert_eq!(sort_compare(&num(e), &num(0.3)), Ordering::Greater);
assert_eq!(sort_compare(&num(100.0), &num(100.0 + 1e-14)), Ordering::Less);
assert_eq!(sort_compare(&num(0.0), &num(-0.0)), Ordering::Equal);
assert_eq!(sort_compare(&num(1.0), &Value::from("a")), Ordering::Less);
// `=` keeps its 15-digit comparison.
assert_eq!(compare(&num(0.3), &num(e)), Ordering::Equal);
}
#[test]
fn arrays() -> Result<(), std::io::Error> {
let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).ok_or_else(|| std::io::Error::other("valid array"))?;
-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());
}
-2
View File
@@ -18,7 +18,6 @@ pub mod macros;
pub mod pivot;
pub mod print;
pub mod python;
pub mod quick_analysis;
pub mod review;
pub mod sheet;
pub mod slicer;
@@ -188,7 +187,6 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(forecast::specs());
v.extend(analysis::specs());
v.extend(print::specs());
v.extend(quick_analysis::specs());
v
})
}
+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), _)| {
+1 -3
View File
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
"AutoFill",
[],
None,
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years|linearTrend|growthTrend}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday; linearTrend, growthTrend = Linear Trend, Growth Trend: the targets continue the least-squares line or the exponential curve fitted to each row or column of source numbers, and the source keeps its values; an error when a source cell is not a number or holds a formula, or for growthTrend when a row or column mixes signs or holds zero)",
"{source: \"A1:A2\", target: \"A1:A10\", mode?: series|alternate|copy|formats|values|extend|days|weekdays|months|years}: the fill-handle drag (alternate = Ctrl+drag: a lone number counts up, any other series copies; values = Fill Without Formatting: the series, targets keep their formats; extend = Fill Series: the series, and a lone number counts up; days, weekdays, months, years = Fill Days, Fill Weekdays, Fill Months, Fill Years: dates step by one unit, or by the difference between the first two dates in that unit, and weekdays skip Saturday and Sunday)",
has_doc,
auto_fill
),
@@ -206,7 +206,6 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
d.selection = e.selection;
// Step by step: a rename and a new sheet undone together match up only one step apart.
super::extra::keep_view_modes(d, &cur_wb);
super::view::keep_zoom(d, &cur_wb);
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
@@ -228,7 +227,6 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
d.wb = e.wb;
d.selection = e.selection;
super::extra::keep_view_modes(d, &cur_wb);
super::view::keep_zoom(d, &cur_wb);
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
+17 -67
View File
@@ -8,12 +8,14 @@ use super::{
/// Typing `=PY(` doesn't make a Python cell; this says what does.
pub(crate) const PY_FORMULA: &str = "Python cells are made with the python.set command (the code as `code`), not by typing =PY(…).";
/// Whether typing `input` into a cell is meant as a formula: `=…`, or `+…`/`-…` when the entry
/// isn't a number on its own, as Excel takes `+5+4` and `+SUM(1)` (see
/// [`gridcraft_core::parse::starts_formula`]). A `+…`/`-…` entry that doesn't parse as a formula
/// still enters as text (`--`), see [`input_to_cell`].
/// Whether typing `input` into a cell enters a formula: `=…`, or `+…`/`-…` followed by a name or
/// a parenthesis (not a number), as Excel takes `+SUM(1)`.
pub(crate) fn is_formula_input(input: &str) -> bool {
gridcraft_core::parse::starts_formula(input)
input.starts_with('=')
|| (input.len() > 1
&& (input.starts_with('+') || input.starts_with('-'))
&& gridcraft_core::parse::parse_number_text(input).is_none()
&& input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '('))
}
/// What typing `input` into a cell produces (constant or formula, plus an automatic number
@@ -27,21 +29,13 @@ 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) {
return Err(EngineError::Other(PY_FORMULA.into()));
}
// As in Excel, a `+` or `-` entry is a formula when it reads as one (`+5+4` enters `=+5+4`)
// and text when it doesn't (`--`, `+49 170 1234567`); only `=` entries are refused.
if is_formula
&& !input.starts_with('=')
&& let Ok(cell) = input_to_cell(&format!("={input}"), sheet, at, wb)
{
return Ok(cell);
}
if input.starts_with('=') {
if is_formula {
let body = input.strip_prefix('=').unwrap_or(input);
let expr = wb.name_call_case(parse_typed_formula(body)?);
check_arg_counts(&expr)?;
@@ -71,8 +65,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()
@@ -151,66 +143,24 @@ pub(super) fn cell_set(s: &mut Session, p: &Json) -> Result<Json> {
// the cell; a cell elsewhere (or on another sheet) gets a one-cell array.
let selected = cx.sel.current();
let range = if sheet == active_sheet && selected.contains(at) { selected } else { RangeRef::cell(at) };
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
// Excel forms no array from a constant: every cell of the selection takes the value.
if cell.formula.is_none() && !range.is_single() {
if range.count() > crate::fill::MAX_FILL_CELLS {
return Err(EngineError::Other("That selection is too large to fill.".into()));
}
let mut by_style: std::collections::HashMap<StyleId, Option<Cell>> = std::collections::HashMap::new();
for c in range.iter() {
let style = cx.wb.sheet(sheet).map(|sh| sh.style_id(c)).unwrap_or_default();
let filled = match by_style.get(&style) {
Some(filled) => filled.clone(),
None => {
let filled = input_to_cell(&input, sheet, c, &mut cx.wb)?;
by_style.insert(style, filled.clone());
filled
}
};
let sh = cx.sheet_mut(sheet)?;
match filled {
Some(f) => {
sh.set_cell(c, f);
crate::cmd::data::grow_autofilter(sh, c);
}
None => {
sh.remove_cell(c);
}
}
cx.touch(sheet, c);
}
return Ok(Json::Null);
}
// A table header can't hold an array's value, and a table resizes under it.
if !range.is_single() && cx.wb.sheet(sheet).is_some_and(|sh| sh.tables.iter().any(|t| t.range.intersects(&range))) {
return Err(EngineError::Other("Multi-cell array formulas aren't allowed in tables.".into()));
}
let mut cell = input_to_cell(&input, sheet, range.start, &mut cx.wb)?.unwrap_or_default();
if let Some(f) = cell.formula.as_mut() {
std::sync::Arc::make_mut(f).array = Some(range);
}
let sh = cx.sheet_mut(sheet)?;
// The array takes the whole range: other cells in it lose their contents. Walk the
// cells the sheet holds rather than every address, so a whole-column array clears
// all of its area, and mark each cleared cell so formulas reading it recalculate.
let cleared: Vec<(CellRef, StyleId)> =
sh.cells.iter_range(range).filter(|(c, x)| *c != range.start && x.has_content()).map(|(c, x)| (c, x.style)).collect();
for &(c, style) in &cleared {
sh.set_cell(c, Cell { style, ..Cell::default() });
// The array takes the whole range: other cells in it lose their contents.
for c in range.iter().skip(1).take(1_000_000) {
if let Some(old) = sh.cells.get(c).filter(|x| x.has_content()) {
let style = old.style;
sh.set_cell(c, Cell { style, ..Cell::default() });
}
}
sh.set_cell(range.start, cell);
cx.touch(sheet, range.start);
// The array's results land in every cell of the range, stored or not, so readers of
// an empty result cell need the touch too. A huge range marks only the cells it held.
if range.count() <= 1_000_000 {
for c in range.iter() {
cx.touch(sheet, c);
}
} else {
for (c, _) in cleared {
cx.touch(sheet, c);
}
}
return Ok(Json::Null);
}
let cell = input_to_cell(&input, sheet, at, &mut cx.wb)?;
@@ -319,7 +269,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)?,
-2
View File
@@ -52,8 +52,6 @@ pub(super) fn auto_fill(s: &mut Session, p: &Json) -> Result<Json> {
"weekdays" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Weekday),
"months" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Month),
"years" => crate::fill::FillMode::Dates(crate::fill::DateUnit::Year),
"linearTrend" => crate::fill::FillMode::LinearTrend,
"growthTrend" => crate::fill::FillMode::GrowthTrend,
_ => crate::fill::FillMode::Series,
};
if target.count() > crate::fill::MAX_FILL_CELLS || src.count() > crate::fill::MAX_FILL_CELLS {
+2 -39
View File
@@ -76,34 +76,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
return Err(EngineError::Other("Too many cells to paste as links at once.".into()));
}
let same_doc = s.doc()?.uid == clip.doc_uid;
// A cut in this workbook moves its cells: the source is emptied before the destination is
// written. As in Excel, it moves only as a plain Paste onto one cell or an area of its own size
// and shape. Every other way (a Paste Special option, tiling over a larger or differently shaped
// area, a row the filter hides) would write the cut cells somewhere other than one place, or not
// at all, after their source was gone, so it is refused here, before anything changes, and the
// cut stays pending.
let cut_move = clip.cut && same_doc;
if cut_move {
let plain = what == What::All && !link && !skip_blanks && !transpose && op == "none";
if !plain {
return Err(EngineError::Other("Cut cells can only be pasted with Paste. To use Paste Special, copy them instead.".into()));
}
let anchored = cell_param_on(s, p, "at", dest_sheet)?.is_some() || sel.is_single();
if !anchored && (sel.height() != h || sel.width() != w) {
return Err(EngineError::Other(
"The cut cells and the paste area aren't the same size and shape: select one cell, or an area the size of the cut cells.".into(),
));
}
// The rows the cut itself would land on, whatever the paste would skip: an anchored or
// taller block is pasted straight down, so `skip_rows` (which only a tiled single row uses)
// can't tell whether it would write into a hidden row.
if let Some(end) = at.offset(i64::from(h) - 1, i64::from(w) - 1) {
let dest = RangeRef::new(at, end);
if s.doc()?.wb.sheet(dest_sheet).is_some_and(|sh| !super::filtered_rows(sh, dest).is_empty()) {
return Err(EngineError::Other("The cut area can't be pasted into rows the filter hides.".into()));
}
}
}
let cut_move = clip.cut && same_doc && what == What::All;
let src_wb = clip.wb.clone();
let Some(src_sheet) = src_wb.sheet(clip.sheet) else { return Err(EngineError::Other("The copied sheet no longer exists.".into())) };
// The source sheet's name now: a cut whose sheet was renamed after it moves its cells,
@@ -235,12 +208,7 @@ pub(super) fn paste_special(s: &mut Session, p: &Json) -> Result<Json> {
moved.dynamic = f.dynamic;
return Some(std::sync::Arc::new(moved));
}
let moved = if transpose {
// A transposed paste turns the references instead of shifting them (#2450).
gridcraft_formula::adjust::transpose_relative(e, sc, dest)
} else {
gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64)
};
let moved = gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64);
Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) }))
};
let moved_py = |cell: &Cell| -> Result<Option<std::sync::Arc<gridcraft_model::PyCode>>> {
@@ -421,11 +389,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);
}
-7
View File
@@ -52,13 +52,6 @@ impl crate::DocState {
// View state: set in place, so the workbook is neither copied nor made dirty.
self.wb.set_active_sheet(i);
self.selection = self.sheet_selections.get(i).cloned().unwrap_or_default();
// A sheet's first visit starts at A1, which may be part of a merged cell: take it whole,
// as a click would (#1348). A selection the sheet remembers comes back as it was.
if self.selection == crate::Selection::default()
&& let Some(sh) = self.wb.sheet(i)
{
self.selection.expand_merges(sh);
}
}
}
-194
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();
@@ -344,137 +314,6 @@ fn an_array_entered_outside_the_selection_covers_only_its_cell() {
assert_eq!(sh.value(CellRef::parse("K20").unwrap()), Value::text("keep"));
}
/// The value a full recalculation from scratch gives `a1` on the active sheet.
fn fully_recalculated(s: &Session, a1: &str) -> Value {
let mut fresh = (*s.doc().unwrap().wb).clone();
gridcraft_calc::Calc::new().recalc_all(&mut fresh);
fresh.active().unwrap().value(CellRef::parse(a1).unwrap())
}
#[test]
fn array_entering_a_constant_recalculates_readers_of_the_cells_it_fills() {
// Found by the command-sequence fuzzer (seeds 4, 1213): only the array's first cell was
// marked changed, so formulas reading the cells it cleared kept their old values.
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [[5, 6, "=B1+1"]]})).unwrap();
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "7", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
// Excel fills both cells with the constant and forms no array.
for a in ["A1", "B1"] {
let c = sh.cell(CellRef::parse(a).unwrap()).unwrap();
assert_eq!(c.value, Value::number(7.0));
assert!(c.formula.is_none());
}
assert_eq!(sh.value(CellRef::parse("C1").unwrap()), Value::number(8.0));
// The fuzzer's minimal repro on the budget sample.
let mut s = Session::new();
s.execute("file.new", json!({"sample": "budget"})).unwrap();
s.execute("selection.set", json!({"active": "C5", "range": "C5:D5"})).unwrap();
s.execute("cell.set", json!({"array": true, "cell": "C5", "input": "7"})).unwrap();
let in_memory = s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D15").unwrap());
assert_eq!(in_memory, fully_recalculated(&s, "D15"));
}
#[test]
fn array_entering_a_constant_grows_an_autofilter_below_it() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1:B3", "values": [["Name", "Qty"], ["a", 1], ["b", 2]]})).unwrap();
s.execute("data.filter", json!({"range": "A1:B3"})).unwrap();
s.execute("selection.set", json!({"range": "A4:A5"})).unwrap();
s.execute("cell.set", json!({"cell": "A4", "input": "new", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.autofilter.as_ref().map(|f| f.range.a1()), Some("A1:B5".to_string()));
}
#[test]
fn array_entering_a_formula_fills_every_cell_as_an_array() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A2", "input": "5"})).unwrap();
for (input, want) in [("=1", 1.0), ("=A2", 5.0)] {
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": input, "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
for a in ["A1", "B1"] {
assert_eq!(sh.value(CellRef::parse(a).unwrap()), Value::number(want), "{input} {a}");
}
let f = sh.cell(CellRef::parse("A1").unwrap()).and_then(|c| c.formula.clone()).unwrap();
assert_eq!(f.array, Some(RangeRef::parse("A1:B1").unwrap()));
}
}
#[test]
fn readers_of_an_empty_array_result_cell_see_its_result() {
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "D1", "input": "=B1+1"})).unwrap();
s.execute("selection.set", json!({"active": "A1", "range": "A1:B1"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "=5", "array": true})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("D1").unwrap()), Value::number(6.0));
assert_eq!(fully_recalculated(&s, "D1"), Value::number(6.0));
}
#[test]
fn a_whole_column_constant_fills_its_whole_area() {
// The loop stopped after a million addresses, so cells further down the column kept
// their old content (and their readers weren't recalculated).
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
s.execute("selection.set", json!({"active": "D1", "range": "D:D"})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "1", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::number(1.0));
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(2.0));
assert_eq!(fully_recalculated(&s, "F1"), Value::number(2.0));
}
#[test]
fn clearing_more_than_a_million_cells_recalculates_readers_of_all_of_them() {
// Clear marked only the first million addresses of the range as changed, so formulas
// reading a cleared cell further down kept its old value.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "D1", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "D1048000", "input": "41"})).unwrap();
s.execute("cell.set", json!({"cell": "F1", "input": "=D1048000+1"})).unwrap();
s.execute("edit.clearContents", json!({"range": "D:D"})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.value(CellRef::parse("D1048000").unwrap()), Value::Empty);
assert_eq!(sh.value(CellRef::parse("F1").unwrap()), Value::number(1.0));
}
#[test]
fn clearing_a_spill_recalculates_readers_of_its_spilled_cells() {
// Clear marks only the cells the sheet holds; a spill's other cells go with its anchor.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(5)"})).unwrap();
s.execute("cell.set", json!({"cell": "C1", "input": "=A3+1"})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(4.0));
s.execute("edit.clearContents", json!({"range": "A1:A5"})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("C1").unwrap()), Value::number(1.0));
assert_eq!(fully_recalculated(&s, "C1"), Value::number(1.0));
}
#[test]
fn readers_of_an_array_formulas_cells_see_its_results() {
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "B2", "values": [[1], [2]]})).unwrap();
s.execute("cell.set", json!({"cell": "C3", "input": "100"})).unwrap();
s.execute("cell.set", json!({"cell": "E1", "input": "=C3+C4+1"})).unwrap();
s.execute("selection.set", json!({"range": "C2:C4"})).unwrap();
s.execute("cell.set", json!({"cell": "C2", "input": "=B2:B3*2", "array": true})).unwrap();
let sh = s.doc().unwrap().wb.active().unwrap();
assert_eq!(sh.value(CellRef::parse("E1").unwrap()), fully_recalculated(&s, "E1"));
}
#[test]
fn wildcards() {
assert!(wildcard("hello", "h*o"));
@@ -636,39 +475,6 @@ fn cut_paste_that_overflows_the_grid_moves_nothing() {
assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0));
}
#[test]
fn transposed_paste_turns_the_formula_with_the_cell_that_carries_it() {
// #2450: the values moved but the formula kept the offset it had in the source column,
// so it read the cell above instead of the cell to its left.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A3", "input": "2025-10-31"})).unwrap();
s.execute("cell.set", json!({"cell": "A4", "input": "=A3+1"})).unwrap();
s.execute("edit.copy", json!({"range": "A3:A4"})).unwrap();
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C3"})).unwrap();
let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap();
let date = get(&mut s, "C3")["value"].as_f64().expect("the date pastes as its serial");
assert_eq!(date, get(&mut s, "A3")["value"].as_f64().unwrap());
assert_eq!(get(&mut s, "D3")["formula"], "=C3+1", "the formula reads the cell to its left, as Excel's does");
assert_eq!(get(&mut s, "D3")["value"].as_f64().unwrap(), date + 1.0, "and shows the day after it");
}
#[test]
fn transposed_paste_turns_every_kind_of_reference_the_way_excel_does() {
// Observed from Excel 16: relative parts turn a quarter turn, a reference pinned with $
// is left standing, and a whole column comes back as a range open to the sheet's edge.
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["=B1+1"], ["=$B$1"], ["=SUM(B1:C3)"], ["=SUM(B:D)"]]})).unwrap();
s.execute("edit.copy", json!({"range": "A1:A4"})).unwrap();
s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C10"})).unwrap();
let formula = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["formula"].clone();
assert_eq!(formula(&mut s, "C10"), "=C11+1");
assert_eq!(formula(&mut s, "D10"), "=$B$1");
assert_eq!(formula(&mut s, "E10"), "=SUM(C11:E12)");
assert_eq!(formula(&mut s, "F10"), "=SUM($C11:$XFD13)");
}
#[test]
fn drag_and_drop_asks_before_replacing_data() {
// #3136: dragging column B's border onto column A replaced A without asking.
+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")) {
+3 -246
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,47 +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() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": true}}})).unwrap();
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], true);
s.execute("home.formatCells", json!({"range": "A1", "style": {"font": {"outline": false}}})).unwrap();
assert_eq!(s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"]["font"]["outline"], false);
}
/// The Format Cells dialog sends the active cell's whole style to every selected cell, so a
/// non-outlined active cell must clear outline on the others, as it does bold.
#[test]
fn format_cells_whole_style_clears_outline_on_the_selection() {
let mut s = crate::Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "plain"})).unwrap();
s.execute("cell.set", json!({"cell": "B1", "input": "hollow"})).unwrap();
s.execute("home.formatCells", json!({"range": "B1", "style": {"font": {"outline": true, "bold": true}}})).unwrap();
let style = s.execute("cell.get", json!({"cell": "A1"})).unwrap()["style"].clone();
s.execute("home.formatCells", json!({"range": "A1:B1", "style": style})).unwrap();
let font = s.execute("cell.get", json!({"cell": "B1"})).unwrap()["style"]["font"].clone();
assert_eq!((font["bold"].clone(), font["outline"].clone()), (json!(false), json!(false)));
}
#[test]
fn arabic_vowel_and_direction_marks_add_no_width() {
let plain = approx_text_width("محمد يدرس في المدرسة", 11.0, false);
+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))]);
}
}
-2
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,
+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" },
+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]"));
}
-287
View File
@@ -1,287 +0,0 @@
//! Quick Analysis › Totals: appends totals (or per-cell percentages / running totals) next to a
//! block of numbers as ordinary formulas, in one undoable edit. The popup in the UI
//! (`ui.quickAnalysis`) is a thin front end for this command; the control channel, CLI and MCP
//! call it directly. The layout is GridCraft's own: aggregates go in the row below the block (or
//! the column to its right), per-cell results in a block of the same shape next to it.
use std::collections::BTreeSet;
use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef};
use gridcraft_model::{Color, NumFmt, Sparkline, SparklineKind};
use serde_json::{Value as Json, json};
use super::{CommandSpec, EngineError, PROTECTED, Result, Session, bad, bool_param, cmd, edit, has_doc, str_param, target_range, target_sheet};
const CMD: &str = "analysis.addTotal";
const SPARK: &str = "analysis.addSparklines";
/// Most sparklines one call may add.
const MAX_SPARKLINES: u64 = 10_000;
/// Most cells one call may write (a per-cell block on a huge selection is refused).
const MAX_OUTPUT_CELLS: u64 = 200_000;
/// Largest block (after clipping to the used range) the command scans for numbers.
const MAX_SCAN_CELLS: u64 = 5_000_000;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"analysis.addTotal",
"Add Totals",
[],
None,
"{function?: sum|average|count|min|max|percentTotal|runningTotal (default sum), direction?: columns|rows (default columns: one result per column, below the block; rows: one per row, right of it; percentTotal and runningTotal write a block of the same shape to the right (columns) or below (rows)), range?: \"A1:C9\" (default: the selection; limited to the used range), overwrite?: bool (else non-empty output cells are refused)} → {function, direction, output, cells}. Quick Analysis › Totals. A header row (columns) or label column (rows) is skipped; columns without numbers get no total. One undo step.",
has_doc,
add_total
),
cmd!(
"analysis.addSparklines",
"Add Sparklines",
[],
None,
"{type?: line|column|winLoss (default line), direction?: rows|columns (default rows: one sparkline per row, in the column right of the block; columns: one per column, in the row below), markers?: bool, range?: \"A1:F9\" (default: the selection; limited to the used range), overwrite?: bool} → {output, sparklines}. Quick Analysis › Sparklines. A header row (columns) or label column (rows) is skipped; lines without numbers get none. One undo step.",
has_doc,
add_sparklines
),
]
}
#[derive(Clone, Copy, PartialEq)]
enum Func {
Aggregate(&'static str),
Percent,
Running,
}
fn parse_func(name: &str) -> Result<Func> {
Ok(match name.to_ascii_lowercase().replace(['_', '-', ' ', '%'], "").as_str() {
"sum" => Func::Aggregate("SUM"),
"average" | "avg" => Func::Aggregate("AVERAGE"),
"count" => Func::Aggregate("COUNT"),
"min" => Func::Aggregate("MIN"),
"max" => Func::Aggregate("MAX"),
"percenttotal" | "percent" => Func::Percent,
"runningtotal" | "running" => Func::Running,
_ => return Err(bad(CMD, format!("unknown function `{name}` (use sum, average, count, min, max, percentTotal or runningTotal)"))),
})
}
/// The block a Quick Analysis result is computed from.
struct Block {
sheet: usize,
/// The selection clipped to the used range.
range: RangeRef,
/// `range` without its header row (columns) or label column (rows).
data: RangeRef,
/// The columns (or, `by_rows`, the rows) of `data` that hold numbers.
lines: BTreeSet<u32>,
by_rows: bool,
/// Last row / column the results must stay clear of: the selection's own far edge, so a
/// selection reaching past the data still gets its results outside it. Whole rows or columns
/// (reaching the sheet limit) fall back to the clipped range.
edge: CellRef,
}
impl Block {
fn cell_at(&self, line: u32, i: u32) -> CellRef {
if self.by_rows { CellRef::new(line, i) } else { CellRef::new(i, line) }
}
/// First and last position along a line of `data`.
fn span_of_line(&self) -> (u32, u32) {
if self.by_rows { (self.data.start.col, self.data.end.col) } else { (self.data.start.row, self.data.end.row) }
}
fn line_range(&self, line: u32, from: u32, to: u32) -> RangeRef {
RangeRef::new(self.cell_at(line, from), self.cell_at(line, to))
}
}
fn block(s: &Session, p: &Json, by_rows: bool, cmd: &str) -> Result<Block> {
let sheet = target_sheet(s, p)?;
let sel = match str_param(p, "range") {
Some(_) => target_range(s, p)?,
None => {
// Never guess from the current area of a multi-area selection.
if s.doc()?.selection.ranges.len() > 1 {
return Err(bad(cmd, "select a single contiguous range"));
}
s.doc()?.selection.current()
}
};
if sel.is_single() {
return Err(bad(cmd, "select at least two cells"));
}
let d = s.doc()?;
let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
// Whole rows / columns are limited to what holds data.
let used = sh.cells.used_range().ok_or_else(|| EngineError::Other("There is no data to analyse.".into()))?;
let r = sel.intersection(&used).ok_or_else(|| EngineError::Other("There is no data to analyse in the selection.".into()))?;
if r.count() > MAX_SCAN_CELLS {
return Err(bad(cmd, "selection too large to analyse"));
}
let is_num = |c: CellRef| sh.value(c).is_number();
let is_text = |c: CellRef| sh.value(c).is_text();
// Header row (columns) / label column (rows): text only, with at least one entry.
let lead: Vec<CellRef> = if by_rows {
(r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect()
} else {
(r.start.col..=r.end.col).map(|c| CellRef::new(r.start.row, c)).collect()
};
let longer_than_one = if by_rows { r.width() > 1 } else { r.height() > 1 };
let has_label = longer_than_one && lead.iter().any(|c| is_text(*c)) && !lead.iter().any(|c| is_num(*c));
let data = if by_rows {
RangeRef::new(CellRef::new(r.start.row, r.start.col + u32::from(has_label)), r.end)
} else {
RangeRef::new(CellRef::new(r.start.row + u32::from(has_label), r.start.col), r.end)
};
let mut lines: BTreeSet<u32> = BTreeSet::new();
for (c, _) in sh.cells.iter_range(data) {
if is_num(c) {
lines.insert(if by_rows { c.row } else { c.col });
}
}
if lines.is_empty() {
return Err(EngineError::Other("The selection holds no numbers.".into()));
}
let edge = CellRef::new(
if sel.end.row >= MAX_ROWS - 1 { r.end.row } else { sel.end.row.max(r.end.row) },
if sel.end.col >= MAX_COLS - 1 { r.end.col } else { sel.end.col.max(r.end.col) },
);
Ok(Block { sheet, range: r, data, lines, by_rows, edge })
}
fn add_total(s: &mut Session, p: &Json) -> Result<Json> {
let func = parse_func(str_param(p, "function").unwrap_or("sum"))?;
let by_rows = match str_param(p, "direction") {
None | Some("columns") => false,
Some("rows") => true,
Some(other) => return Err(bad(CMD, format!("direction must be columns or rows, not `{other}`"))),
};
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
let b = block(s, p, by_rows, CMD)?;
let (r, sheet) = (b.range, b.sheet);
let (lo, hi) = b.span_of_line();
let out_cells = match func {
Func::Aggregate(_) => b.lines.len() as u64,
_ => b.lines.len() as u64 * (u64::from(hi - lo) + 1),
};
if out_cells > MAX_OUTPUT_CELLS {
return Err(bad(CMD, "selection too large for this result"));
}
// `$` pins a part of a reference like a hand-written formula would.
let abs = |c: CellRef, row: bool, col: bool| {
let a = c.a1();
let letters: String = a.chars().take_while(|ch| ch.is_ascii_alphabetic()).collect();
let digits = &a[letters.len()..];
format!("{}{letters}{}{digits}", if col { "$" } else { "" }, if row { "$" } else { "" })
};
// (target, formula) pairs.
let mut writes: Vec<(CellRef, String)> = Vec::with_capacity(out_cells as usize);
let (height, width) = (b.edge.row - r.start.row + 1, b.edge.col - r.start.col + 1);
for &line in &b.lines {
match func {
Func::Aggregate(name) => {
let target =
if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
writes.push((target, format!("={name}({})", b.line_range(line, lo, hi).a1())));
}
Func::Percent | Func::Running => {
for i in lo..=hi {
let src = b.cell_at(line, i);
let target = if by_rows {
CellRef::new(src.row.saturating_add(height), src.col)
} else {
CellRef::new(src.row, src.col.saturating_add(width))
};
let formula = if func == Func::Percent {
// The summed block is locked on the axis the formula is filled along.
let (a, z) = (b.cell_at(line, lo), b.cell_at(line, hi));
format!("={}/SUM({}:{})", src.a1(), abs(a, !by_rows, by_rows), abs(z, !by_rows, by_rows))
} else {
format!("=SUM({}:{})", abs(b.cell_at(line, lo), !by_rows, by_rows), src.a1())
};
writes.push((target, formula));
}
}
}
}
// Everything has to fit on the sheet and may not overwrite data.
if writes.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
return Err(EngineError::Other("There's no room next to the selection for the result.".into()));
}
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
if !overwrite && writes.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.cells.get(*t).is_some_and(|c| c.formula.is_some())) {
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
}
let out = writes.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
let percent = func == Func::Percent;
let count = writes.len();
edit(s, |cx| {
for (t, f) in &writes {
let cell = super::edit::input_to_cell(f, sheet, *t, &mut cx.wb)?.unwrap_or_default();
cx.sheet_mut(sheet)?.set_cell(*t, cell);
if percent {
let cur = cx.wb.sheet(sheet).map(|sh| sh.style_id(*t)).unwrap_or_default();
let new = cx.wb.styles.derive(cur, |st| st.num_fmt = NumFmt::new("0.0%"));
cx.sheet_mut(sheet)?.set_style(*t, new);
}
cx.touch(sheet, *t);
}
Ok(())
})?;
let name = match func {
Func::Aggregate(n) => n.to_ascii_lowercase(),
Func::Percent => "percentTotal".into(),
Func::Running => "runningTotal".into(),
};
Ok(json!({"function": name, "direction": if by_rows { "rows" } else { "columns" }, "output": out.map(|o| o.a1()), "cells": count}))
}
fn add_sparklines(s: &mut Session, p: &Json) -> Result<Json> {
let by_rows = match str_param(p, "direction") {
None | Some("rows") => true,
Some("columns") => false,
Some(other) => return Err(bad(SPARK, format!("direction must be rows or columns, not `{other}`"))),
};
let kind = match str_param(p, "type") {
None | Some("line") => SparklineKind::Line,
Some("column") => SparklineKind::Column,
Some("winLoss") => SparklineKind::WinLoss,
Some(other) => return Err(bad(SPARK, format!("type must be line, column or winLoss, not `{other}`"))),
};
let markers = bool_param(p, "markers").unwrap_or(false);
let overwrite = bool_param(p, "overwrite").unwrap_or(false);
let b = block(s, p, by_rows, SPARK)?;
if b.lines.len() as u64 > MAX_SPARKLINES {
return Err(bad(SPARK, "selection too large for this result"));
}
let (lo, hi) = b.span_of_line();
let sparks: Vec<(CellRef, String)> = b
.lines
.iter()
.map(|&line| {
let at = if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) };
(at, b.line_range(line, lo, hi).a1())
})
.collect();
if sparks.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) {
return Err(EngineError::Other("There's no room next to the selection for the sparklines.".into()));
}
let sheet = b.sheet;
let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?;
// Sparklines are not cell content, so the commit-time protection check does not see them.
if sh.is_protected() {
return Err(EngineError::Other(PROTECTED.into()));
}
if !overwrite && sparks.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.sparklines.iter().any(|x| x.cell == *t)) {
return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into()));
}
let out = sparks.iter().fold(None::<RangeRef>, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t)))));
let count = sparks.len();
edit(s, |cx| {
let sh = cx.sheet_mut(sheet)?;
for (cell, source) in sparks {
sh.sparklines.retain(|x| x.cell != cell);
sh.sparklines.push(Sparkline { cell, source, kind, color: Color::Theme(4, 0), markers });
}
Ok(())
})?;
Ok(json!({"output": out.map(|o| o.a1()), "sparklines": count}))
}
+6 -21
View File
@@ -161,7 +161,7 @@ fn protect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
};
let d = s.doc()?;
let what = d.wb.sheet(sheet).map(|sh| sh.name.clone()).unwrap_or_default();
let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_protection_hash(d, &what, pw)), ..prot };
let prot = SheetProtection { password: str_param(p, "password").filter(|x| !x.is_empty()).map(|pw| new_password_hash(d, &what, pw)), ..prot };
edit(s, |cx| {
// FORMULATEXT reads a sheet's protection: its results are recalculated.
cx.recalc_all = true;
@@ -192,25 +192,13 @@ fn unprotect_sheet(s: &mut Session, p: &Json) -> Result<Json> {
})
}
/// A new hash of a sheet's or the workbook's protection password, in every form a file keeps
/// (Excel's salted SHA-512 and OpenDocument's SHA-256 digest), so it survives saving in either
/// format.
fn new_protection_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
PasswordHash::new_for_files(pw, &new_salt(d, what))
}
/// A new Excel-compatible (SHA-512, salted) hash of `pw`: edit ranges only have this form.
/// A new Excel-compatible (SHA-512, salted) hash of `pw`. The salt mixes `what` is protected
/// with the document, a counter and the clock, so equal passwords get different hashes.
fn new_password_hash(d: &DocState, what: &str, pw: &str) -> PasswordHash {
PasswordHash::new_sha512(pw, &new_salt(d, what))
}
/// A salt mixing `what` is protected with the document, a counter and the clock, so equal
/// passwords get different hashes.
fn new_salt(d: &DocState, what: &str) -> [u8; 16] {
static SALT_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = SALT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let seed = format!("{what}\u{0}{n}\u{0}{}\u{0}{}", d.uid, gridcraft_calc::now_serial().to_bits());
gridcraft_model::password::salt_from(seed.as_bytes())
PasswordHash::new_sha512(pw, &gridcraft_model::password::salt_from(seed.as_bytes()))
}
fn range_text(r: &EditRange) -> String {
@@ -329,7 +317,7 @@ fn protect_workbook(s: &mut Session, p: &Json) -> Result<Json> {
return Ok(json!({"on": on}));
}
let password = if on {
str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_protection_hash(d, "workbook", pw))
str_param(p, "password").filter(|pw| !pw.is_empty()).map(|pw| new_password_hash(d, "workbook", pw))
} else {
if let Some(h) = &d.wb.structure_password
&& !h.verify(str_param(p, "password").unwrap_or("")).map_err(EngineError::Other)?
@@ -461,10 +449,7 @@ mod tests {
let mut s = book();
s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap();
let prot = s.doc().unwrap().wb.active().unwrap().protection.clone().unwrap();
// Kept in both forms: Excel's salted SHA-512 and OpenDocument's SHA-256 digest.
let password = prot.password.as_ref().unwrap();
assert!(matches!(password.excel(), Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512"));
assert_eq!(password.odf_key(), PasswordHash::new_sha256_digest("pa55").odf_key());
assert!(matches!(&prot.password, Some(PasswordHash::Iterated { algorithm, .. }) if algorithm == "SHA-512"));
assert!(s.execute("review.unprotectSheet", json!({})).is_err());
assert!(s.execute("review.unprotectSheet", json!({"password": "pass"})).is_err());
// Protecting again can't swap the password out from under it.
+6 -125
View File
@@ -1,7 +1,7 @@
//! View tab (sheet view state that's saved with the file) and Page Layout settings.
use gridcraft_core::RangeRef;
use gridcraft_model::{Orientation, Workbook};
use gridcraft_model::Orientation;
use serde_json::{Value as Json, json};
use super::{
@@ -62,8 +62,8 @@ pub fn specs() -> Vec<CommandSpec> {
workbook_view_flag(s, p, "vertical")
}),
cmd!("view.rightToLeft", "Sheet Right-to-Left", ["Page Layout", "Sheet Options"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "rtl")),
cmd!(noundo "view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom),
cmd!(noundo "view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))),
cmd!("view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom),
cmd!("view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))),
cmd!(query "view.formulaBar", "Formula Bar", ["View", "Show"], None, "{on?: bool}", always, |s, p| {
s.prefs.formula_bar = bool_param(p, "on").unwrap_or(!s.prefs.formula_bar);
Ok(json!({"on": s.prefs.formula_bar}))
@@ -77,14 +77,14 @@ pub fn specs() -> Vec<CommandSpec> {
always,
status_bar
),
cmd!(noundo "view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection),
cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection),
cmd!("pageLayout.orientation", "Orientation", ["Page Layout", "Page Setup"], None, "{orientation: portrait|landscape}", has_doc, orientation),
cmd!(
"pageLayout.size",
"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
),
@@ -274,34 +274,6 @@ fn zoom(s: &mut Session, p: &Json) -> Result<Json> {
Ok(json!({"zoom": z}))
}
/// Zoom belongs to the window, not to the edits (Excel doesn't undo it, #2313): undo and redo keep
/// each sheet's current zoom when they swap in another snapshot of the workbook. Back at the saved
/// state, the zoom alone doesn't make the workbook dirty, as with `view.zoom`.
pub(crate) fn keep_zoom(d: &mut crate::DocState, now: &Workbook) {
// Sheets have no stable id. A name missing from `now` is a rename being undone or redone, which
// keeps the sheet count and position: the sheet is the one at the same index, under a name the
// restored snapshot doesn't have.
let renamed = |i: usize| {
(now.sheets.len() == d.wb.sheets.len()).then(|| now.sheets.get(i)).flatten().filter(|sh| !d.wb.sheets.iter().any(|s| s.name == sh.name))
};
let current = |i: usize, name: &str| now.sheets.iter().find(|sh| sh.name == name).or_else(|| renamed(i)).map(|sh| sh.zoom);
let changed: Vec<(usize, u16)> =
d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(i, &sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect();
if changed.is_empty() {
return;
}
let saved = std::sync::Arc::ptr_eq(&d.wb, &d.saved);
let wb = std::sync::Arc::make_mut(&mut d.wb);
for (i, z) in changed {
if let Some(sh) = wb.sheet_mut(i) {
sh.zoom = z;
}
}
if saved {
d.saved = d.wb.clone();
}
}
fn zoom_selection(s: &mut Session, p: &Json) -> Result<Json> {
let d = s.doc()?;
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
@@ -324,9 +296,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();
@@ -565,7 +535,6 @@ fn theme(s: &mut Session, p: &Json) -> Result<Json> {
#[cfg(test)]
mod tests {
use super::*;
use gridcraft_core::CellRef;
#[test]
fn zoom_100_resets_the_active_sheet_zoom() {
@@ -576,94 +545,6 @@ mod tests {
assert_eq!(s.doc().unwrap().wb.active().unwrap().zoom, 100);
}
#[test]
fn zooming_is_not_an_undo_step() {
// Excel keeps zoom on the window, not in the edit history (#2313): wheel, slider, dialog,
// 100% and Zoom to Selection leave Undo and Redo alone.
let mut s = Session::new();
s.new_workbook();
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
s.execute("cell.set", json!({"cell": "A2", "input": "y"})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
let (undo, redo) = s.doc().map(|d| (d.undo.len(), d.redo.len())).unwrap();
for (id, params, zoom) in [
("view.zoom", json!({"percent": 150}), 150),
("view.zoomToSelection", json!({"viewWidth": 1200, "viewHeight": 700}), 400),
("view.zoom100", json!({}), 100),
] {
s.execute(id, params).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.wb.active().unwrap().zoom, zoom, "{id}");
assert_eq!((d.undo.len(), d.redo.len()), (undo, redo), "{id} touched the history");
}
let a1 = CellRef::parse("A1").unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().value(a1).is_empty(), "Ctrl+Z after zooming undoes the last edit");
}
#[test]
fn undo_and_redo_keep_the_current_zoom() {
let mut s = Session::new();
s.new_workbook();
let zoom = |s: &Session| s.doc().unwrap().wb.active().unwrap().zoom;
s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap();
s.execute("view.zoom", json!({"percent": 200})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty());
assert_eq!(zoom(&s), 200, "undo keeps the zoom");
// Back at the state on disk: the zoom alone doesn't make the workbook dirty, as in `zoom`.
assert!(!s.doc().unwrap().is_dirty());
s.execute("view.zoom", json!({"percent": 50})).unwrap();
s.execute("edit.redo", json!({})).unwrap();
assert!(!s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty());
assert_eq!(zoom(&s), 50, "redo keeps the zoom");
}
#[test]
fn undoing_a_rename_keeps_the_current_zoom() {
let mut s = Session::new();
s.new_workbook();
let active = |s: &Session| {
let sh = s.doc().unwrap().wb.active().unwrap();
(sh.name.clone(), sh.zoom)
};
let before = active(&s).0;
s.execute("sheet.rename", json!({"name": "Data"})).unwrap();
s.execute("view.zoom", json!({"percent": 150})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(active(&s), (before, 150), "undoing the rename keeps the zoom");
s.execute("view.zoom", json!({"percent": 75})).unwrap();
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(active(&s), ("Data".to_string(), 75), "redoing the rename keeps the zoom");
}
#[test]
fn undoing_several_steps_keeps_each_sheet_its_own_zoom() {
// Adding C then deleting B leaves as many sheets as before under other names: across both
// steps at once, that looks like B renamed to C, and C's zoom used to land on B.
let mut s = Session::new();
s.new_workbook();
let zoom = |s: &Session, name: &str| {
let wb = &s.doc().unwrap().wb;
wb.sheet(wb.sheet_index(name).unwrap()).unwrap().zoom
};
let names = |s: &Session| s.doc().unwrap().wb.sheets.iter().map(|sh| sh.name.clone()).collect::<Vec<_>>();
let first = names(&s)[0].clone();
s.execute("home.insertSheet", json!({"name": "B", "before": 1})).unwrap();
s.execute("home.insertSheet", json!({"name": "C", "before": 2})).unwrap();
s.execute("home.deleteSheet", json!({"sheet": "B"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "C"})).unwrap();
s.execute("view.zoom", json!({"percent": 150})).unwrap();
s.execute("edit.undo", json!({"steps": 2})).unwrap();
assert_eq!(names(&s), [first.clone(), "B".to_string()]);
assert_eq!(zoom(&s, "B"), 100, "B never had C's zoom");
s.execute("sheet.activate", json!({"sheet": "B"})).unwrap();
s.execute("view.zoom", json!({"percent": 80})).unwrap();
s.execute("edit.redo", json!({"steps": 2})).unwrap();
assert_eq!(names(&s), [first, "C".to_string()]);
assert_eq!(zoom(&s, "C"), 150, "C gets its own zoom back, not B's");
}
#[test]
fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() {
let mut s = Session::new();
+3 -7
View File
@@ -51,16 +51,12 @@ fn text_needs_quote_prefix(t: &str, sys: gridcraft_core::date::DateSystem) -> bo
if t.is_empty() {
return false;
}
let first = t.chars().next();
let mut chars = t.chars();
let (first, second) = (chars.next(), chars.next());
if matches!(first, Some('=' | '\'')) {
return true;
}
// A `+` or `-` entry that reads as a formula becomes one (`+5+4`, `-abc`); one that doesn't
// stays text (`--`, `+49 170 1234567`), as `input_to_cell` decides it.
if matches!(first, Some('+' | '-'))
&& gridcraft_core::parse::starts_formula(t)
&& crate::cmd::edit::parse_typed_formula(t).is_ok_and(|e| crate::cmd::edit::check_arg_counts(&e).is_ok())
{
if matches!(first, Some('+' | '-')) && second.is_some_and(|c| c.is_ascii_alphabetic() || c == '(') {
return true;
}
!matches!(gridcraft_core::parse::parse_input(t, sys).value, Value::Text(ref x) if x.as_ref() == t)
+21 -216
View File
@@ -28,12 +28,6 @@ pub enum FillMode {
/// counted in that unit (one unit when they fall in the same one). A source that isn't dates
/// extends like a plain drag.
Dates(DateUnit),
/// Linear Trend: the targets continue the least-squares line (y = mx + b) through the source's
/// numbers. The source keeps its values.
LinearTrend,
/// Growth Trend: the targets continue the exponential curve (y = b·m^x) fitted to the source's
/// numbers. The source keeps its values.
GrowthTrend,
}
/// The step of a [`FillMode::Dates`] fill.
@@ -53,87 +47,6 @@ impl FillMode {
}
}
/// Whether a fill from `src` to `target` runs down or up the sheet rather than across it.
fn fills_vertically(src: RangeRef, target: RangeRef) -> bool {
target.height() != src.height() || target.width() == src.width()
}
/// The numbers in each lane of `src` that a fill to `target` continues, or `None` when a source
/// cell is empty or holds text, a logical value, an error, a formula or Python code.
fn numeric_lanes(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> Option<Vec<Vec<f64>>> {
let sh = wb.sheet(sheet)?;
lane_cells(src, target).map(|lane| lane.map(|c| trend_number(sh, c)).collect()).collect()
}
/// The cells of each lane of `src` that a fill to `target` continues: each column when the fill
/// runs down or up the sheet, each row when it runs across.
fn lane_cells(src: RangeRef, target: RangeRef) -> impl Iterator<Item = impl Iterator<Item = CellRef>> {
let vertical = fills_vertically(src, target);
let (lanes, len) = if vertical { (src.start.col..=src.end.col, src.height()) } else { (src.start.row..=src.end.row, src.width()) };
lanes.map(move |lane| (0..len).map(move |i| if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) }))
}
/// The sign Growth Trend fits a lane's numbers by: 1 when they are all above zero, -1 when they
/// are all below zero, and `None` otherwise.
fn growth_sign(nums: impl IntoIterator<Item = f64>) -> Option<f64> {
let (mut above, mut below) = (true, true);
for y in nums {
above &= y > 0.0;
below &= y < 0.0;
}
if above {
Some(1.0)
} else if below {
Some(-1.0)
} else {
None
}
}
/// The number a trend fill reads from source cell `c`, or `None` when it is empty or holds text, a
/// logical value, an error, a formula or Python code.
fn trend_number(sh: &gridcraft_model::Sheet, c: CellRef) -> Option<f64> {
let cell = sh.cell(c)?;
if cell.formula.is_some() || cell.py.is_some() || !cell.value.is_number() {
return None;
}
cell.value.as_f64()
}
/// Whether the fill menu offers Linear Trend (`growth` false) or Growth Trend (`growth` true) for a
/// fill from `src` to `target`: every source cell holds a number, and for Growth Trend the numbers
/// of each lane are all above zero or all below zero. A source or target larger than
/// [`MAX_FILL_CELLS`], or a target that doesn't hold the source in a corner, is refused by
/// `edit.autoFill`, so neither trend applies to it and no source cell is read.
pub fn trend_applies(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef, growth: bool) -> bool {
let (linear, growth_fits) = trends_that_apply(wb, sheet, src, target);
if growth { growth_fits } else { linear }
}
/// [`trend_applies`] for both trends from one read of the source: (Linear Trend, Growth Trend). It
/// checks each cell's number and sign and fits nothing, so the menu does not wait on a fit.
pub fn trends_that_apply(wb: &Workbook, sheet: usize, src: RangeRef, target: RangeRef) -> (bool, bool) {
if src.count() > MAX_FILL_CELLS || target.count() > MAX_FILL_CELLS || !holds_source_in_corner(src, target) {
return (false, false);
}
let Some(sh) = wb.sheet(sheet) else { return (false, false) };
let mut growth = true;
// The lanes and the sign rule are the ones the fill uses (`numeric_lanes`, `Pattern::growth`).
for lane in lane_cells(src, target) {
let mut missing = false;
let sign = growth_sign(lane.map_while(|c| {
let y = trend_number(sh, c);
missing |= y.is_none();
y
}));
if missing {
return (false, false);
}
growth &= sign.is_some();
}
(true, growth)
}
/// Whether a number format shows a calendar date (`YYYY-MM-DD` and `m/d/yyyy h:mm` do; `0 "days"`
/// and `h:mm` don't).
fn is_date_format(fmt: &str) -> bool {
@@ -189,7 +102,7 @@ pub fn fill_except(
let custom = cx.wb.custom_lists.clone();
let Some(sh) = cx.wb.sheet(sheet) else { return Ok(()) };
// Direction: down/up if target extends rows, else right/left.
let vertical = fills_vertically(src, target);
let vertical = target.height() != src.height() || target.width() == src.width();
let forward = if vertical {
target.end.row > src.end.row || target.start.row == src.start.row
} else {
@@ -207,25 +120,11 @@ pub fn fill_except(
if u64::from(lane_count).saturating_mul(u64::from(steps)) > MAX_FILL_CELLS {
return Err(crate::EngineError::Other("The fill is too large.".into()));
}
// Linear Trend and Growth Trend fit each lane's numbers.
let trends: Vec<Pattern> = match mode {
FillMode::LinearTrend | FillMode::GrowthTrend => {
let Some(lanes) = numeric_lanes(&cx.wb, sheet, src, target) else {
return Err(crate::EngineError::Other("Linear Trend and Growth Trend need a number in every source cell.".into()));
};
let fit = |nums: &Vec<f64>| if mode == FillMode::GrowthTrend { Pattern::growth(nums) } else { Some(Pattern::linear(nums)) };
let Some(trends) = lanes.iter().map(fit).collect() else {
return Err(crate::EngineError::Other("Growth Trend needs numbers that are all above zero or all below zero.".into()));
};
trends
}
_ => Vec::new(),
};
let lanes: Vec<u32> = if vertical { (src.start.col..=src.end.col).collect() } else { (src.start.row..=src.end.row).collect() };
let src_len = if vertical { src.height() } else { src.width() };
let mut writes: Vec<(CellRef, Option<Cell>)> = Vec::new();
let mut pictures = Vec::new();
for (lane_i, lane) in lanes.into_iter().enumerate() {
for lane in lanes {
let src_cells: Vec<(CellRef, Option<Cell>)> = (0..src_len)
.map(|i| {
let c = if vertical { CellRef::new(src.start.row + i, lane) } else { CellRef::new(lane, src.start.col + i) };
@@ -243,9 +142,7 @@ pub fn fill_except(
};
targets.retain(|t| !skip_rows.contains(&t.row));
let fmt = |c: &(CellRef, Option<Cell>)| cx.wb.styles.get(c.1.as_ref().map(|c| c.style).unwrap_or_default()).num_fmt.as_str();
let pattern = if let Some(trend) = trends.get(lane_i) {
trend.clone()
} else if mode.extends_series() || mode == FillMode::Alternate {
let pattern = if mode.extends_series() || mode == FillMode::Alternate {
let first_fmt = src_cells.first().map(fmt).unwrap_or_default();
let dates = match mode {
FillMode::Dates(unit) => Pattern::dates(&src_cells, unit, cx.wb.date_system, first_fmt),
@@ -279,14 +176,7 @@ pub fn fill_except(
writes.push((*t, Some(existing)));
continue;
}
FillMode::ValuesOnly
| FillMode::Series
| FillMode::Alternate
| FillMode::Copy
| FillMode::Extend
| FillMode::Dates(_)
| FillMode::LinearTrend
| FillMode::GrowthTrend => {
FillMode::ValuesOnly | FillMode::Series | FillMode::Alternate | FillMode::Copy | FillMode::Extend | FillMode::Dates(_) => {
let style = if mode == FillMode::ValuesOnly { sh.cell(*t).map(|c| c.style).unwrap_or_default() } else { cell.style };
if let Some(f) = &cell.formula {
if let Some(e) = f.expr() {
@@ -369,42 +259,9 @@ enum Pattern {
step: i64,
sys: gridcraft_core::DateSystem,
},
/// Growth Trend, kept as logarithms so that a value the curve reaches is not lost to an
/// overflow or underflow on the way: the logarithms of the fitted magnitudes at the source's
/// last and first cells, the logarithm of the factor between neighboring cells, and the sign
/// of every value (1 or -1).
Growth {
last: f64,
first: f64,
step: f64,
sign: f64,
},
}
impl Pattern {
/// Linear Trend: the least-squares line through `nums`. A lone number is copied unchanged.
fn linear(nums: &[f64]) -> Pattern {
if nums.len() == 1 {
return Pattern::Copy;
}
let (first, last, step) = least_squares(nums);
Pattern::Linear { last, first, step }
}
/// The exponential curve y = b·m^x fitted to `nums` at positions 0, 1, 2… by least squares on
/// the logarithms, as the GROWTH function fits positive numbers. Numbers below zero are fitted
/// by their magnitudes and keep their sign. `None` when the numbers are not all above zero or
/// all below zero. A lone number, or the same number repeated, is copied unchanged.
fn growth(nums: &[f64]) -> Option<Pattern> {
let sign = growth_sign(nums.iter().copied())?;
if nums.windows(2).all(|w| w.first() == w.last()) {
return Some(Pattern::Copy);
}
let logs: Vec<f64> = nums.iter().map(|y| (y * sign).ln()).collect();
let (first, last, step) = least_squares(&logs);
Some(Pattern::Growth { last, first, step, sign })
}
/// The pattern of Fill Days, Fill Weekdays, Fill Months or Fill Years, or `None` when the
/// source isn't all dates (numbers, not formulas, under a date format in its first cell).
fn dates(cells: &[(CellRef, Option<Cell>)], unit: DateUnit, sys: gridcraft_core::DateSystem, fmt: &str) -> Option<Pattern> {
@@ -487,7 +344,19 @@ impl Pattern {
}
}
// Least-squares step for 2+ values (Excel uses a linear trend).
return Pattern::linear(&nums);
let n = nums.len() as f64;
let mean_x = (n - 1.0) / 2.0;
let mean_y = nums.iter().sum::<f64>() / n;
let mut num = 0.0;
let mut den = 0.0;
for (i, y) in nums.iter().enumerate() {
num += (i as f64 - mean_x) * (y - mean_y);
den += (i as f64 - mean_x).powi(2);
}
let step = if den == 0.0 { 0.0 } else { num / den };
let fitted_last = mean_y + step * (n - 1.0 - mean_x);
let fitted_first = mean_y - step * mean_x;
return Pattern::Linear { last: fitted_last, first: fitted_first, step };
}
// Text.
if !vals.is_empty() && vals.iter().all(|v| v.is_text()) {
@@ -581,45 +450,10 @@ impl Pattern {
let base = if forward { *last } else { *first };
Some(Value::number(add_weekdays(*sys, base, step.checked_mul(k)?.checked_mul(sign)?)?))
}
Pattern::Growth { last, first, step, sign: growth_sign } => {
let base = if forward { *last } else { *first };
Some(Value::number(round15(growth_sign * (base + step * (k * sign) as f64).exp())))
}
}
}
}
/// 2^600 and 2^-600, both exact.
const TWO_POW_600: f64 = f64::from_bits((1023 + 600) << 52);
const TWO_POW_MINUS_600: f64 = f64::from_bits((1023 - 600) << 52);
/// The least-squares line through `nums` at positions 0, 1, 2…: its values at the first and last
/// positions, and its step. A lone number gives a step of zero. When a number is larger than 2^600,
/// the fit runs on the numbers multiplied by 2^-600 and its results are multiplied by 2^600, so the
/// sums stay finite for numbers up to the largest double. When every number is smaller than 2^-600,
/// the fit runs on the numbers multiplied by 2^600 and its results are multiplied by 2^-600, so
/// subnormal numbers keep their step instead of rounding it to zero.
fn least_squares(nums: &[f64]) -> (f64, f64, f64) {
let (down, up) = if nums.iter().any(|y| y.abs() > TWO_POW_600) {
(TWO_POW_MINUS_600, TWO_POW_600)
} else if nums.iter().all(|y| y.abs() < TWO_POW_MINUS_600) {
(TWO_POW_600, TWO_POW_MINUS_600)
} else {
(1.0, 1.0)
};
let n = nums.len() as f64;
let mean_x = (n - 1.0) / 2.0;
let mean_y = nums.iter().map(|y| y * down).sum::<f64>() / n;
let mut num = 0.0;
let mut den = 0.0;
for (i, y) in nums.iter().enumerate() {
num += (i as f64 - mean_x) * (y * down - mean_y);
den += (i as f64 - mean_x).powi(2);
}
let step = if den == 0.0 { 0.0 } else { num / den };
((mean_y - step * mean_x) * up, (mean_y + step * (n - 1.0 - mean_x)) * up, step * up)
}
/// Whether `serial` falls on Monday to Friday; `None` outside the supported date range.
fn is_weekday(sys: gridcraft_core::DateSystem, serial: f64) -> Option<bool> {
datetime_from_serial(sys, serial).map(|d| d.weekday != 0 && d.weekday != 6)
@@ -680,27 +514,13 @@ fn add_months_clamped(sys: gridcraft_core::DateSystem, serial: f64, months: i64)
serial_from_ymd(sys, year, month, (d.day as i64).min(last as i64)).map(|day| day + serial - serial.floor())
}
/// `x` rounded to 15 significant digits through its exact decimal expansion, so a number that
/// already has 15 or fewer digits comes back unchanged at any size. A number near the largest
/// double whose rounding would pass it keeps its value. A whole number below 10^15 is returned
/// as it is, and other numbers are written to a buffer on the stack, so a fill does not allocate
/// for each cell.
fn round15(x: f64) -> f64 {
use std::io::Write;
if x == 0.0 || !x.is_finite() || (x.fract() == 0.0 && x.abs() < 1e15) {
if x == 0.0 || !x.is_finite() {
return x;
}
// "-1.23456789012345e-308" is the longest expansion: 22 bytes.
let mut buf = [0u8; 32];
let mut out = &mut buf[..];
if write!(out, "{x:.14e}").is_err() {
return x;
}
let len = 32 - out.len();
match buf.get(..len).and_then(|b| std::str::from_utf8(b).ok()).and_then(|s| s.parse::<f64>().ok()) {
Some(r) if r.is_finite() => r,
_ => x,
}
let mag = x.abs().log10().floor() as i32;
let p = 10f64.powi(14 - mag);
if !p.is_finite() || p == 0.0 { x } else { (x * p).round() / p }
}
/// `1st Period` → `2nd Period`: an English ordinal ending is rewritten to suit the new number.
@@ -991,21 +811,6 @@ mod tests {
assert_eq!(sh.value(CellRef::new(1, 1)), Value::from("03/12/2023"));
}
#[test]
fn round15_matches_the_decimal_expansion_without_allocating() {
let by_string = |x: f64| match format!("{x:.14e}").parse::<f64>() {
Ok(r) if r.is_finite() => r,
_ => x,
};
let tiny = f64::from_bits(1);
let whole = [1.0, -7.0, 999_999_999_999_999.0, 1e15, 1e15 + 1.0, 123_456_789_012_345_680.0];
let other = [0.1 + 0.2, -1.0 / 3.0, tiny, -tiny, 1e-308, f64::MAX, -f64::MAX, 1.7976931348623e308];
for x in whole.into_iter().chain(other) {
assert_eq!(round15(x).to_bits(), by_string(x).to_bits(), "{x:e}");
}
assert_eq!(round15(-0.0).to_bits(), (-0.0f64).to_bits());
}
#[test]
fn series_keeps_value_equal_to_stop_after_float_drift() {
let mut s = crate::Session::new();
+32 -7
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.
@@ -1147,14 +1143,43 @@ pub fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
Err(EngineError::Other(format!("{path}: no file system in the browser")))
}
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn base64_encode(data: &[u8]) -> String {
gridcraft_model::b64::encode(data)
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
for i in 0..4 {
if i <= chunk.len() {
out.push(B64[((n >> (18 - 6 * i)) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
/// Base64, or a `data:` URL's base64 payload.
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
let s = s.split_once(',').filter(|(h, _)| h.starts_with("data:")).map(|(_, b)| b).unwrap_or(s);
gridcraft_model::b64::decode(s)
let mut out = Vec::with_capacity(s.len() / 4 * 3);
let mut buf = 0u32;
let mut bits = 0;
for c in s.bytes() {
if c == b'=' || c.is_ascii_whitespace() {
continue;
}
let v = B64.iter().position(|&x| x == c)? as u32;
buf = (buf << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((buf >> bits) as u8);
buf &= (1 << bits) - 1;
}
}
Some(out)
}
/// Pixel size of a PNG or JPEG from its header.
+1 -9
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
@@ -348,11 +345,7 @@ impl DocState {
wb.refresh_equations();
let scripts_trusted = !cmd::extra::has_scripts(&wb);
let wb = Arc::new(wb);
let mut sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
// A merged active cell is selected whole, as a click on it selects it (#1348).
if let Some(sh) = wb.active() {
sel.expand_merges(sh);
}
let sel = Selection::at(wb.active().map(|s| s.view_active).unwrap_or_default());
DocState {
saved: wb.clone(),
wb,
@@ -367,7 +360,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::*;
+1 -3
View File
@@ -154,9 +154,7 @@ mod tests {
assert_eq!(functions_in_formula("+SUM(1)"), ["SUM"]);
assert_eq!(functions_in_formula("-ABS(A1)"), ["ABS"]);
assert!(functions_in_formula("-5").is_empty() && functions_in_formula("+1e3").is_empty(), "numbers");
assert!(functions_in_formula("+").is_empty() && functions_in_formula("--").is_empty(), "not formulas");
// A sign before a space still starts a formula, as Excel takes `- SUM(1)` (#2023).
assert_eq!(functions_in_formula("- SUM(1)"), ["SUM"]);
assert!(functions_in_formula("+").is_empty() && functions_in_formula("- SUM(1)").is_empty(), "not formulas");
}
#[test]
+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)));
+5 -786
View File
@@ -343,84 +343,6 @@ fn enter_values_and_formulas() {
assert_eq!(crate::display::cell_text(&d.wb, sh, CellRef::parse("B1").unwrap()), "12%");
}
#[test]
fn a_leading_plus_or_minus_starts_a_formula() {
// #2023: like Excel (and Lotus 1-2-3 before it), typing `+5+4` enters the formula `=+5+4`.
let mut s = s();
let input = |s: &Session, a: &str| s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).map(|c| c.input_text());
for (cell, typed, value) in [
("A1", "+5+4", 9.0),
("A2", "-5+4", -1.0),
("A3", "--5", 5.0),
("A4", "-3/4", -0.75),
("A5", "+A1*2", 18.0),
("A6", "-(A1)", -9.0),
("A7", "+1/30", 1.0 / 30.0),
("A8", "-1/30", -1.0 / 30.0),
] {
s.execute("cell.set", json!({"cell": cell, "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}"));
assert_eq!(input(&s, cell), Some(format!("={typed}")), "{typed}");
assert_eq!(v(&s, cell), Value::Number(value), "{typed}");
}
// A signed number is a number, a lone sign is text, and an apostrophe keeps the text.
for (typed, value) in [
("+5", Value::Number(5.0)),
("-5", Value::Number(-5.0)),
("-12%", Value::Number(-0.12)),
("-$5", Value::Number(-5.0)),
("-", Value::text("-")),
("+", Value::text("+")),
("'+5+4", Value::text("+5+4")),
] {
s.execute("cell.set", json!({"cell": "B1", "input": typed})).unwrap();
assert_eq!(v(&s, "B1"), value, "{typed}");
assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}");
}
// Text that would read as a formula is edited with its apostrophe, so confirming the editor
// unchanged keeps it text; text that wouldn't is edited as it is.
for (typed, shown) in [
("'+5+4", "'+5+4"),
("'-5+4", "'-5+4"),
("'+1-555-1234", "'+1-555-1234"),
("'-abc", "'-abc"),
("--", "--"),
("+49 170 1234567", "+49 170 1234567"),
("+1:30", "+1:30"),
] {
s.execute("cell.set", json!({"cell": "B2", "input": typed})).unwrap();
let before = v(&s, "B2");
let edit = {
let d = s.doc().unwrap();
crate::display::edit_text(&d.wb, d.wb.active().unwrap(), CellRef::parse("B2").unwrap())
};
assert_eq!(edit, shown, "{typed}");
s.execute("cell.set", json!({"cell": "B2", "input": edit})).unwrap();
assert_eq!(v(&s, "B2"), before, "{typed} stays text after an unchanged edit");
}
// As observed in Excel for the web, an entry that doesn't read as a formula stays text, and
// one that does but names nothing known is #NAME?. Only `=` entries are refused.
for typed in ["--", "-----", "+5+", "+49 170 1234567", "+1:30"] {
s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}"));
assert_eq!(v(&s, "C1"), Value::text(typed), "{typed}");
assert_eq!(input(&s, "C1").as_deref(), Some(typed), "{typed}");
}
s.execute("cell.set", json!({"cell": "C2", "input": "- item"})).unwrap();
assert_eq!(v(&s, "C2"), Value::Error(gridcraft_core::CellError::Name));
// Excel for the web keeps `+1:30` as text (above) but reads `-1:30` as a formula (rows 1 to 30).
s.execute("cell.set", json!({"cell": "C40", "input": "-1:30"})).unwrap();
assert_eq!(input(&s, "C40").as_deref(), Some("=-1:30"));
let e = s.execute("cell.set", json!({"cell": "C1", "input": "=--"})).unwrap_err().to_string();
assert!(e.contains("problem with this formula"), "{e}");
assert_eq!(v(&s, "C1"), Value::text("+1:30"), "a refused entry keeps the cell");
// Pasted or split by Text to Columns, the same rule applies.
s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap();
assert_eq!(v(&s, "D1"), Value::text("--"));
assert_eq!(v(&s, "E1"), Value::Number(-1.0));
s.execute("cell.set", json!({"cell": "F1", "input": "a,--,b"})).unwrap();
s.execute("data.textToColumns", json!({"range": "F1", "delimiters": [","]})).unwrap();
assert_eq!([v(&s, "F1"), v(&s, "G1"), v(&s, "H1")], [Value::text("a"), Value::text("--"), Value::text("b")]);
}
#[test]
fn formulas_with_the_wrong_argument_count_are_refused_on_entry() {
// #363: =DATEDIF(start, end) was stored and showed #VALUE!. Like Excel, entry refuses it and
@@ -962,13 +884,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"));
}
@@ -1351,177 +1271,6 @@ fn fill_days_weekdays_months_and_years_step_a_date_by_that_unit() {
assert_eq!(v(&s, "J2"), Value::Number(46081.5));
}
#[test]
fn linear_and_growth_trend_continue_the_fitted_line_or_curve() {
let mut s = s();
let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::<Vec<_>>();
let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::<Vec<_>>();
let fill =
|s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode}));
// The examples on Excel's "Project values in a series" page: 1, 2 and 1, 3 for both trends, 2, 3
// for Growth Trend and 100, 95 for Linear Trend. 2, 3 gives 4, 5, 6 by Linear Trend.
for (col, start, linear, growth) in [
("A", [1.0, 2.0], [3.0, 4.0, 5.0], [4.0, 8.0, 16.0]),
("B", [1.0, 3.0], [5.0, 7.0, 9.0], [9.0, 27.0, 81.0]),
("C", [2.0, 3.0], [4.0, 5.0, 6.0], [4.5, 6.75, 10.125]),
] {
s.execute("range.setValues", json!({"range": format!("{col}1"), "values": [[start[0]], [start[1]]]})).unwrap();
let (src, target) = (format!("{col}1:{col}2"), format!("{col}1:{col}5"));
let cells: Vec<String> = (3..=5).map(|r| format!("{col}{r}")).collect();
let cells: Vec<&str> = cells.iter().map(String::as_str).collect();
fill(&mut s, &src, &target, "linearTrend").unwrap();
assert_eq!(nums(&s, &cells), n(&linear), "Linear Trend from {start:?}");
fill(&mut s, &src, &target, "growthTrend").unwrap();
assert_eq!(nums(&s, &cells), n(&growth), "Growth Trend from {start:?}");
}
s.execute("range.setValues", json!({"range": "F1", "values": [[100], [95]]})).unwrap();
fill(&mut s, "F1:F2", "F1:F4", "linearTrend").unwrap();
assert_eq!(nums(&s, &["F3", "F4"]), n(&[90.0, 85.0]));
// Three numbers: the targets follow the best fit and the source keeps its values. 1, 3, 4 fit
// y = 1.5x + 7/6; 1, 2, 8 fit y = 0.8909·2.8284^x.
s.execute("range.setValues", json!({"range": "D1", "values": [[1, 1], [3, 2], [4, 8]]})).unwrap();
fill(&mut s, "D1:D3", "D1:D5", "linearTrend").unwrap();
assert_eq!(nums(&s, &["D1", "D2", "D3", "D4", "D5"]), n(&[1.0, 3.0, 4.0, 5.66666666666667, 7.16666666666667]));
fill(&mut s, "E1:E3", "E1:E4", "growthTrend").unwrap();
assert_eq!(nums(&s, &["E1", "E2", "E3", "E4"]), n(&[1.0, 2.0, 8.0, 20.158736798318]));
// Upward and leftward the trend continues backward: 1, 2 gives 0 and -1, or 0.5 and 0.25.
s.execute("range.setValues", json!({"range": "G3", "values": [[1], [2]]})).unwrap();
fill(&mut s, "G3:G4", "G1:G4", "linearTrend").unwrap();
assert_eq!(nums(&s, &["G2", "G1"]), n(&[0.0, -1.0]));
s.execute("range.setValues", json!({"range": "J1", "values": [[1, 2]]})).unwrap();
fill(&mut s, "J1:K1", "H1:K1", "growthTrend").unwrap();
assert_eq!(nums(&s, &["I1", "H1"]), n(&[0.5, 0.25]));
// Negative numbers grow away from zero: -2, -4 gives -8.
s.execute("range.setValues", json!({"range": "L1", "values": [[-2], [-4]]})).unwrap();
fill(&mut s, "L1:L2", "L1:L3", "growthTrend").unwrap();
assert_eq!(v(&s, "L3"), Value::Number(-8.0));
// A tiny start with a huge factor still reaches 1e300 without overflowing on the way.
s.execute("range.setValues", json!({"range": "S1", "values": [[1e-200], [1e-100]]})).unwrap();
fill(&mut s, "S1:S2", "S1:S6", "growthTrend").unwrap();
let Value::Number(s6) = v(&s, "S6") else { panic!("S6 is {:?}", v(&s, "S6")) };
assert!((s6 / 1e300 - 1.0).abs() < 1e-9, "S6 = {s6}");
// Numbers near the largest double continue their line without a sum overflowing: two equal
// numbers repeat, and 1e308 four times then 0 fit a step of -2e307 and continue at 2e307.
s.execute("range.setValues", json!({"range": "T1", "values": [[1e308, 1e308], [1e308, 1e308], [0, 1e308], [0, 1e308], [0, 0]]})).unwrap();
fill(&mut s, "T1:T2", "T1:T3", "linearTrend").unwrap();
fill(&mut s, "U1:U5", "U1:U6", "linearTrend").unwrap();
for (cell, want) in [("T3", 1e308), ("U6", 2e307)] {
let Value::Number(got) = v(&s, cell) else { panic!("{cell} is {:?}", v(&s, cell)) };
assert!((got / want - 1.0).abs() < 1e-9, "{cell} = {got}");
}
// A lone number repeats, and dates a month apart step by their days, not by months.
s.execute("cell.set", json!({"cell": "M1", "input": "7"})).unwrap();
fill(&mut s, "M1", "M1:M2", "linearTrend").unwrap();
assert_eq!(v(&s, "M2"), Value::Number(7.0));
// It repeats unchanged, with every digit and at any size, by either trend.
s.execute("range.setValues", json!({"range": "V1", "values": [[1e308, 0.12345678901234567]]})).unwrap();
fill(&mut s, "V1", "V1:V3", "growthTrend").unwrap();
fill(&mut s, "W1", "W1:W3", "linearTrend").unwrap();
assert_eq!(nums(&s, &["V2", "V3", "W2", "W3"]), n(&[1e308, 1e308, 0.12345678901234567, 0.12345678901234567]));
// The smallest double three times repeats rather than averaging to zero.
let tiny = f64::from_bits(1);
s.execute("range.setValues", json!({"range": "X1", "values": [[tiny], [tiny], [tiny]]})).unwrap();
fill(&mut s, "X1:X3", "X1:X4", "linearTrend").unwrap();
assert_eq!(v(&s, "X4"), Value::Number(tiny));
// The two smallest doubles continue their step: 1 and 2 times the smallest give 3 and 4 times it.
s.execute("range.setValues", json!({"range": "AD1", "values": [[tiny], [f64::from_bits(2)]]})).unwrap();
fill(&mut s, "AD1:AD2", "AD1:AD4", "linearTrend").unwrap();
assert_eq!(nums(&s, &["AD3", "AD4"]), n(&[f64::from_bits(3), f64::from_bits(4)]));
// Huge numbers three times repeat exactly: the largest double, and one with 14 digits.
let (big, big14) = (f64::MAX, 1.7976931348623e308);
s.execute("range.setValues", json!({"range": "Y1", "values": [[big, big14], [big, big14], [big, big14]]})).unwrap();
fill(&mut s, "Y1:Z3", "Y1:Z4", "linearTrend").unwrap();
assert_eq!(nums(&s, &["Y4", "Z4"]), n(&[big, big14]));
// Growth Trend repeats the same number exactly too, huge, tiny or below zero.
s.execute("range.setValues", json!({"range": "AA1", "values": [[1e300, 1e-300, -0.3], [1e300, 1e-300, -0.3]]})).unwrap();
fill(&mut s, "AA1:AC2", "AA1:AC4", "growthTrend").unwrap();
assert_eq!(nums(&s, &["AA4", "AB4", "AC4"]), n(&[1e300, 1e-300, -0.3]));
s.execute("cell.set", json!({"cell": "N1", "input": "1/15/2026"})).unwrap();
s.execute("cell.set", json!({"cell": "N2", "input": "2/15/2026"})).unwrap();
fill(&mut s, "N1:N2", "N1:N3", "linearTrend").unwrap();
assert_eq!(v(&s, "N3"), Value::Number(46099.0), "2/15/2026 plus 31 days");
// Text or an empty cell in the source, and zero or mixed signs for Growth Trend, are refused
// and fill nothing.
s.execute("range.setValues", json!({"range": "O1", "values": [[1, 1, 0], ["x", -2, 2]]})).unwrap();
assert!(fill(&mut s, "O1:O2", "O1:O3", "linearTrend").is_err());
assert!(fill(&mut s, "P1:P2", "P1:P3", "growthTrend").is_err());
assert!(fill(&mut s, "Q1:Q2", "Q1:Q3", "growthTrend").is_err());
assert!(fill(&mut s, "R1:R2", "R1:R3", "linearTrend").is_err());
assert_eq!(nums(&s, &["O3", "P3", "Q3", "R3"]), [Value::Empty, Value::Empty, Value::Empty, Value::Empty]);
fill(&mut s, "P1:P2", "P1:P3", "linearTrend").unwrap();
assert_eq!(v(&s, "P3"), Value::Number(-5.0));
}
#[test]
fn trend_fills_are_offered_for_numbers_only() {
let mut s = s();
let offered = |s: &Session, src: &str, target: &str, growth: bool| {
let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r(src), r(target), growth)
};
s.execute("range.setValues", json!({"range": "A1", "values": [[1, -1, 1], [2, -3, "x"]]})).unwrap();
s.execute("cell.set", json!({"cell": "D1", "input": "=A1"})).unwrap();
s.execute("cell.set", json!({"cell": "D2", "input": "5"})).unwrap();
assert!(offered(&s, "A1:A2", "A1:A5", false) && offered(&s, "A1:A2", "A1:A5", true));
// Down A1:B2, each column keeps one sign; across it, row 1 holds 1 and -1.
assert!(offered(&s, "A1:B2", "A1:B5", true));
assert!(offered(&s, "A1:B2", "A1:E2", false) && !offered(&s, "A1:B2", "A1:E2", true));
let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:E2")), (true, false));
assert_eq!(crate::fill::trends_that_apply(&s.doc().unwrap().wb, 0, r("A1:B2"), r("A1:B5")), (true, true));
assert!(!offered(&s, "C1:C2", "C1:C4", false), "text");
assert!(!offered(&s, "D1:D2", "D1:D4", false), "a formula");
assert!(!offered(&s, "E1:E2", "E1:E4", false), "empty cells");
// A fill `edit.autoFill` refuses is not offered: five columns down to the last row is more than
// MAX_FILL_CELLS cells, and a target that doesn't hold the source in a corner.
s.execute("range.setValues", json!({"range": "F1", "values": [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]]})).unwrap();
assert!(offered(&s, "F1:J2", "F1:J1000", false) && offered(&s, "F1:J2", "F1:J1000", true));
assert!(!offered(&s, "F1:J2", "F1:J1048576", false) && !offered(&s, "F1:J2", "F1:J1048576", true), "too large");
assert!(!offered(&s, "F1:J2", "F2:J5", false), "source outside the target");
}
#[test]
fn trend_fills_fit_each_lane_of_a_two_dimensional_source() {
let mut s = s();
let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::<Vec<_>>();
let n = |xs: &[f64]| xs.iter().map(|x| Value::Number(*x)).collect::<Vec<_>>();
let fill =
|s: &mut Session, src: &str, target: &str, mode: &str| s.execute("edit.autoFill", json!({"source": src, "target": target, "mode": mode}));
// Down: column A holds 1, 2 and column B 10, 20, and one command fits each column on its own.
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap();
let down = ["A3", "A4", "A5", "B3", "B4", "B5"];
fill(&mut s, "A1:B2", "A1:B5", "linearTrend").unwrap();
assert_eq!(nums(&s, &down), n(&[3.0, 4.0, 5.0, 30.0, 40.0, 50.0]));
fill(&mut s, "A1:B2", "A1:B5", "growthTrend").unwrap();
assert_eq!(nums(&s, &down), n(&[4.0, 8.0, 16.0, 40.0, 80.0, 160.0]));
// Across: row 1 holds 1, 10 and row 2 holds 2, 20, and each row is fitted on its own.
s.execute("range.setValues", json!({"range": "H1", "values": [[1, 10], [2, 20]]})).unwrap();
let across = ["J1", "K1", "L1", "J2", "K2", "L2"];
fill(&mut s, "H1:I2", "H1:L2", "linearTrend").unwrap();
assert_eq!(nums(&s, &across), n(&[19.0, 28.0, 37.0, 38.0, 56.0, 74.0]));
fill(&mut s, "H1:I2", "H1:L2", "growthTrend").unwrap();
assert_eq!(nums(&s, &across), n(&[100.0, 1000.0, 10000.0, 200.0, 2000.0, 20000.0]));
// The sources keep their values.
assert_eq!(nums(&s, &["A1", "A2", "B1", "B2", "H1", "I1", "H2", "I2"]), n(&[1.0, 2.0, 10.0, 20.0, 1.0, 10.0, 2.0, 20.0]));
}
#[test]
fn a_trend_fill_undoes_as_one_step() {
let mut s = s();
let nums = |s: &Session, cells: &[&str]| cells.iter().map(|c| v(s, c)).collect::<Vec<_>>();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 10], [2, 20]]})).unwrap();
s.execute("cell.set", json!({"cell": "A4", "input": "99"})).unwrap();
s.execute("edit.autoFill", json!({"source": "A1:B2", "target": "A1:B5", "mode": "linearTrend"})).unwrap();
assert_eq!(v(&s, "A4"), Value::Number(4.0));
s.execute("edit.undo", json!({})).unwrap();
// The targets are back as they were (empty, and 99 in A4), and the source is unchanged.
assert_eq!(
nums(&s, &["A3", "A4", "A5", "B3", "B4", "B5"]),
[Value::Empty, Value::Number(99.0), Value::Empty, Value::Empty, Value::Empty, Value::Empty]
);
assert_eq!(nums(&s, &["A1", "A2", "B1", "B2"]), [Value::Number(1.0), Value::Number(2.0), Value::Number(10.0), Value::Number(20.0)]);
}
#[test]
fn only_a_number_in_a_date_format_offers_the_date_fills() {
let mut s = s();
@@ -1990,27 +1739,6 @@ fn case_sensitive_sort_puts_lowercase_first() {
assert_eq!(col, ["a", "A", "aB", "Ab", "b", "B"].map(Value::from));
}
/// Data > Sort orders numbers exactly, like Excel 365: 0.3 sorts before `=0.1+0.2`
/// (0.30000000000000004) ascending and after it descending, whatever the input order.
#[test]
fn sort_orders_numbers_exactly() {
for first_noisy in [true, false] {
let mut s = s();
let (a1, a2, b1, b2) = if first_noisy { ("=0.1+0.2", "0.3", "e", "t") } else { ("0.3", "=0.1+0.2", "t", "e") };
for (cell, input) in [("A1", a1), ("A2", a2), ("B1", b1), ("B2", b2)] {
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
}
let labels = |s: &Session| [v(s, "B1"), v(s, "B2")];
s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A"}]})).unwrap();
assert_eq!(labels(&s), ["t", "e"].map(Value::from), "ascending, noisy first: {first_noisy}");
s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A", "order": "desc"}]})).unwrap();
assert_eq!(labels(&s), ["e", "t"].map(Value::from), "descending, noisy first: {first_noisy}");
s.execute("selection.set", json!({"range": "A1:B2"})).unwrap();
s.execute("data.sortAscending", json!({"range": "A1:B2", "column": "A"})).unwrap();
assert_eq!(labels(&s), ["t", "e"].map(Value::from), "quick sort, noisy first: {first_noisy}");
}
}
/// #3949: Excel sorts values that are not in the custom list A to Z after the listed ones.
#[test]
fn custom_list_sort_puts_unlisted_values_after_the_list_in_order() {
@@ -2166,7 +1894,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 +5319,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";
@@ -5722,140 +5381,6 @@ fn a_decrypted_workbook_never_overwrites_its_encrypted_original() {
std::fs::remove_dir_all(dir).unwrap();
}
fn quick_analysis_block(s: &mut Session) {
for (a, t) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] {
s.execute("cell.set", json!({"cell": a, "input": t})).unwrap();
}
for (r, (q1, q2)) in [(1.0, 10.0), (2.0, 20.0), (3.0, 30.0)].into_iter().enumerate() {
s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap();
s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap();
}
}
#[test]
fn analysis_add_total_writes_formulas_in_one_undo_step() {
// Issue #791 (Quick Analysis › Totals).
let mut s = s();
quick_analysis_block(&mut s);
let before = s.doc().unwrap().undo.len();
// The header row and the text-only column are skipped; the selection is the default range.
s.execute("selection.set", json!({"range": "A1:C4"})).unwrap();
let r = s.execute("analysis.addTotal", json!({"function": "sum"})).unwrap();
assert_eq!(r["output"], "B5:C5");
assert_eq!(v(&s, "B5"), Value::Number(6.0));
assert_eq!(v(&s, "C5"), Value::Number(60.0));
assert_eq!(v(&s, "A5"), Value::Empty, "text columns get no total");
s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "average", "direction": "rows"})).unwrap();
assert_eq!(v(&s, "D2"), Value::Number(5.5));
s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "runningTotal", "overwrite": true})).unwrap();
assert_eq!(v(&s, "D4"), Value::Number(6.0), "running total down column B");
assert_eq!(v(&s, "E4"), Value::Number(60.0));
s.execute("analysis.addTotal", json!({"range": "B1:B4", "function": "percentTotal", "overwrite": true})).unwrap();
assert_eq!(v(&s, "C4"), Value::Number(0.5), "overwrite replaces the C column cell next to B");
assert_eq!(s.doc().unwrap().undo.len(), before + 4, "one undo step per call");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(v(&s, "C4"), Value::Number(30.0));
// A second sum into the occupied row is refused rather than overwriting.
assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4"})).is_err());
}
#[test]
fn analysis_add_total_refuses_bad_and_huge_input() {
let mut s = s();
quick_analysis_block(&mut s);
// Empty params on a single cell, unknown function, no numbers, whole columns, no room.
assert!(s.execute("analysis.addTotal", json!({})).is_err());
assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4", "function": "median"})).is_err());
assert!(s.execute("analysis.addTotal", json!({"range": "A1:A4"})).is_err());
let before = s.doc().unwrap().undo.len();
let r = s.execute("analysis.addTotal", json!({"range": "B:C"})).unwrap();
assert_eq!(r["output"], "B5:C5", "whole columns are clipped to the used range");
assert_eq!(s.doc().unwrap().undo.len(), before + 1);
s.execute("cell.set", json!({"cell": "B1048575", "input": "1"})).unwrap();
s.execute("cell.set", json!({"cell": "B1048576", "input": "2"})).unwrap();
assert!(s.execute("analysis.addTotal", json!({"range": "B1048575:C1048576"})).is_err(), "no row below the last one");
assert!(s.execute("analysis.addTotal", json!({"range": "B1:C1048576", "function": "runningTotal"})).is_err(), "per-cell block over the cap");
}
#[test]
fn analysis_results_stay_outside_a_selection_that_extends_past_the_data() {
let mut s = s();
quick_analysis_block(&mut s);
// Data ends in row 4; the selection runs to row 10, so the sum goes in row 11.
let r = s.execute("analysis.addTotal", json!({"range": "A1:C10"})).unwrap();
assert_eq!(r["output"], "B11:C11");
assert_eq!(v(&s, "B11"), Value::Number(6.0));
assert_eq!(v(&s, "B5"), Value::Empty);
// Per-row blocks and sparklines move out by the selection's size too.
let r = s.execute("analysis.addTotal", json!({"range": "B1:C10", "function": "runningTotal", "direction": "rows"})).unwrap();
assert_eq!(r["output"], "B12:C14", "per-row block lands below the selection, not inside it");
let r = s.execute("analysis.addSparklines", json!({"range": "A1:F4"})).unwrap();
assert_eq!(r["output"], "G2:G4");
let r = s.execute("analysis.addSparklines", json!({"range": "A1:C8", "direction": "columns"})).unwrap();
assert_eq!(r["output"], "B9:C9");
}
#[test]
fn analysis_overwrite_keeps_the_target_cell_style() {
let mut s = s();
quick_analysis_block(&mut s);
s.execute("cell.set", json!({"cell": "B5", "input": "1"})).unwrap();
s.execute("selection.set", json!({"cell": "B5"})).unwrap();
s.execute("home.bold", json!({})).unwrap();
s.execute("analysis.addTotal", json!({"range": "A1:C4", "overwrite": true})).unwrap();
assert_eq!(v(&s, "B5"), Value::Number(6.0));
let d = s.doc().unwrap();
let sh = d.wb.active().unwrap();
assert!(d.wb.styles.get(sh.style_id(CellRef::parse("B5").unwrap())).font.bold, "bold survives the overwrite");
}
#[test]
fn analysis_commands_refuse_a_multi_area_selection_without_a_range() {
let mut s = s();
quick_analysis_block(&mut s);
s.execute("selection.set", json!({"range": "A1:C4,E1:F4"})).unwrap();
for c in ["analysis.addTotal", "analysis.addSparklines"] {
let e = s.execute(c, json!({})).unwrap_err().to_string();
assert!(e.contains("single contiguous range"), "{c}: {e}");
}
assert_eq!(v(&s, "B5"), Value::Empty);
// An explicit range still works.
s.execute("analysis.addTotal", json!({"range": "A1:C4"})).unwrap();
assert_eq!(v(&s, "B5"), Value::Number(6.0));
}
#[test]
fn analysis_add_sparklines_one_per_row_in_one_undo_step() {
let mut s = s();
quick_analysis_block(&mut s);
let before = s.doc().unwrap().undo.len();
let r = s.execute("analysis.addSparklines", json!({"range": "A1:C4", "type": "column"})).unwrap();
assert_eq!(r["output"], "D2:D4", "header row and label column are skipped");
let sparks = s.doc().unwrap().wb.active().unwrap().sparklines.clone();
assert_eq!(sparks.len(), 3);
assert!(sparks.iter().any(|x| x.cell == CellRef::parse("D3").unwrap() && x.source == "B3:C3"));
assert_eq!(s.doc().unwrap().undo.len(), before + 1);
s.execute("edit.undo", json!({})).unwrap();
assert!(s.doc().unwrap().wb.active().unwrap().sparklines.is_empty());
assert!(s.execute("analysis.addSparklines", json!({"range": "A1:A4"})).is_err());
}
#[test]
fn analysis_add_sparklines_refuses_a_protected_sheet() {
let mut s = s();
quick_analysis_block(&mut s);
s.execute("analysis.addSparklines", json!({"range": "A1:C4"})).unwrap();
s.execute("review.protectSheet", json!({})).unwrap();
let (undo, sparks) = (s.doc().unwrap().undo.len(), s.doc().unwrap().wb.active().unwrap().sparklines.clone());
for p in [json!({"range": "A1:C4", "overwrite": true}), json!({"range": "A1:B3", "direction": "columns"})] {
assert!(s.execute("analysis.addSparklines", p).is_err());
}
assert_eq!(s.doc().unwrap().undo.len(), undo, "a refused command leaves no undo step");
assert_eq!(s.doc().unwrap().wb.active().unwrap().sparklines, sparks);
s.execute("review.unprotectSheet", json!({})).unwrap();
s.execute("analysis.addSparklines", json!({"range": "A1:C4", "overwrite": true})).unwrap();
}
#[test]
fn link_open_refuses_every_scheme_but_http_https_and_mailto() {
let mut s = s();
@@ -7672,45 +7197,6 @@ fn pivot_new_sheet_destination_respects_workbook_structure_protection() {
assert!(s.execute("insert.pivotTable", json!({"source": "A1:B3", "location": "New"})).is_err());
}
/// A password set in GridCraft is kept in every form a file stores; XLSX writes its Excel form,
/// so a sheet or workbook password survives saving and reopening and still unprotects.
#[test]
fn passwords_set_in_gridcraft_survive_xlsx_saving() {
let mut s = s();
s.execute("review.protectSheet", json!({"password": "pa55"})).unwrap();
s.execute("review.protectWorkbook", json!({"on": true, "password": "b00k"})).unwrap();
// The workbook password, like the sheet's, also keeps OpenDocument's SHA-256 digest.
let book = s.doc().unwrap().wb.structure_password.clone().unwrap();
assert_eq!(book.odf_key(), gridcraft_model::PasswordHash::new_sha256_digest("b00k").odf_key());
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
let mut t = super::tests::s();
t.execute("file.open", json!({"name": "book.xlsx", "base64": saved["base64"]})).unwrap();
assert!(t.execute("review.unprotectSheet", json!({})).is_err());
assert!(t.execute("review.unprotectSheet", json!({"password": "nope"})).is_err());
t.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap();
assert!(t.execute("review.protectWorkbook", json!({"on": false, "password": "nope"})).is_err());
t.execute("review.protectWorkbook", json!({"on": false, "password": "b00k"})).unwrap();
assert!(!t.doc().unwrap().wb.protected_structure);
}
/// A password held only as a SHA-256 digest (as OpenDocument stores it) unprotects with the
/// password; XLSX has no form for it, so saving keeps the protection without the password.
#[test]
fn sha256_digest_passwords_unprotect_and_save_to_xlsx_without_the_password() {
let mut s = s();
s.execute("review.protectSheet", json!({})).unwrap();
let digest = gridcraft_model::PasswordHash::new_sha256_digest("pa55");
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb).sheet_mut(0).unwrap().protection.as_mut().unwrap().password = Some(digest);
let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
assert!(s.execute("review.unprotectSheet", json!({"password": "nope"})).is_err());
s.execute("review.unprotectSheet", json!({"password": "pa55"})).unwrap();
let mut t = super::tests::s();
t.execute("file.open", json!({"name": "book.xlsx", "base64": saved["base64"]})).unwrap();
let prot = t.doc().unwrap().wb.sheets[0].protection.clone().unwrap();
assert_eq!(prot.password, None);
t.execute("review.unprotectSheet", json!({})).unwrap();
}
/// Renaming a sheet renames a PivotTable's source to it, and the PivotTable still refreshes.
#[test]
fn sheet_rename_renames_a_pivot_source() {
@@ -8171,270 +7657,3 @@ fn history_charges_the_storage_of_empty_comment_replies() {
// 500 replies of no text are still 500 elements.
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.
#[test]
fn opening_and_switching_sheets_select_a_merged_active_cell_whole() {
let mut wb = gridcraft_model::Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
sh.set_value(CellRef::new(0, 0), Value::text("Timesheet"));
sh.merges.push(gridcraft_core::RangeRef::parse("A1:AG1").unwrap());
sh.merges.push(gridcraft_core::RangeRef::parse("C5:E6").unwrap());
sh.view_active = CellRef::parse("C5").unwrap();
let mut second = gridcraft_model::Sheet::new("Sheet2");
second.merges.push(gridcraft_core::RangeRef::parse("A1:C2").unwrap());
wb.sheets.push(std::sync::Arc::new(second));
wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("Sheet3")));
let bytes = gridcraft_xlsx::write_xlsx(&wb).unwrap();
let sel = |s: &Session| {
let sel = &s.doc().unwrap().selection;
(sel.a1(), sel.active.a1())
};
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
let mut s = Session::new();
s.execute("file.open", json!({"name": "timesheet.xlsx", "base64": crate::io::base64_encode(&bytes)})).unwrap();
assert_eq!(sel(&s), pair("C5:E6", "C5"), "on open, a merge away from A1");
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
assert_eq!(sel(&s), pair("A1:C2", "A1"), "first visit of a sheet, a merge at A1");
s.execute("sheet.activate", json!({"sheet": "Sheet3"})).unwrap();
assert_eq!(sel(&s), pair("A1", "A1"), "an unmerged A1 stays a single cell");
// A remembered selection is not expanded again: set one inside Sheet2's merge directly.
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
s.doc_mut().unwrap().selection = crate::Selection::at(CellRef::parse("B2").unwrap());
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
assert_eq!(sel(&s), pair("C5:E6", "C5"), "Sheet1's remembered selection");
s.execute("selection.set", json!({"cell": "B3"})).unwrap();
s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap();
assert_eq!(sel(&s), pair("B2", "B2"), "a remembered selection comes back as it was");
s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap();
assert_eq!(sel(&s), pair("B3", "B3"), "a remembered selection comes back as it was");
}
/// Paste Link would write links to the cells a cut empties, losing them: a cut can't be pasted
/// as links, and nothing changes.
#[test]
fn a_cut_is_not_pasted_as_links() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "link": true, "at": "E1"})).is_err());
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "E1")), (Value::Number(1.0), Value::Number(2.0), Value::Empty));
}
/// A cut pasted into a row the filter hides would skip every cell it writes, so the cells would
/// leave the sheet with the cut: it is refused and nothing changes. A visible row takes it.
#[test]
fn a_cut_is_not_pasted_into_filtered_rows() {
let mut s = s();
let mut rows = vec![json!(["Val", "Tag"])];
for i in 2..=5 {
rows.push(json!([format!("v{i}"), if i == 3 { "hide" } else { "keep" }]));
}
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s.execute("range.setValues", json!({"range": "E1", "values": [[1, 2]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:B1"})).unwrap();
s.execute("data.filter", json!({})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["keep"]})).unwrap();
s.execute("edit.cut", json!({"range": "E1:F1"})).unwrap();
s.execute("selection.set", json!({"range": "A3:B3"})).unwrap();
assert!(s.execute("edit.paste", json!({})).is_err());
assert_eq!((v(&s, "E1"), v(&s, "F1")), (Value::Number(1.0), Value::Number(2.0)));
assert_eq!(v(&s, "A3"), Value::from("v3"));
s.execute("selection.set", json!({"range": "A4:B4"})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
assert_eq!((v(&s, "A4"), v(&s, "B4"), v(&s, "E1")), (Value::Number(1.0), Value::Number(2.0), Value::Empty));
}
/// A taller cut, or one pasted at an explicit cell, goes straight down: refused when a row the
/// filter hides is among the rows it would land on, and nothing changes. A visible place takes it.
#[test]
fn an_anchored_cut_is_not_pasted_over_filtered_rows() {
let mut s = s();
let mut rows = vec![json!(["Val", "Tag"])];
for i in 2..=5 {
rows.push(json!([format!("v{i}"), if i == 3 { "hide" } else { "keep" }]));
}
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
s.execute("range.setValues", json!({"range": "A10", "values": [[1, 2], [3, 4]]})).unwrap();
s.execute("selection.set", json!({"range": "A1:B1"})).unwrap();
s.execute("data.filter", json!({})).unwrap();
s.execute("data.filterBy", json!({"column": "B", "values": ["keep"]})).unwrap();
s.execute("edit.cut", json!({"range": "A10:B11"})).unwrap();
assert!(s.execute("edit.paste", json!({"at": "A2"})).is_err());
assert_eq!((v(&s, "A10"), v(&s, "B11")), (Value::Number(1.0), Value::Number(4.0)));
assert_eq!((v(&s, "A2"), v(&s, "A3")), (Value::from("v2"), Value::from("v3")));
s.execute("edit.paste", json!({"at": "A4"})).unwrap();
assert_eq!((v(&s, "A4"), v(&s, "B5"), v(&s, "A10")), (Value::Number(1.0), Value::Number(4.0), Value::Empty));
}
/// Skip Blanks would empty a cut's blank cells along with their note and format, then skip them:
/// a cut takes no Paste Special option, and nothing changes.
#[test]
fn a_cut_is_not_pasted_skipping_blanks() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1]]})).unwrap();
s.execute("review.newNote", json!({"cell": "B1", "text": "note", "author": "Example"})).unwrap();
s.execute("home.bold", json!({"range": "B1"})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "skipBlanks": true, "at": "E1"})).is_err());
let d = s.doc().unwrap();
let sh = d.wb.active().unwrap();
let b1 = CellRef::parse("B1").unwrap();
assert!(sh.comments.contains_key(&b1));
assert!(d.wb.styles.get(sh.style_id(b1)).font.bold);
assert_eq!((v(&s, "A1"), v(&s, "E1")), (Value::Number(1.0), Value::Empty));
}
/// Transposing a cut would move references to it as if it were not transposed: refused, and a
/// formula reading the cut cells still reads them.
#[test]
fn a_cut_is_not_pasted_transposed() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
s.execute("cell.set", json!({"cell": "H1", "input": "=B1"})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E5"})).is_err());
assert_eq!(formula_at(&s, "H1").as_deref(), Some("B1"));
assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "E5"), v(&s, "E6")), (Value::Number(1.0), Value::Number(2.0), Value::Empty, Value::Empty));
}
/// A cut lands in one place: onto a larger or differently shaped selection it is refused, as in
/// Excel, rather than tiled.
#[test]
fn a_cut_is_not_pasted_over_a_larger_area() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[5]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1"})).unwrap();
s.execute("selection.set", json!({"range": "E1:E3"})).unwrap();
assert!(s.execute("edit.paste", json!({})).is_err());
assert_eq!((v(&s, "A1"), v(&s, "E1"), v(&s, "E2"), v(&s, "E3")), (Value::Number(5.0), Value::Empty, Value::Empty, Value::Empty));
}
/// A paste operation or a partial paste (values only) of a cut would empty the cut cells and
/// combine or keep only part of them: refused, and nothing changes.
#[test]
fn a_cut_is_not_pasted_with_an_operation_or_in_part() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[5]]})).unwrap();
s.execute("range.setValues", json!({"range": "E1", "values": [[2]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "operation": "add", "at": "E1"})).is_err());
assert!(s.execute("edit.pasteSpecial", json!({"what": "values", "at": "E1"})).is_err());
assert_eq!((v(&s, "A1"), v(&s, "E1")), (Value::Number(5.0), Value::Number(2.0)));
}
/// A refused paste leaves the cut pending: a plain Paste onto one cell, or onto an area of the cut's
/// size, still moves it.
#[test]
fn a_refused_cut_paste_leaves_the_cut_to_paste_plainly() {
let mut s = s();
s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2]]})).unwrap();
s.execute("edit.cut", json!({"range": "A1:B1"})).unwrap();
assert!(s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "E5"})).is_err());
s.execute("selection.set", json!({"range": "E1"})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
assert_eq!((v(&s, "A1"), v(&s, "E1"), v(&s, "F1")), (Value::Empty, Value::Number(1.0), Value::Number(2.0)));
assert!(s.clipboard.is_none());
s.execute("edit.cut", json!({"range": "E1:F1"})).unwrap();
s.execute("selection.set", json!({"range": "C3:D3"})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
assert_eq!((v(&s, "E1"), v(&s, "C3"), v(&s, "D3")), (Value::Empty, Value::Number(1.0), Value::Number(2.0)));
}
+1 -1
View File
@@ -531,7 +531,7 @@ fn edit_parts(bytes: &[u8], mut edit: impl FnMut(&str, String) -> String) -> Vec
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
for i in 0..zip.len() {
let mut part = zip.by_index(i).unwrap();
let name = part.name().unwrap().to_string();
let name = part.name().to_string();
let mut data = Vec::new();
part.read_to_end(&mut data).unwrap();
let data = match String::from_utf8(data) {
-12
View File
@@ -546,18 +546,6 @@ fn xl_references_follow_name_and_table_renames() {
assert_eq!(code(&s, 0, "E1").as_deref(), Some("a = xl(\"Choices\")\nb = xl(\"Data[v]\")"));
}
#[test]
fn a_python_cell_is_not_a_trend_source() {
let mut s = s();
s.execute("cell.set", json!({"cell": "A2", "input": "2"})).unwrap();
plant(&mut s, 0, "A1", "1");
let offered = |s: &Session, growth: bool| {
let r = |a: &str| gridcraft_core::RangeRef::parse(a).unwrap();
crate::fill::trend_applies(&s.doc().unwrap().wb, 0, r("A1:A2"), r("A1:A5"), growth)
};
assert!(!offered(&s, false) && !offered(&s, true));
}
#[test]
fn inserting_a_link_without_text_preserves_an_empty_python_cell() {
let mut s = s();
+2 -2
View File
@@ -56,7 +56,7 @@ fn with_parts(bytes: &[u8], edit: impl Fn(&str, &str) -> String, add: &[(&str, &
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 name = f.name().to_string();
let mut data = Vec::new();
f.read_to_end(&mut data).unwrap();
if let Ok(text) = std::str::from_utf8(&data) {
@@ -250,7 +250,7 @@ fn with_damaged_part(bytes: &[u8], name: &str, marker: &str) -> Vec<u8> {
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 entry = f.name().unwrap().to_string();
let entry = f.name().to_string();
let mut data = Vec::new();
f.read_to_end(&mut data).unwrap();
let options = zip::write::SimpleFileOptions::default();
+3 -9
View File
@@ -168,8 +168,7 @@
"vert": "Baseline",
"charset": null,
"family": null,
"minor": true,
"outline": false
"minor": true
},
"fill": {
"pattern": "None",
@@ -220,7 +219,6 @@
"bold": false,
"italic": false,
"strike": false,
"outline": false,
"underline": false,
"size": false,
"name": false,
@@ -240,8 +238,7 @@
"vert": "Baseline",
"charset": null,
"family": null,
"minor": true,
"outline": false
"minor": true
},
"fill": {
"pattern": "None",
@@ -292,7 +289,6 @@
"bold": false,
"italic": false,
"strike": false,
"outline": false,
"underline": false,
"size": false,
"name": false,
@@ -312,8 +308,7 @@
"vert": "Baseline",
"charset": null,
"family": null,
"minor": true,
"outline": false
"minor": true
},
"fill": {
"pattern": "None",
@@ -364,7 +359,6 @@
"bold": false,
"italic": false,
"strike": false,
"outline": false,
"underline": false,
"size": false,
"name": false,
-6
View File
@@ -247,7 +247,6 @@
"bold": false,
"italic": false,
"name": false,
"outline": false,
"protection": false,
"scheme": null,
"size": false,
@@ -267,7 +266,6 @@
"italic": false,
"minor": true,
"name": "Calibri",
"outline": false,
"size": 11.0,
"strike": false,
"underline": "None",
@@ -319,7 +317,6 @@
"bold": false,
"italic": false,
"name": false,
"outline": false,
"protection": false,
"scheme": null,
"size": false,
@@ -339,7 +336,6 @@
"italic": false,
"minor": true,
"name": "Calibri",
"outline": false,
"size": 11.0,
"strike": false,
"underline": "None",
@@ -391,7 +387,6 @@
"bold": false,
"italic": false,
"name": false,
"outline": false,
"protection": false,
"scheme": null,
"size": false,
@@ -411,7 +406,6 @@
"italic": false,
"minor": true,
"name": "Calibri",
"outline": false,
"size": 11.0,
"strike": false,
"underline": "None",
@@ -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]);
}
@@ -60,7 +60,7 @@ fn edit_chart(bytes: &[u8], edit: impl Fn(String) -> String) -> Vec<u8> {
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 name = f.name().to_string();
let mut data = Vec::new();
f.read_to_end(&mut data).unwrap();
if name == "xl/charts/chart1.xml" {
@@ -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()) {
@@ -529,9 +525,9 @@ fn watch_list(wb: &Workbook) -> Option<&str> {
wb.names.iter().find(|n| n.name == WATCH_NAME).map(|n| n.formula.as_str())
}
/// The workbook with view state (active sheet, scroll, active cell, zoom, Normal / Page Layout /
/// Page Break Preview) and the Watch Window list reset: undo restores view state as it was, but
/// switching sheets, zooming or switching views isn't an undoable edit.
/// The workbook with view state (active sheet, scroll, active cell, Normal / Page Layout / Page
/// Break Preview) and the Watch Window list reset: undo restores view state as it was, but
/// switching sheets or views isn't an undoable edit.
fn canonical(wb: &Workbook) -> Workbook {
let mut wb = wb.clone();
wb.set_active_sheet(0);
@@ -540,7 +536,6 @@ fn canonical(wb: &Workbook) -> Workbook {
let sh = Arc::make_mut(sh);
sh.view_active = CellRef::default();
sh.view_top_left = CellRef::default();
sh.zoom = 100;
sh.view = SheetViewMode::Normal;
}
wb
-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));
}
+1 -63
View File
@@ -1,7 +1,7 @@
//! Reference adjustment: copying formulas, inserting/deleting rows and columns, moving cells,
//! renaming and deleting sheets.
use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef};
use gridcraft_core::{CellError, MAX_COLS, MAX_ROWS, RangeRef};
use crate::ast::{Anchor, Expr, RefKind, Reference, SheetSel, clamp_anchor};
@@ -36,68 +36,6 @@ pub fn shift_relative_wrapping(e: Expr, dr: i64, dc: i64) -> Expr {
})
}
/// Paste Special ▸ Transpose: the cell holding the formula moves from `src` to `dest`, so every
/// reference turns a quarter turn with it — its row offset becomes its column offset and the other
/// way round, `(r, c)` → `dest + (c − src.col, r − src.row)`.
///
/// As Excel writes it out: a reference that pins a row or a column with `$` is left exactly as it
/// stands, a whole-row or whole-column reference comes back as a cell range whose open side runs
/// from the transposed far edge of the sheet, and a result that falls off the grid becomes `#REF!`.
pub fn transpose_relative(e: Expr, src: CellRef, dest: CellRef) -> Expr {
e.map(&mut |x| match x {
Expr::Ref(r) if !has_absolute(&r) => match transpose_ref(&r, src, dest) {
Some(r) => Expr::Ref(r),
None => Expr::Error(CellError::Ref),
},
other => other,
})
}
/// Whether any end of the reference pins a row or a column with `$`.
fn has_absolute(r: &Reference) -> bool {
let abs = |a: &Anchor| a.row_abs || a.col_abs;
match &r.kind {
RefKind::Cell(a) => abs(a),
RefKind::Range(a, b) => abs(a) || abs(b),
RefKind::Rows(_, a0, _, a1) | RefKind::Cols(_, a0, _, a1) => *a0 || *a1,
}
}
/// Where an end lands after the turn: its column drives the new row, its row the new column.
fn transpose_anchor(a: &Anchor, src: CellRef, dest: CellRef) -> Option<(u32, u32)> {
clamp_anchor(dest.row as i64 + a.col as i64 - src.col as i64, dest.col as i64 + a.row as i64 - src.row as i64)
}
/// Turns one reference with `src` → `dest`: `None` when an end falls outside the sheet, which
/// the caller turns into `#REF!`.
fn transpose_ref(r: &Reference, src: CellRef, dest: CellRef) -> Option<Reference> {
let kind = match &r.kind {
RefKind::Cell(a) => {
let (row, col) = transpose_anchor(a, src, dest)?;
RefKind::Cell(Anchor { row, col, ..*a })
}
RefKind::Range(a, b) => {
let (row, col) = transpose_anchor(a, src, dest)?;
let (row2, col2) = transpose_anchor(b, src, dest)?;
RefKind::Range(Anchor { row, col, ..*a }, Anchor { row: row2, col: col2, ..*b })
}
// A whole row turns into a cell range: its rows become columns, while its open columns
// become rows pinned with `$` — from the transposed first column down to the last row.
RefKind::Rows(r0, _, r1, _) => {
let (row, col) = clamp_anchor(dest.row as i64 - src.col as i64, dest.col as i64 + *r0 as i64 - src.row as i64)?;
let (row2, col2) = clamp_anchor(MAX_ROWS as i64 - 1, dest.col as i64 + *r1 as i64 - src.row as i64)?;
RefKind::Range(Anchor { row, col, row_abs: true, col_abs: false }, Anchor { row: row2, col: col2, row_abs: true, col_abs: false })
}
// A whole column likewise: its columns become rows, its open rows become columns up to XFD.
RefKind::Cols(c0, _, c1, _) => {
let (row, col) = clamp_anchor(dest.row as i64 + *c0 as i64 - src.col as i64, dest.col as i64 - src.row as i64)?;
let (row2, col2) = clamp_anchor(dest.row as i64 + *c1 as i64 - src.col as i64, MAX_COLS as i64 - 1)?;
RefKind::Range(Anchor { row, col, row_abs: false, col_abs: true }, Anchor { row: row2, col: col2, row_abs: false, col_abs: true })
}
};
Some(Reference { sheet: r.sheet.clone(), kind })
}
/// Whether the formula has a relative (no `$`) row or column anywhere.
pub fn has_relative_refs(e: &Expr) -> bool {
e.references().iter().any(|r| match r.kind {
+1 -23
View File
@@ -1,5 +1,5 @@
use super::*;
use crate::adjust::{Axis, Edit, adjust, rename_sheet, shift_relative, transpose_relative};
use crate::adjust::{Axis, Edit, adjust, rename_sheet, shift_relative};
fn rt(src: &str) -> String {
match parse(src) {
@@ -179,28 +179,6 @@ fn copy_shift() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
#[test]
fn copy_transpose() -> Result<(), Box<dyn std::error::Error>> {
let at = gridcraft_core::CellRef::new;
// The row of each reference drives its new column and the other way round (Excel, observed:
// A1 → F6 carrying =B1+1 comes out as =F7+1).
let e = parse("B1+SUM(B1:C3)+Sheet2!A1")?;
assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "F7+SUM(F7:H8)+Sheet2!F6");
// The turn is around the two positions of the formula's cell, not around A1.
let e = parse("G3+SUM(1:2)")?;
assert_eq!(print(&transpose_relative(e, at(1, 2), at(9, 5))), "G14+SUM(E$8:F$1048576)");
// A reference pinned with `$` is left exactly as it stands.
let e = parse("$B$1+B$1+$B1+SUM($B$1:$C$3)")?;
assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "$B$1+B$1+$B1+SUM($B$1:$C$3)");
// Whole rows and columns come back as a cell range open to the sheet's edge.
let e = parse("SUM(1:2)+SUM(B:D)")?;
assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "SUM(F$6:G$1048576)+SUM($F7:$XFD9)");
// Off the grid is #REF!, like a copy that runs past the edge.
let e = parse("A16384+B1")?;
assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "#REF!+F7");
Ok(())
}
#[test]
fn insert_delete() -> Result<(), Box<dyn std::error::Error>> {
let ins = Edit::Insert { axis: Axis::Rows, at: 2, count: 2 };
+1 -23
View File
@@ -496,16 +496,7 @@ fn yearfrac(a: &[Arg], c: &mut dyn Ctx) -> R<Value> {
let sys = c.date_system();
let s = day_arg(a, 0, sys)?;
let e = day_arg(a, 1, sys)?;
let basis = if has(a, 2) {
let raw = num(a, 2)?;
// Excel rejects any negative basis before truncation: -0.9 would truncate to 0 and slip through.
if raw < 0.0 {
return Err(CellError::Num);
}
to_int(raw)?
} else {
0
};
let basis = if has(a, 2) { to_int(num(a, 2)?)? } else { 0 };
num_val(yearfrac_core(sys, s, e, basis)?)
}
@@ -859,19 +850,6 @@ mod tests {
close(ev("YEARFRAC", vec![n(d(2021.0, 2.0, 28.0)), n(d(2021.0, 2.0, 28.0)), n(0.0)]), 0.0);
}
#[test]
fn yearfrac_rejects_negative_fractional_basis() {
// Excel rejects any negative basis: -0.9 must not truncate to 0.
let (s, e) = (n(d(2024.0, 1.0, 15.0)), n(d(2025.0, 6.0, 30.0)));
is_err(ev("YEARFRAC", vec![s.clone(), e.clone(), n(-0.9)]), CellError::Num);
// A positive fraction still truncates to basis 0.
let whole = match ev("YEARFRAC", vec![s.clone(), e.clone(), n(0.0)]) {
Value::Number(x) => x,
v => panic!("YEARFRAC basis 0 gave {v:?}"),
};
close_tol(ev("YEARFRAC", vec![s, e, n(0.9)]), whole, 1e-12);
}
#[test]
fn date_lifting() {
let v = ev("YEAR", vec![av(row(&[43831.0, 46302.0]))]);
-15
View File
@@ -1237,21 +1237,6 @@ mod tests {
is_err(ev("SORTBY", vec![av(col(&[1.0, 2.0])), av(col(&[1.0, 2.0])), n(0.0)]), CellError::Value);
}
/// SORT and SORTBY order numbers exactly, not at 15 digits (observed in Excel 365).
#[test]
fn sort_orders_numbers_exactly() {
for (t, e) in [(0.3, 0.1 + 0.2), (100.0, 100.0 + 1e-14), (3.3, 1.1 * 3.0)] {
for input in [[e, t], [t, e]] {
let asc = vec![vec![nv(t)], vec![nv(e)]];
let desc = vec![vec![nv(e)], vec![nv(t)]];
assert_eq!(rows_of(&ev("SORT", vec![av(col(&input))])), asc);
assert_eq!(rows_of(&ev("SORT", vec![av(col(&input)), n(1.0), n(-1.0)])), desc);
assert_eq!(rows_of(&ev("SORTBY", vec![av(col(&input)), av(col(&input))])), asc);
assert_eq!(rows_of(&ev("SORTBY", vec![av(col(&input)), av(col(&input)), n(-1.0)])), desc);
}
}
}
#[test]
fn unique_keeps_rows_containing_separator_apart() {
let m = arr(vec![vec![tv("a"), tv("b\u{1}tc")], vec![tv("a\u{1}tb"), tv("c")]]);
+1 -6
View File
@@ -24,12 +24,7 @@ fn serial(sys: DateSystem, y: i32, m: u32, d: u32) -> R<f64> {
}
pub(super) fn basis_arg(a: &[Arg], i: usize) -> R<u32> {
let raw = opt_num(a, i, 0.0)?;
// Excel rejects any negative basis before truncation: -0.9 would truncate to -0.0 and slip through.
if raw < 0.0 {
return Err(CellError::Num);
}
let b = raw.trunc();
let b = opt_num(a, i, 0.0)?.trunc();
if !(0.0..=4.0).contains(&b) {
return Err(CellError::Num);
}
-143
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);
@@ -401,21 +273,6 @@ fn number(v: Value) -> f64 {
}
}
/// A negative fractional basis is #NUM!, not truncation toward zero (#4058).
#[test]
fn negative_fractional_basis_is_rejected() {
let price = |basis: f64| ev("PRICE", vec![d(2024, 1, 15), d(2025, 6, 30), n(0.05), n(0.04), n(100.0), n(2.0), n(basis)]);
is_err(price(-0.9), CellError::Num);
is_err(ev("COUPDAYS", vec![d(2011, 1, 25), d(2011, 11, 15), n(2.0), n(-0.9)]), CellError::Num);
is_err(ev("PRICEMAT", vec![d(2008, 2, 15), d(2008, 4, 13), d(2007, 11, 11), n(0.061), n(0.061), n(-0.9)]), CellError::Num);
is_err(ev("ACCRINTM", vec![d(2008, 4, 1), d(2008, 6, 15), n(0.1), n(1000.0), n(-0.5)]), CellError::Num);
// Controls: a positive fraction still truncates to basis 0, and -1 is still #NUM!.
close_tol(price(0.9), 101.40114791702759, 1e-9);
close_tol(price(0.0), 101.40114791702759, 1e-9);
close(ev("COUPDAYS", vec![d(2011, 1, 25), d(2011, 11, 15), n(2.0), n(0.9)]), 180.0);
is_err(price(-1.0), CellError::Num);
}
#[test]
fn odd_periods() {
// The worked examples on Microsoft's function pages (results as printed there).
+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),
}
-10
View File
@@ -637,16 +637,6 @@ mod tests {
assert_eq!(c, vec![Some([255, 0, 0]), None]);
}
#[test]
fn nested_colours_are_kept_per_glyph() {
// Green a, + and c; black b and the plain +d are left to the equation's own colour.
let l = layout("{\\color{green}a+{\\color{black}b}+c}+d").unwrap();
let g = Some([0, 128, 0]);
let c: Vec<(char, Option<[u8; 3]>)> =
l.items.iter().filter_map(|i| if let Item::Glyph(g) = i { Some((g.ch, g.color)) } else { None }).collect();
assert_eq!(c, vec![('a', g), ('+', g), ('b', None), ('+', g), ('c', g), ('+', None), ('d', None)]);
}
#[test]
fn errors_point_at_the_source() {
let e = layout("a + \\frac{1}{").unwrap_err();
+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 }
+13 -44
View File
@@ -1,18 +1,17 @@
//! Standard base64 (RFC 4648 §4): for serde (image bytes in JSON), and for every crate that
//! reads or writes it in a file (encryption descriptors, password hashes, `data:` URLs).
//! Minimal base64 for serde (image bytes in JSON).
use serde::{Deserialize, Deserializer, Serializer};
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for (i, shift) in [18u32, 12, 6, 0].iter().enumerate() {
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
for i in 0..4 {
if i <= chunk.len() {
out.push(char::from(ALPHABET.get(((n >> shift) & 63) as usize).copied().unwrap_or(b'A')));
out.push(A[((n >> (18 - 6 * i)) & 63) as usize] as char);
} else {
out.push('=');
}
@@ -21,39 +20,21 @@ pub fn encode(data: &[u8]) -> String {
out
}
/// The 6-bit value of a base64 character (inverse of [`ALPHABET`]).
fn value(c: u8) -> Option<u32> {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' => 62,
b'/' => 63,
_ => return None,
};
Some(u32::from(v))
}
/// Decodes base64, whitespace and padding ignored; `None` for any other character.
pub fn decode(s: &str) -> Option<Vec<u8>> {
decode_limited(s, usize::MAX)
}
/// [`decode`], also `None` when the output would pass `limit` bytes (for input from a file).
pub fn decode_limited(s: &str, limit: usize) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity((s.len() / 4 * 3).min(limit).min(1 << 20));
let (mut buf, mut bits) = (0u32, 0u32);
for c in s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=') {
let v = value(c)?;
let mut out = Vec::with_capacity(s.len() / 4 * 3);
let mut buf = 0u32;
let mut bits = 0;
for c in s.bytes() {
if c == b'=' || c.is_ascii_whitespace() {
continue;
}
let v = A.iter().position(|&x| x == c)? as u32;
buf = (buf << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((buf >> bits) as u8);
buf &= (1 << bits) - 1;
if out.len() > limit {
return None;
}
}
}
Some(out)
@@ -108,18 +89,6 @@ pub mod opt {
#[cfg(test)]
mod tests {
#[test]
fn decoding_is_bounded_and_strict() {
assert_eq!(super::decode_limited("AAAA", 3).as_deref(), Some(&[0u8, 0, 0][..]));
assert_eq!(super::decode_limited("AAAAAAAA", 3), None);
assert_eq!(super::decode("AA!A"), None);
assert_eq!(super::decode(" QU Jj\n").as_deref(), Some(&b"ABc"[..]));
// The lookup is the alphabet's inverse, and nothing else decodes.
for c in 0..=u8::MAX {
assert_eq!(super::value(c), super::ALPHABET.iter().position(|a| *a == c).map(|i| i as u32), "{c}");
}
}
#[test]
fn roundtrip() -> Result<(), Box<dyn std::error::Error>> {
for data in [&b""[..], b"a", b"ab", b"abc", b"hello world", &[0, 255, 128, 7]] {
+8 -46
View File
@@ -501,8 +501,6 @@ pub enum ChartKind {
Line,
LineMarkers,
LineStacked,
LineStacked100,
LineStacked100Markers,
Pie,
Doughnut,
Area,
@@ -685,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.
@@ -739,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,
}
}
@@ -868,8 +845,6 @@ impl Chart {
| ChartKind::Line
| ChartKind::LineMarkers
| ChartKind::LineStacked
| ChartKind::LineStacked100
| ChartKind::LineStacked100Markers
| ChartKind::Area
| ChartKind::AreaStacked
| ChartKind::AreaStacked100
@@ -1426,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]
@@ -1444,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;
+4 -8
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],
@@ -202,8 +199,8 @@ impl Default for PrintSettings {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SheetProtection {
/// Hash of the password, never the password itself. XLSX `sheetProtection` writes its Excel
/// form ([`crate::PasswordHash::excel`]); a digest alone has none and is not written there.
/// Hash of the password (Excel-compatible, written to XLSX `sheetProtection`; never the
/// password itself).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<crate::PasswordHash>,
/// The internal hash older GridCraft JSON workbooks stored ([`password_hash`]); still
@@ -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
@@ -4,12 +4,11 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
pub mod b64;
mod b64;
pub mod cell;
mod cellmap;
pub mod features;
pub mod macros;
pub mod paper;
pub mod password;
pub mod preserved;
pub mod python;
@@ -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);
}
}
+5 -207
View File
@@ -1,10 +1,8 @@
//! Excel-compatible password hashes for protection (ECMA-376 Part 1 §18.2.29 and §18.3.1.66
//! attribute sets): the legacy 16-bit hash (`password="CC1A"`) and the iterated, salted hash
//! (`algorithmName`, `hashValue`, `saltValue`, `spinCount`); and the unsalted SHA-256 digest
//! OpenDocument stores (`table:protection-key`). A sheet or workbook password set in GridCraft
//! keeps both an Excel form and the SHA-256 one, so it survives saving in either format (edit
//! ranges keep only the Excel form). Protection is a convenience, not security, but verification
//! really checks the password: an unsupported variant is refused, never accepted.
//! (`algorithmName`, `hashValue`, `saltValue`, `spinCount`). Protection is a convenience, not
//! security, but verification really checks the password: an unsupported variant is refused,
//! never accepted.
use serde::{Deserialize, Serialize};
use sha2::Digest;
@@ -14,82 +12,13 @@ pub const DEFAULT_SPIN_COUNT: u32 = 100_000;
/// Largest spin count accepted when verifying (the documented maximum); a file asking for more
/// would only make verification hang.
pub const MAX_SPIN_COUNT: u32 = 10_000_000;
/// Largest decoded hash or salt accepted from a file (a SHA-512 hash is 64 bytes, Excel's salts
/// 16); anything longer is damaged, and decoding it would only allocate.
const MAX_STORED_BYTES: usize = 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "StoredHash", into = "StoredHash")]
pub enum PasswordHash {
/// The legacy 16-bit hash.
Legacy(u16),
/// An iterated, salted hash as stored in the file: algorithm name, base64 hash and salt.
Iterated { algorithm: String, hash: String, salt: String, spin_count: u32 },
/// The base64 SHA-256 digest of the password's UTF-8 bytes, unsalted: the form OpenDocument
/// stores in `table:protection-key` (ODF 1.3 part 3 §19.701) when
/// `table:protection-key-digest-algorithm` (§19.702) names SHA-256. A writer writes both
/// attributes; a key under any other or no digest algorithm is not this form.
Sha256Digest(String),
/// A password set in GridCraft, kept in the form each file format stores: Excel's hash
/// (which verifies it) and the SHA-256 digest.
Both { excel: Box<PasswordHash>, odf: String },
}
/// How a [`PasswordHash`] is saved in a GridCraft JSON workbook. A password set in GridCraft
/// (`Both` with an iterated Excel form, the usual case) is saved in the `Iterated` shape older
/// GridCraft versions read, with the SHA-256 digest in an extra `odf` field they ignore, so an
/// ordinary Protect Sheet or Protect Workbook doesn't make a workbook unreadable to them. The
/// shapes older versions don't know (`Sha256Digest`, and `Both` over a legacy hash) come only
/// from OpenDocument files, which those versions can't open either.
#[derive(Serialize, Deserialize)]
enum StoredHash {
Legacy(u16),
Iterated {
algorithm: String,
hash: String,
salt: String,
spin_count: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
odf: Option<String>,
},
Sha256Digest(String),
Both {
excel: Box<PasswordHash>,
odf: String,
},
}
impl From<StoredHash> for PasswordHash {
fn from(s: StoredHash) -> PasswordHash {
match s {
StoredHash::Legacy(h) => PasswordHash::Legacy(h),
StoredHash::Iterated { algorithm, hash, salt, spin_count, odf } => {
let iterated = PasswordHash::Iterated { algorithm, hash, salt, spin_count };
match odf {
Some(odf) => PasswordHash::Both { excel: Box::new(iterated), odf },
None => iterated,
}
}
StoredHash::Sha256Digest(k) => PasswordHash::Sha256Digest(k),
StoredHash::Both { excel, odf } => PasswordHash::Both { excel, odf },
}
}
}
impl From<PasswordHash> for StoredHash {
fn from(h: PasswordHash) -> StoredHash {
match h {
PasswordHash::Legacy(h) => StoredHash::Legacy(h),
PasswordHash::Iterated { algorithm, hash, salt, spin_count } => StoredHash::Iterated { algorithm, hash, salt, spin_count, odf: None },
PasswordHash::Sha256Digest(k) => StoredHash::Sha256Digest(k),
PasswordHash::Both { excel, odf } => match *excel {
PasswordHash::Iterated { algorithm, hash, salt, spin_count } => {
StoredHash::Iterated { algorithm, hash, salt, spin_count, odf: Some(odf) }
}
excel => StoredHash::Both { excel: Box::new(excel), odf },
},
}
}
}
impl PasswordHash {
@@ -104,49 +33,11 @@ impl PasswordHash {
}
}
/// A SHA-256 digest of a new password (the form OpenDocument stores).
pub fn new_sha256_digest(password: &str) -> PasswordHash {
PasswordHash::Sha256Digest(sha256_digest(password))
}
/// A new password in every form a file keeps: Excel's (SHA-512, salted) and the SHA-256
/// digest, so it survives saving in either format.
pub fn new_for_files(password: &str, salt: &[u8]) -> PasswordHash {
PasswordHash::Both { excel: Box::new(PasswordHash::new_sha512(password, salt)), odf: sha256_digest(password) }
}
/// The hash as Excel stores it, if it has that form. Not recursive: a `Both` read from a
/// damaged file that nests another `Both` has no Excel form.
pub fn excel(&self) -> Option<&PasswordHash> {
match self {
PasswordHash::Legacy(_) | PasswordHash::Iterated { .. } => Some(self),
PasswordHash::Sha256Digest(_) => None,
PasswordHash::Both { excel, .. } => match excel.as_ref() {
h @ (PasswordHash::Legacy(_) | PasswordHash::Iterated { .. }) => Some(h),
PasswordHash::Sha256Digest(_) | PasswordHash::Both { .. } => None,
},
}
}
/// The SHA-256 digest (base64), if it has that form.
pub fn odf_key(&self) -> Option<&str> {
match self {
PasswordHash::Sha256Digest(k) | PasswordHash::Both { odf: k, .. } => Some(k),
PasswordHash::Legacy(_) | PasswordHash::Iterated { .. } => None,
}
}
/// Whether `password` matches. `Err` when the hash can't be checked (unsupported algorithm,
/// broken base64, spin count over [`MAX_SPIN_COUNT`]).
pub fn verify(&self, password: &str) -> Result<bool, String> {
match self {
PasswordHash::Legacy(h) => Ok(legacy_hash(password) == *h),
// Checked through its Excel form (one level only: see `excel`), else its digest.
PasswordHash::Both { odf, .. } => match self.excel() {
Some(excel) => excel.verify(password),
None => verify_sha256_digest(odf, password),
},
PasswordHash::Sha256Digest(hash) => verify_sha256_digest(hash, password),
PasswordHash::Iterated { algorithm, hash, salt, spin_count } => {
if algorithm.is_empty() {
return Err("the stored password hash is damaged".into());
@@ -154,13 +45,10 @@ impl PasswordHash {
if *spin_count > MAX_SPIN_COUNT {
return Err(format!("the password uses a spin count of {spin_count}, more than the {MAX_SPIN_COUNT} allowed"));
}
let (Some(want), Some(salt)) =
(crate::b64::decode_limited(hash, MAX_STORED_BYTES), crate::b64::decode_limited(salt, MAX_STORED_BYTES))
else {
let (Some(want), Some(salt)) = (crate::b64::decode(hash), crate::b64::decode(salt)) else {
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),
@@ -172,16 +60,6 @@ impl PasswordHash {
}
}
/// The base64 SHA-256 digest of `password`'s UTF-8 bytes.
fn sha256_digest(password: &str) -> String {
crate::b64::encode(&sha2::Sha256::digest(password.as_bytes()))
}
fn verify_sha256_digest(hash: &str, password: &str) -> Result<bool, String> {
let want = crate::b64::decode_limited(hash, 64).ok_or_else(|| "the stored password hash is damaged".to_string())?;
Ok(sha2::Sha256::digest(password.as_bytes()).as_slice() == want.as_slice())
}
/// A 16-byte salt derived from `seed` (callers mix in what varies: names, a counter, the clock).
pub fn salt_from(seed: &[u8]) -> [u8; 16] {
let h = sha2::Sha512::digest(seed);
@@ -237,19 +115,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,79 +124,12 @@ 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")?);
let broken = PasswordHash::Iterated { algorithm: "SHA-512".into(), hash: "!!".into(), salt: salt.clone(), spin_count: 1 };
assert!(broken.verify("s3cret").is_err());
let huge_salt = PasswordHash::Iterated { algorithm: "SHA-512".into(), hash, salt: "A".repeat(4 * MAX_STORED_BYTES), spin_count: 1 };
assert!(huge_salt.verify("s3cret").is_err());
Ok(())
}
#[test]
fn sha256_digests_verify() -> Result<(), Box<dyn std::error::Error>> {
// SHA-256 of "abc", base64.
let h = PasswordHash::Sha256Digest("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=".into());
assert_eq!(h, PasswordHash::new_sha256_digest("abc"));
assert!(h.verify("abc")?);
assert!(!h.verify("abd")?);
assert!(PasswordHash::Sha256Digest("!!".into()).verify("abc").is_err());
assert_eq!(h.excel(), None);
assert_eq!(h.odf_key(), Some("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="));
Ok(())
}
#[test]
fn passwords_set_in_gridcraft_keep_both_forms() -> Result<(), Box<dyn std::error::Error>> {
let h = PasswordHash::new_for_files("pa55", b"0123456789abcdef");
assert_eq!(h.excel(), Some(&PasswordHash::new_sha512("pa55", b"0123456789abcdef")));
assert_eq!(h.odf_key(), PasswordHash::new_sha256_digest("pa55").odf_key());
assert!(h.verify("pa55")?);
assert!(!h.verify("pass")?);
// Each form checks the password on its own.
assert!(h.excel().ok_or("no Excel form")?.verify("pa55")?);
assert!(PasswordHash::Sha256Digest(h.odf_key().ok_or("no digest")?.into()).verify("pa55")?);
// A nested `Both` (only a damaged file makes one) has no Excel form and falls back to its digest.
let nested = PasswordHash::Both { excel: Box::new(h.clone()), odf: PasswordHash::new_sha256_digest("x").odf_key().unwrap_or("").into() };
assert_eq!(nested.excel(), None);
assert!(nested.verify("x")?);
assert!(!nested.verify("pa55")?);
// The JSON form round-trips.
let back: PasswordHash = serde_json::from_str(&serde_json::to_string(&h)?)?;
assert_eq!(back, h);
Ok(())
}
/// An ordinary password set in GridCraft is saved in the shape an older GridCraft reads (its
/// `PasswordHash` had only `Legacy` and `Iterated`), and reads back with both forms.
#[test]
fn a_gridcraft_password_is_saved_so_older_versions_read_it() -> Result<(), Box<dyn std::error::Error>> {
#[derive(Debug, PartialEq, Deserialize)]
enum OlderPasswordHash {
Legacy(u16),
Iterated { algorithm: String, hash: String, salt: String, spin_count: u32 },
}
let both = PasswordHash::new_for_files("pa55", b"0123456789abcdef");
let saved = serde_json::to_string(&both)?;
let older: OlderPasswordHash = serde_json::from_str(&saved)?;
let Some(PasswordHash::Iterated { algorithm, hash, salt, spin_count }) = both.excel().cloned() else {
return Err("no Excel form".into());
};
assert_eq!(older, OlderPasswordHash::Iterated { algorithm, hash, salt, spin_count });
// This version reads both forms back.
let back: PasswordHash = serde_json::from_str(&saved)?;
assert_eq!(back, both);
assert!(back.verify("pa55")?);
// What an older version saved still opens.
let excel_only = PasswordHash::new_sha512("pa55", b"0123456789abcdef");
let back: PasswordHash = serde_json::from_str(&serde_json::to_string(&excel_only)?)?;
assert_eq!(back, excel_only);
assert_eq!(serde_json::from_str::<PasswordHash>("{\"Legacy\":52250}")?, PasswordHash::Legacy(52250));
// A legacy hash with a digest has no older shape and keeps its own.
let legacy_both = PasswordHash::Both { excel: Box::new(PasswordHash::Legacy(52250)), odf: "AA==".into() };
assert_eq!(serde_json::from_str::<PasswordHash>(&serde_json::to_string(&legacy_both)?)?, legacy_both);
Ok(())
}
}
-8
View File
@@ -8,7 +8,6 @@
use std::sync::Arc;
use crate::sheet::Visibility;
use crate::style::Style;
/// A relationship from an owning part (the package root, the workbook or a sheet, or a kept part)
/// to a kept part or to an external target.
@@ -33,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
+1 -64
View File
@@ -197,11 +197,6 @@ pub struct Font {
/// theme's minor font. Fonts derived from it (bold, a colour, a size) keep the link.
#[serde(default = "default_minor")]
pub minor: bool,
/// Outlined (hollow) letters: an XLSX `<outline/>`. Kept and saved; GridCraft does not
/// draw it yet (the letters render solid). Always serialized, like the other flags, so a
/// whole style sent back through `home.formatCells` (the Format Cells dialog) clears it.
#[serde(default)]
pub outline: bool,
}
fn default_minor() -> bool {
@@ -213,7 +208,7 @@ impl Hash for Font {
fn hash<H: Hasher>(&self, h: &mut H) {
self.name.hash(h);
self.size.to_bits().hash(h);
(self.bold, self.italic, self.underline, self.strike, self.color, self.vert, self.charset, self.family, self.minor, self.outline).hash(h);
(self.bold, self.italic, self.underline, self.strike, self.color, self.vert, self.charset, self.family, self.minor).hash(h);
}
}
@@ -231,7 +226,6 @@ impl Default for Font {
charset: None,
family: None,
minor: true,
outline: false,
}
}
}
@@ -376,17 +370,6 @@ pub struct Alignment {
/// Unspecified inherits in differential styles and uses context for ordinary cells.
#[serde(default)]
pub reading_order: Option<ReadingOrder>,
/// Space between the cell's edges and its text, left, right, top, bottom, in hundredths
/// of a point; `None` where the file stated none (the application's own). An OpenDocument
/// cell's padding; Excel has none. Not drawn yet.
#[serde(default, skip_serializing_if = "Alignment::no_padding")]
pub padding: [Option<u16>; 4],
}
impl Alignment {
fn no_padding(p: &[Option<u16>; 4]) -> bool {
p.iter().all(Option::is_none)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -425,9 +408,6 @@ pub struct DxfStated {
pub bold: bool,
pub italic: bool,
pub strike: bool,
/// Outlined letters turned off (`<outline val="0"/>`). Defaulted so JSON saved before it opens.
#[serde(default)]
pub outline: bool,
pub underline: bool,
pub size: bool,
pub name: bool,
@@ -549,49 +529,6 @@ mod tests {
assert!(!t.get(StyleId(999)).font.bold);
}
/// Two fonts differing only in outlined letters are different styles; JSON states the flag
/// even when off, and JSON saved before it existed reads as not outlined.
#[test]
fn outline_makes_a_distinct_style() -> Result<(), Box<dyn std::error::Error>> {
let mut t = StyleTable::default();
let outlined = t.derive(StyleId::DEFAULT, |s| s.font.outline = true);
assert_ne!(outlined, StyleId::DEFAULT);
assert_ne!(Font { outline: true, ..Font::default() }, Font::default());
assert_eq!(t.derive(outlined, |s| s.font.outline = false), StyleId::DEFAULT);
let mut json = serde_json::to_value(Font::default())?;
assert_eq!(json.get("outline"), Some(&serde_json::Value::Bool(false)));
assert!(json.as_object_mut().ok_or("none")?.remove("outline").is_some());
assert_eq!(serde_json::from_value::<Font>(json)?, Font::default());
let on = serde_json::to_value(Font { outline: true, ..Font::default() })?;
assert_eq!(on.get("outline"), Some(&serde_json::Value::Bool(true)));
let mut stated = serde_json::to_value(DxfStated::default())?;
assert!(stated.as_object_mut().ok_or("none")?.remove("outline").is_some());
assert_eq!(serde_json::from_value::<DxfStated>(stated)?, DxfStated::default());
Ok(())
}
#[test]
fn padding_keeps_styles_apart_and_survives_json() -> Result<(), Box<dyn std::error::Error>> {
let mut t = StyleTable::default();
let padded = t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(65535)]);
let other = t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(1)]);
assert_ne!(padded, StyleId::DEFAULT);
assert_ne!(padded, other);
assert_eq!(t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(65535)]), padded);
assert_eq!(t.derive(padded, |s| s.align.padding = [None; 4]), StyleId::DEFAULT);
let style = t.get(padded).clone();
let json = serde_json::to_string(&style)?;
assert!(json.contains("padding"), "{json}");
assert_eq!(serde_json::from_str::<Style>(&json)?, style);
// No padding: nothing written, and JSON written before the field existed still reads.
let plain = serde_json::to_string(&Alignment::default())?;
assert!(!plain.contains("padding"), "{plain}");
assert_eq!(serde_json::from_str::<Alignment>(&plain)?, Alignment::default());
Ok(())
}
#[test]
fn a_theme_saved_before_per_script_fonts_still_opens() -> Result<(), Box<dyn std::error::Error>> {
let mut json = serde_json::to_value(Theme::default())?;
+1 -16
View File
@@ -219,14 +219,9 @@ pub struct Workbook {
pub props: DocProps,
/// Workbook structure protection.
pub protected_structure: bool,
/// Hash of the structure protection's password, never the password. XLSX
/// `workbookProtection` writes its Excel form ([`crate::PasswordHash::excel`]); a digest
/// alone has none and is not written there.
/// Password of the structure protection (XLSX `workbookProtection`), never the password.
#[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 +292,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 +562,6 @@ impl Workbook {
props: DocProps::default(),
protected_structure: false,
structure_password: None,
write_reservation: None,
custom_lists: vec![],
cell_styles: vec![],
phonetics: vec![],
+13 -105
View File
@@ -7,9 +7,7 @@
//! 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).
@@ -512,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).
@@ -539,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.
@@ -564,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);
@@ -941,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;
@@ -954,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.
@@ -982,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);
@@ -1029,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`).
@@ -1072,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,
@@ -1098,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,

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